1 #![cfg_attr(test, allow(unused))]
6 use crate::io::prelude::*;
8 use crate::cell::{Cell, RefCell};
10 use crate::io::{self, BufReader, IoSlice, IoSliceMut, LineWriter, Lines};
11 use crate::lazy::SyncOnceCell;
13 use crate::sync::atomic::{AtomicBool, Ordering};
14 use crate::sync::{Arc, Mutex, MutexGuard};
15 use crate::sys::stdio;
16 use crate::sys_common::remutex::{ReentrantMutex, ReentrantMutexGuard};
18 type LocalStream = Arc<Mutex<Vec<u8>>>;
21 /// Used by the test crate to capture the output of the print macros and panics.
22 static OUTPUT_CAPTURE: Cell<Option<LocalStream>> = {
27 /// Flag to indicate OUTPUT_CAPTURE is used.
29 /// If it is None and was never set on any thread, this flag is set to false,
30 /// and OUTPUT_CAPTURE can be safely ignored on all threads, saving some time
31 /// and memory registering an unused thread local.
33 /// Note about memory ordering: This contains information about whether a
34 /// thread local variable might be in use. Although this is a global flag, the
35 /// memory ordering between threads does not matter: we only want this flag to
36 /// have a consistent order between set_output_capture and print_to *within
37 /// the same thread*. Within the same thread, things always have a perfectly
38 /// consistent order. So Ordering::Relaxed is fine.
39 static OUTPUT_CAPTURE_USED: AtomicBool = AtomicBool::new(false);
41 /// A handle to a raw instance of the standard input stream of this process.
43 /// This handle is not synchronized or buffered in any fashion. Constructed via
44 /// the `std::io::stdio::stdin_raw` function.
45 struct StdinRaw(stdio::Stdin);
47 /// A handle to a raw instance of the standard output stream of this process.
49 /// This handle is not synchronized or buffered in any fashion. Constructed via
50 /// the `std::io::stdio::stdout_raw` function.
51 struct StdoutRaw(stdio::Stdout);
53 /// A handle to a raw instance of the standard output stream of this process.
55 /// This handle is not synchronized or buffered in any fashion. Constructed via
56 /// the `std::io::stdio::stderr_raw` function.
57 struct StderrRaw(stdio::Stderr);
59 /// Constructs a new raw handle to the standard input of this process.
61 /// The returned handle does not interact with any other handles created nor
62 /// handles returned by `std::io::stdin`. Data buffered by the `std::io::stdin`
63 /// handles is **not** available to raw handles returned from this function.
65 /// The returned handle has no external synchronization or buffering.
66 #[unstable(feature = "libstd_sys_internals", issue = "none")]
67 const fn stdin_raw() -> StdinRaw {
68 StdinRaw(stdio::Stdin::new())
71 /// Constructs a new raw handle to the standard output stream of this process.
73 /// The returned handle does not interact with any other handles created nor
74 /// handles returned by `std::io::stdout`. Note that data is buffered by the
75 /// `std::io::stdout` handles so writes which happen via this raw handle may
76 /// appear before previous writes.
78 /// The returned handle has no external synchronization or buffering layered on
80 #[unstable(feature = "libstd_sys_internals", issue = "none")]
81 const fn stdout_raw() -> StdoutRaw {
82 StdoutRaw(stdio::Stdout::new())
85 /// Constructs a new raw handle to the standard error stream of this process.
87 /// The returned handle does not interact with any other handles created nor
88 /// handles returned by `std::io::stderr`.
90 /// The returned handle has no external synchronization or buffering layered on
92 #[unstable(feature = "libstd_sys_internals", issue = "none")]
93 const fn stderr_raw() -> StderrRaw {
94 StderrRaw(stdio::Stderr::new())
97 impl Read for StdinRaw {
98 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
99 handle_ebadf(self.0.read(buf), 0)
102 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
103 handle_ebadf(self.0.read_vectored(bufs), 0)
107 fn is_read_vectored(&self) -> bool {
108 self.0.is_read_vectored()
111 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
112 handle_ebadf(self.0.read_to_end(buf), 0)
115 fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
116 handle_ebadf(self.0.read_to_string(buf), 0)
120 impl Write for StdoutRaw {
121 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
122 handle_ebadf(self.0.write(buf), buf.len())
125 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
126 let total = bufs.iter().map(|b| b.len()).sum();
127 handle_ebadf(self.0.write_vectored(bufs), total)
131 fn is_write_vectored(&self) -> bool {
132 self.0.is_write_vectored()
135 fn flush(&mut self) -> io::Result<()> {
136 handle_ebadf(self.0.flush(), ())
139 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
140 handle_ebadf(self.0.write_all(buf), ())
143 fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> {
144 handle_ebadf(self.0.write_all_vectored(bufs), ())
147 fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> io::Result<()> {
148 handle_ebadf(self.0.write_fmt(fmt), ())
152 impl Write for StderrRaw {
153 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
154 handle_ebadf(self.0.write(buf), buf.len())
157 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
158 let total = bufs.iter().map(|b| b.len()).sum();
159 handle_ebadf(self.0.write_vectored(bufs), total)
163 fn is_write_vectored(&self) -> bool {
164 self.0.is_write_vectored()
167 fn flush(&mut self) -> io::Result<()> {
168 handle_ebadf(self.0.flush(), ())
171 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
172 handle_ebadf(self.0.write_all(buf), ())
175 fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> {
176 handle_ebadf(self.0.write_all_vectored(bufs), ())
179 fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> io::Result<()> {
180 handle_ebadf(self.0.write_fmt(fmt), ())
184 fn handle_ebadf<T>(r: io::Result<T>, default: T) -> io::Result<T> {
186 Err(ref e) if stdio::is_ebadf(e) => Ok(default),
191 /// A handle to the standard input stream of a process.
193 /// Each handle is a shared reference to a global buffer of input data to this
194 /// process. A handle can be `lock`'d to gain full access to [`BufRead`] methods
195 /// (e.g., `.lines()`). Reads to this handle are otherwise locked with respect
198 /// This handle implements the `Read` trait, but beware that concurrent reads
199 /// of `Stdin` must be executed with care.
201 /// Created by the [`io::stdin`] method.
203 /// [`io::stdin`]: stdin
205 /// ### Note: Windows Portability Consideration
207 /// When operating in a console, the Windows implementation of this stream does not support
208 /// non-UTF-8 byte sequences. Attempting to read bytes that are not valid UTF-8 will return
216 /// fn main() -> io::Result<()> {
217 /// let mut buffer = String::new();
218 /// let mut stdin = io::stdin(); // We get `Stdin` here.
219 /// stdin.read_line(&mut buffer)?;
223 #[stable(feature = "rust1", since = "1.0.0")]
225 inner: &'static Mutex<BufReader<StdinRaw>>,
228 /// A locked reference to the [`Stdin`] handle.
230 /// This handle implements both the [`Read`] and [`BufRead`] traits, and
231 /// is constructed via the [`Stdin::lock`] method.
233 /// ### Note: Windows Portability Consideration
235 /// When operating in a console, the Windows implementation of this stream does not support
236 /// non-UTF-8 byte sequences. Attempting to read bytes that are not valid UTF-8 will return
242 /// use std::io::{self, BufRead};
244 /// fn main() -> io::Result<()> {
245 /// let mut buffer = String::new();
246 /// let stdin = io::stdin(); // We get `Stdin` here.
248 /// let mut handle = stdin.lock(); // We get `StdinLock` here.
249 /// handle.read_line(&mut buffer)?;
250 /// } // `StdinLock` is dropped here.
254 #[must_use = "if unused stdin will immediately unlock"]
255 #[stable(feature = "rust1", since = "1.0.0")]
256 pub struct StdinLock<'a> {
257 inner: MutexGuard<'a, BufReader<StdinRaw>>,
260 /// Constructs a new handle to the standard input of the current process.
262 /// Each handle returned is a reference to a shared global buffer whose access
263 /// is synchronized via a mutex. If you need more explicit control over
264 /// locking, see the [`Stdin::lock`] method.
266 /// ### Note: Windows Portability Consideration
267 /// When operating in a console, the Windows implementation of this stream does not support
268 /// non-UTF-8 byte sequences. Attempting to read bytes that are not valid UTF-8 will return
273 /// Using implicit synchronization:
278 /// fn main() -> io::Result<()> {
279 /// let mut buffer = String::new();
280 /// io::stdin().read_line(&mut buffer)?;
285 /// Using explicit synchronization:
288 /// use std::io::{self, BufRead};
290 /// fn main() -> io::Result<()> {
291 /// let mut buffer = String::new();
292 /// let stdin = io::stdin();
293 /// let mut handle = stdin.lock();
295 /// handle.read_line(&mut buffer)?;
300 #[stable(feature = "rust1", since = "1.0.0")]
301 pub fn stdin() -> Stdin {
302 static INSTANCE: SyncOnceCell<Mutex<BufReader<StdinRaw>>> = SyncOnceCell::new();
304 inner: INSTANCE.get_or_init(|| {
305 Mutex::new(BufReader::with_capacity(stdio::STDIN_BUF_SIZE, stdin_raw()))
311 /// Locks this handle to the standard input stream, returning a readable
314 /// The lock is released when the returned lock goes out of scope. The
315 /// returned guard also implements the [`Read`] and [`BufRead`] traits for
316 /// accessing the underlying data.
321 /// use std::io::{self, BufRead};
323 /// fn main() -> io::Result<()> {
324 /// let mut buffer = String::new();
325 /// let stdin = io::stdin();
326 /// let mut handle = stdin.lock();
328 /// handle.read_line(&mut buffer)?;
332 #[stable(feature = "rust1", since = "1.0.0")]
333 pub fn lock(&self) -> StdinLock<'static> {
334 // Locks this handle with 'static lifetime. This depends on the
335 // implementation detail that the underlying `Mutex` is static.
336 StdinLock { inner: self.inner.lock().unwrap_or_else(|e| e.into_inner()) }
339 /// Locks this handle and reads a line of input, appending it to the specified buffer.
341 /// For detailed semantics of this method, see the documentation on
342 /// [`BufRead::read_line`].
349 /// let mut input = String::new();
350 /// match io::stdin().read_line(&mut input) {
352 /// println!("{} bytes read", n);
353 /// println!("{}", input);
355 /// Err(error) => println!("error: {}", error),
359 /// You can run the example one of two ways:
361 /// - Pipe some text to it, e.g., `printf foo | path/to/executable`
362 /// - Give it text interactively by running the executable directly,
363 /// in which case it will wait for the Enter key to be pressed before
365 #[stable(feature = "rust1", since = "1.0.0")]
366 pub fn read_line(&self, buf: &mut String) -> io::Result<usize> {
367 self.lock().read_line(buf)
370 /// Consumes this handle and returns an iterator over input lines.
372 /// For detailed semantics of this method, see the documentation on
373 /// [`BufRead::lines`].
378 /// #![feature(stdin_forwarders)]
381 /// let lines = io::stdin().lines();
382 /// for line in lines {
383 /// println!("got a line: {}", line.unwrap());
386 #[must_use = "`self` will be dropped if the result is not used"]
387 #[unstable(feature = "stdin_forwarders", issue = "87096")]
388 pub fn lines(self) -> Lines<StdinLock<'static>> {
393 #[stable(feature = "std_debug", since = "1.16.0")]
394 impl fmt::Debug for Stdin {
395 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
396 f.debug_struct("Stdin").finish_non_exhaustive()
400 #[stable(feature = "rust1", since = "1.0.0")]
401 impl Read for Stdin {
402 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
403 self.lock().read(buf)
405 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
406 self.lock().read_vectored(bufs)
409 fn is_read_vectored(&self) -> bool {
410 self.lock().is_read_vectored()
412 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
413 self.lock().read_to_end(buf)
415 fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
416 self.lock().read_to_string(buf)
418 fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
419 self.lock().read_exact(buf)
423 // only used by platform-dependent io::copy specializations, i.e. unused on some platforms
424 #[cfg(any(target_os = "linux", target_os = "android"))]
426 pub(crate) fn as_mut_buf(&mut self) -> &mut BufReader<impl Read> {
431 #[stable(feature = "rust1", since = "1.0.0")]
432 impl Read for StdinLock<'_> {
433 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
437 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
438 self.inner.read_vectored(bufs)
442 fn is_read_vectored(&self) -> bool {
443 self.inner.is_read_vectored()
446 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
447 self.inner.read_to_end(buf)
450 fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
451 self.inner.read_to_string(buf)
454 fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
455 self.inner.read_exact(buf)
459 #[stable(feature = "rust1", since = "1.0.0")]
460 impl BufRead for StdinLock<'_> {
461 fn fill_buf(&mut self) -> io::Result<&[u8]> {
462 self.inner.fill_buf()
465 fn consume(&mut self, n: usize) {
466 self.inner.consume(n)
469 fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> io::Result<usize> {
470 self.inner.read_until(byte, buf)
473 fn read_line(&mut self, buf: &mut String) -> io::Result<usize> {
474 self.inner.read_line(buf)
478 #[stable(feature = "std_debug", since = "1.16.0")]
479 impl fmt::Debug for StdinLock<'_> {
480 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
481 f.debug_struct("StdinLock").finish_non_exhaustive()
485 /// A handle to the global standard output stream of the current process.
487 /// Each handle shares a global buffer of data to be written to the standard
488 /// output stream. Access is also synchronized via a lock and explicit control
489 /// over locking is available via the [`lock`] method.
491 /// Created by the [`io::stdout`] method.
493 /// ### Note: Windows Portability Consideration
494 /// When operating in a console, the Windows implementation of this stream does not support
495 /// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
498 /// [`lock`]: Stdout::lock
499 /// [`io::stdout`]: stdout
500 #[stable(feature = "rust1", since = "1.0.0")]
502 // FIXME: this should be LineWriter or BufWriter depending on the state of
503 // stdout (tty or not). Note that if this is not line buffered it
504 // should also flush-on-panic or some form of flush-on-abort.
505 inner: Pin<&'static ReentrantMutex<RefCell<LineWriter<StdoutRaw>>>>,
508 /// A locked reference to the [`Stdout`] handle.
510 /// This handle implements the [`Write`] trait, and is constructed via
511 /// the [`Stdout::lock`] method. See its documentation for more.
513 /// ### Note: Windows Portability Consideration
514 /// When operating in a console, the Windows implementation of this stream does not support
515 /// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
517 #[must_use = "if unused stdout will immediately unlock"]
518 #[stable(feature = "rust1", since = "1.0.0")]
519 pub struct StdoutLock<'a> {
520 inner: ReentrantMutexGuard<'a, RefCell<LineWriter<StdoutRaw>>>,
523 static STDOUT: SyncOnceCell<ReentrantMutex<RefCell<LineWriter<StdoutRaw>>>> = SyncOnceCell::new();
525 /// Constructs a new handle to the standard output of the current process.
527 /// Each handle returned is a reference to a shared global buffer whose access
528 /// is synchronized via a mutex. If you need more explicit control over
529 /// locking, see the [`Stdout::lock`] method.
531 /// ### Note: Windows Portability Consideration
532 /// When operating in a console, the Windows implementation of this stream does not support
533 /// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
538 /// Using implicit synchronization:
541 /// use std::io::{self, Write};
543 /// fn main() -> io::Result<()> {
544 /// io::stdout().write_all(b"hello world")?;
550 /// Using explicit synchronization:
553 /// use std::io::{self, Write};
555 /// fn main() -> io::Result<()> {
556 /// let stdout = io::stdout();
557 /// let mut handle = stdout.lock();
559 /// handle.write_all(b"hello world")?;
565 #[stable(feature = "rust1", since = "1.0.0")]
566 pub fn stdout() -> Stdout {
568 inner: Pin::static_ref(&STDOUT).get_or_init_pin(
569 || unsafe { ReentrantMutex::new(RefCell::new(LineWriter::new(stdout_raw()))) },
570 |mutex| unsafe { mutex.init() },
576 if let Some(instance) = STDOUT.get() {
577 // Flush the data and disable buffering during shutdown
578 // by replacing the line writer by one with zero
579 // buffering capacity.
580 // We use try_lock() instead of lock(), because someone
581 // might have leaked a StdoutLock, which would
582 // otherwise cause a deadlock here.
583 if let Some(lock) = Pin::static_ref(instance).try_lock() {
584 *lock.borrow_mut() = LineWriter::with_capacity(0, stdout_raw());
590 /// Locks this handle to the standard output stream, returning a writable
593 /// The lock is released when the returned lock goes out of scope. The
594 /// returned guard also implements the `Write` trait for writing data.
599 /// use std::io::{self, Write};
601 /// fn main() -> io::Result<()> {
602 /// let mut stdout = io::stdout().lock();
604 /// stdout.write_all(b"hello world")?;
609 #[stable(feature = "rust1", since = "1.0.0")]
610 pub fn lock(&self) -> StdoutLock<'static> {
611 // Locks this handle with 'static lifetime. This depends on the
612 // implementation detail that the underlying `ReentrantMutex` is
614 StdoutLock { inner: self.inner.lock() }
618 #[stable(feature = "std_debug", since = "1.16.0")]
619 impl fmt::Debug for Stdout {
620 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
621 f.debug_struct("Stdout").finish_non_exhaustive()
625 #[stable(feature = "rust1", since = "1.0.0")]
626 impl Write for Stdout {
627 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
630 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
631 (&*self).write_vectored(bufs)
634 fn is_write_vectored(&self) -> bool {
635 io::Write::is_write_vectored(&&*self)
637 fn flush(&mut self) -> io::Result<()> {
640 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
641 (&*self).write_all(buf)
643 fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> {
644 (&*self).write_all_vectored(bufs)
646 fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> io::Result<()> {
647 (&*self).write_fmt(args)
651 #[stable(feature = "write_mt", since = "1.48.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)
677 #[stable(feature = "rust1", since = "1.0.0")]
678 impl Write for StdoutLock<'_> {
679 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
680 self.inner.borrow_mut().write(buf)
682 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
683 self.inner.borrow_mut().write_vectored(bufs)
686 fn is_write_vectored(&self) -> bool {
687 self.inner.borrow_mut().is_write_vectored()
689 fn flush(&mut self) -> io::Result<()> {
690 self.inner.borrow_mut().flush()
692 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
693 self.inner.borrow_mut().write_all(buf)
695 fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> {
696 self.inner.borrow_mut().write_all_vectored(bufs)
700 #[stable(feature = "std_debug", since = "1.16.0")]
701 impl fmt::Debug for StdoutLock<'_> {
702 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
703 f.debug_struct("StdoutLock").finish_non_exhaustive()
707 /// A handle to the standard error stream of a process.
709 /// For more information, see the [`io::stderr`] method.
711 /// [`io::stderr`]: stderr
713 /// ### Note: Windows Portability Consideration
714 /// When operating in a console, the Windows implementation of this stream does not support
715 /// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
717 #[stable(feature = "rust1", since = "1.0.0")]
719 inner: Pin<&'static ReentrantMutex<RefCell<StderrRaw>>>,
722 /// A locked reference to the [`Stderr`] handle.
724 /// This handle implements the [`Write`] trait and is constructed via
725 /// the [`Stderr::lock`] method. See its documentation for more.
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
731 #[must_use = "if unused stderr will immediately unlock"]
732 #[stable(feature = "rust1", since = "1.0.0")]
733 pub struct StderrLock<'a> {
734 inner: ReentrantMutexGuard<'a, RefCell<StderrRaw>>,
737 /// Constructs a new handle to the standard error of the current process.
739 /// This handle is not buffered.
741 /// ### Note: Windows Portability Consideration
742 /// When operating in a console, the Windows implementation of this stream does not support
743 /// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
748 /// Using implicit synchronization:
751 /// use std::io::{self, Write};
753 /// fn main() -> io::Result<()> {
754 /// io::stderr().write_all(b"hello world")?;
760 /// Using explicit synchronization:
763 /// use std::io::{self, Write};
765 /// fn main() -> io::Result<()> {
766 /// let stderr = io::stderr();
767 /// let mut handle = stderr.lock();
769 /// handle.write_all(b"hello world")?;
775 #[stable(feature = "rust1", since = "1.0.0")]
776 pub fn stderr() -> Stderr {
777 // Note that unlike `stdout()` we don't use `at_exit` here to register a
778 // destructor. Stderr is not buffered , so there's no need to run a
779 // destructor for flushing the buffer
780 static INSTANCE: SyncOnceCell<ReentrantMutex<RefCell<StderrRaw>>> = SyncOnceCell::new();
783 inner: Pin::static_ref(&INSTANCE).get_or_init_pin(
784 || unsafe { ReentrantMutex::new(RefCell::new(stderr_raw())) },
785 |mutex| unsafe { mutex.init() },
791 /// Locks this handle to the standard error stream, returning a writable
794 /// The lock is released when the returned lock goes out of scope. The
795 /// returned guard also implements the [`Write`] trait for writing data.
800 /// use std::io::{self, Write};
802 /// fn foo() -> io::Result<()> {
803 /// let stderr = io::stderr();
804 /// let mut handle = stderr.lock();
806 /// handle.write_all(b"hello world")?;
811 #[stable(feature = "rust1", since = "1.0.0")]
812 pub fn lock(&self) -> StderrLock<'static> {
813 // Locks this handle with 'static lifetime. This depends on the
814 // implementation detail that the underlying `ReentrantMutex` is
816 StderrLock { inner: self.inner.lock() }
820 #[stable(feature = "std_debug", since = "1.16.0")]
821 impl fmt::Debug for Stderr {
822 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
823 f.debug_struct("Stderr").finish_non_exhaustive()
827 #[stable(feature = "rust1", since = "1.0.0")]
828 impl Write for Stderr {
829 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
832 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
833 (&*self).write_vectored(bufs)
836 fn is_write_vectored(&self) -> bool {
837 io::Write::is_write_vectored(&&*self)
839 fn flush(&mut self) -> io::Result<()> {
842 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
843 (&*self).write_all(buf)
845 fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> {
846 (&*self).write_all_vectored(bufs)
848 fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> io::Result<()> {
849 (&*self).write_fmt(args)
853 #[stable(feature = "write_mt", since = "1.48.0")]
854 impl Write for &Stderr {
855 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
856 self.lock().write(buf)
858 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
859 self.lock().write_vectored(bufs)
862 fn is_write_vectored(&self) -> bool {
863 self.lock().is_write_vectored()
865 fn flush(&mut self) -> io::Result<()> {
868 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
869 self.lock().write_all(buf)
871 fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> {
872 self.lock().write_all_vectored(bufs)
874 fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> io::Result<()> {
875 self.lock().write_fmt(args)
879 #[stable(feature = "rust1", since = "1.0.0")]
880 impl Write for StderrLock<'_> {
881 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
882 self.inner.borrow_mut().write(buf)
884 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
885 self.inner.borrow_mut().write_vectored(bufs)
888 fn is_write_vectored(&self) -> bool {
889 self.inner.borrow_mut().is_write_vectored()
891 fn flush(&mut self) -> io::Result<()> {
892 self.inner.borrow_mut().flush()
894 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
895 self.inner.borrow_mut().write_all(buf)
897 fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> {
898 self.inner.borrow_mut().write_all_vectored(bufs)
902 #[stable(feature = "std_debug", since = "1.16.0")]
903 impl fmt::Debug for StderrLock<'_> {
904 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
905 f.debug_struct("StderrLock").finish_non_exhaustive()
909 /// Sets the thread-local output capture buffer and returns the old one.
911 feature = "internal_output_capture",
912 reason = "this function is meant for use in the test crate \
913 and may disappear in the future",
917 pub fn set_output_capture(sink: Option<LocalStream>) -> Option<LocalStream> {
918 if sink.is_none() && !OUTPUT_CAPTURE_USED.load(Ordering::Relaxed) {
919 // OUTPUT_CAPTURE is definitely None since OUTPUT_CAPTURE_USED is false.
922 OUTPUT_CAPTURE_USED.store(true, Ordering::Relaxed);
923 OUTPUT_CAPTURE.with(move |slot| slot.replace(sink))
926 /// Write `args` to the capture buffer if enabled and possible, or `global_s`
927 /// otherwise. `label` identifies the stream in a panic message.
929 /// This function is used to print error messages, so it takes extra
930 /// care to avoid causing a panic when `local_s` is unusable.
931 /// For instance, if the TLS key for the local stream is
932 /// already destroyed, or if the local stream is locked by another
933 /// thread, it will just fall back to the global stream.
935 /// However, if the actual I/O causes an error, this function does panic.
936 fn print_to<T>(args: fmt::Arguments<'_>, global_s: fn() -> T, label: &str)
940 if OUTPUT_CAPTURE_USED.load(Ordering::Relaxed)
941 && OUTPUT_CAPTURE.try_with(|s| {
942 // Note that we completely remove a local sink to write to in case
943 // our printing recursively panics/prints, so the recursive
944 // panic/print goes to the global sink instead of our local sink.
946 let _ = w.lock().unwrap_or_else(|e| e.into_inner()).write_fmt(args);
951 // Successfully wrote to capture buffer.
955 if let Err(e) = global_s().write_fmt(args) {
956 panic!("failed printing to {}: {}", label, e);
961 feature = "print_internals",
962 reason = "implementation detail which may disappear or be replaced at any time",
967 pub fn _print(args: fmt::Arguments<'_>) {
968 print_to(args, stdout, "stdout");
972 feature = "print_internals",
973 reason = "implementation detail which may disappear or be replaced at any time",
978 pub fn _eprint(args: fmt::Arguments<'_>) {
979 print_to(args, stderr, "stderr");
983 pub use realstd::io::{_eprint, _print};