6 use io::{self, Initializer, BufReader, LineWriter};
7 use sync::{Arc, Mutex, MutexGuard};
9 use sys_common::remutex::{ReentrantMutex, ReentrantMutexGuard};
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.
36 /// Not exposed, but used inside the standard library for panic output.
37 pub(crate) struct StderrRaw(stdio::Stderr);
39 /// Constructs a new raw handle to the standard input of this process.
41 /// The returned handle does not interact with any other handles created nor
42 /// handles returned by `std::io::stdin`. Data buffered by the `std::io::stdin`
43 /// handles is **not** available to raw handles returned from this function.
45 /// The returned handle has no external synchronization or buffering.
46 fn stdin_raw() -> io::Result<StdinRaw> { stdio::Stdin::new().map(StdinRaw) }
48 /// Constructs a new raw handle to the standard output stream of this process.
50 /// The returned handle does not interact with any other handles created nor
51 /// handles returned by `std::io::stdout`. Note that data is buffered by the
52 /// `std::io::stdout` handles so writes which happen via this raw handle may
53 /// appear before previous writes.
55 /// The returned handle has no external synchronization or buffering layered on
57 fn stdout_raw() -> io::Result<StdoutRaw> { stdio::Stdout::new().map(StdoutRaw) }
59 /// Constructs a new raw handle to the standard error stream of this process.
61 /// The returned handle does not interact with any other handles created nor
62 /// handles returned by `std::io::stderr`.
64 /// The returned handle has no external synchronization or buffering layered on
67 /// Not exposed, but used inside the standard library for panic output.
68 pub(crate) fn stderr_raw() -> io::Result<StderrRaw> { stdio::Stderr::new().map(StderrRaw) }
70 impl Read for StdinRaw {
71 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) }
74 unsafe fn initializer(&self) -> Initializer {
78 impl Write for StdoutRaw {
79 fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) }
80 fn flush(&mut self) -> io::Result<()> { self.0.flush() }
82 impl Write for StderrRaw {
83 fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) }
84 fn flush(&mut self) -> io::Result<()> { self.0.flush() }
92 impl<W: io::Write> io::Write for Maybe<W> {
93 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
95 Maybe::Real(ref mut w) => handle_ebadf(w.write(buf), buf.len()),
96 Maybe::Fake => Ok(buf.len())
100 fn flush(&mut self) -> io::Result<()> {
102 Maybe::Real(ref mut w) => handle_ebadf(w.flush(), ()),
103 Maybe::Fake => Ok(())
108 impl<R: io::Read> io::Read for Maybe<R> {
109 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
111 Maybe::Real(ref mut r) => handle_ebadf(r.read(buf), 0),
117 fn handle_ebadf<T>(r: io::Result<T>, default: T) -> io::Result<T> {
119 Err(ref e) if stdio::is_ebadf(e) => Ok(default),
124 /// A handle to the standard input stream of a process.
126 /// Each handle is a shared reference to a global buffer of input data to this
127 /// process. A handle can be `lock`'d to gain full access to [`BufRead`] methods
128 /// (e.g., `.lines()`). Reads to this handle are otherwise locked with respect
131 /// This handle implements the `Read` trait, but beware that concurrent reads
132 /// of `Stdin` must be executed with care.
134 /// Created by the [`io::stdin`] method.
136 /// [`io::stdin`]: fn.stdin.html
137 /// [`BufRead`]: trait.BufRead.html
139 /// ### Note: Windows Portability Consideration
140 /// When operating in a console, the Windows implementation of this stream does not support
141 /// non-UTF-8 byte sequences. Attempting to read bytes that are not valid UTF-8 will return
143 #[stable(feature = "rust1", since = "1.0.0")]
145 inner: Arc<Mutex<BufReader<Maybe<StdinRaw>>>>,
148 /// A locked reference to the `Stdin` handle.
150 /// This handle implements both the [`Read`] and [`BufRead`] traits, and
151 /// is constructed via the [`Stdin::lock`] method.
153 /// [`Read`]: trait.Read.html
154 /// [`BufRead`]: trait.BufRead.html
155 /// [`Stdin::lock`]: struct.Stdin.html#method.lock
157 /// ### Note: Windows Portability Consideration
158 /// When operating in a console, the Windows implementation of this stream does not support
159 /// non-UTF-8 byte sequences. Attempting to read bytes that are not valid UTF-8 will return
161 #[stable(feature = "rust1", since = "1.0.0")]
162 pub struct StdinLock<'a> {
163 inner: MutexGuard<'a, BufReader<Maybe<StdinRaw>>>,
166 /// Constructs a new handle to the standard input of the current process.
168 /// Each handle returned is a reference to a shared global buffer whose access
169 /// is synchronized via a mutex. If you need more explicit control over
170 /// locking, see the [`lock() method`][lock].
172 /// [lock]: struct.Stdin.html#method.lock
174 /// ### Note: Windows Portability Consideration
175 /// When operating in a console, the Windows implementation of this stream does not support
176 /// non-UTF-8 byte sequences. Attempting to read bytes that are not valid UTF-8 will return
181 /// Using implicit synchronization:
184 /// use std::io::{self, Read};
186 /// fn main() -> io::Result<()> {
187 /// let mut buffer = String::new();
188 /// io::stdin().read_to_string(&mut buffer)?;
193 /// Using explicit synchronization:
196 /// use std::io::{self, Read};
198 /// fn main() -> io::Result<()> {
199 /// let mut buffer = String::new();
200 /// let stdin = io::stdin();
201 /// let mut handle = stdin.lock();
203 /// handle.read_to_string(&mut buffer)?;
207 #[stable(feature = "rust1", since = "1.0.0")]
208 pub fn stdin() -> Stdin {
209 static INSTANCE: Lazy<Mutex<BufReader<Maybe<StdinRaw>>>> = Lazy::new();
212 INSTANCE.get(stdin_init).expect("cannot access stdin during shutdown")
216 fn stdin_init() -> Arc<Mutex<BufReader<Maybe<StdinRaw>>>> {
217 // This must not reentrantly access `INSTANCE`
218 let stdin = match stdin_raw() {
219 Ok(stdin) => Maybe::Real(stdin),
223 Arc::new(Mutex::new(BufReader::with_capacity(stdio::STDIN_BUF_SIZE, stdin)))
228 /// Locks this handle to the standard input stream, returning a readable
231 /// The lock is released when the returned lock goes out of scope. The
232 /// returned guard also implements the [`Read`] and [`BufRead`] traits for
233 /// accessing the underlying data.
235 /// [`Read`]: trait.Read.html
236 /// [`BufRead`]: trait.BufRead.html
241 /// use std::io::{self, Read};
243 /// fn main() -> io::Result<()> {
244 /// let mut buffer = String::new();
245 /// let stdin = io::stdin();
246 /// let mut handle = stdin.lock();
248 /// handle.read_to_string(&mut buffer)?;
252 #[stable(feature = "rust1", since = "1.0.0")]
253 pub fn lock(&self) -> StdinLock {
254 StdinLock { inner: self.inner.lock().unwrap_or_else(|e| e.into_inner()) }
257 /// Locks this handle and reads a line of input into the specified buffer.
259 /// For detailed semantics of this method, see the documentation on
260 /// [`BufRead::read_line`].
262 /// [`BufRead::read_line`]: trait.BufRead.html#method.read_line
269 /// let mut input = String::new();
270 /// match io::stdin().read_line(&mut input) {
272 /// println!("{} bytes read", n);
273 /// println!("{}", input);
275 /// Err(error) => println!("error: {}", error),
279 /// You can run the example one of two ways:
281 /// - Pipe some text to it, e.g., `printf foo | path/to/executable`
282 /// - Give it text interactively by running the executable directly,
283 /// in which case it will wait for the Enter key to be pressed before
285 #[stable(feature = "rust1", since = "1.0.0")]
286 pub fn read_line(&self, buf: &mut String) -> io::Result<usize> {
287 self.lock().read_line(buf)
291 #[stable(feature = "std_debug", since = "1.16.0")]
292 impl fmt::Debug for Stdin {
293 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
294 f.pad("Stdin { .. }")
298 #[stable(feature = "rust1", since = "1.0.0")]
299 impl Read for Stdin {
300 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
301 self.lock().read(buf)
304 unsafe fn initializer(&self) -> Initializer {
307 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
308 self.lock().read_to_end(buf)
310 fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
311 self.lock().read_to_string(buf)
313 fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
314 self.lock().read_exact(buf)
318 #[stable(feature = "rust1", since = "1.0.0")]
319 impl<'a> Read for StdinLock<'a> {
320 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
324 unsafe fn initializer(&self) -> Initializer {
329 #[stable(feature = "rust1", since = "1.0.0")]
330 impl<'a> BufRead for StdinLock<'a> {
331 fn fill_buf(&mut self) -> io::Result<&[u8]> { self.inner.fill_buf() }
332 fn consume(&mut self, n: usize) { self.inner.consume(n) }
335 #[stable(feature = "std_debug", since = "1.16.0")]
336 impl<'a> fmt::Debug for StdinLock<'a> {
337 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
338 f.pad("StdinLock { .. }")
342 /// A handle to the global standard output stream of the current process.
344 /// Each handle shares a global buffer of data to be written to the standard
345 /// output stream. Access is also synchronized via a lock and explicit control
346 /// over locking is available via the [`lock`] method.
348 /// Created by the [`io::stdout`] method.
350 /// ### Note: Windows Portability Consideration
351 /// When operating in a console, the Windows implementation of this stream does not support
352 /// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
355 /// [`lock`]: #method.lock
356 /// [`io::stdout`]: fn.stdout.html
357 #[stable(feature = "rust1", since = "1.0.0")]
359 // FIXME: this should be LineWriter or BufWriter depending on the state of
360 // stdout (tty or not). Note that if this is not line buffered it
361 // should also flush-on-panic or some form of flush-on-abort.
362 inner: Arc<ReentrantMutex<RefCell<LineWriter<Maybe<StdoutRaw>>>>>,
365 /// A locked reference to the `Stdout` handle.
367 /// This handle implements the [`Write`] trait, and is constructed via
368 /// the [`Stdout::lock`] method.
370 /// ### Note: Windows Portability Consideration
371 /// When operating in a console, the Windows implementation of this stream does not support
372 /// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
375 /// [`Write`]: trait.Write.html
376 /// [`Stdout::lock`]: struct.Stdout.html#method.lock
377 #[stable(feature = "rust1", since = "1.0.0")]
378 pub struct StdoutLock<'a> {
379 inner: ReentrantMutexGuard<'a, RefCell<LineWriter<Maybe<StdoutRaw>>>>,
382 /// Constructs a new handle to the standard output of the current process.
384 /// Each handle returned is a reference to a shared global buffer whose access
385 /// is synchronized via a mutex. If you need more explicit control over
386 /// locking, see the [Stdout::lock] method.
388 /// [Stdout::lock]: struct.Stdout.html#method.lock
390 /// ### Note: Windows Portability Consideration
391 /// When operating in a console, the Windows implementation of this stream does not support
392 /// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
397 /// Using implicit synchronization:
400 /// use std::io::{self, Write};
402 /// fn main() -> io::Result<()> {
403 /// io::stdout().write(b"hello world")?;
409 /// Using explicit synchronization:
412 /// use std::io::{self, Write};
414 /// fn main() -> io::Result<()> {
415 /// let stdout = io::stdout();
416 /// let mut handle = stdout.lock();
418 /// handle.write(b"hello world")?;
423 #[stable(feature = "rust1", since = "1.0.0")]
424 pub fn stdout() -> Stdout {
425 static INSTANCE: Lazy<ReentrantMutex<RefCell<LineWriter<Maybe<StdoutRaw>>>>> = Lazy::new();
428 INSTANCE.get(stdout_init).expect("cannot access stdout during shutdown")
432 fn stdout_init() -> Arc<ReentrantMutex<RefCell<LineWriter<Maybe<StdoutRaw>>>>> {
433 // This must not reentrantly access `INSTANCE`
434 let stdout = match stdout_raw() {
435 Ok(stdout) => Maybe::Real(stdout),
438 Arc::new(ReentrantMutex::new(RefCell::new(LineWriter::new(stdout))))
443 /// Locks this handle to the standard output stream, returning a writable
446 /// The lock is released when the returned lock goes out of scope. The
447 /// returned guard also implements the `Write` trait for writing data.
452 /// use std::io::{self, Write};
454 /// fn main() -> io::Result<()> {
455 /// let stdout = io::stdout();
456 /// let mut handle = stdout.lock();
458 /// handle.write(b"hello world")?;
463 #[stable(feature = "rust1", since = "1.0.0")]
464 pub fn lock(&self) -> StdoutLock {
465 StdoutLock { inner: self.inner.lock().unwrap_or_else(|e| e.into_inner()) }
469 #[stable(feature = "std_debug", since = "1.16.0")]
470 impl fmt::Debug for Stdout {
471 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
472 f.pad("Stdout { .. }")
476 #[stable(feature = "rust1", since = "1.0.0")]
477 impl Write for Stdout {
478 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
479 self.lock().write(buf)
481 fn flush(&mut self) -> io::Result<()> {
484 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
485 self.lock().write_all(buf)
487 fn write_fmt(&mut self, args: fmt::Arguments) -> io::Result<()> {
488 self.lock().write_fmt(args)
491 #[stable(feature = "rust1", since = "1.0.0")]
492 impl<'a> Write for StdoutLock<'a> {
493 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
494 self.inner.borrow_mut().write(buf)
496 fn flush(&mut self) -> io::Result<()> {
497 self.inner.borrow_mut().flush()
501 #[stable(feature = "std_debug", since = "1.16.0")]
502 impl<'a> fmt::Debug for StdoutLock<'a> {
503 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
504 f.pad("StdoutLock { .. }")
508 /// A handle to the standard error stream of a process.
510 /// For more information, see the [`io::stderr`] method.
512 /// [`io::stderr`]: fn.stderr.html
514 /// ### Note: Windows Portability Consideration
515 /// When operating in a console, the Windows implementation of this stream does not support
516 /// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
518 #[stable(feature = "rust1", since = "1.0.0")]
520 inner: Arc<ReentrantMutex<RefCell<Maybe<StderrRaw>>>>,
523 /// A locked reference to the `Stderr` handle.
525 /// This handle implements the `Write` trait and is constructed via
526 /// the [`Stderr::lock`] method.
528 /// [`Stderr::lock`]: struct.Stderr.html#method.lock
530 /// ### Note: Windows Portability Consideration
531 /// When operating in a console, the Windows implementation of this stream does not support
532 /// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
534 #[stable(feature = "rust1", since = "1.0.0")]
535 pub struct StderrLock<'a> {
536 inner: ReentrantMutexGuard<'a, RefCell<Maybe<StderrRaw>>>,
539 /// Constructs a new handle to the standard error of the current process.
541 /// This handle is not buffered.
543 /// ### Note: Windows Portability Consideration
544 /// When operating in a console, the Windows implementation of this stream does not support
545 /// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
550 /// Using implicit synchronization:
553 /// use std::io::{self, Write};
555 /// fn main() -> io::Result<()> {
556 /// io::stderr().write(b"hello world")?;
562 /// Using explicit synchronization:
565 /// use std::io::{self, Write};
567 /// fn main() -> io::Result<()> {
568 /// let stderr = io::stderr();
569 /// let mut handle = stderr.lock();
571 /// handle.write(b"hello world")?;
576 #[stable(feature = "rust1", since = "1.0.0")]
577 pub fn stderr() -> Stderr {
578 static INSTANCE: Lazy<ReentrantMutex<RefCell<Maybe<StderrRaw>>>> = Lazy::new();
581 INSTANCE.get(stderr_init).expect("cannot access stderr during shutdown")
585 fn stderr_init() -> Arc<ReentrantMutex<RefCell<Maybe<StderrRaw>>>> {
586 // This must not reentrantly access `INSTANCE`
587 let stderr = match stderr_raw() {
588 Ok(stderr) => Maybe::Real(stderr),
591 Arc::new(ReentrantMutex::new(RefCell::new(stderr)))
596 /// Locks this handle to the standard error stream, returning a writable
599 /// The lock is released when the returned lock goes out of scope. The
600 /// returned guard also implements the `Write` trait for writing data.
605 /// use std::io::{self, Write};
607 /// fn foo() -> io::Result<()> {
608 /// let stderr = io::stderr();
609 /// let mut handle = stderr.lock();
611 /// handle.write(b"hello world")?;
616 #[stable(feature = "rust1", since = "1.0.0")]
617 pub fn lock(&self) -> StderrLock {
618 StderrLock { inner: self.inner.lock().unwrap_or_else(|e| e.into_inner()) }
622 #[stable(feature = "std_debug", since = "1.16.0")]
623 impl fmt::Debug for Stderr {
624 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
625 f.pad("Stderr { .. }")
629 #[stable(feature = "rust1", since = "1.0.0")]
630 impl Write for Stderr {
631 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
632 self.lock().write(buf)
634 fn flush(&mut self) -> io::Result<()> {
637 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
638 self.lock().write_all(buf)
640 fn write_fmt(&mut self, args: fmt::Arguments) -> io::Result<()> {
641 self.lock().write_fmt(args)
644 #[stable(feature = "rust1", since = "1.0.0")]
645 impl<'a> Write for StderrLock<'a> {
646 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
647 self.inner.borrow_mut().write(buf)
649 fn flush(&mut self) -> io::Result<()> {
650 self.inner.borrow_mut().flush()
654 #[stable(feature = "std_debug", since = "1.16.0")]
655 impl<'a> fmt::Debug for StderrLock<'a> {
656 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
657 f.pad("StderrLock { .. }")
661 /// Resets the thread-local stderr handle to the specified writer
663 /// This will replace the current thread's stderr handle, returning the old
664 /// handle. All future calls to `panic!` and friends will emit their output to
665 /// this specified handle.
667 /// Note that this does not need to be called for all new threads; the default
668 /// output handle is to the process's stderr stream.
669 #[unstable(feature = "set_stdio",
670 reason = "this function may disappear completely or be replaced \
671 with a more general mechanism",
674 pub fn set_panic(sink: Option<Box<dyn Write + Send>>) -> Option<Box<dyn Write + Send>> {
675 use panicking::LOCAL_STDERR;
677 LOCAL_STDERR.with(move |slot| {
678 mem::replace(&mut *slot.borrow_mut(), sink)
679 }).and_then(|mut s| {
685 /// Resets the thread-local stdout handle to the specified writer
687 /// This will replace the current thread's stdout handle, returning the old
688 /// handle. All future calls to `print!` and friends will emit their output to
689 /// this specified handle.
691 /// Note that this does not need to be called for all new threads; the default
692 /// output handle is to the process's stdout stream.
693 #[unstable(feature = "set_stdio",
694 reason = "this function may disappear completely or be replaced \
695 with a more general mechanism",
698 pub fn set_print(sink: Option<Box<dyn Write + Send>>) -> Option<Box<dyn Write + Send>> {
700 LOCAL_STDOUT.with(move |slot| {
701 mem::replace(&mut *slot.borrow_mut(), sink)
702 }).and_then(|mut s| {
708 /// Write `args` to output stream `local_s` if possible, `global_s`
709 /// otherwise. `label` identifies the stream in a panic message.
711 /// This function is used to print error messages, so it takes extra
712 /// care to avoid causing a panic when `local_stream` is unusable.
713 /// For instance, if the TLS key for the local stream is
714 /// already destroyed, or if the local stream is locked by another
715 /// thread, it will just fall back to the global stream.
717 /// However, if the actual I/O causes an error, this function does panic.
719 args: fmt::Arguments,
720 local_s: &'static LocalKey<RefCell<Option<Box<dyn Write+Send>>>>,
727 let result = local_s.try_with(|s| {
728 if let Ok(mut borrowed) = s.try_borrow_mut() {
729 if let Some(w) = borrowed.as_mut() {
730 return w.write_fmt(args);
733 global_s().write_fmt(args)
734 }).unwrap_or_else(|_| {
735 global_s().write_fmt(args)
738 if let Err(e) = result {
739 panic!("failed printing to {}: {}", label, e);
743 #[unstable(feature = "print_internals",
744 reason = "implementation detail which may disappear or be replaced at any time",
747 pub fn _print(args: fmt::Arguments) {
748 print_to(args, &LOCAL_STDOUT, stdout, "stdout");
751 #[unstable(feature = "print_internals",
752 reason = "implementation detail which may disappear or be replaced at any time",
755 pub fn _eprint(args: fmt::Arguments) {
756 use panicking::LOCAL_STDERR;
757 print_to(args, &LOCAL_STDERR, stderr, "stderr");
762 use panic::{UnwindSafe, RefUnwindSafe};
767 fn stdout_unwind_safe() {
768 assert_unwind_safe::<Stdout>();
771 fn stdoutlock_unwind_safe() {
772 assert_unwind_safe::<StdoutLock>();
773 assert_unwind_safe::<StdoutLock<'static>>();
776 fn stderr_unwind_safe() {
777 assert_unwind_safe::<Stderr>();
780 fn stderrlock_unwind_safe() {
781 assert_unwind_safe::<StderrLock>();
782 assert_unwind_safe::<StderrLock<'static>>();
785 fn assert_unwind_safe<T: UnwindSafe + RefUnwindSafe>() {}
788 #[cfg_attr(target_os = "emscripten", ignore)]
789 fn panic_doesnt_poison() {
798 }).join().unwrap_err();