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};
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 unsafe fn initializer(&self) -> Initializer {
95 impl Write for StdoutRaw {
96 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
100 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
101 self.0.write_vectored(bufs)
104 fn flush(&mut self) -> io::Result<()> {
108 impl Write for StderrRaw {
109 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
113 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
114 self.0.write_vectored(bufs)
117 fn flush(&mut self) -> io::Result<()> {
127 impl<W: io::Write> io::Write for Maybe<W> {
128 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
130 Maybe::Real(ref mut w) => handle_ebadf(w.write(buf), buf.len()),
131 Maybe::Fake => Ok(buf.len()),
135 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
136 let total = bufs.iter().map(|b| b.len()).sum();
138 Maybe::Real(w) => handle_ebadf(w.write_vectored(bufs), total),
139 Maybe::Fake => Ok(total),
143 fn flush(&mut self) -> io::Result<()> {
145 Maybe::Real(ref mut w) => handle_ebadf(w.flush(), ()),
146 Maybe::Fake => Ok(()),
151 impl<R: io::Read> io::Read for Maybe<R> {
152 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
154 Maybe::Real(ref mut r) => handle_ebadf(r.read(buf), 0),
155 Maybe::Fake => Ok(0),
159 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
161 Maybe::Real(r) => handle_ebadf(r.read_vectored(bufs), 0),
162 Maybe::Fake => Ok(0),
167 fn handle_ebadf<T>(r: io::Result<T>, default: T) -> io::Result<T> {
169 Err(ref e) if stdio::is_ebadf(e) => Ok(default),
174 /// A handle to the standard input stream of a process.
176 /// Each handle is a shared reference to a global buffer of input data to this
177 /// process. A handle can be `lock`'d to gain full access to [`BufRead`] methods
178 /// (e.g., `.lines()`). Reads to this handle are otherwise locked with respect
181 /// This handle implements the `Read` trait, but beware that concurrent reads
182 /// of `Stdin` must be executed with care.
184 /// Created by the [`io::stdin`] method.
186 /// [`io::stdin`]: fn.stdin.html
187 /// [`BufRead`]: trait.BufRead.html
189 /// ### Note: Windows Portability Consideration
190 /// When operating in a console, the Windows implementation of this stream does not support
191 /// non-UTF-8 byte sequences. Attempting to read bytes that are not valid UTF-8 will return
193 #[stable(feature = "rust1", since = "1.0.0")]
195 inner: Arc<Mutex<BufReader<Maybe<StdinRaw>>>>,
198 /// A locked reference to the `Stdin` handle.
200 /// This handle implements both the [`Read`] and [`BufRead`] traits, and
201 /// is constructed via the [`Stdin::lock`] method.
203 /// [`Read`]: trait.Read.html
204 /// [`BufRead`]: trait.BufRead.html
205 /// [`Stdin::lock`]: struct.Stdin.html#method.lock
207 /// ### Note: Windows Portability Consideration
208 /// When operating in a console, the Windows implementation of this stream does not support
209 /// non-UTF-8 byte sequences. Attempting to read bytes that are not valid UTF-8 will return
211 #[stable(feature = "rust1", since = "1.0.0")]
212 pub struct StdinLock<'a> {
213 inner: MutexGuard<'a, BufReader<Maybe<StdinRaw>>>,
216 /// Constructs a new handle to the standard input of the current process.
218 /// Each handle returned is a reference to a shared global buffer whose access
219 /// is synchronized via a mutex. If you need more explicit control over
220 /// locking, see the [`Stdin::lock`] method.
222 /// [`Stdin::lock`]: struct.Stdin.html#method.lock
224 /// ### Note: Windows Portability Consideration
225 /// When operating in a console, the Windows implementation of this stream does not support
226 /// non-UTF-8 byte sequences. Attempting to read bytes that are not valid UTF-8 will return
231 /// Using implicit synchronization:
234 /// use std::io::{self, Read};
236 /// fn main() -> io::Result<()> {
237 /// let mut buffer = String::new();
238 /// io::stdin().read_to_string(&mut buffer)?;
243 /// Using explicit synchronization:
246 /// use std::io::{self, Read};
248 /// fn main() -> io::Result<()> {
249 /// let mut buffer = String::new();
250 /// let stdin = io::stdin();
251 /// let mut handle = stdin.lock();
253 /// handle.read_to_string(&mut buffer)?;
257 #[stable(feature = "rust1", since = "1.0.0")]
258 pub fn stdin() -> Stdin {
259 static INSTANCE: Lazy<Mutex<BufReader<Maybe<StdinRaw>>>> = Lazy::new();
261 inner: unsafe { INSTANCE.get(stdin_init).expect("cannot access stdin during shutdown") },
264 fn stdin_init() -> Arc<Mutex<BufReader<Maybe<StdinRaw>>>> {
265 // This must not reentrantly access `INSTANCE`
266 let stdin = match stdin_raw() {
267 Ok(stdin) => Maybe::Real(stdin),
271 Arc::new(Mutex::new(BufReader::with_capacity(stdio::STDIN_BUF_SIZE, stdin)))
276 /// Locks this handle to the standard input stream, returning a readable
279 /// The lock is released when the returned lock goes out of scope. The
280 /// returned guard also implements the [`Read`] and [`BufRead`] traits for
281 /// accessing the underlying data.
283 /// [`Read`]: trait.Read.html
284 /// [`BufRead`]: trait.BufRead.html
289 /// use std::io::{self, Read};
291 /// fn main() -> io::Result<()> {
292 /// let mut buffer = String::new();
293 /// let stdin = io::stdin();
294 /// let mut handle = stdin.lock();
296 /// handle.read_to_string(&mut buffer)?;
300 #[stable(feature = "rust1", since = "1.0.0")]
301 pub fn lock(&self) -> StdinLock<'_> {
302 StdinLock { inner: self.inner.lock().unwrap_or_else(|e| e.into_inner()) }
305 /// Locks this handle and reads a line of input into the specified buffer.
307 /// For detailed semantics of this method, see the documentation on
308 /// [`BufRead::read_line`].
310 /// [`BufRead::read_line`]: trait.BufRead.html#method.read_line
317 /// let mut input = String::new();
318 /// match io::stdin().read_line(&mut input) {
320 /// println!("{} bytes read", n);
321 /// println!("{}", input);
323 /// Err(error) => println!("error: {}", error),
327 /// You can run the example one of two ways:
329 /// - Pipe some text to it, e.g., `printf foo | path/to/executable`
330 /// - Give it text interactively by running the executable directly,
331 /// in which case it will wait for the Enter key to be pressed before
333 #[stable(feature = "rust1", since = "1.0.0")]
334 pub fn read_line(&self, buf: &mut String) -> io::Result<usize> {
335 self.lock().read_line(buf)
339 #[stable(feature = "std_debug", since = "1.16.0")]
340 impl fmt::Debug for Stdin {
341 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
342 f.pad("Stdin { .. }")
346 #[stable(feature = "rust1", since = "1.0.0")]
347 impl Read for Stdin {
348 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
349 self.lock().read(buf)
351 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
352 self.lock().read_vectored(bufs)
355 unsafe fn initializer(&self) -> Initializer {
358 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
359 self.lock().read_to_end(buf)
361 fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
362 self.lock().read_to_string(buf)
364 fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
365 self.lock().read_exact(buf)
369 #[stable(feature = "rust1", since = "1.0.0")]
370 impl Read for StdinLock<'_> {
371 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
375 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
376 self.inner.read_vectored(bufs)
380 unsafe fn initializer(&self) -> Initializer {
385 #[stable(feature = "rust1", since = "1.0.0")]
386 impl BufRead for StdinLock<'_> {
387 fn fill_buf(&mut self) -> io::Result<&[u8]> {
388 self.inner.fill_buf()
390 fn consume(&mut self, n: usize) {
391 self.inner.consume(n)
395 #[stable(feature = "std_debug", since = "1.16.0")]
396 impl fmt::Debug for StdinLock<'_> {
397 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
398 f.pad("StdinLock { .. }")
402 /// A handle to the global standard output stream of the current process.
404 /// Each handle shares a global buffer of data to be written to the standard
405 /// output stream. Access is also synchronized via a lock and explicit control
406 /// over locking is available via the [`lock`] method.
408 /// Created by the [`io::stdout`] method.
410 /// ### Note: Windows Portability Consideration
411 /// When operating in a console, the Windows implementation of this stream does not support
412 /// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
415 /// [`lock`]: #method.lock
416 /// [`io::stdout`]: fn.stdout.html
417 #[stable(feature = "rust1", since = "1.0.0")]
419 // FIXME: this should be LineWriter or BufWriter depending on the state of
420 // stdout (tty or not). Note that if this is not line buffered it
421 // should also flush-on-panic or some form of flush-on-abort.
422 inner: Arc<ReentrantMutex<RefCell<LineWriter<Maybe<StdoutRaw>>>>>,
425 /// A locked reference to the `Stdout` handle.
427 /// This handle implements the [`Write`] trait, and is constructed via
428 /// the [`Stdout::lock`] method.
430 /// ### Note: Windows Portability Consideration
431 /// When operating in a console, the Windows implementation of this stream does not support
432 /// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
435 /// [`Write`]: trait.Write.html
436 /// [`Stdout::lock`]: struct.Stdout.html#method.lock
437 #[stable(feature = "rust1", since = "1.0.0")]
438 pub struct StdoutLock<'a> {
439 inner: ReentrantMutexGuard<'a, RefCell<LineWriter<Maybe<StdoutRaw>>>>,
442 /// Constructs a new handle to the standard output of the current process.
444 /// Each handle returned is a reference to a shared global buffer whose access
445 /// is synchronized via a mutex. If you need more explicit control over
446 /// locking, see the [`Stdout::lock`] method.
448 /// [`Stdout::lock`]: struct.Stdout.html#method.lock
450 /// ### Note: Windows Portability Consideration
451 /// When operating in a console, the Windows implementation of this stream does not support
452 /// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
457 /// Using implicit synchronization:
460 /// use std::io::{self, Write};
462 /// fn main() -> io::Result<()> {
463 /// io::stdout().write_all(b"hello world")?;
469 /// Using explicit synchronization:
472 /// use std::io::{self, Write};
474 /// fn main() -> io::Result<()> {
475 /// let stdout = io::stdout();
476 /// let mut handle = stdout.lock();
478 /// handle.write_all(b"hello world")?;
483 #[stable(feature = "rust1", since = "1.0.0")]
484 pub fn stdout() -> Stdout {
485 static INSTANCE: Lazy<ReentrantMutex<RefCell<LineWriter<Maybe<StdoutRaw>>>>> = Lazy::new();
487 inner: unsafe { INSTANCE.get(stdout_init).expect("cannot access stdout during shutdown") },
490 fn stdout_init() -> Arc<ReentrantMutex<RefCell<LineWriter<Maybe<StdoutRaw>>>>> {
491 // This must not reentrantly access `INSTANCE`
492 let stdout = match stdout_raw() {
493 Ok(stdout) => Maybe::Real(stdout),
496 Arc::new(ReentrantMutex::new(RefCell::new(LineWriter::new(stdout))))
501 /// Locks this handle to the standard output stream, returning a writable
504 /// The lock is released when the returned lock goes out of scope. The
505 /// returned guard also implements the `Write` trait for writing data.
510 /// use std::io::{self, Write};
512 /// fn main() -> io::Result<()> {
513 /// let stdout = io::stdout();
514 /// let mut handle = stdout.lock();
516 /// handle.write_all(b"hello world")?;
521 #[stable(feature = "rust1", since = "1.0.0")]
522 pub fn lock(&self) -> StdoutLock<'_> {
523 StdoutLock { inner: self.inner.lock().unwrap_or_else(|e| e.into_inner()) }
527 #[stable(feature = "std_debug", since = "1.16.0")]
528 impl fmt::Debug for Stdout {
529 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
530 f.pad("Stdout { .. }")
534 #[stable(feature = "rust1", since = "1.0.0")]
535 impl Write for Stdout {
536 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
537 self.lock().write(buf)
539 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
540 self.lock().write_vectored(bufs)
542 fn flush(&mut self) -> io::Result<()> {
545 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
546 self.lock().write_all(buf)
548 fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> io::Result<()> {
549 self.lock().write_fmt(args)
552 #[stable(feature = "rust1", since = "1.0.0")]
553 impl Write for StdoutLock<'_> {
554 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
555 self.inner.borrow_mut().write(buf)
557 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
558 self.inner.borrow_mut().write_vectored(bufs)
560 fn flush(&mut self) -> io::Result<()> {
561 self.inner.borrow_mut().flush()
565 #[stable(feature = "std_debug", since = "1.16.0")]
566 impl fmt::Debug for StdoutLock<'_> {
567 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
568 f.pad("StdoutLock { .. }")
572 /// A handle to the standard error stream of a process.
574 /// For more information, see the [`io::stderr`] method.
576 /// [`io::stderr`]: fn.stderr.html
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")]
584 inner: Arc<ReentrantMutex<RefCell<Maybe<StderrRaw>>>>,
587 /// A locked reference to the `Stderr` handle.
589 /// This handle implements the `Write` trait and is constructed via
590 /// the [`Stderr::lock`] method.
592 /// [`Stderr::lock`]: struct.Stderr.html#method.lock
594 /// ### Note: Windows Portability Consideration
595 /// When operating in a console, the Windows implementation of this stream does not support
596 /// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
598 #[stable(feature = "rust1", since = "1.0.0")]
599 pub struct StderrLock<'a> {
600 inner: ReentrantMutexGuard<'a, RefCell<Maybe<StderrRaw>>>,
603 /// Constructs a new handle to the standard error of the current process.
605 /// This handle is not buffered.
607 /// ### Note: Windows Portability Consideration
608 /// When operating in a console, the Windows implementation of this stream does not support
609 /// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
614 /// Using implicit synchronization:
617 /// use std::io::{self, Write};
619 /// fn main() -> io::Result<()> {
620 /// io::stderr().write_all(b"hello world")?;
626 /// Using explicit synchronization:
629 /// use std::io::{self, Write};
631 /// fn main() -> io::Result<()> {
632 /// let stderr = io::stderr();
633 /// let mut handle = stderr.lock();
635 /// handle.write_all(b"hello world")?;
640 #[stable(feature = "rust1", since = "1.0.0")]
641 pub fn stderr() -> Stderr {
642 static INSTANCE: Lazy<ReentrantMutex<RefCell<Maybe<StderrRaw>>>> = Lazy::new();
644 inner: unsafe { INSTANCE.get(stderr_init).expect("cannot access stderr during shutdown") },
647 fn stderr_init() -> Arc<ReentrantMutex<RefCell<Maybe<StderrRaw>>>> {
648 // This must not reentrantly access `INSTANCE`
649 let stderr = match stderr_raw() {
650 Ok(stderr) => Maybe::Real(stderr),
653 Arc::new(ReentrantMutex::new(RefCell::new(stderr)))
658 /// Locks this handle to the standard error stream, returning a writable
661 /// The lock is released when the returned lock goes out of scope. The
662 /// returned guard also implements the `Write` trait for writing data.
667 /// use std::io::{self, Write};
669 /// fn foo() -> io::Result<()> {
670 /// let stderr = io::stderr();
671 /// let mut handle = stderr.lock();
673 /// handle.write_all(b"hello world")?;
678 #[stable(feature = "rust1", since = "1.0.0")]
679 pub fn lock(&self) -> StderrLock<'_> {
680 StderrLock { inner: self.inner.lock().unwrap_or_else(|e| e.into_inner()) }
684 #[stable(feature = "std_debug", since = "1.16.0")]
685 impl fmt::Debug for Stderr {
686 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
687 f.pad("Stderr { .. }")
691 #[stable(feature = "rust1", since = "1.0.0")]
692 impl Write for Stderr {
693 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
694 self.lock().write(buf)
696 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
697 self.lock().write_vectored(bufs)
699 fn flush(&mut self) -> io::Result<()> {
702 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
703 self.lock().write_all(buf)
705 fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> io::Result<()> {
706 self.lock().write_fmt(args)
709 #[stable(feature = "rust1", since = "1.0.0")]
710 impl Write for StderrLock<'_> {
711 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
712 self.inner.borrow_mut().write(buf)
714 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
715 self.inner.borrow_mut().write_vectored(bufs)
717 fn flush(&mut self) -> io::Result<()> {
718 self.inner.borrow_mut().flush()
722 #[stable(feature = "std_debug", since = "1.16.0")]
723 impl fmt::Debug for StderrLock<'_> {
724 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
725 f.pad("StderrLock { .. }")
729 /// Resets the thread-local stderr handle to the specified writer
731 /// This will replace the current thread's stderr handle, returning the old
732 /// handle. All future calls to `panic!` and friends will emit their output to
733 /// this specified handle.
735 /// Note that this does not need to be called for all new threads; the default
736 /// output handle is to the process's stderr stream.
738 feature = "set_stdio",
739 reason = "this function may disappear completely or be replaced \
740 with a more general mechanism",
744 pub fn set_panic(sink: Option<Box<dyn Write + Send>>) -> Option<Box<dyn Write + Send>> {
746 LOCAL_STDERR.with(move |slot| mem::replace(&mut *slot.borrow_mut(), sink)).and_then(|mut s| {
752 /// Resets the thread-local stdout handle to the specified writer
754 /// This will replace the current thread's stdout handle, returning the old
755 /// handle. All future calls to `print!` and friends will emit their output to
756 /// this specified handle.
758 /// Note that this does not need to be called for all new threads; the default
759 /// output handle is to the process's stdout stream.
761 feature = "set_stdio",
762 reason = "this function may disappear completely or be replaced \
763 with a more general mechanism",
767 pub fn set_print(sink: Option<Box<dyn Write + Send>>) -> Option<Box<dyn Write + Send>> {
769 LOCAL_STDOUT.with(move |slot| mem::replace(&mut *slot.borrow_mut(), sink)).and_then(|mut s| {
775 /// Write `args` to output stream `local_s` if possible, `global_s`
776 /// otherwise. `label` identifies the stream in a panic message.
778 /// This function is used to print error messages, so it takes extra
779 /// care to avoid causing a panic when `local_s` is unusable.
780 /// For instance, if the TLS key for the local stream is
781 /// already destroyed, or if the local stream is locked by another
782 /// thread, it will just fall back to the global stream.
784 /// However, if the actual I/O causes an error, this function does panic.
786 args: fmt::Arguments<'_>,
787 local_s: &'static LocalKey<RefCell<Option<Box<dyn Write + Send>>>>,
795 if let Ok(mut borrowed) = s.try_borrow_mut() {
796 if let Some(w) = borrowed.as_mut() {
797 return w.write_fmt(args);
800 global_s().write_fmt(args)
802 .unwrap_or_else(|_| global_s().write_fmt(args));
804 if let Err(e) = result {
805 panic!("failed printing to {}: {}", label, e);
810 feature = "print_internals",
811 reason = "implementation detail which may disappear or be replaced at any time",
816 pub fn _print(args: fmt::Arguments<'_>) {
817 print_to(args, &LOCAL_STDOUT, stdout, "stdout");
821 feature = "print_internals",
822 reason = "implementation detail which may disappear or be replaced at any time",
827 pub fn _eprint(args: fmt::Arguments<'_>) {
828 print_to(args, &LOCAL_STDERR, stderr, "stderr");
832 pub use realstd::io::{_eprint, _print};
837 use crate::panic::{RefUnwindSafe, UnwindSafe};
841 fn stdout_unwind_safe() {
842 assert_unwind_safe::<Stdout>();
845 fn stdoutlock_unwind_safe() {
846 assert_unwind_safe::<StdoutLock<'_>>();
847 assert_unwind_safe::<StdoutLock<'static>>();
850 fn stderr_unwind_safe() {
851 assert_unwind_safe::<Stderr>();
854 fn stderrlock_unwind_safe() {
855 assert_unwind_safe::<StderrLock<'_>>();
856 assert_unwind_safe::<StderrLock<'static>>();
859 fn assert_unwind_safe<T: UnwindSafe + RefUnwindSafe>() {}
862 #[cfg_attr(target_os = "emscripten", ignore)]
863 fn panic_doesnt_poison() {