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.
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.
14 use cell::{RefCell, BorrowState};
18 use io::{self, BufReader, LineWriter};
19 use sync::{Arc, Mutex, MutexGuard};
21 use sys_common::remutex::{ReentrantMutex, ReentrantMutexGuard};
22 use thread::LocalKeyState;
24 /// Stdout used by print! and println! macros
26 static LOCAL_STDOUT: RefCell<Option<Box<Write + Send>>> = {
31 /// A handle to a raw instance of the standard input stream of this process.
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);
37 /// A handle to a raw instance of the standard output stream of this process.
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);
43 /// A handle to a raw instance of the standard output stream of this process.
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);
49 /// Constructs a new raw handle to the standard input of this process.
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.
55 /// The returned handle has no external synchronization or buffering.
56 fn stdin_raw() -> io::Result<StdinRaw> { stdio::Stdin::new().map(StdinRaw) }
58 /// Constructs a new raw handle to the standard output stream of this process.
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.
65 /// The returned handle has no external synchronization or buffering layered on
67 fn stdout_raw() -> io::Result<StdoutRaw> { stdio::Stdout::new().map(StdoutRaw) }
69 /// Constructs a new raw handle to the standard error stream of this process.
71 /// The returned handle does not interact with any other handles created nor
72 /// handles returned by `std::io::stderr`.
74 /// The returned handle has no external synchronization or buffering layered on
76 fn stderr_raw() -> io::Result<StderrRaw> { stdio::Stderr::new().map(StderrRaw) }
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)
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(()) }
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(()) }
98 impl<W: io::Write> io::Write for Maybe<W> {
99 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
101 Maybe::Real(ref mut w) => handle_ebadf(w.write(buf), buf.len()),
102 Maybe::Fake => Ok(buf.len())
106 fn flush(&mut self) -> io::Result<()> {
108 Maybe::Real(ref mut w) => handle_ebadf(w.flush(), ()),
109 Maybe::Fake => Ok(())
114 impl<R: io::Read> io::Read for Maybe<R> {
115 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
117 Maybe::Real(ref mut r) => handle_ebadf(r.read(buf), 0),
121 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
123 Maybe::Real(ref mut r) => handle_ebadf(r.read_to_end(buf), 0),
129 fn handle_ebadf<T>(r: io::Result<T>, default: T) -> io::Result<T> {
131 const ERR: i32 = ::sys::c::ERROR_INVALID_HANDLE as i32;
133 const ERR: i32 = ::libc::EBADF as i32;
136 Err(ref e) if e.raw_os_error() == Some(ERR) => Ok(default),
141 /// A handle to the standard input stream of a process.
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
148 /// This handle implements the `Read` trait, but beware that concurrent reads
149 /// of `Stdin` must be executed with care.
151 /// Created by the [`io::stdin`] method.
153 /// [`io::stdin`]: fn.stdin.html
154 /// [`BufRead`]: trait.BufRead.html
155 #[stable(feature = "rust1", since = "1.0.0")]
157 inner: Arc<Mutex<BufReader<Maybe<StdinRaw>>>>,
160 /// A locked reference to the `Stdin` handle.
162 /// This handle implements both the [`Read`] and [`BufRead`] traits, and
163 /// is constructed via the [`Stdin::lock`] method.
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>>>,
173 /// Constructs a new handle to the standard input of the current process.
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].
179 /// [lock]: struct.Stdin.html#method.lock
183 /// Using implicit synchronization:
186 /// use std::io::{self, Read};
188 /// # fn foo() -> io::Result<String> {
189 /// let mut buffer = String::new();
190 /// try!(io::stdin().read_to_string(&mut buffer));
195 /// Using explicit synchronization:
198 /// use std::io::{self, Read};
200 /// # fn foo() -> io::Result<String> {
201 /// let mut buffer = String::new();
202 /// let stdin = io::stdin();
203 /// let mut handle = stdin.lock();
205 /// try!(handle.read_to_string(&mut buffer));
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);
213 inner: INSTANCE.get().expect("cannot access stdin during shutdown"),
216 fn stdin_init() -> Arc<Mutex<BufReader<Maybe<StdinRaw>>>> {
217 let stdin = match stdin_raw() {
218 Ok(stdin) => Maybe::Real(stdin),
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)
229 BufReader::new(stdin)
235 /// Locks this handle to the standard input stream, returning a readable
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.
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()) }
249 /// Locks this handle and reads a line of input into the specified buffer.
251 /// For detailed semantics of this method, see the documentation on
252 /// [`BufRead::read_line`].
254 /// [`BufRead::read_line`]: trait.BufRead.html#method.read_line
261 /// let mut input = String::new();
262 /// match io::stdin().read_line(&mut input) {
264 /// println!("{} bytes read", n);
265 /// println!("{}", input);
267 /// Err(error) => println!("error: {}", error),
271 /// You can run the example one of two ways:
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
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)
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)
288 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
289 self.lock().read_to_end(buf)
291 fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
292 self.lock().read_to_string(buf)
294 fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
295 self.lock().read_exact(buf)
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> {
304 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
305 self.inner.read_to_end(buf)
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) }
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.
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.
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
327 const OUT_MAX: usize = 8192;
329 const OUT_MAX: usize = ::usize::MAX;
331 /// A handle to the global standard output stream of the current process.
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.
337 /// Created by the [`io::stdout`] method.
339 /// [`io::stdout`]: fn.stdout.html
340 #[stable(feature = "rust1", since = "1.0.0")]
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>>>>>,
348 /// A locked reference to the `Stdout` handle.
350 /// This handle implements the [`Write`] trait, and is constructed via
351 /// the [`Stdout::lock`] method.
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>>>>,
360 /// Constructs a new handle to the standard output of the current process.
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.
366 /// [Stdout::lock]: struct.Stdout.html#method.lock
370 /// Using implicit synchronization:
373 /// use std::io::{self, Write};
375 /// # fn foo() -> io::Result<()> {
376 /// try!(io::stdout().write(b"hello world"));
382 /// Using explicit synchronization:
385 /// use std::io::{self, Write};
387 /// # fn foo() -> io::Result<()> {
388 /// let stdout = io::stdout();
389 /// let mut handle = stdout.lock();
391 /// try!(handle.write(b"hello world"));
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);
401 inner: INSTANCE.get().expect("cannot access stdout during shutdown"),
404 fn stdout_init() -> Arc<ReentrantMutex<RefCell<LineWriter<Maybe<StdoutRaw>>>>> {
405 let stdout = match stdout_raw() {
406 Ok(stdout) => Maybe::Real(stdout),
409 Arc::new(ReentrantMutex::new(RefCell::new(LineWriter::new(stdout))))
414 /// Locks this handle to the standard output stream, returning a writable
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()) }
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)
430 fn flush(&mut self) -> io::Result<()> {
433 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
434 self.lock().write_all(buf)
436 fn write_fmt(&mut self, args: fmt::Arguments) -> io::Result<()> {
437 self.lock().write_fmt(args)
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)])
445 fn flush(&mut self) -> io::Result<()> {
446 self.inner.borrow_mut().flush()
450 /// A handle to the standard error stream of a process.
452 /// For more information, see the [`io::stderr`] method.
454 /// [`io::stderr`]: fn.stderr.html
455 #[stable(feature = "rust1", since = "1.0.0")]
457 inner: Arc<ReentrantMutex<RefCell<Maybe<StderrRaw>>>>,
460 /// A locked reference to the `Stderr` handle.
462 /// This handle implements the `Write` trait and is constructed via
463 /// the [`Stderr::lock`] method.
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>>>,
471 /// Constructs a new handle to the standard error of the current process.
473 /// This handle is not buffered.
477 /// Using implicit synchronization:
480 /// use std::io::{self, Write};
482 /// # fn foo() -> io::Result<()> {
483 /// try!(io::stderr().write(b"hello world"));
489 /// Using explicit synchronization:
492 /// use std::io::{self, Write};
494 /// # fn foo() -> io::Result<()> {
495 /// let stderr = io::stderr();
496 /// let mut handle = stderr.lock();
498 /// try!(handle.write(b"hello world"));
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);
507 inner: INSTANCE.get().expect("cannot access stderr during shutdown"),
510 fn stderr_init() -> Arc<ReentrantMutex<RefCell<Maybe<StderrRaw>>>> {
511 let stderr = match stderr_raw() {
512 Ok(stderr) => Maybe::Real(stderr),
515 Arc::new(ReentrantMutex::new(RefCell::new(stderr)))
520 /// Locks this handle to the standard error stream, returning a writable
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()) }
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)
536 fn flush(&mut self) -> io::Result<()> {
539 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
540 self.lock().write_all(buf)
542 fn write_fmt(&mut self, args: fmt::Arguments) -> io::Result<()> {
543 self.lock().write_fmt(args)
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)])
551 fn flush(&mut self) -> io::Result<()> {
552 self.inner.borrow_mut().flush()
556 /// Resets the thread-local stderr handle to the specified writer
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.
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",
569 pub fn set_panic(sink: Box<Write + Send>) -> Option<Box<Write + Send>> {
570 use panicking::LOCAL_STDERR;
572 LOCAL_STDERR.with(move |slot| {
573 mem::replace(&mut *slot.borrow_mut(), Some(sink))
574 }).and_then(|mut s| {
580 /// Resets the thread-local stdout handle to the specified writer
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.
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",
593 pub fn set_print(sink: Box<Write + Send>) -> Option<Box<Write + Send>> {
595 LOCAL_STDOUT.with(move |slot| {
596 mem::replace(&mut *slot.borrow_mut(), Some(sink))
597 }).and_then(|mut s| {
603 #[unstable(feature = "print",
604 reason = "implementation detail which may disappear or be replaced at any time",
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:
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.
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);
629 stdout().write_fmt(args)
633 if let Err(e) = result {
634 panic!("failed printing to stdout: {}", e);
644 fn panic_doesnt_poison() {
653 }).join().unwrap_err();