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.
89 #[stable(feature = "rust1", since = "1.0.0")]
91 inner: Arc<Mutex<BufReader<StdinRaw>>>,
94 /// A locked reference to the a `Stdin` handle.
96 /// This handle implements both the `Read` and `BufRead` traits and is
97 /// constructed via the `lock` method on `Stdin`.
98 #[stable(feature = "rust1", since = "1.0.0")]
99 pub struct StdinLock<'a> {
100 inner: MutexGuard<'a, BufReader<StdinRaw>>,
103 /// Create a new handle to the global standard input stream of this process.
105 /// The handle returned refers to a globally shared buffer between all threads.
106 /// Access is synchronized and can be explicitly controlled with the `lock()`
109 /// The `Read` trait is implemented for the returned value but the `BufRead`
110 /// trait is not due to the global nature of the standard input stream. The
111 /// locked version, `StdinLock`, implements both `Read` and `BufRead`, however.
113 /// To avoid locking and buffering altogether, it is recommended to use the
114 /// `stdin_raw` constructor.
115 #[stable(feature = "rust1", since = "1.0.0")]
116 pub fn stdin() -> Stdin {
117 static INSTANCE: Lazy<Mutex<BufReader<StdinRaw>>> = lazy_init!(stdin_init);
119 inner: INSTANCE.get().expect("cannot access stdin during shutdown"),
122 fn stdin_init() -> Arc<Mutex<BufReader<StdinRaw>>> {
123 // The default buffer capacity is 64k, but apparently windows
124 // doesn't like 64k reads on stdin. See #13304 for details, but the
125 // idea is that on windows we use a slightly smaller buffer that's
126 // been seen to be acceptable.
127 Arc::new(Mutex::new(if cfg!(windows) {
128 BufReader::with_capacity(8 * 1024, stdin_raw())
130 BufReader::new(stdin_raw())
136 /// Lock this handle to the standard input stream, returning a readable
139 /// The lock is released when the returned lock goes out of scope. The
140 /// returned guard also implements the `Read` and `BufRead` traits for
141 /// accessing the underlying data.
142 #[stable(feature = "rust1", since = "1.0.0")]
143 pub fn lock(&self) -> StdinLock {
144 StdinLock { inner: self.inner.lock().unwrap() }
147 /// Locks this handle and reads a line of input into the specified buffer.
149 /// For detailed semantics of this method, see the documentation on
150 /// `BufRead::read_line`.
151 #[stable(feature = "rust1", since = "1.0.0")]
152 pub fn read_line(&mut self, buf: &mut String) -> io::Result<usize> {
153 self.lock().read_line(buf)
157 #[stable(feature = "rust1", since = "1.0.0")]
158 impl Read for Stdin {
159 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
160 self.lock().read(buf)
162 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
163 self.lock().read_to_end(buf)
165 fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
166 self.lock().read_to_string(buf)
170 #[stable(feature = "rust1", since = "1.0.0")]
171 impl<'a> Read for StdinLock<'a> {
172 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
176 #[stable(feature = "rust1", since = "1.0.0")]
177 impl<'a> BufRead for StdinLock<'a> {
178 fn fill_buf(&mut self) -> io::Result<&[u8]> { self.inner.fill_buf() }
179 fn consume(&mut self, n: usize) { self.inner.consume(n) }
182 // As with stdin on windows, stdout often can't handle writes of large
183 // sizes. For an example, see #14940. For this reason, don't try to
184 // write the entire output buffer on windows. On unix we can just
185 // write the whole buffer all at once.
187 // For some other references, it appears that this problem has been
188 // encountered by others [1] [2]. We choose the number 8KB just because
189 // libuv does the same.
191 // [1]: https://tahoe-lafs.org/trac/tahoe-lafs/ticket/1232
192 // [2]: http://www.mail-archive.com/log4net-dev@logging.apache.org/msg00661.html
194 const OUT_MAX: usize = 8192;
196 const OUT_MAX: usize = ::usize::MAX;
198 /// A handle to the global standard output stream of the current process.
200 /// Each handle shares a global buffer of data to be written to the standard
201 /// output stream. Access is also synchronized via a lock and explicit control
202 /// over locking is available via the `lock` method.
203 #[stable(feature = "rust1", since = "1.0.0")]
205 // FIXME: this should be LineWriter or BufWriter depending on the state of
206 // stdout (tty or not). Note that if this is not line buffered it
207 // should also flush-on-panic or some form of flush-on-abort.
208 inner: Arc<Mutex<LineWriter<StdoutRaw>>>,
211 /// A locked reference to the a `Stdout` handle.
213 /// This handle implements the `Write` trait and is constructed via the `lock`
214 /// method on `Stdout`.
215 #[stable(feature = "rust1", since = "1.0.0")]
216 pub struct StdoutLock<'a> {
217 inner: MutexGuard<'a, LineWriter<StdoutRaw>>,
220 /// Constructs a new reference to the standard output of the current process.
222 /// Each handle returned is a reference to a shared global buffer whose access
223 /// is synchronized via a mutex. Explicit control over synchronization is
224 /// provided via the `lock` method.
226 /// The returned handle implements the `Write` trait.
228 /// To avoid locking and buffering altogether, it is recommended to use the
229 /// `stdout_raw` constructor.
230 #[stable(feature = "rust1", since = "1.0.0")]
231 pub fn stdout() -> Stdout {
232 static INSTANCE: Lazy<Mutex<LineWriter<StdoutRaw>>> = lazy_init!(stdout_init);
234 inner: INSTANCE.get().expect("cannot access stdout during shutdown"),
237 fn stdout_init() -> Arc<Mutex<LineWriter<StdoutRaw>>> {
238 Arc::new(Mutex::new(LineWriter::new(stdout_raw())))
243 /// Lock this handle to the standard output stream, returning a writable
246 /// The lock is released when the returned lock goes out of scope. The
247 /// returned guard also implements the `Write` trait for writing data.
248 #[stable(feature = "rust1", since = "1.0.0")]
249 pub fn lock(&self) -> StdoutLock {
250 StdoutLock { inner: self.inner.lock().unwrap() }
254 #[stable(feature = "rust1", since = "1.0.0")]
255 impl Write for Stdout {
256 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
257 self.lock().write(buf)
259 fn flush(&mut self) -> io::Result<()> {
262 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
263 self.lock().write_all(buf)
265 fn write_fmt(&mut self, fmt: fmt::Arguments) -> io::Result<()> {
266 self.lock().write_fmt(fmt)
269 #[stable(feature = "rust1", since = "1.0.0")]
270 impl<'a> Write for StdoutLock<'a> {
271 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
272 self.inner.write(&buf[..cmp::min(buf.len(), OUT_MAX)])
274 fn flush(&mut self) -> io::Result<()> { self.inner.flush() }
277 /// A handle to the standard error stream of a process.
279 /// For more information, see `stderr`
280 #[stable(feature = "rust1", since = "1.0.0")]
282 inner: Arc<Mutex<StderrRaw>>,
285 /// A locked reference to the a `Stderr` handle.
287 /// This handle implements the `Write` trait and is constructed via the `lock`
288 /// method on `Stderr`.
289 #[stable(feature = "rust1", since = "1.0.0")]
290 pub struct StderrLock<'a> {
291 inner: MutexGuard<'a, StderrRaw>,
294 /// Constructs a new reference to the standard error stream of a process.
296 /// Each returned handle is synchronized amongst all other handles created from
297 /// this function. No handles are buffered, however.
299 /// The returned handle implements the `Write` trait.
301 /// To avoid locking altogether, it is recommended to use the `stderr_raw`
303 #[stable(feature = "rust1", since = "1.0.0")]
304 pub fn stderr() -> Stderr {
305 static INSTANCE: Lazy<Mutex<StderrRaw>> = lazy_init!(stderr_init);
307 inner: INSTANCE.get().expect("cannot access stderr during shutdown"),
310 fn stderr_init() -> Arc<Mutex<StderrRaw>> {
311 Arc::new(Mutex::new(stderr_raw()))
316 /// Lock this handle to the standard error stream, returning a writable
319 /// The lock is released when the returned lock goes out of scope. The
320 /// returned guard also implements the `Write` trait for writing data.
321 #[stable(feature = "rust1", since = "1.0.0")]
322 pub fn lock(&self) -> StderrLock {
323 StderrLock { inner: self.inner.lock().unwrap() }
327 #[stable(feature = "rust1", since = "1.0.0")]
328 impl Write for Stderr {
329 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
330 self.lock().write(buf)
332 fn flush(&mut self) -> io::Result<()> {
335 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
336 self.lock().write_all(buf)
338 fn write_fmt(&mut self, fmt: fmt::Arguments) -> io::Result<()> {
339 self.lock().write_fmt(fmt)
342 #[stable(feature = "rust1", since = "1.0.0")]
343 impl<'a> Write for StderrLock<'a> {
344 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
345 self.inner.write(&buf[..cmp::min(buf.len(), OUT_MAX)])
347 fn flush(&mut self) -> io::Result<()> { self.inner.flush() }
350 /// Resets the task-local stdout handle to the specified writer
352 /// This will replace the current task's stdout handle, returning the old
353 /// handle. All future calls to `print` and friends will emit their output to
354 /// this specified handle.
356 /// Note that this does not need to be called for all new tasks; the default
357 /// output handle is to the process's stdout stream.
358 #[unstable(feature = "set_panic",
359 reason = "this function may disappear completely or be replaced \
360 with a more general mechanism")]
362 pub fn set_panic(sink: Box<Write + Send>) -> Option<Box<Write + Send>> {
363 use panicking::LOCAL_STDERR;
365 LOCAL_STDERR.with(move |slot| {
366 mem::replace(&mut *slot.borrow_mut(), Some(sink))
367 }).and_then(|mut s| {