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`]: stdin
257 /// ### 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
266 /// use std::io::{self, Read};
268 /// fn main() -> io::Result<()> {
269 /// let mut buffer = String::new();
270 /// let mut stdin = io::stdin(); // We get `Stdin` here.
271 /// stdin.read_to_string(&mut buffer)?;
275 #[stable(feature = "rust1", since = "1.0.0")]
277 inner: Arc<Mutex<BufReader<Maybe<StdinRaw>>>>,
280 /// A locked reference to the `Stdin` handle.
282 /// This handle implements both the [`Read`] and [`BufRead`] traits, and
283 /// is constructed via the [`Stdin::lock`] method.
285 /// ### Note: Windows Portability Consideration
287 /// When operating in a console, the Windows implementation of this stream does not support
288 /// non-UTF-8 byte sequences. Attempting to read bytes that are not valid UTF-8 will return
294 /// use std::io::{self, Read};
296 /// fn main() -> io::Result<()> {
297 /// let mut buffer = String::new();
298 /// let stdin = io::stdin(); // We get `Stdin` here.
300 /// let mut stdin_lock = stdin.lock(); // We get `StdinLock` here.
301 /// stdin_lock.read_to_string(&mut buffer)?;
302 /// } // `StdinLock` is dropped here.
306 #[stable(feature = "rust1", since = "1.0.0")]
307 pub struct StdinLock<'a> {
308 inner: MutexGuard<'a, BufReader<Maybe<StdinRaw>>>,
311 /// Constructs a new handle to the standard input of the current process.
313 /// Each handle returned is a reference to a shared global buffer whose access
314 /// is synchronized via a mutex. If you need more explicit control over
315 /// locking, see the [`Stdin::lock`] method.
317 /// ### Note: Windows Portability Consideration
318 /// When operating in a console, the Windows implementation of this stream does not support
319 /// non-UTF-8 byte sequences. Attempting to read bytes that are not valid UTF-8 will return
324 /// Using implicit synchronization:
327 /// use std::io::{self, Read};
329 /// fn main() -> io::Result<()> {
330 /// let mut buffer = String::new();
331 /// io::stdin().read_to_string(&mut buffer)?;
336 /// Using explicit synchronization:
339 /// use std::io::{self, Read};
341 /// fn main() -> io::Result<()> {
342 /// let mut buffer = String::new();
343 /// let stdin = io::stdin();
344 /// let mut handle = stdin.lock();
346 /// handle.read_to_string(&mut buffer)?;
350 #[stable(feature = "rust1", since = "1.0.0")]
351 pub fn stdin() -> Stdin {
352 static INSTANCE: Lazy<Mutex<BufReader<Maybe<StdinRaw>>>> = Lazy::new();
354 inner: unsafe { INSTANCE.get(stdin_init).expect("cannot access stdin during shutdown") },
357 fn stdin_init() -> Arc<Mutex<BufReader<Maybe<StdinRaw>>>> {
358 // This must not reentrantly access `INSTANCE`
359 let stdin = match stdin_raw() {
360 Ok(stdin) => Maybe::Real(stdin),
364 Arc::new(Mutex::new(BufReader::with_capacity(stdio::STDIN_BUF_SIZE, stdin)))
369 /// Locks this handle to the standard input stream, returning a readable
372 /// The lock is released when the returned lock goes out of scope. The
373 /// returned guard also implements the [`Read`] and [`BufRead`] traits for
374 /// accessing the underlying data.
379 /// use std::io::{self, Read};
381 /// fn main() -> io::Result<()> {
382 /// let mut buffer = String::new();
383 /// let stdin = io::stdin();
384 /// let mut handle = stdin.lock();
386 /// handle.read_to_string(&mut buffer)?;
390 #[stable(feature = "rust1", since = "1.0.0")]
391 pub fn lock(&self) -> StdinLock<'_> {
392 StdinLock { inner: self.inner.lock().unwrap_or_else(|e| e.into_inner()) }
395 /// Locks this handle and reads a line of input, appending it to the specified buffer.
397 /// For detailed semantics of this method, see the documentation on
398 /// [`BufRead::read_line`].
405 /// let mut input = String::new();
406 /// match io::stdin().read_line(&mut input) {
408 /// println!("{} bytes read", n);
409 /// println!("{}", input);
411 /// Err(error) => println!("error: {}", error),
415 /// You can run the example one of two ways:
417 /// - Pipe some text to it, e.g., `printf foo | path/to/executable`
418 /// - Give it text interactively by running the executable directly,
419 /// in which case it will wait for the Enter key to be pressed before
421 #[stable(feature = "rust1", since = "1.0.0")]
422 pub fn read_line(&self, buf: &mut String) -> io::Result<usize> {
423 self.lock().read_line(buf)
427 #[stable(feature = "std_debug", since = "1.16.0")]
428 impl fmt::Debug for Stdin {
429 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
430 f.pad("Stdin { .. }")
434 #[stable(feature = "rust1", since = "1.0.0")]
435 impl Read for Stdin {
436 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
437 self.lock().read(buf)
439 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
440 self.lock().read_vectored(bufs)
443 fn is_read_vectored(&self) -> bool {
444 self.lock().is_read_vectored()
447 unsafe fn initializer(&self) -> Initializer {
450 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
451 self.lock().read_to_end(buf)
453 fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
454 self.lock().read_to_string(buf)
456 fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
457 self.lock().read_exact(buf)
461 #[stable(feature = "rust1", since = "1.0.0")]
462 impl Read for StdinLock<'_> {
463 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
467 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
468 self.inner.read_vectored(bufs)
472 fn is_read_vectored(&self) -> bool {
473 self.inner.is_read_vectored()
477 unsafe fn initializer(&self) -> Initializer {
481 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
482 self.inner.read_to_end(buf)
485 fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
486 self.inner.read_to_string(buf)
489 fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
490 self.inner.read_exact(buf)
494 #[stable(feature = "rust1", since = "1.0.0")]
495 impl BufRead for StdinLock<'_> {
496 fn fill_buf(&mut self) -> io::Result<&[u8]> {
497 self.inner.fill_buf()
500 fn consume(&mut self, n: usize) {
501 self.inner.consume(n)
504 fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> io::Result<usize> {
505 self.inner.read_until(byte, buf)
508 fn read_line(&mut self, buf: &mut String) -> io::Result<usize> {
509 self.inner.read_line(buf)
513 #[stable(feature = "std_debug", since = "1.16.0")]
514 impl fmt::Debug for StdinLock<'_> {
515 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
516 f.pad("StdinLock { .. }")
520 /// A handle to the global standard output stream of the current process.
522 /// Each handle shares a global buffer of data to be written to the standard
523 /// output stream. Access is also synchronized via a lock and explicit control
524 /// over locking is available via the [`lock`] method.
526 /// Created by the [`io::stdout`] method.
528 /// ### Note: Windows Portability Consideration
529 /// When operating in a console, the Windows implementation of this stream does not support
530 /// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
533 /// [`lock`]: Stdout::lock
534 /// [`io::stdout`]: stdout
535 #[stable(feature = "rust1", since = "1.0.0")]
537 // FIXME: this should be LineWriter or BufWriter depending on the state of
538 // stdout (tty or not). Note that if this is not line buffered it
539 // should also flush-on-panic or some form of flush-on-abort.
540 inner: Arc<ReentrantMutex<RefCell<LineWriter<Maybe<StdoutRaw>>>>>,
543 /// A locked reference to the `Stdout` handle.
545 /// This handle implements the [`Write`] trait, and is constructed via
546 /// the [`Stdout::lock`] method.
548 /// ### Note: Windows Portability Consideration
549 /// When operating in a console, the Windows implementation of this stream does not support
550 /// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
552 #[stable(feature = "rust1", since = "1.0.0")]
553 pub struct StdoutLock<'a> {
554 inner: ReentrantMutexGuard<'a, RefCell<LineWriter<Maybe<StdoutRaw>>>>,
557 /// Constructs a new handle to the standard output of the current process.
559 /// Each handle returned is a reference to a shared global buffer whose access
560 /// is synchronized via a mutex. If you need more explicit control over
561 /// locking, see the [`Stdout::lock`] method.
563 /// ### Note: Windows Portability Consideration
564 /// When operating in a console, the Windows implementation of this stream does not support
565 /// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
570 /// Using implicit synchronization:
573 /// use std::io::{self, Write};
575 /// fn main() -> io::Result<()> {
576 /// io::stdout().write_all(b"hello world")?;
582 /// Using explicit synchronization:
585 /// use std::io::{self, Write};
587 /// fn main() -> io::Result<()> {
588 /// let stdout = io::stdout();
589 /// let mut handle = stdout.lock();
591 /// handle.write_all(b"hello world")?;
596 #[stable(feature = "rust1", since = "1.0.0")]
597 pub fn stdout() -> Stdout {
598 static INSTANCE: Lazy<ReentrantMutex<RefCell<LineWriter<Maybe<StdoutRaw>>>>> = Lazy::new();
600 inner: unsafe { INSTANCE.get(stdout_init).expect("cannot access stdout during shutdown") },
603 fn stdout_init() -> Arc<ReentrantMutex<RefCell<LineWriter<Maybe<StdoutRaw>>>>> {
604 // This must not reentrantly access `INSTANCE`
605 let stdout = match stdout_raw() {
606 Ok(stdout) => Maybe::Real(stdout),
610 let ret = Arc::new(ReentrantMutex::new(RefCell::new(LineWriter::new(stdout))));
618 /// Locks this handle to the standard output stream, returning a writable
621 /// The lock is released when the returned lock goes out of scope. The
622 /// returned guard also implements the `Write` trait for writing data.
627 /// use std::io::{self, Write};
629 /// fn main() -> io::Result<()> {
630 /// let stdout = io::stdout();
631 /// let mut handle = stdout.lock();
633 /// handle.write_all(b"hello world")?;
638 #[stable(feature = "rust1", since = "1.0.0")]
639 pub fn lock(&self) -> StdoutLock<'_> {
640 StdoutLock { inner: self.inner.lock() }
644 #[stable(feature = "std_debug", since = "1.16.0")]
645 impl fmt::Debug for Stdout {
646 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
647 f.pad("Stdout { .. }")
651 #[stable(feature = "rust1", since = "1.0.0")]
652 impl Write for Stdout {
653 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
654 self.lock().write(buf)
656 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
657 self.lock().write_vectored(bufs)
660 fn is_write_vectored(&self) -> bool {
661 self.lock().is_write_vectored()
663 fn flush(&mut self) -> io::Result<()> {
666 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
667 self.lock().write_all(buf)
669 fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> {
670 self.lock().write_all_vectored(bufs)
672 fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> io::Result<()> {
673 self.lock().write_fmt(args)
676 #[stable(feature = "rust1", since = "1.0.0")]
677 impl Write for StdoutLock<'_> {
678 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
679 self.inner.borrow_mut().write(buf)
681 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
682 self.inner.borrow_mut().write_vectored(bufs)
685 fn is_write_vectored(&self) -> bool {
686 self.inner.borrow_mut().is_write_vectored()
688 fn flush(&mut self) -> io::Result<()> {
689 self.inner.borrow_mut().flush()
691 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
692 self.inner.borrow_mut().write_all(buf)
694 fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> {
695 self.inner.borrow_mut().write_all_vectored(bufs)
699 #[stable(feature = "std_debug", since = "1.16.0")]
700 impl fmt::Debug for StdoutLock<'_> {
701 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
702 f.pad("StdoutLock { .. }")
706 /// A handle to the standard error stream of a process.
708 /// For more information, see the [`io::stderr`] method.
710 /// [`io::stderr`]: stderr
712 /// ### Note: Windows Portability Consideration
713 /// When operating in a console, the Windows implementation of this stream does not support
714 /// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
716 #[stable(feature = "rust1", since = "1.0.0")]
718 inner: &'static ReentrantMutex<RefCell<Maybe<StderrRaw>>>,
721 /// A locked reference to the `Stderr` handle.
723 /// This handle implements the `Write` trait and is constructed via
724 /// the [`Stderr::lock`] method.
726 /// ### Note: Windows Portability Consideration
727 /// When operating in a console, the Windows implementation of this stream does not support
728 /// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
730 #[stable(feature = "rust1", since = "1.0.0")]
731 pub struct StderrLock<'a> {
732 inner: ReentrantMutexGuard<'a, RefCell<Maybe<StderrRaw>>>,
735 /// Constructs a new handle to the standard error of the current process.
737 /// This handle is not buffered.
739 /// ### Note: Windows Portability Consideration
740 /// When operating in a console, the Windows implementation of this stream does not support
741 /// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
746 /// Using implicit synchronization:
749 /// use std::io::{self, Write};
751 /// fn main() -> io::Result<()> {
752 /// io::stderr().write_all(b"hello world")?;
758 /// Using explicit synchronization:
761 /// use std::io::{self, Write};
763 /// fn main() -> io::Result<()> {
764 /// let stderr = io::stderr();
765 /// let mut handle = stderr.lock();
767 /// handle.write_all(b"hello world")?;
772 #[stable(feature = "rust1", since = "1.0.0")]
773 pub fn stderr() -> Stderr {
774 // Note that unlike `stdout()` we don't use `Lazy` here which registers a
775 // destructor. Stderr is not buffered nor does the `stderr_raw` type consume
776 // any owned resources, so there's no need to run any destructors at some
777 // point in the future.
779 // This has the added benefit of allowing `stderr` to be usable during
780 // process shutdown as well!
781 static INSTANCE: ReentrantMutex<RefCell<Maybe<StderrRaw>>> =
782 unsafe { ReentrantMutex::new(RefCell::new(Maybe::Fake)) };
784 // When accessing stderr we need one-time initialization of the reentrant
785 // mutex, followed by one-time detection of whether we actually have a
786 // stderr handle or not. Afterwards we can just always use the now-filled-in
788 static INIT: Once = Once::new();
789 INIT.call_once(|| unsafe {
791 if let Ok(stderr) = stderr_raw() {
792 *INSTANCE.lock().borrow_mut() = Maybe::Real(stderr);
795 Stderr { inner: &INSTANCE }
799 /// Locks this handle to the standard error stream, returning a writable
802 /// The lock is released when the returned lock goes out of scope. The
803 /// returned guard also implements the [`Write`] trait for writing data.
808 /// use std::io::{self, Write};
810 /// fn foo() -> io::Result<()> {
811 /// let stderr = io::stderr();
812 /// let mut handle = stderr.lock();
814 /// handle.write_all(b"hello world")?;
819 #[stable(feature = "rust1", since = "1.0.0")]
820 pub fn lock(&self) -> StderrLock<'_> {
821 StderrLock { inner: self.inner.lock() }
825 #[stable(feature = "std_debug", since = "1.16.0")]
826 impl fmt::Debug for Stderr {
827 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
828 f.pad("Stderr { .. }")
832 #[stable(feature = "rust1", since = "1.0.0")]
833 impl Write for Stderr {
834 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
835 self.lock().write(buf)
837 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
838 self.lock().write_vectored(bufs)
841 fn is_write_vectored(&self) -> bool {
842 self.lock().is_write_vectored()
844 fn flush(&mut self) -> io::Result<()> {
847 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
848 self.lock().write_all(buf)
850 fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> {
851 self.lock().write_all_vectored(bufs)
853 fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> io::Result<()> {
854 self.lock().write_fmt(args)
857 #[stable(feature = "rust1", since = "1.0.0")]
858 impl Write for StderrLock<'_> {
859 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
860 self.inner.borrow_mut().write(buf)
862 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
863 self.inner.borrow_mut().write_vectored(bufs)
866 fn is_write_vectored(&self) -> bool {
867 self.inner.borrow_mut().is_write_vectored()
869 fn flush(&mut self) -> io::Result<()> {
870 self.inner.borrow_mut().flush()
872 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
873 self.inner.borrow_mut().write_all(buf)
875 fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> {
876 self.inner.borrow_mut().write_all_vectored(bufs)
880 #[stable(feature = "std_debug", since = "1.16.0")]
881 impl fmt::Debug for StderrLock<'_> {
882 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
883 f.pad("StderrLock { .. }")
887 /// Resets the thread-local stderr handle to the specified writer
889 /// This will replace the current thread's stderr handle, returning the old
890 /// handle. All future calls to `panic!` and friends will emit their output to
891 /// this specified handle.
893 /// Note that this does not need to be called for all new threads; the default
894 /// output handle is to the process's stderr stream.
896 feature = "set_stdio",
897 reason = "this function may disappear completely or be replaced \
898 with a more general mechanism",
902 pub fn set_panic(sink: Option<Box<dyn Write + Send>>) -> Option<Box<dyn Write + Send>> {
904 LOCAL_STDERR.with(move |slot| mem::replace(&mut *slot.borrow_mut(), sink)).and_then(|mut s| {
910 /// Resets the thread-local stdout handle to the specified writer
912 /// This will replace the current thread's stdout handle, returning the old
913 /// handle. All future calls to `print!` and friends will emit their output to
914 /// this specified handle.
916 /// Note that this does not need to be called for all new threads; the default
917 /// output handle is to the process's stdout stream.
919 feature = "set_stdio",
920 reason = "this function may disappear completely or be replaced \
921 with a more general mechanism",
925 pub fn set_print(sink: Option<Box<dyn Write + Send>>) -> Option<Box<dyn Write + Send>> {
927 LOCAL_STDOUT.with(move |slot| mem::replace(&mut *slot.borrow_mut(), sink)).and_then(|mut s| {
933 /// Write `args` to output stream `local_s` if possible, `global_s`
934 /// otherwise. `label` identifies the stream in a panic message.
936 /// This function is used to print error messages, so it takes extra
937 /// care to avoid causing a panic when `local_s` is unusable.
938 /// For instance, if the TLS key for the local stream is
939 /// already destroyed, or if the local stream is locked by another
940 /// thread, it will just fall back to the global stream.
942 /// However, if the actual I/O causes an error, this function does panic.
944 args: fmt::Arguments<'_>,
945 local_s: &'static LocalKey<RefCell<Option<Box<dyn Write + Send>>>>,
953 // Note that we completely remove a local sink to write to in case
954 // our printing recursively panics/prints, so the recursive
955 // panic/print goes to the global sink instead of our local sink.
956 let prev = s.borrow_mut().take();
957 if let Some(mut w) = prev {
958 let result = w.write_fmt(args);
959 *s.borrow_mut() = Some(w);
962 global_s().write_fmt(args)
964 .unwrap_or_else(|_| global_s().write_fmt(args));
966 if let Err(e) = result {
967 panic!("failed printing to {}: {}", label, e);
972 feature = "print_internals",
973 reason = "implementation detail which may disappear or be replaced at any time",
978 pub fn _print(args: fmt::Arguments<'_>) {
979 print_to(args, &LOCAL_STDOUT, stdout, "stdout");
983 feature = "print_internals",
984 reason = "implementation detail which may disappear or be replaced at any time",
989 pub fn _eprint(args: fmt::Arguments<'_>) {
990 print_to(args, &LOCAL_STDERR, stderr, "stderr");
994 pub use realstd::io::{_eprint, _print};
999 use crate::panic::{RefUnwindSafe, UnwindSafe};
1003 fn stdout_unwind_safe() {
1004 assert_unwind_safe::<Stdout>();
1007 fn stdoutlock_unwind_safe() {
1008 assert_unwind_safe::<StdoutLock<'_>>();
1009 assert_unwind_safe::<StdoutLock<'static>>();
1012 fn stderr_unwind_safe() {
1013 assert_unwind_safe::<Stderr>();
1016 fn stderrlock_unwind_safe() {
1017 assert_unwind_safe::<StderrLock<'_>>();
1018 assert_unwind_safe::<StderrLock<'static>>();
1021 fn assert_unwind_safe<T: UnwindSafe + RefUnwindSafe>() {}
1024 #[cfg_attr(target_os = "emscripten", ignore)]
1025 fn panic_doesnt_poison() {