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