]> git.lizzy.rs Git - rust.git/blob - library/std/src/io/stdio.rs
Fix font color for help button in ayu and dark themes
[rust.git] / library / std / src / io / stdio.rs
1 #![cfg_attr(test, allow(unused))]
2
3 use crate::io::prelude::*;
4
5 use crate::cell::RefCell;
6 use crate::fmt;
7 use crate::io::lazy::Lazy;
8 use crate::io::{self, BufReader, Initializer, IoSlice, IoSliceMut, LineWriter};
9 use crate::sync::{Arc, Mutex, MutexGuard, Once};
10 use crate::sys::stdio;
11 use crate::sys_common::remutex::{ReentrantMutex, ReentrantMutexGuard};
12 use crate::thread::LocalKey;
13
14 thread_local! {
15     /// Stdout used by print! and println! macros
16     static LOCAL_STDOUT: RefCell<Option<Box<dyn Write + Send>>> = {
17         RefCell::new(None)
18     }
19 }
20
21 thread_local! {
22     /// Stderr used by eprint! and eprintln! macros, and panics
23     static LOCAL_STDERR: RefCell<Option<Box<dyn Write + Send>>> = {
24         RefCell::new(None)
25     }
26 }
27
28 /// A handle to a raw instance of the standard input stream of this process.
29 ///
30 /// This handle is not synchronized or buffered in any fashion. Constructed via
31 /// the `std::io::stdio::stdin_raw` function.
32 struct StdinRaw(stdio::Stdin);
33
34 /// A handle to a raw instance of the standard output stream of this process.
35 ///
36 /// This handle is not synchronized or buffered in any fashion. Constructed via
37 /// the `std::io::stdio::stdout_raw` function.
38 struct StdoutRaw(stdio::Stdout);
39
40 /// A handle to a raw instance of the standard output stream of this process.
41 ///
42 /// This handle is not synchronized or buffered in any fashion. Constructed via
43 /// the `std::io::stdio::stderr_raw` function.
44 struct StderrRaw(stdio::Stderr);
45
46 /// Constructs a new raw handle to the standard input of this process.
47 ///
48 /// The returned handle does not interact with any other handles created nor
49 /// handles returned by `std::io::stdin`. Data buffered by the `std::io::stdin`
50 /// handles is **not** available to raw handles returned from this function.
51 ///
52 /// The returned handle has no external synchronization or buffering.
53 fn stdin_raw() -> io::Result<StdinRaw> {
54     stdio::Stdin::new().map(StdinRaw)
55 }
56
57 /// Constructs a new raw handle to the standard output stream of this process.
58 ///
59 /// The returned handle does not interact with any other handles created nor
60 /// handles returned by `std::io::stdout`. Note that data is buffered by the
61 /// `std::io::stdout` handles so writes which happen via this raw handle may
62 /// appear before previous writes.
63 ///
64 /// The returned handle has no external synchronization or buffering layered on
65 /// top.
66 fn stdout_raw() -> io::Result<StdoutRaw> {
67     stdio::Stdout::new().map(StdoutRaw)
68 }
69
70 /// Constructs a new raw handle to the standard error stream of this process.
71 ///
72 /// The returned handle does not interact with any other handles created nor
73 /// handles returned by `std::io::stderr`.
74 ///
75 /// The returned handle has no external synchronization or buffering layered on
76 /// top.
77 fn stderr_raw() -> io::Result<StderrRaw> {
78     stdio::Stderr::new().map(StderrRaw)
79 }
80
81 impl Read for StdinRaw {
82     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
83         self.0.read(buf)
84     }
85
86     fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
87         self.0.read_vectored(bufs)
88     }
89
90     #[inline]
91     fn is_read_vectored(&self) -> bool {
92         self.0.is_read_vectored()
93     }
94
95     #[inline]
96     unsafe fn initializer(&self) -> Initializer {
97         Initializer::nop()
98     }
99
100     fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
101         self.0.read_to_end(buf)
102     }
103
104     fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
105         self.0.read_to_string(buf)
106     }
107
108     fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
109         self.0.read_exact(buf)
110     }
111 }
112
113 impl Write for StdoutRaw {
114     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
115         self.0.write(buf)
116     }
117
118     fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
119         self.0.write_vectored(bufs)
120     }
121
122     #[inline]
123     fn is_write_vectored(&self) -> bool {
124         self.0.is_write_vectored()
125     }
126
127     fn flush(&mut self) -> io::Result<()> {
128         self.0.flush()
129     }
130
131     fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
132         self.0.write_all(buf)
133     }
134
135     fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> {
136         self.0.write_all_vectored(bufs)
137     }
138
139     fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> io::Result<()> {
140         self.0.write_fmt(fmt)
141     }
142 }
143
144 impl Write for StderrRaw {
145     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
146         self.0.write(buf)
147     }
148
149     fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
150         self.0.write_vectored(bufs)
151     }
152
153     #[inline]
154     fn is_write_vectored(&self) -> bool {
155         self.0.is_write_vectored()
156     }
157
158     fn flush(&mut self) -> io::Result<()> {
159         self.0.flush()
160     }
161
162     fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
163         self.0.write_all(buf)
164     }
165
166     fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> {
167         self.0.write_all_vectored(bufs)
168     }
169
170     fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> io::Result<()> {
171         self.0.write_fmt(fmt)
172     }
173 }
174
175 enum Maybe<T> {
176     Real(T),
177     Fake,
178 }
179
180 impl<W: io::Write> io::Write for Maybe<W> {
181     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
182         match *self {
183             Maybe::Real(ref mut w) => handle_ebadf(w.write(buf), buf.len()),
184             Maybe::Fake => Ok(buf.len()),
185         }
186     }
187
188     fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
189         let total = bufs.iter().map(|b| b.len()).sum();
190         match self {
191             Maybe::Real(w) => handle_ebadf(w.write_vectored(bufs), total),
192             Maybe::Fake => Ok(total),
193         }
194     }
195
196     #[inline]
197     fn is_write_vectored(&self) -> bool {
198         match self {
199             Maybe::Real(w) => w.is_write_vectored(),
200             Maybe::Fake => true,
201         }
202     }
203
204     fn flush(&mut self) -> io::Result<()> {
205         match *self {
206             Maybe::Real(ref mut w) => handle_ebadf(w.flush(), ()),
207             Maybe::Fake => Ok(()),
208         }
209     }
210 }
211
212 impl<R: io::Read> io::Read for Maybe<R> {
213     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
214         match *self {
215             Maybe::Real(ref mut r) => handle_ebadf(r.read(buf), 0),
216             Maybe::Fake => Ok(0),
217         }
218     }
219
220     fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
221         match self {
222             Maybe::Real(r) => handle_ebadf(r.read_vectored(bufs), 0),
223             Maybe::Fake => Ok(0),
224         }
225     }
226
227     #[inline]
228     fn is_read_vectored(&self) -> bool {
229         match self {
230             Maybe::Real(w) => w.is_read_vectored(),
231             Maybe::Fake => true,
232         }
233     }
234 }
235
236 fn handle_ebadf<T>(r: io::Result<T>, default: T) -> io::Result<T> {
237     match r {
238         Err(ref e) if stdio::is_ebadf(e) => Ok(default),
239         r => r,
240     }
241 }
242
243 /// A handle to the standard input stream of a process.
244 ///
245 /// Each handle is a shared reference to a global buffer of input data to this
246 /// process. A handle can be `lock`'d to gain full access to [`BufRead`] methods
247 /// (e.g., `.lines()`). Reads to this handle are otherwise locked with respect
248 /// to other reads.
249 ///
250 /// This handle implements the `Read` trait, but beware that concurrent reads
251 /// of `Stdin` must be executed with care.
252 ///
253 /// Created by the [`io::stdin`] method.
254 ///
255 /// [`io::stdin`]: stdin
256 ///
257 /// ### Note: Windows Portability Consideration
258 ///
259 /// When operating in a console, the Windows implementation of this stream does not support
260 /// non-UTF-8 byte sequences. Attempting to read bytes that are not valid UTF-8 will return
261 /// an error.
262 ///
263 /// # Examples
264 ///
265 /// ```no_run
266 /// use std::io::{self, Read};
267 ///
268 /// fn main() -> io::Result<()> {
269 ///     let mut buffer = String::new();
270 ///     let mut stdin = io::stdin(); // We get `Stdin` here.
271 ///     stdin.read_to_string(&mut buffer)?;
272 ///     Ok(())
273 /// }
274 /// ```
275 #[stable(feature = "rust1", since = "1.0.0")]
276 pub struct Stdin {
277     inner: Arc<Mutex<BufReader<Maybe<StdinRaw>>>>,
278 }
279
280 /// A locked reference to the `Stdin` handle.
281 ///
282 /// This handle implements both the [`Read`] and [`BufRead`] traits, and
283 /// is constructed via the [`Stdin::lock`] method.
284 ///
285 /// ### Note: Windows Portability Consideration
286 ///
287 /// When operating in a console, the Windows implementation of this stream does not support
288 /// non-UTF-8 byte sequences. Attempting to read bytes that are not valid UTF-8 will return
289 /// an error.
290 ///
291 /// # Examples
292 ///
293 /// ```no_run
294 /// use std::io::{self, Read};
295 ///
296 /// fn main() -> io::Result<()> {
297 ///     let mut buffer = String::new();
298 ///     let stdin = io::stdin(); // We get `Stdin` here.
299 ///     {
300 ///         let mut stdin_lock = stdin.lock(); // We get `StdinLock` here.
301 ///         stdin_lock.read_to_string(&mut buffer)?;
302 ///     } // `StdinLock` is dropped here.
303 ///     Ok(())
304 /// }
305 /// ```
306 #[stable(feature = "rust1", since = "1.0.0")]
307 pub struct StdinLock<'a> {
308     inner: MutexGuard<'a, BufReader<Maybe<StdinRaw>>>,
309 }
310
311 /// Constructs a new handle to the standard input of the current process.
312 ///
313 /// Each handle returned is a reference to a shared global buffer whose access
314 /// is synchronized via a mutex. If you need more explicit control over
315 /// locking, see the [`Stdin::lock`] method.
316 ///
317 /// ### Note: Windows Portability Consideration
318 /// When operating in a console, the Windows implementation of this stream does not support
319 /// non-UTF-8 byte sequences. Attempting to read bytes that are not valid UTF-8 will return
320 /// an error.
321 ///
322 /// # Examples
323 ///
324 /// Using implicit synchronization:
325 ///
326 /// ```no_run
327 /// use std::io::{self, Read};
328 ///
329 /// fn main() -> io::Result<()> {
330 ///     let mut buffer = String::new();
331 ///     io::stdin().read_to_string(&mut buffer)?;
332 ///     Ok(())
333 /// }
334 /// ```
335 ///
336 /// Using explicit synchronization:
337 ///
338 /// ```no_run
339 /// use std::io::{self, Read};
340 ///
341 /// fn main() -> io::Result<()> {
342 ///     let mut buffer = String::new();
343 ///     let stdin = io::stdin();
344 ///     let mut handle = stdin.lock();
345 ///
346 ///     handle.read_to_string(&mut buffer)?;
347 ///     Ok(())
348 /// }
349 /// ```
350 #[stable(feature = "rust1", since = "1.0.0")]
351 pub fn stdin() -> Stdin {
352     static INSTANCE: Lazy<Mutex<BufReader<Maybe<StdinRaw>>>> = Lazy::new();
353     return Stdin {
354         inner: unsafe { INSTANCE.get(stdin_init).expect("cannot access stdin during shutdown") },
355     };
356
357     fn stdin_init() -> Arc<Mutex<BufReader<Maybe<StdinRaw>>>> {
358         // This must not reentrantly access `INSTANCE`
359         let stdin = match stdin_raw() {
360             Ok(stdin) => Maybe::Real(stdin),
361             _ => Maybe::Fake,
362         };
363
364         Arc::new(Mutex::new(BufReader::with_capacity(stdio::STDIN_BUF_SIZE, stdin)))
365     }
366 }
367
368 impl Stdin {
369     /// Locks this handle to the standard input stream, returning a readable
370     /// guard.
371     ///
372     /// The lock is released when the returned lock goes out of scope. The
373     /// returned guard also implements the [`Read`] and [`BufRead`] traits for
374     /// accessing the underlying data.
375     ///
376     /// # Examples
377     ///
378     /// ```no_run
379     /// use std::io::{self, Read};
380     ///
381     /// fn main() -> io::Result<()> {
382     ///     let mut buffer = String::new();
383     ///     let stdin = io::stdin();
384     ///     let mut handle = stdin.lock();
385     ///
386     ///     handle.read_to_string(&mut buffer)?;
387     ///     Ok(())
388     /// }
389     /// ```
390     #[stable(feature = "rust1", since = "1.0.0")]
391     pub fn lock(&self) -> StdinLock<'_> {
392         StdinLock { inner: self.inner.lock().unwrap_or_else(|e| e.into_inner()) }
393     }
394
395     /// Locks this handle and reads a line of input, appending it to the specified buffer.
396     ///
397     /// For detailed semantics of this method, see the documentation on
398     /// [`BufRead::read_line`].
399     ///
400     /// # Examples
401     ///
402     /// ```no_run
403     /// use std::io;
404     ///
405     /// let mut input = String::new();
406     /// match io::stdin().read_line(&mut input) {
407     ///     Ok(n) => {
408     ///         println!("{} bytes read", n);
409     ///         println!("{}", input);
410     ///     }
411     ///     Err(error) => println!("error: {}", error),
412     /// }
413     /// ```
414     ///
415     /// You can run the example one of two ways:
416     ///
417     /// - Pipe some text to it, e.g., `printf foo | path/to/executable`
418     /// - Give it text interactively by running the executable directly,
419     ///   in which case it will wait for the Enter key to be pressed before
420     ///   continuing
421     #[stable(feature = "rust1", since = "1.0.0")]
422     pub fn read_line(&self, buf: &mut String) -> io::Result<usize> {
423         self.lock().read_line(buf)
424     }
425 }
426
427 #[stable(feature = "std_debug", since = "1.16.0")]
428 impl fmt::Debug for Stdin {
429     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
430         f.pad("Stdin { .. }")
431     }
432 }
433
434 #[stable(feature = "rust1", since = "1.0.0")]
435 impl Read for Stdin {
436     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
437         self.lock().read(buf)
438     }
439     fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
440         self.lock().read_vectored(bufs)
441     }
442     #[inline]
443     fn is_read_vectored(&self) -> bool {
444         self.lock().is_read_vectored()
445     }
446     #[inline]
447     unsafe fn initializer(&self) -> Initializer {
448         Initializer::nop()
449     }
450     fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
451         self.lock().read_to_end(buf)
452     }
453     fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
454         self.lock().read_to_string(buf)
455     }
456     fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
457         self.lock().read_exact(buf)
458     }
459 }
460
461 #[stable(feature = "rust1", since = "1.0.0")]
462 impl Read for StdinLock<'_> {
463     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
464         self.inner.read(buf)
465     }
466
467     fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
468         self.inner.read_vectored(bufs)
469     }
470
471     #[inline]
472     fn is_read_vectored(&self) -> bool {
473         self.inner.is_read_vectored()
474     }
475
476     #[inline]
477     unsafe fn initializer(&self) -> Initializer {
478         Initializer::nop()
479     }
480
481     fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
482         self.inner.read_to_end(buf)
483     }
484
485     fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
486         self.inner.read_to_string(buf)
487     }
488
489     fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
490         self.inner.read_exact(buf)
491     }
492 }
493
494 #[stable(feature = "rust1", since = "1.0.0")]
495 impl BufRead for StdinLock<'_> {
496     fn fill_buf(&mut self) -> io::Result<&[u8]> {
497         self.inner.fill_buf()
498     }
499
500     fn consume(&mut self, n: usize) {
501         self.inner.consume(n)
502     }
503
504     fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> io::Result<usize> {
505         self.inner.read_until(byte, buf)
506     }
507
508     fn read_line(&mut self, buf: &mut String) -> io::Result<usize> {
509         self.inner.read_line(buf)
510     }
511 }
512
513 #[stable(feature = "std_debug", since = "1.16.0")]
514 impl fmt::Debug for StdinLock<'_> {
515     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
516         f.pad("StdinLock { .. }")
517     }
518 }
519
520 /// A handle to the global standard output stream of the current process.
521 ///
522 /// Each handle shares a global buffer of data to be written to the standard
523 /// output stream. Access is also synchronized via a lock and explicit control
524 /// over locking is available via the [`lock`] method.
525 ///
526 /// Created by the [`io::stdout`] method.
527 ///
528 /// ### Note: Windows Portability Consideration
529 /// When operating in a console, the Windows implementation of this stream does not support
530 /// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
531 /// an error.
532 ///
533 /// [`lock`]: Stdout::lock
534 /// [`io::stdout`]: stdout
535 #[stable(feature = "rust1", since = "1.0.0")]
536 pub struct Stdout {
537     // FIXME: this should be LineWriter or BufWriter depending on the state of
538     //        stdout (tty or not). Note that if this is not line buffered it
539     //        should also flush-on-panic or some form of flush-on-abort.
540     inner: Arc<ReentrantMutex<RefCell<LineWriter<Maybe<StdoutRaw>>>>>,
541 }
542
543 /// A locked reference to the `Stdout` handle.
544 ///
545 /// This handle implements the [`Write`] trait, and is constructed via
546 /// the [`Stdout::lock`] method.
547 ///
548 /// ### Note: Windows Portability Consideration
549 /// When operating in a console, the Windows implementation of this stream does not support
550 /// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
551 /// an error.
552 #[stable(feature = "rust1", since = "1.0.0")]
553 pub struct StdoutLock<'a> {
554     inner: ReentrantMutexGuard<'a, RefCell<LineWriter<Maybe<StdoutRaw>>>>,
555 }
556
557 /// Constructs a new handle to the standard output of the current process.
558 ///
559 /// Each handle returned is a reference to a shared global buffer whose access
560 /// is synchronized via a mutex. If you need more explicit control over
561 /// locking, see the [`Stdout::lock`] method.
562 ///
563 /// ### Note: Windows Portability Consideration
564 /// When operating in a console, the Windows implementation of this stream does not support
565 /// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
566 /// an error.
567 ///
568 /// # Examples
569 ///
570 /// Using implicit synchronization:
571 ///
572 /// ```no_run
573 /// use std::io::{self, Write};
574 ///
575 /// fn main() -> io::Result<()> {
576 ///     io::stdout().write_all(b"hello world")?;
577 ///
578 ///     Ok(())
579 /// }
580 /// ```
581 ///
582 /// Using explicit synchronization:
583 ///
584 /// ```no_run
585 /// use std::io::{self, Write};
586 ///
587 /// fn main() -> io::Result<()> {
588 ///     let stdout = io::stdout();
589 ///     let mut handle = stdout.lock();
590 ///
591 ///     handle.write_all(b"hello world")?;
592 ///
593 ///     Ok(())
594 /// }
595 /// ```
596 #[stable(feature = "rust1", since = "1.0.0")]
597 pub fn stdout() -> Stdout {
598     static INSTANCE: Lazy<ReentrantMutex<RefCell<LineWriter<Maybe<StdoutRaw>>>>> = Lazy::new();
599     return Stdout {
600         inner: unsafe { INSTANCE.get(stdout_init).expect("cannot access stdout during shutdown") },
601     };
602
603     fn stdout_init() -> Arc<ReentrantMutex<RefCell<LineWriter<Maybe<StdoutRaw>>>>> {
604         // This must not reentrantly access `INSTANCE`
605         let stdout = match stdout_raw() {
606             Ok(stdout) => Maybe::Real(stdout),
607             _ => Maybe::Fake,
608         };
609         unsafe {
610             let ret = Arc::new(ReentrantMutex::new(RefCell::new(LineWriter::new(stdout))));
611             ret.init();
612             ret
613         }
614     }
615 }
616
617 impl Stdout {
618     /// Locks this handle to the standard output stream, returning a writable
619     /// guard.
620     ///
621     /// The lock is released when the returned lock goes out of scope. The
622     /// returned guard also implements the `Write` trait for writing data.
623     ///
624     /// # Examples
625     ///
626     /// ```no_run
627     /// use std::io::{self, Write};
628     ///
629     /// fn main() -> io::Result<()> {
630     ///     let stdout = io::stdout();
631     ///     let mut handle = stdout.lock();
632     ///
633     ///     handle.write_all(b"hello world")?;
634     ///
635     ///     Ok(())
636     /// }
637     /// ```
638     #[stable(feature = "rust1", since = "1.0.0")]
639     pub fn lock(&self) -> StdoutLock<'_> {
640         StdoutLock { inner: self.inner.lock() }
641     }
642 }
643
644 #[stable(feature = "std_debug", since = "1.16.0")]
645 impl fmt::Debug for Stdout {
646     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
647         f.pad("Stdout { .. }")
648     }
649 }
650
651 #[stable(feature = "rust1", since = "1.0.0")]
652 impl Write for Stdout {
653     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
654         self.lock().write(buf)
655     }
656     fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
657         self.lock().write_vectored(bufs)
658     }
659     #[inline]
660     fn is_write_vectored(&self) -> bool {
661         self.lock().is_write_vectored()
662     }
663     fn flush(&mut self) -> io::Result<()> {
664         self.lock().flush()
665     }
666     fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
667         self.lock().write_all(buf)
668     }
669     fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> {
670         self.lock().write_all_vectored(bufs)
671     }
672     fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> io::Result<()> {
673         self.lock().write_fmt(args)
674     }
675 }
676 #[stable(feature = "rust1", since = "1.0.0")]
677 impl Write for StdoutLock<'_> {
678     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
679         self.inner.borrow_mut().write(buf)
680     }
681     fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
682         self.inner.borrow_mut().write_vectored(bufs)
683     }
684     #[inline]
685     fn is_write_vectored(&self) -> bool {
686         self.inner.borrow_mut().is_write_vectored()
687     }
688     fn flush(&mut self) -> io::Result<()> {
689         self.inner.borrow_mut().flush()
690     }
691     fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
692         self.inner.borrow_mut().write_all(buf)
693     }
694     fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> {
695         self.inner.borrow_mut().write_all_vectored(bufs)
696     }
697 }
698
699 #[stable(feature = "std_debug", since = "1.16.0")]
700 impl fmt::Debug for StdoutLock<'_> {
701     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
702         f.pad("StdoutLock { .. }")
703     }
704 }
705
706 /// A handle to the standard error stream of a process.
707 ///
708 /// For more information, see the [`io::stderr`] method.
709 ///
710 /// [`io::stderr`]: stderr
711 ///
712 /// ### Note: Windows Portability Consideration
713 /// When operating in a console, the Windows implementation of this stream does not support
714 /// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
715 /// an error.
716 #[stable(feature = "rust1", since = "1.0.0")]
717 pub struct Stderr {
718     inner: &'static ReentrantMutex<RefCell<Maybe<StderrRaw>>>,
719 }
720
721 /// A locked reference to the `Stderr` handle.
722 ///
723 /// This handle implements the `Write` trait and is constructed via
724 /// the [`Stderr::lock`] method.
725 ///
726 /// ### Note: Windows Portability Consideration
727 /// When operating in a console, the Windows implementation of this stream does not support
728 /// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
729 /// an error.
730 #[stable(feature = "rust1", since = "1.0.0")]
731 pub struct StderrLock<'a> {
732     inner: ReentrantMutexGuard<'a, RefCell<Maybe<StderrRaw>>>,
733 }
734
735 /// Constructs a new handle to the standard error of the current process.
736 ///
737 /// This handle is not buffered.
738 ///
739 /// ### Note: Windows Portability Consideration
740 /// When operating in a console, the Windows implementation of this stream does not support
741 /// non-UTF-8 byte sequences. Attempting to write bytes that are not valid UTF-8 will return
742 /// an error.
743 ///
744 /// # Examples
745 ///
746 /// Using implicit synchronization:
747 ///
748 /// ```no_run
749 /// use std::io::{self, Write};
750 ///
751 /// fn main() -> io::Result<()> {
752 ///     io::stderr().write_all(b"hello world")?;
753 ///
754 ///     Ok(())
755 /// }
756 /// ```
757 ///
758 /// Using explicit synchronization:
759 ///
760 /// ```no_run
761 /// use std::io::{self, Write};
762 ///
763 /// fn main() -> io::Result<()> {
764 ///     let stderr = io::stderr();
765 ///     let mut handle = stderr.lock();
766 ///
767 ///     handle.write_all(b"hello world")?;
768 ///
769 ///     Ok(())
770 /// }
771 /// ```
772 #[stable(feature = "rust1", since = "1.0.0")]
773 pub fn stderr() -> Stderr {
774     // Note that unlike `stdout()` we don't use `Lazy` here which registers a
775     // destructor. Stderr is not buffered nor does the `stderr_raw` type consume
776     // any owned resources, so there's no need to run any destructors at some
777     // point in the future.
778     //
779     // This has the added benefit of allowing `stderr` to be usable during
780     // process shutdown as well!
781     static INSTANCE: ReentrantMutex<RefCell<Maybe<StderrRaw>>> =
782         unsafe { ReentrantMutex::new(RefCell::new(Maybe::Fake)) };
783
784     // When accessing stderr we need one-time initialization of the reentrant
785     // mutex, followed by one-time detection of whether we actually have a
786     // stderr handle or not. Afterwards we can just always use the now-filled-in
787     // `INSTANCE` value.
788     static INIT: Once = Once::new();
789     INIT.call_once(|| unsafe {
790         INSTANCE.init();
791         if let Ok(stderr) = stderr_raw() {
792             *INSTANCE.lock().borrow_mut() = Maybe::Real(stderr);
793         }
794     });
795     Stderr { inner: &INSTANCE }
796 }
797
798 impl Stderr {
799     /// Locks this handle to the standard error stream, returning a writable
800     /// guard.
801     ///
802     /// The lock is released when the returned lock goes out of scope. The
803     /// returned guard also implements the [`Write`] trait for writing data.
804     ///
805     /// # Examples
806     ///
807     /// ```
808     /// use std::io::{self, Write};
809     ///
810     /// fn foo() -> io::Result<()> {
811     ///     let stderr = io::stderr();
812     ///     let mut handle = stderr.lock();
813     ///
814     ///     handle.write_all(b"hello world")?;
815     ///
816     ///     Ok(())
817     /// }
818     /// ```
819     #[stable(feature = "rust1", since = "1.0.0")]
820     pub fn lock(&self) -> StderrLock<'_> {
821         StderrLock { inner: self.inner.lock() }
822     }
823 }
824
825 #[stable(feature = "std_debug", since = "1.16.0")]
826 impl fmt::Debug for Stderr {
827     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
828         f.pad("Stderr { .. }")
829     }
830 }
831
832 #[stable(feature = "rust1", since = "1.0.0")]
833 impl Write for Stderr {
834     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
835         self.lock().write(buf)
836     }
837     fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
838         self.lock().write_vectored(bufs)
839     }
840     #[inline]
841     fn is_write_vectored(&self) -> bool {
842         self.lock().is_write_vectored()
843     }
844     fn flush(&mut self) -> io::Result<()> {
845         self.lock().flush()
846     }
847     fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
848         self.lock().write_all(buf)
849     }
850     fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> {
851         self.lock().write_all_vectored(bufs)
852     }
853     fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> io::Result<()> {
854         self.lock().write_fmt(args)
855     }
856 }
857 #[stable(feature = "rust1", since = "1.0.0")]
858 impl Write for StderrLock<'_> {
859     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
860         self.inner.borrow_mut().write(buf)
861     }
862     fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
863         self.inner.borrow_mut().write_vectored(bufs)
864     }
865     #[inline]
866     fn is_write_vectored(&self) -> bool {
867         self.inner.borrow_mut().is_write_vectored()
868     }
869     fn flush(&mut self) -> io::Result<()> {
870         self.inner.borrow_mut().flush()
871     }
872     fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
873         self.inner.borrow_mut().write_all(buf)
874     }
875     fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> {
876         self.inner.borrow_mut().write_all_vectored(bufs)
877     }
878 }
879
880 #[stable(feature = "std_debug", since = "1.16.0")]
881 impl fmt::Debug for StderrLock<'_> {
882     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
883         f.pad("StderrLock { .. }")
884     }
885 }
886
887 /// Resets the thread-local stderr handle to the specified writer
888 ///
889 /// This will replace the current thread's stderr handle, returning the old
890 /// handle. All future calls to `panic!` and friends will emit their output to
891 /// this specified handle.
892 ///
893 /// Note that this does not need to be called for all new threads; the default
894 /// output handle is to the process's stderr stream.
895 #[unstable(
896     feature = "set_stdio",
897     reason = "this function may disappear completely or be replaced \
898                      with a more general mechanism",
899     issue = "none"
900 )]
901 #[doc(hidden)]
902 pub fn set_panic(sink: Option<Box<dyn Write + Send>>) -> Option<Box<dyn Write + Send>> {
903     use crate::mem;
904     LOCAL_STDERR.with(move |slot| mem::replace(&mut *slot.borrow_mut(), sink)).and_then(|mut s| {
905         let _ = s.flush();
906         Some(s)
907     })
908 }
909
910 /// Resets the thread-local stdout handle to the specified writer
911 ///
912 /// This will replace the current thread's stdout handle, returning the old
913 /// handle. All future calls to `print!` and friends will emit their output to
914 /// this specified handle.
915 ///
916 /// Note that this does not need to be called for all new threads; the default
917 /// output handle is to the process's stdout stream.
918 #[unstable(
919     feature = "set_stdio",
920     reason = "this function may disappear completely or be replaced \
921                      with a more general mechanism",
922     issue = "none"
923 )]
924 #[doc(hidden)]
925 pub fn set_print(sink: Option<Box<dyn Write + Send>>) -> Option<Box<dyn Write + Send>> {
926     use crate::mem;
927     LOCAL_STDOUT.with(move |slot| mem::replace(&mut *slot.borrow_mut(), sink)).and_then(|mut s| {
928         let _ = s.flush();
929         Some(s)
930     })
931 }
932
933 /// Write `args` to output stream `local_s` if possible, `global_s`
934 /// otherwise. `label` identifies the stream in a panic message.
935 ///
936 /// This function is used to print error messages, so it takes extra
937 /// care to avoid causing a panic when `local_s` is unusable.
938 /// For instance, if the TLS key for the local stream is
939 /// already destroyed, or if the local stream is locked by another
940 /// thread, it will just fall back to the global stream.
941 ///
942 /// However, if the actual I/O causes an error, this function does panic.
943 fn print_to<T>(
944     args: fmt::Arguments<'_>,
945     local_s: &'static LocalKey<RefCell<Option<Box<dyn Write + Send>>>>,
946     global_s: fn() -> T,
947     label: &str,
948 ) where
949     T: Write,
950 {
951     let result = local_s
952         .try_with(|s| {
953             // Note that we completely remove a local sink to write to in case
954             // our printing recursively panics/prints, so the recursive
955             // panic/print goes to the global sink instead of our local sink.
956             let prev = s.borrow_mut().take();
957             if let Some(mut w) = prev {
958                 let result = w.write_fmt(args);
959                 *s.borrow_mut() = Some(w);
960                 return result;
961             }
962             global_s().write_fmt(args)
963         })
964         .unwrap_or_else(|_| global_s().write_fmt(args));
965
966     if let Err(e) = result {
967         panic!("failed printing to {}: {}", label, e);
968     }
969 }
970
971 #[unstable(
972     feature = "print_internals",
973     reason = "implementation detail which may disappear or be replaced at any time",
974     issue = "none"
975 )]
976 #[doc(hidden)]
977 #[cfg(not(test))]
978 pub fn _print(args: fmt::Arguments<'_>) {
979     print_to(args, &LOCAL_STDOUT, stdout, "stdout");
980 }
981
982 #[unstable(
983     feature = "print_internals",
984     reason = "implementation detail which may disappear or be replaced at any time",
985     issue = "none"
986 )]
987 #[doc(hidden)]
988 #[cfg(not(test))]
989 pub fn _eprint(args: fmt::Arguments<'_>) {
990     print_to(args, &LOCAL_STDERR, stderr, "stderr");
991 }
992
993 #[cfg(test)]
994 pub use realstd::io::{_eprint, _print};
995
996 #[cfg(test)]
997 mod tests {
998     use super::*;
999     use crate::panic::{RefUnwindSafe, UnwindSafe};
1000     use crate::thread;
1001
1002     #[test]
1003     fn stdout_unwind_safe() {
1004         assert_unwind_safe::<Stdout>();
1005     }
1006     #[test]
1007     fn stdoutlock_unwind_safe() {
1008         assert_unwind_safe::<StdoutLock<'_>>();
1009         assert_unwind_safe::<StdoutLock<'static>>();
1010     }
1011     #[test]
1012     fn stderr_unwind_safe() {
1013         assert_unwind_safe::<Stderr>();
1014     }
1015     #[test]
1016     fn stderrlock_unwind_safe() {
1017         assert_unwind_safe::<StderrLock<'_>>();
1018         assert_unwind_safe::<StderrLock<'static>>();
1019     }
1020
1021     fn assert_unwind_safe<T: UnwindSafe + RefUnwindSafe>() {}
1022
1023     #[test]
1024     #[cfg_attr(target_os = "emscripten", ignore)]
1025     fn panic_doesnt_poison() {
1026         thread::spawn(|| {
1027             let _a = stdin();
1028             let _a = _a.lock();
1029             let _a = stdout();
1030             let _a = _a.lock();
1031             let _a = stderr();
1032             let _a = _a.lock();
1033             panic!();
1034         })
1035         .join()
1036         .unwrap_err();
1037
1038         let _a = stdin();
1039         let _a = _a.lock();
1040         let _a = stdout();
1041         let _a = _a.lock();
1042         let _a = stderr();
1043         let _a = _a.lock();
1044     }
1045 }