]> git.lizzy.rs Git - rust.git/blob - src/libstd/io/stdio.rs
Rollup merge of #23362 - dotdash:llvm_req, r=alexcrichton
[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 cmp;
15 use fmt;
16 use io::lazy::Lazy;
17 use io::{self, BufReader, LineWriter};
18 use sync::{Arc, Mutex, MutexGuard};
19 use sys::stdio;
20
21 /// A handle to a raw instance of the standard input stream of this process.
22 ///
23 /// This handle is not synchronized or buffered in any fashion. Constructed via
24 /// the `std::io::stdin_raw` function.
25 pub struct StdinRaw(stdio::Stdin);
26
27 /// A handle to a raw instance of the standard output stream of this process.
28 ///
29 /// This handle is not synchronized or buffered in any fashion. Constructed via
30 /// the `std::io::stdout_raw` function.
31 pub struct StdoutRaw(stdio::Stdout);
32
33 /// A handle to a raw instance of the standard output stream of this process.
34 ///
35 /// This handle is not synchronized or buffered in any fashion. Constructed via
36 /// the `std::io::stderr_raw` function.
37 pub struct StderrRaw(stdio::Stderr);
38
39 /// Construct a new raw handle to the standard input of this process.
40 ///
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.
44 ///
45 /// The returned handle has no external synchronization or buffering.
46 pub fn stdin_raw() -> StdinRaw { StdinRaw(stdio::Stdin::new()) }
47
48 /// Construct a new raw handle to the standard input stream of this process.
49 ///
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.
54 ///
55 /// The returned handle has no external synchronization or buffering layered on
56 /// top.
57 pub fn stdout_raw() -> StdoutRaw { StdoutRaw(stdio::Stdout::new()) }
58
59 /// Construct a new raw handle to the standard input stream of this process.
60 ///
61 /// The returned handle does not interact with any other handles created nor
62 /// handles returned by `std::io::stdout`.
63 ///
64 /// The returned handle has no external synchronization or buffering layered on
65 /// top.
66 pub fn stderr_raw() -> StderrRaw { StderrRaw(stdio::Stderr::new()) }
67
68 impl Read for StdinRaw {
69     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) }
70 }
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(()) }
74 }
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(()) }
78 }
79
80 /// A handle to the standard input stream of a process.
81 ///
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
85 /// to other writes.
86 ///
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")]
90 pub struct Stdin {
91     inner: Arc<Mutex<BufReader<StdinRaw>>>,
92 }
93
94 /// A locked reference to the a `Stdin` handle.
95 ///
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>>,
101 }
102
103 /// Create a new handle to the global standard input stream of this process.
104 ///
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()`
107 /// method.
108 ///
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 ///
113 /// To avoid locking and buffering altogether, it is recommended to use the
114 /// `stdin_raw` constructor.
115 #[stable(feature = "rust1", since = "1.0.0")]
116 pub fn stdin() -> Stdin {
117     static INSTANCE: Lazy<Mutex<BufReader<StdinRaw>>> = lazy_init!(stdin_init);
118     return Stdin {
119         inner: INSTANCE.get().expect("cannot access stdin during shutdown"),
120     };
121
122     fn stdin_init() -> Arc<Mutex<BufReader<StdinRaw>>> {
123         // The default buffer capacity is 64k, but apparently windows
124         // doesn't like 64k reads on stdin. See #13304 for details, but the
125         // idea is that on windows we use a slightly smaller buffer that's
126         // been seen to be acceptable.
127         Arc::new(Mutex::new(if cfg!(windows) {
128             BufReader::with_capacity(8 * 1024, stdin_raw())
129         } else {
130             BufReader::new(stdin_raw())
131         }))
132     }
133 }
134
135 impl Stdin {
136     /// Lock this handle to the standard input stream, returning a readable
137     /// guard.
138     ///
139     /// The lock is released when the returned lock goes out of scope. The
140     /// returned guard also implements the `Read` and `BufRead` traits for
141     /// accessing the underlying data.
142     #[stable(feature = "rust1", since = "1.0.0")]
143     pub fn lock(&self) -> StdinLock {
144         StdinLock { inner: self.inner.lock().unwrap() }
145     }
146
147     /// Locks this handle and reads a line of input into the specified buffer.
148     ///
149     /// For detailed semantics of this method, see the documentation on
150     /// `BufRead::read_line`.
151     #[stable(feature = "rust1", since = "1.0.0")]
152     pub fn read_line(&mut self, buf: &mut String) -> io::Result<usize> {
153         self.lock().read_line(buf)
154     }
155 }
156
157 #[stable(feature = "rust1", since = "1.0.0")]
158 impl Read for Stdin {
159     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
160         self.lock().read(buf)
161     }
162     fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
163         self.lock().read_to_end(buf)
164     }
165     fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
166         self.lock().read_to_string(buf)
167     }
168 }
169
170 #[stable(feature = "rust1", since = "1.0.0")]
171 impl<'a> Read for StdinLock<'a> {
172     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
173         self.inner.read(buf)
174     }
175 }
176 #[stable(feature = "rust1", since = "1.0.0")]
177 impl<'a> BufRead for StdinLock<'a> {
178     fn fill_buf(&mut self) -> io::Result<&[u8]> { self.inner.fill_buf() }
179     fn consume(&mut self, n: usize) { self.inner.consume(n) }
180 }
181
182 // As with stdin on windows, stdout often can't handle writes of large
183 // sizes. For an example, see #14940. For this reason, don't try to
184 // write the entire output buffer on windows. On unix we can just
185 // write the whole buffer all at once.
186 //
187 // For some other references, it appears that this problem has been
188 // encountered by others [1] [2]. We choose the number 8KB just because
189 // libuv does the same.
190 //
191 // [1]: https://tahoe-lafs.org/trac/tahoe-lafs/ticket/1232
192 // [2]: http://www.mail-archive.com/log4net-dev@logging.apache.org/msg00661.html
193 #[cfg(windows)]
194 const OUT_MAX: usize = 8192;
195 #[cfg(unix)]
196 const OUT_MAX: usize = ::usize::MAX;
197
198 /// A handle to the global standard output stream of the current process.
199 ///
200 /// Each handle shares a global buffer of data to be written to the standard
201 /// output stream. Access is also synchronized via a lock and explicit control
202 /// over locking is available via the `lock` method.
203 #[stable(feature = "rust1", since = "1.0.0")]
204 pub struct Stdout {
205     // FIXME: this should be LineWriter or BufWriter depending on the state of
206     //        stdout (tty or not). Note that if this is not line buffered it
207     //        should also flush-on-panic or some form of flush-on-abort.
208     inner: Arc<Mutex<LineWriter<StdoutRaw>>>,
209 }
210
211 /// A locked reference to the a `Stdout` handle.
212 ///
213 /// This handle implements the `Write` trait and is constructed via the `lock`
214 /// method on `Stdout`.
215 #[stable(feature = "rust1", since = "1.0.0")]
216 pub struct StdoutLock<'a> {
217     inner: MutexGuard<'a, LineWriter<StdoutRaw>>,
218 }
219
220 /// Constructs a new reference to the standard output of the current process.
221 ///
222 /// Each handle returned is a reference to a shared global buffer whose access
223 /// is synchronized via a mutex. Explicit control over synchronization is
224 /// provided via the `lock` method.
225 ///
226 /// The returned handle implements the `Write` trait.
227 ///
228 /// To avoid locking and buffering altogether, it is recommended to use the
229 /// `stdout_raw` constructor.
230 #[stable(feature = "rust1", since = "1.0.0")]
231 pub fn stdout() -> Stdout {
232     static INSTANCE: Lazy<Mutex<LineWriter<StdoutRaw>>> = lazy_init!(stdout_init);
233     return Stdout {
234         inner: INSTANCE.get().expect("cannot access stdout during shutdown"),
235     };
236
237     fn stdout_init() -> Arc<Mutex<LineWriter<StdoutRaw>>> {
238         Arc::new(Mutex::new(LineWriter::new(stdout_raw())))
239     }
240 }
241
242 impl Stdout {
243     /// Lock this handle to the standard output stream, returning a writable
244     /// guard.
245     ///
246     /// The lock is released when the returned lock goes out of scope. The
247     /// returned guard also implements the `Write` trait for writing data.
248     #[stable(feature = "rust1", since = "1.0.0")]
249     pub fn lock(&self) -> StdoutLock {
250         StdoutLock { inner: self.inner.lock().unwrap() }
251     }
252 }
253
254 #[stable(feature = "rust1", since = "1.0.0")]
255 impl Write for Stdout {
256     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
257         self.lock().write(buf)
258     }
259     fn flush(&mut self) -> io::Result<()> {
260         self.lock().flush()
261     }
262     fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
263         self.lock().write_all(buf)
264     }
265     fn write_fmt(&mut self, fmt: fmt::Arguments) -> io::Result<()> {
266         self.lock().write_fmt(fmt)
267     }
268 }
269 #[stable(feature = "rust1", since = "1.0.0")]
270 impl<'a> Write for StdoutLock<'a> {
271     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
272         self.inner.write(&buf[..cmp::min(buf.len(), OUT_MAX)])
273     }
274     fn flush(&mut self) -> io::Result<()> { self.inner.flush() }
275 }
276
277 /// A handle to the standard error stream of a process.
278 ///
279 /// For more information, see `stderr`
280 #[stable(feature = "rust1", since = "1.0.0")]
281 pub struct Stderr {
282     inner: Arc<Mutex<StderrRaw>>,
283 }
284
285 /// A locked reference to the a `Stderr` handle.
286 ///
287 /// This handle implements the `Write` trait and is constructed via the `lock`
288 /// method on `Stderr`.
289 #[stable(feature = "rust1", since = "1.0.0")]
290 pub struct StderrLock<'a> {
291     inner: MutexGuard<'a, StderrRaw>,
292 }
293
294 /// Constructs a new reference to the standard error stream of a process.
295 ///
296 /// Each returned handle is synchronized amongst all other handles created from
297 /// this function. No handles are buffered, however.
298 ///
299 /// The returned handle implements the `Write` trait.
300 ///
301 /// To avoid locking altogether, it is recommended to use the `stderr_raw`
302 /// constructor.
303 #[stable(feature = "rust1", since = "1.0.0")]
304 pub fn stderr() -> Stderr {
305     static INSTANCE: Lazy<Mutex<StderrRaw>> = lazy_init!(stderr_init);
306     return Stderr {
307         inner: INSTANCE.get().expect("cannot access stderr during shutdown"),
308     };
309
310     fn stderr_init() -> Arc<Mutex<StderrRaw>> {
311         Arc::new(Mutex::new(stderr_raw()))
312     }
313 }
314
315 impl Stderr {
316     /// Lock this handle to the standard error stream, returning a writable
317     /// guard.
318     ///
319     /// The lock is released when the returned lock goes out of scope. The
320     /// returned guard also implements the `Write` trait for writing data.
321     #[stable(feature = "rust1", since = "1.0.0")]
322     pub fn lock(&self) -> StderrLock {
323         StderrLock { inner: self.inner.lock().unwrap() }
324     }
325 }
326
327 #[stable(feature = "rust1", since = "1.0.0")]
328 impl Write for Stderr {
329     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
330         self.lock().write(buf)
331     }
332     fn flush(&mut self) -> io::Result<()> {
333         self.lock().flush()
334     }
335     fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
336         self.lock().write_all(buf)
337     }
338     fn write_fmt(&mut self, fmt: fmt::Arguments) -> io::Result<()> {
339         self.lock().write_fmt(fmt)
340     }
341 }
342 #[stable(feature = "rust1", since = "1.0.0")]
343 impl<'a> Write for StderrLock<'a> {
344     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
345         self.inner.write(&buf[..cmp::min(buf.len(), OUT_MAX)])
346     }
347     fn flush(&mut self) -> io::Result<()> { self.inner.flush() }
348 }
349
350 /// Resets the task-local stdout handle to the specified writer
351 ///
352 /// This will replace the current task's stdout handle, returning the old
353 /// handle. All future calls to `print` and friends will emit their output to
354 /// this specified handle.
355 ///
356 /// Note that this does not need to be called for all new tasks; the default
357 /// output handle is to the process's stdout stream.
358 #[unstable(feature = "set_panic",
359            reason = "this function may disappear completely or be replaced \
360                      with a more general mechanism")]
361 #[doc(hidden)]
362 pub fn set_panic(sink: Box<Write + Send>) -> Option<Box<Write + Send>> {
363     use panicking::LOCAL_STDERR;
364     use mem;
365     LOCAL_STDERR.with(move |slot| {
366         mem::replace(&mut *slot.borrow_mut(), Some(sink))
367     }).and_then(|mut s| {
368         let _ = s.flush();
369         Some(s)
370     })
371 }