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.
13 use cell::{RefCell, BorrowState};
16 use io::{self, BufReader, LineWriter};
17 use sync::{Arc, Mutex, MutexGuard};
19 use sys_common::remutex::{ReentrantMutex, ReentrantMutexGuard};
20 use thread::LocalKeyState;
22 /// Stdout used by print! and println! macros
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 /// Constructs 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() -> io::Result<StdinRaw> { stdio::Stdin::new().map(StdinRaw) }
56 /// Constructs a new raw handle to the standard output 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::stdout` 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() -> io::Result<StdoutRaw> { stdio::Stdout::new().map(StdoutRaw) }
67 /// Constructs a new raw handle to the standard error stream of this process.
69 /// The returned handle does not interact with any other handles created nor
70 /// handles returned by `std::io::stderr`.
72 /// The returned handle has no external synchronization or buffering layered on
74 fn stderr_raw() -> io::Result<StderrRaw> { stdio::Stderr::new().map(StderrRaw) }
76 impl Read for StdinRaw {
77 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) }
78 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
79 self.0.read_to_end(buf)
82 impl Write for StdoutRaw {
83 fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) }
84 fn flush(&mut self) -> io::Result<()> { Ok(()) }
86 impl Write for StderrRaw {
87 fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) }
88 fn flush(&mut self) -> io::Result<()> { Ok(()) }
96 impl<W: io::Write> io::Write for Maybe<W> {
97 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
99 Maybe::Real(ref mut w) => handle_ebadf(w.write(buf), buf.len()),
100 Maybe::Fake => Ok(buf.len())
104 fn flush(&mut self) -> io::Result<()> {
106 Maybe::Real(ref mut w) => handle_ebadf(w.flush(), ()),
107 Maybe::Fake => Ok(())
112 impl<R: io::Read> io::Read for Maybe<R> {
113 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
115 Maybe::Real(ref mut r) => handle_ebadf(r.read(buf), 0),
119 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
121 Maybe::Real(ref mut r) => handle_ebadf(r.read_to_end(buf), 0),
127 fn handle_ebadf<T>(r: io::Result<T>, default: T) -> io::Result<T> {
129 const ERR: i32 = ::sys::c::ERROR_INVALID_HANDLE as i32;
131 const ERR: i32 = ::libc::EBADF as i32;
134 Err(ref e) if e.raw_os_error() == Some(ERR) => Ok(default),
139 /// A handle to the standard input stream of a process.
141 /// Each handle is a shared reference to a global buffer of input data to this
142 /// process. A handle can be `lock`'d to gain full access to [`BufRead`] methods
143 /// (e.g. `.lines()`). Reads to this handle are otherwise locked with respect
146 /// This handle implements the `Read` trait, but beware that concurrent reads
147 /// of `Stdin` must be executed with care.
149 /// Created by the [`io::stdin`] method.
151 /// [`io::stdin`]: fn.stdin.html
152 /// [`BufRead`]: trait.BufRead.html
153 #[stable(feature = "rust1", since = "1.0.0")]
155 inner: Arc<Mutex<BufReader<Maybe<StdinRaw>>>>,
158 /// A locked reference to the `Stdin` handle.
160 /// This handle implements both the [`Read`] and [`BufRead`] traits, and
161 /// is constructed via the [`Stdin::lock`] method.
163 /// [`Read`]: trait.Read.html
164 /// [`BufRead`]: trait.BufRead.html
165 /// [`Stdin::lock`]: struct.Stdin.html#method.lock
166 #[stable(feature = "rust1", since = "1.0.0")]
167 pub struct StdinLock<'a> {
168 inner: MutexGuard<'a, BufReader<Maybe<StdinRaw>>>,
171 /// Constructs a new handle to the standard input of the current process.
173 /// Each handle returned is a reference to a shared global buffer whose access
174 /// is synchronized via a mutex. If you need more explicit control over
175 /// locking, see the [`lock() method`][lock].
177 /// [lock]: struct.Stdin.html#method.lock
181 /// Using implicit synchronization:
184 /// use std::io::{self, Read};
186 /// # fn foo() -> io::Result<String> {
187 /// let mut buffer = String::new();
188 /// try!(io::stdin().read_to_string(&mut buffer));
193 /// Using explicit synchronization:
196 /// use std::io::{self, Read};
198 /// # fn foo() -> io::Result<String> {
199 /// let mut buffer = String::new();
200 /// let stdin = io::stdin();
201 /// let mut handle = stdin.lock();
203 /// try!(handle.read_to_string(&mut buffer));
207 #[stable(feature = "rust1", since = "1.0.0")]
208 pub fn stdin() -> Stdin {
209 static INSTANCE: Lazy<Mutex<BufReader<Maybe<StdinRaw>>>> = Lazy::new(stdin_init);
211 inner: INSTANCE.get().expect("cannot access stdin during shutdown"),
214 fn stdin_init() -> Arc<Mutex<BufReader<Maybe<StdinRaw>>>> {
215 let stdin = match stdin_raw() {
216 Ok(stdin) => Maybe::Real(stdin),
220 // The default buffer capacity is 64k, but apparently windows
221 // doesn't like 64k reads on stdin. See #13304 for details, but the
222 // idea is that on windows we use a slightly smaller buffer that's
223 // been seen to be acceptable.
224 Arc::new(Mutex::new(if cfg!(windows) {
225 BufReader::with_capacity(8 * 1024, stdin)
227 BufReader::new(stdin)
233 /// Locks this handle to the standard input stream, returning a readable
236 /// The lock is released when the returned lock goes out of scope. The
237 /// returned guard also implements the [`Read`] and [`BufRead`] traits for
238 /// accessing the underlying data.
240 /// [`Read`]: trait.Read.html
241 /// [`BufRead`]: trait.BufRead.html
246 /// use std::io::{self, Read};
248 /// # fn foo() -> io::Result<String> {
249 /// let mut buffer = String::new();
250 /// let stdin = io::stdin();
251 /// let mut handle = stdin.lock();
253 /// try!(handle.read_to_string(&mut buffer));
257 #[stable(feature = "rust1", since = "1.0.0")]
258 pub fn lock(&self) -> StdinLock {
259 StdinLock { inner: self.inner.lock().unwrap_or_else(|e| e.into_inner()) }
262 /// Locks this handle and reads a line of input into the specified buffer.
264 /// For detailed semantics of this method, see the documentation on
265 /// [`BufRead::read_line`].
267 /// [`BufRead::read_line`]: trait.BufRead.html#method.read_line
274 /// let mut input = String::new();
275 /// match io::stdin().read_line(&mut input) {
277 /// println!("{} bytes read", n);
278 /// println!("{}", input);
280 /// Err(error) => println!("error: {}", error),
284 /// You can run the example one of two ways:
286 /// - Pipe some text to it, e.g. `printf foo | path/to/executable`
287 /// - Give it text interactively by running the executable directly,
288 /// in which case it will wait for the Enter key to be pressed before
290 #[stable(feature = "rust1", since = "1.0.0")]
291 pub fn read_line(&self, buf: &mut String) -> io::Result<usize> {
292 self.lock().read_line(buf)
296 #[stable(feature = "rust1", since = "1.0.0")]
297 impl Read for Stdin {
298 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
299 self.lock().read(buf)
301 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
302 self.lock().read_to_end(buf)
304 fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
305 self.lock().read_to_string(buf)
307 fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
308 self.lock().read_exact(buf)
312 #[stable(feature = "rust1", since = "1.0.0")]
313 impl<'a> Read for StdinLock<'a> {
314 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
317 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
318 self.inner.read_to_end(buf)
322 #[stable(feature = "rust1", since = "1.0.0")]
323 impl<'a> BufRead for StdinLock<'a> {
324 fn fill_buf(&mut self) -> io::Result<&[u8]> { self.inner.fill_buf() }
325 fn consume(&mut self, n: usize) { self.inner.consume(n) }
328 /// A handle to the global standard output stream of the current process.
330 /// Each handle shares a global buffer of data to be written to the standard
331 /// output stream. Access is also synchronized via a lock and explicit control
332 /// over locking is available via the `lock` method.
334 /// Created by the [`io::stdout`] method.
336 /// [`io::stdout`]: fn.stdout.html
337 #[stable(feature = "rust1", since = "1.0.0")]
339 // FIXME: this should be LineWriter or BufWriter depending on the state of
340 // stdout (tty or not). Note that if this is not line buffered it
341 // should also flush-on-panic or some form of flush-on-abort.
342 inner: Arc<ReentrantMutex<RefCell<LineWriter<Maybe<StdoutRaw>>>>>,
345 /// A locked reference to the `Stdout` handle.
347 /// This handle implements the [`Write`] trait, and is constructed via
348 /// the [`Stdout::lock`] method.
350 /// [`Write`]: trait.Write.html
351 /// [`Stdout::lock`]: struct.Stdout.html#method.lock
352 #[stable(feature = "rust1", since = "1.0.0")]
353 pub struct StdoutLock<'a> {
354 inner: ReentrantMutexGuard<'a, RefCell<LineWriter<Maybe<StdoutRaw>>>>,
357 /// Constructs a new handle to the standard output of the current process.
359 /// Each handle returned is a reference to a shared global buffer whose access
360 /// is synchronized via a mutex. If you need more explicit control over
361 /// locking, see the [Stdout::lock] method.
363 /// [Stdout::lock]: struct.Stdout.html#method.lock
367 /// Using implicit synchronization:
370 /// use std::io::{self, Write};
372 /// # fn foo() -> io::Result<()> {
373 /// try!(io::stdout().write(b"hello world"));
379 /// Using explicit synchronization:
382 /// use std::io::{self, Write};
384 /// # fn foo() -> io::Result<()> {
385 /// let stdout = io::stdout();
386 /// let mut handle = stdout.lock();
388 /// try!(handle.write(b"hello world"));
393 #[stable(feature = "rust1", since = "1.0.0")]
394 pub fn stdout() -> Stdout {
395 static INSTANCE: Lazy<ReentrantMutex<RefCell<LineWriter<Maybe<StdoutRaw>>>>>
396 = Lazy::new(stdout_init);
398 inner: INSTANCE.get().expect("cannot access stdout during shutdown"),
401 fn stdout_init() -> Arc<ReentrantMutex<RefCell<LineWriter<Maybe<StdoutRaw>>>>> {
402 let stdout = match stdout_raw() {
403 Ok(stdout) => Maybe::Real(stdout),
406 Arc::new(ReentrantMutex::new(RefCell::new(LineWriter::new(stdout))))
411 /// Locks this handle to the standard output stream, returning a writable
414 /// The lock is released when the returned lock goes out of scope. The
415 /// returned guard also implements the `Write` trait for writing data.
420 /// use std::io::{self, Write};
422 /// # fn foo() -> io::Result<()> {
423 /// let stdout = io::stdout();
424 /// let mut handle = stdout.lock();
426 /// try!(handle.write(b"hello world"));
431 #[stable(feature = "rust1", since = "1.0.0")]
432 pub fn lock(&self) -> StdoutLock {
433 StdoutLock { inner: self.inner.lock().unwrap_or_else(|e| e.into_inner()) }
437 #[stable(feature = "rust1", since = "1.0.0")]
438 impl Write for Stdout {
439 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
440 self.lock().write(buf)
442 fn flush(&mut self) -> io::Result<()> {
445 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
446 self.lock().write_all(buf)
448 fn write_fmt(&mut self, args: fmt::Arguments) -> io::Result<()> {
449 self.lock().write_fmt(args)
452 #[stable(feature = "rust1", since = "1.0.0")]
453 impl<'a> Write for StdoutLock<'a> {
454 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
455 self.inner.borrow_mut().write(buf)
457 fn flush(&mut self) -> io::Result<()> {
458 self.inner.borrow_mut().flush()
462 /// A handle to the standard error stream of a process.
464 /// For more information, see the [`io::stderr`] method.
466 /// [`io::stderr`]: fn.stderr.html
467 #[stable(feature = "rust1", since = "1.0.0")]
469 inner: Arc<ReentrantMutex<RefCell<Maybe<StderrRaw>>>>,
472 /// A locked reference to the `Stderr` handle.
474 /// This handle implements the `Write` trait and is constructed via
475 /// the [`Stderr::lock`] method.
477 /// [`Stderr::lock`]: struct.Stderr.html#method.lock
478 #[stable(feature = "rust1", since = "1.0.0")]
479 pub struct StderrLock<'a> {
480 inner: ReentrantMutexGuard<'a, RefCell<Maybe<StderrRaw>>>,
483 /// Constructs a new handle to the standard error of the current process.
485 /// This handle is not buffered.
489 /// Using implicit synchronization:
492 /// use std::io::{self, Write};
494 /// # fn foo() -> io::Result<()> {
495 /// try!(io::stderr().write(b"hello world"));
501 /// Using explicit synchronization:
504 /// use std::io::{self, Write};
506 /// # fn foo() -> io::Result<()> {
507 /// let stderr = io::stderr();
508 /// let mut handle = stderr.lock();
510 /// try!(handle.write(b"hello world"));
515 #[stable(feature = "rust1", since = "1.0.0")]
516 pub fn stderr() -> Stderr {
517 static INSTANCE: Lazy<ReentrantMutex<RefCell<Maybe<StderrRaw>>>> = Lazy::new(stderr_init);
519 inner: INSTANCE.get().expect("cannot access stderr during shutdown"),
522 fn stderr_init() -> Arc<ReentrantMutex<RefCell<Maybe<StderrRaw>>>> {
523 let stderr = match stderr_raw() {
524 Ok(stderr) => Maybe::Real(stderr),
527 Arc::new(ReentrantMutex::new(RefCell::new(stderr)))
532 /// Locks this handle to the standard error stream, returning a writable
535 /// The lock is released when the returned lock goes out of scope. The
536 /// returned guard also implements the `Write` trait for writing data.
541 /// use std::io::{self, Write};
543 /// fn foo() -> io::Result<()> {
544 /// let stderr = io::stderr();
545 /// let mut handle = stderr.lock();
547 /// try!(handle.write(b"hello world"));
552 #[stable(feature = "rust1", since = "1.0.0")]
553 pub fn lock(&self) -> StderrLock {
554 StderrLock { inner: self.inner.lock().unwrap_or_else(|e| e.into_inner()) }
558 #[stable(feature = "rust1", since = "1.0.0")]
559 impl Write for Stderr {
560 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
561 self.lock().write(buf)
563 fn flush(&mut self) -> io::Result<()> {
566 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
567 self.lock().write_all(buf)
569 fn write_fmt(&mut self, args: fmt::Arguments) -> io::Result<()> {
570 self.lock().write_fmt(args)
573 #[stable(feature = "rust1", since = "1.0.0")]
574 impl<'a> Write for StderrLock<'a> {
575 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
576 self.inner.borrow_mut().write(buf)
578 fn flush(&mut self) -> io::Result<()> {
579 self.inner.borrow_mut().flush()
583 /// Resets the thread-local stderr handle to the specified writer
585 /// This will replace the current thread's stderr handle, returning the old
586 /// handle. All future calls to `panic!` and friends will emit their output to
587 /// this specified handle.
589 /// Note that this does not need to be called for all new threads; the default
590 /// output handle is to the process's stderr stream.
591 #[unstable(feature = "set_stdio",
592 reason = "this function may disappear completely or be replaced \
593 with a more general mechanism",
596 pub fn set_panic(sink: Box<Write + Send>) -> Option<Box<Write + Send>> {
597 use panicking::LOCAL_STDERR;
599 LOCAL_STDERR.with(move |slot| {
600 mem::replace(&mut *slot.borrow_mut(), Some(sink))
601 }).and_then(|mut s| {
607 /// Resets the thread-local stdout handle to the specified writer
609 /// This will replace the current thread's stdout handle, returning the old
610 /// handle. All future calls to `print!` and friends will emit their output to
611 /// this specified handle.
613 /// Note that this does not need to be called for all new threads; the default
614 /// output handle is to the process's stdout stream.
615 #[unstable(feature = "set_stdio",
616 reason = "this function may disappear completely or be replaced \
617 with a more general mechanism",
620 pub fn set_print(sink: Box<Write + Send>) -> Option<Box<Write + Send>> {
622 LOCAL_STDOUT.with(move |slot| {
623 mem::replace(&mut *slot.borrow_mut(), Some(sink))
624 }).and_then(|mut s| {
630 #[unstable(feature = "print",
631 reason = "implementation detail which may disappear or be replaced at any time",
634 pub fn _print(args: fmt::Arguments) {
635 // As an implementation of the `println!` macro, we want to try our best to
636 // not panic wherever possible and get the output somewhere. There are
637 // currently two possible vectors for panics we take care of here:
639 // 1. If the TLS key for the local stdout has been destroyed, accessing it
640 // would cause a panic. Note that we just lump in the uninitialized case
641 // here for convenience, we're not trying to avoid a panic.
642 // 2. If the local stdout is currently in use (e.g. we're in the middle of
643 // already printing) then accessing again would cause a panic.
645 // If, however, the actual I/O causes an error, we do indeed panic.
646 let result = match LOCAL_STDOUT.state() {
647 LocalKeyState::Uninitialized |
648 LocalKeyState::Destroyed => stdout().write_fmt(args),
649 LocalKeyState::Valid => {
650 LOCAL_STDOUT.with(|s| {
651 if s.borrow_state() == BorrowState::Unused {
652 if let Some(w) = s.borrow_mut().as_mut() {
653 return w.write_fmt(args);
656 stdout().write_fmt(args)
660 if let Err(e) = result {
661 panic!("failed printing to stdout: {}", e);
671 fn panic_doesnt_poison() {
680 }).join().unwrap_err();