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 impl Write for StdoutRaw {
101 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
105 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
106 self.0.write_vectored(bufs)
110 fn is_write_vectored(&self) -> bool {
111 self.0.is_write_vectored()
114 fn flush(&mut self) -> io::Result<()> {
118 impl Write for StderrRaw {
119 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
123 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
124 self.0.write_vectored(bufs)
128 fn is_write_vectored(&self) -> bool {
129 self.0.is_write_vectored()
132 fn flush(&mut self) -> io::Result<()> {
142 impl<W: io::Write> io::Write for Maybe<W> {
143 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
145 Maybe::Real(ref mut w) => handle_ebadf(w.write(buf), buf.len()),
146 Maybe::Fake => Ok(buf.len()),
150 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
151 let total = bufs.iter().map(|b| b.len()).sum();
153 Maybe::Real(w) => handle_ebadf(w.write_vectored(bufs), total),
154 Maybe::Fake => Ok(total),
159 fn is_write_vectored(&self) -> bool {
161 Maybe::Real(w) => w.is_write_vectored(),
166 fn flush(&mut self) -> io::Result<()> {
168 Maybe::Real(ref mut w) => handle_ebadf(w.flush(), ()),
169 Maybe::Fake => Ok(()),
174 impl<R: io::Read> io::Read for Maybe<R> {
175 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
177 Maybe::Real(ref mut r) => handle_ebadf(r.read(buf), 0),
178 Maybe::Fake => Ok(0),
182 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
184 Maybe::Real(r) => handle_ebadf(r.read_vectored(bufs), 0),
185 Maybe::Fake => Ok(0),
190 fn is_read_vectored(&self) -> bool {
192 Maybe::Real(w) => w.is_read_vectored(),
198 fn handle_ebadf<T>(r: io::Result<T>, default: T) -> io::Result<T> {
200 Err(ref e) if stdio::is_ebadf(e) => Ok(default),
205 /// A handle to the standard input stream of a process.
207 /// Each handle is a shared reference to a global buffer of input data to this
208 /// process. A handle can be `lock`'d to gain full access to [`BufRead`] methods
209 /// (e.g., `.lines()`). Reads to this handle are otherwise locked with respect
212 /// This handle implements the `Read` trait, but beware that concurrent reads
213 /// of `Stdin` must be executed with care.
215 /// Created by the [`io::stdin`] method.
217 /// [`io::stdin`]: fn.stdin.html
218 /// [`BufRead`]: trait.BufRead.html
220 /// ### Note: Windows Portability Consideration
222 /// When operating in a console, the Windows implementation of this stream does not support
223 /// non-UTF-8 byte sequences. Attempting to read bytes that are not valid UTF-8 will return
229 /// use std::io::{self, Read};
231 /// fn main() -> io::Result<()> {
232 /// let mut buffer = String::new();
233 /// let mut stdin = io::stdin(); // We get `Stdin` here.
234 /// stdin.read_to_string(&mut buffer)?;
238 #[stable(feature = "rust1", since = "1.0.0")]
240 inner: Arc<Mutex<BufReader<Maybe<StdinRaw>>>>,
243 /// A locked reference to the `Stdin` handle.
245 /// This handle implements both the [`Read`] and [`BufRead`] traits, and
246 /// is constructed via the [`Stdin::lock`] method.
248 /// [`Read`]: trait.Read.html
249 /// [`BufRead`]: trait.BufRead.html
250 /// [`Stdin::lock`]: struct.Stdin.html#method.lock
252 /// ### Note: Windows Portability Consideration
254 /// When operating in a console, the Windows implementation of this stream does not support
255 /// non-UTF-8 byte sequences. Attempting to read bytes that are not valid UTF-8 will return
261 /// use std::io::{self, Read};
263 /// fn main() -> io::Result<()> {
264 /// let mut buffer = String::new();
265 /// let stdin = io::stdin(); // We get `Stdin` here.
267 /// let mut stdin_lock = stdin.lock(); // We get `StdinLock` here.
268 /// stdin_lock.read_to_string(&mut buffer)?;
269 /// } // `StdinLock` is dropped here.
273 #[stable(feature = "rust1", since = "1.0.0")]
274 pub struct StdinLock<'a> {
275 inner: MutexGuard<'a, BufReader<Maybe<StdinRaw>>>,
278 /// Constructs a new handle to the standard input of the current process.
280 /// Each handle returned is a reference to a shared global buffer whose access
281 /// is synchronized via a mutex. If you need more explicit control over
282 /// locking, see the [`Stdin::lock`] method.
284 /// [`Stdin::lock`]: struct.Stdin.html#method.lock
286 /// ### 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
293 /// Using implicit synchronization:
296 /// use std::io::{self, Read};
298 /// fn main() -> io::Result<()> {
299 /// let mut buffer = String::new();
300 /// io::stdin().read_to_string(&mut buffer)?;
305 /// Using explicit synchronization:
308 /// use std::io::{self, Read};
310 /// fn main() -> io::Result<()> {
311 /// let mut buffer = String::new();
312 /// let stdin = io::stdin();
313 /// let mut handle = stdin.lock();
315 /// handle.read_to_string(&mut buffer)?;
319 #[stable(feature = "rust1", since = "1.0.0")]
320 pub fn stdin() -> Stdin {
321 static INSTANCE: Lazy<Mutex<BufReader<Maybe<StdinRaw>>>> = Lazy::new();
323 inner: unsafe { INSTANCE.get(stdin_init).expect("cannot access stdin during shutdown") },
326 fn stdin_init() -> Arc<Mutex<BufReader<Maybe<StdinRaw>>>> {
327 // This must not reentrantly access `INSTANCE`
328 let stdin = match stdin_raw() {
329 Ok(stdin) => Maybe::Real(stdin),
333 Arc::new(Mutex::new(BufReader::with_capacity(stdio::STDIN_BUF_SIZE, stdin)))
338 /// Locks this handle to the standard input stream, returning a readable
341 /// The lock is released when the returned lock goes out of scope. The
342 /// returned guard also implements the [`Read`] and [`BufRead`] traits for
343 /// accessing the underlying data.
345 /// [`Read`]: trait.Read.html
346 /// [`BufRead`]: trait.BufRead.html
351 /// use std::io::{self, Read};
353 /// fn main() -> io::Result<()> {
354 /// let mut buffer = String::new();
355 /// let stdin = io::stdin();
356 /// let mut handle = stdin.lock();
358 /// handle.read_to_string(&mut buffer)?;
362 #[stable(feature = "rust1", since = "1.0.0")]
363 pub fn lock(&self) -> StdinLock<'_> {
364 StdinLock { inner: self.inner.lock().unwrap_or_else(|e| e.into_inner()) }
367 /// Locks this handle and reads a line of input, appending it to the specified buffer.
369 /// For detailed semantics of this method, see the documentation on
370 /// [`BufRead::read_line`].
372 /// [`BufRead::read_line`]: trait.BufRead.html#method.read_line
379 /// let mut input = String::new();
380 /// match io::stdin().read_line(&mut input) {
382 /// println!("{} bytes read", n);
383 /// println!("{}", input);
385 /// Err(error) => println!("error: {}", error),
389 /// You can run the example one of two ways:
391 /// - Pipe some text to it, e.g., `printf foo | path/to/executable`
392 /// - Give it text interactively by running the executable directly,
393 /// in which case it will wait for the Enter key to be pressed before
395 #[stable(feature = "rust1", since = "1.0.0")]
396 pub fn read_line(&self, buf: &mut String) -> io::Result<usize> {
397 self.lock().read_line(buf)
401 #[stable(feature = "std_debug", since = "1.16.0")]
402 impl fmt::Debug for Stdin {
403 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
404 f.pad("Stdin { .. }")
408 #[stable(feature = "rust1", since = "1.0.0")]
409 impl Read for Stdin {
410 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
411 self.lock().read(buf)
413 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
414 self.lock().read_vectored(bufs)
417 fn is_read_vectored(&self) -> bool {
418 self.lock().is_read_vectored()
421 unsafe fn initializer(&self) -> Initializer {
424 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
425 self.lock().read_to_end(buf)
427 fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
428 self.lock().read_to_string(buf)
430 fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
431 self.lock().read_exact(buf)
435 #[stable(feature = "rust1", since = "1.0.0")]
436 impl Read for StdinLock<'_> {
437 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
441 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
442 self.inner.read_vectored(bufs)
446 fn is_read_vectored(&self) -> bool {
447 self.inner.is_read_vectored()
451 unsafe fn initializer(&self) -> Initializer {
456 #[stable(feature = "rust1", since = "1.0.0")]
457 impl BufRead for StdinLock<'_> {
458 fn fill_buf(&mut self) -> io::Result<&[u8]> {
459 self.inner.fill_buf()
461 fn consume(&mut self, n: usize) {
462 self.inner.consume(n)
466 #[stable(feature = "std_debug", since = "1.16.0")]
467 impl fmt::Debug for StdinLock<'_> {
468 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
469 f.pad("StdinLock { .. }")
473 /// A handle to the global standard output stream of the current process.
475 /// Each handle shares a global buffer of data to be written to the standard
476 /// output stream. Access is also synchronized via a lock and explicit control
477 /// over locking is available via the [`lock`] method.
479 /// Created by the [`io::stdout`] method.
481 /// ### Note: Windows Portability Consideration
482 /// When operating in a console, the Windows implementation of this stream does not support
483 /// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
486 /// [`lock`]: #method.lock
487 /// [`io::stdout`]: fn.stdout.html
488 #[stable(feature = "rust1", since = "1.0.0")]
490 // FIXME: this should be LineWriter or BufWriter depending on the state of
491 // stdout (tty or not). Note that if this is not line buffered it
492 // should also flush-on-panic or some form of flush-on-abort.
493 inner: Arc<ReentrantMutex<RefCell<LineWriter<Maybe<StdoutRaw>>>>>,
496 /// A locked reference to the `Stdout` handle.
498 /// This handle implements the [`Write`] trait, and is constructed via
499 /// the [`Stdout::lock`] method.
501 /// ### Note: Windows Portability Consideration
502 /// When operating in a console, the Windows implementation of this stream does not support
503 /// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
506 /// [`Write`]: trait.Write.html
507 /// [`Stdout::lock`]: struct.Stdout.html#method.lock
508 #[stable(feature = "rust1", since = "1.0.0")]
509 pub struct StdoutLock<'a> {
510 inner: ReentrantMutexGuard<'a, RefCell<LineWriter<Maybe<StdoutRaw>>>>,
513 /// Constructs a new handle to the standard output of the current process.
515 /// Each handle returned is a reference to a shared global buffer whose access
516 /// is synchronized via a mutex. If you need more explicit control over
517 /// locking, see the [`Stdout::lock`] method.
519 /// [`Stdout::lock`]: struct.Stdout.html#method.lock
521 /// ### Note: Windows Portability Consideration
522 /// When operating in a console, the Windows implementation of this stream does not support
523 /// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
528 /// Using implicit synchronization:
531 /// use std::io::{self, Write};
533 /// fn main() -> io::Result<()> {
534 /// io::stdout().write_all(b"hello world")?;
540 /// Using explicit synchronization:
543 /// use std::io::{self, Write};
545 /// fn main() -> io::Result<()> {
546 /// let stdout = io::stdout();
547 /// let mut handle = stdout.lock();
549 /// handle.write_all(b"hello world")?;
554 #[stable(feature = "rust1", since = "1.0.0")]
555 pub fn stdout() -> Stdout {
556 static INSTANCE: Lazy<ReentrantMutex<RefCell<LineWriter<Maybe<StdoutRaw>>>>> = Lazy::new();
558 inner: unsafe { INSTANCE.get(stdout_init).expect("cannot access stdout during shutdown") },
561 fn stdout_init() -> Arc<ReentrantMutex<RefCell<LineWriter<Maybe<StdoutRaw>>>>> {
562 // This must not reentrantly access `INSTANCE`
563 let stdout = match stdout_raw() {
564 Ok(stdout) => Maybe::Real(stdout),
568 let ret = Arc::new(ReentrantMutex::new(RefCell::new(LineWriter::new(stdout))));
576 /// Locks this handle to the standard output stream, returning a writable
579 /// The lock is released when the returned lock goes out of scope. The
580 /// returned guard also implements the `Write` trait for writing data.
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 lock(&self) -> StdoutLock<'_> {
598 StdoutLock { inner: self.inner.lock() }
602 #[stable(feature = "std_debug", since = "1.16.0")]
603 impl fmt::Debug for Stdout {
604 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
605 f.pad("Stdout { .. }")
609 #[stable(feature = "rust1", since = "1.0.0")]
610 impl Write for Stdout {
611 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
612 self.lock().write(buf)
614 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
615 self.lock().write_vectored(bufs)
618 fn is_write_vectored(&self) -> bool {
619 self.lock().is_write_vectored()
621 fn flush(&mut self) -> io::Result<()> {
624 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
625 self.lock().write_all(buf)
627 fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> io::Result<()> {
628 self.lock().write_fmt(args)
631 #[stable(feature = "rust1", since = "1.0.0")]
632 impl Write for StdoutLock<'_> {
633 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
634 self.inner.borrow_mut().write(buf)
636 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
637 self.inner.borrow_mut().write_vectored(bufs)
640 fn is_write_vectored(&self) -> bool {
641 self.inner.borrow_mut().is_write_vectored()
643 fn flush(&mut self) -> io::Result<()> {
644 self.inner.borrow_mut().flush()
648 #[stable(feature = "std_debug", since = "1.16.0")]
649 impl fmt::Debug for StdoutLock<'_> {
650 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
651 f.pad("StdoutLock { .. }")
655 /// A handle to the standard error stream of a process.
657 /// For more information, see the [`io::stderr`] method.
659 /// [`io::stderr`]: fn.stderr.html
661 /// ### Note: Windows Portability Consideration
662 /// When operating in a console, the Windows implementation of this stream does not support
663 /// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
665 #[stable(feature = "rust1", since = "1.0.0")]
667 inner: &'static ReentrantMutex<RefCell<Maybe<StderrRaw>>>,
670 /// A locked reference to the `Stderr` handle.
672 /// This handle implements the `Write` trait and is constructed via
673 /// the [`Stderr::lock`] method.
675 /// [`Stderr::lock`]: struct.Stderr.html#method.lock
677 /// ### Note: Windows Portability Consideration
678 /// When operating in a console, the Windows implementation of this stream does not support
679 /// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
681 #[stable(feature = "rust1", since = "1.0.0")]
682 pub struct StderrLock<'a> {
683 inner: ReentrantMutexGuard<'a, RefCell<Maybe<StderrRaw>>>,
686 /// Constructs a new handle to the standard error of the current process.
688 /// This handle is not buffered.
690 /// ### Note: Windows Portability Consideration
691 /// When operating in a console, the Windows implementation of this stream does not support
692 /// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
697 /// Using implicit synchronization:
700 /// use std::io::{self, Write};
702 /// fn main() -> io::Result<()> {
703 /// io::stderr().write_all(b"hello world")?;
709 /// Using explicit synchronization:
712 /// use std::io::{self, Write};
714 /// fn main() -> io::Result<()> {
715 /// let stderr = io::stderr();
716 /// let mut handle = stderr.lock();
718 /// handle.write_all(b"hello world")?;
723 #[stable(feature = "rust1", since = "1.0.0")]
724 pub fn stderr() -> Stderr {
725 // Note that unlike `stdout()` we don't use `Lazy` here which registers a
726 // destructor. Stderr is not buffered nor does the `stderr_raw` type consume
727 // any owned resources, so there's no need to run any destructors at some
728 // point in the future.
730 // This has the added benefit of allowing `stderr` to be usable during
731 // process shutdown as well!
732 static INSTANCE: ReentrantMutex<RefCell<Maybe<StderrRaw>>> =
733 unsafe { ReentrantMutex::new(RefCell::new(Maybe::Fake)) };
735 // When accessing stderr we need one-time initialization of the reentrant
736 // mutex, followed by one-time detection of whether we actually have a
737 // stderr handle or not. Afterwards we can just always use the now-filled-in
739 static INIT: Once = Once::new();
740 INIT.call_once(|| unsafe {
742 if let Ok(stderr) = stderr_raw() {
743 *INSTANCE.lock().borrow_mut() = Maybe::Real(stderr);
746 Stderr { inner: &INSTANCE }
750 /// Locks this handle to the standard error stream, returning a writable
753 /// The lock is released when the returned lock goes out of scope. The
754 /// returned guard also implements the `Write` trait for writing data.
759 /// use std::io::{self, Write};
761 /// fn foo() -> io::Result<()> {
762 /// let stderr = io::stderr();
763 /// let mut handle = stderr.lock();
765 /// handle.write_all(b"hello world")?;
770 #[stable(feature = "rust1", since = "1.0.0")]
771 pub fn lock(&self) -> StderrLock<'_> {
772 StderrLock { inner: self.inner.lock() }
776 #[stable(feature = "std_debug", since = "1.16.0")]
777 impl fmt::Debug for Stderr {
778 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
779 f.pad("Stderr { .. }")
783 #[stable(feature = "rust1", since = "1.0.0")]
784 impl Write for Stderr {
785 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
786 self.lock().write(buf)
788 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
789 self.lock().write_vectored(bufs)
792 fn is_write_vectored(&self) -> bool {
793 self.lock().is_write_vectored()
795 fn flush(&mut self) -> io::Result<()> {
798 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
799 self.lock().write_all(buf)
801 fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> io::Result<()> {
802 self.lock().write_fmt(args)
805 #[stable(feature = "rust1", since = "1.0.0")]
806 impl Write for StderrLock<'_> {
807 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
808 self.inner.borrow_mut().write(buf)
810 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
811 self.inner.borrow_mut().write_vectored(bufs)
814 fn is_write_vectored(&self) -> bool {
815 self.inner.borrow_mut().is_write_vectored()
817 fn flush(&mut self) -> io::Result<()> {
818 self.inner.borrow_mut().flush()
822 #[stable(feature = "std_debug", since = "1.16.0")]
823 impl fmt::Debug for StderrLock<'_> {
824 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
825 f.pad("StderrLock { .. }")
829 /// Resets the thread-local stderr handle to the specified writer
831 /// This will replace the current thread's stderr handle, returning the old
832 /// handle. All future calls to `panic!` and friends will emit their output to
833 /// this specified handle.
835 /// Note that this does not need to be called for all new threads; the default
836 /// output handle is to the process's stderr stream.
838 feature = "set_stdio",
839 reason = "this function may disappear completely or be replaced \
840 with a more general mechanism",
844 pub fn set_panic(sink: Option<Box<dyn Write + Send>>) -> Option<Box<dyn Write + Send>> {
846 LOCAL_STDERR.with(move |slot| mem::replace(&mut *slot.borrow_mut(), sink)).and_then(|mut s| {
852 /// Resets the thread-local stdout handle to the specified writer
854 /// This will replace the current thread's stdout handle, returning the old
855 /// handle. All future calls to `print!` and friends will emit their output to
856 /// this specified handle.
858 /// Note that this does not need to be called for all new threads; the default
859 /// output handle is to the process's stdout stream.
861 feature = "set_stdio",
862 reason = "this function may disappear completely or be replaced \
863 with a more general mechanism",
867 pub fn set_print(sink: Option<Box<dyn Write + Send>>) -> Option<Box<dyn Write + Send>> {
869 LOCAL_STDOUT.with(move |slot| mem::replace(&mut *slot.borrow_mut(), sink)).and_then(|mut s| {
875 /// Write `args` to output stream `local_s` if possible, `global_s`
876 /// otherwise. `label` identifies the stream in a panic message.
878 /// This function is used to print error messages, so it takes extra
879 /// care to avoid causing a panic when `local_s` is unusable.
880 /// For instance, if the TLS key for the local stream is
881 /// already destroyed, or if the local stream is locked by another
882 /// thread, it will just fall back to the global stream.
884 /// However, if the actual I/O causes an error, this function does panic.
886 args: fmt::Arguments<'_>,
887 local_s: &'static LocalKey<RefCell<Option<Box<dyn Write + Send>>>>,
895 // Note that we completely remove a local sink to write to in case
896 // our printing recursively panics/prints, so the recursive
897 // panic/print goes to the global sink instead of our local sink.
898 let prev = s.borrow_mut().take();
899 if let Some(mut w) = prev {
900 let result = w.write_fmt(args);
901 *s.borrow_mut() = Some(w);
904 global_s().write_fmt(args)
906 .unwrap_or_else(|_| global_s().write_fmt(args));
908 if let Err(e) = result {
909 panic!("failed printing to {}: {}", label, e);
914 feature = "print_internals",
915 reason = "implementation detail which may disappear or be replaced at any time",
920 pub fn _print(args: fmt::Arguments<'_>) {
921 print_to(args, &LOCAL_STDOUT, stdout, "stdout");
925 feature = "print_internals",
926 reason = "implementation detail which may disappear or be replaced at any time",
931 pub fn _eprint(args: fmt::Arguments<'_>) {
932 print_to(args, &LOCAL_STDERR, stderr, "stderr");
936 pub use realstd::io::{_eprint, _print};
941 use crate::panic::{RefUnwindSafe, UnwindSafe};
945 fn stdout_unwind_safe() {
946 assert_unwind_safe::<Stdout>();
949 fn stdoutlock_unwind_safe() {
950 assert_unwind_safe::<StdoutLock<'_>>();
951 assert_unwind_safe::<StdoutLock<'static>>();
954 fn stderr_unwind_safe() {
955 assert_unwind_safe::<Stderr>();
958 fn stderrlock_unwind_safe() {
959 assert_unwind_safe::<StderrLock<'_>>();
960 assert_unwind_safe::<StderrLock<'static>>();
963 fn assert_unwind_safe<T: UnwindSafe + RefUnwindSafe>() {}
966 #[cfg_attr(target_os = "emscripten", ignore)]
967 fn panic_doesnt_poison() {