]> git.lizzy.rs Git - rust.git/blob - src/libstd/io/stdio.rs
std: Implement stdio for `std::io`
[rust.git] / src / libstd / io / stdio.rs
1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use prelude::v1::*;
12 use io::prelude::*;
13
14 use cmp;
15 use fmt;
16 use io::lazy::Lazy;
17 use io::{self, BufReader, LineWriter};
18 use sync::{Arc, Mutex, MutexGuard};
19 use sys::stdio;
20
21 /// A handle to a raw instance of the standard input stream of this process.
22 ///
23 /// This handle is not synchronized or buffered in any fashion. Constructed via
24 /// the `std::io::stdin_raw` function.
25 pub struct StdinRaw(stdio::Stdin);
26
27 /// A handle to a raw instance of the standard output stream of this process.
28 ///
29 /// This handle is not synchronized or buffered in any fashion. Constructed via
30 /// the `std::io::stdout_raw` function.
31 pub struct StdoutRaw(stdio::Stdout);
32
33 /// A handle to a raw instance of the standard output stream of this process.
34 ///
35 /// This handle is not synchronized or buffered in any fashion. Constructed via
36 /// the `std::io::stderr_raw` function.
37 pub struct StderrRaw(stdio::Stderr);
38
39 /// Construct a new raw handle to the standard input of this process.
40 ///
41 /// The returned handle does not interact with any other handles created nor
42 /// handles returned by `std::io::stdin`. Data buffered by the `std::io::stdin`
43 /// handles is **not** available to raw handles returned from this function.
44 ///
45 /// The returned handle has no external synchronization or buffering.
46 pub fn stdin_raw() -> StdinRaw { StdinRaw(stdio::Stdin::new()) }
47
48 /// Construct a new raw handle to the standard input stream of this process.
49 ///
50 /// The returned handle does not interact with any other handles created nor
51 /// handles returned by `std::io::stdout`. Note that data is buffered by the
52 /// `std::io::stdin` handles so writes which happen via this raw handle may
53 /// appear before previous writes.
54 ///
55 /// The returned handle has no external synchronization or buffering layered on
56 /// top.
57 pub fn stdout_raw() -> StdoutRaw { StdoutRaw(stdio::Stdout::new()) }
58
59 /// Construct a new raw handle to the standard input stream of this process.
60 ///
61 /// The returned handle does not interact with any other handles created nor
62 /// handles returned by `std::io::stdout`.
63 ///
64 /// The returned handle has no external synchronization or buffering layered on
65 /// top.
66 pub fn stderr_raw() -> StderrRaw { StderrRaw(stdio::Stderr::new()) }
67
68 impl Read for StdinRaw {
69     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) }
70 }
71 impl Write for StdoutRaw {
72     fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) }
73     fn flush(&mut self) -> io::Result<()> { Ok(()) }
74 }
75 impl Write for StderrRaw {
76     fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) }
77     fn flush(&mut self) -> io::Result<()> { Ok(()) }
78 }
79
80 /// A handle to the standard input stream of a process.
81 ///
82 /// Each handle is a shared reference to a global buffer of input data to this
83 /// process. A handle can be `lock`'d to gain full access to `BufRead` methods
84 /// (e.g. `.lines()`). Writes to this handle are otherwise locked with respect
85 /// to other writes.
86 ///
87 /// This handle implements the `Read` trait, but beware that concurrent reads
88 /// of `Stdin` must be executed with care.
89 pub struct Stdin {
90     inner: Arc<Mutex<BufReader<StdinRaw>>>,
91 }
92
93 /// A locked reference to the a `Stdin` handle.
94 ///
95 /// This handle implements both the `Read` and `BufRead` traits and is
96 /// constructed via the `lock` method on `Stdin`.
97 pub struct StdinLock<'a> {
98     inner: MutexGuard<'a, BufReader<StdinRaw>>,
99 }
100
101 /// Create a new handle to the global standard input stream of this process.
102 ///
103 /// The handle returned refers to a globally shared buffer between all threads.
104 /// Access is synchronized and can be explicitly controlled with the `lock()`
105 /// method.
106 ///
107 /// The `Read` trait is implemented for the returned value but the `BufRead`
108 /// trait is not due to the global nature of the standard input stream. The
109 /// locked version, `StdinLock`, implements both `Read` and `BufRead`, however.
110 ///
111 /// To avoid locking and buffering altogether, it is recommended to use the
112 /// `stdin_raw` constructor.
113 pub fn stdin() -> Stdin {
114     static INSTANCE: Lazy<Mutex<BufReader<StdinRaw>>> = lazy_init!(stdin_init);
115     return Stdin {
116         inner: INSTANCE.get().expect("cannot access stdin during shutdown"),
117     };
118
119     fn stdin_init() -> Arc<Mutex<BufReader<StdinRaw>>> {
120         // The default buffer capacity is 64k, but apparently windows
121         // doesn't like 64k reads on stdin. See #13304 for details, but the
122         // idea is that on windows we use a slightly smaller buffer that's
123         // been seen to be acceptable.
124         Arc::new(Mutex::new(if cfg!(windows) {
125             BufReader::with_capacity(8 * 1024, stdin_raw())
126         } else {
127             BufReader::new(stdin_raw())
128         }))
129     }
130 }
131
132 impl Stdin {
133     /// Lock this handle to the standard input stream, returning a readable
134     /// guard.
135     ///
136     /// The lock is released when the returned lock goes out of scope. The
137     /// returned guard also implements the `Read` and `BufRead` traits for
138     /// accessing the underlying data.
139     pub fn lock(&self) -> StdinLock {
140         StdinLock { inner: self.inner.lock().unwrap() }
141     }
142 }
143
144 impl Read for Stdin {
145     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
146         self.lock().read(buf)
147     }
148
149     fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<()> {
150         self.lock().read_to_end(buf)
151     }
152
153     fn read_to_string(&mut self, buf: &mut String) -> io::Result<()> {
154         self.lock().read_to_string(buf)
155     }
156 }
157
158 impl<'a> Read for StdinLock<'a> {
159     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
160         // Flush stdout so that weird issues like a print!'d prompt not being
161         // shown until after the user hits enter.
162         drop(stdout().flush());
163         self.inner.read(buf)
164     }
165 }
166 impl<'a> BufRead for StdinLock<'a> {
167     fn fill_buf(&mut self) -> io::Result<&[u8]> { self.inner.fill_buf() }
168     fn consume(&mut self, n: usize) { self.inner.consume(n) }
169 }
170
171 // As with stdin on windows, stdout often can't handle writes of large
172 // sizes. For an example, see #14940. For this reason, don't try to
173 // write the entire output buffer on windows. On unix we can just
174 // write the whole buffer all at once.
175 //
176 // For some other references, it appears that this problem has been
177 // encountered by others [1] [2]. We choose the number 8KB just because
178 // libuv does the same.
179 //
180 // [1]: https://tahoe-lafs.org/trac/tahoe-lafs/ticket/1232
181 // [2]: http://www.mail-archive.com/log4net-dev@logging.apache.org/msg00661.html
182 #[cfg(windows)]
183 const OUT_MAX: usize = 8192;
184 #[cfg(unix)]
185 const OUT_MAX: usize = ::usize::MAX;
186
187 /// A handle to the global standard output stream of the current process.
188 ///
189 /// Each handle shares a global buffer of data to be written to the standard
190 /// output stream. Access is also synchronized via a lock and explicit control
191 /// over locking is available via the `lock` method.
192 pub struct Stdout {
193     // FIXME: this should be LineWriter or BufWriter depending on the state of
194     //        stdout (tty or not). Note that if this is not line buffered it
195     //        should also flush-on-panic or some form of flush-on-abort.
196     inner: Arc<Mutex<LineWriter<StdoutRaw>>>,
197 }
198
199 /// A locked reference to the a `Stdout` handle.
200 ///
201 /// This handle implements the `Write` trait and is constructed via the `lock`
202 /// method on `Stdout`.
203 pub struct StdoutLock<'a> {
204     inner: MutexGuard<'a, LineWriter<StdoutRaw>>,
205 }
206
207 /// Constructs a new reference to the standard output of the current process.
208 ///
209 /// Each handle returned is a reference to a shared global buffer whose access
210 /// is synchronized via a mutex. Explicit control over synchronization is
211 /// provided via the `lock` method.
212 ///
213 /// The returned handle implements the `Write` trait.
214 ///
215 /// To avoid locking and buffering altogether, it is recommended to use the
216 /// `stdout_raw` constructor.
217 pub fn stdout() -> Stdout {
218     static INSTANCE: Lazy<Mutex<LineWriter<StdoutRaw>>> = lazy_init!(stdout_init);
219     return Stdout {
220         inner: INSTANCE.get().expect("cannot access stdout during shutdown"),
221     };
222
223     fn stdout_init() -> Arc<Mutex<LineWriter<StdoutRaw>>> {
224         Arc::new(Mutex::new(LineWriter::new(stdout_raw())))
225     }
226 }
227
228 impl Stdout {
229     /// Lock this handle to the standard output stream, returning a writable
230     /// guard.
231     ///
232     /// The lock is released when the returned lock goes out of scope. The
233     /// returned guard also implements the `Write` trait for writing data.
234     pub fn lock(&self) -> StdoutLock {
235         StdoutLock { inner: self.inner.lock().unwrap() }
236     }
237 }
238
239 impl Write for Stdout {
240     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
241         self.lock().write(buf)
242     }
243     fn flush(&mut self) -> io::Result<()> {
244         self.lock().flush()
245     }
246     fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
247         self.lock().write_all(buf)
248     }
249     fn write_fmt(&mut self, fmt: fmt::Arguments) -> io::Result<()> {
250         self.lock().write_fmt(fmt)
251     }
252 }
253 impl<'a> Write for StdoutLock<'a> {
254     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
255         self.inner.write(&buf[..cmp::min(buf.len(), OUT_MAX)])
256     }
257     fn flush(&mut self) -> io::Result<()> { self.inner.flush() }
258 }
259
260 /// A handle to the standard error stream of a process.
261 ///
262 /// For more information, see `stderr`
263 pub struct Stderr {
264     inner: Arc<Mutex<StderrRaw>>,
265 }
266
267 /// A locked reference to the a `Stderr` handle.
268 ///
269 /// This handle implements the `Write` trait and is constructed via the `lock`
270 /// method on `Stderr`.
271 pub struct StderrLock<'a> {
272     inner: MutexGuard<'a, StderrRaw>,
273 }
274
275 /// Constructs a new reference to the standard error stream of a process.
276 ///
277 /// Each returned handle is synchronized amongst all other handles created from
278 /// this function. No handles are buffered, however.
279 ///
280 /// The returned handle implements the `Write` trait.
281 ///
282 /// To avoid locking altogether, it is recommended to use the `stderr_raw`
283 /// constructor.
284 pub fn stderr() -> Stderr {
285     static INSTANCE: Lazy<Mutex<StderrRaw>> = lazy_init!(stderr_init);
286     return Stderr {
287         inner: INSTANCE.get().expect("cannot access stderr during shutdown"),
288     };
289
290     fn stderr_init() -> Arc<Mutex<StderrRaw>> {
291         Arc::new(Mutex::new(stderr_raw()))
292     }
293 }
294
295 impl Stderr {
296     /// Lock this handle to the standard error stream, returning a writable
297     /// guard.
298     ///
299     /// The lock is released when the returned lock goes out of scope. The
300     /// returned guard also implements the `Write` trait for writing data.
301     pub fn lock(&self) -> StderrLock {
302         StderrLock { inner: self.inner.lock().unwrap() }
303     }
304 }
305
306 impl Write for Stderr {
307     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
308         self.lock().write(buf)
309     }
310     fn flush(&mut self) -> io::Result<()> {
311         self.lock().flush()
312     }
313     fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
314         self.lock().write_all(buf)
315     }
316     fn write_fmt(&mut self, fmt: fmt::Arguments) -> io::Result<()> {
317         self.lock().write_fmt(fmt)
318     }
319 }
320 impl<'a> Write for StderrLock<'a> {
321     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
322         self.inner.write(&buf[..cmp::min(buf.len(), OUT_MAX)])
323     }
324     fn flush(&mut self) -> io::Result<()> { self.inner.flush() }
325 }