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.
14 use cell::{RefCell, BorrowState};
17 use io::{self, BufReader, LineWriter};
18 use sync::{Arc, Mutex, MutexGuard};
20 use sys_common::remutex::{ReentrantMutex, ReentrantMutexGuard};
21 use thread::LocalKeyState;
23 /// Stdout used by print! and println! macros
25 static LOCAL_STDOUT: RefCell<Option<Box<Write + Send>>> = {
30 /// A handle to a raw instance of the standard input stream of this process.
32 /// This handle is not synchronized or buffered in any fashion. Constructed via
33 /// the `std::io::stdio::stdin_raw` function.
34 struct StdinRaw(stdio::Stdin);
36 /// A handle to a raw instance of the standard output stream of this process.
38 /// This handle is not synchronized or buffered in any fashion. Constructed via
39 /// the `std::io::stdio::stdout_raw` function.
40 struct StdoutRaw(stdio::Stdout);
42 /// A handle to a raw instance of the standard output stream of this process.
44 /// This handle is not synchronized or buffered in any fashion. Constructed via
45 /// the `std::io::stdio::stderr_raw` function.
46 struct StderrRaw(stdio::Stderr);
48 /// Constructs a new raw handle to the standard input of this process.
50 /// The returned handle does not interact with any other handles created nor
51 /// handles returned by `std::io::stdin`. Data buffered by the `std::io::stdin`
52 /// handles is **not** available to raw handles returned from this function.
54 /// The returned handle has no external synchronization or buffering.
55 fn stdin_raw() -> io::Result<StdinRaw> { stdio::Stdin::new().map(StdinRaw) }
57 /// Constructs a new raw handle to the standard output stream of this process.
59 /// The returned handle does not interact with any other handles created nor
60 /// handles returned by `std::io::stdout`. Note that data is buffered by the
61 /// `std::io::stdout` handles so writes which happen via this raw handle may
62 /// appear before previous writes.
64 /// The returned handle has no external synchronization or buffering layered on
66 fn stdout_raw() -> io::Result<StdoutRaw> { stdio::Stdout::new().map(StdoutRaw) }
68 /// Constructs a new raw handle to the standard error stream of this process.
70 /// The returned handle does not interact with any other handles created nor
71 /// handles returned by `std::io::stderr`.
73 /// The returned handle has no external synchronization or buffering layered on
75 fn stderr_raw() -> io::Result<StderrRaw> { stdio::Stderr::new().map(StderrRaw) }
77 impl Read for StdinRaw {
78 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) }
79 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
80 self.0.read_to_end(buf)
83 impl Write for StdoutRaw {
84 fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) }
85 fn flush(&mut self) -> io::Result<()> { Ok(()) }
87 impl Write for StderrRaw {
88 fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) }
89 fn flush(&mut self) -> io::Result<()> { Ok(()) }
97 impl<W: io::Write> io::Write for Maybe<W> {
98 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
100 Maybe::Real(ref mut w) => handle_ebadf(w.write(buf), buf.len()),
101 Maybe::Fake => Ok(buf.len())
105 fn flush(&mut self) -> io::Result<()> {
107 Maybe::Real(ref mut w) => handle_ebadf(w.flush(), ()),
108 Maybe::Fake => Ok(())
113 impl<R: io::Read> io::Read for Maybe<R> {
114 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
116 Maybe::Real(ref mut r) => handle_ebadf(r.read(buf), 0),
120 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
122 Maybe::Real(ref mut r) => handle_ebadf(r.read_to_end(buf), 0),
128 fn handle_ebadf<T>(r: io::Result<T>, default: T) -> io::Result<T> {
130 const ERR: i32 = ::sys::c::ERROR_INVALID_HANDLE as i32;
132 const ERR: i32 = ::libc::EBADF as i32;
135 Err(ref e) if e.raw_os_error() == Some(ERR) => Ok(default),
140 /// A handle to the standard input stream of a process.
142 /// Each handle is a shared reference to a global buffer of input data to this
143 /// process. A handle can be `lock`'d to gain full access to [`BufRead`] methods
144 /// (e.g. `.lines()`). Reads to this handle are otherwise locked with respect
147 /// This handle implements the `Read` trait, but beware that concurrent reads
148 /// of `Stdin` must be executed with care.
150 /// Created by the [`io::stdin`] method.
152 /// [`io::stdin`]: fn.stdin.html
153 /// [`BufRead`]: trait.BufRead.html
154 #[stable(feature = "rust1", since = "1.0.0")]
156 inner: Arc<Mutex<BufReader<Maybe<StdinRaw>>>>,
159 /// A locked reference to the `Stdin` handle.
161 /// This handle implements both the [`Read`] and [`BufRead`] traits, and
162 /// is constructed via the [`Stdin::lock`] method.
164 /// [`Read`]: trait.Read.html
165 /// [`BufRead`]: trait.BufRead.html
166 /// [`Stdin::lock`]: struct.Stdin.html#method.lock
167 #[stable(feature = "rust1", since = "1.0.0")]
168 pub struct StdinLock<'a> {
169 inner: MutexGuard<'a, BufReader<Maybe<StdinRaw>>>,
172 /// Constructs a new handle to the standard input of the current process.
174 /// Each handle returned is a reference to a shared global buffer whose access
175 /// is synchronized via a mutex. If you need more explicit control over
176 /// locking, see the [`lock() method`][lock].
178 /// [lock]: struct.Stdin.html#method.lock
182 /// Using implicit synchronization:
185 /// use std::io::{self, Read};
187 /// # fn foo() -> io::Result<String> {
188 /// let mut buffer = String::new();
189 /// try!(io::stdin().read_to_string(&mut buffer));
194 /// Using explicit synchronization:
197 /// use std::io::{self, Read};
199 /// # fn foo() -> io::Result<String> {
200 /// let mut buffer = String::new();
201 /// let stdin = io::stdin();
202 /// let mut handle = stdin.lock();
204 /// try!(handle.read_to_string(&mut buffer));
208 #[stable(feature = "rust1", since = "1.0.0")]
209 pub fn stdin() -> Stdin {
210 static INSTANCE: Lazy<Mutex<BufReader<Maybe<StdinRaw>>>> = Lazy::new(stdin_init);
212 inner: INSTANCE.get().expect("cannot access stdin during shutdown"),
215 fn stdin_init() -> Arc<Mutex<BufReader<Maybe<StdinRaw>>>> {
216 let stdin = match stdin_raw() {
217 Ok(stdin) => Maybe::Real(stdin),
221 // The default buffer capacity is 64k, but apparently windows
222 // doesn't like 64k reads on stdin. See #13304 for details, but the
223 // idea is that on windows we use a slightly smaller buffer that's
224 // been seen to be acceptable.
225 Arc::new(Mutex::new(if cfg!(windows) {
226 BufReader::with_capacity(8 * 1024, stdin)
228 BufReader::new(stdin)
234 /// Locks this handle to the standard input stream, returning a readable
237 /// The lock is released when the returned lock goes out of scope. The
238 /// returned guard also implements the [`Read`] and [`BufRead`] traits for
239 /// accessing the underlying data.
241 /// [`Read`]: trait.Read.html
242 /// [`BufRead`]: trait.BufRead.html
243 #[stable(feature = "rust1", since = "1.0.0")]
244 pub fn lock(&self) -> StdinLock {
245 StdinLock { inner: self.inner.lock().unwrap_or_else(|e| e.into_inner()) }
248 /// Locks this handle and reads a line of input into the specified buffer.
250 /// For detailed semantics of this method, see the documentation on
251 /// [`BufRead::read_line`].
253 /// [`BufRead::read_line`]: trait.BufRead.html#method.read_line
260 /// let mut input = String::new();
261 /// match io::stdin().read_line(&mut input) {
263 /// println!("{} bytes read", n);
264 /// println!("{}", input);
266 /// Err(error) => println!("error: {}", error),
270 /// You can run the example one of two ways:
272 /// - Pipe some text to it, e.g. `printf foo | path/to/executable`
273 /// - Give it text interactively by running the executable directly,
274 /// in which case it will wait for the Enter key to be pressed before
276 #[stable(feature = "rust1", since = "1.0.0")]
277 pub fn read_line(&self, buf: &mut String) -> io::Result<usize> {
278 self.lock().read_line(buf)
282 #[stable(feature = "rust1", since = "1.0.0")]
283 impl Read for Stdin {
284 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
285 self.lock().read(buf)
287 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
288 self.lock().read_to_end(buf)
290 fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
291 self.lock().read_to_string(buf)
293 fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
294 self.lock().read_exact(buf)
298 #[stable(feature = "rust1", since = "1.0.0")]
299 impl<'a> Read for StdinLock<'a> {
300 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
303 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
304 self.inner.read_to_end(buf)
308 #[stable(feature = "rust1", since = "1.0.0")]
309 impl<'a> BufRead for StdinLock<'a> {
310 fn fill_buf(&mut self) -> io::Result<&[u8]> { self.inner.fill_buf() }
311 fn consume(&mut self, n: usize) { self.inner.consume(n) }
314 /// A handle to the global standard output stream of the current process.
316 /// Each handle shares a global buffer of data to be written to the standard
317 /// output stream. Access is also synchronized via a lock and explicit control
318 /// over locking is available via the `lock` method.
320 /// Created by the [`io::stdout`] method.
322 /// [`io::stdout`]: fn.stdout.html
323 #[stable(feature = "rust1", since = "1.0.0")]
325 // FIXME: this should be LineWriter or BufWriter depending on the state of
326 // stdout (tty or not). Note that if this is not line buffered it
327 // should also flush-on-panic or some form of flush-on-abort.
328 inner: Arc<ReentrantMutex<RefCell<LineWriter<Maybe<StdoutRaw>>>>>,
331 /// A locked reference to the `Stdout` handle.
333 /// This handle implements the [`Write`] trait, and is constructed via
334 /// the [`Stdout::lock`] method.
336 /// [`Write`]: trait.Write.html
337 /// [`Stdout::lock`]: struct.Stdout.html#method.lock
338 #[stable(feature = "rust1", since = "1.0.0")]
339 pub struct StdoutLock<'a> {
340 inner: ReentrantMutexGuard<'a, RefCell<LineWriter<Maybe<StdoutRaw>>>>,
343 /// Constructs a new handle to the standard output of the current process.
345 /// Each handle returned is a reference to a shared global buffer whose access
346 /// is synchronized via a mutex. If you need more explicit control over
347 /// locking, see the [Stdout::lock] method.
349 /// [Stdout::lock]: struct.Stdout.html#method.lock
353 /// Using implicit synchronization:
356 /// use std::io::{self, Write};
358 /// # fn foo() -> io::Result<()> {
359 /// try!(io::stdout().write(b"hello world"));
365 /// Using explicit synchronization:
368 /// use std::io::{self, Write};
370 /// # fn foo() -> io::Result<()> {
371 /// let stdout = io::stdout();
372 /// let mut handle = stdout.lock();
374 /// try!(handle.write(b"hello world"));
379 #[stable(feature = "rust1", since = "1.0.0")]
380 pub fn stdout() -> Stdout {
381 static INSTANCE: Lazy<ReentrantMutex<RefCell<LineWriter<Maybe<StdoutRaw>>>>>
382 = Lazy::new(stdout_init);
384 inner: INSTANCE.get().expect("cannot access stdout during shutdown"),
387 fn stdout_init() -> Arc<ReentrantMutex<RefCell<LineWriter<Maybe<StdoutRaw>>>>> {
388 let stdout = match stdout_raw() {
389 Ok(stdout) => Maybe::Real(stdout),
392 Arc::new(ReentrantMutex::new(RefCell::new(LineWriter::new(stdout))))
397 /// Locks this handle to the standard output stream, returning a writable
400 /// The lock is released when the returned lock goes out of scope. The
401 /// returned guard also implements the `Write` trait for writing data.
402 #[stable(feature = "rust1", since = "1.0.0")]
403 pub fn lock(&self) -> StdoutLock {
404 StdoutLock { inner: self.inner.lock().unwrap_or_else(|e| e.into_inner()) }
408 #[stable(feature = "rust1", since = "1.0.0")]
409 impl Write for Stdout {
410 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
411 self.lock().write(buf)
413 fn flush(&mut self) -> io::Result<()> {
416 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
417 self.lock().write_all(buf)
419 fn write_fmt(&mut self, args: fmt::Arguments) -> io::Result<()> {
420 self.lock().write_fmt(args)
423 #[stable(feature = "rust1", since = "1.0.0")]
424 impl<'a> Write for StdoutLock<'a> {
425 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
426 self.inner.borrow_mut().write(buf)
428 fn flush(&mut self) -> io::Result<()> {
429 self.inner.borrow_mut().flush()
433 /// A handle to the standard error stream of a process.
435 /// For more information, see the [`io::stderr`] method.
437 /// [`io::stderr`]: fn.stderr.html
438 #[stable(feature = "rust1", since = "1.0.0")]
440 inner: Arc<ReentrantMutex<RefCell<Maybe<StderrRaw>>>>,
443 /// A locked reference to the `Stderr` handle.
445 /// This handle implements the `Write` trait and is constructed via
446 /// the [`Stderr::lock`] method.
448 /// [`Stderr::lock`]: struct.Stderr.html#method.lock
449 #[stable(feature = "rust1", since = "1.0.0")]
450 pub struct StderrLock<'a> {
451 inner: ReentrantMutexGuard<'a, RefCell<Maybe<StderrRaw>>>,
454 /// Constructs a new handle to the standard error of the current process.
456 /// This handle is not buffered.
460 /// Using implicit synchronization:
463 /// use std::io::{self, Write};
465 /// # fn foo() -> io::Result<()> {
466 /// try!(io::stderr().write(b"hello world"));
472 /// Using explicit synchronization:
475 /// use std::io::{self, Write};
477 /// # fn foo() -> io::Result<()> {
478 /// let stderr = io::stderr();
479 /// let mut handle = stderr.lock();
481 /// try!(handle.write(b"hello world"));
486 #[stable(feature = "rust1", since = "1.0.0")]
487 pub fn stderr() -> Stderr {
488 static INSTANCE: Lazy<ReentrantMutex<RefCell<Maybe<StderrRaw>>>> = Lazy::new(stderr_init);
490 inner: INSTANCE.get().expect("cannot access stderr during shutdown"),
493 fn stderr_init() -> Arc<ReentrantMutex<RefCell<Maybe<StderrRaw>>>> {
494 let stderr = match stderr_raw() {
495 Ok(stderr) => Maybe::Real(stderr),
498 Arc::new(ReentrantMutex::new(RefCell::new(stderr)))
503 /// Locks this handle to the standard error stream, returning a writable
506 /// The lock is released when the returned lock goes out of scope. The
507 /// returned guard also implements the `Write` trait for writing data.
508 #[stable(feature = "rust1", since = "1.0.0")]
509 pub fn lock(&self) -> StderrLock {
510 StderrLock { inner: self.inner.lock().unwrap_or_else(|e| e.into_inner()) }
514 #[stable(feature = "rust1", since = "1.0.0")]
515 impl Write for Stderr {
516 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
517 self.lock().write(buf)
519 fn flush(&mut self) -> io::Result<()> {
522 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
523 self.lock().write_all(buf)
525 fn write_fmt(&mut self, args: fmt::Arguments) -> io::Result<()> {
526 self.lock().write_fmt(args)
529 #[stable(feature = "rust1", since = "1.0.0")]
530 impl<'a> Write for StderrLock<'a> {
531 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
532 self.inner.borrow_mut().write(buf)
534 fn flush(&mut self) -> io::Result<()> {
535 self.inner.borrow_mut().flush()
539 /// Resets the thread-local stderr handle to the specified writer
541 /// This will replace the current thread's stderr handle, returning the old
542 /// handle. All future calls to `panic!` and friends will emit their output to
543 /// this specified handle.
545 /// Note that this does not need to be called for all new threads; the default
546 /// output handle is to the process's stderr stream.
547 #[unstable(feature = "set_stdio",
548 reason = "this function may disappear completely or be replaced \
549 with a more general mechanism",
552 pub fn set_panic(sink: Box<Write + Send>) -> Option<Box<Write + Send>> {
553 use panicking::LOCAL_STDERR;
555 LOCAL_STDERR.with(move |slot| {
556 mem::replace(&mut *slot.borrow_mut(), Some(sink))
557 }).and_then(|mut s| {
563 /// Resets the thread-local stdout handle to the specified writer
565 /// This will replace the current thread's stdout handle, returning the old
566 /// handle. All future calls to `print!` and friends will emit their output to
567 /// this specified handle.
569 /// Note that this does not need to be called for all new threads; the default
570 /// output handle is to the process's stdout stream.
571 #[unstable(feature = "set_stdio",
572 reason = "this function may disappear completely or be replaced \
573 with a more general mechanism",
576 pub fn set_print(sink: Box<Write + Send>) -> Option<Box<Write + Send>> {
578 LOCAL_STDOUT.with(move |slot| {
579 mem::replace(&mut *slot.borrow_mut(), Some(sink))
580 }).and_then(|mut s| {
586 #[unstable(feature = "print",
587 reason = "implementation detail which may disappear or be replaced at any time",
590 pub fn _print(args: fmt::Arguments) {
591 // As an implementation of the `println!` macro, we want to try our best to
592 // not panic wherever possible and get the output somewhere. There are
593 // currently two possible vectors for panics we take care of here:
595 // 1. If the TLS key for the local stdout has been destroyed, accessing it
596 // would cause a panic. Note that we just lump in the uninitialized case
597 // here for convenience, we're not trying to avoid a panic.
598 // 2. If the local stdout is currently in use (e.g. we're in the middle of
599 // already printing) then accessing again would cause a panic.
601 // If, however, the actual I/O causes an error, we do indeed panic.
602 let result = match LOCAL_STDOUT.state() {
603 LocalKeyState::Uninitialized |
604 LocalKeyState::Destroyed => stdout().write_fmt(args),
605 LocalKeyState::Valid => {
606 LOCAL_STDOUT.with(|s| {
607 if s.borrow_state() == BorrowState::Unused {
608 if let Some(w) = s.borrow_mut().as_mut() {
609 return w.write_fmt(args);
612 stdout().write_fmt(args)
616 if let Err(e) = result {
617 panic!("failed printing to stdout: {}", e);
627 fn panic_doesnt_poison() {
636 }).join().unwrap_err();