]> git.lizzy.rs Git - rust.git/blob - src/libstd/io/stdio.rs
Rollup merge of #23379 - kballard:tweak-stdio-docs-no-raw-constructors, 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::stdio::stdin_raw` function.
25 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::stdio::stdout_raw` function.
31 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::stdio::stderr_raw` function.
37 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 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 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 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 #[stable(feature = "rust1", since = "1.0.0")]
113 pub fn stdin() -> Stdin {
114     static INSTANCE: Lazy<Mutex<BufReader<StdinRaw>>> = lazy_init!(stdin_init);
115     return Stdin {
116         inner: INSTANCE.get().expect("cannot access stdin during shutdown"),
117     };
118
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())
126         } else {
127             BufReader::new(stdin_raw())
128         }))
129     }
130 }
131
132 impl Stdin {
133     /// Lock this handle to the standard input stream, returning a readable
134     /// guard.
135     ///
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() }
142     }
143
144     /// Locks this handle and reads a line of input into the specified buffer.
145     ///
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)
151     }
152 }
153
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)
158     }
159     fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
160         self.lock().read_to_end(buf)
161     }
162     fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
163         self.lock().read_to_string(buf)
164     }
165 }
166
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> {
170         self.inner.read(buf)
171     }
172 }
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) }
177 }
178
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.
183 //
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.
187 //
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
190 #[cfg(windows)]
191 const OUT_MAX: usize = 8192;
192 #[cfg(unix)]
193 const OUT_MAX: usize = ::usize::MAX;
194
195 /// A handle to the global standard output stream of the current process.
196 ///
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")]
201 pub struct Stdout {
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>>>,
206 }
207
208 /// A locked reference to the a `Stdout` handle.
209 ///
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>>,
215 }
216
217 /// Constructs a new reference to the standard output of the current process.
218 ///
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.
222 ///
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);
227     return Stdout {
228         inner: INSTANCE.get().expect("cannot access stdout during shutdown"),
229     };
230
231     fn stdout_init() -> Arc<Mutex<LineWriter<StdoutRaw>>> {
232         Arc::new(Mutex::new(LineWriter::new(stdout_raw())))
233     }
234 }
235
236 impl Stdout {
237     /// Lock this handle to the standard output stream, returning a writable
238     /// guard.
239     ///
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() }
245     }
246 }
247
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)
252     }
253     fn flush(&mut self) -> io::Result<()> {
254         self.lock().flush()
255     }
256     fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
257         self.lock().write_all(buf)
258     }
259     fn write_fmt(&mut self, fmt: fmt::Arguments) -> io::Result<()> {
260         self.lock().write_fmt(fmt)
261     }
262 }
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)])
267     }
268     fn flush(&mut self) -> io::Result<()> { self.inner.flush() }
269 }
270
271 /// A handle to the standard error stream of a process.
272 ///
273 /// For more information, see `stderr`
274 #[stable(feature = "rust1", since = "1.0.0")]
275 pub struct Stderr {
276     inner: Arc<Mutex<StderrRaw>>,
277 }
278
279 /// A locked reference to the a `Stderr` handle.
280 ///
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>,
286 }
287
288 /// Constructs a new reference to the standard error stream of a process.
289 ///
290 /// Each returned handle is synchronized amongst all other handles created from
291 /// this function. No handles are buffered, however.
292 ///
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);
297     return Stderr {
298         inner: INSTANCE.get().expect("cannot access stderr during shutdown"),
299     };
300
301     fn stderr_init() -> Arc<Mutex<StderrRaw>> {
302         Arc::new(Mutex::new(stderr_raw()))
303     }
304 }
305
306 impl Stderr {
307     /// Lock this handle to the standard error stream, returning a writable
308     /// guard.
309     ///
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() }
315     }
316 }
317
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)
322     }
323     fn flush(&mut self) -> io::Result<()> {
324         self.lock().flush()
325     }
326     fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
327         self.lock().write_all(buf)
328     }
329     fn write_fmt(&mut self, fmt: fmt::Arguments) -> io::Result<()> {
330         self.lock().write_fmt(fmt)
331     }
332 }
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)])
337     }
338     fn flush(&mut self) -> io::Result<()> { self.inner.flush() }
339 }
340
341 /// Resets the task-local stdout handle to the specified writer
342 ///
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.
346 ///
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")]
352 #[doc(hidden)]
353 pub fn set_panic(sink: Box<Write + Send>) -> Option<Box<Write + Send>> {
354     use panicking::LOCAL_STDERR;
355     use mem;
356     LOCAL_STDERR.with(move |slot| {
357         mem::replace(&mut *slot.borrow_mut(), Some(sink))
358     }).and_then(|mut s| {
359         let _ = s.flush();
360         Some(s)
361     })
362 }