]> git.lizzy.rs Git - rust.git/blob - library/std/src/io/stdio.rs
Merge set_panic and set_print into set_output_capture.
[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};
11 use crate::lazy::SyncOnceCell;
12 use crate::sync::atomic::{AtomicBool, Ordering};
13 use crate::sync::{Arc, Mutex, MutexGuard};
14 use crate::sys::stdio;
15 use crate::sys_common;
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 stdin_lock = stdin.lock(); // We get `StdinLock` here.
254 ///         stdin_lock.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 impl Stdin {
314     /// Locks this handle to the standard input stream, returning a readable
315     /// guard.
316     ///
317     /// The lock is released when the returned lock goes out of scope. The
318     /// returned guard also implements the [`Read`] and [`BufRead`] traits for
319     /// accessing the underlying data.
320     ///
321     /// # Examples
322     ///
323     /// ```no_run
324     /// use std::io::{self, Read};
325     ///
326     /// fn main() -> io::Result<()> {
327     ///     let mut buffer = String::new();
328     ///     let stdin = io::stdin();
329     ///     let mut handle = stdin.lock();
330     ///
331     ///     handle.read_to_string(&mut buffer)?;
332     ///     Ok(())
333     /// }
334     /// ```
335     #[stable(feature = "rust1", since = "1.0.0")]
336     pub fn lock(&self) -> StdinLock<'_> {
337         StdinLock { inner: self.inner.lock().unwrap_or_else(|e| e.into_inner()) }
338     }
339
340     /// Locks this handle and reads a line of input, appending it to the specified buffer.
341     ///
342     /// For detailed semantics of this method, see the documentation on
343     /// [`BufRead::read_line`].
344     ///
345     /// # Examples
346     ///
347     /// ```no_run
348     /// use std::io;
349     ///
350     /// let mut input = String::new();
351     /// match io::stdin().read_line(&mut input) {
352     ///     Ok(n) => {
353     ///         println!("{} bytes read", n);
354     ///         println!("{}", input);
355     ///     }
356     ///     Err(error) => println!("error: {}", error),
357     /// }
358     /// ```
359     ///
360     /// You can run the example one of two ways:
361     ///
362     /// - Pipe some text to it, e.g., `printf foo | path/to/executable`
363     /// - Give it text interactively by running the executable directly,
364     ///   in which case it will wait for the Enter key to be pressed before
365     ///   continuing
366     #[stable(feature = "rust1", since = "1.0.0")]
367     pub fn read_line(&self, buf: &mut String) -> io::Result<usize> {
368         self.lock().read_line(buf)
369     }
370 }
371
372 #[stable(feature = "std_debug", since = "1.16.0")]
373 impl fmt::Debug for Stdin {
374     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
375         f.pad("Stdin { .. }")
376     }
377 }
378
379 #[stable(feature = "rust1", since = "1.0.0")]
380 impl Read for Stdin {
381     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
382         self.lock().read(buf)
383     }
384     fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
385         self.lock().read_vectored(bufs)
386     }
387     #[inline]
388     fn is_read_vectored(&self) -> bool {
389         self.lock().is_read_vectored()
390     }
391     #[inline]
392     unsafe fn initializer(&self) -> Initializer {
393         Initializer::nop()
394     }
395     fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
396         self.lock().read_to_end(buf)
397     }
398     fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
399         self.lock().read_to_string(buf)
400     }
401     fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
402         self.lock().read_exact(buf)
403     }
404 }
405
406 #[stable(feature = "rust1", since = "1.0.0")]
407 impl Read for StdinLock<'_> {
408     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
409         self.inner.read(buf)
410     }
411
412     fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
413         self.inner.read_vectored(bufs)
414     }
415
416     #[inline]
417     fn is_read_vectored(&self) -> bool {
418         self.inner.is_read_vectored()
419     }
420
421     #[inline]
422     unsafe fn initializer(&self) -> Initializer {
423         Initializer::nop()
424     }
425
426     fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
427         self.inner.read_to_end(buf)
428     }
429
430     fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
431         self.inner.read_to_string(buf)
432     }
433
434     fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
435         self.inner.read_exact(buf)
436     }
437 }
438
439 #[stable(feature = "rust1", since = "1.0.0")]
440 impl BufRead for StdinLock<'_> {
441     fn fill_buf(&mut self) -> io::Result<&[u8]> {
442         self.inner.fill_buf()
443     }
444
445     fn consume(&mut self, n: usize) {
446         self.inner.consume(n)
447     }
448
449     fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> io::Result<usize> {
450         self.inner.read_until(byte, buf)
451     }
452
453     fn read_line(&mut self, buf: &mut String) -> io::Result<usize> {
454         self.inner.read_line(buf)
455     }
456 }
457
458 #[stable(feature = "std_debug", since = "1.16.0")]
459 impl fmt::Debug for StdinLock<'_> {
460     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
461         f.pad("StdinLock { .. }")
462     }
463 }
464
465 /// A handle to the global standard output stream of the current process.
466 ///
467 /// Each handle shares a global buffer of data to be written to the standard
468 /// output stream. Access is also synchronized via a lock and explicit control
469 /// over locking is available via the [`lock`] method.
470 ///
471 /// Created by the [`io::stdout`] method.
472 ///
473 /// ### Note: Windows Portability Consideration
474 /// When operating in a console, the Windows implementation of this stream does not support
475 /// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
476 /// an error.
477 ///
478 /// [`lock`]: Stdout::lock
479 /// [`io::stdout`]: stdout
480 #[stable(feature = "rust1", since = "1.0.0")]
481 pub struct Stdout {
482     // FIXME: this should be LineWriter or BufWriter depending on the state of
483     //        stdout (tty or not). Note that if this is not line buffered it
484     //        should also flush-on-panic or some form of flush-on-abort.
485     inner: &'static ReentrantMutex<RefCell<LineWriter<StdoutRaw>>>,
486 }
487
488 /// A locked reference to the `Stdout` handle.
489 ///
490 /// This handle implements the [`Write`] trait, and is constructed via
491 /// the [`Stdout::lock`] method.
492 ///
493 /// ### Note: Windows Portability Consideration
494 /// When operating in a console, the Windows implementation of this stream does not support
495 /// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
496 /// an error.
497 #[stable(feature = "rust1", since = "1.0.0")]
498 pub struct StdoutLock<'a> {
499     inner: ReentrantMutexGuard<'a, RefCell<LineWriter<StdoutRaw>>>,
500 }
501
502 /// Constructs a new handle to the standard output of the current process.
503 ///
504 /// Each handle returned is a reference to a shared global buffer whose access
505 /// is synchronized via a mutex. If you need more explicit control over
506 /// locking, see the [`Stdout::lock`] method.
507 ///
508 /// ### Note: Windows Portability Consideration
509 /// When operating in a console, the Windows implementation of this stream does not support
510 /// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
511 /// an error.
512 ///
513 /// # Examples
514 ///
515 /// Using implicit synchronization:
516 ///
517 /// ```no_run
518 /// use std::io::{self, Write};
519 ///
520 /// fn main() -> io::Result<()> {
521 ///     io::stdout().write_all(b"hello world")?;
522 ///
523 ///     Ok(())
524 /// }
525 /// ```
526 ///
527 /// Using explicit synchronization:
528 ///
529 /// ```no_run
530 /// use std::io::{self, Write};
531 ///
532 /// fn main() -> io::Result<()> {
533 ///     let stdout = io::stdout();
534 ///     let mut handle = stdout.lock();
535 ///
536 ///     handle.write_all(b"hello world")?;
537 ///
538 ///     Ok(())
539 /// }
540 /// ```
541 #[stable(feature = "rust1", since = "1.0.0")]
542 pub fn stdout() -> Stdout {
543     static INSTANCE: SyncOnceCell<ReentrantMutex<RefCell<LineWriter<StdoutRaw>>>> =
544         SyncOnceCell::new();
545     Stdout {
546         inner: INSTANCE.get_or_init(|| unsafe {
547             let _ = sys_common::at_exit(|| {
548                 if let Some(instance) = INSTANCE.get() {
549                     // Flush the data and disable buffering during shutdown
550                     // by replacing the line writer by one with zero
551                     // buffering capacity.
552                     // We use try_lock() instead of lock(), because someone
553                     // might have leaked a StdoutLock, which would
554                     // otherwise cause a deadlock here.
555                     if let Some(lock) = instance.try_lock() {
556                         *lock.borrow_mut() = LineWriter::with_capacity(0, stdout_raw());
557                     }
558                 }
559             });
560             let r = ReentrantMutex::new(RefCell::new(LineWriter::new(stdout_raw())));
561             r.init();
562             r
563         }),
564     }
565 }
566
567 impl Stdout {
568     /// Locks this handle to the standard output stream, returning a writable
569     /// guard.
570     ///
571     /// The lock is released when the returned lock goes out of scope. The
572     /// returned guard also implements the `Write` trait for writing data.
573     ///
574     /// # Examples
575     ///
576     /// ```no_run
577     /// use std::io::{self, Write};
578     ///
579     /// fn main() -> io::Result<()> {
580     ///     let stdout = io::stdout();
581     ///     let mut handle = stdout.lock();
582     ///
583     ///     handle.write_all(b"hello world")?;
584     ///
585     ///     Ok(())
586     /// }
587     /// ```
588     #[stable(feature = "rust1", since = "1.0.0")]
589     pub fn lock(&self) -> StdoutLock<'_> {
590         StdoutLock { inner: self.inner.lock() }
591     }
592 }
593
594 #[stable(feature = "std_debug", since = "1.16.0")]
595 impl fmt::Debug for Stdout {
596     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
597         f.pad("Stdout { .. }")
598     }
599 }
600
601 #[stable(feature = "rust1", since = "1.0.0")]
602 impl Write for Stdout {
603     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
604         (&*self).write(buf)
605     }
606     fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
607         (&*self).write_vectored(bufs)
608     }
609     #[inline]
610     fn is_write_vectored(&self) -> bool {
611         io::Write::is_write_vectored(&&*self)
612     }
613     fn flush(&mut self) -> io::Result<()> {
614         (&*self).flush()
615     }
616     fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
617         (&*self).write_all(buf)
618     }
619     fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> {
620         (&*self).write_all_vectored(bufs)
621     }
622     fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> io::Result<()> {
623         (&*self).write_fmt(args)
624     }
625 }
626
627 #[stable(feature = "write_mt", since = "1.48.0")]
628 impl Write for &Stdout {
629     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
630         self.lock().write(buf)
631     }
632     fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
633         self.lock().write_vectored(bufs)
634     }
635     #[inline]
636     fn is_write_vectored(&self) -> bool {
637         self.lock().is_write_vectored()
638     }
639     fn flush(&mut self) -> io::Result<()> {
640         self.lock().flush()
641     }
642     fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
643         self.lock().write_all(buf)
644     }
645     fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> {
646         self.lock().write_all_vectored(bufs)
647     }
648     fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> io::Result<()> {
649         self.lock().write_fmt(args)
650     }
651 }
652
653 #[stable(feature = "rust1", since = "1.0.0")]
654 impl Write for StdoutLock<'_> {
655     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
656         self.inner.borrow_mut().write(buf)
657     }
658     fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
659         self.inner.borrow_mut().write_vectored(bufs)
660     }
661     #[inline]
662     fn is_write_vectored(&self) -> bool {
663         self.inner.borrow_mut().is_write_vectored()
664     }
665     fn flush(&mut self) -> io::Result<()> {
666         self.inner.borrow_mut().flush()
667     }
668     fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
669         self.inner.borrow_mut().write_all(buf)
670     }
671     fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> {
672         self.inner.borrow_mut().write_all_vectored(bufs)
673     }
674 }
675
676 #[stable(feature = "std_debug", since = "1.16.0")]
677 impl fmt::Debug for StdoutLock<'_> {
678     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
679         f.pad("StdoutLock { .. }")
680     }
681 }
682
683 /// A handle to the standard error stream of a process.
684 ///
685 /// For more information, see the [`io::stderr`] method.
686 ///
687 /// [`io::stderr`]: stderr
688 ///
689 /// ### Note: Windows Portability Consideration
690 /// When operating in a console, the Windows implementation of this stream does not support
691 /// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
692 /// an error.
693 #[stable(feature = "rust1", since = "1.0.0")]
694 pub struct Stderr {
695     inner: &'static ReentrantMutex<RefCell<StderrRaw>>,
696 }
697
698 /// A locked reference to the `Stderr` handle.
699 ///
700 /// This handle implements the `Write` trait and is constructed via
701 /// the [`Stderr::lock`] method.
702 ///
703 /// ### Note: Windows Portability Consideration
704 /// When operating in a console, the Windows implementation of this stream does not support
705 /// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
706 /// an error.
707 #[stable(feature = "rust1", since = "1.0.0")]
708 pub struct StderrLock<'a> {
709     inner: ReentrantMutexGuard<'a, RefCell<StderrRaw>>,
710 }
711
712 /// Constructs a new handle to the standard error of the current process.
713 ///
714 /// This handle is not buffered.
715 ///
716 /// ### Note: Windows Portability Consideration
717 /// When operating in a console, the Windows implementation of this stream does not support
718 /// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
719 /// an error.
720 ///
721 /// # Examples
722 ///
723 /// Using implicit synchronization:
724 ///
725 /// ```no_run
726 /// use std::io::{self, Write};
727 ///
728 /// fn main() -> io::Result<()> {
729 ///     io::stderr().write_all(b"hello world")?;
730 ///
731 ///     Ok(())
732 /// }
733 /// ```
734 ///
735 /// Using explicit synchronization:
736 ///
737 /// ```no_run
738 /// use std::io::{self, Write};
739 ///
740 /// fn main() -> io::Result<()> {
741 ///     let stderr = io::stderr();
742 ///     let mut handle = stderr.lock();
743 ///
744 ///     handle.write_all(b"hello world")?;
745 ///
746 ///     Ok(())
747 /// }
748 /// ```
749 #[stable(feature = "rust1", since = "1.0.0")]
750 pub fn stderr() -> Stderr {
751     // Note that unlike `stdout()` we don't use `Lazy` here which registers a
752     // destructor. Stderr is not buffered nor does the `stderr_raw` type consume
753     // any owned resources, so there's no need to run any destructors at some
754     // point in the future.
755     //
756     // This has the added benefit of allowing `stderr` to be usable during
757     // process shutdown as well!
758     static INSTANCE: SyncOnceCell<ReentrantMutex<RefCell<StderrRaw>>> = SyncOnceCell::new();
759
760     Stderr {
761         inner: INSTANCE.get_or_init(|| unsafe {
762             let r = ReentrantMutex::new(RefCell::new(stderr_raw()));
763             r.init();
764             r
765         }),
766     }
767 }
768
769 impl Stderr {
770     /// Locks this handle to the standard error stream, returning a writable
771     /// guard.
772     ///
773     /// The lock is released when the returned lock goes out of scope. The
774     /// returned guard also implements the [`Write`] trait for writing data.
775     ///
776     /// # Examples
777     ///
778     /// ```
779     /// use std::io::{self, Write};
780     ///
781     /// fn foo() -> io::Result<()> {
782     ///     let stderr = io::stderr();
783     ///     let mut handle = stderr.lock();
784     ///
785     ///     handle.write_all(b"hello world")?;
786     ///
787     ///     Ok(())
788     /// }
789     /// ```
790     #[stable(feature = "rust1", since = "1.0.0")]
791     pub fn lock(&self) -> StderrLock<'_> {
792         StderrLock { inner: self.inner.lock() }
793     }
794 }
795
796 #[stable(feature = "std_debug", since = "1.16.0")]
797 impl fmt::Debug for Stderr {
798     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
799         f.pad("Stderr { .. }")
800     }
801 }
802
803 #[stable(feature = "rust1", since = "1.0.0")]
804 impl Write for Stderr {
805     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
806         (&*self).write(buf)
807     }
808     fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
809         (&*self).write_vectored(bufs)
810     }
811     #[inline]
812     fn is_write_vectored(&self) -> bool {
813         io::Write::is_write_vectored(&&*self)
814     }
815     fn flush(&mut self) -> io::Result<()> {
816         (&*self).flush()
817     }
818     fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
819         (&*self).write_all(buf)
820     }
821     fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> {
822         (&*self).write_all_vectored(bufs)
823     }
824     fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> io::Result<()> {
825         (&*self).write_fmt(args)
826     }
827 }
828
829 #[stable(feature = "write_mt", since = "1.48.0")]
830 impl Write for &Stderr {
831     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
832         self.lock().write(buf)
833     }
834     fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
835         self.lock().write_vectored(bufs)
836     }
837     #[inline]
838     fn is_write_vectored(&self) -> bool {
839         self.lock().is_write_vectored()
840     }
841     fn flush(&mut self) -> io::Result<()> {
842         self.lock().flush()
843     }
844     fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
845         self.lock().write_all(buf)
846     }
847     fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> {
848         self.lock().write_all_vectored(bufs)
849     }
850     fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> io::Result<()> {
851         self.lock().write_fmt(args)
852     }
853 }
854
855 #[stable(feature = "rust1", since = "1.0.0")]
856 impl Write for StderrLock<'_> {
857     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
858         self.inner.borrow_mut().write(buf)
859     }
860     fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
861         self.inner.borrow_mut().write_vectored(bufs)
862     }
863     #[inline]
864     fn is_write_vectored(&self) -> bool {
865         self.inner.borrow_mut().is_write_vectored()
866     }
867     fn flush(&mut self) -> io::Result<()> {
868         self.inner.borrow_mut().flush()
869     }
870     fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
871         self.inner.borrow_mut().write_all(buf)
872     }
873     fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> {
874         self.inner.borrow_mut().write_all_vectored(bufs)
875     }
876 }
877
878 #[stable(feature = "std_debug", since = "1.16.0")]
879 impl fmt::Debug for StderrLock<'_> {
880     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
881         f.pad("StderrLock { .. }")
882     }
883 }
884
885 /// Sets the thread-local output capture buffer and returns the old one.
886 #[unstable(
887     feature = "internal_output_capture",
888     reason = "this function is meant for use in the test crate \
889         and may disappear in the future",
890     issue = "none"
891 )]
892 #[doc(hidden)]
893 pub fn set_output_capture(sink: Option<LocalStream>) -> Option<LocalStream> {
894     if sink.is_none() && !OUTPUT_CAPTURE_USED.load(Ordering::Relaxed) {
895         // OUTPUT_CAPTURE is definitely None since OUTPUT_CAPTURE_USED is false.
896         return None;
897     }
898     OUTPUT_CAPTURE_USED.store(true, Ordering::Relaxed);
899     OUTPUT_CAPTURE.with(move |slot| slot.replace(sink))
900 }
901
902 /// Write `args` to the capture buffer if enabled and possible, or `global_s`
903 /// otherwise. `label` identifies the stream in a panic message.
904 ///
905 /// This function is used to print error messages, so it takes extra
906 /// care to avoid causing a panic when `local_s` is unusable.
907 /// For instance, if the TLS key for the local stream is
908 /// already destroyed, or if the local stream is locked by another
909 /// thread, it will just fall back to the global stream.
910 ///
911 /// However, if the actual I/O causes an error, this function does panic.
912 fn print_to<T>(args: fmt::Arguments<'_>, global_s: fn() -> T, label: &str)
913 where
914     T: Write,
915 {
916     if OUTPUT_CAPTURE_USED.load(Ordering::Relaxed)
917         && OUTPUT_CAPTURE.try_with(|s| {
918             // Note that we completely remove a local sink to write to in case
919             // our printing recursively panics/prints, so the recursive
920             // panic/print goes to the global sink instead of our local sink.
921             s.take().map(|w| {
922                 let _ = w.lock().unwrap_or_else(|e| e.into_inner()).write_fmt(args);
923                 s.set(Some(w));
924             })
925         }) == Ok(Some(()))
926     {
927         // Succesfully wrote to capture buffer.
928         return;
929     }
930
931     if let Err(e) = global_s().write_fmt(args) {
932         panic!("failed printing to {}: {}", label, e);
933     }
934 }
935
936 #[unstable(
937     feature = "print_internals",
938     reason = "implementation detail which may disappear or be replaced at any time",
939     issue = "none"
940 )]
941 #[doc(hidden)]
942 #[cfg(not(test))]
943 pub fn _print(args: fmt::Arguments<'_>) {
944     print_to(args, stdout, "stdout");
945 }
946
947 #[unstable(
948     feature = "print_internals",
949     reason = "implementation detail which may disappear or be replaced at any time",
950     issue = "none"
951 )]
952 #[doc(hidden)]
953 #[cfg(not(test))]
954 pub fn _eprint(args: fmt::Arguments<'_>) {
955     print_to(args, stderr, "stderr");
956 }
957
958 #[cfg(test)]
959 pub use realstd::io::{_eprint, _print};