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
::io
::{read_to_end_uninitialized}
;
22 use sys_common
::remutex
::{ReentrantMutex, ReentrantMutexGuard}
;
23 use thread
::LocalKeyState
;
25 /// Stdout used by print! and println! macros
27 static LOCAL_STDOUT
: RefCell
<Option
<Box
<Write
+ Send
>>> = {
32 /// A handle to a raw instance of the standard input stream of this process.
34 /// This handle is not synchronized or buffered in any fashion. Constructed via
35 /// the `std::io::stdio::stdin_raw` function.
36 struct StdinRaw(stdio
::Stdin
);
38 /// A handle to a raw instance of the standard output stream of this process.
40 /// This handle is not synchronized or buffered in any fashion. Constructed via
41 /// the `std::io::stdio::stdout_raw` function.
42 struct StdoutRaw(stdio
::Stdout
);
44 /// A handle to a raw instance of the standard output stream of this process.
46 /// This handle is not synchronized or buffered in any fashion. Constructed via
47 /// the `std::io::stdio::stderr_raw` function.
48 struct StderrRaw(stdio
::Stderr
);
50 /// Constructs a new raw handle to the standard input of this process.
52 /// The returned handle does not interact with any other handles created nor
53 /// handles returned by `std::io::stdin`. Data buffered by the `std::io::stdin`
54 /// handles is **not** available to raw handles returned from this function.
56 /// The returned handle has no external synchronization or buffering.
57 fn stdin_raw() -> io
::Result
<StdinRaw
> { stdio::Stdin::new().map(StdinRaw) }
59 /// Constructs a new raw handle to the standard output stream of this process.
61 /// The returned handle does not interact with any other handles created nor
62 /// handles returned by `std::io::stdout`. Note that data is buffered by the
63 /// `std::io::stdout` handles so writes which happen via this raw handle may
64 /// appear before previous writes.
66 /// The returned handle has no external synchronization or buffering layered on
68 fn stdout_raw() -> io
::Result
<StdoutRaw
> { stdio::Stdout::new().map(StdoutRaw) }
70 /// Constructs a new raw handle to the standard error stream of this process.
72 /// The returned handle does not interact with any other handles created nor
73 /// handles returned by `std::io::stderr`.
75 /// The returned handle has no external synchronization or buffering layered on
77 fn stderr_raw() -> io
::Result
<StderrRaw
> { stdio::Stderr::new().map(StderrRaw) }
79 impl Read
for StdinRaw
{
80 fn read(&mut self, buf
: &mut [u8]) -> io
::Result
<usize> { self.0.read(buf) }
82 impl Write
for StdoutRaw
{
83 fn write(&mut self, buf
: &[u8]) -> io
::Result
<usize> { self.0.write(buf) }
84 fn flush(&mut self) -> io
::Result
<()> { Ok(()) }
86 impl Write
for StderrRaw
{
87 fn write(&mut self, buf
: &[u8]) -> io
::Result
<usize> { self.0.write(buf) }
88 fn flush(&mut self) -> io
::Result
<()> { Ok(()) }
96 impl<W
: io
::Write
> io
::Write
for Maybe
<W
> {
97 fn write(&mut self, buf
: &[u8]) -> io
::Result
<usize> {
99 Maybe
::Real(ref mut w
) => handle_ebadf(w
.write(buf
), buf
.len()),
100 Maybe
::Fake
=> Ok(buf
.len())
104 fn flush(&mut self) -> io
::Result
<()> {
106 Maybe
::Real(ref mut w
) => handle_ebadf(w
.flush(), ()),
107 Maybe
::Fake
=> Ok(())
112 impl<R
: io
::Read
> io
::Read
for Maybe
<R
> {
113 fn read(&mut self, buf
: &mut [u8]) -> io
::Result
<usize> {
115 Maybe
::Real(ref mut r
) => handle_ebadf(r
.read(buf
), 0),
121 fn handle_ebadf
<T
>(r
: io
::Result
<T
>, default: T
) -> io
::Result
<T
> {
123 const ERR
: i32 = ::sys
::c
::ERROR_INVALID_HANDLE
as i32;
125 const ERR
: i32 = ::libc
::EBADF
as i32;
128 Err(ref e
) if e
.raw_os_error() == Some(ERR
) => Ok(default),
133 /// A handle to the standard input stream of a process.
135 /// Each handle is a shared reference to a global buffer of input data to this
136 /// process. A handle can be `lock`'d to gain full access to [`BufRead`] methods
137 /// (e.g. `.lines()`). Writes to this handle are otherwise locked with respect
140 /// This handle implements the `Read` trait, but beware that concurrent reads
141 /// of `Stdin` must be executed with care.
143 /// Created by the [`io::stdin`] method.
145 /// [`io::stdin`]: fn.stdin.html
146 /// [`BufRead`]: trait.BufRead.html
147 #[stable(feature = "rust1", since = "1.0.0")]
149 inner
: Arc
<Mutex
<BufReader
<Maybe
<StdinRaw
>>>>,
152 /// A locked reference to the `Stdin` handle.
154 /// This handle implements both the [`Read`] and [`BufRead`] traits, and
155 /// is constructed via the [`Stdin::lock`] method.
157 /// [`Read`]: trait.Read.html
158 /// [`BufRead`]: trait.BufRead.html
159 /// [`Stdin::lock`]: struct.Stdin.html#method.lock
160 #[stable(feature = "rust1", since = "1.0.0")]
161 pub struct StdinLock
<'a
> {
162 inner
: MutexGuard
<'a
, BufReader
<Maybe
<StdinRaw
>>>,
165 /// Constructs a new handle to the standard input of the current process.
167 /// Each handle returned is a reference to a shared global buffer whose access
168 /// is synchronized via a mutex. If you need more explicit control over
169 /// locking, see the [`lock() method`][lock].
171 /// [lock]: struct.Stdin.html#method.lock
175 /// Using implicit synchronization:
178 /// use std::io::{self, Read};
180 /// # fn foo() -> io::Result<String> {
181 /// let mut buffer = String::new();
182 /// try!(io::stdin().read_to_string(&mut buffer));
187 /// Using explicit synchronization:
190 /// use std::io::{self, Read};
192 /// # fn foo() -> io::Result<String> {
193 /// let mut buffer = String::new();
194 /// let stdin = io::stdin();
195 /// let mut handle = stdin.lock();
197 /// try!(handle.read_to_string(&mut buffer));
201 #[stable(feature = "rust1", since = "1.0.0")]
202 pub fn stdin() -> Stdin
{
203 static INSTANCE
: Lazy
<Mutex
<BufReader
<Maybe
<StdinRaw
>>>> = Lazy
::new(stdin_init
);
205 inner
: INSTANCE
.get().expect("cannot access stdin during shutdown"),
208 fn stdin_init() -> Arc
<Mutex
<BufReader
<Maybe
<StdinRaw
>>>> {
209 let stdin
= match stdin_raw() {
210 Ok(stdin
) => Maybe
::Real(stdin
),
214 // The default buffer capacity is 64k, but apparently windows
215 // doesn't like 64k reads on stdin. See #13304 for details, but the
216 // idea is that on windows we use a slightly smaller buffer that's
217 // been seen to be acceptable.
218 Arc
::new(Mutex
::new(if cfg
!(windows
) {
219 BufReader
::with_capacity(8 * 1024, stdin
)
221 BufReader
::new(stdin
)
227 /// Locks this handle to the standard input stream, returning a readable
230 /// The lock is released when the returned lock goes out of scope. The
231 /// returned guard also implements the [`Read`] and [`BufRead`] traits for
232 /// accessing the underlying data.
234 /// [`Read`]: trait.Read.html
235 /// [`BufRead`]: trait.BufRead.html
236 #[stable(feature = "rust1", since = "1.0.0")]
237 pub fn lock(&self) -> StdinLock
{
238 StdinLock { inner: self.inner.lock().unwrap_or_else(|e| e.into_inner()) }
241 /// Locks this handle and reads a line of input into the specified buffer.
243 /// For detailed semantics of this method, see the documentation on
244 /// [`BufRead::read_line`].
246 /// [`BufRead::read_line`]: trait.BufRead.html#method.read_line
253 /// let mut input = String::new();
254 /// match io::stdin().read_line(&mut input) {
256 /// println!("{} bytes read", n);
257 /// println!("{}", input);
259 /// Err(error) => println!("error: {}", error),
263 /// You can run the example one of two ways:
265 /// - Pipe some text to it, e.g. `printf foo | path/to/executable`
266 /// - Give it text interactively by running the executable directly,
267 /// in which case it will wait for the Enter key to be pressed before
269 #[stable(feature = "rust1", since = "1.0.0")]
270 pub fn read_line(&self, buf
: &mut String
) -> io
::Result
<usize> {
271 self.lock().read_line(buf
)
275 #[stable(feature = "rust1", since = "1.0.0")]
276 impl Read
for Stdin
{
277 fn read(&mut self, buf
: &mut [u8]) -> io
::Result
<usize> {
278 self.lock().read(buf
)
280 fn read_to_end(&mut self, buf
: &mut Vec
<u8>) -> io
::Result
<usize> {
281 self.lock().read_to_end(buf
)
283 fn read_to_string(&mut self, buf
: &mut String
) -> io
::Result
<usize> {
284 self.lock().read_to_string(buf
)
286 fn read_exact(&mut self, buf
: &mut [u8]) -> io
::Result
<()> {
287 self.lock().read_exact(buf
)
291 #[stable(feature = "rust1", since = "1.0.0")]
292 impl<'a
> Read
for StdinLock
<'a
> {
293 fn read(&mut self, buf
: &mut [u8]) -> io
::Result
<usize> {
296 fn read_to_end(&mut self, buf
: &mut Vec
<u8>) -> io
::Result
<usize> {
297 unsafe { read_to_end_uninitialized(self, buf) }
301 #[stable(feature = "rust1", since = "1.0.0")]
302 impl<'a
> BufRead
for StdinLock
<'a
> {
303 fn fill_buf(&mut self) -> io
::Result
<&[u8]> { self.inner.fill_buf() }
304 fn consume(&mut self, n
: usize) { self.inner.consume(n) }
307 // As with stdin on windows, stdout often can't handle writes of large
308 // sizes. For an example, see #14940. For this reason, don't try to
309 // write the entire output buffer on windows. On unix we can just
310 // write the whole buffer all at once.
312 // For some other references, it appears that this problem has been
313 // encountered by others [1] [2]. We choose the number 8KB just because
314 // libuv does the same.
316 // [1]: https://tahoe-lafs.org/trac/tahoe-lafs/ticket/1232
317 // [2]: http://www.mail-archive.com/log4net-dev@logging.apache.org/msg00661.html
319 const OUT_MAX
: usize = 8192;
321 const OUT_MAX
: usize = ::usize::MAX
;
323 /// A handle to the global standard output stream of the current process.
325 /// Each handle shares a global buffer of data to be written to the standard
326 /// output stream. Access is also synchronized via a lock and explicit control
327 /// over locking is available via the `lock` method.
329 /// Created by the [`io::stdout`] method.
331 /// [`io::stdout`]: fn.stdout.html
332 #[stable(feature = "rust1", since = "1.0.0")]
334 // FIXME: this should be LineWriter or BufWriter depending on the state of
335 // stdout (tty or not). Note that if this is not line buffered it
336 // should also flush-on-panic or some form of flush-on-abort.
337 inner
: Arc
<ReentrantMutex
<RefCell
<LineWriter
<Maybe
<StdoutRaw
>>>>>,
340 /// A locked reference to the `Stdout` handle.
342 /// This handle implements the [`Write`] trait, and is constructed via
343 /// the [`Stdout::lock`] method.
345 /// [`Write`]: trait.Write.html
346 /// [`Stdout::lock`]: struct.Stdout.html#method.lock
347 #[stable(feature = "rust1", since = "1.0.0")]
348 pub struct StdoutLock
<'a
> {
349 inner
: ReentrantMutexGuard
<'a
, RefCell
<LineWriter
<Maybe
<StdoutRaw
>>>>,
352 /// Constructs a new handle to the standard output of the current process.
354 /// Each handle returned is a reference to a shared global buffer whose access
355 /// is synchronized via a mutex. If you need more explicit control over
356 /// locking, see the [Stdout::lock] method.
358 /// [Stdout::lock]: struct.Stdout.html#method.lock
362 /// Using implicit synchronization:
365 /// use std::io::{self, Write};
367 /// # fn foo() -> io::Result<()> {
368 /// try!(io::stdout().write(b"hello world"));
374 /// Using explicit synchronization:
377 /// use std::io::{self, Write};
379 /// # fn foo() -> io::Result<()> {
380 /// let stdout = io::stdout();
381 /// let mut handle = stdout.lock();
383 /// try!(handle.write(b"hello world"));
388 #[stable(feature = "rust1", since = "1.0.0")]
389 pub fn stdout() -> Stdout
{
390 static INSTANCE
: Lazy
<ReentrantMutex
<RefCell
<LineWriter
<Maybe
<StdoutRaw
>>>>>
391 = Lazy
::new(stdout_init
);
393 inner
: INSTANCE
.get().expect("cannot access stdout during shutdown"),
396 fn stdout_init() -> Arc
<ReentrantMutex
<RefCell
<LineWriter
<Maybe
<StdoutRaw
>>>>> {
397 let stdout
= match stdout_raw() {
398 Ok(stdout
) => Maybe
::Real(stdout
),
401 Arc
::new(ReentrantMutex
::new(RefCell
::new(LineWriter
::new(stdout
))))
406 /// Locks this handle to the standard output stream, returning a writable
409 /// The lock is released when the returned lock goes out of scope. The
410 /// returned guard also implements the `Write` trait for writing data.
411 #[stable(feature = "rust1", since = "1.0.0")]
412 pub fn lock(&self) -> StdoutLock
{
413 StdoutLock { inner: self.inner.lock().unwrap_or_else(|e| e.into_inner()) }
417 #[stable(feature = "rust1", since = "1.0.0")]
418 impl Write
for Stdout
{
419 fn write(&mut self, buf
: &[u8]) -> io
::Result
<usize> {
420 self.lock().write(buf
)
422 fn flush(&mut self) -> io
::Result
<()> {
425 fn write_all(&mut self, buf
: &[u8]) -> io
::Result
<()> {
426 self.lock().write_all(buf
)
428 fn write_fmt(&mut self, args
: fmt
::Arguments
) -> io
::Result
<()> {
429 self.lock().write_fmt(args
)
432 #[stable(feature = "rust1", since = "1.0.0")]
433 impl<'a
> Write
for StdoutLock
<'a
> {
434 fn write(&mut self, buf
: &[u8]) -> io
::Result
<usize> {
435 self.inner
.borrow_mut().write(&buf
[..cmp
::min(buf
.len(), OUT_MAX
)])
437 fn flush(&mut self) -> io
::Result
<()> {
438 self.inner
.borrow_mut().flush()
442 /// A handle to the standard error stream of a process.
444 /// For more information, see the [`io::stderr`] method.
446 /// [`io::stderr`]: fn.stderr.html
447 #[stable(feature = "rust1", since = "1.0.0")]
449 inner
: Arc
<ReentrantMutex
<RefCell
<Maybe
<StderrRaw
>>>>,
452 /// A locked reference to the `Stderr` handle.
454 /// This handle implements the `Write` trait and is constructed via
455 /// the [`Stderr::lock`] method.
457 /// [`Stderr::lock`]: struct.Stderr.html#method.lock
458 #[stable(feature = "rust1", since = "1.0.0")]
459 pub struct StderrLock
<'a
> {
460 inner
: ReentrantMutexGuard
<'a
, RefCell
<Maybe
<StderrRaw
>>>,
463 /// Constructs a new handle to the standard error of the current process.
465 /// This handle is not buffered.
469 /// Using implicit synchronization:
472 /// use std::io::{self, Write};
474 /// # fn foo() -> io::Result<()> {
475 /// try!(io::stderr().write(b"hello world"));
481 /// Using explicit synchronization:
484 /// use std::io::{self, Write};
486 /// # fn foo() -> io::Result<()> {
487 /// let stderr = io::stderr();
488 /// let mut handle = stderr.lock();
490 /// try!(handle.write(b"hello world"));
495 #[stable(feature = "rust1", since = "1.0.0")]
496 pub fn stderr() -> Stderr
{
497 static INSTANCE
: Lazy
<ReentrantMutex
<RefCell
<Maybe
<StderrRaw
>>>> = Lazy
::new(stderr_init
);
499 inner
: INSTANCE
.get().expect("cannot access stderr during shutdown"),
502 fn stderr_init() -> Arc
<ReentrantMutex
<RefCell
<Maybe
<StderrRaw
>>>> {
503 let stderr
= match stderr_raw() {
504 Ok(stderr
) => Maybe
::Real(stderr
),
507 Arc
::new(ReentrantMutex
::new(RefCell
::new(stderr
)))
512 /// Locks this handle to the standard error stream, returning a writable
515 /// The lock is released when the returned lock goes out of scope. The
516 /// returned guard also implements the `Write` trait for writing data.
517 #[stable(feature = "rust1", since = "1.0.0")]
518 pub fn lock(&self) -> StderrLock
{
519 StderrLock { inner: self.inner.lock().unwrap_or_else(|e| e.into_inner()) }
523 #[stable(feature = "rust1", since = "1.0.0")]
524 impl Write
for Stderr
{
525 fn write(&mut self, buf
: &[u8]) -> io
::Result
<usize> {
526 self.lock().write(buf
)
528 fn flush(&mut self) -> io
::Result
<()> {
531 fn write_all(&mut self, buf
: &[u8]) -> io
::Result
<()> {
532 self.lock().write_all(buf
)
534 fn write_fmt(&mut self, args
: fmt
::Arguments
) -> io
::Result
<()> {
535 self.lock().write_fmt(args
)
538 #[stable(feature = "rust1", since = "1.0.0")]
539 impl<'a
> Write
for StderrLock
<'a
> {
540 fn write(&mut self, buf
: &[u8]) -> io
::Result
<usize> {
541 self.inner
.borrow_mut().write(&buf
[..cmp
::min(buf
.len(), OUT_MAX
)])
543 fn flush(&mut self) -> io
::Result
<()> {
544 self.inner
.borrow_mut().flush()
548 /// Resets the thread-local stderr handle to the specified writer
550 /// This will replace the current thread's stderr handle, returning the old
551 /// handle. All future calls to `panic!` and friends will emit their output to
552 /// this specified handle.
554 /// Note that this does not need to be called for all new threads; the default
555 /// output handle is to the process's stderr stream.
556 #[unstable(feature = "set_stdio",
557 reason
= "this function may disappear completely or be replaced \
558 with a more general mechanism",
561 pub fn set_panic(sink
: Box
<Write
+ Send
>) -> Option
<Box
<Write
+ Send
>> {
562 use panicking
::LOCAL_STDERR
;
564 LOCAL_STDERR
.with(move |slot
| {
565 mem
::replace(&mut *slot
.borrow_mut(), Some(sink
))
566 }).and_then(|mut s
| {
572 /// Resets the thread-local stdout handle to the specified writer
574 /// This will replace the current thread's stdout handle, returning the old
575 /// handle. All future calls to `print!` and friends will emit their output to
576 /// this specified handle.
578 /// Note that this does not need to be called for all new threads; the default
579 /// output handle is to the process's stdout stream.
580 #[unstable(feature = "set_stdio",
581 reason
= "this function may disappear completely or be replaced \
582 with a more general mechanism",
585 pub fn set_print(sink
: Box
<Write
+ Send
>) -> Option
<Box
<Write
+ Send
>> {
587 LOCAL_STDOUT
.with(move |slot
| {
588 mem
::replace(&mut *slot
.borrow_mut(), Some(sink
))
589 }).and_then(|mut s
| {
595 #[unstable(feature = "print",
596 reason
= "implementation detail which may disappear or be replaced at any time",
599 pub fn _print(args
: fmt
::Arguments
) {
600 // As an implementation of the `println!` macro, we want to try our best to
601 // not panic wherever possible and get the output somewhere. There are
602 // currently two possible vectors for panics we take care of here:
604 // 1. If the TLS key for the local stdout has been destroyed, accessing it
605 // would cause a panic. Note that we just lump in the uninitialized case
606 // here for convenience, we're not trying to avoid a panic.
607 // 2. If the local stdout is currently in use (e.g. we're in the middle of
608 // already printing) then accessing again would cause a panic.
610 // If, however, the actual I/O causes an error, we do indeed panic.
611 let result
= match LOCAL_STDOUT
.state() {
612 LocalKeyState
::Uninitialized
|
613 LocalKeyState
::Destroyed
=> stdout().write_fmt(args
),
614 LocalKeyState
::Valid
=> {
615 LOCAL_STDOUT
.with(|s
| {
616 if s
.borrow_state() == BorrowState
::Unused
{
617 if let Some(w
) = s
.borrow_mut().as_mut() {
618 return w
.write_fmt(args
);
621 stdout().write_fmt(args
)
625 if let Err(e
) = result
{
626 panic
!("failed printing to stdout: {}", e
);
636 fn panic_doesnt_poison() {
645 }).join().unwrap_err();