1 #![cfg_attr(test, allow(unused))]
3 use crate::io::prelude::*;
5 use crate::cell::RefCell;
7 use crate::io::lazy::Lazy;
8 use crate::io::{self, BufReader, Initializer, IoSlice, IoSliceMut, LineWriter};
9 use crate::sync::{Arc, Mutex, MutexGuard, Once};
10 use crate::sys::stdio;
11 use crate::sys_common::remutex::{ReentrantMutex, ReentrantMutexGuard};
12 use crate::thread::LocalKey;
15 /// Stdout used by print! and println! macros
16 static LOCAL_STDOUT: RefCell<Option<Box<dyn Write + Send>>> = {
22 /// Stderr used by eprint! and eprintln! macros, and panics
23 static LOCAL_STDERR: RefCell<Option<Box<dyn Write + Send>>> = {
28 /// A handle to a raw instance of the standard input stream of this process.
30 /// This handle is not synchronized or buffered in any fashion. Constructed via
31 /// the `std::io::stdio::stdin_raw` function.
32 struct StdinRaw(stdio::Stdin);
34 /// A handle to a raw instance of the standard output stream of this process.
36 /// This handle is not synchronized or buffered in any fashion. Constructed via
37 /// the `std::io::stdio::stdout_raw` function.
38 struct StdoutRaw(stdio::Stdout);
40 /// A handle to a raw instance of the standard output stream of this process.
42 /// This handle is not synchronized or buffered in any fashion. Constructed via
43 /// the `std::io::stdio::stderr_raw` function.
44 struct StderrRaw(stdio::Stderr);
46 /// Constructs a new raw handle to the standard input of this process.
48 /// The returned handle does not interact with any other handles created nor
49 /// handles returned by `std::io::stdin`. Data buffered by the `std::io::stdin`
50 /// handles is **not** available to raw handles returned from this function.
52 /// The returned handle has no external synchronization or buffering.
53 fn stdin_raw() -> io::Result<StdinRaw> {
54 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> {
67 stdio::Stdout::new().map(StdoutRaw)
70 /// Constructs a new raw handle to the standard error stream of this process.
72 /// The returned handle does not interact with any other handles created nor
73 /// handles returned by `std::io::stderr`.
75 /// The returned handle has no external synchronization or buffering layered on
77 fn stderr_raw() -> io::Result<StderrRaw> {
78 stdio::Stderr::new().map(StderrRaw)
81 impl Read for StdinRaw {
82 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
86 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
87 self.0.read_vectored(bufs)
91 fn is_read_vectored(&self) -> bool {
92 self.0.is_read_vectored()
96 unsafe fn initializer(&self) -> Initializer {
100 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
101 self.0.read_to_end(buf)
104 fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
105 self.0.read_to_string(buf)
108 fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
109 self.0.read_exact(buf)
113 impl Write for StdoutRaw {
114 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
118 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
119 self.0.write_vectored(bufs)
123 fn is_write_vectored(&self) -> bool {
124 self.0.is_write_vectored()
127 fn flush(&mut self) -> io::Result<()> {
131 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
132 self.0.write_all(buf)
135 fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> {
136 self.0.write_all_vectored(bufs)
139 fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> io::Result<()> {
140 self.0.write_fmt(fmt)
144 impl Write for StderrRaw {
145 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
149 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
150 self.0.write_vectored(bufs)
154 fn is_write_vectored(&self) -> bool {
155 self.0.is_write_vectored()
158 fn flush(&mut self) -> io::Result<()> {
162 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
163 self.0.write_all(buf)
166 fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> {
167 self.0.write_all_vectored(bufs)
170 fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> io::Result<()> {
171 self.0.write_fmt(fmt)
180 impl<W: io::Write> io::Write for Maybe<W> {
181 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
183 Maybe::Real(ref mut w) => handle_ebadf(w.write(buf), buf.len()),
184 Maybe::Fake => Ok(buf.len()),
188 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
189 let total = bufs.iter().map(|b| b.len()).sum();
191 Maybe::Real(w) => handle_ebadf(w.write_vectored(bufs), total),
192 Maybe::Fake => Ok(total),
197 fn is_write_vectored(&self) -> bool {
199 Maybe::Real(w) => w.is_write_vectored(),
204 fn flush(&mut self) -> io::Result<()> {
206 Maybe::Real(ref mut w) => handle_ebadf(w.flush(), ()),
207 Maybe::Fake => Ok(()),
212 impl<R: io::Read> io::Read for Maybe<R> {
213 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
215 Maybe::Real(ref mut r) => handle_ebadf(r.read(buf), 0),
216 Maybe::Fake => Ok(0),
220 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
222 Maybe::Real(r) => handle_ebadf(r.read_vectored(bufs), 0),
223 Maybe::Fake => Ok(0),
228 fn is_read_vectored(&self) -> bool {
230 Maybe::Real(w) => w.is_read_vectored(),
236 fn handle_ebadf<T>(r: io::Result<T>, default: T) -> io::Result<T> {
238 Err(ref e) if stdio::is_ebadf(e) => Ok(default),
243 /// A handle to the standard input stream of a process.
245 /// Each handle is a shared reference to a global buffer of input data to this
246 /// process. A handle can be `lock`'d to gain full access to [`BufRead`] methods
247 /// (e.g., `.lines()`). Reads to this handle are otherwise locked with respect
250 /// This handle implements the `Read` trait, but beware that concurrent reads
251 /// of `Stdin` must be executed with care.
253 /// Created by the [`io::stdin`] method.
255 /// [`io::stdin`]: fn.stdin.html
256 /// [`BufRead`]: trait.BufRead.html
258 /// ### Note: Windows Portability Consideration
259 /// When operating in a console, the Windows implementation of this stream does not support
260 /// non-UTF-8 byte sequences. Attempting to read bytes that are not valid UTF-8 will return
262 #[stable(feature = "rust1", since = "1.0.0")]
264 inner: Arc<Mutex<BufReader<Maybe<StdinRaw>>>>,
267 /// A locked reference to the `Stdin` handle.
269 /// This handle implements both the [`Read`] and [`BufRead`] traits, and
270 /// is constructed via the [`Stdin::lock`] method.
272 /// [`Read`]: trait.Read.html
273 /// [`BufRead`]: trait.BufRead.html
274 /// [`Stdin::lock`]: struct.Stdin.html#method.lock
276 /// ### Note: Windows Portability Consideration
277 /// When operating in a console, the Windows implementation of this stream does not support
278 /// non-UTF-8 byte sequences. Attempting to read bytes that are not valid UTF-8 will return
280 #[stable(feature = "rust1", since = "1.0.0")]
281 pub struct StdinLock<'a> {
282 inner: MutexGuard<'a, BufReader<Maybe<StdinRaw>>>,
285 /// Constructs a new handle to the standard input of the current process.
287 /// Each handle returned is a reference to a shared global buffer whose access
288 /// is synchronized via a mutex. If you need more explicit control over
289 /// locking, see the [`Stdin::lock`] method.
291 /// [`Stdin::lock`]: struct.Stdin.html#method.lock
293 /// ### Note: Windows Portability Consideration
294 /// When operating in a console, the Windows implementation of this stream does not support
295 /// non-UTF-8 byte sequences. Attempting to read bytes that are not valid UTF-8 will return
300 /// Using implicit synchronization:
303 /// use std::io::{self, Read};
305 /// fn main() -> io::Result<()> {
306 /// let mut buffer = String::new();
307 /// io::stdin().read_to_string(&mut buffer)?;
312 /// Using explicit synchronization:
315 /// use std::io::{self, Read};
317 /// fn main() -> io::Result<()> {
318 /// let mut buffer = String::new();
319 /// let stdin = io::stdin();
320 /// let mut handle = stdin.lock();
322 /// handle.read_to_string(&mut buffer)?;
326 #[stable(feature = "rust1", since = "1.0.0")]
327 pub fn stdin() -> Stdin {
328 static INSTANCE: Lazy<Mutex<BufReader<Maybe<StdinRaw>>>> = Lazy::new();
330 inner: unsafe { INSTANCE.get(stdin_init).expect("cannot access stdin during shutdown") },
333 fn stdin_init() -> Arc<Mutex<BufReader<Maybe<StdinRaw>>>> {
334 // This must not reentrantly access `INSTANCE`
335 let stdin = match stdin_raw() {
336 Ok(stdin) => Maybe::Real(stdin),
340 Arc::new(Mutex::new(BufReader::with_capacity(stdio::STDIN_BUF_SIZE, stdin)))
345 /// Locks this handle to the standard input stream, returning a readable
348 /// The lock is released when the returned lock goes out of scope. The
349 /// returned guard also implements the [`Read`] and [`BufRead`] traits for
350 /// accessing the underlying data.
352 /// [`Read`]: trait.Read.html
353 /// [`BufRead`]: trait.BufRead.html
358 /// use std::io::{self, Read};
360 /// fn main() -> io::Result<()> {
361 /// let mut buffer = String::new();
362 /// let stdin = io::stdin();
363 /// let mut handle = stdin.lock();
365 /// handle.read_to_string(&mut buffer)?;
369 #[stable(feature = "rust1", since = "1.0.0")]
370 pub fn lock(&self) -> StdinLock<'_> {
371 StdinLock { inner: self.inner.lock().unwrap_or_else(|e| e.into_inner()) }
374 /// Locks this handle and reads a line of input, appending it to the specified buffer.
376 /// For detailed semantics of this method, see the documentation on
377 /// [`BufRead::read_line`].
379 /// [`BufRead::read_line`]: trait.BufRead.html#method.read_line
386 /// let mut input = String::new();
387 /// match io::stdin().read_line(&mut input) {
389 /// println!("{} bytes read", n);
390 /// println!("{}", input);
392 /// Err(error) => println!("error: {}", error),
396 /// You can run the example one of two ways:
398 /// - Pipe some text to it, e.g., `printf foo | path/to/executable`
399 /// - Give it text interactively by running the executable directly,
400 /// in which case it will wait for the Enter key to be pressed before
402 #[stable(feature = "rust1", since = "1.0.0")]
403 pub fn read_line(&self, buf: &mut String) -> io::Result<usize> {
404 self.lock().read_line(buf)
408 #[stable(feature = "std_debug", since = "1.16.0")]
409 impl fmt::Debug for Stdin {
410 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
411 f.pad("Stdin { .. }")
415 #[stable(feature = "rust1", since = "1.0.0")]
416 impl Read for Stdin {
417 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
418 self.lock().read(buf)
420 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
421 self.lock().read_vectored(bufs)
424 fn is_read_vectored(&self) -> bool {
425 self.lock().is_read_vectored()
428 unsafe fn initializer(&self) -> Initializer {
431 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
432 self.lock().read_to_end(buf)
434 fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
435 self.lock().read_to_string(buf)
437 fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
438 self.lock().read_exact(buf)
442 #[stable(feature = "rust1", since = "1.0.0")]
443 impl Read for StdinLock<'_> {
444 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
448 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
449 self.inner.read_vectored(bufs)
453 fn is_read_vectored(&self) -> bool {
454 self.inner.is_read_vectored()
458 unsafe fn initializer(&self) -> Initializer {
462 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
463 self.inner.read_to_end(buf)
466 fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
467 self.inner.read_to_string(buf)
470 fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
471 self.inner.read_exact(buf)
475 #[stable(feature = "rust1", since = "1.0.0")]
476 impl BufRead for StdinLock<'_> {
477 fn fill_buf(&mut self) -> io::Result<&[u8]> {
478 self.inner.fill_buf()
481 fn consume(&mut self, n: usize) {
482 self.inner.consume(n)
485 fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> io::Result<usize> {
486 self.inner.read_until(byte, buf)
489 fn read_line(&mut self, buf: &mut String) -> io::Result<usize> {
490 self.inner.read_line(buf)
494 #[stable(feature = "std_debug", since = "1.16.0")]
495 impl fmt::Debug for StdinLock<'_> {
496 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
497 f.pad("StdinLock { .. }")
501 /// A handle to the global standard output stream of the current process.
503 /// Each handle shares a global buffer of data to be written to the standard
504 /// output stream. Access is also synchronized via a lock and explicit control
505 /// over locking is available via the [`lock`] method.
507 /// Created by the [`io::stdout`] method.
509 /// ### Note: Windows Portability Consideration
510 /// When operating in a console, the Windows implementation of this stream does not support
511 /// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
514 /// [`lock`]: #method.lock
515 /// [`io::stdout`]: fn.stdout.html
516 #[stable(feature = "rust1", since = "1.0.0")]
518 // FIXME: this should be LineWriter or BufWriter depending on the state of
519 // stdout (tty or not). Note that if this is not line buffered it
520 // should also flush-on-panic or some form of flush-on-abort.
521 inner: Arc<ReentrantMutex<RefCell<LineWriter<Maybe<StdoutRaw>>>>>,
524 /// A locked reference to the `Stdout` handle.
526 /// This handle implements the [`Write`] trait, and is constructed via
527 /// the [`Stdout::lock`] method.
529 /// ### Note: Windows Portability Consideration
530 /// When operating in a console, the Windows implementation of this stream does not support
531 /// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
534 /// [`Write`]: trait.Write.html
535 /// [`Stdout::lock`]: struct.Stdout.html#method.lock
536 #[stable(feature = "rust1", since = "1.0.0")]
537 pub struct StdoutLock<'a> {
538 inner: ReentrantMutexGuard<'a, RefCell<LineWriter<Maybe<StdoutRaw>>>>,
541 /// Constructs a new handle to the standard output of the current process.
543 /// Each handle returned is a reference to a shared global buffer whose access
544 /// is synchronized via a mutex. If you need more explicit control over
545 /// locking, see the [`Stdout::lock`] method.
547 /// [`Stdout::lock`]: struct.Stdout.html#method.lock
549 /// ### Note: Windows Portability Consideration
550 /// When operating in a console, the Windows implementation of this stream does not support
551 /// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
556 /// Using implicit synchronization:
559 /// use std::io::{self, Write};
561 /// fn main() -> io::Result<()> {
562 /// io::stdout().write_all(b"hello world")?;
568 /// Using explicit synchronization:
571 /// use std::io::{self, Write};
573 /// fn main() -> io::Result<()> {
574 /// let stdout = io::stdout();
575 /// let mut handle = stdout.lock();
577 /// handle.write_all(b"hello world")?;
582 #[stable(feature = "rust1", since = "1.0.0")]
583 pub fn stdout() -> Stdout {
584 static INSTANCE: Lazy<ReentrantMutex<RefCell<LineWriter<Maybe<StdoutRaw>>>>> = Lazy::new();
586 inner: unsafe { INSTANCE.get(stdout_init).expect("cannot access stdout during shutdown") },
589 fn stdout_init() -> Arc<ReentrantMutex<RefCell<LineWriter<Maybe<StdoutRaw>>>>> {
590 // This must not reentrantly access `INSTANCE`
591 let stdout = match stdout_raw() {
592 Ok(stdout) => Maybe::Real(stdout),
596 let ret = Arc::new(ReentrantMutex::new(RefCell::new(LineWriter::new(stdout))));
604 /// Locks this handle to the standard output stream, returning a writable
607 /// The lock is released when the returned lock goes out of scope. The
608 /// returned guard also implements the `Write` trait for writing data.
613 /// use std::io::{self, Write};
615 /// fn main() -> io::Result<()> {
616 /// let stdout = io::stdout();
617 /// let mut handle = stdout.lock();
619 /// handle.write_all(b"hello world")?;
624 #[stable(feature = "rust1", since = "1.0.0")]
625 pub fn lock(&self) -> StdoutLock<'_> {
626 StdoutLock { inner: self.inner.lock() }
630 #[stable(feature = "std_debug", since = "1.16.0")]
631 impl fmt::Debug for Stdout {
632 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
633 f.pad("Stdout { .. }")
637 #[stable(feature = "rust1", since = "1.0.0")]
638 impl Write for Stdout {
639 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
640 self.lock().write(buf)
642 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
643 self.lock().write_vectored(bufs)
646 fn is_write_vectored(&self) -> bool {
647 self.lock().is_write_vectored()
649 fn flush(&mut self) -> io::Result<()> {
652 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
653 self.lock().write_all(buf)
655 fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> {
656 self.lock().write_all_vectored(bufs)
658 fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> io::Result<()> {
659 self.lock().write_fmt(args)
662 #[stable(feature = "rust1", since = "1.0.0")]
663 impl Write for StdoutLock<'_> {
664 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
665 self.inner.borrow_mut().write(buf)
667 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
668 self.inner.borrow_mut().write_vectored(bufs)
671 fn is_write_vectored(&self) -> bool {
672 self.inner.borrow_mut().is_write_vectored()
674 fn flush(&mut self) -> io::Result<()> {
675 self.inner.borrow_mut().flush()
677 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
678 self.inner.borrow_mut().write_all(buf)
680 fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> {
681 self.inner.borrow_mut().write_all_vectored(bufs)
685 #[stable(feature = "std_debug", since = "1.16.0")]
686 impl fmt::Debug for StdoutLock<'_> {
687 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
688 f.pad("StdoutLock { .. }")
692 /// A handle to the standard error stream of a process.
694 /// For more information, see the [`io::stderr`] method.
696 /// [`io::stderr`]: fn.stderr.html
698 /// ### Note: Windows Portability Consideration
699 /// When operating in a console, the Windows implementation of this stream does not support
700 /// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
702 #[stable(feature = "rust1", since = "1.0.0")]
704 inner: &'static ReentrantMutex<RefCell<Maybe<StderrRaw>>>,
707 /// A locked reference to the `Stderr` handle.
709 /// This handle implements the `Write` trait and is constructed via
710 /// the [`Stderr::lock`] method.
712 /// [`Stderr::lock`]: struct.Stderr.html#method.lock
714 /// ### Note: Windows Portability Consideration
715 /// When operating in a console, the Windows implementation of this stream does not support
716 /// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
718 #[stable(feature = "rust1", since = "1.0.0")]
719 pub struct StderrLock<'a> {
720 inner: ReentrantMutexGuard<'a, RefCell<Maybe<StderrRaw>>>,
723 /// Constructs a new handle to the standard error of the current process.
725 /// This handle is not buffered.
727 /// ### Note: Windows Portability Consideration
728 /// When operating in a console, the Windows implementation of this stream does not support
729 /// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
734 /// Using implicit synchronization:
737 /// use std::io::{self, Write};
739 /// fn main() -> io::Result<()> {
740 /// io::stderr().write_all(b"hello world")?;
746 /// Using explicit synchronization:
749 /// use std::io::{self, Write};
751 /// fn main() -> io::Result<()> {
752 /// let stderr = io::stderr();
753 /// let mut handle = stderr.lock();
755 /// handle.write_all(b"hello world")?;
760 #[stable(feature = "rust1", since = "1.0.0")]
761 pub fn stderr() -> Stderr {
762 // Note that unlike `stdout()` we don't use `Lazy` here which registers a
763 // destructor. Stderr is not buffered nor does the `stderr_raw` type consume
764 // any owned resources, so there's no need to run any destructors at some
765 // point in the future.
767 // This has the added benefit of allowing `stderr` to be usable during
768 // process shutdown as well!
769 static INSTANCE: ReentrantMutex<RefCell<Maybe<StderrRaw>>> =
770 unsafe { ReentrantMutex::new(RefCell::new(Maybe::Fake)) };
772 // When accessing stderr we need one-time initialization of the reentrant
773 // mutex, followed by one-time detection of whether we actually have a
774 // stderr handle or not. Afterwards we can just always use the now-filled-in
776 static INIT: Once = Once::new();
777 INIT.call_once(|| unsafe {
779 if let Ok(stderr) = stderr_raw() {
780 *INSTANCE.lock().borrow_mut() = Maybe::Real(stderr);
783 Stderr { inner: &INSTANCE }
787 /// Locks this handle to the standard error stream, returning a writable
790 /// The lock is released when the returned lock goes out of scope. The
791 /// returned guard also implements the `Write` trait for writing data.
796 /// use std::io::{self, Write};
798 /// fn foo() -> io::Result<()> {
799 /// let stderr = io::stderr();
800 /// let mut handle = stderr.lock();
802 /// handle.write_all(b"hello world")?;
807 #[stable(feature = "rust1", since = "1.0.0")]
808 pub fn lock(&self) -> StderrLock<'_> {
809 StderrLock { inner: self.inner.lock() }
813 #[stable(feature = "std_debug", since = "1.16.0")]
814 impl fmt::Debug for Stderr {
815 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
816 f.pad("Stderr { .. }")
820 #[stable(feature = "rust1", since = "1.0.0")]
821 impl Write for Stderr {
822 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
823 self.lock().write(buf)
825 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
826 self.lock().write_vectored(bufs)
829 fn is_write_vectored(&self) -> bool {
830 self.lock().is_write_vectored()
832 fn flush(&mut self) -> io::Result<()> {
835 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
836 self.lock().write_all(buf)
838 fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> {
839 self.lock().write_all_vectored(bufs)
841 fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> io::Result<()> {
842 self.lock().write_fmt(args)
845 #[stable(feature = "rust1", since = "1.0.0")]
846 impl Write for StderrLock<'_> {
847 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
848 self.inner.borrow_mut().write(buf)
850 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
851 self.inner.borrow_mut().write_vectored(bufs)
854 fn is_write_vectored(&self) -> bool {
855 self.inner.borrow_mut().is_write_vectored()
857 fn flush(&mut self) -> io::Result<()> {
858 self.inner.borrow_mut().flush()
860 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
861 self.inner.borrow_mut().write_all(buf)
863 fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> {
864 self.inner.borrow_mut().write_all_vectored(bufs)
868 #[stable(feature = "std_debug", since = "1.16.0")]
869 impl fmt::Debug for StderrLock<'_> {
870 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
871 f.pad("StderrLock { .. }")
875 /// Resets the thread-local stderr handle to the specified writer
877 /// This will replace the current thread's stderr handle, returning the old
878 /// handle. All future calls to `panic!` and friends will emit their output to
879 /// this specified handle.
881 /// Note that this does not need to be called for all new threads; the default
882 /// output handle is to the process's stderr stream.
884 feature = "set_stdio",
885 reason = "this function may disappear completely or be replaced \
886 with a more general mechanism",
890 pub fn set_panic(sink: Option<Box<dyn Write + Send>>) -> Option<Box<dyn Write + Send>> {
892 LOCAL_STDERR.with(move |slot| mem::replace(&mut *slot.borrow_mut(), sink)).and_then(|mut s| {
898 /// Resets the thread-local stdout handle to the specified writer
900 /// This will replace the current thread's stdout handle, returning the old
901 /// handle. All future calls to `print!` and friends will emit their output to
902 /// this specified handle.
904 /// Note that this does not need to be called for all new threads; the default
905 /// output handle is to the process's stdout stream.
907 feature = "set_stdio",
908 reason = "this function may disappear completely or be replaced \
909 with a more general mechanism",
913 pub fn set_print(sink: Option<Box<dyn Write + Send>>) -> Option<Box<dyn Write + Send>> {
915 LOCAL_STDOUT.with(move |slot| mem::replace(&mut *slot.borrow_mut(), sink)).and_then(|mut s| {
921 /// Write `args` to output stream `local_s` if possible, `global_s`
922 /// otherwise. `label` identifies the stream in a panic message.
924 /// This function is used to print error messages, so it takes extra
925 /// care to avoid causing a panic when `local_s` is unusable.
926 /// For instance, if the TLS key for the local stream is
927 /// already destroyed, or if the local stream is locked by another
928 /// thread, it will just fall back to the global stream.
930 /// However, if the actual I/O causes an error, this function does panic.
932 args: fmt::Arguments<'_>,
933 local_s: &'static LocalKey<RefCell<Option<Box<dyn Write + Send>>>>,
941 // Note that we completely remove a local sink to write to in case
942 // our printing recursively panics/prints, so the recursive
943 // panic/print goes to the global sink instead of our local sink.
944 let prev = s.borrow_mut().take();
945 if let Some(mut w) = prev {
946 let result = w.write_fmt(args);
947 *s.borrow_mut() = Some(w);
950 global_s().write_fmt(args)
952 .unwrap_or_else(|_| global_s().write_fmt(args));
954 if let Err(e) = result {
955 panic!("failed printing to {}: {}", label, e);
960 feature = "print_internals",
961 reason = "implementation detail which may disappear or be replaced at any time",
966 pub fn _print(args: fmt::Arguments<'_>) {
967 print_to(args, &LOCAL_STDOUT, stdout, "stdout");
971 feature = "print_internals",
972 reason = "implementation detail which may disappear or be replaced at any time",
977 pub fn _eprint(args: fmt::Arguments<'_>) {
978 print_to(args, &LOCAL_STDERR, stderr, "stderr");
982 pub use realstd::io::{_eprint, _print};
987 use crate::panic::{RefUnwindSafe, UnwindSafe};
991 fn stdout_unwind_safe() {
992 assert_unwind_safe::<Stdout>();
995 fn stdoutlock_unwind_safe() {
996 assert_unwind_safe::<StdoutLock<'_>>();
997 assert_unwind_safe::<StdoutLock<'static>>();
1000 fn stderr_unwind_safe() {
1001 assert_unwind_safe::<Stderr>();
1004 fn stderrlock_unwind_safe() {
1005 assert_unwind_safe::<StderrLock<'_>>();
1006 assert_unwind_safe::<StderrLock<'static>>();
1009 fn assert_unwind_safe<T: UnwindSafe + RefUnwindSafe>() {}
1012 #[cfg_attr(target_os = "emscripten", ignore)]
1013 fn panic_doesnt_poison() {