std/io/stdio.rs
1#![cfg_attr(test, allow(unused))]
2
3#[cfg(test)]
4mod tests;
5
6use crate::cell::{Cell, RefCell};
7use crate::fmt;
8use crate::fs::File;
9use crate::io::prelude::*;
10use crate::io::{
11 self, BorrowedCursor, BufReader, IoSlice, IoSliceMut, LineWriter, Lines, SpecReadByte,
12};
13use crate::panic::{RefUnwindSafe, UnwindSafe};
14use crate::sync::atomic::{Atomic, AtomicBool, Ordering};
15use crate::sync::{Arc, Mutex, MutexGuard, OnceLock, ReentrantLock, ReentrantLockGuard};
16use crate::sys::stdio;
17use crate::thread::AccessError;
18
19type LocalStream = Arc<Mutex<Vec<u8>>>;
20
21thread_local! {
22 /// Used by the test crate to capture the output of the print macros and panics.
23 static OUTPUT_CAPTURE: Cell<Option<LocalStream>> = const {
24 Cell::new(None)
25 }
26}
27
28/// Flag to indicate OUTPUT_CAPTURE is used.
29///
30/// If it is None and was never set on any thread, this flag is set to false,
31/// and OUTPUT_CAPTURE can be safely ignored on all threads, saving some time
32/// and memory registering an unused thread local.
33///
34/// Note about memory ordering: This contains information about whether a
35/// thread local variable might be in use. Although this is a global flag, the
36/// memory ordering between threads does not matter: we only want this flag to
37/// have a consistent order between set_output_capture and print_to *within
38/// the same thread*. Within the same thread, things always have a perfectly
39/// consistent order. So Ordering::Relaxed is fine.
40static OUTPUT_CAPTURE_USED: Atomic<bool> = AtomicBool::new(false);
41
42/// A handle to a raw instance of the standard input stream of this process.
43///
44/// This handle is not synchronized or buffered in any fashion. Constructed via
45/// the `std::io::stdio::stdin_raw` function.
46struct StdinRaw(stdio::Stdin);
47
48/// A handle to a raw instance of the standard output stream of this process.
49///
50/// This handle is not synchronized or buffered in any fashion. Constructed via
51/// the `std::io::stdio::stdout_raw` function.
52struct StdoutRaw(stdio::Stdout);
53
54/// A handle to a raw instance of the standard output stream of this process.
55///
56/// This handle is not synchronized or buffered in any fashion. Constructed via
57/// the `std::io::stdio::stderr_raw` function.
58struct StderrRaw(stdio::Stderr);
59
60/// Constructs a new raw handle to the standard input of this process.
61///
62/// The returned handle does not interact with any other handles created nor
63/// handles returned by `std::io::stdin`. Data buffered by the `std::io::stdin`
64/// handles is **not** available to raw handles returned from this function.
65///
66/// The returned handle has no external synchronization or buffering.
67#[unstable(feature = "libstd_sys_internals", issue = "none")]
68const fn stdin_raw() -> StdinRaw {
69 StdinRaw(stdio::Stdin::new())
70}
71
72/// Constructs a new raw handle to the standard output stream of this process.
73///
74/// The returned handle does not interact with any other handles created nor
75/// handles returned by `std::io::stdout`. Note that data is buffered by the
76/// `std::io::stdout` handles so writes which happen via this raw handle may
77/// appear before previous writes.
78///
79/// The returned handle has no external synchronization or buffering layered on
80/// top.
81#[unstable(feature = "libstd_sys_internals", issue = "none")]
82const fn stdout_raw() -> StdoutRaw {
83 StdoutRaw(stdio::Stdout::new())
84}
85
86/// Constructs a new raw handle to the standard error stream of this process.
87///
88/// The returned handle does not interact with any other handles created nor
89/// handles returned by `std::io::stderr`.
90///
91/// The returned handle has no external synchronization or buffering layered on
92/// top.
93#[unstable(feature = "libstd_sys_internals", issue = "none")]
94const fn stderr_raw() -> StderrRaw {
95 StderrRaw(stdio::Stderr::new())
96}
97
98impl Read for StdinRaw {
99 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
100 self.0.read(buf)
101 }
102
103 fn read_buf(&mut self, buf: BorrowedCursor<'_, u8>) -> io::Result<()> {
104 self.0.read_buf(buf)
105 }
106
107 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
108 self.0.read_vectored(bufs)
109 }
110
111 #[inline]
112 fn is_read_vectored(&self) -> bool {
113 self.0.is_read_vectored()
114 }
115
116 fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
117 if buf.is_empty() {
118 return Ok(());
119 }
120 self.0.read_exact(buf)
121 }
122
123 fn read_buf_exact(&mut self, buf: BorrowedCursor<'_, u8>) -> io::Result<()> {
124 if buf.capacity() == 0 {
125 return Ok(());
126 }
127 self.0.read_buf_exact(buf)
128 }
129
130 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
131 self.0.read_to_end(buf)
132 }
133
134 fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
135 self.0.read_to_string(buf)
136 }
137}
138
139impl Write for StdoutRaw {
140 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
141 self.0.write(buf)
142 }
143
144 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
145 self.0.write_vectored(bufs)
146 }
147
148 #[inline]
149 fn is_write_vectored(&self) -> bool {
150 self.0.is_write_vectored()
151 }
152
153 fn flush(&mut self) -> io::Result<()> {
154 self.0.flush()
155 }
156
157 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
158 self.0.write_all(buf)
159 }
160
161 fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> {
162 self.0.write_all_vectored(bufs)
163 }
164
165 fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> io::Result<()> {
166 self.0.write_fmt(fmt)
167 }
168}
169
170impl Write for StderrRaw {
171 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
172 self.0.write(buf)
173 }
174
175 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
176 self.0.write_vectored(bufs)
177 }
178
179 #[inline]
180 fn is_write_vectored(&self) -> bool {
181 self.0.is_write_vectored()
182 }
183
184 fn flush(&mut self) -> io::Result<()> {
185 self.0.flush()
186 }
187
188 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
189 self.0.write_all(buf)
190 }
191
192 fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> {
193 self.0.write_all_vectored(bufs)
194 }
195
196 fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> io::Result<()> {
197 self.0.write_fmt(fmt)
198 }
199}
200
201/// A handle to the standard input stream of a process.
202///
203/// Each handle is a shared reference to a global buffer of input data to this
204/// process. A handle can be `lock`'d to gain full access to [`BufRead`] methods
205/// (e.g., `.lines()`). Reads to this handle are otherwise locked with respect
206/// to other reads.
207///
208/// This handle implements the `Read` trait, but beware that concurrent reads
209/// of `Stdin` must be executed with care.
210///
211/// Created by the [`io::stdin`] method.
212///
213/// [`io::stdin`]: stdin
214///
215/// ### Note: Windows Portability Considerations
216///
217/// When operating in a console, the Windows implementation of this stream does not support
218/// non-UTF-8 byte sequences. Attempting to read bytes that are not valid UTF-8 will return
219/// an error.
220///
221/// In a process with a detached console, such as one using
222/// `#![windows_subsystem = "windows"]`, or in a child process spawned from such a process,
223/// the contained handle will be null. In such cases, the standard library's `Read` and
224/// `Write` will do nothing and silently succeed. All other I/O operations, via the
225/// standard library or via raw Windows API calls, will fail.
226///
227/// # Examples
228///
229/// ```no_run
230/// use std::io;
231///
232/// fn main() -> io::Result<()> {
233/// let mut buffer = String::new();
234/// let stdin = io::stdin(); // We get `Stdin` here.
235/// stdin.read_line(&mut buffer)?;
236/// Ok(())
237/// }
238/// ```
239#[stable(feature = "rust1", since = "1.0.0")]
240#[cfg_attr(not(test), rustc_diagnostic_item = "Stdin")]
241pub struct Stdin {
242 inner: &'static Mutex<BufReader<StdinRaw>>,
243}
244
245/// A locked reference to the [`Stdin`] handle.
246///
247/// This handle implements both the [`Read`] and [`BufRead`] traits, and
248/// is constructed via the [`Stdin::lock`] method.
249///
250/// ### Note: Windows Portability Considerations
251///
252/// When operating in a console, the Windows implementation of this stream does not support
253/// non-UTF-8 byte sequences. Attempting to read bytes that are not valid UTF-8 will return
254/// an error.
255///
256/// In a process with a detached console, such as one using
257/// `#![windows_subsystem = "windows"]`, or in a child process spawned from such a process,
258/// the contained handle will be null. In such cases, the standard library's `Read` and
259/// `Write` will do nothing and silently succeed. All other I/O operations, via the
260/// standard library or via raw Windows API calls, will fail.
261///
262/// # Examples
263///
264/// ```no_run
265/// use std::io::{self, BufRead};
266///
267/// fn main() -> io::Result<()> {
268/// let mut buffer = String::new();
269/// let stdin = io::stdin(); // We get `Stdin` here.
270/// {
271/// let mut handle = stdin.lock(); // We get `StdinLock` here.
272/// handle.read_line(&mut buffer)?;
273/// } // `StdinLock` is dropped here.
274/// Ok(())
275/// }
276/// ```
277#[must_use = "if unused stdin will immediately unlock"]
278#[stable(feature = "rust1", since = "1.0.0")]
279#[cfg_attr(not(test), rustc_diagnostic_item = "StdinLock")]
280pub struct StdinLock<'a> {
281 inner: MutexGuard<'a, BufReader<StdinRaw>>,
282}
283
284/// Constructs a new handle to the standard input of the current process.
285///
286/// Each handle returned is a reference to a shared global buffer whose access
287/// is synchronized via a mutex. If you need more explicit control over
288/// locking, see the [`Stdin::lock`] method.
289///
290/// ### Note: Windows Portability Considerations
291///
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
294/// an error.
295///
296/// In a process with a detached console, such as one using
297/// `#![windows_subsystem = "windows"]`, or in a child process spawned from such a process,
298/// the contained handle will be null. In such cases, the standard library's `Read` and
299/// `Write` will do nothing and silently succeed. All other I/O operations, via the
300/// standard library or via raw Windows API calls, will fail.
301///
302/// # Examples
303///
304/// Using implicit synchronization:
305///
306/// ```no_run
307/// use std::io;
308///
309/// fn main() -> io::Result<()> {
310/// let mut buffer = String::new();
311/// io::stdin().read_line(&mut buffer)?;
312/// Ok(())
313/// }
314/// ```
315///
316/// Using explicit synchronization:
317///
318/// ```no_run
319/// use std::io::{self, BufRead};
320///
321/// fn main() -> io::Result<()> {
322/// let mut buffer = String::new();
323/// let stdin = io::stdin();
324/// let mut handle = stdin.lock();
325///
326/// handle.read_line(&mut buffer)?;
327/// Ok(())
328/// }
329/// ```
330#[must_use]
331#[stable(feature = "rust1", since = "1.0.0")]
332pub fn stdin() -> Stdin {
333 static INSTANCE: OnceLock<Mutex<BufReader<StdinRaw>>> = OnceLock::new();
334 Stdin {
335 inner: INSTANCE.get_or_init(|| {
336 Mutex::new(BufReader::with_capacity(stdio::STDIN_BUF_SIZE, stdin_raw()))
337 }),
338 }
339}
340
341impl Stdin {
342 /// Locks this handle to the standard input stream, returning a readable
343 /// guard.
344 ///
345 /// The lock is released when the returned lock goes out of scope. The
346 /// returned guard also implements the [`Read`] and [`BufRead`] traits for
347 /// accessing the underlying data.
348 ///
349 /// # Examples
350 ///
351 /// ```no_run
352 /// use std::io::{self, BufRead};
353 ///
354 /// fn main() -> io::Result<()> {
355 /// let mut buffer = String::new();
356 /// let stdin = io::stdin();
357 /// let mut handle = stdin.lock();
358 ///
359 /// handle.read_line(&mut buffer)?;
360 /// Ok(())
361 /// }
362 /// ```
363 #[stable(feature = "rust1", since = "1.0.0")]
364 pub fn lock(&self) -> StdinLock<'static> {
365 // Locks this handle with 'static lifetime. This depends on the
366 // implementation detail that the underlying `Mutex` is static.
367 StdinLock { inner: self.inner.lock().unwrap_or_else(|e| e.into_inner()) }
368 }
369
370 /// Locks this handle and reads a line of input, appending it to the specified buffer.
371 ///
372 /// For detailed semantics of this method, see the documentation on
373 /// [`BufRead::read_line`]. In particular:
374 /// * Previous content of the buffer will be preserved. To avoid appending
375 /// to the buffer, you need to [`clear`] it first.
376 /// * The trailing newline character, if any, is included in the buffer.
377 ///
378 /// [`clear`]: String::clear
379 ///
380 /// # Examples
381 ///
382 /// ```no_run
383 /// use std::io;
384 ///
385 /// let mut input = String::new();
386 /// match io::stdin().read_line(&mut input) {
387 /// Ok(n) => {
388 /// println!("{n} bytes read");
389 /// println!("{input}");
390 /// }
391 /// Err(error) => println!("error: {error}"),
392 /// }
393 /// ```
394 ///
395 /// You can run the example one of two ways:
396 ///
397 /// - Pipe some text to it, e.g., `printf foo | path/to/executable`
398 /// - Give it text interactively by running the executable directly,
399 /// in which case it will wait for the Enter key to be pressed before
400 /// continuing
401 #[stable(feature = "rust1", since = "1.0.0")]
402 #[rustc_confusables("get_line")]
403 pub fn read_line(&self, buf: &mut String) -> io::Result<usize> {
404 self.lock().read_line(buf)
405 }
406
407 /// Consumes this handle and returns an iterator over input lines.
408 ///
409 /// For detailed semantics of this method, see the documentation on
410 /// [`BufRead::lines`].
411 ///
412 /// # Examples
413 ///
414 /// ```no_run
415 /// use std::io;
416 ///
417 /// let lines = io::stdin().lines();
418 /// for line in lines {
419 /// println!("got a line: {}", line.unwrap());
420 /// }
421 /// ```
422 #[must_use = "`self` will be dropped if the result is not used"]
423 #[stable(feature = "stdin_forwarders", since = "1.62.0")]
424 pub fn lines(self) -> Lines<StdinLock<'static>> {
425 self.lock().lines()
426 }
427}
428
429#[stable(feature = "std_debug", since = "1.16.0")]
430impl fmt::Debug for Stdin {
431 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
432 f.debug_struct("Stdin").finish_non_exhaustive()
433 }
434}
435
436#[stable(feature = "rust1", since = "1.0.0")]
437impl Read for Stdin {
438 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
439 self.lock().read(buf)
440 }
441 fn read_buf(&mut self, buf: BorrowedCursor<'_, u8>) -> io::Result<()> {
442 self.lock().read_buf(buf)
443 }
444 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
445 self.lock().read_vectored(bufs)
446 }
447 #[inline]
448 fn is_read_vectored(&self) -> bool {
449 self.lock().is_read_vectored()
450 }
451 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
452 self.lock().read_to_end(buf)
453 }
454 fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
455 self.lock().read_to_string(buf)
456 }
457 fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
458 self.lock().read_exact(buf)
459 }
460 fn read_buf_exact(&mut self, cursor: BorrowedCursor<'_, u8>) -> io::Result<()> {
461 self.lock().read_buf_exact(cursor)
462 }
463}
464
465#[stable(feature = "read_shared_stdin", since = "1.78.0")]
466impl Read for &Stdin {
467 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
468 self.lock().read(buf)
469 }
470 fn read_buf(&mut self, buf: BorrowedCursor<'_, u8>) -> io::Result<()> {
471 self.lock().read_buf(buf)
472 }
473 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
474 self.lock().read_vectored(bufs)
475 }
476 #[inline]
477 fn is_read_vectored(&self) -> bool {
478 self.lock().is_read_vectored()
479 }
480 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
481 self.lock().read_to_end(buf)
482 }
483 fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
484 self.lock().read_to_string(buf)
485 }
486 fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
487 self.lock().read_exact(buf)
488 }
489 fn read_buf_exact(&mut self, cursor: BorrowedCursor<'_, u8>) -> io::Result<()> {
490 self.lock().read_buf_exact(cursor)
491 }
492}
493
494// only used by platform-dependent io::copy specializations, i.e. unused on some platforms
495#[cfg(any(target_os = "linux", target_os = "android"))]
496impl StdinLock<'_> {
497 pub(crate) fn as_mut_buf(&mut self) -> &mut BufReader<impl Read> {
498 &mut self.inner
499 }
500}
501
502#[stable(feature = "rust1", since = "1.0.0")]
503impl Read for StdinLock<'_> {
504 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
505 self.inner.read(buf)
506 }
507
508 fn read_buf(&mut self, buf: BorrowedCursor<'_, u8>) -> io::Result<()> {
509 self.inner.read_buf(buf)
510 }
511
512 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
513 self.inner.read_vectored(bufs)
514 }
515
516 #[inline]
517 fn is_read_vectored(&self) -> bool {
518 self.inner.is_read_vectored()
519 }
520
521 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
522 self.inner.read_to_end(buf)
523 }
524
525 fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
526 self.inner.read_to_string(buf)
527 }
528
529 fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
530 self.inner.read_exact(buf)
531 }
532
533 fn read_buf_exact(&mut self, cursor: BorrowedCursor<'_, u8>) -> io::Result<()> {
534 self.inner.read_buf_exact(cursor)
535 }
536}
537
538#[doc(hidden)]
539#[unstable(feature = "core_io_internals", reason = "exposed only for libstd", issue = "none")]
540impl SpecReadByte for StdinLock<'_> {
541 #[inline]
542 fn spec_read_byte(&mut self) -> Option<io::Result<u8>> {
543 BufReader::spec_read_byte(&mut *self.inner)
544 }
545}
546
547#[stable(feature = "rust1", since = "1.0.0")]
548impl BufRead for StdinLock<'_> {
549 fn fill_buf(&mut self) -> io::Result<&[u8]> {
550 self.inner.fill_buf()
551 }
552
553 fn consume(&mut self, n: usize) {
554 self.inner.consume(n)
555 }
556
557 fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> io::Result<usize> {
558 self.inner.read_until(byte, buf)
559 }
560
561 fn read_line(&mut self, buf: &mut String) -> io::Result<usize> {
562 self.inner.read_line(buf)
563 }
564}
565
566#[stable(feature = "std_debug", since = "1.16.0")]
567impl fmt::Debug for StdinLock<'_> {
568 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
569 f.debug_struct("StdinLock").finish_non_exhaustive()
570 }
571}
572
573/// A handle to the global standard output stream of the current process.
574///
575/// Each handle shares a global buffer of data to be written to the standard
576/// output stream. Access is also synchronized via a lock and explicit control
577/// over locking is available via the [`lock`] method.
578///
579/// By default, the handle is line-buffered when connected to a terminal, meaning
580/// it flushes automatically when a newline (`\n`) is encountered. For immediate
581/// output, you can manually call the [`flush`] method. When the handle goes out
582/// of scope, the buffer is automatically flushed.
583///
584/// Created by the [`io::stdout`] method.
585///
586/// ### Note: Windows Portability Considerations
587///
588/// When operating in a console, the Windows implementation of this stream decodes bytes
589/// as UTF-8, replacing malformed sequences with the Unicode replacement character (U+FFFD).
590///
591/// In a process with a detached console, such as one using
592/// `#![windows_subsystem = "windows"]`, or in a child process spawned from such a process,
593/// the contained handle will be null. In such cases, the standard library's `Read` and
594/// `Write` will do nothing and silently succeed. All other I/O operations, via the
595/// standard library or via raw Windows API calls, will fail.
596///
597/// [`lock`]: Stdout::lock
598/// [`flush`]: Write::flush
599/// [`io::stdout`]: stdout
600#[stable(feature = "rust1", since = "1.0.0")]
601pub struct Stdout {
602 // FIXME: this should be LineWriter or BufWriter depending on the state of
603 // stdout (tty or not). Note that if this is not line buffered it
604 // should also flush-on-panic or some form of flush-on-abort.
605 inner: &'static ReentrantLock<RefCell<LineWriter<StdoutRaw>>>,
606}
607
608/// A locked reference to the [`Stdout`] handle.
609///
610/// This handle implements the [`Write`] trait, and is constructed via
611/// the [`Stdout::lock`] method. See its documentation for more.
612///
613/// By default, the handle is line-buffered when connected to a terminal, meaning
614/// it flushes automatically when a newline (`\n`) is encountered. For immediate
615/// output, you can manually call the [`flush`] method. When the handle goes out
616/// of scope, the buffer is automatically flushed.
617///
618/// ### Note: Windows Portability Considerations
619///
620/// When operating in a console, the Windows implementation of this stream decodes bytes
621/// as UTF-8, replacing malformed sequences with the Unicode replacement character (U+FFFD).
622///
623/// In a process with a detached console, such as one using
624/// `#![windows_subsystem = "windows"]`, or in a child process spawned from such a process,
625/// the contained handle will be null. In such cases, the standard library's `Read` and
626/// `Write` will do nothing and silently succeed. All other I/O operations, via the
627/// standard library or via raw Windows API calls, will fail.
628///
629/// [`flush`]: Write::flush
630#[must_use = "if unused stdout will immediately unlock"]
631#[stable(feature = "rust1", since = "1.0.0")]
632pub struct StdoutLock<'a> {
633 inner: ReentrantLockGuard<'a, RefCell<LineWriter<StdoutRaw>>>,
634}
635
636static STDOUT: OnceLock<ReentrantLock<RefCell<LineWriter<StdoutRaw>>>> = OnceLock::new();
637
638/// Constructs a new handle to the standard output of the current process.
639///
640/// Each handle returned is a reference to a shared global buffer whose access
641/// is synchronized via a mutex. If you need more explicit control over
642/// locking, see the [`Stdout::lock`] method.
643///
644/// By default, the handle is line-buffered when connected to a terminal, meaning
645/// it flushes automatically when a newline (`\n`) is encountered. For immediate
646/// output, you can manually call the [`flush`] method. When the handle goes out
647/// of scope, the buffer is automatically flushed.
648///
649/// ### Note: Windows Portability Considerations
650///
651/// When operating in a console, the Windows implementation of this stream decodes bytes
652/// as UTF-8, replacing malformed sequences with the Unicode replacement character (U+FFFD).
653///
654/// In a process with a detached console, such as one using
655/// `#![windows_subsystem = "windows"]`, or in a child process spawned from such a process,
656/// the contained handle will be null. In such cases, the standard library's `Read` and
657/// `Write` will do nothing and silently succeed. All other I/O operations, via the
658/// standard library or via raw Windows API calls, will fail.
659///
660/// # Examples
661///
662/// Using implicit synchronization:
663///
664/// ```no_run
665/// use std::io::{self, Write};
666///
667/// fn main() -> io::Result<()> {
668/// io::stdout().write_all(b"hello world")?;
669///
670/// Ok(())
671/// }
672/// ```
673///
674/// Using explicit synchronization:
675///
676/// ```no_run
677/// use std::io::{self, Write};
678///
679/// fn main() -> io::Result<()> {
680/// let stdout = io::stdout();
681/// let mut handle = stdout.lock();
682///
683/// handle.write_all(b"hello world")?;
684///
685/// Ok(())
686/// }
687/// ```
688///
689/// Ensuring output is flushed immediately:
690///
691/// ```no_run
692/// use std::io::{self, Write};
693///
694/// fn main() -> io::Result<()> {
695/// let mut stdout = io::stdout();
696/// stdout.write_all(b"hello, ")?;
697/// stdout.flush()?; // Manual flush
698/// stdout.write_all(b"world!\n")?; // Automatically flushed
699/// Ok(())
700/// }
701/// ```
702///
703/// [`flush`]: Write::flush
704#[must_use]
705#[stable(feature = "rust1", since = "1.0.0")]
706#[cfg_attr(not(test), rustc_diagnostic_item = "io_stdout")]
707pub fn stdout() -> Stdout {
708 Stdout {
709 inner: STDOUT
710 .get_or_init(|| ReentrantLock::new(RefCell::new(LineWriter::new(stdout_raw())))),
711 }
712}
713
714// Flush the data and disable buffering during shutdown
715// by replacing the line writer by one with zero
716// buffering capacity.
717pub(crate) fn cleanup() {
718 let mut initialized = false;
719 let stdout = STDOUT.get_or_init(|| {
720 initialized = true;
721 ReentrantLock::new(RefCell::new(LineWriter::with_capacity(0, stdout_raw())))
722 });
723
724 if !initialized {
725 // The buffer was previously initialized, overwrite it here.
726 // We use try_lock() instead of lock(), because someone
727 // might have leaked a StdoutLock, which would
728 // otherwise cause a deadlock here.
729 if let Some(lock) = stdout.try_lock() {
730 *lock.borrow_mut() = LineWriter::with_capacity(0, stdout_raw());
731 }
732 }
733}
734
735impl Stdout {
736 /// Locks this handle to the standard output stream, returning a writable
737 /// guard.
738 ///
739 /// The lock is released when the returned lock goes out of scope. The
740 /// returned guard also implements the `Write` trait for writing data.
741 ///
742 /// # Examples
743 ///
744 /// ```no_run
745 /// use std::io::{self, Write};
746 ///
747 /// fn main() -> io::Result<()> {
748 /// let mut stdout = io::stdout().lock();
749 ///
750 /// stdout.write_all(b"hello world")?;
751 ///
752 /// Ok(())
753 /// }
754 /// ```
755 #[stable(feature = "rust1", since = "1.0.0")]
756 pub fn lock(&self) -> StdoutLock<'static> {
757 // Locks this handle with 'static lifetime. This depends on the
758 // implementation detail that the underlying `ReentrantMutex` is
759 // static.
760 StdoutLock { inner: self.inner.lock() }
761 }
762}
763
764#[stable(feature = "catch_unwind", since = "1.9.0")]
765impl UnwindSafe for Stdout {}
766
767#[stable(feature = "catch_unwind", since = "1.9.0")]
768impl RefUnwindSafe for Stdout {}
769
770#[stable(feature = "std_debug", since = "1.16.0")]
771impl fmt::Debug for Stdout {
772 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
773 f.debug_struct("Stdout").finish_non_exhaustive()
774 }
775}
776
777#[stable(feature = "rust1", since = "1.0.0")]
778impl Write for Stdout {
779 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
780 (&*self).write(buf)
781 }
782 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
783 (&*self).write_vectored(bufs)
784 }
785 #[inline]
786 fn is_write_vectored(&self) -> bool {
787 io::Write::is_write_vectored(&self)
788 }
789 fn flush(&mut self) -> io::Result<()> {
790 (&*self).flush()
791 }
792 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
793 (&*self).write_all(buf)
794 }
795 fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> {
796 (&*self).write_all_vectored(bufs)
797 }
798 fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> io::Result<()> {
799 (&*self).write_fmt(args)
800 }
801}
802
803#[stable(feature = "write_mt", since = "1.48.0")]
804impl Write for &Stdout {
805 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
806 self.lock().write(buf)
807 }
808 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
809 self.lock().write_vectored(bufs)
810 }
811 #[inline]
812 fn is_write_vectored(&self) -> bool {
813 self.lock().is_write_vectored()
814 }
815 fn flush(&mut self) -> io::Result<()> {
816 self.lock().flush()
817 }
818 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
819 self.lock().write_all(buf)
820 }
821 fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> {
822 self.lock().write_all_vectored(bufs)
823 }
824 fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> io::Result<()> {
825 self.lock().write_fmt(args)
826 }
827}
828
829#[stable(feature = "catch_unwind", since = "1.9.0")]
830impl UnwindSafe for StdoutLock<'_> {}
831
832#[stable(feature = "catch_unwind", since = "1.9.0")]
833impl RefUnwindSafe for StdoutLock<'_> {}
834
835#[stable(feature = "rust1", since = "1.0.0")]
836impl Write for StdoutLock<'_> {
837 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
838 self.inner.borrow_mut().write(buf)
839 }
840 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
841 self.inner.borrow_mut().write_vectored(bufs)
842 }
843 #[inline]
844 fn is_write_vectored(&self) -> bool {
845 self.inner.borrow_mut().is_write_vectored()
846 }
847 fn flush(&mut self) -> io::Result<()> {
848 self.inner.borrow_mut().flush()
849 }
850 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
851 self.inner.borrow_mut().write_all(buf)
852 }
853 fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> {
854 self.inner.borrow_mut().write_all_vectored(bufs)
855 }
856}
857
858#[stable(feature = "std_debug", since = "1.16.0")]
859impl fmt::Debug for StdoutLock<'_> {
860 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
861 f.debug_struct("StdoutLock").finish_non_exhaustive()
862 }
863}
864
865/// A handle to the standard error stream of a process.
866///
867/// For more information, see the [`io::stderr`] method.
868///
869/// [`io::stderr`]: stderr
870///
871/// ### Note: Windows Portability Considerations
872///
873/// When operating in a console, the Windows implementation of this stream decodes bytes
874/// as UTF-8, replacing malformed sequences with the Unicode replacement character (U+FFFD).
875///
876/// In a process with a detached console, such as one using
877/// `#![windows_subsystem = "windows"]`, or in a child process spawned from such a process,
878/// the contained handle will be null. In such cases, the standard library's `Read` and
879/// `Write` will do nothing and silently succeed. All other I/O operations, via the
880/// standard library or via raw Windows API calls, will fail.
881#[stable(feature = "rust1", since = "1.0.0")]
882pub struct Stderr {
883 inner: &'static ReentrantLock<RefCell<StderrRaw>>,
884}
885
886/// A locked reference to the [`Stderr`] handle.
887///
888/// This handle implements the [`Write`] trait and is constructed via
889/// the [`Stderr::lock`] method. See its documentation for more.
890///
891/// ### Note: Windows Portability Considerations
892///
893/// When operating in a console, the Windows implementation of this stream decodes bytes
894/// as UTF-8, replacing malformed sequences with the Unicode replacement character (U+FFFD).
895///
896/// In a process with a detached console, such as one using
897/// `#![windows_subsystem = "windows"]`, or in a child process spawned from such a process,
898/// the contained handle will be null. In such cases, the standard library's `Read` and
899/// `Write` will do nothing and silently succeed. All other I/O operations, via the
900/// standard library or via raw Windows API calls, will fail.
901#[must_use = "if unused stderr will immediately unlock"]
902#[stable(feature = "rust1", since = "1.0.0")]
903pub struct StderrLock<'a> {
904 inner: ReentrantLockGuard<'a, RefCell<StderrRaw>>,
905}
906
907/// Constructs a new handle to the standard error of the current process.
908///
909/// This handle is not buffered.
910///
911/// ### Note: Windows Portability Considerations
912///
913/// When operating in a console, the Windows implementation of this stream decodes bytes
914/// as UTF-8, replacing malformed sequences with the Unicode replacement character (U+FFFD).
915///
916/// In a process with a detached console, such as one using
917/// `#![windows_subsystem = "windows"]`, or in a child process spawned from such a process,
918/// the contained handle will be null. In such cases, the standard library's `Read` and
919/// `Write` will do nothing and silently succeed. All other I/O operations, via the
920/// standard library or via raw Windows API calls, will fail.
921///
922/// # Examples
923///
924/// Using implicit synchronization:
925///
926/// ```no_run
927/// use std::io::{self, Write};
928///
929/// fn main() -> io::Result<()> {
930/// io::stderr().write_all(b"hello world")?;
931///
932/// Ok(())
933/// }
934/// ```
935///
936/// Using explicit synchronization:
937///
938/// ```no_run
939/// use std::io::{self, Write};
940///
941/// fn main() -> io::Result<()> {
942/// let stderr = io::stderr();
943/// let mut handle = stderr.lock();
944///
945/// handle.write_all(b"hello world")?;
946///
947/// Ok(())
948/// }
949/// ```
950#[must_use]
951#[stable(feature = "rust1", since = "1.0.0")]
952#[cfg_attr(not(test), rustc_diagnostic_item = "io_stderr")]
953pub fn stderr() -> Stderr {
954 // Note that unlike `stdout()` we don't use `at_exit` here to register a
955 // destructor. Stderr is not buffered, so there's no need to run a
956 // destructor for flushing the buffer
957 static INSTANCE: ReentrantLock<RefCell<StderrRaw>> =
958 ReentrantLock::new(RefCell::new(stderr_raw()));
959
960 Stderr { inner: &INSTANCE }
961}
962
963impl Stderr {
964 /// Locks this handle to the standard error stream, returning a writable
965 /// guard.
966 ///
967 /// The lock is released when the returned lock goes out of scope. The
968 /// returned guard also implements the [`Write`] trait for writing data.
969 ///
970 /// # Examples
971 ///
972 /// ```
973 /// use std::io::{self, Write};
974 ///
975 /// fn foo() -> io::Result<()> {
976 /// let stderr = io::stderr();
977 /// let mut handle = stderr.lock();
978 ///
979 /// handle.write_all(b"hello world")?;
980 ///
981 /// Ok(())
982 /// }
983 /// ```
984 #[stable(feature = "rust1", since = "1.0.0")]
985 pub fn lock(&self) -> StderrLock<'static> {
986 // Locks this handle with 'static lifetime. This depends on the
987 // implementation detail that the underlying `ReentrantMutex` is
988 // static.
989 StderrLock { inner: self.inner.lock() }
990 }
991}
992
993#[stable(feature = "catch_unwind", since = "1.9.0")]
994impl UnwindSafe for Stderr {}
995
996#[stable(feature = "catch_unwind", since = "1.9.0")]
997impl RefUnwindSafe for Stderr {}
998
999#[stable(feature = "std_debug", since = "1.16.0")]
1000impl fmt::Debug for Stderr {
1001 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1002 f.debug_struct("Stderr").finish_non_exhaustive()
1003 }
1004}
1005
1006#[stable(feature = "rust1", since = "1.0.0")]
1007impl Write for Stderr {
1008 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
1009 (&*self).write(buf)
1010 }
1011 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
1012 (&*self).write_vectored(bufs)
1013 }
1014 #[inline]
1015 fn is_write_vectored(&self) -> bool {
1016 io::Write::is_write_vectored(&self)
1017 }
1018 fn flush(&mut self) -> io::Result<()> {
1019 (&*self).flush()
1020 }
1021 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
1022 (&*self).write_all(buf)
1023 }
1024 fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> {
1025 (&*self).write_all_vectored(bufs)
1026 }
1027 fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> io::Result<()> {
1028 (&*self).write_fmt(args)
1029 }
1030}
1031
1032#[stable(feature = "write_mt", since = "1.48.0")]
1033impl Write for &Stderr {
1034 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
1035 self.lock().write(buf)
1036 }
1037 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
1038 self.lock().write_vectored(bufs)
1039 }
1040 #[inline]
1041 fn is_write_vectored(&self) -> bool {
1042 self.lock().is_write_vectored()
1043 }
1044 fn flush(&mut self) -> io::Result<()> {
1045 self.lock().flush()
1046 }
1047 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
1048 self.lock().write_all(buf)
1049 }
1050 fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> {
1051 self.lock().write_all_vectored(bufs)
1052 }
1053 fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> io::Result<()> {
1054 self.lock().write_fmt(args)
1055 }
1056}
1057
1058#[stable(feature = "catch_unwind", since = "1.9.0")]
1059impl UnwindSafe for StderrLock<'_> {}
1060
1061#[stable(feature = "catch_unwind", since = "1.9.0")]
1062impl RefUnwindSafe for StderrLock<'_> {}
1063
1064#[stable(feature = "rust1", since = "1.0.0")]
1065impl Write for StderrLock<'_> {
1066 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
1067 self.inner.borrow_mut().write(buf)
1068 }
1069 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
1070 self.inner.borrow_mut().write_vectored(bufs)
1071 }
1072 #[inline]
1073 fn is_write_vectored(&self) -> bool {
1074 self.inner.borrow_mut().is_write_vectored()
1075 }
1076 fn flush(&mut self) -> io::Result<()> {
1077 self.inner.borrow_mut().flush()
1078 }
1079 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
1080 self.inner.borrow_mut().write_all(buf)
1081 }
1082 fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> {
1083 self.inner.borrow_mut().write_all_vectored(bufs)
1084 }
1085}
1086
1087#[stable(feature = "std_debug", since = "1.16.0")]
1088impl fmt::Debug for StderrLock<'_> {
1089 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1090 f.debug_struct("StderrLock").finish_non_exhaustive()
1091 }
1092}
1093
1094/// Sets the thread-local output capture buffer and returns the old one.
1095#[unstable(
1096 feature = "internal_output_capture",
1097 reason = "this function is meant for use in the test crate \
1098 and may disappear in the future",
1099 issue = "none"
1100)]
1101#[doc(hidden)]
1102pub fn set_output_capture(sink: Option<LocalStream>) -> Option<LocalStream> {
1103 try_set_output_capture(sink).expect(
1104 "cannot access a Thread Local Storage value \
1105 during or after destruction",
1106 )
1107}
1108
1109/// Tries to set the thread-local output capture buffer and returns the old one.
1110/// This may fail once thread-local destructors are called. It's used in panic
1111/// handling instead of `set_output_capture`.
1112#[unstable(
1113 feature = "internal_output_capture",
1114 reason = "this function is meant for use in the test crate \
1115 and may disappear in the future",
1116 issue = "none"
1117)]
1118#[doc(hidden)]
1119pub fn try_set_output_capture(
1120 sink: Option<LocalStream>,
1121) -> Result<Option<LocalStream>, AccessError> {
1122 if sink.is_none() && !OUTPUT_CAPTURE_USED.load(Ordering::Relaxed) {
1123 // OUTPUT_CAPTURE is definitely None since OUTPUT_CAPTURE_USED is false.
1124 return Ok(None);
1125 }
1126 OUTPUT_CAPTURE_USED.store(true, Ordering::Relaxed);
1127 OUTPUT_CAPTURE.try_with(move |slot| slot.replace(sink))
1128}
1129
1130/// Writes `args` to the capture buffer if enabled and possible, or `global_s`
1131/// otherwise. `label` identifies the stream in a panic message.
1132///
1133/// This function is used to print error messages, so it takes extra
1134/// care to avoid causing a panic when `OUTPUT_CAPTURE` is unusable.
1135/// For instance, if the TLS key for output capturing is already destroyed, or
1136/// if the local stream is in use by another thread, it will just fall back to
1137/// the global stream.
1138///
1139/// However, if the actual I/O causes an error, this function does panic.
1140///
1141/// Writing to non-blocking stdout/stderr can cause an error, which will lead
1142/// this function to panic.
1143fn print_to<T>(args: fmt::Arguments<'_>, global_s: fn() -> T, label: &str)
1144where
1145 T: Write,
1146{
1147 if print_to_buffer_if_capture_used(args) {
1148 // Successfully wrote to capture buffer.
1149 return;
1150 }
1151
1152 if let Err(e) = global_s().write_fmt(args)
1153 && !stdio::is_ebadf(&e)
1154 {
1155 panic!("failed printing to {label}: {e}");
1156 }
1157}
1158
1159fn print_to_buffer_if_capture_used(args: fmt::Arguments<'_>) -> bool {
1160 OUTPUT_CAPTURE_USED.load(Ordering::Relaxed)
1161 && OUTPUT_CAPTURE.try_with(|s| {
1162 // Note that we completely remove a local sink to write to in case
1163 // our printing recursively panics/prints, so the recursive
1164 // panic/print goes to the global sink instead of our local sink.
1165 s.take().map(|w| {
1166 let _ = w.lock().unwrap_or_else(|e| e.into_inner()).write_fmt(args);
1167 s.set(Some(w));
1168 })
1169 }) == Ok(Some(()))
1170}
1171
1172/// Used by impl Termination for Result to print error after `main` or a test
1173/// has returned. Should avoid panicking, although we can't help it if one of
1174/// the Display impls inside args decides to.
1175pub(crate) fn attempt_print_to_stderr(args: fmt::Arguments<'_>) {
1176 if print_to_buffer_if_capture_used(args) {
1177 return;
1178 }
1179
1180 // Ignore error if the write fails, for example because stderr is already
1181 // closed. There is not much point panicking at this point.
1182 let _ = stderr().write_fmt(args);
1183}
1184
1185/// Trait to determine if a descriptor/handle refers to a terminal/tty.
1186#[stable(feature = "is_terminal", since = "1.70.0")]
1187pub impl(crate) trait IsTerminal {
1188 /// Returns `true` if the descriptor/handle refers to a terminal/tty.
1189 ///
1190 /// On platforms where Rust does not know how to detect a terminal yet, this will return
1191 /// `false`. This will also return `false` if an unexpected error occurred, such as from
1192 /// passing an invalid file descriptor.
1193 ///
1194 /// # Platform-specific behavior
1195 ///
1196 /// On Windows, in addition to detecting consoles, this currently uses some heuristics to
1197 /// detect older msys/cygwin/mingw pseudo-terminals based on device name: devices with names
1198 /// starting with `msys-` or `cygwin-` and ending in `-pty` will be considered terminals.
1199 /// Note that this [may change in the future][changes].
1200 ///
1201 /// # Examples
1202 ///
1203 /// An example of a type for which `IsTerminal` is implemented is [`Stdin`]:
1204 ///
1205 /// ```no_run
1206 /// use std::io::{self, IsTerminal, Write};
1207 ///
1208 /// fn main() -> io::Result<()> {
1209 /// let stdin = io::stdin();
1210 ///
1211 /// // Indicate that the user is prompted for input, if this is a terminal.
1212 /// if stdin.is_terminal() {
1213 /// print!("> ");
1214 /// io::stdout().flush()?;
1215 /// }
1216 ///
1217 /// let mut name = String::new();
1218 /// let _ = stdin.read_line(&mut name)?;
1219 ///
1220 /// println!("Hello {}", name.trim_end());
1221 ///
1222 /// Ok(())
1223 /// }
1224 /// ```
1225 ///
1226 /// The example can be run in two ways:
1227 ///
1228 /// - If you run this example by piping some text to it, e.g. `echo "foo" | path/to/executable`
1229 /// it will print: `Hello foo`.
1230 /// - If you instead run the example interactively by running `path/to/executable` directly, it will
1231 /// prompt for input.
1232 ///
1233 /// [changes]: io#platform-specific-behavior
1234 /// [`Stdin`]: crate::io::Stdin
1235 #[doc(alias = "isatty", alias = "atty")]
1236 #[stable(feature = "is_terminal", since = "1.70.0")]
1237 fn is_terminal(&self) -> bool;
1238}
1239
1240macro_rules! impl_is_terminal {
1241 ($($t:ty),*$(,)?) => {$(
1242 #[stable(feature = "is_terminal", since = "1.70.0")]
1243 impl IsTerminal for $t {
1244 #[inline]
1245 fn is_terminal(&self) -> bool {
1246 crate::sys::io::is_terminal(self)
1247 }
1248 }
1249 )*}
1250}
1251
1252impl_is_terminal!(File, Stdin, StdinLock<'_>, Stdout, StdoutLock<'_>, Stderr, StderrLock<'_>);
1253
1254#[unstable(
1255 feature = "print_internals",
1256 reason = "implementation detail which may disappear or be replaced at any time",
1257 issue = "none"
1258)]
1259#[doc(hidden)]
1260#[cfg(not(test))]
1261pub fn _print(args: fmt::Arguments<'_>) {
1262 print_to(args, stdout, "stdout");
1263}
1264
1265#[unstable(
1266 feature = "print_internals",
1267 reason = "implementation detail which may disappear or be replaced at any time",
1268 issue = "none"
1269)]
1270#[doc(hidden)]
1271#[cfg(not(test))]
1272pub fn _eprint(args: fmt::Arguments<'_>) {
1273 print_to(args, stderr, "stderr");
1274}
1275
1276#[cfg(test)]
1277pub use realstd::io::{_eprint, _print};