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.
17 use io::{self, BufReader, LineWriter};
18 use sync::{Arc, Mutex, MutexGuard};
21 /// A handle to a raw instance of the standard input stream of this process.
23 /// This handle is not synchronized or buffered in any fashion. Constructed via
24 /// the `std::io::stdio::stdin_raw` function.
25 struct StdinRaw(stdio::Stdin);
27 /// A handle to a raw instance of the standard output stream of this process.
29 /// This handle is not synchronized or buffered in any fashion. Constructed via
30 /// the `std::io::stdio::stdout_raw` function.
31 struct StdoutRaw(stdio::Stdout);
33 /// A handle to a raw instance of the standard output stream of this process.
35 /// This handle is not synchronized or buffered in any fashion. Constructed via
36 /// the `std::io::stdio::stderr_raw` function.
37 struct StderrRaw(stdio::Stderr);
39 /// Construct a new raw handle to the standard input of this process.
41 /// The returned handle does not interact with any other handles created nor
42 /// handles returned by `std::io::stdin`. Data buffered by the `std::io::stdin`
43 /// handles is **not** available to raw handles returned from this function.
45 /// The returned handle has no external synchronization or buffering.
46 fn stdin_raw() -> StdinRaw { StdinRaw(stdio::Stdin::new()) }
48 /// Construct a new raw handle to the standard input stream of this process.
50 /// The returned handle does not interact with any other handles created nor
51 /// handles returned by `std::io::stdout`. Note that data is buffered by the
52 /// `std::io::stdin` handles so writes which happen via this raw handle may
53 /// appear before previous writes.
55 /// The returned handle has no external synchronization or buffering layered on
57 fn stdout_raw() -> StdoutRaw { StdoutRaw(stdio::Stdout::new()) }
59 /// Construct a new raw handle to the standard input stream of this process.
61 /// The returned handle does not interact with any other handles created nor
62 /// handles returned by `std::io::stdout`.
64 /// The returned handle has no external synchronization or buffering layered on
66 fn stderr_raw() -> StderrRaw { StderrRaw(stdio::Stderr::new()) }
68 impl Read for StdinRaw {
69 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) }
71 impl Write for StdoutRaw {
72 fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) }
73 fn flush(&mut self) -> io::Result<()> { Ok(()) }
75 impl Write for StderrRaw {
76 fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) }
77 fn flush(&mut self) -> io::Result<()> { Ok(()) }
80 /// A handle to the standard input stream of a process.
82 /// Each handle is a shared reference to a global buffer of input data to this
83 /// process. A handle can be `lock`'d to gain full access to `BufRead` methods
84 /// (e.g. `.lines()`). Writes to this handle are otherwise locked with respect
87 /// This handle implements the `Read` trait, but beware that concurrent reads
88 /// of `Stdin` must be executed with care.
89 #[stable(feature = "rust1", since = "1.0.0")]
91 inner: Arc<Mutex<BufReader<StdinRaw>>>,
94 /// A locked reference to the a `Stdin` handle.
96 /// This handle implements both the `Read` and `BufRead` traits and is
97 /// constructed via the `lock` method on `Stdin`.
98 #[stable(feature = "rust1", since = "1.0.0")]
99 pub struct StdinLock<'a> {
100 inner: MutexGuard<'a, BufReader<StdinRaw>>,
103 /// Create a new handle to the global standard input stream of this process.
105 /// The handle returned refers to a globally shared buffer between all threads.
106 /// Access is synchronized and can be explicitly controlled with the `lock()`
109 /// The `Read` trait is implemented for the returned value but the `BufRead`
110 /// trait is not due to the global nature of the standard input stream. The
111 /// locked version, `StdinLock`, implements both `Read` and `BufRead`, however.
112 #[stable(feature = "rust1", since = "1.0.0")]
113 pub fn stdin() -> Stdin {
114 static INSTANCE: Lazy<Mutex<BufReader<StdinRaw>>> = lazy_init!(stdin_init);
116 inner: INSTANCE.get().expect("cannot access stdin during shutdown"),
119 fn stdin_init() -> Arc<Mutex<BufReader<StdinRaw>>> {
120 // The default buffer capacity is 64k, but apparently windows
121 // doesn't like 64k reads on stdin. See #13304 for details, but the
122 // idea is that on windows we use a slightly smaller buffer that's
123 // been seen to be acceptable.
124 Arc::new(Mutex::new(if cfg!(windows) {
125 BufReader::with_capacity(8 * 1024, stdin_raw())
127 BufReader::new(stdin_raw())
133 /// Lock this handle to the standard input stream, returning a readable
136 /// The lock is released when the returned lock goes out of scope. The
137 /// returned guard also implements the `Read` and `BufRead` traits for
138 /// accessing the underlying data.
139 #[stable(feature = "rust1", since = "1.0.0")]
140 pub fn lock(&self) -> StdinLock {
141 StdinLock { inner: self.inner.lock().unwrap() }
144 /// Locks this handle and reads a line of input into the specified buffer.
146 /// For detailed semantics of this method, see the documentation on
147 /// `BufRead::read_line`.
148 #[stable(feature = "rust1", since = "1.0.0")]
149 pub fn read_line(&mut self, buf: &mut String) -> io::Result<usize> {
150 self.lock().read_line(buf)
154 #[stable(feature = "rust1", since = "1.0.0")]
155 impl Read for Stdin {
156 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
157 self.lock().read(buf)
159 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
160 self.lock().read_to_end(buf)
162 fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
163 self.lock().read_to_string(buf)
167 #[stable(feature = "rust1", since = "1.0.0")]
168 impl<'a> Read for StdinLock<'a> {
169 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
173 #[stable(feature = "rust1", since = "1.0.0")]
174 impl<'a> BufRead for StdinLock<'a> {
175 fn fill_buf(&mut self) -> io::Result<&[u8]> { self.inner.fill_buf() }
176 fn consume(&mut self, n: usize) { self.inner.consume(n) }
179 // As with stdin on windows, stdout often can't handle writes of large
180 // sizes. For an example, see #14940. For this reason, don't try to
181 // write the entire output buffer on windows. On unix we can just
182 // write the whole buffer all at once.
184 // For some other references, it appears that this problem has been
185 // encountered by others [1] [2]. We choose the number 8KB just because
186 // libuv does the same.
188 // [1]: https://tahoe-lafs.org/trac/tahoe-lafs/ticket/1232
189 // [2]: http://www.mail-archive.com/log4net-dev@logging.apache.org/msg00661.html
191 const OUT_MAX: usize = 8192;
193 const OUT_MAX: usize = ::usize::MAX;
195 /// A handle to the global standard output stream of the current process.
197 /// Each handle shares a global buffer of data to be written to the standard
198 /// output stream. Access is also synchronized via a lock and explicit control
199 /// over locking is available via the `lock` method.
200 #[stable(feature = "rust1", since = "1.0.0")]
202 // FIXME: this should be LineWriter or BufWriter depending on the state of
203 // stdout (tty or not). Note that if this is not line buffered it
204 // should also flush-on-panic or some form of flush-on-abort.
205 inner: Arc<Mutex<LineWriter<StdoutRaw>>>,
208 /// A locked reference to the a `Stdout` handle.
210 /// This handle implements the `Write` trait and is constructed via the `lock`
211 /// method on `Stdout`.
212 #[stable(feature = "rust1", since = "1.0.0")]
213 pub struct StdoutLock<'a> {
214 inner: MutexGuard<'a, LineWriter<StdoutRaw>>,
217 /// Constructs a new reference to the standard output of the current process.
219 /// Each handle returned is a reference to a shared global buffer whose access
220 /// is synchronized via a mutex. Explicit control over synchronization is
221 /// provided via the `lock` method.
223 /// The returned handle implements the `Write` trait.
224 #[stable(feature = "rust1", since = "1.0.0")]
225 pub fn stdout() -> Stdout {
226 static INSTANCE: Lazy<Mutex<LineWriter<StdoutRaw>>> = lazy_init!(stdout_init);
228 inner: INSTANCE.get().expect("cannot access stdout during shutdown"),
231 fn stdout_init() -> Arc<Mutex<LineWriter<StdoutRaw>>> {
232 Arc::new(Mutex::new(LineWriter::new(stdout_raw())))
237 /// Lock this handle to the standard output stream, returning a writable
240 /// The lock is released when the returned lock goes out of scope. The
241 /// returned guard also implements the `Write` trait for writing data.
242 #[stable(feature = "rust1", since = "1.0.0")]
243 pub fn lock(&self) -> StdoutLock {
244 StdoutLock { inner: self.inner.lock().unwrap() }
248 #[stable(feature = "rust1", since = "1.0.0")]
249 impl Write for Stdout {
250 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
251 self.lock().write(buf)
253 fn flush(&mut self) -> io::Result<()> {
256 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
257 self.lock().write_all(buf)
259 fn write_fmt(&mut self, fmt: fmt::Arguments) -> io::Result<()> {
260 self.lock().write_fmt(fmt)
263 #[stable(feature = "rust1", since = "1.0.0")]
264 impl<'a> Write for StdoutLock<'a> {
265 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
266 self.inner.write(&buf[..cmp::min(buf.len(), OUT_MAX)])
268 fn flush(&mut self) -> io::Result<()> { self.inner.flush() }
271 /// A handle to the standard error stream of a process.
273 /// For more information, see `stderr`
274 #[stable(feature = "rust1", since = "1.0.0")]
276 inner: Arc<Mutex<StderrRaw>>,
279 /// A locked reference to the a `Stderr` handle.
281 /// This handle implements the `Write` trait and is constructed via the `lock`
282 /// method on `Stderr`.
283 #[stable(feature = "rust1", since = "1.0.0")]
284 pub struct StderrLock<'a> {
285 inner: MutexGuard<'a, StderrRaw>,
288 /// Constructs a new reference to the standard error stream of a process.
290 /// Each returned handle is synchronized amongst all other handles created from
291 /// this function. No handles are buffered, however.
293 /// The returned handle implements the `Write` trait.
294 #[stable(feature = "rust1", since = "1.0.0")]
295 pub fn stderr() -> Stderr {
296 static INSTANCE: Lazy<Mutex<StderrRaw>> = lazy_init!(stderr_init);
298 inner: INSTANCE.get().expect("cannot access stderr during shutdown"),
301 fn stderr_init() -> Arc<Mutex<StderrRaw>> {
302 Arc::new(Mutex::new(stderr_raw()))
307 /// Lock this handle to the standard error stream, returning a writable
310 /// The lock is released when the returned lock goes out of scope. The
311 /// returned guard also implements the `Write` trait for writing data.
312 #[stable(feature = "rust1", since = "1.0.0")]
313 pub fn lock(&self) -> StderrLock {
314 StderrLock { inner: self.inner.lock().unwrap() }
318 #[stable(feature = "rust1", since = "1.0.0")]
319 impl Write for Stderr {
320 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
321 self.lock().write(buf)
323 fn flush(&mut self) -> io::Result<()> {
326 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
327 self.lock().write_all(buf)
329 fn write_fmt(&mut self, fmt: fmt::Arguments) -> io::Result<()> {
330 self.lock().write_fmt(fmt)
333 #[stable(feature = "rust1", since = "1.0.0")]
334 impl<'a> Write for StderrLock<'a> {
335 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
336 self.inner.write(&buf[..cmp::min(buf.len(), OUT_MAX)])
338 fn flush(&mut self) -> io::Result<()> { self.inner.flush() }
341 /// Resets the task-local stdout handle to the specified writer
343 /// This will replace the current task's stdout handle, returning the old
344 /// handle. All future calls to `print` and friends will emit their output to
345 /// this specified handle.
347 /// Note that this does not need to be called for all new tasks; the default
348 /// output handle is to the process's stdout stream.
349 #[unstable(feature = "set_panic",
350 reason = "this function may disappear completely or be replaced \
351 with a more general mechanism")]
353 pub fn set_panic(sink: Box<Write + Send>) -> Option<Box<Write + Send>> {
354 use panicking::LOCAL_STDERR;
356 LOCAL_STDERR.with(move |slot| {
357 mem::replace(&mut *slot.borrow_mut(), Some(sink))
358 }).and_then(|mut s| {