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
247 /// use std::io::{self, Read};
249 /// # fn foo() -> io::Result<String> {
250 /// let mut buffer = String::new();
251 /// let stdin = io::stdin();
252 /// let mut handle = stdin.lock();
254 /// try!(handle.read_to_string(&mut buffer));
258 #[stable(feature = "rust1", since = "1.0.0")]
259 pub fn lock(&self) -> StdinLock {
260 StdinLock { inner: self.inner.lock().unwrap_or_else(|e| e.into_inner()) }
263 /// Locks this handle and reads a line of input into the specified buffer.
265 /// For detailed semantics of this method, see the documentation on
266 /// [`BufRead::read_line`].
268 /// [`BufRead::read_line`]: trait.BufRead.html#method.read_line
275 /// let mut input = String::new();
276 /// match io::stdin().read_line(&mut input) {
278 /// println!("{} bytes read", n);
279 /// println!("{}", input);
281 /// Err(error) => println!("error: {}", error),
285 /// You can run the example one of two ways:
287 /// - Pipe some text to it, e.g. `printf foo | path/to/executable`
288 /// - Give it text interactively by running the executable directly,
289 /// in which case it will wait for the Enter key to be pressed before
291 #[stable(feature = "rust1", since = "1.0.0")]
292 pub fn read_line(&self, buf: &mut String) -> io::Result<usize> {
293 self.lock().read_line(buf)
297 #[stable(feature = "rust1", since = "1.0.0")]
298 impl Read for Stdin {
299 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
300 self.lock().read(buf)
302 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
303 self.lock().read_to_end(buf)
305 fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
306 self.lock().read_to_string(buf)
308 fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
309 self.lock().read_exact(buf)
313 #[stable(feature = "rust1", since = "1.0.0")]
314 impl<'a> Read for StdinLock<'a> {
315 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
318 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
319 self.inner.read_to_end(buf)
323 #[stable(feature = "rust1", since = "1.0.0")]
324 impl<'a> BufRead for StdinLock<'a> {
325 fn fill_buf(&mut self) -> io::Result<&[u8]> { self.inner.fill_buf() }
326 fn consume(&mut self, n: usize) { self.inner.consume(n) }
329 /// A handle to the global standard output stream of the current process.
331 /// Each handle shares a global buffer of data to be written to the standard
332 /// output stream. Access is also synchronized via a lock and explicit control
333 /// over locking is available via the `lock` method.
335 /// Created by the [`io::stdout`] method.
337 /// [`io::stdout`]: fn.stdout.html
338 #[stable(feature = "rust1", since = "1.0.0")]
340 // FIXME: this should be LineWriter or BufWriter depending on the state of
341 // stdout (tty or not). Note that if this is not line buffered it
342 // should also flush-on-panic or some form of flush-on-abort.
343 inner: Arc<ReentrantMutex<RefCell<LineWriter<Maybe<StdoutRaw>>>>>,
346 /// A locked reference to the `Stdout` handle.
348 /// This handle implements the [`Write`] trait, and is constructed via
349 /// the [`Stdout::lock`] method.
351 /// [`Write`]: trait.Write.html
352 /// [`Stdout::lock`]: struct.Stdout.html#method.lock
353 #[stable(feature = "rust1", since = "1.0.0")]
354 pub struct StdoutLock<'a> {
355 inner: ReentrantMutexGuard<'a, RefCell<LineWriter<Maybe<StdoutRaw>>>>,
358 /// Constructs a new handle to the standard output of the current process.
360 /// Each handle returned is a reference to a shared global buffer whose access
361 /// is synchronized via a mutex. If you need more explicit control over
362 /// locking, see the [Stdout::lock] method.
364 /// [Stdout::lock]: struct.Stdout.html#method.lock
368 /// Using implicit synchronization:
371 /// use std::io::{self, Write};
373 /// # fn foo() -> io::Result<()> {
374 /// try!(io::stdout().write(b"hello world"));
380 /// Using explicit synchronization:
383 /// use std::io::{self, Write};
385 /// # fn foo() -> io::Result<()> {
386 /// let stdout = io::stdout();
387 /// let mut handle = stdout.lock();
389 /// try!(handle.write(b"hello world"));
394 #[stable(feature = "rust1", since = "1.0.0")]
395 pub fn stdout() -> Stdout {
396 static INSTANCE: Lazy<ReentrantMutex<RefCell<LineWriter<Maybe<StdoutRaw>>>>>
397 = Lazy::new(stdout_init);
399 inner: INSTANCE.get().expect("cannot access stdout during shutdown"),
402 fn stdout_init() -> Arc<ReentrantMutex<RefCell<LineWriter<Maybe<StdoutRaw>>>>> {
403 let stdout = match stdout_raw() {
404 Ok(stdout) => Maybe::Real(stdout),
407 Arc::new(ReentrantMutex::new(RefCell::new(LineWriter::new(stdout))))
412 /// Locks this handle to the standard output stream, returning a writable
415 /// The lock is released when the returned lock goes out of scope. The
416 /// returned guard also implements the `Write` trait for writing data.
421 /// use std::io::{self, Write};
423 /// # fn foo() -> io::Result<()> {
424 /// let stdout = io::stdout();
425 /// let mut handle = stdout.lock();
427 /// try!(handle.write(b"hello world"));
432 #[stable(feature = "rust1", since = "1.0.0")]
433 pub fn lock(&self) -> StdoutLock {
434 StdoutLock { inner: self.inner.lock().unwrap_or_else(|e| e.into_inner()) }
438 #[stable(feature = "rust1", since = "1.0.0")]
439 impl Write for Stdout {
440 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
441 self.lock().write(buf)
443 fn flush(&mut self) -> io::Result<()> {
446 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
447 self.lock().write_all(buf)
449 fn write_fmt(&mut self, args: fmt::Arguments) -> io::Result<()> {
450 self.lock().write_fmt(args)
453 #[stable(feature = "rust1", since = "1.0.0")]
454 impl<'a> Write for StdoutLock<'a> {
455 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
456 self.inner.borrow_mut().write(buf)
458 fn flush(&mut self) -> io::Result<()> {
459 self.inner.borrow_mut().flush()
463 /// A handle to the standard error stream of a process.
465 /// For more information, see the [`io::stderr`] method.
467 /// [`io::stderr`]: fn.stderr.html
468 #[stable(feature = "rust1", since = "1.0.0")]
470 inner: Arc<ReentrantMutex<RefCell<Maybe<StderrRaw>>>>,
473 /// A locked reference to the `Stderr` handle.
475 /// This handle implements the `Write` trait and is constructed via
476 /// the [`Stderr::lock`] method.
478 /// [`Stderr::lock`]: struct.Stderr.html#method.lock
479 #[stable(feature = "rust1", since = "1.0.0")]
480 pub struct StderrLock<'a> {
481 inner: ReentrantMutexGuard<'a, RefCell<Maybe<StderrRaw>>>,
484 /// Constructs a new handle to the standard error of the current process.
486 /// This handle is not buffered.
490 /// Using implicit synchronization:
493 /// use std::io::{self, Write};
495 /// # fn foo() -> io::Result<()> {
496 /// try!(io::stderr().write(b"hello world"));
502 /// Using explicit synchronization:
505 /// use std::io::{self, Write};
507 /// # fn foo() -> io::Result<()> {
508 /// let stderr = io::stderr();
509 /// let mut handle = stderr.lock();
511 /// try!(handle.write(b"hello world"));
516 #[stable(feature = "rust1", since = "1.0.0")]
517 pub fn stderr() -> Stderr {
518 static INSTANCE: Lazy<ReentrantMutex<RefCell<Maybe<StderrRaw>>>> = Lazy::new(stderr_init);
520 inner: INSTANCE.get().expect("cannot access stderr during shutdown"),
523 fn stderr_init() -> Arc<ReentrantMutex<RefCell<Maybe<StderrRaw>>>> {
524 let stderr = match stderr_raw() {
525 Ok(stderr) => Maybe::Real(stderr),
528 Arc::new(ReentrantMutex::new(RefCell::new(stderr)))
533 /// Locks this handle to the standard error stream, returning a writable
536 /// The lock is released when the returned lock goes out of scope. The
537 /// returned guard also implements the `Write` trait for writing data.
542 /// use std::io::{self, Write};
544 /// fn foo() -> io::Result<()> {
545 /// let stderr = io::stderr();
546 /// let mut handle = stderr.lock();
548 /// try!(handle.write(b"hello world"));
553 #[stable(feature = "rust1", since = "1.0.0")]
554 pub fn lock(&self) -> StderrLock {
555 StderrLock { inner: self.inner.lock().unwrap_or_else(|e| e.into_inner()) }
559 #[stable(feature = "rust1", since = "1.0.0")]
560 impl Write for Stderr {
561 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
562 self.lock().write(buf)
564 fn flush(&mut self) -> io::Result<()> {
567 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
568 self.lock().write_all(buf)
570 fn write_fmt(&mut self, args: fmt::Arguments) -> io::Result<()> {
571 self.lock().write_fmt(args)
574 #[stable(feature = "rust1", since = "1.0.0")]
575 impl<'a> Write for StderrLock<'a> {
576 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
577 self.inner.borrow_mut().write(buf)
579 fn flush(&mut self) -> io::Result<()> {
580 self.inner.borrow_mut().flush()
584 /// Resets the thread-local stderr handle to the specified writer
586 /// This will replace the current thread's stderr handle, returning the old
587 /// handle. All future calls to `panic!` and friends will emit their output to
588 /// this specified handle.
590 /// Note that this does not need to be called for all new threads; the default
591 /// output handle is to the process's stderr stream.
592 #[unstable(feature = "set_stdio",
593 reason = "this function may disappear completely or be replaced \
594 with a more general mechanism",
597 pub fn set_panic(sink: Box<Write + Send>) -> Option<Box<Write + Send>> {
598 use panicking::LOCAL_STDERR;
600 LOCAL_STDERR.with(move |slot| {
601 mem::replace(&mut *slot.borrow_mut(), Some(sink))
602 }).and_then(|mut s| {
608 /// Resets the thread-local stdout handle to the specified writer
610 /// This will replace the current thread's stdout handle, returning the old
611 /// handle. All future calls to `print!` and friends will emit their output to
612 /// this specified handle.
614 /// Note that this does not need to be called for all new threads; the default
615 /// output handle is to the process's stdout stream.
616 #[unstable(feature = "set_stdio",
617 reason = "this function may disappear completely or be replaced \
618 with a more general mechanism",
621 pub fn set_print(sink: Box<Write + Send>) -> Option<Box<Write + Send>> {
623 LOCAL_STDOUT.with(move |slot| {
624 mem::replace(&mut *slot.borrow_mut(), Some(sink))
625 }).and_then(|mut s| {
631 #[unstable(feature = "print",
632 reason = "implementation detail which may disappear or be replaced at any time",
635 pub fn _print(args: fmt::Arguments) {
636 // As an implementation of the `println!` macro, we want to try our best to
637 // not panic wherever possible and get the output somewhere. There are
638 // currently two possible vectors for panics we take care of here:
640 // 1. If the TLS key for the local stdout has been destroyed, accessing it
641 // would cause a panic. Note that we just lump in the uninitialized case
642 // here for convenience, we're not trying to avoid a panic.
643 // 2. If the local stdout is currently in use (e.g. we're in the middle of
644 // already printing) then accessing again would cause a panic.
646 // If, however, the actual I/O causes an error, we do indeed panic.
647 let result = match LOCAL_STDOUT.state() {
648 LocalKeyState::Uninitialized |
649 LocalKeyState::Destroyed => stdout().write_fmt(args),
650 LocalKeyState::Valid => {
651 LOCAL_STDOUT.with(|s| {
652 if s.borrow_state() == BorrowState::Unused {
653 if let Some(w) = s.borrow_mut().as_mut() {
654 return w.write_fmt(args);
657 stdout().write_fmt(args)
661 if let Err(e) = result {
662 panic!("failed printing to stdout: {}", e);
672 fn panic_doesnt_poison() {
681 }).join().unwrap_err();