]> git.lizzy.rs Git - rust.git/blob - library/std/src/io/mod.rs
e6b9314fd886d669388927a1d97c70344a953fa3
[rust.git] / library / std / src / io / mod.rs
1 //! Traits, helpers, and type definitions for core I/O functionality.
2 //!
3 //! The `std::io` module contains a number of common things you'll need
4 //! when doing input and output. The most core part of this module is
5 //! the [`Read`] and [`Write`] traits, which provide the
6 //! most general interface for reading and writing input and output.
7 //!
8 //! # Read and Write
9 //!
10 //! Because they are traits, [`Read`] and [`Write`] are implemented by a number
11 //! of other types, and you can implement them for your types too. As such,
12 //! you'll see a few different types of I/O throughout the documentation in
13 //! this module: [`File`]s, [`TcpStream`]s, and sometimes even [`Vec<T>`]s. For
14 //! example, [`Read`] adds a [`read`][`Read::read`] method, which we can use on
15 //! [`File`]s:
16 //!
17 //! ```no_run
18 //! use std::io;
19 //! use std::io::prelude::*;
20 //! use std::fs::File;
21 //!
22 //! fn main() -> io::Result<()> {
23 //!     let mut f = File::open("foo.txt")?;
24 //!     let mut buffer = [0; 10];
25 //!
26 //!     // read up to 10 bytes
27 //!     let n = f.read(&mut buffer)?;
28 //!
29 //!     println!("The bytes: {:?}", &buffer[..n]);
30 //!     Ok(())
31 //! }
32 //! ```
33 //!
34 //! [`Read`] and [`Write`] are so important, implementors of the two traits have a
35 //! nickname: readers and writers. So you'll sometimes see 'a reader' instead
36 //! of 'a type that implements the [`Read`] trait'. Much easier!
37 //!
38 //! ## Seek and BufRead
39 //!
40 //! Beyond that, there are two important traits that are provided: [`Seek`]
41 //! and [`BufRead`]. Both of these build on top of a reader to control
42 //! how the reading happens. [`Seek`] lets you control where the next byte is
43 //! coming from:
44 //!
45 //! ```no_run
46 //! use std::io;
47 //! use std::io::prelude::*;
48 //! use std::io::SeekFrom;
49 //! use std::fs::File;
50 //!
51 //! fn main() -> io::Result<()> {
52 //!     let mut f = File::open("foo.txt")?;
53 //!     let mut buffer = [0; 10];
54 //!
55 //!     // skip to the last 10 bytes of the file
56 //!     f.seek(SeekFrom::End(-10))?;
57 //!
58 //!     // read up to 10 bytes
59 //!     let n = f.read(&mut buffer)?;
60 //!
61 //!     println!("The bytes: {:?}", &buffer[..n]);
62 //!     Ok(())
63 //! }
64 //! ```
65 //!
66 //! [`BufRead`] uses an internal buffer to provide a number of other ways to read, but
67 //! to show it off, we'll need to talk about buffers in general. Keep reading!
68 //!
69 //! ## BufReader and BufWriter
70 //!
71 //! Byte-based interfaces are unwieldy and can be inefficient, as we'd need to be
72 //! making near-constant calls to the operating system. To help with this,
73 //! `std::io` comes with two structs, [`BufReader`] and [`BufWriter`], which wrap
74 //! readers and writers. The wrapper uses a buffer, reducing the number of
75 //! calls and providing nicer methods for accessing exactly what you want.
76 //!
77 //! For example, [`BufReader`] works with the [`BufRead`] trait to add extra
78 //! methods to any reader:
79 //!
80 //! ```no_run
81 //! use std::io;
82 //! use std::io::prelude::*;
83 //! use std::io::BufReader;
84 //! use std::fs::File;
85 //!
86 //! fn main() -> io::Result<()> {
87 //!     let f = File::open("foo.txt")?;
88 //!     let mut reader = BufReader::new(f);
89 //!     let mut buffer = String::new();
90 //!
91 //!     // read a line into buffer
92 //!     reader.read_line(&mut buffer)?;
93 //!
94 //!     println!("{}", buffer);
95 //!     Ok(())
96 //! }
97 //! ```
98 //!
99 //! [`BufWriter`] doesn't add any new ways of writing; it just buffers every call
100 //! to [`write`][`Write::write`]:
101 //!
102 //! ```no_run
103 //! use std::io;
104 //! use std::io::prelude::*;
105 //! use std::io::BufWriter;
106 //! use std::fs::File;
107 //!
108 //! fn main() -> io::Result<()> {
109 //!     let f = File::create("foo.txt")?;
110 //!     {
111 //!         let mut writer = BufWriter::new(f);
112 //!
113 //!         // write a byte to the buffer
114 //!         writer.write(&[42])?;
115 //!
116 //!     } // the buffer is flushed once writer goes out of scope
117 //!
118 //!     Ok(())
119 //! }
120 //! ```
121 //!
122 //! ## Standard input and output
123 //!
124 //! A very common source of input is standard input:
125 //!
126 //! ```no_run
127 //! use std::io;
128 //!
129 //! fn main() -> io::Result<()> {
130 //!     let mut input = String::new();
131 //!
132 //!     io::stdin().read_line(&mut input)?;
133 //!
134 //!     println!("You typed: {}", input.trim());
135 //!     Ok(())
136 //! }
137 //! ```
138 //!
139 //! Note that you cannot use the [`?` operator] in functions that do not return
140 //! a [`Result<T, E>`][`Result`]. Instead, you can call [`.unwrap()`]
141 //! or `match` on the return value to catch any possible errors:
142 //!
143 //! ```no_run
144 //! use std::io;
145 //!
146 //! let mut input = String::new();
147 //!
148 //! io::stdin().read_line(&mut input).unwrap();
149 //! ```
150 //!
151 //! And a very common source of output is standard output:
152 //!
153 //! ```no_run
154 //! use std::io;
155 //! use std::io::prelude::*;
156 //!
157 //! fn main() -> io::Result<()> {
158 //!     io::stdout().write(&[42])?;
159 //!     Ok(())
160 //! }
161 //! ```
162 //!
163 //! Of course, using [`io::stdout`] directly is less common than something like
164 //! [`println!`].
165 //!
166 //! ## Iterator types
167 //!
168 //! A large number of the structures provided by `std::io` are for various
169 //! ways of iterating over I/O. For example, [`Lines`] is used to split over
170 //! lines:
171 //!
172 //! ```no_run
173 //! use std::io;
174 //! use std::io::prelude::*;
175 //! use std::io::BufReader;
176 //! use std::fs::File;
177 //!
178 //! fn main() -> io::Result<()> {
179 //!     let f = File::open("foo.txt")?;
180 //!     let reader = BufReader::new(f);
181 //!
182 //!     for line in reader.lines() {
183 //!         println!("{}", line?);
184 //!     }
185 //!     Ok(())
186 //! }
187 //! ```
188 //!
189 //! ## Functions
190 //!
191 //! There are a number of [functions][functions-list] that offer access to various
192 //! features. For example, we can use three of these functions to copy everything
193 //! from standard input to standard output:
194 //!
195 //! ```no_run
196 //! use std::io;
197 //!
198 //! fn main() -> io::Result<()> {
199 //!     io::copy(&mut io::stdin(), &mut io::stdout())?;
200 //!     Ok(())
201 //! }
202 //! ```
203 //!
204 //! [functions-list]: #functions-1
205 //!
206 //! ## io::Result
207 //!
208 //! Last, but certainly not least, is [`io::Result`]. This type is used
209 //! as the return type of many `std::io` functions that can cause an error, and
210 //! can be returned from your own functions as well. Many of the examples in this
211 //! module use the [`?` operator]:
212 //!
213 //! ```
214 //! use std::io;
215 //!
216 //! fn read_input() -> io::Result<()> {
217 //!     let mut input = String::new();
218 //!
219 //!     io::stdin().read_line(&mut input)?;
220 //!
221 //!     println!("You typed: {}", input.trim());
222 //!
223 //!     Ok(())
224 //! }
225 //! ```
226 //!
227 //! The return type of `read_input()`, [`io::Result<()>`][`io::Result`], is a very
228 //! common type for functions which don't have a 'real' return value, but do want to
229 //! return errors if they happen. In this case, the only purpose of this function is
230 //! to read the line and print it, so we use `()`.
231 //!
232 //! ## Platform-specific behavior
233 //!
234 //! Many I/O functions throughout the standard library are documented to indicate
235 //! what various library or syscalls they are delegated to. This is done to help
236 //! applications both understand what's happening under the hood as well as investigate
237 //! any possibly unclear semantics. Note, however, that this is informative, not a binding
238 //! contract. The implementation of many of these functions are subject to change over
239 //! time and may call fewer or more syscalls/library functions.
240 //!
241 //! [`File`]: crate::fs::File
242 //! [`TcpStream`]: crate::net::TcpStream
243 //! [`Vec<T>`]: Vec
244 //! [`io::stdout`]: stdout
245 //! [`io::Result`]: self::Result
246 //! [`?` operator]: ../../book/appendix-02-operators.html
247 //! [`Result`]: crate::result::Result
248 //! [`.unwrap()`]: crate::result::Result::unwrap
249
250 #![stable(feature = "rust1", since = "1.0.0")]
251
252 #[cfg(test)]
253 mod tests;
254
255 use crate::cmp;
256 use crate::fmt;
257 use crate::memchr;
258 use crate::ops::{Deref, DerefMut};
259 use crate::ptr;
260 use crate::slice;
261 use crate::str;
262 use crate::sys;
263
264 #[stable(feature = "rust1", since = "1.0.0")]
265 pub use self::buffered::IntoInnerError;
266 #[stable(feature = "rust1", since = "1.0.0")]
267 pub use self::buffered::{BufReader, BufWriter, LineWriter};
268 #[stable(feature = "rust1", since = "1.0.0")]
269 pub use self::cursor::Cursor;
270 #[stable(feature = "rust1", since = "1.0.0")]
271 pub use self::error::{Error, ErrorKind, Result};
272 #[stable(feature = "rust1", since = "1.0.0")]
273 pub use self::stdio::{stderr, stdin, stdout, Stderr, Stdin, Stdout};
274 #[stable(feature = "rust1", since = "1.0.0")]
275 pub use self::stdio::{StderrLock, StdinLock, StdoutLock};
276 #[unstable(feature = "print_internals", issue = "none")]
277 pub use self::stdio::{_eprint, _print};
278 #[unstable(feature = "libstd_io_internals", issue = "42788")]
279 #[doc(no_inline, hidden)]
280 pub use self::stdio::{set_panic, set_print};
281 #[stable(feature = "rust1", since = "1.0.0")]
282 pub use self::util::{copy, empty, repeat, sink, Empty, Repeat, Sink};
283
284 pub(crate) use self::stdio::clone_io;
285
286 mod buffered;
287 mod cursor;
288 mod error;
289 mod impls;
290 pub mod prelude;
291 mod stdio;
292 mod util;
293
294 const DEFAULT_BUF_SIZE: usize = crate::sys_common::io::DEFAULT_BUF_SIZE;
295
296 struct Guard<'a> {
297     buf: &'a mut Vec<u8>,
298     len: usize,
299 }
300
301 impl Drop for Guard<'_> {
302     fn drop(&mut self) {
303         unsafe {
304             self.buf.set_len(self.len);
305         }
306     }
307 }
308
309 // A few methods below (read_to_string, read_line) will append data into a
310 // `String` buffer, but we need to be pretty careful when doing this. The
311 // implementation will just call `.as_mut_vec()` and then delegate to a
312 // byte-oriented reading method, but we must ensure that when returning we never
313 // leave `buf` in a state such that it contains invalid UTF-8 in its bounds.
314 //
315 // To this end, we use an RAII guard (to protect against panics) which updates
316 // the length of the string when it is dropped. This guard initially truncates
317 // the string to the prior length and only after we've validated that the
318 // new contents are valid UTF-8 do we allow it to set a longer length.
319 //
320 // The unsafety in this function is twofold:
321 //
322 // 1. We're looking at the raw bytes of `buf`, so we take on the burden of UTF-8
323 //    checks.
324 // 2. We're passing a raw buffer to the function `f`, and it is expected that
325 //    the function only *appends* bytes to the buffer. We'll get undefined
326 //    behavior if existing bytes are overwritten to have non-UTF-8 data.
327 fn append_to_string<F>(buf: &mut String, f: F) -> Result<usize>
328 where
329     F: FnOnce(&mut Vec<u8>) -> Result<usize>,
330 {
331     unsafe {
332         let mut g = Guard { len: buf.len(), buf: buf.as_mut_vec() };
333         let ret = f(g.buf);
334         if str::from_utf8(&g.buf[g.len..]).is_err() {
335             ret.and_then(|_| {
336                 Err(Error::new(ErrorKind::InvalidData, "stream did not contain valid UTF-8"))
337             })
338         } else {
339             g.len = g.buf.len();
340             ret
341         }
342     }
343 }
344
345 // This uses an adaptive system to extend the vector when it fills. We want to
346 // avoid paying to allocate and zero a huge chunk of memory if the reader only
347 // has 4 bytes while still making large reads if the reader does have a ton
348 // of data to return. Simply tacking on an extra DEFAULT_BUF_SIZE space every
349 // time is 4,500 times (!) slower than a default reservation size of 32 if the
350 // reader has a very small amount of data to return.
351 //
352 // Because we're extending the buffer with uninitialized data for trusted
353 // readers, we need to make sure to truncate that if any of this panics.
354 fn read_to_end<R: Read + ?Sized>(r: &mut R, buf: &mut Vec<u8>) -> Result<usize> {
355     read_to_end_with_reservation(r, buf, |_| 32)
356 }
357
358 fn read_to_end_with_reservation<R, F>(
359     r: &mut R,
360     buf: &mut Vec<u8>,
361     mut reservation_size: F,
362 ) -> Result<usize>
363 where
364     R: Read + ?Sized,
365     F: FnMut(&R) -> usize,
366 {
367     let start_len = buf.len();
368     let mut g = Guard { len: buf.len(), buf };
369     let ret;
370     loop {
371         if g.len == g.buf.len() {
372             unsafe {
373                 // FIXME(danielhenrymantilla): #42788
374                 //
375                 //   - This creates a (mut) reference to a slice of
376                 //     _uninitialized_ integers, which is **undefined behavior**
377                 //
378                 //   - Only the standard library gets to soundly "ignore" this,
379                 //     based on its privileged knowledge of unstable rustc
380                 //     internals;
381                 g.buf.reserve(reservation_size(r));
382                 let capacity = g.buf.capacity();
383                 g.buf.set_len(capacity);
384                 r.initializer().initialize(&mut g.buf[g.len..]);
385             }
386         }
387
388         match r.read(&mut g.buf[g.len..]) {
389             Ok(0) => {
390                 ret = Ok(g.len - start_len);
391                 break;
392             }
393             Ok(n) => g.len += n,
394             Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
395             Err(e) => {
396                 ret = Err(e);
397                 break;
398             }
399         }
400     }
401
402     ret
403 }
404
405 pub(crate) fn default_read_vectored<F>(read: F, bufs: &mut [IoSliceMut<'_>]) -> Result<usize>
406 where
407     F: FnOnce(&mut [u8]) -> Result<usize>,
408 {
409     let buf = bufs.iter_mut().find(|b| !b.is_empty()).map_or(&mut [][..], |b| &mut **b);
410     read(buf)
411 }
412
413 pub(crate) fn default_write_vectored<F>(write: F, bufs: &[IoSlice<'_>]) -> Result<usize>
414 where
415     F: FnOnce(&[u8]) -> Result<usize>,
416 {
417     let buf = bufs.iter().find(|b| !b.is_empty()).map_or(&[][..], |b| &**b);
418     write(buf)
419 }
420
421 /// The `Read` trait allows for reading bytes from a source.
422 ///
423 /// Implementors of the `Read` trait are called 'readers'.
424 ///
425 /// Readers are defined by one required method, [`read()`]. Each call to [`read()`]
426 /// will attempt to pull bytes from this source into a provided buffer. A
427 /// number of other methods are implemented in terms of [`read()`], giving
428 /// implementors a number of ways to read bytes while only needing to implement
429 /// a single method.
430 ///
431 /// Readers are intended to be composable with one another. Many implementors
432 /// throughout [`std::io`] take and provide types which implement the `Read`
433 /// trait.
434 ///
435 /// Please note that each call to [`read()`] may involve a system call, and
436 /// therefore, using something that implements [`BufRead`], such as
437 /// [`BufReader`], will be more efficient.
438 ///
439 /// # Examples
440 ///
441 /// [`File`]s implement `Read`:
442 ///
443 /// ```no_run
444 /// use std::io;
445 /// use std::io::prelude::*;
446 /// use std::fs::File;
447 ///
448 /// fn main() -> io::Result<()> {
449 ///     let mut f = File::open("foo.txt")?;
450 ///     let mut buffer = [0; 10];
451 ///
452 ///     // read up to 10 bytes
453 ///     f.read(&mut buffer)?;
454 ///
455 ///     let mut buffer = Vec::new();
456 ///     // read the whole file
457 ///     f.read_to_end(&mut buffer)?;
458 ///
459 ///     // read into a String, so that you don't need to do the conversion.
460 ///     let mut buffer = String::new();
461 ///     f.read_to_string(&mut buffer)?;
462 ///
463 ///     // and more! See the other methods for more details.
464 ///     Ok(())
465 /// }
466 /// ```
467 ///
468 /// Read from [`&str`] because [`&[u8]`][slice] implements `Read`:
469 ///
470 /// ```no_run
471 /// # use std::io;
472 /// use std::io::prelude::*;
473 ///
474 /// fn main() -> io::Result<()> {
475 ///     let mut b = "This string will be read".as_bytes();
476 ///     let mut buffer = [0; 10];
477 ///
478 ///     // read up to 10 bytes
479 ///     b.read(&mut buffer)?;
480 ///
481 ///     // etc... it works exactly as a File does!
482 ///     Ok(())
483 /// }
484 /// ```
485 ///
486 /// [`read()`]: Read::read
487 /// [`&str`]: prim@str
488 /// [`std::io`]: self
489 /// [`File`]: crate::fs::File
490 /// [slice]: ../../std/primitive.slice.html
491 #[stable(feature = "rust1", since = "1.0.0")]
492 #[doc(spotlight)]
493 pub trait Read {
494     /// Pull some bytes from this source into the specified buffer, returning
495     /// how many bytes were read.
496     ///
497     /// This function does not provide any guarantees about whether it blocks
498     /// waiting for data, but if an object needs to block for a read and cannot,
499     /// it will typically signal this via an [`Err`] return value.
500     ///
501     /// If the return value of this method is [`Ok(n)`], then it must be
502     /// guaranteed that `0 <= n <= buf.len()`. A nonzero `n` value indicates
503     /// that the buffer `buf` has been filled in with `n` bytes of data from this
504     /// source. If `n` is `0`, then it can indicate one of two scenarios:
505     ///
506     /// 1. This reader has reached its "end of file" and will likely no longer
507     ///    be able to produce bytes. Note that this does not mean that the
508     ///    reader will *always* no longer be able to produce bytes.
509     /// 2. The buffer specified was 0 bytes in length.
510     ///
511     /// It is not an error if the returned value `n` is smaller than the buffer size,
512     /// even when the reader is not at the end of the stream yet.
513     /// This may happen for example because fewer bytes are actually available right now
514     /// (e. g. being close to end-of-file) or because read() was interrupted by a signal.
515     ///
516     /// No guarantees are provided about the contents of `buf` when this
517     /// function is called, implementations cannot rely on any property of the
518     /// contents of `buf` being true. It is recommended that *implementations*
519     /// only write data to `buf` instead of reading its contents.
520     ///
521     /// Correspondingly, however, *callers* of this method may not assume any guarantees
522     /// about how the implementation uses `buf`. The trait is safe to implement,
523     /// so it is possible that the code that's supposed to write to the buffer might also read
524     /// from it. It is your responsibility to make sure that `buf` is initialized
525     /// before calling `read`. Calling `read` with an uninitialized `buf` (of the kind one
526     /// obtains via [`MaybeUninit<T>`]) is not safe, and can lead to undefined behavior.
527     ///
528     /// [`MaybeUninit<T>`]: crate::mem::MaybeUninit
529     ///
530     /// # Errors
531     ///
532     /// If this function encounters any form of I/O or other error, an error
533     /// variant will be returned. If an error is returned then it must be
534     /// guaranteed that no bytes were read.
535     ///
536     /// An error of the [`ErrorKind::Interrupted`] kind is non-fatal and the read
537     /// operation should be retried if there is nothing else to do.
538     ///
539     /// # Examples
540     ///
541     /// [`File`]s implement `Read`:
542     ///
543     /// [`Ok(n)`]: Ok
544     /// [`File`]: crate::fs::File
545     ///
546     /// ```no_run
547     /// use std::io;
548     /// use std::io::prelude::*;
549     /// use std::fs::File;
550     ///
551     /// fn main() -> io::Result<()> {
552     ///     let mut f = File::open("foo.txt")?;
553     ///     let mut buffer = [0; 10];
554     ///
555     ///     // read up to 10 bytes
556     ///     let n = f.read(&mut buffer[..])?;
557     ///
558     ///     println!("The bytes: {:?}", &buffer[..n]);
559     ///     Ok(())
560     /// }
561     /// ```
562     #[stable(feature = "rust1", since = "1.0.0")]
563     fn read(&mut self, buf: &mut [u8]) -> Result<usize>;
564
565     /// Like `read`, except that it reads into a slice of buffers.
566     ///
567     /// Data is copied to fill each buffer in order, with the final buffer
568     /// written to possibly being only partially filled. This method must
569     /// behave equivalently to a single call to `read` with concatenated
570     /// buffers.
571     ///
572     /// The default implementation calls `read` with either the first nonempty
573     /// buffer provided, or an empty one if none exists.
574     #[stable(feature = "iovec", since = "1.36.0")]
575     fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize> {
576         default_read_vectored(|b| self.read(b), bufs)
577     }
578
579     /// Determines if this `Read`er has an efficient `read_vectored`
580     /// implementation.
581     ///
582     /// If a `Read`er does not override the default `read_vectored`
583     /// implementation, code using it may want to avoid the method all together
584     /// and coalesce writes into a single buffer for higher performance.
585     ///
586     /// The default implementation returns `false`.
587     #[unstable(feature = "can_vector", issue = "69941")]
588     fn is_read_vectored(&self) -> bool {
589         false
590     }
591
592     /// Determines if this `Read`er can work with buffers of uninitialized
593     /// memory.
594     ///
595     /// The default implementation returns an initializer which will zero
596     /// buffers.
597     ///
598     /// If a `Read`er guarantees that it can work properly with uninitialized
599     /// memory, it should call [`Initializer::nop()`]. See the documentation for
600     /// [`Initializer`] for details.
601     ///
602     /// The behavior of this method must be independent of the state of the
603     /// `Read`er - the method only takes `&self` so that it can be used through
604     /// trait objects.
605     ///
606     /// # Safety
607     ///
608     /// This method is unsafe because a `Read`er could otherwise return a
609     /// non-zeroing `Initializer` from another `Read` type without an `unsafe`
610     /// block.
611     #[unstable(feature = "read_initializer", issue = "42788")]
612     #[inline]
613     unsafe fn initializer(&self) -> Initializer {
614         Initializer::zeroing()
615     }
616
617     /// Read all bytes until EOF in this source, placing them into `buf`.
618     ///
619     /// All bytes read from this source will be appended to the specified buffer
620     /// `buf`. This function will continuously call [`read()`] to append more data to
621     /// `buf` until [`read()`] returns either [`Ok(0)`] or an error of
622     /// non-[`ErrorKind::Interrupted`] kind.
623     ///
624     /// If successful, this function will return the total number of bytes read.
625     ///
626     /// # Errors
627     ///
628     /// If this function encounters an error of the kind
629     /// [`ErrorKind::Interrupted`] then the error is ignored and the operation
630     /// will continue.
631     ///
632     /// If any other read error is encountered then this function immediately
633     /// returns. Any bytes which have already been read will be appended to
634     /// `buf`.
635     ///
636     /// # Examples
637     ///
638     /// [`File`]s implement `Read`:
639     ///
640     /// [`read()`]: Read::read
641     /// [`Ok(0)`]: Ok
642     /// [`File`]: crate::fs::File
643     ///
644     /// ```no_run
645     /// use std::io;
646     /// use std::io::prelude::*;
647     /// use std::fs::File;
648     ///
649     /// fn main() -> io::Result<()> {
650     ///     let mut f = File::open("foo.txt")?;
651     ///     let mut buffer = Vec::new();
652     ///
653     ///     // read the whole file
654     ///     f.read_to_end(&mut buffer)?;
655     ///     Ok(())
656     /// }
657     /// ```
658     ///
659     /// (See also the [`std::fs::read`] convenience function for reading from a
660     /// file.)
661     ///
662     /// [`std::fs::read`]: crate::fs::read
663     #[stable(feature = "rust1", since = "1.0.0")]
664     fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
665         read_to_end(self, buf)
666     }
667
668     /// Read all bytes until EOF in this source, appending them to `buf`.
669     ///
670     /// If successful, this function returns the number of bytes which were read
671     /// and appended to `buf`.
672     ///
673     /// # Errors
674     ///
675     /// If the data in this stream is *not* valid UTF-8 then an error is
676     /// returned and `buf` is unchanged.
677     ///
678     /// See [`read_to_end`] for other error semantics.
679     ///
680     /// [`read_to_end`]: Read::read_to_end
681     ///
682     /// # Examples
683     ///
684     /// [`File`]s implement `Read`:
685     ///
686     /// [`File`]: crate::fs::File
687     ///
688     /// ```no_run
689     /// use std::io;
690     /// use std::io::prelude::*;
691     /// use std::fs::File;
692     ///
693     /// fn main() -> io::Result<()> {
694     ///     let mut f = File::open("foo.txt")?;
695     ///     let mut buffer = String::new();
696     ///
697     ///     f.read_to_string(&mut buffer)?;
698     ///     Ok(())
699     /// }
700     /// ```
701     ///
702     /// (See also the [`std::fs::read_to_string`] convenience function for
703     /// reading from a file.)
704     ///
705     /// [`std::fs::read_to_string`]: crate::fs::read_to_string
706     #[stable(feature = "rust1", since = "1.0.0")]
707     fn read_to_string(&mut self, buf: &mut String) -> Result<usize> {
708         // Note that we do *not* call `.read_to_end()` here. We are passing
709         // `&mut Vec<u8>` (the raw contents of `buf`) into the `read_to_end`
710         // method to fill it up. An arbitrary implementation could overwrite the
711         // entire contents of the vector, not just append to it (which is what
712         // we are expecting).
713         //
714         // To prevent extraneously checking the UTF-8-ness of the entire buffer
715         // we pass it to our hardcoded `read_to_end` implementation which we
716         // know is guaranteed to only read data into the end of the buffer.
717         append_to_string(buf, |b| read_to_end(self, b))
718     }
719
720     /// Read the exact number of bytes required to fill `buf`.
721     ///
722     /// This function reads as many bytes as necessary to completely fill the
723     /// specified buffer `buf`.
724     ///
725     /// No guarantees are provided about the contents of `buf` when this
726     /// function is called, implementations cannot rely on any property of the
727     /// contents of `buf` being true. It is recommended that implementations
728     /// only write data to `buf` instead of reading its contents. The
729     /// documentation on [`read`] has a more detailed explanation on this
730     /// subject.
731     ///
732     /// # Errors
733     ///
734     /// If this function encounters an error of the kind
735     /// [`ErrorKind::Interrupted`] then the error is ignored and the operation
736     /// will continue.
737     ///
738     /// If this function encounters an "end of file" before completely filling
739     /// the buffer, it returns an error of the kind [`ErrorKind::UnexpectedEof`].
740     /// The contents of `buf` are unspecified in this case.
741     ///
742     /// If any other read error is encountered then this function immediately
743     /// returns. The contents of `buf` are unspecified in this case.
744     ///
745     /// If this function returns an error, it is unspecified how many bytes it
746     /// has read, but it will never read more than would be necessary to
747     /// completely fill the buffer.
748     ///
749     /// # Examples
750     ///
751     /// [`File`]s implement `Read`:
752     ///
753     /// [`read`]: Read::read
754     /// [`File`]: crate::fs::File
755     ///
756     /// ```no_run
757     /// use std::io;
758     /// use std::io::prelude::*;
759     /// use std::fs::File;
760     ///
761     /// fn main() -> io::Result<()> {
762     ///     let mut f = File::open("foo.txt")?;
763     ///     let mut buffer = [0; 10];
764     ///
765     ///     // read exactly 10 bytes
766     ///     f.read_exact(&mut buffer)?;
767     ///     Ok(())
768     /// }
769     /// ```
770     #[stable(feature = "read_exact", since = "1.6.0")]
771     fn read_exact(&mut self, mut buf: &mut [u8]) -> Result<()> {
772         while !buf.is_empty() {
773             match self.read(buf) {
774                 Ok(0) => break,
775                 Ok(n) => {
776                     let tmp = buf;
777                     buf = &mut tmp[n..];
778                 }
779                 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
780                 Err(e) => return Err(e),
781             }
782         }
783         if !buf.is_empty() {
784             Err(Error::new(ErrorKind::UnexpectedEof, "failed to fill whole buffer"))
785         } else {
786             Ok(())
787         }
788     }
789
790     /// Creates a "by reference" adaptor for this instance of `Read`.
791     ///
792     /// The returned adaptor also implements `Read` and will simply borrow this
793     /// current reader.
794     ///
795     /// # Examples
796     ///
797     /// [`File`]s implement `Read`:
798     ///
799     /// [`File`]: crate::fs::File
800     ///
801     /// ```no_run
802     /// use std::io;
803     /// use std::io::Read;
804     /// use std::fs::File;
805     ///
806     /// fn main() -> io::Result<()> {
807     ///     let mut f = File::open("foo.txt")?;
808     ///     let mut buffer = Vec::new();
809     ///     let mut other_buffer = Vec::new();
810     ///
811     ///     {
812     ///         let reference = f.by_ref();
813     ///
814     ///         // read at most 5 bytes
815     ///         reference.take(5).read_to_end(&mut buffer)?;
816     ///
817     ///     } // drop our &mut reference so we can use f again
818     ///
819     ///     // original file still usable, read the rest
820     ///     f.read_to_end(&mut other_buffer)?;
821     ///     Ok(())
822     /// }
823     /// ```
824     #[stable(feature = "rust1", since = "1.0.0")]
825     fn by_ref(&mut self) -> &mut Self
826     where
827         Self: Sized,
828     {
829         self
830     }
831
832     /// Transforms this `Read` instance to an [`Iterator`] over its bytes.
833     ///
834     /// The returned type implements [`Iterator`] where the `Item` is
835     /// [`Result`]`<`[`u8`]`, `[`io::Error`]`>`.
836     /// The yielded item is [`Ok`] if a byte was successfully read and [`Err`]
837     /// otherwise. EOF is mapped to returning [`None`] from this iterator.
838     ///
839     /// # Examples
840     ///
841     /// [`File`]s implement `Read`:
842     ///
843     /// [`File`]: crate::fs::File
844     /// [`Result`]: crate::result::Result
845     /// [`io::Error`]: self::Error
846     ///
847     /// ```no_run
848     /// use std::io;
849     /// use std::io::prelude::*;
850     /// use std::fs::File;
851     ///
852     /// fn main() -> io::Result<()> {
853     ///     let mut f = File::open("foo.txt")?;
854     ///
855     ///     for byte in f.bytes() {
856     ///         println!("{}", byte.unwrap());
857     ///     }
858     ///     Ok(())
859     /// }
860     /// ```
861     #[stable(feature = "rust1", since = "1.0.0")]
862     fn bytes(self) -> Bytes<Self>
863     where
864         Self: Sized,
865     {
866         Bytes { inner: self }
867     }
868
869     /// Creates an adaptor which will chain this stream with another.
870     ///
871     /// The returned `Read` instance will first read all bytes from this object
872     /// until EOF is encountered. Afterwards the output is equivalent to the
873     /// output of `next`.
874     ///
875     /// # Examples
876     ///
877     /// [`File`]s implement `Read`:
878     ///
879     /// [`File`]: crate::fs::File
880     ///
881     /// ```no_run
882     /// use std::io;
883     /// use std::io::prelude::*;
884     /// use std::fs::File;
885     ///
886     /// fn main() -> io::Result<()> {
887     ///     let mut f1 = File::open("foo.txt")?;
888     ///     let mut f2 = File::open("bar.txt")?;
889     ///
890     ///     let mut handle = f1.chain(f2);
891     ///     let mut buffer = String::new();
892     ///
893     ///     // read the value into a String. We could use any Read method here,
894     ///     // this is just one example.
895     ///     handle.read_to_string(&mut buffer)?;
896     ///     Ok(())
897     /// }
898     /// ```
899     #[stable(feature = "rust1", since = "1.0.0")]
900     fn chain<R: Read>(self, next: R) -> Chain<Self, R>
901     where
902         Self: Sized,
903     {
904         Chain { first: self, second: next, done_first: false }
905     }
906
907     /// Creates an adaptor which will read at most `limit` bytes from it.
908     ///
909     /// This function returns a new instance of `Read` which will read at most
910     /// `limit` bytes, after which it will always return EOF ([`Ok(0)`]). Any
911     /// read errors will not count towards the number of bytes read and future
912     /// calls to [`read()`] may succeed.
913     ///
914     /// # Examples
915     ///
916     /// [`File`]s implement `Read`:
917     ///
918     /// [`File`]: crate::fs::File
919     /// [`Ok(0)`]: Ok
920     /// [`read()`]: Read::read
921     ///
922     /// ```no_run
923     /// use std::io;
924     /// use std::io::prelude::*;
925     /// use std::fs::File;
926     ///
927     /// fn main() -> io::Result<()> {
928     ///     let mut f = File::open("foo.txt")?;
929     ///     let mut buffer = [0; 5];
930     ///
931     ///     // read at most five bytes
932     ///     let mut handle = f.take(5);
933     ///
934     ///     handle.read(&mut buffer)?;
935     ///     Ok(())
936     /// }
937     /// ```
938     #[stable(feature = "rust1", since = "1.0.0")]
939     fn take(self, limit: u64) -> Take<Self>
940     where
941         Self: Sized,
942     {
943         Take { inner: self, limit }
944     }
945 }
946
947 /// A buffer type used with `Read::read_vectored`.
948 ///
949 /// It is semantically a wrapper around an `&mut [u8]`, but is guaranteed to be
950 /// ABI compatible with the `iovec` type on Unix platforms and `WSABUF` on
951 /// Windows.
952 #[stable(feature = "iovec", since = "1.36.0")]
953 #[repr(transparent)]
954 pub struct IoSliceMut<'a>(sys::io::IoSliceMut<'a>);
955
956 #[stable(feature = "iovec-send-sync", since = "1.44.0")]
957 unsafe impl<'a> Send for IoSliceMut<'a> {}
958
959 #[stable(feature = "iovec-send-sync", since = "1.44.0")]
960 unsafe impl<'a> Sync for IoSliceMut<'a> {}
961
962 #[stable(feature = "iovec", since = "1.36.0")]
963 impl<'a> fmt::Debug for IoSliceMut<'a> {
964     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
965         fmt::Debug::fmt(self.0.as_slice(), fmt)
966     }
967 }
968
969 impl<'a> IoSliceMut<'a> {
970     /// Creates a new `IoSliceMut` wrapping a byte slice.
971     ///
972     /// # Panics
973     ///
974     /// Panics on Windows if the slice is larger than 4GB.
975     #[stable(feature = "iovec", since = "1.36.0")]
976     #[inline]
977     pub fn new(buf: &'a mut [u8]) -> IoSliceMut<'a> {
978         IoSliceMut(sys::io::IoSliceMut::new(buf))
979     }
980
981     /// Advance the internal cursor of the slice.
982     ///
983     /// # Notes
984     ///
985     /// Elements in the slice may be modified if the cursor is not advanced to
986     /// the end of the slice. For example if we have a slice of buffers with 2
987     /// `IoSliceMut`s, both of length 8, and we advance the cursor by 10 bytes
988     /// the first `IoSliceMut` will be untouched however the second will be
989     /// modified to remove the first 2 bytes (10 - 8).
990     ///
991     /// # Examples
992     ///
993     /// ```
994     /// #![feature(io_slice_advance)]
995     ///
996     /// use std::io::IoSliceMut;
997     /// use std::ops::Deref;
998     ///
999     /// let mut buf1 = [1; 8];
1000     /// let mut buf2 = [2; 16];
1001     /// let mut buf3 = [3; 8];
1002     /// let mut bufs = &mut [
1003     ///     IoSliceMut::new(&mut buf1),
1004     ///     IoSliceMut::new(&mut buf2),
1005     ///     IoSliceMut::new(&mut buf3),
1006     /// ][..];
1007     ///
1008     /// // Mark 10 bytes as read.
1009     /// bufs = IoSliceMut::advance(bufs, 10);
1010     /// assert_eq!(bufs[0].deref(), [2; 14].as_ref());
1011     /// assert_eq!(bufs[1].deref(), [3; 8].as_ref());
1012     /// ```
1013     #[unstable(feature = "io_slice_advance", issue = "62726")]
1014     #[inline]
1015     pub fn advance<'b>(bufs: &'b mut [IoSliceMut<'a>], n: usize) -> &'b mut [IoSliceMut<'a>] {
1016         // Number of buffers to remove.
1017         let mut remove = 0;
1018         // Total length of all the to be removed buffers.
1019         let mut accumulated_len = 0;
1020         for buf in bufs.iter() {
1021             if accumulated_len + buf.len() > n {
1022                 break;
1023             } else {
1024                 accumulated_len += buf.len();
1025                 remove += 1;
1026             }
1027         }
1028
1029         let bufs = &mut bufs[remove..];
1030         if !bufs.is_empty() {
1031             bufs[0].0.advance(n - accumulated_len)
1032         }
1033         bufs
1034     }
1035 }
1036
1037 #[stable(feature = "iovec", since = "1.36.0")]
1038 impl<'a> Deref for IoSliceMut<'a> {
1039     type Target = [u8];
1040
1041     #[inline]
1042     fn deref(&self) -> &[u8] {
1043         self.0.as_slice()
1044     }
1045 }
1046
1047 #[stable(feature = "iovec", since = "1.36.0")]
1048 impl<'a> DerefMut for IoSliceMut<'a> {
1049     #[inline]
1050     fn deref_mut(&mut self) -> &mut [u8] {
1051         self.0.as_mut_slice()
1052     }
1053 }
1054
1055 /// A buffer type used with `Write::write_vectored`.
1056 ///
1057 /// It is semantically a wrapper around an `&[u8]`, but is guaranteed to be
1058 /// ABI compatible with the `iovec` type on Unix platforms and `WSABUF` on
1059 /// Windows.
1060 #[stable(feature = "iovec", since = "1.36.0")]
1061 #[derive(Copy, Clone)]
1062 #[repr(transparent)]
1063 pub struct IoSlice<'a>(sys::io::IoSlice<'a>);
1064
1065 #[stable(feature = "iovec-send-sync", since = "1.44.0")]
1066 unsafe impl<'a> Send for IoSlice<'a> {}
1067
1068 #[stable(feature = "iovec-send-sync", since = "1.44.0")]
1069 unsafe impl<'a> Sync for IoSlice<'a> {}
1070
1071 #[stable(feature = "iovec", since = "1.36.0")]
1072 impl<'a> fmt::Debug for IoSlice<'a> {
1073     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1074         fmt::Debug::fmt(self.0.as_slice(), fmt)
1075     }
1076 }
1077
1078 impl<'a> IoSlice<'a> {
1079     /// Creates a new `IoSlice` wrapping a byte slice.
1080     ///
1081     /// # Panics
1082     ///
1083     /// Panics on Windows if the slice is larger than 4GB.
1084     #[stable(feature = "iovec", since = "1.36.0")]
1085     #[inline]
1086     pub fn new(buf: &'a [u8]) -> IoSlice<'a> {
1087         IoSlice(sys::io::IoSlice::new(buf))
1088     }
1089
1090     /// Advance the internal cursor of the slice.
1091     ///
1092     /// # Notes
1093     ///
1094     /// Elements in the slice may be modified if the cursor is not advanced to
1095     /// the end of the slice. For example if we have a slice of buffers with 2
1096     /// `IoSlice`s, both of length 8, and we advance the cursor by 10 bytes the
1097     /// first `IoSlice` will be untouched however the second will be modified to
1098     /// remove the first 2 bytes (10 - 8).
1099     ///
1100     /// # Examples
1101     ///
1102     /// ```
1103     /// #![feature(io_slice_advance)]
1104     ///
1105     /// use std::io::IoSlice;
1106     /// use std::ops::Deref;
1107     ///
1108     /// let buf1 = [1; 8];
1109     /// let buf2 = [2; 16];
1110     /// let buf3 = [3; 8];
1111     /// let mut bufs = &mut [
1112     ///     IoSlice::new(&buf1),
1113     ///     IoSlice::new(&buf2),
1114     ///     IoSlice::new(&buf3),
1115     /// ][..];
1116     ///
1117     /// // Mark 10 bytes as written.
1118     /// bufs = IoSlice::advance(bufs, 10);
1119     /// assert_eq!(bufs[0].deref(), [2; 14].as_ref());
1120     /// assert_eq!(bufs[1].deref(), [3; 8].as_ref());
1121     #[unstable(feature = "io_slice_advance", issue = "62726")]
1122     #[inline]
1123     pub fn advance<'b>(bufs: &'b mut [IoSlice<'a>], n: usize) -> &'b mut [IoSlice<'a>] {
1124         // Number of buffers to remove.
1125         let mut remove = 0;
1126         // Total length of all the to be removed buffers.
1127         let mut accumulated_len = 0;
1128         for buf in bufs.iter() {
1129             if accumulated_len + buf.len() > n {
1130                 break;
1131             } else {
1132                 accumulated_len += buf.len();
1133                 remove += 1;
1134             }
1135         }
1136
1137         let bufs = &mut bufs[remove..];
1138         if !bufs.is_empty() {
1139             bufs[0].0.advance(n - accumulated_len)
1140         }
1141         bufs
1142     }
1143 }
1144
1145 #[stable(feature = "iovec", since = "1.36.0")]
1146 impl<'a> Deref for IoSlice<'a> {
1147     type Target = [u8];
1148
1149     #[inline]
1150     fn deref(&self) -> &[u8] {
1151         self.0.as_slice()
1152     }
1153 }
1154
1155 /// A type used to conditionally initialize buffers passed to `Read` methods.
1156 #[unstable(feature = "read_initializer", issue = "42788")]
1157 #[derive(Debug)]
1158 pub struct Initializer(bool);
1159
1160 impl Initializer {
1161     /// Returns a new `Initializer` which will zero out buffers.
1162     #[unstable(feature = "read_initializer", issue = "42788")]
1163     #[inline]
1164     pub fn zeroing() -> Initializer {
1165         Initializer(true)
1166     }
1167
1168     /// Returns a new `Initializer` which will not zero out buffers.
1169     ///
1170     /// # Safety
1171     ///
1172     /// This may only be called by `Read`ers which guarantee that they will not
1173     /// read from buffers passed to `Read` methods, and that the return value of
1174     /// the method accurately reflects the number of bytes that have been
1175     /// written to the head of the buffer.
1176     #[unstable(feature = "read_initializer", issue = "42788")]
1177     #[inline]
1178     pub unsafe fn nop() -> Initializer {
1179         Initializer(false)
1180     }
1181
1182     /// Indicates if a buffer should be initialized.
1183     #[unstable(feature = "read_initializer", issue = "42788")]
1184     #[inline]
1185     pub fn should_initialize(&self) -> bool {
1186         self.0
1187     }
1188
1189     /// Initializes a buffer if necessary.
1190     #[unstable(feature = "read_initializer", issue = "42788")]
1191     #[inline]
1192     pub fn initialize(&self, buf: &mut [u8]) {
1193         if self.should_initialize() {
1194             unsafe { ptr::write_bytes(buf.as_mut_ptr(), 0, buf.len()) }
1195         }
1196     }
1197 }
1198
1199 /// A trait for objects which are byte-oriented sinks.
1200 ///
1201 /// Implementors of the `Write` trait are sometimes called 'writers'.
1202 ///
1203 /// Writers are defined by two required methods, [`write`] and [`flush`]:
1204 ///
1205 /// * The [`write`] method will attempt to write some data into the object,
1206 ///   returning how many bytes were successfully written.
1207 ///
1208 /// * The [`flush`] method is useful for adaptors and explicit buffers
1209 ///   themselves for ensuring that all buffered data has been pushed out to the
1210 ///   'true sink'.
1211 ///
1212 /// Writers are intended to be composable with one another. Many implementors
1213 /// throughout [`std::io`] take and provide types which implement the `Write`
1214 /// trait.
1215 ///
1216 /// [`write`]: Write::write
1217 /// [`flush`]: Write::flush
1218 /// [`std::io`]: self
1219 ///
1220 /// # Examples
1221 ///
1222 /// ```no_run
1223 /// use std::io::prelude::*;
1224 /// use std::fs::File;
1225 ///
1226 /// fn main() -> std::io::Result<()> {
1227 ///     let data = b"some bytes";
1228 ///
1229 ///     let mut pos = 0;
1230 ///     let mut buffer = File::create("foo.txt")?;
1231 ///
1232 ///     while pos < data.len() {
1233 ///         let bytes_written = buffer.write(&data[pos..])?;
1234 ///         pos += bytes_written;
1235 ///     }
1236 ///     Ok(())
1237 /// }
1238 /// ```
1239 ///
1240 /// The trait also provides convenience methods like [`write_all`], which calls
1241 /// `write` in a loop until its entire input has been written.
1242 ///
1243 /// [`write_all`]: Write::write_all
1244 #[stable(feature = "rust1", since = "1.0.0")]
1245 #[doc(spotlight)]
1246 pub trait Write {
1247     /// Write a buffer into this writer, returning how many bytes were written.
1248     ///
1249     /// This function will attempt to write the entire contents of `buf`, but
1250     /// the entire write may not succeed, or the write may also generate an
1251     /// error. A call to `write` represents *at most one* attempt to write to
1252     /// any wrapped object.
1253     ///
1254     /// Calls to `write` are not guaranteed to block waiting for data to be
1255     /// written, and a write which would otherwise block can be indicated through
1256     /// an [`Err`] variant.
1257     ///
1258     /// If the return value is [`Ok(n)`] then it must be guaranteed that
1259     /// `n <= buf.len()`. A return value of `0` typically means that the
1260     /// underlying object is no longer able to accept bytes and will likely not
1261     /// be able to in the future as well, or that the buffer provided is empty.
1262     ///
1263     /// # Errors
1264     ///
1265     /// Each call to `write` may generate an I/O error indicating that the
1266     /// operation could not be completed. If an error is returned then no bytes
1267     /// in the buffer were written to this writer.
1268     ///
1269     /// It is **not** considered an error if the entire buffer could not be
1270     /// written to this writer.
1271     ///
1272     /// An error of the [`ErrorKind::Interrupted`] kind is non-fatal and the
1273     /// write operation should be retried if there is nothing else to do.
1274     ///
1275     /// # Examples
1276     ///
1277     /// ```no_run
1278     /// use std::io::prelude::*;
1279     /// use std::fs::File;
1280     ///
1281     /// fn main() -> std::io::Result<()> {
1282     ///     let mut buffer = File::create("foo.txt")?;
1283     ///
1284     ///     // Writes some prefix of the byte string, not necessarily all of it.
1285     ///     buffer.write(b"some bytes")?;
1286     ///     Ok(())
1287     /// }
1288     /// ```
1289     ///
1290     /// [`Ok(n)`]: Ok
1291     #[stable(feature = "rust1", since = "1.0.0")]
1292     fn write(&mut self, buf: &[u8]) -> Result<usize>;
1293
1294     /// Like [`write`], except that it writes from a slice of buffers.
1295     ///
1296     /// Data is copied from each buffer in order, with the final buffer
1297     /// read from possibly being only partially consumed. This method must
1298     /// behave as a call to [`write`] with the buffers concatenated would.
1299     ///
1300     /// The default implementation calls [`write`] with either the first nonempty
1301     /// buffer provided, or an empty one if none exists.
1302     ///
1303     /// [`write`]: Write::write
1304     #[stable(feature = "iovec", since = "1.36.0")]
1305     fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> Result<usize> {
1306         default_write_vectored(|b| self.write(b), bufs)
1307     }
1308
1309     /// Determines if this `Write`er has an efficient [`write_vectored`]
1310     /// implementation.
1311     ///
1312     /// If a `Write`er does not override the default [`write_vectored`]
1313     /// implementation, code using it may want to avoid the method all together
1314     /// and coalesce writes into a single buffer for higher performance.
1315     ///
1316     /// The default implementation returns `false`.
1317     ///
1318     /// [`write_vectored`]: Write::write_vectored
1319     #[unstable(feature = "can_vector", issue = "69941")]
1320     fn is_write_vectored(&self) -> bool {
1321         false
1322     }
1323
1324     /// Flush this output stream, ensuring that all intermediately buffered
1325     /// contents reach their destination.
1326     ///
1327     /// # Errors
1328     ///
1329     /// It is considered an error if not all bytes could be written due to
1330     /// I/O errors or EOF being reached.
1331     ///
1332     /// # Examples
1333     ///
1334     /// ```no_run
1335     /// use std::io::prelude::*;
1336     /// use std::io::BufWriter;
1337     /// use std::fs::File;
1338     ///
1339     /// fn main() -> std::io::Result<()> {
1340     ///     let mut buffer = BufWriter::new(File::create("foo.txt")?);
1341     ///
1342     ///     buffer.write_all(b"some bytes")?;
1343     ///     buffer.flush()?;
1344     ///     Ok(())
1345     /// }
1346     /// ```
1347     #[stable(feature = "rust1", since = "1.0.0")]
1348     fn flush(&mut self) -> Result<()>;
1349
1350     /// Attempts to write an entire buffer into this writer.
1351     ///
1352     /// This method will continuously call [`write`] until there is no more data
1353     /// to be written or an error of non-[`ErrorKind::Interrupted`] kind is
1354     /// returned. This method will not return until the entire buffer has been
1355     /// successfully written or such an error occurs. The first error that is
1356     /// not of [`ErrorKind::Interrupted`] kind generated from this method will be
1357     /// returned.
1358     ///
1359     /// If the buffer contains no data, this will never call [`write`].
1360     ///
1361     /// # Errors
1362     ///
1363     /// This function will return the first error of
1364     /// non-[`ErrorKind::Interrupted`] kind that [`write`] returns.
1365     ///
1366     /// [`write`]: Write::write
1367     ///
1368     /// # Examples
1369     ///
1370     /// ```no_run
1371     /// use std::io::prelude::*;
1372     /// use std::fs::File;
1373     ///
1374     /// fn main() -> std::io::Result<()> {
1375     ///     let mut buffer = File::create("foo.txt")?;
1376     ///
1377     ///     buffer.write_all(b"some bytes")?;
1378     ///     Ok(())
1379     /// }
1380     /// ```
1381     #[stable(feature = "rust1", since = "1.0.0")]
1382     fn write_all(&mut self, mut buf: &[u8]) -> Result<()> {
1383         while !buf.is_empty() {
1384             match self.write(buf) {
1385                 Ok(0) => {
1386                     return Err(Error::new(ErrorKind::WriteZero, "failed to write whole buffer"));
1387                 }
1388                 Ok(n) => buf = &buf[n..],
1389                 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
1390                 Err(e) => return Err(e),
1391             }
1392         }
1393         Ok(())
1394     }
1395
1396     /// Attempts to write multiple buffers into this writer.
1397     ///
1398     /// This method will continuously call [`write_vectored`] until there is no
1399     /// more data to be written or an error of non-[`ErrorKind::Interrupted`]
1400     /// kind is returned. This method will not return until all buffers have
1401     /// been successfully written or such an error occurs. The first error that
1402     /// is not of [`ErrorKind::Interrupted`] kind generated from this method
1403     /// will be returned.
1404     ///
1405     /// If the buffer contains no data, this will never call [`write_vectored`].
1406     ///
1407     /// # Notes
1408     ///
1409     /// Unlike [`write_vectored`], this takes a *mutable* reference to
1410     /// a slice of [`IoSlice`]s, not an immutable one. That's because we need to
1411     /// modify the slice to keep track of the bytes already written.
1412     ///
1413     /// Once this function returns, the contents of `bufs` are unspecified, as
1414     /// this depends on how many calls to [`write_vectored`] were necessary. It is
1415     /// best to understand this function as taking ownership of `bufs` and to
1416     /// not use `bufs` afterwards. The underlying buffers, to which the
1417     /// [`IoSlice`]s point (but not the [`IoSlice`]s themselves), are unchanged and
1418     /// can be reused.
1419     ///
1420     /// [`write_vectored`]: Write::write_vectored
1421     ///
1422     /// # Examples
1423     ///
1424     /// ```
1425     /// #![feature(write_all_vectored)]
1426     /// # fn main() -> std::io::Result<()> {
1427     ///
1428     /// use std::io::{Write, IoSlice};
1429     ///
1430     /// let mut writer = Vec::new();
1431     /// let bufs = &mut [
1432     ///     IoSlice::new(&[1]),
1433     ///     IoSlice::new(&[2, 3]),
1434     ///     IoSlice::new(&[4, 5, 6]),
1435     /// ];
1436     ///
1437     /// writer.write_all_vectored(bufs)?;
1438     /// // Note: the contents of `bufs` is now undefined, see the Notes section.
1439     ///
1440     /// assert_eq!(writer, &[1, 2, 3, 4, 5, 6]);
1441     /// # Ok(()) }
1442     /// ```
1443     #[unstable(feature = "write_all_vectored", issue = "70436")]
1444     fn write_all_vectored(&mut self, mut bufs: &mut [IoSlice<'_>]) -> Result<()> {
1445         // Guarantee that bufs is empty if it contains no data,
1446         // to avoid calling write_vectored if there is no data to be written.
1447         bufs = IoSlice::advance(bufs, 0);
1448         while !bufs.is_empty() {
1449             match self.write_vectored(bufs) {
1450                 Ok(0) => {
1451                     return Err(Error::new(ErrorKind::WriteZero, "failed to write whole buffer"));
1452                 }
1453                 Ok(n) => bufs = IoSlice::advance(bufs, n),
1454                 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
1455                 Err(e) => return Err(e),
1456             }
1457         }
1458         Ok(())
1459     }
1460
1461     /// Writes a formatted string into this writer, returning any error
1462     /// encountered.
1463     ///
1464     /// This method is primarily used to interface with the
1465     /// [`format_args!()`] macro, but it is rare that this should
1466     /// explicitly be called. The [`write!()`] macro should be favored to
1467     /// invoke this method instead.
1468     ///
1469     /// This function internally uses the [`write_all`] method on
1470     /// this trait and hence will continuously write data so long as no errors
1471     /// are received. This also means that partial writes are not indicated in
1472     /// this signature.
1473     ///
1474     /// [`write_all`]: Write::write_all
1475     ///
1476     /// # Errors
1477     ///
1478     /// This function will return any I/O error reported while formatting.
1479     ///
1480     /// # Examples
1481     ///
1482     /// ```no_run
1483     /// use std::io::prelude::*;
1484     /// use std::fs::File;
1485     ///
1486     /// fn main() -> std::io::Result<()> {
1487     ///     let mut buffer = File::create("foo.txt")?;
1488     ///
1489     ///     // this call
1490     ///     write!(buffer, "{:.*}", 2, 1.234567)?;
1491     ///     // turns into this:
1492     ///     buffer.write_fmt(format_args!("{:.*}", 2, 1.234567))?;
1493     ///     Ok(())
1494     /// }
1495     /// ```
1496     #[stable(feature = "rust1", since = "1.0.0")]
1497     fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> Result<()> {
1498         // Create a shim which translates a Write to a fmt::Write and saves
1499         // off I/O errors. instead of discarding them
1500         struct Adaptor<'a, T: ?Sized + 'a> {
1501             inner: &'a mut T,
1502             error: Result<()>,
1503         }
1504
1505         impl<T: Write + ?Sized> fmt::Write for Adaptor<'_, T> {
1506             fn write_str(&mut self, s: &str) -> fmt::Result {
1507                 match self.inner.write_all(s.as_bytes()) {
1508                     Ok(()) => Ok(()),
1509                     Err(e) => {
1510                         self.error = Err(e);
1511                         Err(fmt::Error)
1512                     }
1513                 }
1514             }
1515         }
1516
1517         let mut output = Adaptor { inner: self, error: Ok(()) };
1518         match fmt::write(&mut output, fmt) {
1519             Ok(()) => Ok(()),
1520             Err(..) => {
1521                 // check if the error came from the underlying `Write` or not
1522                 if output.error.is_err() {
1523                     output.error
1524                 } else {
1525                     Err(Error::new(ErrorKind::Other, "formatter error"))
1526                 }
1527             }
1528         }
1529     }
1530
1531     /// Creates a "by reference" adaptor for this instance of `Write`.
1532     ///
1533     /// The returned adaptor also implements `Write` and will simply borrow this
1534     /// current writer.
1535     ///
1536     /// # Examples
1537     ///
1538     /// ```no_run
1539     /// use std::io::Write;
1540     /// use std::fs::File;
1541     ///
1542     /// fn main() -> std::io::Result<()> {
1543     ///     let mut buffer = File::create("foo.txt")?;
1544     ///
1545     ///     let reference = buffer.by_ref();
1546     ///
1547     ///     // we can use reference just like our original buffer
1548     ///     reference.write_all(b"some bytes")?;
1549     ///     Ok(())
1550     /// }
1551     /// ```
1552     #[stable(feature = "rust1", since = "1.0.0")]
1553     fn by_ref(&mut self) -> &mut Self
1554     where
1555         Self: Sized,
1556     {
1557         self
1558     }
1559 }
1560
1561 /// The `Seek` trait provides a cursor which can be moved within a stream of
1562 /// bytes.
1563 ///
1564 /// The stream typically has a fixed size, allowing seeking relative to either
1565 /// end or the current offset.
1566 ///
1567 /// # Examples
1568 ///
1569 /// [`File`]s implement `Seek`:
1570 ///
1571 /// [`File`]: crate::fs::File
1572 ///
1573 /// ```no_run
1574 /// use std::io;
1575 /// use std::io::prelude::*;
1576 /// use std::fs::File;
1577 /// use std::io::SeekFrom;
1578 ///
1579 /// fn main() -> io::Result<()> {
1580 ///     let mut f = File::open("foo.txt")?;
1581 ///
1582 ///     // move the cursor 42 bytes from the start of the file
1583 ///     f.seek(SeekFrom::Start(42))?;
1584 ///     Ok(())
1585 /// }
1586 /// ```
1587 #[stable(feature = "rust1", since = "1.0.0")]
1588 pub trait Seek {
1589     /// Seek to an offset, in bytes, in a stream.
1590     ///
1591     /// A seek beyond the end of a stream is allowed, but behavior is defined
1592     /// by the implementation.
1593     ///
1594     /// If the seek operation completed successfully,
1595     /// this method returns the new position from the start of the stream.
1596     /// That position can be used later with [`SeekFrom::Start`].
1597     ///
1598     /// # Errors
1599     ///
1600     /// Seeking to a negative offset is considered an error.
1601     #[stable(feature = "rust1", since = "1.0.0")]
1602     fn seek(&mut self, pos: SeekFrom) -> Result<u64>;
1603
1604     /// Returns the length of this stream (in bytes).
1605     ///
1606     /// This method is implemented using up to three seek operations. If this
1607     /// method returns successfully, the seek position is unchanged (i.e. the
1608     /// position before calling this method is the same as afterwards).
1609     /// However, if this method returns an error, the seek position is
1610     /// unspecified.
1611     ///
1612     /// If you need to obtain the length of *many* streams and you don't care
1613     /// about the seek position afterwards, you can reduce the number of seek
1614     /// operations by simply calling `seek(SeekFrom::End(0))` and using its
1615     /// return value (it is also the stream length).
1616     ///
1617     /// Note that length of a stream can change over time (for example, when
1618     /// data is appended to a file). So calling this method multiple times does
1619     /// not necessarily return the same length each time.
1620     ///
1621     /// # Example
1622     ///
1623     /// ```no_run
1624     /// #![feature(seek_convenience)]
1625     /// use std::{
1626     ///     io::{self, Seek},
1627     ///     fs::File,
1628     /// };
1629     ///
1630     /// fn main() -> io::Result<()> {
1631     ///     let mut f = File::open("foo.txt")?;
1632     ///
1633     ///     let len = f.stream_len()?;
1634     ///     println!("The file is currently {} bytes long", len);
1635     ///     Ok(())
1636     /// }
1637     /// ```
1638     #[unstable(feature = "seek_convenience", issue = "59359")]
1639     fn stream_len(&mut self) -> Result<u64> {
1640         let old_pos = self.stream_position()?;
1641         let len = self.seek(SeekFrom::End(0))?;
1642
1643         // Avoid seeking a third time when we were already at the end of the
1644         // stream. The branch is usually way cheaper than a seek operation.
1645         if old_pos != len {
1646             self.seek(SeekFrom::Start(old_pos))?;
1647         }
1648
1649         Ok(len)
1650     }
1651
1652     /// Returns the current seek position from the start of the stream.
1653     ///
1654     /// This is equivalent to `self.seek(SeekFrom::Current(0))`.
1655     ///
1656     /// # Example
1657     ///
1658     /// ```no_run
1659     /// #![feature(seek_convenience)]
1660     /// use std::{
1661     ///     io::{self, BufRead, BufReader, Seek},
1662     ///     fs::File,
1663     /// };
1664     ///
1665     /// fn main() -> io::Result<()> {
1666     ///     let mut f = BufReader::new(File::open("foo.txt")?);
1667     ///
1668     ///     let before = f.stream_position()?;
1669     ///     f.read_line(&mut String::new())?;
1670     ///     let after = f.stream_position()?;
1671     ///
1672     ///     println!("The first line was {} bytes long", after - before);
1673     ///     Ok(())
1674     /// }
1675     /// ```
1676     #[unstable(feature = "seek_convenience", issue = "59359")]
1677     fn stream_position(&mut self) -> Result<u64> {
1678         self.seek(SeekFrom::Current(0))
1679     }
1680 }
1681
1682 /// Enumeration of possible methods to seek within an I/O object.
1683 ///
1684 /// It is used by the [`Seek`] trait.
1685 #[derive(Copy, PartialEq, Eq, Clone, Debug)]
1686 #[stable(feature = "rust1", since = "1.0.0")]
1687 pub enum SeekFrom {
1688     /// Sets the offset to the provided number of bytes.
1689     #[stable(feature = "rust1", since = "1.0.0")]
1690     Start(#[stable(feature = "rust1", since = "1.0.0")] u64),
1691
1692     /// Sets the offset to the size of this object plus the specified number of
1693     /// bytes.
1694     ///
1695     /// It is possible to seek beyond the end of an object, but it's an error to
1696     /// seek before byte 0.
1697     #[stable(feature = "rust1", since = "1.0.0")]
1698     End(#[stable(feature = "rust1", since = "1.0.0")] i64),
1699
1700     /// Sets the offset to the current position plus the specified number of
1701     /// bytes.
1702     ///
1703     /// It is possible to seek beyond the end of an object, but it's an error to
1704     /// seek before byte 0.
1705     #[stable(feature = "rust1", since = "1.0.0")]
1706     Current(#[stable(feature = "rust1", since = "1.0.0")] i64),
1707 }
1708
1709 fn read_until<R: BufRead + ?Sized>(r: &mut R, delim: u8, buf: &mut Vec<u8>) -> Result<usize> {
1710     let mut read = 0;
1711     loop {
1712         let (done, used) = {
1713             let available = match r.fill_buf() {
1714                 Ok(n) => n,
1715                 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
1716                 Err(e) => return Err(e),
1717             };
1718             match memchr::memchr(delim, available) {
1719                 Some(i) => {
1720                     buf.extend_from_slice(&available[..=i]);
1721                     (true, i + 1)
1722                 }
1723                 None => {
1724                     buf.extend_from_slice(available);
1725                     (false, available.len())
1726                 }
1727             }
1728         };
1729         r.consume(used);
1730         read += used;
1731         if done || used == 0 {
1732             return Ok(read);
1733         }
1734     }
1735 }
1736
1737 /// A `BufRead` is a type of `Read`er which has an internal buffer, allowing it
1738 /// to perform extra ways of reading.
1739 ///
1740 /// For example, reading line-by-line is inefficient without using a buffer, so
1741 /// if you want to read by line, you'll need `BufRead`, which includes a
1742 /// [`read_line`] method as well as a [`lines`] iterator.
1743 ///
1744 /// # Examples
1745 ///
1746 /// A locked standard input implements `BufRead`:
1747 ///
1748 /// ```no_run
1749 /// use std::io;
1750 /// use std::io::prelude::*;
1751 ///
1752 /// let stdin = io::stdin();
1753 /// for line in stdin.lock().lines() {
1754 ///     println!("{}", line.unwrap());
1755 /// }
1756 /// ```
1757 ///
1758 /// If you have something that implements [`Read`], you can use the [`BufReader`
1759 /// type][`BufReader`] to turn it into a `BufRead`.
1760 ///
1761 /// For example, [`File`] implements [`Read`], but not `BufRead`.
1762 /// [`BufReader`] to the rescue!
1763 ///
1764 /// [`File`]: crate::fs::File
1765 /// [`read_line`]: BufRead::read_line
1766 /// [`lines`]: BufRead::lines
1767 ///
1768 /// ```no_run
1769 /// use std::io::{self, BufReader};
1770 /// use std::io::prelude::*;
1771 /// use std::fs::File;
1772 ///
1773 /// fn main() -> io::Result<()> {
1774 ///     let f = File::open("foo.txt")?;
1775 ///     let f = BufReader::new(f);
1776 ///
1777 ///     for line in f.lines() {
1778 ///         println!("{}", line.unwrap());
1779 ///     }
1780 ///
1781 ///     Ok(())
1782 /// }
1783 /// ```
1784 #[stable(feature = "rust1", since = "1.0.0")]
1785 pub trait BufRead: Read {
1786     /// Returns the contents of the internal buffer, filling it with more data
1787     /// from the inner reader if it is empty.
1788     ///
1789     /// This function is a lower-level call. It needs to be paired with the
1790     /// [`consume`] method to function properly. When calling this
1791     /// method, none of the contents will be "read" in the sense that later
1792     /// calling `read` may return the same contents. As such, [`consume`] must
1793     /// be called with the number of bytes that are consumed from this buffer to
1794     /// ensure that the bytes are never returned twice.
1795     ///
1796     /// [`consume`]: BufRead::consume
1797     ///
1798     /// An empty buffer returned indicates that the stream has reached EOF.
1799     ///
1800     /// # Errors
1801     ///
1802     /// This function will return an I/O error if the underlying reader was
1803     /// read, but returned an error.
1804     ///
1805     /// # Examples
1806     ///
1807     /// A locked standard input implements `BufRead`:
1808     ///
1809     /// ```no_run
1810     /// use std::io;
1811     /// use std::io::prelude::*;
1812     ///
1813     /// let stdin = io::stdin();
1814     /// let mut stdin = stdin.lock();
1815     ///
1816     /// let buffer = stdin.fill_buf().unwrap();
1817     ///
1818     /// // work with buffer
1819     /// println!("{:?}", buffer);
1820     ///
1821     /// // ensure the bytes we worked with aren't returned again later
1822     /// let length = buffer.len();
1823     /// stdin.consume(length);
1824     /// ```
1825     #[stable(feature = "rust1", since = "1.0.0")]
1826     fn fill_buf(&mut self) -> Result<&[u8]>;
1827
1828     /// Tells this buffer that `amt` bytes have been consumed from the buffer,
1829     /// so they should no longer be returned in calls to `read`.
1830     ///
1831     /// This function is a lower-level call. It needs to be paired with the
1832     /// [`fill_buf`] method to function properly. This function does
1833     /// not perform any I/O, it simply informs this object that some amount of
1834     /// its buffer, returned from [`fill_buf`], has been consumed and should
1835     /// no longer be returned. As such, this function may do odd things if
1836     /// [`fill_buf`] isn't called before calling it.
1837     ///
1838     /// The `amt` must be `<=` the number of bytes in the buffer returned by
1839     /// [`fill_buf`].
1840     ///
1841     /// # Examples
1842     ///
1843     /// Since `consume()` is meant to be used with [`fill_buf`],
1844     /// that method's example includes an example of `consume()`.
1845     ///
1846     /// [`fill_buf`]: BufRead::fill_buf
1847     #[stable(feature = "rust1", since = "1.0.0")]
1848     fn consume(&mut self, amt: usize);
1849
1850     /// Read all bytes into `buf` until the delimiter `byte` or EOF is reached.
1851     ///
1852     /// This function will read bytes from the underlying stream until the
1853     /// delimiter or EOF is found. Once found, all bytes up to, and including,
1854     /// the delimiter (if found) will be appended to `buf`.
1855     ///
1856     /// If successful, this function will return the total number of bytes read.
1857     ///
1858     /// This function is blocking and should be used carefully: it is possible for
1859     /// an attacker to continuously send bytes without ever sending the delimiter
1860     /// or EOF.
1861     ///
1862     /// # Errors
1863     ///
1864     /// This function will ignore all instances of [`ErrorKind::Interrupted`] and
1865     /// will otherwise return any errors returned by [`fill_buf`].
1866     ///
1867     /// If an I/O error is encountered then all bytes read so far will be
1868     /// present in `buf` and its length will have been adjusted appropriately.
1869     ///
1870     /// [`fill_buf`]: BufRead::fill_buf
1871     ///
1872     /// # Examples
1873     ///
1874     /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1875     /// this example, we use [`Cursor`] to read all the bytes in a byte slice
1876     /// in hyphen delimited segments:
1877     ///
1878     /// ```
1879     /// use std::io::{self, BufRead};
1880     ///
1881     /// let mut cursor = io::Cursor::new(b"lorem-ipsum");
1882     /// let mut buf = vec![];
1883     ///
1884     /// // cursor is at 'l'
1885     /// let num_bytes = cursor.read_until(b'-', &mut buf)
1886     ///     .expect("reading from cursor won't fail");
1887     /// assert_eq!(num_bytes, 6);
1888     /// assert_eq!(buf, b"lorem-");
1889     /// buf.clear();
1890     ///
1891     /// // cursor is at 'i'
1892     /// let num_bytes = cursor.read_until(b'-', &mut buf)
1893     ///     .expect("reading from cursor won't fail");
1894     /// assert_eq!(num_bytes, 5);
1895     /// assert_eq!(buf, b"ipsum");
1896     /// buf.clear();
1897     ///
1898     /// // cursor is at EOF
1899     /// let num_bytes = cursor.read_until(b'-', &mut buf)
1900     ///     .expect("reading from cursor won't fail");
1901     /// assert_eq!(num_bytes, 0);
1902     /// assert_eq!(buf, b"");
1903     /// ```
1904     #[stable(feature = "rust1", since = "1.0.0")]
1905     fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> Result<usize> {
1906         read_until(self, byte, buf)
1907     }
1908
1909     /// Read all bytes until a newline (the `0xA` byte) is reached, and append
1910     /// them to the provided buffer.
1911     ///
1912     /// This function will read bytes from the underlying stream until the
1913     /// newline delimiter (the `0xA` byte) or EOF is found. Once found, all bytes
1914     /// up to, and including, the delimiter (if found) will be appended to
1915     /// `buf`.
1916     ///
1917     /// If successful, this function will return the total number of bytes read.
1918     ///
1919     /// If this function returns [`Ok(0)`], the stream has reached EOF.
1920     ///
1921     /// This function is blocking and should be used carefully: it is possible for
1922     /// an attacker to continuously send bytes without ever sending a newline
1923     /// or EOF.
1924     ///
1925     /// [`Ok(0)`]: Ok
1926     ///
1927     /// # Errors
1928     ///
1929     /// This function has the same error semantics as [`read_until`] and will
1930     /// also return an error if the read bytes are not valid UTF-8. If an I/O
1931     /// error is encountered then `buf` may contain some bytes already read in
1932     /// the event that all data read so far was valid UTF-8.
1933     ///
1934     /// [`read_until`]: BufRead::read_until
1935     ///
1936     /// # Examples
1937     ///
1938     /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1939     /// this example, we use [`Cursor`] to read all the lines in a byte slice:
1940     ///
1941     /// ```
1942     /// use std::io::{self, BufRead};
1943     ///
1944     /// let mut cursor = io::Cursor::new(b"foo\nbar");
1945     /// let mut buf = String::new();
1946     ///
1947     /// // cursor is at 'f'
1948     /// let num_bytes = cursor.read_line(&mut buf)
1949     ///     .expect("reading from cursor won't fail");
1950     /// assert_eq!(num_bytes, 4);
1951     /// assert_eq!(buf, "foo\n");
1952     /// buf.clear();
1953     ///
1954     /// // cursor is at 'b'
1955     /// let num_bytes = cursor.read_line(&mut buf)
1956     ///     .expect("reading from cursor won't fail");
1957     /// assert_eq!(num_bytes, 3);
1958     /// assert_eq!(buf, "bar");
1959     /// buf.clear();
1960     ///
1961     /// // cursor is at EOF
1962     /// let num_bytes = cursor.read_line(&mut buf)
1963     ///     .expect("reading from cursor won't fail");
1964     /// assert_eq!(num_bytes, 0);
1965     /// assert_eq!(buf, "");
1966     /// ```
1967     #[stable(feature = "rust1", since = "1.0.0")]
1968     fn read_line(&mut self, buf: &mut String) -> Result<usize> {
1969         // Note that we are not calling the `.read_until` method here, but
1970         // rather our hardcoded implementation. For more details as to why, see
1971         // the comments in `read_to_end`.
1972         append_to_string(buf, |b| read_until(self, b'\n', b))
1973     }
1974
1975     /// Returns an iterator over the contents of this reader split on the byte
1976     /// `byte`.
1977     ///
1978     /// The iterator returned from this function will return instances of
1979     /// [`io::Result`]`<`[`Vec<u8>`]`>`. Each vector returned will *not* have
1980     /// the delimiter byte at the end.
1981     ///
1982     /// This function will yield errors whenever [`read_until`] would have
1983     /// also yielded an error.
1984     ///
1985     /// [`io::Result`]: self::Result
1986     /// [`Vec<u8>`]: Vec
1987     /// [`read_until`]: BufRead::read_until
1988     ///
1989     /// # Examples
1990     ///
1991     /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
1992     /// this example, we use [`Cursor`] to iterate over all hyphen delimited
1993     /// segments in a byte slice
1994     ///
1995     /// ```
1996     /// use std::io::{self, BufRead};
1997     ///
1998     /// let cursor = io::Cursor::new(b"lorem-ipsum-dolor");
1999     ///
2000     /// let mut split_iter = cursor.split(b'-').map(|l| l.unwrap());
2001     /// assert_eq!(split_iter.next(), Some(b"lorem".to_vec()));
2002     /// assert_eq!(split_iter.next(), Some(b"ipsum".to_vec()));
2003     /// assert_eq!(split_iter.next(), Some(b"dolor".to_vec()));
2004     /// assert_eq!(split_iter.next(), None);
2005     /// ```
2006     #[stable(feature = "rust1", since = "1.0.0")]
2007     fn split(self, byte: u8) -> Split<Self>
2008     where
2009         Self: Sized,
2010     {
2011         Split { buf: self, delim: byte }
2012     }
2013
2014     /// Returns an iterator over the lines of this reader.
2015     ///
2016     /// The iterator returned from this function will yield instances of
2017     /// [`io::Result`]`<`[`String`]`>`. Each string returned will *not* have a newline
2018     /// byte (the `0xA` byte) or `CRLF` (`0xD`, `0xA` bytes) at the end.
2019     ///
2020     /// [`io::Result`]: self::Result
2021     ///
2022     /// # Examples
2023     ///
2024     /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
2025     /// this example, we use [`Cursor`] to iterate over all the lines in a byte
2026     /// slice.
2027     ///
2028     /// ```
2029     /// use std::io::{self, BufRead};
2030     ///
2031     /// let cursor = io::Cursor::new(b"lorem\nipsum\r\ndolor");
2032     ///
2033     /// let mut lines_iter = cursor.lines().map(|l| l.unwrap());
2034     /// assert_eq!(lines_iter.next(), Some(String::from("lorem")));
2035     /// assert_eq!(lines_iter.next(), Some(String::from("ipsum")));
2036     /// assert_eq!(lines_iter.next(), Some(String::from("dolor")));
2037     /// assert_eq!(lines_iter.next(), None);
2038     /// ```
2039     ///
2040     /// # Errors
2041     ///
2042     /// Each line of the iterator has the same error semantics as [`BufRead::read_line`].
2043     #[stable(feature = "rust1", since = "1.0.0")]
2044     fn lines(self) -> Lines<Self>
2045     where
2046         Self: Sized,
2047     {
2048         Lines { buf: self }
2049     }
2050 }
2051
2052 /// Adaptor to chain together two readers.
2053 ///
2054 /// This struct is generally created by calling [`chain`] on a reader.
2055 /// Please see the documentation of [`chain`] for more details.
2056 ///
2057 /// [`chain`]: Read::chain
2058 #[stable(feature = "rust1", since = "1.0.0")]
2059 pub struct Chain<T, U> {
2060     first: T,
2061     second: U,
2062     done_first: bool,
2063 }
2064
2065 impl<T, U> Chain<T, U> {
2066     /// Consumes the `Chain`, returning the wrapped readers.
2067     ///
2068     /// # Examples
2069     ///
2070     /// ```no_run
2071     /// use std::io;
2072     /// use std::io::prelude::*;
2073     /// use std::fs::File;
2074     ///
2075     /// fn main() -> io::Result<()> {
2076     ///     let mut foo_file = File::open("foo.txt")?;
2077     ///     let mut bar_file = File::open("bar.txt")?;
2078     ///
2079     ///     let chain = foo_file.chain(bar_file);
2080     ///     let (foo_file, bar_file) = chain.into_inner();
2081     ///     Ok(())
2082     /// }
2083     /// ```
2084     #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2085     pub fn into_inner(self) -> (T, U) {
2086         (self.first, self.second)
2087     }
2088
2089     /// Gets references to the underlying readers in this `Chain`.
2090     ///
2091     /// # Examples
2092     ///
2093     /// ```no_run
2094     /// use std::io;
2095     /// use std::io::prelude::*;
2096     /// use std::fs::File;
2097     ///
2098     /// fn main() -> io::Result<()> {
2099     ///     let mut foo_file = File::open("foo.txt")?;
2100     ///     let mut bar_file = File::open("bar.txt")?;
2101     ///
2102     ///     let chain = foo_file.chain(bar_file);
2103     ///     let (foo_file, bar_file) = chain.get_ref();
2104     ///     Ok(())
2105     /// }
2106     /// ```
2107     #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2108     pub fn get_ref(&self) -> (&T, &U) {
2109         (&self.first, &self.second)
2110     }
2111
2112     /// Gets mutable references to the underlying readers in this `Chain`.
2113     ///
2114     /// Care should be taken to avoid modifying the internal I/O state of the
2115     /// underlying readers as doing so may corrupt the internal state of this
2116     /// `Chain`.
2117     ///
2118     /// # Examples
2119     ///
2120     /// ```no_run
2121     /// use std::io;
2122     /// use std::io::prelude::*;
2123     /// use std::fs::File;
2124     ///
2125     /// fn main() -> io::Result<()> {
2126     ///     let mut foo_file = File::open("foo.txt")?;
2127     ///     let mut bar_file = File::open("bar.txt")?;
2128     ///
2129     ///     let mut chain = foo_file.chain(bar_file);
2130     ///     let (foo_file, bar_file) = chain.get_mut();
2131     ///     Ok(())
2132     /// }
2133     /// ```
2134     #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2135     pub fn get_mut(&mut self) -> (&mut T, &mut U) {
2136         (&mut self.first, &mut self.second)
2137     }
2138 }
2139
2140 #[stable(feature = "std_debug", since = "1.16.0")]
2141 impl<T: fmt::Debug, U: fmt::Debug> fmt::Debug for Chain<T, U> {
2142     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2143         f.debug_struct("Chain").field("t", &self.first).field("u", &self.second).finish()
2144     }
2145 }
2146
2147 #[stable(feature = "rust1", since = "1.0.0")]
2148 impl<T: Read, U: Read> Read for Chain<T, U> {
2149     fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
2150         if !self.done_first {
2151             match self.first.read(buf)? {
2152                 0 if !buf.is_empty() => self.done_first = true,
2153                 n => return Ok(n),
2154             }
2155         }
2156         self.second.read(buf)
2157     }
2158
2159     fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize> {
2160         if !self.done_first {
2161             match self.first.read_vectored(bufs)? {
2162                 0 if bufs.iter().any(|b| !b.is_empty()) => self.done_first = true,
2163                 n => return Ok(n),
2164             }
2165         }
2166         self.second.read_vectored(bufs)
2167     }
2168
2169     unsafe fn initializer(&self) -> Initializer {
2170         let initializer = self.first.initializer();
2171         if initializer.should_initialize() { initializer } else { self.second.initializer() }
2172     }
2173 }
2174
2175 #[stable(feature = "chain_bufread", since = "1.9.0")]
2176 impl<T: BufRead, U: BufRead> BufRead for Chain<T, U> {
2177     fn fill_buf(&mut self) -> Result<&[u8]> {
2178         if !self.done_first {
2179             match self.first.fill_buf()? {
2180                 buf if buf.is_empty() => {
2181                     self.done_first = true;
2182                 }
2183                 buf => return Ok(buf),
2184             }
2185         }
2186         self.second.fill_buf()
2187     }
2188
2189     fn consume(&mut self, amt: usize) {
2190         if !self.done_first { self.first.consume(amt) } else { self.second.consume(amt) }
2191     }
2192 }
2193
2194 /// Reader adaptor which limits the bytes read from an underlying reader.
2195 ///
2196 /// This struct is generally created by calling [`take`] on a reader.
2197 /// Please see the documentation of [`take`] for more details.
2198 ///
2199 /// [`take`]: Read::take
2200 #[stable(feature = "rust1", since = "1.0.0")]
2201 #[derive(Debug)]
2202 pub struct Take<T> {
2203     inner: T,
2204     limit: u64,
2205 }
2206
2207 impl<T> Take<T> {
2208     /// Returns the number of bytes that can be read before this instance will
2209     /// return EOF.
2210     ///
2211     /// # Note
2212     ///
2213     /// This instance may reach `EOF` after reading fewer bytes than indicated by
2214     /// this method if the underlying [`Read`] instance reaches EOF.
2215     ///
2216     /// # Examples
2217     ///
2218     /// ```no_run
2219     /// use std::io;
2220     /// use std::io::prelude::*;
2221     /// use std::fs::File;
2222     ///
2223     /// fn main() -> io::Result<()> {
2224     ///     let f = File::open("foo.txt")?;
2225     ///
2226     ///     // read at most five bytes
2227     ///     let handle = f.take(5);
2228     ///
2229     ///     println!("limit: {}", handle.limit());
2230     ///     Ok(())
2231     /// }
2232     /// ```
2233     #[stable(feature = "rust1", since = "1.0.0")]
2234     pub fn limit(&self) -> u64 {
2235         self.limit
2236     }
2237
2238     /// Sets the number of bytes that can be read before this instance will
2239     /// return EOF. This is the same as constructing a new `Take` instance, so
2240     /// the amount of bytes read and the previous limit value don't matter when
2241     /// calling this method.
2242     ///
2243     /// # Examples
2244     ///
2245     /// ```no_run
2246     /// use std::io;
2247     /// use std::io::prelude::*;
2248     /// use std::fs::File;
2249     ///
2250     /// fn main() -> io::Result<()> {
2251     ///     let f = File::open("foo.txt")?;
2252     ///
2253     ///     // read at most five bytes
2254     ///     let mut handle = f.take(5);
2255     ///     handle.set_limit(10);
2256     ///
2257     ///     assert_eq!(handle.limit(), 10);
2258     ///     Ok(())
2259     /// }
2260     /// ```
2261     #[stable(feature = "take_set_limit", since = "1.27.0")]
2262     pub fn set_limit(&mut self, limit: u64) {
2263         self.limit = limit;
2264     }
2265
2266     /// Consumes the `Take`, returning the wrapped reader.
2267     ///
2268     /// # Examples
2269     ///
2270     /// ```no_run
2271     /// use std::io;
2272     /// use std::io::prelude::*;
2273     /// use std::fs::File;
2274     ///
2275     /// fn main() -> io::Result<()> {
2276     ///     let mut file = File::open("foo.txt")?;
2277     ///
2278     ///     let mut buffer = [0; 5];
2279     ///     let mut handle = file.take(5);
2280     ///     handle.read(&mut buffer)?;
2281     ///
2282     ///     let file = handle.into_inner();
2283     ///     Ok(())
2284     /// }
2285     /// ```
2286     #[stable(feature = "io_take_into_inner", since = "1.15.0")]
2287     pub fn into_inner(self) -> T {
2288         self.inner
2289     }
2290
2291     /// Gets a reference to the underlying reader.
2292     ///
2293     /// # Examples
2294     ///
2295     /// ```no_run
2296     /// use std::io;
2297     /// use std::io::prelude::*;
2298     /// use std::fs::File;
2299     ///
2300     /// fn main() -> io::Result<()> {
2301     ///     let mut file = File::open("foo.txt")?;
2302     ///
2303     ///     let mut buffer = [0; 5];
2304     ///     let mut handle = file.take(5);
2305     ///     handle.read(&mut buffer)?;
2306     ///
2307     ///     let file = handle.get_ref();
2308     ///     Ok(())
2309     /// }
2310     /// ```
2311     #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2312     pub fn get_ref(&self) -> &T {
2313         &self.inner
2314     }
2315
2316     /// Gets a mutable reference to the underlying reader.
2317     ///
2318     /// Care should be taken to avoid modifying the internal I/O state of the
2319     /// underlying reader as doing so may corrupt the internal limit of this
2320     /// `Take`.
2321     ///
2322     /// # Examples
2323     ///
2324     /// ```no_run
2325     /// use std::io;
2326     /// use std::io::prelude::*;
2327     /// use std::fs::File;
2328     ///
2329     /// fn main() -> io::Result<()> {
2330     ///     let mut file = File::open("foo.txt")?;
2331     ///
2332     ///     let mut buffer = [0; 5];
2333     ///     let mut handle = file.take(5);
2334     ///     handle.read(&mut buffer)?;
2335     ///
2336     ///     let file = handle.get_mut();
2337     ///     Ok(())
2338     /// }
2339     /// ```
2340     #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2341     pub fn get_mut(&mut self) -> &mut T {
2342         &mut self.inner
2343     }
2344 }
2345
2346 #[stable(feature = "rust1", since = "1.0.0")]
2347 impl<T: Read> Read for Take<T> {
2348     fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
2349         // Don't call into inner reader at all at EOF because it may still block
2350         if self.limit == 0 {
2351             return Ok(0);
2352         }
2353
2354         let max = cmp::min(buf.len() as u64, self.limit) as usize;
2355         let n = self.inner.read(&mut buf[..max])?;
2356         self.limit -= n as u64;
2357         Ok(n)
2358     }
2359
2360     unsafe fn initializer(&self) -> Initializer {
2361         self.inner.initializer()
2362     }
2363
2364     fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
2365         // Pass in a reservation_size closure that respects the current value
2366         // of limit for each read. If we hit the read limit, this prevents the
2367         // final zero-byte read from allocating again.
2368         read_to_end_with_reservation(self, buf, |self_| cmp::min(self_.limit, 32) as usize)
2369     }
2370 }
2371
2372 #[stable(feature = "rust1", since = "1.0.0")]
2373 impl<T: BufRead> BufRead for Take<T> {
2374     fn fill_buf(&mut self) -> Result<&[u8]> {
2375         // Don't call into inner reader at all at EOF because it may still block
2376         if self.limit == 0 {
2377             return Ok(&[]);
2378         }
2379
2380         let buf = self.inner.fill_buf()?;
2381         let cap = cmp::min(buf.len() as u64, self.limit) as usize;
2382         Ok(&buf[..cap])
2383     }
2384
2385     fn consume(&mut self, amt: usize) {
2386         // Don't let callers reset the limit by passing an overlarge value
2387         let amt = cmp::min(amt as u64, self.limit) as usize;
2388         self.limit -= amt as u64;
2389         self.inner.consume(amt);
2390     }
2391 }
2392
2393 /// An iterator over `u8` values of a reader.
2394 ///
2395 /// This struct is generally created by calling [`bytes`] on a reader.
2396 /// Please see the documentation of [`bytes`] for more details.
2397 ///
2398 /// [`bytes`]: Read::bytes
2399 #[stable(feature = "rust1", since = "1.0.0")]
2400 #[derive(Debug)]
2401 pub struct Bytes<R> {
2402     inner: R,
2403 }
2404
2405 #[stable(feature = "rust1", since = "1.0.0")]
2406 impl<R: Read> Iterator for Bytes<R> {
2407     type Item = Result<u8>;
2408
2409     fn next(&mut self) -> Option<Result<u8>> {
2410         let mut byte = 0;
2411         loop {
2412             return match self.inner.read(slice::from_mut(&mut byte)) {
2413                 Ok(0) => None,
2414                 Ok(..) => Some(Ok(byte)),
2415                 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
2416                 Err(e) => Some(Err(e)),
2417             };
2418         }
2419     }
2420 }
2421
2422 /// An iterator over the contents of an instance of `BufRead` split on a
2423 /// particular byte.
2424 ///
2425 /// This struct is generally created by calling [`split`] on a `BufRead`.
2426 /// Please see the documentation of [`split`] for more details.
2427 ///
2428 /// [`split`]: BufRead::split
2429 #[stable(feature = "rust1", since = "1.0.0")]
2430 #[derive(Debug)]
2431 pub struct Split<B> {
2432     buf: B,
2433     delim: u8,
2434 }
2435
2436 #[stable(feature = "rust1", since = "1.0.0")]
2437 impl<B: BufRead> Iterator for Split<B> {
2438     type Item = Result<Vec<u8>>;
2439
2440     fn next(&mut self) -> Option<Result<Vec<u8>>> {
2441         let mut buf = Vec::new();
2442         match self.buf.read_until(self.delim, &mut buf) {
2443             Ok(0) => None,
2444             Ok(_n) => {
2445                 if buf[buf.len() - 1] == self.delim {
2446                     buf.pop();
2447                 }
2448                 Some(Ok(buf))
2449             }
2450             Err(e) => Some(Err(e)),
2451         }
2452     }
2453 }
2454
2455 /// An iterator over the lines of an instance of `BufRead`.
2456 ///
2457 /// This struct is generally created by calling [`lines`] on a `BufRead`.
2458 /// Please see the documentation of [`lines`] for more details.
2459 ///
2460 /// [`lines`]: BufRead::lines
2461 #[stable(feature = "rust1", since = "1.0.0")]
2462 #[derive(Debug)]
2463 pub struct Lines<B> {
2464     buf: B,
2465 }
2466
2467 #[stable(feature = "rust1", since = "1.0.0")]
2468 impl<B: BufRead> Iterator for Lines<B> {
2469     type Item = Result<String>;
2470
2471     fn next(&mut self) -> Option<Result<String>> {
2472         let mut buf = String::new();
2473         match self.buf.read_line(&mut buf) {
2474             Ok(0) => None,
2475             Ok(_n) => {
2476                 if buf.ends_with('\n') {
2477                     buf.pop();
2478                     if buf.ends_with('\r') {
2479                         buf.pop();
2480                     }
2481                 }
2482                 Some(Ok(buf))
2483             }
2484             Err(e) => Some(Err(e)),
2485         }
2486     }
2487 }