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, Initializer, BufReader, LineWriter, IoSlice, IoSliceMut};
9 use crate::sync::{Arc, Mutex, MutexGuard};
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> { stdio::Stdin::new().map(StdinRaw) }
55 /// Constructs a new raw handle to the standard output stream of this process.
57 /// The returned handle does not interact with any other handles created nor
58 /// handles returned by `std::io::stdout`. Note that data is buffered by the
59 /// `std::io::stdout` handles so writes which happen via this raw handle may
60 /// appear before previous writes.
62 /// The returned handle has no external synchronization or buffering layered on
64 fn stdout_raw() -> io::Result<StdoutRaw> { stdio::Stdout::new().map(StdoutRaw) }
66 /// Constructs a new raw handle to the standard error stream of this process.
68 /// The returned handle does not interact with any other handles created nor
69 /// handles returned by `std::io::stderr`.
71 /// The returned handle has no external synchronization or buffering layered on
73 fn stderr_raw() -> io::Result<StderrRaw> { stdio::Stderr::new().map(StderrRaw) }
75 impl Read for StdinRaw {
76 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) }
78 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
79 self.0.read_vectored(bufs)
83 unsafe fn initializer(&self) -> Initializer {
87 impl Write for StdoutRaw {
88 fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) }
90 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
91 self.0.write_vectored(bufs)
94 fn flush(&mut self) -> io::Result<()> { self.0.flush() }
96 impl Write for StderrRaw {
97 fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) }
99 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
100 self.0.write_vectored(bufs)
103 fn flush(&mut self) -> io::Result<()> { self.0.flush() }
111 impl<W: io::Write> io::Write for Maybe<W> {
112 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
114 Maybe::Real(ref mut w) => handle_ebadf(w.write(buf), buf.len()),
115 Maybe::Fake => Ok(buf.len())
119 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
120 let total = bufs.iter().map(|b| b.len()).sum();
122 Maybe::Real(w) => handle_ebadf(w.write_vectored(bufs), total),
123 Maybe::Fake => Ok(total),
127 fn flush(&mut self) -> io::Result<()> {
129 Maybe::Real(ref mut w) => handle_ebadf(w.flush(), ()),
130 Maybe::Fake => Ok(())
135 impl<R: io::Read> io::Read for Maybe<R> {
136 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
138 Maybe::Real(ref mut r) => handle_ebadf(r.read(buf), 0),
143 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
145 Maybe::Real(r) => handle_ebadf(r.read_vectored(bufs), 0),
151 fn handle_ebadf<T>(r: io::Result<T>, default: T) -> io::Result<T> {
153 Err(ref e) if stdio::is_ebadf(e) => Ok(default),
158 /// A handle to the standard input stream of a process.
160 /// Each handle is a shared reference to a global buffer of input data to this
161 /// process. A handle can be `lock`'d to gain full access to [`BufRead`] methods
162 /// (e.g., `.lines()`). Reads to this handle are otherwise locked with respect
165 /// This handle implements the `Read` trait, but beware that concurrent reads
166 /// of `Stdin` must be executed with care.
168 /// Created by the [`io::stdin`] method.
170 /// [`io::stdin`]: fn.stdin.html
171 /// [`BufRead`]: trait.BufRead.html
173 /// ### Note: Windows Portability Consideration
174 /// When operating in a console, the Windows implementation of this stream does not support
175 /// non-UTF-8 byte sequences. Attempting to read bytes that are not valid UTF-8 will return
177 #[stable(feature = "rust1", since = "1.0.0")]
179 inner: Arc<Mutex<BufReader<Maybe<StdinRaw>>>>,
182 /// A locked reference to the `Stdin` handle.
184 /// This handle implements both the [`Read`] and [`BufRead`] traits, and
185 /// is constructed via the [`Stdin::lock`] method.
187 /// [`Read`]: trait.Read.html
188 /// [`BufRead`]: trait.BufRead.html
189 /// [`Stdin::lock`]: struct.Stdin.html#method.lock
191 /// ### Note: Windows Portability Consideration
192 /// When operating in a console, the Windows implementation of this stream does not support
193 /// non-UTF-8 byte sequences. Attempting to read bytes that are not valid UTF-8 will return
195 #[stable(feature = "rust1", since = "1.0.0")]
196 pub struct StdinLock<'a> {
197 inner: MutexGuard<'a, BufReader<Maybe<StdinRaw>>>,
200 /// Constructs a new handle to the standard input of the current process.
202 /// Each handle returned is a reference to a shared global buffer whose access
203 /// is synchronized via a mutex. If you need more explicit control over
204 /// locking, see the [`Stdin::lock`] method.
206 /// [`Stdin::lock`]: struct.Stdin.html#method.lock
208 /// ### Note: Windows Portability Consideration
209 /// When operating in a console, the Windows implementation of this stream does not support
210 /// non-UTF-8 byte sequences. Attempting to read bytes that are not valid UTF-8 will return
215 /// Using implicit synchronization:
218 /// use std::io::{self, Read};
220 /// fn main() -> io::Result<()> {
221 /// let mut buffer = String::new();
222 /// io::stdin().read_to_string(&mut buffer)?;
227 /// Using explicit synchronization:
230 /// use std::io::{self, Read};
232 /// fn main() -> io::Result<()> {
233 /// let mut buffer = String::new();
234 /// let stdin = io::stdin();
235 /// let mut handle = stdin.lock();
237 /// handle.read_to_string(&mut buffer)?;
241 #[stable(feature = "rust1", since = "1.0.0")]
242 pub fn stdin() -> Stdin {
243 static INSTANCE: Lazy<Mutex<BufReader<Maybe<StdinRaw>>>> = Lazy::new();
246 INSTANCE.get(stdin_init).expect("cannot access stdin during shutdown")
250 fn stdin_init() -> Arc<Mutex<BufReader<Maybe<StdinRaw>>>> {
251 // This must not reentrantly access `INSTANCE`
252 let stdin = match stdin_raw() {
253 Ok(stdin) => Maybe::Real(stdin),
257 Arc::new(Mutex::new(BufReader::with_capacity(stdio::STDIN_BUF_SIZE, stdin)))
262 /// Locks this handle to the standard input stream, returning a readable
265 /// The lock is released when the returned lock goes out of scope. The
266 /// returned guard also implements the [`Read`] and [`BufRead`] traits for
267 /// accessing the underlying data.
269 /// [`Read`]: trait.Read.html
270 /// [`BufRead`]: trait.BufRead.html
275 /// use std::io::{self, Read};
277 /// fn main() -> io::Result<()> {
278 /// let mut buffer = String::new();
279 /// let stdin = io::stdin();
280 /// let mut handle = stdin.lock();
282 /// handle.read_to_string(&mut buffer)?;
286 #[stable(feature = "rust1", since = "1.0.0")]
287 pub fn lock(&self) -> StdinLock<'_> {
288 StdinLock { inner: self.inner.lock().unwrap_or_else(|e| e.into_inner()) }
291 /// Locks this handle and reads a line of input into the specified buffer.
293 /// For detailed semantics of this method, see the documentation on
294 /// [`BufRead::read_line`].
296 /// [`BufRead::read_line`]: trait.BufRead.html#method.read_line
303 /// let mut input = String::new();
304 /// match io::stdin().read_line(&mut input) {
306 /// println!("{} bytes read", n);
307 /// println!("{}", input);
309 /// Err(error) => println!("error: {}", error),
313 /// You can run the example one of two ways:
315 /// - Pipe some text to it, e.g., `printf foo | path/to/executable`
316 /// - Give it text interactively by running the executable directly,
317 /// in which case it will wait for the Enter key to be pressed before
319 #[stable(feature = "rust1", since = "1.0.0")]
320 pub fn read_line(&self, buf: &mut String) -> io::Result<usize> {
321 self.lock().read_line(buf)
325 #[stable(feature = "std_debug", since = "1.16.0")]
326 impl fmt::Debug for Stdin {
327 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
328 f.pad("Stdin { .. }")
332 #[stable(feature = "rust1", since = "1.0.0")]
333 impl Read for Stdin {
334 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
335 self.lock().read(buf)
337 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
338 self.lock().read_vectored(bufs)
341 unsafe fn initializer(&self) -> Initializer {
344 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
345 self.lock().read_to_end(buf)
347 fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
348 self.lock().read_to_string(buf)
350 fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
351 self.lock().read_exact(buf)
355 #[stable(feature = "rust1", since = "1.0.0")]
356 impl Read for StdinLock<'_> {
357 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
361 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
362 self.inner.read_vectored(bufs)
366 unsafe fn initializer(&self) -> Initializer {
371 #[stable(feature = "rust1", since = "1.0.0")]
372 impl BufRead for StdinLock<'_> {
373 fn fill_buf(&mut self) -> io::Result<&[u8]> { self.inner.fill_buf() }
374 fn consume(&mut self, n: usize) { self.inner.consume(n) }
377 #[stable(feature = "std_debug", since = "1.16.0")]
378 impl fmt::Debug for StdinLock<'_> {
379 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
380 f.pad("StdinLock { .. }")
384 /// A handle to the global standard output stream of the current process.
386 /// Each handle shares a global buffer of data to be written to the standard
387 /// output stream. Access is also synchronized via a lock and explicit control
388 /// over locking is available via the [`lock`] method.
390 /// Created by the [`io::stdout`] method.
392 /// ### Note: Windows Portability Consideration
393 /// When operating in a console, the Windows implementation of this stream does not support
394 /// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
397 /// [`lock`]: #method.lock
398 /// [`io::stdout`]: fn.stdout.html
399 #[stable(feature = "rust1", since = "1.0.0")]
401 // FIXME: this should be LineWriter or BufWriter depending on the state of
402 // stdout (tty or not). Note that if this is not line buffered it
403 // should also flush-on-panic or some form of flush-on-abort.
404 inner: Arc<ReentrantMutex<RefCell<LineWriter<Maybe<StdoutRaw>>>>>,
407 /// A locked reference to the `Stdout` handle.
409 /// This handle implements the [`Write`] trait, and is constructed via
410 /// the [`Stdout::lock`] method.
412 /// ### Note: Windows Portability Consideration
413 /// When operating in a console, the Windows implementation of this stream does not support
414 /// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
417 /// [`Write`]: trait.Write.html
418 /// [`Stdout::lock`]: struct.Stdout.html#method.lock
419 #[stable(feature = "rust1", since = "1.0.0")]
420 pub struct StdoutLock<'a> {
421 inner: ReentrantMutexGuard<'a, RefCell<LineWriter<Maybe<StdoutRaw>>>>,
424 /// Constructs a new handle to the standard output of the current process.
426 /// Each handle returned is a reference to a shared global buffer whose access
427 /// is synchronized via a mutex. If you need more explicit control over
428 /// locking, see the [`Stdout::lock`] method.
430 /// [`Stdout::lock`]: struct.Stdout.html#method.lock
432 /// ### Note: Windows Portability Consideration
433 /// When operating in a console, the Windows implementation of this stream does not support
434 /// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
439 /// Using implicit synchronization:
442 /// use std::io::{self, Write};
444 /// fn main() -> io::Result<()> {
445 /// io::stdout().write_all(b"hello world")?;
451 /// Using explicit synchronization:
454 /// use std::io::{self, Write};
456 /// fn main() -> io::Result<()> {
457 /// let stdout = io::stdout();
458 /// let mut handle = stdout.lock();
460 /// handle.write_all(b"hello world")?;
465 #[stable(feature = "rust1", since = "1.0.0")]
466 pub fn stdout() -> Stdout {
467 static INSTANCE: Lazy<ReentrantMutex<RefCell<LineWriter<Maybe<StdoutRaw>>>>> = Lazy::new();
470 INSTANCE.get(stdout_init).expect("cannot access stdout during shutdown")
474 fn stdout_init() -> Arc<ReentrantMutex<RefCell<LineWriter<Maybe<StdoutRaw>>>>> {
475 // This must not reentrantly access `INSTANCE`
476 let stdout = match stdout_raw() {
477 Ok(stdout) => Maybe::Real(stdout),
480 Arc::new(ReentrantMutex::new(RefCell::new(LineWriter::new(stdout))))
485 /// Locks this handle to the standard output stream, returning a writable
488 /// The lock is released when the returned lock goes out of scope. The
489 /// returned guard also implements the `Write` trait for writing data.
494 /// use std::io::{self, Write};
496 /// fn main() -> io::Result<()> {
497 /// let stdout = io::stdout();
498 /// let mut handle = stdout.lock();
500 /// handle.write_all(b"hello world")?;
505 #[stable(feature = "rust1", since = "1.0.0")]
506 pub fn lock(&self) -> StdoutLock<'_> {
507 StdoutLock { inner: self.inner.lock().unwrap_or_else(|e| e.into_inner()) }
511 #[stable(feature = "std_debug", since = "1.16.0")]
512 impl fmt::Debug for Stdout {
513 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
514 f.pad("Stdout { .. }")
518 #[stable(feature = "rust1", since = "1.0.0")]
519 impl Write for Stdout {
520 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
521 self.lock().write(buf)
523 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
524 self.lock().write_vectored(bufs)
526 fn flush(&mut self) -> io::Result<()> {
529 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
530 self.lock().write_all(buf)
532 fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> io::Result<()> {
533 self.lock().write_fmt(args)
536 #[stable(feature = "rust1", since = "1.0.0")]
537 impl Write for StdoutLock<'_> {
538 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
539 self.inner.borrow_mut().write(buf)
541 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
542 self.inner.borrow_mut().write_vectored(bufs)
544 fn flush(&mut self) -> io::Result<()> {
545 self.inner.borrow_mut().flush()
549 #[stable(feature = "std_debug", since = "1.16.0")]
550 impl fmt::Debug for StdoutLock<'_> {
551 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
552 f.pad("StdoutLock { .. }")
556 /// A handle to the standard error stream of a process.
558 /// For more information, see the [`io::stderr`] method.
560 /// [`io::stderr`]: fn.stderr.html
562 /// ### Note: Windows Portability Consideration
563 /// When operating in a console, the Windows implementation of this stream does not support
564 /// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
566 #[stable(feature = "rust1", since = "1.0.0")]
568 inner: Arc<ReentrantMutex<RefCell<Maybe<StderrRaw>>>>,
571 /// A locked reference to the `Stderr` handle.
573 /// This handle implements the `Write` trait and is constructed via
574 /// the [`Stderr::lock`] method.
576 /// [`Stderr::lock`]: struct.Stderr.html#method.lock
578 /// ### Note: Windows Portability Consideration
579 /// When operating in a console, the Windows implementation of this stream does not support
580 /// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
582 #[stable(feature = "rust1", since = "1.0.0")]
583 pub struct StderrLock<'a> {
584 inner: ReentrantMutexGuard<'a, RefCell<Maybe<StderrRaw>>>,
587 /// Constructs a new handle to the standard error of the current process.
589 /// This handle is not buffered.
591 /// ### Note: Windows Portability Consideration
592 /// When operating in a console, the Windows implementation of this stream does not support
593 /// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
598 /// Using implicit synchronization:
601 /// use std::io::{self, Write};
603 /// fn main() -> io::Result<()> {
604 /// io::stderr().write_all(b"hello world")?;
610 /// Using explicit synchronization:
613 /// use std::io::{self, Write};
615 /// fn main() -> io::Result<()> {
616 /// let stderr = io::stderr();
617 /// let mut handle = stderr.lock();
619 /// handle.write_all(b"hello world")?;
624 #[stable(feature = "rust1", since = "1.0.0")]
625 pub fn stderr() -> Stderr {
626 static INSTANCE: Lazy<ReentrantMutex<RefCell<Maybe<StderrRaw>>>> = Lazy::new();
629 INSTANCE.get(stderr_init).expect("cannot access stderr during shutdown")
633 fn stderr_init() -> Arc<ReentrantMutex<RefCell<Maybe<StderrRaw>>>> {
634 // This must not reentrantly access `INSTANCE`
635 let stderr = match stderr_raw() {
636 Ok(stderr) => Maybe::Real(stderr),
639 Arc::new(ReentrantMutex::new(RefCell::new(stderr)))
644 /// Locks this handle to the standard error stream, returning a writable
647 /// The lock is released when the returned lock goes out of scope. The
648 /// returned guard also implements the `Write` trait for writing data.
653 /// use std::io::{self, Write};
655 /// fn foo() -> io::Result<()> {
656 /// let stderr = io::stderr();
657 /// let mut handle = stderr.lock();
659 /// handle.write_all(b"hello world")?;
664 #[stable(feature = "rust1", since = "1.0.0")]
665 pub fn lock(&self) -> StderrLock<'_> {
666 StderrLock { inner: self.inner.lock().unwrap_or_else(|e| e.into_inner()) }
670 #[stable(feature = "std_debug", since = "1.16.0")]
671 impl fmt::Debug for Stderr {
672 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
673 f.pad("Stderr { .. }")
677 #[stable(feature = "rust1", since = "1.0.0")]
678 impl Write for Stderr {
679 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
680 self.lock().write(buf)
682 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
683 self.lock().write_vectored(bufs)
685 fn flush(&mut self) -> io::Result<()> {
688 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
689 self.lock().write_all(buf)
691 fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> io::Result<()> {
692 self.lock().write_fmt(args)
695 #[stable(feature = "rust1", since = "1.0.0")]
696 impl Write for StderrLock<'_> {
697 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
698 self.inner.borrow_mut().write(buf)
700 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
701 self.inner.borrow_mut().write_vectored(bufs)
703 fn flush(&mut self) -> io::Result<()> {
704 self.inner.borrow_mut().flush()
708 #[stable(feature = "std_debug", since = "1.16.0")]
709 impl fmt::Debug for StderrLock<'_> {
710 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
711 f.pad("StderrLock { .. }")
715 /// Resets the thread-local stderr handle to the specified writer
717 /// This will replace the current thread's stderr handle, returning the old
718 /// handle. All future calls to `panic!` and friends will emit their output to
719 /// this specified handle.
721 /// Note that this does not need to be called for all new threads; the default
722 /// output handle is to the process's stderr stream.
723 #[unstable(feature = "set_stdio",
724 reason = "this function may disappear completely or be replaced \
725 with a more general mechanism",
728 pub fn set_panic(sink: Option<Box<dyn Write + Send>>) -> Option<Box<dyn Write + Send>> {
730 LOCAL_STDERR.with(move |slot| {
731 mem::replace(&mut *slot.borrow_mut(), sink)
732 }).and_then(|mut s| {
738 /// Resets the thread-local stdout handle to the specified writer
740 /// This will replace the current thread's stdout handle, returning the old
741 /// handle. All future calls to `print!` and friends will emit their output to
742 /// this specified handle.
744 /// Note that this does not need to be called for all new threads; the default
745 /// output handle is to the process's stdout stream.
746 #[unstable(feature = "set_stdio",
747 reason = "this function may disappear completely or be replaced \
748 with a more general mechanism",
751 pub fn set_print(sink: Option<Box<dyn Write + Send>>) -> Option<Box<dyn Write + Send>> {
753 LOCAL_STDOUT.with(move |slot| {
754 mem::replace(&mut *slot.borrow_mut(), sink)
755 }).and_then(|mut s| {
761 /// Write `args` to output stream `local_s` if possible, `global_s`
762 /// otherwise. `label` identifies the stream in a panic message.
764 /// This function is used to print error messages, so it takes extra
765 /// care to avoid causing a panic when `local_stream` is unusable.
766 /// For instance, if the TLS key for the local stream is
767 /// already destroyed, or if the local stream is locked by another
768 /// thread, it will just fall back to the global stream.
770 /// However, if the actual I/O causes an error, this function does panic.
772 args: fmt::Arguments<'_>,
773 local_s: &'static LocalKey<RefCell<Option<Box<dyn Write+Send>>>>,
780 let result = local_s.try_with(|s| {
781 if let Ok(mut borrowed) = s.try_borrow_mut() {
782 if let Some(w) = borrowed.as_mut() {
783 return w.write_fmt(args);
786 global_s().write_fmt(args)
787 }).unwrap_or_else(|_| {
788 global_s().write_fmt(args)
791 if let Err(e) = result {
792 panic!("failed printing to {}: {}", label, e);
796 #[unstable(feature = "print_internals",
797 reason = "implementation detail which may disappear or be replaced at any time",
801 pub fn _print(args: fmt::Arguments<'_>) {
802 print_to(args, &LOCAL_STDOUT, stdout, "stdout");
805 #[unstable(feature = "print_internals",
806 reason = "implementation detail which may disappear or be replaced at any time",
810 pub fn _eprint(args: fmt::Arguments<'_>) {
811 print_to(args, &LOCAL_STDERR, stderr, "stderr");
815 pub use realstd::io::{_eprint, _print};
819 use crate::panic::{UnwindSafe, RefUnwindSafe};
824 fn stdout_unwind_safe() {
825 assert_unwind_safe::<Stdout>();
828 fn stdoutlock_unwind_safe() {
829 assert_unwind_safe::<StdoutLock<'_>>();
830 assert_unwind_safe::<StdoutLock<'static>>();
833 fn stderr_unwind_safe() {
834 assert_unwind_safe::<Stderr>();
837 fn stderrlock_unwind_safe() {
838 assert_unwind_safe::<StderrLock<'_>>();
839 assert_unwind_safe::<StderrLock<'static>>();
842 fn assert_unwind_safe<T: UnwindSafe + RefUnwindSafe>() {}
845 #[cfg_attr(target_os = "emscripten", ignore)]
846 fn panic_doesnt_poison() {
855 }).join().unwrap_err();