1 #![cfg_attr(test, allow(unused))]
3 use crate::io::prelude::*;
5 use crate::cell::RefCell;
7 use crate::io::lazy::Lazy;
8 use crate::io::{self, BufReader, Initializer, IoSlice, IoSliceMut, LineWriter};
9 use crate::sync::{Arc, Mutex, MutexGuard, Once};
10 use crate::sys::stdio;
11 use crate::sys_common::remutex::{ReentrantMutex, ReentrantMutexGuard};
12 use crate::thread::LocalKey;
15 /// Stdout used by print! and println! macros
16 static LOCAL_STDOUT: RefCell<Option<Box<dyn Write + Send>>> = {
22 /// Stderr used by eprint! and eprintln! macros, and panics
23 static LOCAL_STDERR: RefCell<Option<Box<dyn Write + Send>>> = {
28 /// A handle to a raw instance of the standard input stream of this process.
30 /// This handle is not synchronized or buffered in any fashion. Constructed via
31 /// the `std::io::stdio::stdin_raw` function.
32 struct StdinRaw(stdio::Stdin);
34 /// A handle to a raw instance of the standard output stream of this process.
36 /// This handle is not synchronized or buffered in any fashion. Constructed via
37 /// the `std::io::stdio::stdout_raw` function.
38 struct StdoutRaw(stdio::Stdout);
40 /// A handle to a raw instance of the standard output stream of this process.
42 /// This handle is not synchronized or buffered in any fashion. Constructed via
43 /// the `std::io::stdio::stderr_raw` function.
44 struct StderrRaw(stdio::Stderr);
46 /// Constructs a new raw handle to the standard input of this process.
48 /// The returned handle does not interact with any other handles created nor
49 /// handles returned by `std::io::stdin`. Data buffered by the `std::io::stdin`
50 /// handles is **not** available to raw handles returned from this function.
52 /// The returned handle has no external synchronization or buffering.
53 fn stdin_raw() -> io::Result<StdinRaw> {
54 stdio::Stdin::new().map(StdinRaw)
57 /// Constructs a new raw handle to the standard output stream of this process.
59 /// The returned handle does not interact with any other handles created nor
60 /// handles returned by `std::io::stdout`. Note that data is buffered by the
61 /// `std::io::stdout` handles so writes which happen via this raw handle may
62 /// appear before previous writes.
64 /// The returned handle has no external synchronization or buffering layered on
66 fn stdout_raw() -> io::Result<StdoutRaw> {
67 stdio::Stdout::new().map(StdoutRaw)
70 /// Constructs a new raw handle to the standard error stream of this process.
72 /// The returned handle does not interact with any other handles created nor
73 /// handles returned by `std::io::stderr`.
75 /// The returned handle has no external synchronization or buffering layered on
77 fn stderr_raw() -> io::Result<StderrRaw> {
78 stdio::Stderr::new().map(StderrRaw)
81 impl Read for StdinRaw {
82 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
86 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
87 self.0.read_vectored(bufs)
91 fn is_read_vectored(&self) -> bool {
92 self.0.is_read_vectored()
96 unsafe fn initializer(&self) -> Initializer {
100 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
101 self.0.read_to_end(buf)
104 fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
105 self.0.read_to_string(buf)
108 fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
109 self.0.read_exact(buf)
113 impl Write for StdoutRaw {
114 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
118 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
119 self.0.write_vectored(bufs)
123 fn is_write_vectored(&self) -> bool {
124 self.0.is_write_vectored()
127 fn flush(&mut self) -> io::Result<()> {
131 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
132 self.0.write_all(buf)
135 fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> {
136 self.0.write_all_vectored(bufs)
139 fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> io::Result<()> {
140 self.0.write_fmt(fmt)
144 impl Write for StderrRaw {
145 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
149 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
150 self.0.write_vectored(bufs)
154 fn is_write_vectored(&self) -> bool {
155 self.0.is_write_vectored()
158 fn flush(&mut self) -> io::Result<()> {
162 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
163 self.0.write_all(buf)
166 fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> {
167 self.0.write_all_vectored(bufs)
170 fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> io::Result<()> {
171 self.0.write_fmt(fmt)
180 impl<W: io::Write> io::Write for Maybe<W> {
181 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
183 Maybe::Real(ref mut w) => handle_ebadf(w.write(buf), buf.len()),
184 Maybe::Fake => Ok(buf.len()),
188 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
189 let total = bufs.iter().map(|b| b.len()).sum();
191 Maybe::Real(w) => handle_ebadf(w.write_vectored(bufs), total),
192 Maybe::Fake => Ok(total),
197 fn is_write_vectored(&self) -> bool {
199 Maybe::Real(w) => w.is_write_vectored(),
204 fn flush(&mut self) -> io::Result<()> {
206 Maybe::Real(ref mut w) => handle_ebadf(w.flush(), ()),
207 Maybe::Fake => Ok(()),
212 impl<R: io::Read> io::Read for Maybe<R> {
213 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
215 Maybe::Real(ref mut r) => handle_ebadf(r.read(buf), 0),
216 Maybe::Fake => Ok(0),
220 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
222 Maybe::Real(r) => handle_ebadf(r.read_vectored(bufs), 0),
223 Maybe::Fake => Ok(0),
228 fn is_read_vectored(&self) -> bool {
230 Maybe::Real(w) => w.is_read_vectored(),
236 fn handle_ebadf<T>(r: io::Result<T>, default: T) -> io::Result<T> {
238 Err(ref e) if stdio::is_ebadf(e) => Ok(default),
243 /// A handle to the standard input stream of a process.
245 /// Each handle is a shared reference to a global buffer of input data to this
246 /// process. A handle can be `lock`'d to gain full access to [`BufRead`] methods
247 /// (e.g., `.lines()`). Reads to this handle are otherwise locked with respect
250 /// This handle implements the `Read` trait, but beware that concurrent reads
251 /// of `Stdin` must be executed with care.
253 /// Created by the [`io::stdin`] method.
255 /// [`io::stdin`]: fn.stdin.html
256 /// [`BufRead`]: trait.BufRead.html
258 /// ### Note: Windows Portability Consideration
260 /// When operating in a console, the Windows implementation of this stream does not support
261 /// non-UTF-8 byte sequences. Attempting to read bytes that are not valid UTF-8 will return
267 /// use std::io::{self, Read};
269 /// fn main() -> io::Result<()> {
270 /// let mut buffer = String::new();
271 /// let mut stdin = io::stdin(); // We get `Stdin` here.
272 /// stdin.read_to_string(&mut buffer)?;
276 #[stable(feature = "rust1", since = "1.0.0")]
278 inner: Arc<Mutex<BufReader<Maybe<StdinRaw>>>>,
281 /// A locked reference to the `Stdin` handle.
283 /// This handle implements both the [`Read`] and [`BufRead`] traits, and
284 /// is constructed via the [`Stdin::lock`] method.
286 /// [`Read`]: trait.Read.html
287 /// [`BufRead`]: trait.BufRead.html
288 /// [`Stdin::lock`]: struct.Stdin.html#method.lock
290 /// ### Note: Windows Portability Consideration
292 /// When operating in a console, the Windows implementation of this stream does not support
293 /// non-UTF-8 byte sequences. Attempting to read bytes that are not valid UTF-8 will return
299 /// use std::io::{self, Read};
301 /// fn main() -> io::Result<()> {
302 /// let mut buffer = String::new();
303 /// let stdin = io::stdin(); // We get `Stdin` here.
305 /// let mut stdin_lock = stdin.lock(); // We get `StdinLock` here.
306 /// stdin_lock.read_to_string(&mut buffer)?;
307 /// } // `StdinLock` is dropped here.
311 #[stable(feature = "rust1", since = "1.0.0")]
312 pub struct StdinLock<'a> {
313 inner: MutexGuard<'a, BufReader<Maybe<StdinRaw>>>,
316 /// Constructs a new handle to the standard input of the current process.
318 /// Each handle returned is a reference to a shared global buffer whose access
319 /// is synchronized via a mutex. If you need more explicit control over
320 /// locking, see the [`Stdin::lock`] method.
322 /// [`Stdin::lock`]: struct.Stdin.html#method.lock
324 /// ### Note: Windows Portability Consideration
325 /// When operating in a console, the Windows implementation of this stream does not support
326 /// non-UTF-8 byte sequences. Attempting to read bytes that are not valid UTF-8 will return
331 /// Using implicit synchronization:
334 /// use std::io::{self, Read};
336 /// fn main() -> io::Result<()> {
337 /// let mut buffer = String::new();
338 /// io::stdin().read_to_string(&mut buffer)?;
343 /// Using explicit synchronization:
346 /// use std::io::{self, Read};
348 /// fn main() -> io::Result<()> {
349 /// let mut buffer = String::new();
350 /// let stdin = io::stdin();
351 /// let mut handle = stdin.lock();
353 /// handle.read_to_string(&mut buffer)?;
357 #[stable(feature = "rust1", since = "1.0.0")]
358 pub fn stdin() -> Stdin {
359 static INSTANCE: Lazy<Mutex<BufReader<Maybe<StdinRaw>>>> = Lazy::new();
361 inner: unsafe { INSTANCE.get(stdin_init).expect("cannot access stdin during shutdown") },
364 fn stdin_init() -> Arc<Mutex<BufReader<Maybe<StdinRaw>>>> {
365 // This must not reentrantly access `INSTANCE`
366 let stdin = match stdin_raw() {
367 Ok(stdin) => Maybe::Real(stdin),
371 Arc::new(Mutex::new(BufReader::with_capacity(stdio::STDIN_BUF_SIZE, stdin)))
376 /// Locks this handle to the standard input stream, returning a readable
379 /// The lock is released when the returned lock goes out of scope. The
380 /// returned guard also implements the [`Read`] and [`BufRead`] traits for
381 /// accessing the underlying data.
383 /// [`Read`]: trait.Read.html
384 /// [`BufRead`]: trait.BufRead.html
389 /// use std::io::{self, Read};
391 /// fn main() -> io::Result<()> {
392 /// let mut buffer = String::new();
393 /// let stdin = io::stdin();
394 /// let mut handle = stdin.lock();
396 /// handle.read_to_string(&mut buffer)?;
400 #[stable(feature = "rust1", since = "1.0.0")]
401 pub fn lock(&self) -> StdinLock<'_> {
402 StdinLock { inner: self.inner.lock().unwrap_or_else(|e| e.into_inner()) }
405 /// Locks this handle and reads a line of input, appending it to the specified buffer.
407 /// For detailed semantics of this method, see the documentation on
408 /// [`BufRead::read_line`].
410 /// [`BufRead::read_line`]: trait.BufRead.html#method.read_line
417 /// let mut input = String::new();
418 /// match io::stdin().read_line(&mut input) {
420 /// println!("{} bytes read", n);
421 /// println!("{}", input);
423 /// Err(error) => println!("error: {}", error),
427 /// You can run the example one of two ways:
429 /// - Pipe some text to it, e.g., `printf foo | path/to/executable`
430 /// - Give it text interactively by running the executable directly,
431 /// in which case it will wait for the Enter key to be pressed before
433 #[stable(feature = "rust1", since = "1.0.0")]
434 pub fn read_line(&self, buf: &mut String) -> io::Result<usize> {
435 self.lock().read_line(buf)
439 #[stable(feature = "std_debug", since = "1.16.0")]
440 impl fmt::Debug for Stdin {
441 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
442 f.pad("Stdin { .. }")
446 #[stable(feature = "rust1", since = "1.0.0")]
447 impl Read for Stdin {
448 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
449 self.lock().read(buf)
451 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
452 self.lock().read_vectored(bufs)
455 fn is_read_vectored(&self) -> bool {
456 self.lock().is_read_vectored()
459 unsafe fn initializer(&self) -> Initializer {
462 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
463 self.lock().read_to_end(buf)
465 fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
466 self.lock().read_to_string(buf)
468 fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
469 self.lock().read_exact(buf)
473 #[stable(feature = "rust1", since = "1.0.0")]
474 impl Read for StdinLock<'_> {
475 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
479 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
480 self.inner.read_vectored(bufs)
484 fn is_read_vectored(&self) -> bool {
485 self.inner.is_read_vectored()
489 unsafe fn initializer(&self) -> Initializer {
493 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
494 self.inner.read_to_end(buf)
497 fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
498 self.inner.read_to_string(buf)
501 fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
502 self.inner.read_exact(buf)
506 #[stable(feature = "rust1", since = "1.0.0")]
507 impl BufRead for StdinLock<'_> {
508 fn fill_buf(&mut self) -> io::Result<&[u8]> {
509 self.inner.fill_buf()
512 fn consume(&mut self, n: usize) {
513 self.inner.consume(n)
516 fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> io::Result<usize> {
517 self.inner.read_until(byte, buf)
520 fn read_line(&mut self, buf: &mut String) -> io::Result<usize> {
521 self.inner.read_line(buf)
525 #[stable(feature = "std_debug", since = "1.16.0")]
526 impl fmt::Debug for StdinLock<'_> {
527 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
528 f.pad("StdinLock { .. }")
532 /// A handle to the global standard output stream of the current process.
534 /// Each handle shares a global buffer of data to be written to the standard
535 /// output stream. Access is also synchronized via a lock and explicit control
536 /// over locking is available via the [`lock`] method.
538 /// Created by the [`io::stdout`] method.
540 /// ### Note: Windows Portability Consideration
541 /// When operating in a console, the Windows implementation of this stream does not support
542 /// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
545 /// [`lock`]: #method.lock
546 /// [`io::stdout`]: fn.stdout.html
547 #[stable(feature = "rust1", since = "1.0.0")]
549 // FIXME: this should be LineWriter or BufWriter depending on the state of
550 // stdout (tty or not). Note that if this is not line buffered it
551 // should also flush-on-panic or some form of flush-on-abort.
552 inner: Arc<ReentrantMutex<RefCell<LineWriter<Maybe<StdoutRaw>>>>>,
555 /// A locked reference to the `Stdout` handle.
557 /// This handle implements the [`Write`] trait, and is constructed via
558 /// the [`Stdout::lock`] method.
560 /// ### Note: Windows Portability Consideration
561 /// When operating in a console, the Windows implementation of this stream does not support
562 /// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
565 /// [`Write`]: trait.Write.html
566 /// [`Stdout::lock`]: struct.Stdout.html#method.lock
567 #[stable(feature = "rust1", since = "1.0.0")]
568 pub struct StdoutLock<'a> {
569 inner: ReentrantMutexGuard<'a, RefCell<LineWriter<Maybe<StdoutRaw>>>>,
572 /// Constructs a new handle to the standard output of the current process.
574 /// Each handle returned is a reference to a shared global buffer whose access
575 /// is synchronized via a mutex. If you need more explicit control over
576 /// locking, see the [`Stdout::lock`] method.
578 /// [`Stdout::lock`]: struct.Stdout.html#method.lock
580 /// ### Note: Windows Portability Consideration
581 /// When operating in a console, the Windows implementation of this stream does not support
582 /// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
587 /// Using implicit synchronization:
590 /// use std::io::{self, Write};
592 /// fn main() -> io::Result<()> {
593 /// io::stdout().write_all(b"hello world")?;
599 /// Using explicit synchronization:
602 /// use std::io::{self, Write};
604 /// fn main() -> io::Result<()> {
605 /// let stdout = io::stdout();
606 /// let mut handle = stdout.lock();
608 /// handle.write_all(b"hello world")?;
613 #[stable(feature = "rust1", since = "1.0.0")]
614 pub fn stdout() -> Stdout {
615 static INSTANCE: Lazy<ReentrantMutex<RefCell<LineWriter<Maybe<StdoutRaw>>>>> = Lazy::new();
617 inner: unsafe { INSTANCE.get(stdout_init).expect("cannot access stdout during shutdown") },
620 fn stdout_init() -> Arc<ReentrantMutex<RefCell<LineWriter<Maybe<StdoutRaw>>>>> {
621 // This must not reentrantly access `INSTANCE`
622 let stdout = match stdout_raw() {
623 Ok(stdout) => Maybe::Real(stdout),
627 let ret = Arc::new(ReentrantMutex::new(RefCell::new(LineWriter::new(stdout))));
635 /// Locks this handle to the standard output stream, returning a writable
638 /// The lock is released when the returned lock goes out of scope. The
639 /// returned guard also implements the `Write` trait for writing data.
644 /// use std::io::{self, Write};
646 /// fn main() -> io::Result<()> {
647 /// let stdout = io::stdout();
648 /// let mut handle = stdout.lock();
650 /// handle.write_all(b"hello world")?;
655 #[stable(feature = "rust1", since = "1.0.0")]
656 pub fn lock(&self) -> StdoutLock<'_> {
657 StdoutLock { inner: self.inner.lock() }
661 #[stable(feature = "std_debug", since = "1.16.0")]
662 impl fmt::Debug for Stdout {
663 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
664 f.pad("Stdout { .. }")
668 #[stable(feature = "rust1", since = "1.0.0")]
669 impl Write for Stdout {
670 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
671 self.lock().write(buf)
673 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
674 self.lock().write_vectored(bufs)
677 fn is_write_vectored(&self) -> bool {
678 self.lock().is_write_vectored()
680 fn flush(&mut self) -> io::Result<()> {
683 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
684 self.lock().write_all(buf)
686 fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> {
687 self.lock().write_all_vectored(bufs)
689 fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> io::Result<()> {
690 self.lock().write_fmt(args)
693 #[stable(feature = "rust1", since = "1.0.0")]
694 impl Write for StdoutLock<'_> {
695 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
696 self.inner.borrow_mut().write(buf)
698 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
699 self.inner.borrow_mut().write_vectored(bufs)
702 fn is_write_vectored(&self) -> bool {
703 self.inner.borrow_mut().is_write_vectored()
705 fn flush(&mut self) -> io::Result<()> {
706 self.inner.borrow_mut().flush()
708 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
709 self.inner.borrow_mut().write_all(buf)
711 fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> {
712 self.inner.borrow_mut().write_all_vectored(bufs)
716 #[stable(feature = "std_debug", since = "1.16.0")]
717 impl fmt::Debug for StdoutLock<'_> {
718 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
719 f.pad("StdoutLock { .. }")
723 /// A handle to the standard error stream of a process.
725 /// For more information, see the [`io::stderr`] method.
727 /// [`io::stderr`]: fn.stderr.html
729 /// ### Note: Windows Portability Consideration
730 /// When operating in a console, the Windows implementation of this stream does not support
731 /// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
733 #[stable(feature = "rust1", since = "1.0.0")]
735 inner: &'static ReentrantMutex<RefCell<Maybe<StderrRaw>>>,
738 /// A locked reference to the `Stderr` handle.
740 /// This handle implements the `Write` trait and is constructed via
741 /// the [`Stderr::lock`] method.
743 /// [`Stderr::lock`]: struct.Stderr.html#method.lock
745 /// ### Note: Windows Portability Consideration
746 /// When operating in a console, the Windows implementation of this stream does not support
747 /// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
749 #[stable(feature = "rust1", since = "1.0.0")]
750 pub struct StderrLock<'a> {
751 inner: ReentrantMutexGuard<'a, RefCell<Maybe<StderrRaw>>>,
754 /// Constructs a new handle to the standard error of the current process.
756 /// This handle is not buffered.
758 /// ### Note: Windows Portability Consideration
759 /// When operating in a console, the Windows implementation of this stream does not support
760 /// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
765 /// Using implicit synchronization:
768 /// use std::io::{self, Write};
770 /// fn main() -> io::Result<()> {
771 /// io::stderr().write_all(b"hello world")?;
777 /// Using explicit synchronization:
780 /// use std::io::{self, Write};
782 /// fn main() -> io::Result<()> {
783 /// let stderr = io::stderr();
784 /// let mut handle = stderr.lock();
786 /// handle.write_all(b"hello world")?;
791 #[stable(feature = "rust1", since = "1.0.0")]
792 pub fn stderr() -> Stderr {
793 // Note that unlike `stdout()` we don't use `Lazy` here which registers a
794 // destructor. Stderr is not buffered nor does the `stderr_raw` type consume
795 // any owned resources, so there's no need to run any destructors at some
796 // point in the future.
798 // This has the added benefit of allowing `stderr` to be usable during
799 // process shutdown as well!
800 static INSTANCE: ReentrantMutex<RefCell<Maybe<StderrRaw>>> =
801 unsafe { ReentrantMutex::new(RefCell::new(Maybe::Fake)) };
803 // When accessing stderr we need one-time initialization of the reentrant
804 // mutex, followed by one-time detection of whether we actually have a
805 // stderr handle or not. Afterwards we can just always use the now-filled-in
807 static INIT: Once = Once::new();
808 INIT.call_once(|| unsafe {
810 if let Ok(stderr) = stderr_raw() {
811 *INSTANCE.lock().borrow_mut() = Maybe::Real(stderr);
814 Stderr { inner: &INSTANCE }
818 /// Locks this handle to the standard error stream, returning a writable
821 /// The lock is released when the returned lock goes out of scope. The
822 /// returned guard also implements the `Write` trait for writing data.
827 /// use std::io::{self, Write};
829 /// fn foo() -> io::Result<()> {
830 /// let stderr = io::stderr();
831 /// let mut handle = stderr.lock();
833 /// handle.write_all(b"hello world")?;
838 #[stable(feature = "rust1", since = "1.0.0")]
839 pub fn lock(&self) -> StderrLock<'_> {
840 StderrLock { inner: self.inner.lock() }
844 #[stable(feature = "std_debug", since = "1.16.0")]
845 impl fmt::Debug for Stderr {
846 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
847 f.pad("Stderr { .. }")
851 #[stable(feature = "rust1", since = "1.0.0")]
852 impl Write for Stderr {
853 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
854 self.lock().write(buf)
856 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
857 self.lock().write_vectored(bufs)
860 fn is_write_vectored(&self) -> bool {
861 self.lock().is_write_vectored()
863 fn flush(&mut self) -> io::Result<()> {
866 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
867 self.lock().write_all(buf)
869 fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> {
870 self.lock().write_all_vectored(bufs)
872 fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> io::Result<()> {
873 self.lock().write_fmt(args)
876 #[stable(feature = "rust1", since = "1.0.0")]
877 impl Write for StderrLock<'_> {
878 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
879 self.inner.borrow_mut().write(buf)
881 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
882 self.inner.borrow_mut().write_vectored(bufs)
885 fn is_write_vectored(&self) -> bool {
886 self.inner.borrow_mut().is_write_vectored()
888 fn flush(&mut self) -> io::Result<()> {
889 self.inner.borrow_mut().flush()
891 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
892 self.inner.borrow_mut().write_all(buf)
894 fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> {
895 self.inner.borrow_mut().write_all_vectored(bufs)
899 #[stable(feature = "std_debug", since = "1.16.0")]
900 impl fmt::Debug for StderrLock<'_> {
901 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
902 f.pad("StderrLock { .. }")
906 /// Resets the thread-local stderr handle to the specified writer
908 /// This will replace the current thread's stderr handle, returning the old
909 /// handle. All future calls to `panic!` and friends will emit their output to
910 /// this specified handle.
912 /// Note that this does not need to be called for all new threads; the default
913 /// output handle is to the process's stderr stream.
915 feature = "set_stdio",
916 reason = "this function may disappear completely or be replaced \
917 with a more general mechanism",
921 pub fn set_panic(sink: Option<Box<dyn Write + Send>>) -> Option<Box<dyn Write + Send>> {
923 LOCAL_STDERR.with(move |slot| mem::replace(&mut *slot.borrow_mut(), sink)).and_then(|mut s| {
929 /// Resets the thread-local stdout handle to the specified writer
931 /// This will replace the current thread's stdout handle, returning the old
932 /// handle. All future calls to `print!` and friends will emit their output to
933 /// this specified handle.
935 /// Note that this does not need to be called for all new threads; the default
936 /// output handle is to the process's stdout stream.
938 feature = "set_stdio",
939 reason = "this function may disappear completely or be replaced \
940 with a more general mechanism",
944 pub fn set_print(sink: Option<Box<dyn Write + Send>>) -> Option<Box<dyn Write + Send>> {
946 LOCAL_STDOUT.with(move |slot| mem::replace(&mut *slot.borrow_mut(), sink)).and_then(|mut s| {
952 /// Write `args` to output stream `local_s` if possible, `global_s`
953 /// otherwise. `label` identifies the stream in a panic message.
955 /// This function is used to print error messages, so it takes extra
956 /// care to avoid causing a panic when `local_s` is unusable.
957 /// For instance, if the TLS key for the local stream is
958 /// already destroyed, or if the local stream is locked by another
959 /// thread, it will just fall back to the global stream.
961 /// However, if the actual I/O causes an error, this function does panic.
963 args: fmt::Arguments<'_>,
964 local_s: &'static LocalKey<RefCell<Option<Box<dyn Write + Send>>>>,
972 // Note that we completely remove a local sink to write to in case
973 // our printing recursively panics/prints, so the recursive
974 // panic/print goes to the global sink instead of our local sink.
975 let prev = s.borrow_mut().take();
976 if let Some(mut w) = prev {
977 let result = w.write_fmt(args);
978 *s.borrow_mut() = Some(w);
981 global_s().write_fmt(args)
983 .unwrap_or_else(|_| global_s().write_fmt(args));
985 if let Err(e) = result {
986 panic!("failed printing to {}: {}", label, e);
991 feature = "print_internals",
992 reason = "implementation detail which may disappear or be replaced at any time",
997 pub fn _print(args: fmt::Arguments<'_>) {
998 print_to(args, &LOCAL_STDOUT, stdout, "stdout");
1002 feature = "print_internals",
1003 reason = "implementation detail which may disappear or be replaced at any time",
1008 pub fn _eprint(args: fmt::Arguments<'_>) {
1009 print_to(args, &LOCAL_STDERR, stderr, "stderr");
1013 pub use realstd::io::{_eprint, _print};
1018 use crate::panic::{RefUnwindSafe, UnwindSafe};
1022 fn stdout_unwind_safe() {
1023 assert_unwind_safe::<Stdout>();
1026 fn stdoutlock_unwind_safe() {
1027 assert_unwind_safe::<StdoutLock<'_>>();
1028 assert_unwind_safe::<StdoutLock<'static>>();
1031 fn stderr_unwind_safe() {
1032 assert_unwind_safe::<Stderr>();
1035 fn stderrlock_unwind_safe() {
1036 assert_unwind_safe::<StderrLock<'_>>();
1037 assert_unwind_safe::<StderrLock<'static>>();
1040 fn assert_unwind_safe<T: UnwindSafe + RefUnwindSafe>() {}
1043 #[cfg_attr(target_os = "emscripten", ignore)]
1044 fn panic_doesnt_poison() {