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.
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.
17 use io::{self, BufReader, LineWriter};
18 use sync::{Arc, Mutex, MutexGuard};
21 /// A handle to a raw instance of the standard input stream of this process.
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);
27 /// A handle to a raw instance of the standard output stream of this process.
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);
33 /// A handle to a raw instance of the standard output stream of this process.
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);
39 /// Construct a new raw handle to the standard input of this process.
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.
45 /// The returned handle has no external synchronization or buffering.
46 pub fn stdin_raw() -> StdinRaw { StdinRaw(stdio::Stdin::new()) }
48 /// Construct a new raw handle to the standard input stream of this process.
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.
55 /// The returned handle has no external synchronization or buffering layered on
57 pub fn stdout_raw() -> StdoutRaw { StdoutRaw(stdio::Stdout::new()) }
59 /// Construct a new raw handle to the standard input stream of this process.
61 /// The returned handle does not interact with any other handles created nor
62 /// handles returned by `std::io::stdout`.
64 /// The returned handle has no external synchronization or buffering layered on
66 pub fn stderr_raw() -> StderrRaw { StderrRaw(stdio::Stderr::new()) }
68 impl Read for StdinRaw {
69 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) }
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(()) }
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(()) }
80 /// A handle to the standard input stream of a process.
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
87 /// This handle implements the `Read` trait, but beware that concurrent reads
88 /// of `Stdin` must be executed with care.
90 inner: Arc<Mutex<BufReader<StdinRaw>>>,
93 /// A locked reference to the a `Stdin` handle.
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>>,
101 /// Create a new handle to the global standard input stream of this process.
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()`
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.
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);
116 inner: INSTANCE.get().expect("cannot access stdin during shutdown"),
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())
127 BufReader::new(stdin_raw())
133 /// Lock this handle to the standard input stream, returning a readable
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() }
144 impl Read for Stdin {
145 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
146 self.lock().read(buf)
149 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<()> {
150 self.lock().read_to_end(buf)
153 fn read_to_string(&mut self, buf: &mut String) -> io::Result<()> {
154 self.lock().read_to_string(buf)
158 impl<'a> Read for StdinLock<'a> {
159 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
163 impl<'a> BufRead for StdinLock<'a> {
164 fn fill_buf(&mut self) -> io::Result<&[u8]> { self.inner.fill_buf() }
165 fn consume(&mut self, n: usize) { self.inner.consume(n) }
168 // As with stdin on windows, stdout often can't handle writes of large
169 // sizes. For an example, see #14940. For this reason, don't try to
170 // write the entire output buffer on windows. On unix we can just
171 // write the whole buffer all at once.
173 // For some other references, it appears that this problem has been
174 // encountered by others [1] [2]. We choose the number 8KB just because
175 // libuv does the same.
177 // [1]: https://tahoe-lafs.org/trac/tahoe-lafs/ticket/1232
178 // [2]: http://www.mail-archive.com/log4net-dev@logging.apache.org/msg00661.html
180 const OUT_MAX: usize = 8192;
182 const OUT_MAX: usize = ::usize::MAX;
184 /// A handle to the global standard output stream of the current process.
186 /// Each handle shares a global buffer of data to be written to the standard
187 /// output stream. Access is also synchronized via a lock and explicit control
188 /// over locking is available via the `lock` method.
190 // FIXME: this should be LineWriter or BufWriter depending on the state of
191 // stdout (tty or not). Note that if this is not line buffered it
192 // should also flush-on-panic or some form of flush-on-abort.
193 inner: Arc<Mutex<LineWriter<StdoutRaw>>>,
196 /// A locked reference to the a `Stdout` handle.
198 /// This handle implements the `Write` trait and is constructed via the `lock`
199 /// method on `Stdout`.
200 pub struct StdoutLock<'a> {
201 inner: MutexGuard<'a, LineWriter<StdoutRaw>>,
204 /// Constructs a new reference to the standard output of the current process.
206 /// Each handle returned is a reference to a shared global buffer whose access
207 /// is synchronized via a mutex. Explicit control over synchronization is
208 /// provided via the `lock` method.
210 /// The returned handle implements the `Write` trait.
212 /// To avoid locking and buffering altogether, it is recommended to use the
213 /// `stdout_raw` constructor.
214 pub fn stdout() -> Stdout {
215 static INSTANCE: Lazy<Mutex<LineWriter<StdoutRaw>>> = lazy_init!(stdout_init);
217 inner: INSTANCE.get().expect("cannot access stdout during shutdown"),
220 fn stdout_init() -> Arc<Mutex<LineWriter<StdoutRaw>>> {
221 Arc::new(Mutex::new(LineWriter::new(stdout_raw())))
226 /// Lock this handle to the standard output stream, returning a writable
229 /// The lock is released when the returned lock goes out of scope. The
230 /// returned guard also implements the `Write` trait for writing data.
231 pub fn lock(&self) -> StdoutLock {
232 StdoutLock { inner: self.inner.lock().unwrap() }
236 impl Write for Stdout {
237 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
238 self.lock().write(buf)
240 fn flush(&mut self) -> io::Result<()> {
243 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
244 self.lock().write_all(buf)
246 fn write_fmt(&mut self, fmt: fmt::Arguments) -> io::Result<()> {
247 self.lock().write_fmt(fmt)
250 impl<'a> Write for StdoutLock<'a> {
251 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
252 self.inner.write(&buf[..cmp::min(buf.len(), OUT_MAX)])
254 fn flush(&mut self) -> io::Result<()> { self.inner.flush() }
257 /// A handle to the standard error stream of a process.
259 /// For more information, see `stderr`
261 inner: Arc<Mutex<StderrRaw>>,
264 /// A locked reference to the a `Stderr` handle.
266 /// This handle implements the `Write` trait and is constructed via the `lock`
267 /// method on `Stderr`.
268 pub struct StderrLock<'a> {
269 inner: MutexGuard<'a, StderrRaw>,
272 /// Constructs a new reference to the standard error stream of a process.
274 /// Each returned handle is synchronized amongst all other handles created from
275 /// this function. No handles are buffered, however.
277 /// The returned handle implements the `Write` trait.
279 /// To avoid locking altogether, it is recommended to use the `stderr_raw`
281 pub fn stderr() -> Stderr {
282 static INSTANCE: Lazy<Mutex<StderrRaw>> = lazy_init!(stderr_init);
284 inner: INSTANCE.get().expect("cannot access stderr during shutdown"),
287 fn stderr_init() -> Arc<Mutex<StderrRaw>> {
288 Arc::new(Mutex::new(stderr_raw()))
293 /// Lock this handle to the standard error stream, returning a writable
296 /// The lock is released when the returned lock goes out of scope. The
297 /// returned guard also implements the `Write` trait for writing data.
298 pub fn lock(&self) -> StderrLock {
299 StderrLock { inner: self.inner.lock().unwrap() }
303 impl Write for Stderr {
304 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
305 self.lock().write(buf)
307 fn flush(&mut self) -> io::Result<()> {
310 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
311 self.lock().write_all(buf)
313 fn write_fmt(&mut self, fmt: fmt::Arguments) -> io::Result<()> {
314 self.lock().write_fmt(fmt)
317 impl<'a> Write for StderrLock<'a> {
318 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
319 self.inner.write(&buf[..cmp::min(buf.len(), OUT_MAX)])
321 fn flush(&mut self) -> io::Result<()> { self.inner.flush() }