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