1 use crate::io::prelude::*;
3 use crate::cell::RefCell;
5 use crate::io::lazy::Lazy;
6 use crate::io::{self, Initializer, BufReader, LineWriter};
7 use crate::sync::{Arc, Mutex, MutexGuard};
9 use crate::sys_common::remutex::{ReentrantMutex, ReentrantMutexGuard};
10 use crate::thread::LocalKey;
12 /// Stdout used by print! and println! macros
14 static LOCAL_STDOUT: RefCell<Option<Box<dyn Write + Send>>> = {
19 /// A handle to a raw instance of the standard input stream of this process.
21 /// This handle is not synchronized or buffered in any fashion. Constructed via
22 /// the `std::io::stdio::stdin_raw` function.
23 struct StdinRaw(stdio::Stdin);
25 /// A handle to a raw instance of the standard output stream of this process.
27 /// This handle is not synchronized or buffered in any fashion. Constructed via
28 /// the `std::io::stdio::stdout_raw` function.
29 struct StdoutRaw(stdio::Stdout);
31 /// A handle to a raw instance of the standard output stream of this process.
33 /// This handle is not synchronized or buffered in any fashion. Constructed via
34 /// the `std::io::stdio::stderr_raw` function.
35 struct StderrRaw(stdio::Stderr);
37 /// Constructs a new raw handle to the standard input of this process.
39 /// The returned handle does not interact with any other handles created nor
40 /// handles returned by `std::io::stdin`. Data buffered by the `std::io::stdin`
41 /// handles is **not** available to raw handles returned from this function.
43 /// The returned handle has no external synchronization or buffering.
44 fn stdin_raw() -> io::Result<StdinRaw> { stdio::Stdin::new().map(StdinRaw) }
46 /// Constructs a new raw handle to the standard output stream of this process.
48 /// The returned handle does not interact with any other handles created nor
49 /// handles returned by `std::io::stdout`. Note that data is buffered by the
50 /// `std::io::stdout` handles so writes which happen via this raw handle may
51 /// appear before previous writes.
53 /// The returned handle has no external synchronization or buffering layered on
55 fn stdout_raw() -> io::Result<StdoutRaw> { stdio::Stdout::new().map(StdoutRaw) }
57 /// Constructs a new raw handle to the standard error stream of this process.
59 /// The returned handle does not interact with any other handles created nor
60 /// handles returned by `std::io::stderr`.
62 /// The returned handle has no external synchronization or buffering layered on
64 fn stderr_raw() -> io::Result<StderrRaw> { stdio::Stderr::new().map(StderrRaw) }
66 impl Read for StdinRaw {
67 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) }
70 unsafe fn initializer(&self) -> Initializer {
74 impl Write for StdoutRaw {
75 fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) }
76 fn flush(&mut self) -> io::Result<()> { self.0.flush() }
78 impl Write for StderrRaw {
79 fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) }
80 fn flush(&mut self) -> io::Result<()> { self.0.flush() }
88 impl<W: io::Write> io::Write for Maybe<W> {
89 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
91 Maybe::Real(ref mut w) => handle_ebadf(w.write(buf), buf.len()),
92 Maybe::Fake => Ok(buf.len())
96 fn flush(&mut self) -> io::Result<()> {
98 Maybe::Real(ref mut w) => handle_ebadf(w.flush(), ()),
104 impl<R: io::Read> io::Read for Maybe<R> {
105 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
107 Maybe::Real(ref mut r) => handle_ebadf(r.read(buf), 0),
113 fn handle_ebadf<T>(r: io::Result<T>, default: T) -> io::Result<T> {
115 Err(ref e) if stdio::is_ebadf(e) => Ok(default),
120 /// A handle to the standard input stream of a process.
122 /// Each handle is a shared reference to a global buffer of input data to this
123 /// process. A handle can be `lock`'d to gain full access to [`BufRead`] methods
124 /// (e.g., `.lines()`). Reads to this handle are otherwise locked with respect
127 /// This handle implements the `Read` trait, but beware that concurrent reads
128 /// of `Stdin` must be executed with care.
130 /// Created by the [`io::stdin`] method.
132 /// [`io::stdin`]: fn.stdin.html
133 /// [`BufRead`]: trait.BufRead.html
135 /// ### Note: Windows Portability Consideration
136 /// When operating in a console, the Windows implementation of this stream does not support
137 /// non-UTF-8 byte sequences. Attempting to read bytes that are not valid UTF-8 will return
139 #[stable(feature = "rust1", since = "1.0.0")]
141 inner: Arc<Mutex<BufReader<Maybe<StdinRaw>>>>,
144 /// A locked reference to the `Stdin` handle.
146 /// This handle implements both the [`Read`] and [`BufRead`] traits, and
147 /// is constructed via the [`Stdin::lock`] method.
149 /// [`Read`]: trait.Read.html
150 /// [`BufRead`]: trait.BufRead.html
151 /// [`Stdin::lock`]: struct.Stdin.html#method.lock
153 /// ### Note: Windows Portability Consideration
154 /// When operating in a console, the Windows implementation of this stream does not support
155 /// non-UTF-8 byte sequences. Attempting to read bytes that are not valid UTF-8 will return
157 #[stable(feature = "rust1", since = "1.0.0")]
158 pub struct StdinLock<'a> {
159 inner: MutexGuard<'a, BufReader<Maybe<StdinRaw>>>,
162 /// Constructs a new handle to the standard input of the current process.
164 /// Each handle returned is a reference to a shared global buffer whose access
165 /// is synchronized via a mutex. If you need more explicit control over
166 /// locking, see the [`lock() method`][lock].
168 /// [lock]: struct.Stdin.html#method.lock
170 /// ### Note: Windows Portability Consideration
171 /// When operating in a console, the Windows implementation of this stream does not support
172 /// non-UTF-8 byte sequences. Attempting to read bytes that are not valid UTF-8 will return
177 /// Using implicit synchronization:
180 /// use std::io::{self, Read};
182 /// fn main() -> io::Result<()> {
183 /// let mut buffer = String::new();
184 /// io::stdin().read_to_string(&mut buffer)?;
189 /// Using explicit synchronization:
192 /// use std::io::{self, Read};
194 /// fn main() -> io::Result<()> {
195 /// let mut buffer = String::new();
196 /// let stdin = io::stdin();
197 /// let mut handle = stdin.lock();
199 /// handle.read_to_string(&mut buffer)?;
203 #[stable(feature = "rust1", since = "1.0.0")]
204 pub fn stdin() -> Stdin {
205 static INSTANCE: Lazy<Mutex<BufReader<Maybe<StdinRaw>>>> = Lazy::new();
208 INSTANCE.get(stdin_init).expect("cannot access stdin during shutdown")
212 fn stdin_init() -> Arc<Mutex<BufReader<Maybe<StdinRaw>>>> {
213 // This must not reentrantly access `INSTANCE`
214 let stdin = match stdin_raw() {
215 Ok(stdin) => Maybe::Real(stdin),
219 Arc::new(Mutex::new(BufReader::with_capacity(stdio::STDIN_BUF_SIZE, stdin)))
224 /// Locks this handle to the standard input stream, returning a readable
227 /// The lock is released when the returned lock goes out of scope. The
228 /// returned guard also implements the [`Read`] and [`BufRead`] traits for
229 /// accessing the underlying data.
231 /// [`Read`]: trait.Read.html
232 /// [`BufRead`]: trait.BufRead.html
237 /// use std::io::{self, Read};
239 /// fn main() -> io::Result<()> {
240 /// let mut buffer = String::new();
241 /// let stdin = io::stdin();
242 /// let mut handle = stdin.lock();
244 /// handle.read_to_string(&mut buffer)?;
248 #[stable(feature = "rust1", since = "1.0.0")]
249 pub fn lock(&self) -> StdinLock {
250 StdinLock { inner: self.inner.lock().unwrap_or_else(|e| e.into_inner()) }
253 /// Locks this handle and reads a line of input into the specified buffer.
255 /// For detailed semantics of this method, see the documentation on
256 /// [`BufRead::read_line`].
258 /// [`BufRead::read_line`]: trait.BufRead.html#method.read_line
265 /// let mut input = String::new();
266 /// match io::stdin().read_line(&mut input) {
268 /// println!("{} bytes read", n);
269 /// println!("{}", input);
271 /// Err(error) => println!("error: {}", error),
275 /// You can run the example one of two ways:
277 /// - Pipe some text to it, e.g., `printf foo | path/to/executable`
278 /// - Give it text interactively by running the executable directly,
279 /// in which case it will wait for the Enter key to be pressed before
281 #[stable(feature = "rust1", since = "1.0.0")]
282 pub fn read_line(&self, buf: &mut String) -> io::Result<usize> {
283 self.lock().read_line(buf)
287 #[stable(feature = "std_debug", since = "1.16.0")]
288 impl fmt::Debug for Stdin {
289 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
290 f.pad("Stdin { .. }")
294 #[stable(feature = "rust1", since = "1.0.0")]
295 impl Read for Stdin {
296 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
297 self.lock().read(buf)
300 unsafe fn initializer(&self) -> Initializer {
303 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
304 self.lock().read_to_end(buf)
306 fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
307 self.lock().read_to_string(buf)
309 fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
310 self.lock().read_exact(buf)
314 #[stable(feature = "rust1", since = "1.0.0")]
315 impl Read for StdinLock<'_> {
316 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
320 unsafe fn initializer(&self) -> Initializer {
325 #[stable(feature = "rust1", since = "1.0.0")]
326 impl BufRead for StdinLock<'_> {
327 fn fill_buf(&mut self) -> io::Result<&[u8]> { self.inner.fill_buf() }
328 fn consume(&mut self, n: usize) { self.inner.consume(n) }
331 #[stable(feature = "std_debug", since = "1.16.0")]
332 impl fmt::Debug for StdinLock<'_> {
333 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
334 f.pad("StdinLock { .. }")
338 /// A handle to the global standard output stream of the current process.
340 /// Each handle shares a global buffer of data to be written to the standard
341 /// output stream. Access is also synchronized via a lock and explicit control
342 /// over locking is available via the [`lock`] method.
344 /// Created by the [`io::stdout`] method.
346 /// ### Note: Windows Portability Consideration
347 /// When operating in a console, the Windows implementation of this stream does not support
348 /// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
351 /// [`lock`]: #method.lock
352 /// [`io::stdout`]: fn.stdout.html
353 #[stable(feature = "rust1", since = "1.0.0")]
355 // FIXME: this should be LineWriter or BufWriter depending on the state of
356 // stdout (tty or not). Note that if this is not line buffered it
357 // should also flush-on-panic or some form of flush-on-abort.
358 inner: Arc<ReentrantMutex<RefCell<LineWriter<Maybe<StdoutRaw>>>>>,
361 /// A locked reference to the `Stdout` handle.
363 /// This handle implements the [`Write`] trait, and is constructed via
364 /// the [`Stdout::lock`] method.
366 /// ### Note: Windows Portability Consideration
367 /// When operating in a console, the Windows implementation of this stream does not support
368 /// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
371 /// [`Write`]: trait.Write.html
372 /// [`Stdout::lock`]: struct.Stdout.html#method.lock
373 #[stable(feature = "rust1", since = "1.0.0")]
374 pub struct StdoutLock<'a> {
375 inner: ReentrantMutexGuard<'a, RefCell<LineWriter<Maybe<StdoutRaw>>>>,
378 /// Constructs a new handle to the standard output of the current process.
380 /// Each handle returned is a reference to a shared global buffer whose access
381 /// is synchronized via a mutex. If you need more explicit control over
382 /// locking, see the [Stdout::lock] method.
384 /// [Stdout::lock]: struct.Stdout.html#method.lock
386 /// ### Note: Windows Portability Consideration
387 /// When operating in a console, the Windows implementation of this stream does not support
388 /// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
393 /// Using implicit synchronization:
396 /// use std::io::{self, Write};
398 /// fn main() -> io::Result<()> {
399 /// io::stdout().write(b"hello world")?;
405 /// Using explicit synchronization:
408 /// use std::io::{self, Write};
410 /// fn main() -> io::Result<()> {
411 /// let stdout = io::stdout();
412 /// let mut handle = stdout.lock();
414 /// handle.write(b"hello world")?;
419 #[stable(feature = "rust1", since = "1.0.0")]
420 pub fn stdout() -> Stdout {
421 static INSTANCE: Lazy<ReentrantMutex<RefCell<LineWriter<Maybe<StdoutRaw>>>>> = Lazy::new();
424 INSTANCE.get(stdout_init).expect("cannot access stdout during shutdown")
428 fn stdout_init() -> Arc<ReentrantMutex<RefCell<LineWriter<Maybe<StdoutRaw>>>>> {
429 // This must not reentrantly access `INSTANCE`
430 let stdout = match stdout_raw() {
431 Ok(stdout) => Maybe::Real(stdout),
434 Arc::new(ReentrantMutex::new(RefCell::new(LineWriter::new(stdout))))
439 /// Locks this handle to the standard output stream, returning a writable
442 /// The lock is released when the returned lock goes out of scope. The
443 /// returned guard also implements the `Write` trait for writing data.
448 /// use std::io::{self, Write};
450 /// fn main() -> io::Result<()> {
451 /// let stdout = io::stdout();
452 /// let mut handle = stdout.lock();
454 /// handle.write(b"hello world")?;
459 #[stable(feature = "rust1", since = "1.0.0")]
460 pub fn lock(&self) -> StdoutLock {
461 StdoutLock { inner: self.inner.lock().unwrap_or_else(|e| e.into_inner()) }
465 #[stable(feature = "std_debug", since = "1.16.0")]
466 impl fmt::Debug for Stdout {
467 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
468 f.pad("Stdout { .. }")
472 #[stable(feature = "rust1", since = "1.0.0")]
473 impl Write for Stdout {
474 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
475 self.lock().write(buf)
477 fn flush(&mut self) -> io::Result<()> {
480 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
481 self.lock().write_all(buf)
483 fn write_fmt(&mut self, args: fmt::Arguments) -> io::Result<()> {
484 self.lock().write_fmt(args)
487 #[stable(feature = "rust1", since = "1.0.0")]
488 impl Write for StdoutLock<'_> {
489 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
490 self.inner.borrow_mut().write(buf)
492 fn flush(&mut self) -> io::Result<()> {
493 self.inner.borrow_mut().flush()
497 #[stable(feature = "std_debug", since = "1.16.0")]
498 impl fmt::Debug for StdoutLock<'_> {
499 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
500 f.pad("StdoutLock { .. }")
504 /// A handle to the standard error stream of a process.
506 /// For more information, see the [`io::stderr`] method.
508 /// [`io::stderr`]: fn.stderr.html
510 /// ### Note: Windows Portability Consideration
511 /// When operating in a console, the Windows implementation of this stream does not support
512 /// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
514 #[stable(feature = "rust1", since = "1.0.0")]
516 inner: Arc<ReentrantMutex<RefCell<Maybe<StderrRaw>>>>,
519 /// A locked reference to the `Stderr` handle.
521 /// This handle implements the `Write` trait and is constructed via
522 /// the [`Stderr::lock`] method.
524 /// [`Stderr::lock`]: struct.Stderr.html#method.lock
526 /// ### Note: Windows Portability Consideration
527 /// When operating in a console, the Windows implementation of this stream does not support
528 /// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
530 #[stable(feature = "rust1", since = "1.0.0")]
531 pub struct StderrLock<'a> {
532 inner: ReentrantMutexGuard<'a, RefCell<Maybe<StderrRaw>>>,
535 /// Constructs a new handle to the standard error of the current process.
537 /// This handle is not buffered.
539 /// ### Note: Windows Portability Consideration
540 /// When operating in a console, the Windows implementation of this stream does not support
541 /// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
546 /// Using implicit synchronization:
549 /// use std::io::{self, Write};
551 /// fn main() -> io::Result<()> {
552 /// io::stderr().write(b"hello world")?;
558 /// Using explicit synchronization:
561 /// use std::io::{self, Write};
563 /// fn main() -> io::Result<()> {
564 /// let stderr = io::stderr();
565 /// let mut handle = stderr.lock();
567 /// handle.write(b"hello world")?;
572 #[stable(feature = "rust1", since = "1.0.0")]
573 pub fn stderr() -> Stderr {
574 static INSTANCE: Lazy<ReentrantMutex<RefCell<Maybe<StderrRaw>>>> = Lazy::new();
577 INSTANCE.get(stderr_init).expect("cannot access stderr during shutdown")
581 fn stderr_init() -> Arc<ReentrantMutex<RefCell<Maybe<StderrRaw>>>> {
582 // This must not reentrantly access `INSTANCE`
583 let stderr = match stderr_raw() {
584 Ok(stderr) => Maybe::Real(stderr),
587 Arc::new(ReentrantMutex::new(RefCell::new(stderr)))
592 /// Locks this handle to the standard error stream, returning a writable
595 /// The lock is released when the returned lock goes out of scope. The
596 /// returned guard also implements the `Write` trait for writing data.
601 /// use std::io::{self, Write};
603 /// fn foo() -> io::Result<()> {
604 /// let stderr = io::stderr();
605 /// let mut handle = stderr.lock();
607 /// handle.write(b"hello world")?;
612 #[stable(feature = "rust1", since = "1.0.0")]
613 pub fn lock(&self) -> StderrLock {
614 StderrLock { inner: self.inner.lock().unwrap_or_else(|e| e.into_inner()) }
618 #[stable(feature = "std_debug", since = "1.16.0")]
619 impl fmt::Debug for Stderr {
620 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
621 f.pad("Stderr { .. }")
625 #[stable(feature = "rust1", since = "1.0.0")]
626 impl Write for Stderr {
627 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
628 self.lock().write(buf)
630 fn flush(&mut self) -> io::Result<()> {
633 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
634 self.lock().write_all(buf)
636 fn write_fmt(&mut self, args: fmt::Arguments) -> io::Result<()> {
637 self.lock().write_fmt(args)
640 #[stable(feature = "rust1", since = "1.0.0")]
641 impl Write for StderrLock<'_> {
642 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
643 self.inner.borrow_mut().write(buf)
645 fn flush(&mut self) -> io::Result<()> {
646 self.inner.borrow_mut().flush()
650 #[stable(feature = "std_debug", since = "1.16.0")]
651 impl fmt::Debug for StderrLock<'_> {
652 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
653 f.pad("StderrLock { .. }")
657 /// Resets the thread-local stderr handle to the specified writer
659 /// This will replace the current thread's stderr handle, returning the old
660 /// handle. All future calls to `panic!` and friends will emit their output to
661 /// this specified handle.
663 /// Note that this does not need to be called for all new threads; the default
664 /// output handle is to the process's stderr stream.
665 #[unstable(feature = "set_stdio",
666 reason = "this function may disappear completely or be replaced \
667 with a more general mechanism",
670 pub fn set_panic(sink: Option<Box<dyn Write + Send>>) -> Option<Box<dyn Write + Send>> {
671 use crate::panicking::LOCAL_STDERR;
673 LOCAL_STDERR.with(move |slot| {
674 mem::replace(&mut *slot.borrow_mut(), sink)
675 }).and_then(|mut s| {
681 /// Resets the thread-local stdout handle to the specified writer
683 /// This will replace the current thread's stdout handle, returning the old
684 /// handle. All future calls to `print!` and friends will emit their output to
685 /// this specified handle.
687 /// Note that this does not need to be called for all new threads; the default
688 /// output handle is to the process's stdout stream.
689 #[unstable(feature = "set_stdio",
690 reason = "this function may disappear completely or be replaced \
691 with a more general mechanism",
694 pub fn set_print(sink: Option<Box<dyn Write + Send>>) -> Option<Box<dyn Write + Send>> {
696 LOCAL_STDOUT.with(move |slot| {
697 mem::replace(&mut *slot.borrow_mut(), sink)
698 }).and_then(|mut s| {
704 /// Write `args` to output stream `local_s` if possible, `global_s`
705 /// otherwise. `label` identifies the stream in a panic message.
707 /// This function is used to print error messages, so it takes extra
708 /// care to avoid causing a panic when `local_stream` is unusable.
709 /// For instance, if the TLS key for the local stream is
710 /// already destroyed, or if the local stream is locked by another
711 /// thread, it will just fall back to the global stream.
713 /// However, if the actual I/O causes an error, this function does panic.
715 args: fmt::Arguments,
716 local_s: &'static LocalKey<RefCell<Option<Box<dyn Write+Send>>>>,
723 let result = local_s.try_with(|s| {
724 if let Ok(mut borrowed) = s.try_borrow_mut() {
725 if let Some(w) = borrowed.as_mut() {
726 return w.write_fmt(args);
729 global_s().write_fmt(args)
730 }).unwrap_or_else(|_| {
731 global_s().write_fmt(args)
734 if let Err(e) = result {
735 panic!("failed printing to {}: {}", label, e);
739 #[unstable(feature = "print_internals",
740 reason = "implementation detail which may disappear or be replaced at any time",
743 pub fn _print(args: fmt::Arguments) {
744 print_to(args, &LOCAL_STDOUT, stdout, "stdout");
747 #[unstable(feature = "print_internals",
748 reason = "implementation detail which may disappear or be replaced at any time",
751 pub fn _eprint(args: fmt::Arguments) {
752 use crate::panicking::LOCAL_STDERR;
753 print_to(args, &LOCAL_STDERR, stderr, "stderr");
758 use crate::panic::{UnwindSafe, RefUnwindSafe};
763 fn stdout_unwind_safe() {
764 assert_unwind_safe::<Stdout>();
767 fn stdoutlock_unwind_safe() {
768 assert_unwind_safe::<StdoutLock>();
769 assert_unwind_safe::<StdoutLock<'static>>();
772 fn stderr_unwind_safe() {
773 assert_unwind_safe::<Stderr>();
776 fn stderrlock_unwind_safe() {
777 assert_unwind_safe::<StderrLock>();
778 assert_unwind_safe::<StderrLock<'static>>();
781 fn assert_unwind_safe<T: UnwindSafe + RefUnwindSafe>() {}
784 #[cfg_attr(target_os = "emscripten", ignore)]
785 fn panic_doesnt_poison() {
794 }).join().unwrap_err();