]> git.lizzy.rs Git - rust.git/blob - src/libstd/io/stdio.rs
Rollup merge of #35363 - GuillaumeGomez:err_codes, r=jonathandturner
[rust.git] / src / libstd / io / stdio.rs
1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use prelude::v1::*;
12 use io::prelude::*;
13
14 use cell::{RefCell, BorrowState};
15 use fmt;
16 use io::lazy::Lazy;
17 use io::{self, BufReader, LineWriter};
18 use sync::{Arc, Mutex, MutexGuard};
19 use sys::stdio;
20 use sys_common::remutex::{ReentrantMutex, ReentrantMutexGuard};
21 use thread::LocalKeyState;
22
23 /// Stdout used by print! and println! macros
24 thread_local! {
25     static LOCAL_STDOUT: RefCell<Option<Box<Write + Send>>> = {
26         RefCell::new(None)
27     }
28 }
29
30 /// A handle to a raw instance of the standard input stream of this process.
31 ///
32 /// This handle is not synchronized or buffered in any fashion. Constructed via
33 /// the `std::io::stdio::stdin_raw` function.
34 struct StdinRaw(stdio::Stdin);
35
36 /// A handle to a raw instance of the standard output stream of this process.
37 ///
38 /// This handle is not synchronized or buffered in any fashion. Constructed via
39 /// the `std::io::stdio::stdout_raw` function.
40 struct StdoutRaw(stdio::Stdout);
41
42 /// A handle to a raw instance of the standard output stream of this process.
43 ///
44 /// This handle is not synchronized or buffered in any fashion. Constructed via
45 /// the `std::io::stdio::stderr_raw` function.
46 struct StderrRaw(stdio::Stderr);
47
48 /// Constructs a new raw handle to the standard input of this process.
49 ///
50 /// The returned handle does not interact with any other handles created nor
51 /// handles returned by `std::io::stdin`. Data buffered by the `std::io::stdin`
52 /// handles is **not** available to raw handles returned from this function.
53 ///
54 /// The returned handle has no external synchronization or buffering.
55 fn stdin_raw() -> io::Result<StdinRaw> { stdio::Stdin::new().map(StdinRaw) }
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> { stdio::Stdout::new().map(StdoutRaw) }
67
68 /// Constructs a new raw handle to the standard error stream of this process.
69 ///
70 /// The returned handle does not interact with any other handles created nor
71 /// handles returned by `std::io::stderr`.
72 ///
73 /// The returned handle has no external synchronization or buffering layered on
74 /// top.
75 fn stderr_raw() -> io::Result<StderrRaw> { stdio::Stderr::new().map(StderrRaw) }
76
77 impl Read for StdinRaw {
78     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) }
79     fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
80         self.0.read_to_end(buf)
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<()> { Ok(()) }
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<()> { Ok(()) }
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     fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
121         match *self {
122             Maybe::Real(ref mut r) => handle_ebadf(r.read_to_end(buf), 0),
123             Maybe::Fake => Ok(0)
124         }
125     }
126 }
127
128 fn handle_ebadf<T>(r: io::Result<T>, default: T) -> io::Result<T> {
129     #[cfg(windows)]
130     const ERR: i32 = ::sys::c::ERROR_INVALID_HANDLE as i32;
131     #[cfg(not(windows))]
132     const ERR: i32 = ::libc::EBADF as i32;
133
134     match r {
135         Err(ref e) if e.raw_os_error() == Some(ERR) => Ok(default),
136         r => r
137     }
138 }
139
140 /// A handle to the standard input stream of a process.
141 ///
142 /// Each handle is a shared reference to a global buffer of input data to this
143 /// process. A handle can be `lock`'d to gain full access to [`BufRead`] methods
144 /// (e.g. `.lines()`). Reads to this handle are otherwise locked with respect
145 /// to other reads.
146 ///
147 /// This handle implements the `Read` trait, but beware that concurrent reads
148 /// of `Stdin` must be executed with care.
149 ///
150 /// Created by the [`io::stdin`] method.
151 ///
152 /// [`io::stdin`]: fn.stdin.html
153 /// [`BufRead`]: trait.BufRead.html
154 #[stable(feature = "rust1", since = "1.0.0")]
155 pub struct Stdin {
156     inner: Arc<Mutex<BufReader<Maybe<StdinRaw>>>>,
157 }
158
159 /// A locked reference to the `Stdin` handle.
160 ///
161 /// This handle implements both the [`Read`] and [`BufRead`] traits, and
162 /// is constructed via the [`Stdin::lock`] method.
163 ///
164 /// [`Read`]: trait.Read.html
165 /// [`BufRead`]: trait.BufRead.html
166 /// [`Stdin::lock`]: struct.Stdin.html#method.lock
167 #[stable(feature = "rust1", since = "1.0.0")]
168 pub struct StdinLock<'a> {
169     inner: MutexGuard<'a, BufReader<Maybe<StdinRaw>>>,
170 }
171
172 /// Constructs a new handle to the standard input of the current process.
173 ///
174 /// Each handle returned is a reference to a shared global buffer whose access
175 /// is synchronized via a mutex. If you need more explicit control over
176 /// locking, see the [`lock() method`][lock].
177 ///
178 /// [lock]: struct.Stdin.html#method.lock
179 ///
180 /// # Examples
181 ///
182 /// Using implicit synchronization:
183 ///
184 /// ```
185 /// use std::io::{self, Read};
186 ///
187 /// # fn foo() -> io::Result<String> {
188 /// let mut buffer = String::new();
189 /// try!(io::stdin().read_to_string(&mut buffer));
190 /// # Ok(buffer)
191 /// # }
192 /// ```
193 ///
194 /// Using explicit synchronization:
195 ///
196 /// ```
197 /// use std::io::{self, Read};
198 ///
199 /// # fn foo() -> io::Result<String> {
200 /// let mut buffer = String::new();
201 /// let stdin = io::stdin();
202 /// let mut handle = stdin.lock();
203 ///
204 /// try!(handle.read_to_string(&mut buffer));
205 /// # Ok(buffer)
206 /// # }
207 /// ```
208 #[stable(feature = "rust1", since = "1.0.0")]
209 pub fn stdin() -> Stdin {
210     static INSTANCE: Lazy<Mutex<BufReader<Maybe<StdinRaw>>>> = Lazy::new(stdin_init);
211     return Stdin {
212         inner: INSTANCE.get().expect("cannot access stdin during shutdown"),
213     };
214
215     fn stdin_init() -> Arc<Mutex<BufReader<Maybe<StdinRaw>>>> {
216         let stdin = match stdin_raw() {
217             Ok(stdin) => Maybe::Real(stdin),
218             _ => Maybe::Fake
219         };
220
221         // The default buffer capacity is 64k, but apparently windows
222         // doesn't like 64k reads on stdin. See #13304 for details, but the
223         // idea is that on windows we use a slightly smaller buffer that's
224         // been seen to be acceptable.
225         Arc::new(Mutex::new(if cfg!(windows) {
226             BufReader::with_capacity(8 * 1024, stdin)
227         } else {
228             BufReader::new(stdin)
229         }))
230     }
231 }
232
233 impl Stdin {
234     /// Locks this handle to the standard input stream, returning a readable
235     /// guard.
236     ///
237     /// The lock is released when the returned lock goes out of scope. The
238     /// returned guard also implements the [`Read`] and [`BufRead`] traits for
239     /// accessing the underlying data.
240     ///
241     /// [`Read`]: trait.Read.html
242     /// [`BufRead`]: trait.BufRead.html
243     ///
244     /// # Examples
245     ///
246     /// ```
247     /// use std::io::{self, Read};
248     ///
249     /// # fn foo() -> io::Result<String> {
250     /// let mut buffer = String::new();
251     /// let stdin = io::stdin();
252     /// let mut handle = stdin.lock();
253     ///
254     /// try!(handle.read_to_string(&mut buffer));
255     /// # Ok(buffer)
256     /// # }
257     /// ```
258     #[stable(feature = "rust1", since = "1.0.0")]
259     pub fn lock(&self) -> StdinLock {
260         StdinLock { inner: self.inner.lock().unwrap_or_else(|e| e.into_inner()) }
261     }
262
263     /// Locks this handle and reads a line of input into the specified buffer.
264     ///
265     /// For detailed semantics of this method, see the documentation on
266     /// [`BufRead::read_line`].
267     ///
268     /// [`BufRead::read_line`]: trait.BufRead.html#method.read_line
269     ///
270     /// # Examples
271     ///
272     /// ```no_run
273     /// use std::io;
274     ///
275     /// let mut input = String::new();
276     /// match io::stdin().read_line(&mut input) {
277     ///     Ok(n) => {
278     ///         println!("{} bytes read", n);
279     ///         println!("{}", input);
280     ///     }
281     ///     Err(error) => println!("error: {}", error),
282     /// }
283     /// ```
284     ///
285     /// You can run the example one of two ways:
286     ///
287     /// - Pipe some text to it, e.g. `printf foo | path/to/executable`
288     /// - Give it text interactively by running the executable directly,
289     ///   in which case it will wait for the Enter key to be pressed before
290     ///   continuing
291     #[stable(feature = "rust1", since = "1.0.0")]
292     pub fn read_line(&self, buf: &mut String) -> io::Result<usize> {
293         self.lock().read_line(buf)
294     }
295 }
296
297 #[stable(feature = "rust1", since = "1.0.0")]
298 impl Read for Stdin {
299     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
300         self.lock().read(buf)
301     }
302     fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
303         self.lock().read_to_end(buf)
304     }
305     fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
306         self.lock().read_to_string(buf)
307     }
308     fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
309         self.lock().read_exact(buf)
310     }
311 }
312
313 #[stable(feature = "rust1", since = "1.0.0")]
314 impl<'a> Read for StdinLock<'a> {
315     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
316         self.inner.read(buf)
317     }
318     fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
319         self.inner.read_to_end(buf)
320     }
321 }
322
323 #[stable(feature = "rust1", since = "1.0.0")]
324 impl<'a> BufRead for StdinLock<'a> {
325     fn fill_buf(&mut self) -> io::Result<&[u8]> { self.inner.fill_buf() }
326     fn consume(&mut self, n: usize) { self.inner.consume(n) }
327 }
328
329 /// A handle to the global standard output stream of the current process.
330 ///
331 /// Each handle shares a global buffer of data to be written to the standard
332 /// output stream. Access is also synchronized via a lock and explicit control
333 /// over locking is available via the `lock` method.
334 ///
335 /// Created by the [`io::stdout`] method.
336 ///
337 /// [`io::stdout`]: fn.stdout.html
338 #[stable(feature = "rust1", since = "1.0.0")]
339 pub struct Stdout {
340     // FIXME: this should be LineWriter or BufWriter depending on the state of
341     //        stdout (tty or not). Note that if this is not line buffered it
342     //        should also flush-on-panic or some form of flush-on-abort.
343     inner: Arc<ReentrantMutex<RefCell<LineWriter<Maybe<StdoutRaw>>>>>,
344 }
345
346 /// A locked reference to the `Stdout` handle.
347 ///
348 /// This handle implements the [`Write`] trait, and is constructed via
349 /// the [`Stdout::lock`] method.
350 ///
351 /// [`Write`]: trait.Write.html
352 /// [`Stdout::lock`]: struct.Stdout.html#method.lock
353 #[stable(feature = "rust1", since = "1.0.0")]
354 pub struct StdoutLock<'a> {
355     inner: ReentrantMutexGuard<'a, RefCell<LineWriter<Maybe<StdoutRaw>>>>,
356 }
357
358 /// Constructs a new handle to the standard output of the current process.
359 ///
360 /// Each handle returned is a reference to a shared global buffer whose access
361 /// is synchronized via a mutex. If you need more explicit control over
362 /// locking, see the [Stdout::lock] method.
363 ///
364 /// [Stdout::lock]: struct.Stdout.html#method.lock
365 ///
366 /// # Examples
367 ///
368 /// Using implicit synchronization:
369 ///
370 /// ```
371 /// use std::io::{self, Write};
372 ///
373 /// # fn foo() -> io::Result<()> {
374 /// try!(io::stdout().write(b"hello world"));
375 ///
376 /// # Ok(())
377 /// # }
378 /// ```
379 ///
380 /// Using explicit synchronization:
381 ///
382 /// ```
383 /// use std::io::{self, Write};
384 ///
385 /// # fn foo() -> io::Result<()> {
386 /// let stdout = io::stdout();
387 /// let mut handle = stdout.lock();
388 ///
389 /// try!(handle.write(b"hello world"));
390 ///
391 /// # Ok(())
392 /// # }
393 /// ```
394 #[stable(feature = "rust1", since = "1.0.0")]
395 pub fn stdout() -> Stdout {
396     static INSTANCE: Lazy<ReentrantMutex<RefCell<LineWriter<Maybe<StdoutRaw>>>>>
397         = Lazy::new(stdout_init);
398     return Stdout {
399         inner: INSTANCE.get().expect("cannot access stdout during shutdown"),
400     };
401
402     fn stdout_init() -> Arc<ReentrantMutex<RefCell<LineWriter<Maybe<StdoutRaw>>>>> {
403         let stdout = match stdout_raw() {
404             Ok(stdout) => Maybe::Real(stdout),
405             _ => Maybe::Fake,
406         };
407         Arc::new(ReentrantMutex::new(RefCell::new(LineWriter::new(stdout))))
408     }
409 }
410
411 impl Stdout {
412     /// Locks this handle to the standard output stream, returning a writable
413     /// guard.
414     ///
415     /// The lock is released when the returned lock goes out of scope. The
416     /// returned guard also implements the `Write` trait for writing data.
417     ///
418     /// # Examples
419     ///
420     /// ```
421     /// use std::io::{self, Write};
422     ///
423     /// # fn foo() -> io::Result<()> {
424     /// let stdout = io::stdout();
425     /// let mut handle = stdout.lock();
426     ///
427     /// try!(handle.write(b"hello world"));
428     ///
429     /// # Ok(())
430     /// # }
431     /// ```
432     #[stable(feature = "rust1", since = "1.0.0")]
433     pub fn lock(&self) -> StdoutLock {
434         StdoutLock { inner: self.inner.lock().unwrap_or_else(|e| e.into_inner()) }
435     }
436 }
437
438 #[stable(feature = "rust1", since = "1.0.0")]
439 impl Write for Stdout {
440     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
441         self.lock().write(buf)
442     }
443     fn flush(&mut self) -> io::Result<()> {
444         self.lock().flush()
445     }
446     fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
447         self.lock().write_all(buf)
448     }
449     fn write_fmt(&mut self, args: fmt::Arguments) -> io::Result<()> {
450         self.lock().write_fmt(args)
451     }
452 }
453 #[stable(feature = "rust1", since = "1.0.0")]
454 impl<'a> Write for StdoutLock<'a> {
455     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
456         self.inner.borrow_mut().write(buf)
457     }
458     fn flush(&mut self) -> io::Result<()> {
459         self.inner.borrow_mut().flush()
460     }
461 }
462
463 /// A handle to the standard error stream of a process.
464 ///
465 /// For more information, see the [`io::stderr`] method.
466 ///
467 /// [`io::stderr`]: fn.stderr.html
468 #[stable(feature = "rust1", since = "1.0.0")]
469 pub struct Stderr {
470     inner: Arc<ReentrantMutex<RefCell<Maybe<StderrRaw>>>>,
471 }
472
473 /// A locked reference to the `Stderr` handle.
474 ///
475 /// This handle implements the `Write` trait and is constructed via
476 /// the [`Stderr::lock`] method.
477 ///
478 /// [`Stderr::lock`]: struct.Stderr.html#method.lock
479 #[stable(feature = "rust1", since = "1.0.0")]
480 pub struct StderrLock<'a> {
481     inner: ReentrantMutexGuard<'a, RefCell<Maybe<StderrRaw>>>,
482 }
483
484 /// Constructs a new handle to the standard error of the current process.
485 ///
486 /// This handle is not buffered.
487 ///
488 /// # Examples
489 ///
490 /// Using implicit synchronization:
491 ///
492 /// ```
493 /// use std::io::{self, Write};
494 ///
495 /// # fn foo() -> io::Result<()> {
496 /// try!(io::stderr().write(b"hello world"));
497 ///
498 /// # Ok(())
499 /// # }
500 /// ```
501 ///
502 /// Using explicit synchronization:
503 ///
504 /// ```
505 /// use std::io::{self, Write};
506 ///
507 /// # fn foo() -> io::Result<()> {
508 /// let stderr = io::stderr();
509 /// let mut handle = stderr.lock();
510 ///
511 /// try!(handle.write(b"hello world"));
512 ///
513 /// # Ok(())
514 /// # }
515 /// ```
516 #[stable(feature = "rust1", since = "1.0.0")]
517 pub fn stderr() -> Stderr {
518     static INSTANCE: Lazy<ReentrantMutex<RefCell<Maybe<StderrRaw>>>> = Lazy::new(stderr_init);
519     return Stderr {
520         inner: INSTANCE.get().expect("cannot access stderr during shutdown"),
521     };
522
523     fn stderr_init() -> Arc<ReentrantMutex<RefCell<Maybe<StderrRaw>>>> {
524         let stderr = match stderr_raw() {
525             Ok(stderr) => Maybe::Real(stderr),
526             _ => Maybe::Fake,
527         };
528         Arc::new(ReentrantMutex::new(RefCell::new(stderr)))
529     }
530 }
531
532 impl Stderr {
533     /// Locks this handle to the standard error stream, returning a writable
534     /// guard.
535     ///
536     /// The lock is released when the returned lock goes out of scope. The
537     /// returned guard also implements the `Write` trait for writing data.
538     ///
539     /// # Examples
540     ///
541     /// ```
542     /// use std::io::{self, Write};
543     ///
544     /// fn foo() -> io::Result<()> {
545     ///     let stderr = io::stderr();
546     ///     let mut handle = stderr.lock();
547     ///
548     ///     try!(handle.write(b"hello world"));
549     ///
550     ///     Ok(())
551     /// }
552     /// ```
553     #[stable(feature = "rust1", since = "1.0.0")]
554     pub fn lock(&self) -> StderrLock {
555         StderrLock { inner: self.inner.lock().unwrap_or_else(|e| e.into_inner()) }
556     }
557 }
558
559 #[stable(feature = "rust1", since = "1.0.0")]
560 impl Write for Stderr {
561     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
562         self.lock().write(buf)
563     }
564     fn flush(&mut self) -> io::Result<()> {
565         self.lock().flush()
566     }
567     fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
568         self.lock().write_all(buf)
569     }
570     fn write_fmt(&mut self, args: fmt::Arguments) -> io::Result<()> {
571         self.lock().write_fmt(args)
572     }
573 }
574 #[stable(feature = "rust1", since = "1.0.0")]
575 impl<'a> Write for StderrLock<'a> {
576     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
577         self.inner.borrow_mut().write(buf)
578     }
579     fn flush(&mut self) -> io::Result<()> {
580         self.inner.borrow_mut().flush()
581     }
582 }
583
584 /// Resets the thread-local stderr handle to the specified writer
585 ///
586 /// This will replace the current thread's stderr handle, returning the old
587 /// handle. All future calls to `panic!` and friends will emit their output to
588 /// this specified handle.
589 ///
590 /// Note that this does not need to be called for all new threads; the default
591 /// output handle is to the process's stderr stream.
592 #[unstable(feature = "set_stdio",
593            reason = "this function may disappear completely or be replaced \
594                      with a more general mechanism",
595            issue = "0")]
596 #[doc(hidden)]
597 pub fn set_panic(sink: Box<Write + Send>) -> Option<Box<Write + Send>> {
598     use panicking::LOCAL_STDERR;
599     use mem;
600     LOCAL_STDERR.with(move |slot| {
601         mem::replace(&mut *slot.borrow_mut(), Some(sink))
602     }).and_then(|mut s| {
603         let _ = s.flush();
604         Some(s)
605     })
606 }
607
608 /// Resets the thread-local stdout handle to the specified writer
609 ///
610 /// This will replace the current thread's stdout handle, returning the old
611 /// handle. All future calls to `print!` and friends will emit their output to
612 /// this specified handle.
613 ///
614 /// Note that this does not need to be called for all new threads; the default
615 /// output handle is to the process's stdout stream.
616 #[unstable(feature = "set_stdio",
617            reason = "this function may disappear completely or be replaced \
618                      with a more general mechanism",
619            issue = "0")]
620 #[doc(hidden)]
621 pub fn set_print(sink: Box<Write + Send>) -> Option<Box<Write + Send>> {
622     use mem;
623     LOCAL_STDOUT.with(move |slot| {
624         mem::replace(&mut *slot.borrow_mut(), Some(sink))
625     }).and_then(|mut s| {
626         let _ = s.flush();
627         Some(s)
628     })
629 }
630
631 #[unstable(feature = "print",
632            reason = "implementation detail which may disappear or be replaced at any time",
633            issue = "0")]
634 #[doc(hidden)]
635 pub fn _print(args: fmt::Arguments) {
636     // As an implementation of the `println!` macro, we want to try our best to
637     // not panic wherever possible and get the output somewhere. There are
638     // currently two possible vectors for panics we take care of here:
639     //
640     // 1. If the TLS key for the local stdout has been destroyed, accessing it
641     //    would cause a panic. Note that we just lump in the uninitialized case
642     //    here for convenience, we're not trying to avoid a panic.
643     // 2. If the local stdout is currently in use (e.g. we're in the middle of
644     //    already printing) then accessing again would cause a panic.
645     //
646     // If, however, the actual I/O causes an error, we do indeed panic.
647     let result = match LOCAL_STDOUT.state() {
648         LocalKeyState::Uninitialized |
649         LocalKeyState::Destroyed => stdout().write_fmt(args),
650         LocalKeyState::Valid => {
651             LOCAL_STDOUT.with(|s| {
652                 if s.borrow_state() == BorrowState::Unused {
653                     if let Some(w) = s.borrow_mut().as_mut() {
654                         return w.write_fmt(args);
655                     }
656                 }
657                 stdout().write_fmt(args)
658             })
659         }
660     };
661     if let Err(e) = result {
662         panic!("failed printing to stdout: {}", e);
663     }
664 }
665
666 #[cfg(test)]
667 mod tests {
668     use thread;
669     use super::*;
670
671     #[test]
672     fn panic_doesnt_poison() {
673         thread::spawn(|| {
674             let _a = stdin();
675             let _a = _a.lock();
676             let _a = stdout();
677             let _a = _a.lock();
678             let _a = stderr();
679             let _a = _a.lock();
680             panic!();
681         }).join().unwrap_err();
682
683         let _a = stdin();
684         let _a = _a.lock();
685         let _a = stdout();
686         let _a = _a.lock();
687         let _a = stderr();
688         let _a = _a.lock();
689     }
690 }