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.
18 use io::{self, BufReader, LineWriter};
19 use sync::{Arc, Mutex, MutexGuard};
22 /// Stdout used by print! and println! macroses
24 static LOCAL_STDOUT: RefCell<Option<Box<Write + Send>>> = {
29 /// A handle to a raw instance of the standard input stream of this process.
31 /// This handle is not synchronized or buffered in any fashion. Constructed via
32 /// the `std::io::stdio::stdin_raw` function.
33 struct StdinRaw(stdio::Stdin);
35 /// A handle to a raw instance of the standard output stream of this process.
37 /// This handle is not synchronized or buffered in any fashion. Constructed via
38 /// the `std::io::stdio::stdout_raw` function.
39 struct StdoutRaw(stdio::Stdout);
41 /// A handle to a raw instance of the standard output stream of this process.
43 /// This handle is not synchronized or buffered in any fashion. Constructed via
44 /// the `std::io::stdio::stderr_raw` function.
45 struct StderrRaw(stdio::Stderr);
47 /// Construct a new raw handle to the standard input of this process.
49 /// The returned handle does not interact with any other handles created nor
50 /// handles returned by `std::io::stdin`. Data buffered by the `std::io::stdin`
51 /// handles is **not** available to raw handles returned from this function.
53 /// The returned handle has no external synchronization or buffering.
54 fn stdin_raw() -> StdinRaw { StdinRaw(stdio::Stdin::new()) }
56 /// Construct a new raw handle to the standard input stream of this process.
58 /// The returned handle does not interact with any other handles created nor
59 /// handles returned by `std::io::stdout`. Note that data is buffered by the
60 /// `std::io::stdin` handles so writes which happen via this raw handle may
61 /// appear before previous writes.
63 /// The returned handle has no external synchronization or buffering layered on
65 fn stdout_raw() -> StdoutRaw { StdoutRaw(stdio::Stdout::new()) }
67 /// Construct a new raw handle to the standard input stream of this process.
69 /// The returned handle does not interact with any other handles created nor
70 /// handles returned by `std::io::stdout`.
72 /// The returned handle has no external synchronization or buffering layered on
74 fn stderr_raw() -> StderrRaw { StderrRaw(stdio::Stderr::new()) }
76 impl Read for StdinRaw {
77 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) }
79 impl Write for StdoutRaw {
80 fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) }
81 fn flush(&mut self) -> io::Result<()> { Ok(()) }
83 impl Write for StderrRaw {
84 fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) }
85 fn flush(&mut self) -> io::Result<()> { Ok(()) }
88 /// A handle to the standard input stream of a process.
90 /// Each handle is a shared reference to a global buffer of input data to this
91 /// process. A handle can be `lock`'d to gain full access to `BufRead` methods
92 /// (e.g. `.lines()`). Writes to this handle are otherwise locked with respect
95 /// This handle implements the `Read` trait, but beware that concurrent reads
96 /// of `Stdin` must be executed with care.
97 #[stable(feature = "rust1", since = "1.0.0")]
99 inner: Arc<Mutex<BufReader<StdinRaw>>>,
102 /// A locked reference to the a `Stdin` handle.
104 /// This handle implements both the `Read` and `BufRead` traits and is
105 /// constructed via the `lock` method on `Stdin`.
106 #[stable(feature = "rust1", since = "1.0.0")]
107 pub struct StdinLock<'a> {
108 inner: MutexGuard<'a, BufReader<StdinRaw>>,
111 /// Create a new handle to the global standard input stream of this process.
113 /// The handle returned refers to a globally shared buffer between all threads.
114 /// Access is synchronized and can be explicitly controlled with the `lock()`
117 /// The `Read` trait is implemented for the returned value but the `BufRead`
118 /// trait is not due to the global nature of the standard input stream. The
119 /// locked version, `StdinLock`, implements both `Read` and `BufRead`, however.
120 #[stable(feature = "rust1", since = "1.0.0")]
121 pub fn stdin() -> Stdin {
122 static INSTANCE: Lazy<Mutex<BufReader<StdinRaw>>> = lazy_init!(stdin_init);
124 inner: INSTANCE.get().expect("cannot access stdin during shutdown"),
127 fn stdin_init() -> Arc<Mutex<BufReader<StdinRaw>>> {
128 // The default buffer capacity is 64k, but apparently windows
129 // doesn't like 64k reads on stdin. See #13304 for details, but the
130 // idea is that on windows we use a slightly smaller buffer that's
131 // been seen to be acceptable.
132 Arc::new(Mutex::new(if cfg!(windows) {
133 BufReader::with_capacity(8 * 1024, stdin_raw())
135 BufReader::new(stdin_raw())
141 /// Lock this handle to the standard input stream, returning a readable
144 /// The lock is released when the returned lock goes out of scope. The
145 /// returned guard also implements the `Read` and `BufRead` traits for
146 /// accessing the underlying data.
147 #[stable(feature = "rust1", since = "1.0.0")]
148 pub fn lock(&self) -> StdinLock {
149 StdinLock { inner: self.inner.lock().unwrap() }
152 /// Locks this handle and reads a line of input into the specified buffer.
154 /// For detailed semantics of this method, see the documentation on
155 /// `BufRead::read_line`.
156 #[stable(feature = "rust1", since = "1.0.0")]
157 pub fn read_line(&mut self, buf: &mut String) -> io::Result<usize> {
158 self.lock().read_line(buf)
162 #[stable(feature = "rust1", since = "1.0.0")]
163 impl Read for Stdin {
164 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
165 self.lock().read(buf)
167 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
168 self.lock().read_to_end(buf)
170 fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
171 self.lock().read_to_string(buf)
175 #[stable(feature = "rust1", since = "1.0.0")]
176 impl<'a> Read for StdinLock<'a> {
177 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
181 #[stable(feature = "rust1", since = "1.0.0")]
182 impl<'a> BufRead for StdinLock<'a> {
183 fn fill_buf(&mut self) -> io::Result<&[u8]> { self.inner.fill_buf() }
184 fn consume(&mut self, n: usize) { self.inner.consume(n) }
187 // As with stdin on windows, stdout often can't handle writes of large
188 // sizes. For an example, see #14940. For this reason, don't try to
189 // write the entire output buffer on windows. On unix we can just
190 // write the whole buffer all at once.
192 // For some other references, it appears that this problem has been
193 // encountered by others [1] [2]. We choose the number 8KB just because
194 // libuv does the same.
196 // [1]: https://tahoe-lafs.org/trac/tahoe-lafs/ticket/1232
197 // [2]: http://www.mail-archive.com/log4net-dev@logging.apache.org/msg00661.html
199 const OUT_MAX: usize = 8192;
201 const OUT_MAX: usize = ::usize::MAX;
203 /// A handle to the global standard output stream of the current process.
205 /// Each handle shares a global buffer of data to be written to the standard
206 /// output stream. Access is also synchronized via a lock and explicit control
207 /// over locking is available via the `lock` method.
208 #[stable(feature = "rust1", since = "1.0.0")]
210 // FIXME: this should be LineWriter or BufWriter depending on the state of
211 // stdout (tty or not). Note that if this is not line buffered it
212 // should also flush-on-panic or some form of flush-on-abort.
213 inner: Arc<Mutex<LineWriter<StdoutRaw>>>,
216 /// A locked reference to the a `Stdout` handle.
218 /// This handle implements the `Write` trait and is constructed via the `lock`
219 /// method on `Stdout`.
220 #[stable(feature = "rust1", since = "1.0.0")]
221 pub struct StdoutLock<'a> {
222 inner: MutexGuard<'a, LineWriter<StdoutRaw>>,
225 /// Constructs a new reference to the standard output of the current process.
227 /// Each handle returned is a reference to a shared global buffer whose access
228 /// is synchronized via a mutex. Explicit control over synchronization is
229 /// provided via the `lock` method.
231 /// The returned handle implements the `Write` trait.
232 #[stable(feature = "rust1", since = "1.0.0")]
233 pub fn stdout() -> Stdout {
234 static INSTANCE: Lazy<Mutex<LineWriter<StdoutRaw>>> = lazy_init!(stdout_init);
236 inner: INSTANCE.get().expect("cannot access stdout during shutdown"),
239 fn stdout_init() -> Arc<Mutex<LineWriter<StdoutRaw>>> {
240 Arc::new(Mutex::new(LineWriter::new(stdout_raw())))
245 /// Lock this handle to the standard output stream, returning a writable
248 /// The lock is released when the returned lock goes out of scope. The
249 /// returned guard also implements the `Write` trait for writing data.
250 #[stable(feature = "rust1", since = "1.0.0")]
251 pub fn lock(&self) -> StdoutLock {
252 StdoutLock { inner: self.inner.lock().unwrap() }
256 #[stable(feature = "rust1", since = "1.0.0")]
257 impl Write for Stdout {
258 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
259 self.lock().write(buf)
261 fn flush(&mut self) -> io::Result<()> {
264 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
265 self.lock().write_all(buf)
267 fn write_fmt(&mut self, fmt: fmt::Arguments) -> io::Result<()> {
268 self.lock().write_fmt(fmt)
271 #[stable(feature = "rust1", since = "1.0.0")]
272 impl<'a> Write for StdoutLock<'a> {
273 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
274 self.inner.write(&buf[..cmp::min(buf.len(), OUT_MAX)])
276 fn flush(&mut self) -> io::Result<()> { self.inner.flush() }
279 /// A handle to the standard error stream of a process.
281 /// For more information, see `stderr`
282 #[stable(feature = "rust1", since = "1.0.0")]
284 inner: Arc<Mutex<StderrRaw>>,
287 /// A locked reference to the a `Stderr` handle.
289 /// This handle implements the `Write` trait and is constructed via the `lock`
290 /// method on `Stderr`.
291 #[stable(feature = "rust1", since = "1.0.0")]
292 pub struct StderrLock<'a> {
293 inner: MutexGuard<'a, StderrRaw>,
296 /// Constructs a new reference to the standard error stream of a process.
298 /// Each returned handle is synchronized amongst all other handles created from
299 /// this function. No handles are buffered, however.
301 /// The returned handle implements the `Write` trait.
302 #[stable(feature = "rust1", since = "1.0.0")]
303 pub fn stderr() -> Stderr {
304 static INSTANCE: Lazy<Mutex<StderrRaw>> = lazy_init!(stderr_init);
306 inner: INSTANCE.get().expect("cannot access stderr during shutdown"),
309 fn stderr_init() -> Arc<Mutex<StderrRaw>> {
310 Arc::new(Mutex::new(stderr_raw()))
315 /// Lock this handle to the standard error stream, returning a writable
318 /// The lock is released when the returned lock goes out of scope. The
319 /// returned guard also implements the `Write` trait for writing data.
320 #[stable(feature = "rust1", since = "1.0.0")]
321 pub fn lock(&self) -> StderrLock {
322 StderrLock { inner: self.inner.lock().unwrap() }
326 #[stable(feature = "rust1", since = "1.0.0")]
327 impl Write for Stderr {
328 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
329 self.lock().write(buf)
331 fn flush(&mut self) -> io::Result<()> {
334 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
335 self.lock().write_all(buf)
337 fn write_fmt(&mut self, fmt: fmt::Arguments) -> io::Result<()> {
338 self.lock().write_fmt(fmt)
341 #[stable(feature = "rust1", since = "1.0.0")]
342 impl<'a> Write for StderrLock<'a> {
343 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
344 self.inner.write(&buf[..cmp::min(buf.len(), OUT_MAX)])
346 fn flush(&mut self) -> io::Result<()> { self.inner.flush() }
349 /// Resets the task-local stderr handle to the specified writer
351 /// This will replace the current task's stderr handle, returning the old
352 /// handle. All future calls to `panic!` and friends will emit their output to
353 /// this specified handle.
355 /// Note that this does not need to be called for all new tasks; the default
356 /// output handle is to the process's stderr stream.
357 #[unstable(feature = "set_stdio",
358 reason = "this function may disappear completely or be replaced \
359 with a more general mechanism")]
361 pub fn set_panic(sink: Box<Write + Send>) -> Option<Box<Write + Send>> {
362 use panicking::LOCAL_STDERR;
364 LOCAL_STDERR.with(move |slot| {
365 mem::replace(&mut *slot.borrow_mut(), Some(sink))
366 }).and_then(|mut s| {
372 /// Resets the task-local stdout handle to the specified writer
374 /// This will replace the current task's stdout handle, returning the old
375 /// handle. All future calls to `print!` and friends will emit their output to
376 /// this specified handle.
378 /// Note that this does not need to be called for all new tasks; the default
379 /// output handle is to the process's stdout stream.
380 #[unstable(feature = "set_stdio",
381 reason = "this function may disappear completely or be replaced \
382 with a more general mechanism")]
384 pub fn set_print(sink: Box<Write + Send>) -> Option<Box<Write + Send>> {
386 LOCAL_STDOUT.with(move |slot| {
387 mem::replace(&mut *slot.borrow_mut(), Some(sink))
388 }).and_then(|mut s| {
394 #[unstable(feature = "print",
395 reason = "implementation detail which may disappear or be replaced at any time")]
397 pub fn _print(args: fmt::Arguments) {
398 if let Err(e) = LOCAL_STDOUT.with(|s| match s.borrow_mut().as_mut() {
399 Some(w) => w.write_fmt(args),
400 None => stdout().write_fmt(args)
402 panic!("failed printing to stdout: {}", e);