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