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