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