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