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