]> git.lizzy.rs Git - rust.git/blob - library/std/src/io/mod.rs
Auto merge of #91962 - matthiaskrgr:rollup-2g082jw, r=matthiaskrgr
[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 //! [`io::stdout`]: stdout
244 //! [`io::Result`]: self::Result
245 //! [`?` operator]: ../../book/appendix-02-operators.html
246 //! [`Result`]: crate::result::Result
247 //! [`.unwrap()`]: crate::result::Result::unwrap
248
249 #![stable(feature = "rust1", since = "1.0.0")]
250
251 #[cfg(test)]
252 mod tests;
253
254 use crate::cmp;
255 use crate::convert::TryInto;
256 use crate::fmt;
257 use crate::mem::replace;
258 use crate::ops::{Deref, DerefMut};
259 use crate::slice;
260 use crate::str;
261 use crate::sys;
262 use crate::sys_common::memchr;
263
264 #[stable(feature = "rust1", since = "1.0.0")]
265 pub use self::buffered::IntoInnerError;
266 #[stable(feature = "bufwriter_into_parts", since = "1.56.0")]
267 pub use self::buffered::WriterPanicked;
268 #[stable(feature = "rust1", since = "1.0.0")]
269 pub use self::buffered::{BufReader, BufWriter, LineWriter};
270 #[stable(feature = "rust1", since = "1.0.0")]
271 pub use self::copy::copy;
272 #[stable(feature = "rust1", since = "1.0.0")]
273 pub use self::cursor::Cursor;
274 #[stable(feature = "rust1", since = "1.0.0")]
275 pub use self::error::{Error, ErrorKind, Result};
276 #[unstable(feature = "internal_output_capture", issue = "none")]
277 #[doc(no_inline, hidden)]
278 pub use self::stdio::set_output_capture;
279 #[stable(feature = "rust1", since = "1.0.0")]
280 pub use self::stdio::{stderr, stdin, stdout, Stderr, Stdin, Stdout};
281 #[unstable(feature = "stdio_locked", issue = "86845")]
282 pub use self::stdio::{stderr_locked, stdin_locked, stdout_locked};
283 #[stable(feature = "rust1", since = "1.0.0")]
284 pub use self::stdio::{StderrLock, StdinLock, StdoutLock};
285 #[unstable(feature = "print_internals", issue = "none")]
286 pub use self::stdio::{_eprint, _print};
287 #[stable(feature = "rust1", since = "1.0.0")]
288 pub use self::util::{empty, repeat, sink, Empty, Repeat, Sink};
289
290 #[unstable(feature = "read_buf", issue = "78485")]
291 pub use self::readbuf::ReadBuf;
292
293 mod buffered;
294 pub(crate) mod copy;
295 mod cursor;
296 mod error;
297 mod impls;
298 pub mod prelude;
299 mod readbuf;
300 mod stdio;
301 mod util;
302
303 const DEFAULT_BUF_SIZE: usize = crate::sys_common::io::DEFAULT_BUF_SIZE;
304
305 pub(crate) use stdio::cleanup;
306
307 struct Guard<'a> {
308     buf: &'a mut Vec<u8>,
309     len: usize,
310 }
311
312 impl Drop for Guard<'_> {
313     fn drop(&mut self) {
314         unsafe {
315             self.buf.set_len(self.len);
316         }
317     }
318 }
319
320 // Several `read_to_string` and `read_line` methods in the standard library will
321 // append data into a `String` buffer, but we need to be pretty careful when
322 // doing this. The implementation will just call `.as_mut_vec()` and then
323 // delegate to a byte-oriented reading method, but we must ensure that when
324 // returning we never leave `buf` in a state such that it contains invalid UTF-8
325 // in its bounds.
326 //
327 // To this end, we use an RAII guard (to protect against panics) which updates
328 // the length of the string when it is dropped. This guard initially truncates
329 // the string to the prior length and only after we've validated that the
330 // new contents are valid UTF-8 do we allow it to set a longer length.
331 //
332 // The unsafety in this function is twofold:
333 //
334 // 1. We're looking at the raw bytes of `buf`, so we take on the burden of UTF-8
335 //    checks.
336 // 2. We're passing a raw buffer to the function `f`, and it is expected that
337 //    the function only *appends* bytes to the buffer. We'll get undefined
338 //    behavior if existing bytes are overwritten to have non-UTF-8 data.
339 pub(crate) unsafe fn append_to_string<F>(buf: &mut String, f: F) -> Result<usize>
340 where
341     F: FnOnce(&mut Vec<u8>) -> Result<usize>,
342 {
343     let mut g = Guard { len: buf.len(), buf: buf.as_mut_vec() };
344     let ret = f(g.buf);
345     if str::from_utf8(&g.buf[g.len..]).is_err() {
346         ret.and_then(|_| {
347             Err(Error::new_const(ErrorKind::InvalidData, &"stream did not contain valid UTF-8"))
348         })
349     } else {
350         g.len = g.buf.len();
351         ret
352     }
353 }
354
355 // This uses an adaptive system to extend the vector when it fills. We want to
356 // avoid paying to allocate and zero a huge chunk of memory if the reader only
357 // has 4 bytes while still making large reads if the reader does have a ton
358 // of data to return. Simply tacking on an extra DEFAULT_BUF_SIZE space every
359 // time is 4,500 times (!) slower than a default reservation size of 32 if the
360 // reader has a very small amount of data to return.
361 pub(crate) fn default_read_to_end<R: Read + ?Sized>(r: &mut R, buf: &mut Vec<u8>) -> Result<usize> {
362     let start_len = buf.len();
363     let start_cap = buf.capacity();
364
365     let mut initialized = 0; // Extra initialized bytes from previous loop iteration
366     loop {
367         if buf.len() == buf.capacity() {
368             buf.reserve(32); // buf is full, need more space
369         }
370
371         let mut read_buf = ReadBuf::uninit(buf.spare_capacity_mut());
372
373         // SAFETY: These bytes were initialized but not filled in the previous loop
374         unsafe {
375             read_buf.assume_init(initialized);
376         }
377
378         match r.read_buf(&mut read_buf) {
379             Ok(()) => {}
380             Err(e) if e.kind() == ErrorKind::Interrupted => continue,
381             Err(e) => return Err(e),
382         }
383
384         if read_buf.filled_len() == 0 {
385             return Ok(buf.len() - start_len);
386         }
387
388         // store how much was initialized but not filled
389         initialized = read_buf.initialized_len() - read_buf.filled_len();
390         let new_len = read_buf.filled_len() + buf.len();
391
392         // SAFETY: ReadBuf's invariants mean this much memory is init
393         unsafe {
394             buf.set_len(new_len);
395         }
396
397         if buf.len() == buf.capacity() && buf.capacity() == start_cap {
398             // The buffer might be an exact fit. Let's read into a probe buffer
399             // and see if it returns `Ok(0)`. If so, we've avoided an
400             // unnecessary doubling of the capacity. But if not, append the
401             // probe buffer to the primary buffer and let its capacity grow.
402             let mut probe = [0u8; 32];
403
404             loop {
405                 match r.read(&mut probe) {
406                     Ok(0) => return Ok(buf.len() - start_len),
407                     Ok(n) => {
408                         buf.extend_from_slice(&probe[..n]);
409                         break;
410                     }
411                     Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
412                     Err(e) => return Err(e),
413                 }
414             }
415         }
416     }
417 }
418
419 pub(crate) fn default_read_to_string<R: Read + ?Sized>(
420     r: &mut R,
421     buf: &mut String,
422 ) -> Result<usize> {
423     // Note that we do *not* call `r.read_to_end()` here. We are passing
424     // `&mut Vec<u8>` (the raw contents of `buf`) into the `read_to_end`
425     // method to fill it up. An arbitrary implementation could overwrite the
426     // entire contents of the vector, not just append to it (which is what
427     // we are expecting).
428     //
429     // To prevent extraneously checking the UTF-8-ness of the entire buffer
430     // we pass it to our hardcoded `default_read_to_end` implementation which
431     // we know is guaranteed to only read data into the end of the buffer.
432     unsafe { append_to_string(buf, |b| default_read_to_end(r, b)) }
433 }
434
435 pub(crate) fn default_read_vectored<F>(read: F, bufs: &mut [IoSliceMut<'_>]) -> Result<usize>
436 where
437     F: FnOnce(&mut [u8]) -> Result<usize>,
438 {
439     let buf = bufs.iter_mut().find(|b| !b.is_empty()).map_or(&mut [][..], |b| &mut **b);
440     read(buf)
441 }
442
443 pub(crate) fn default_write_vectored<F>(write: F, bufs: &[IoSlice<'_>]) -> Result<usize>
444 where
445     F: FnOnce(&[u8]) -> Result<usize>,
446 {
447     let buf = bufs.iter().find(|b| !b.is_empty()).map_or(&[][..], |b| &**b);
448     write(buf)
449 }
450
451 pub(crate) fn default_read_exact<R: Read + ?Sized>(this: &mut R, mut buf: &mut [u8]) -> Result<()> {
452     while !buf.is_empty() {
453         match this.read(buf) {
454             Ok(0) => break,
455             Ok(n) => {
456                 let tmp = buf;
457                 buf = &mut tmp[n..];
458             }
459             Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
460             Err(e) => return Err(e),
461         }
462     }
463     if !buf.is_empty() {
464         Err(Error::new_const(ErrorKind::UnexpectedEof, &"failed to fill whole buffer"))
465     } else {
466         Ok(())
467     }
468 }
469
470 pub(crate) fn default_read_buf<F>(read: F, buf: &mut ReadBuf<'_>) -> Result<()>
471 where
472     F: FnOnce(&mut [u8]) -> Result<usize>,
473 {
474     let n = read(buf.initialize_unfilled())?;
475     buf.add_filled(n);
476     Ok(())
477 }
478
479 /// The `Read` trait allows for reading bytes from a source.
480 ///
481 /// Implementors of the `Read` trait are called 'readers'.
482 ///
483 /// Readers are defined by one required method, [`read()`]. Each call to [`read()`]
484 /// will attempt to pull bytes from this source into a provided buffer. A
485 /// number of other methods are implemented in terms of [`read()`], giving
486 /// implementors a number of ways to read bytes while only needing to implement
487 /// a single method.
488 ///
489 /// Readers are intended to be composable with one another. Many implementors
490 /// throughout [`std::io`] take and provide types which implement the `Read`
491 /// trait.
492 ///
493 /// Please note that each call to [`read()`] may involve a system call, and
494 /// therefore, using something that implements [`BufRead`], such as
495 /// [`BufReader`], will be more efficient.
496 ///
497 /// # Examples
498 ///
499 /// [`File`]s implement `Read`:
500 ///
501 /// ```no_run
502 /// use std::io;
503 /// use std::io::prelude::*;
504 /// use std::fs::File;
505 ///
506 /// fn main() -> io::Result<()> {
507 ///     let mut f = File::open("foo.txt")?;
508 ///     let mut buffer = [0; 10];
509 ///
510 ///     // read up to 10 bytes
511 ///     f.read(&mut buffer)?;
512 ///
513 ///     let mut buffer = Vec::new();
514 ///     // read the whole file
515 ///     f.read_to_end(&mut buffer)?;
516 ///
517 ///     // read into a String, so that you don't need to do the conversion.
518 ///     let mut buffer = String::new();
519 ///     f.read_to_string(&mut buffer)?;
520 ///
521 ///     // and more! See the other methods for more details.
522 ///     Ok(())
523 /// }
524 /// ```
525 ///
526 /// Read from [`&str`] because [`&[u8]`][prim@slice] implements `Read`:
527 ///
528 /// ```no_run
529 /// # use std::io;
530 /// use std::io::prelude::*;
531 ///
532 /// fn main() -> io::Result<()> {
533 ///     let mut b = "This string will be read".as_bytes();
534 ///     let mut buffer = [0; 10];
535 ///
536 ///     // read up to 10 bytes
537 ///     b.read(&mut buffer)?;
538 ///
539 ///     // etc... it works exactly as a File does!
540 ///     Ok(())
541 /// }
542 /// ```
543 ///
544 /// [`read()`]: Read::read
545 /// [`&str`]: prim@str
546 /// [`std::io`]: self
547 /// [`File`]: crate::fs::File
548 #[stable(feature = "rust1", since = "1.0.0")]
549 #[doc(notable_trait)]
550 #[cfg_attr(not(test), rustc_diagnostic_item = "IoRead")]
551 pub trait Read {
552     /// Pull some bytes from this source into the specified buffer, returning
553     /// how many bytes were read.
554     ///
555     /// This function does not provide any guarantees about whether it blocks
556     /// waiting for data, but if an object needs to block for a read and cannot,
557     /// it will typically signal this via an [`Err`] return value.
558     ///
559     /// If the return value of this method is [`Ok(n)`], then implementations must
560     /// guarantee that `0 <= n <= buf.len()`. A nonzero `n` value indicates
561     /// that the buffer `buf` has been filled in with `n` bytes of data from this
562     /// source. If `n` is `0`, then it can indicate one of two scenarios:
563     ///
564     /// 1. This reader has reached its "end of file" and will likely no longer
565     ///    be able to produce bytes. Note that this does not mean that the
566     ///    reader will *always* no longer be able to produce bytes. As an example,
567     ///    on Linux, this method will call the `recv` syscall for a [`TcpStream`],
568     ///    where returning zero indicates the connection was shut down correctly. While
569     ///    for [`File`], it is possible to reach the end of file and get zero as result,
570     ///    but if more data is appended to the file, future calls to `read` will return
571     ///    more data.
572     /// 2. The buffer specified was 0 bytes in length.
573     ///
574     /// It is not an error if the returned value `n` is smaller than the buffer size,
575     /// even when the reader is not at the end of the stream yet.
576     /// This may happen for example because fewer bytes are actually available right now
577     /// (e. g. being close to end-of-file) or because read() was interrupted by a signal.
578     ///
579     /// As this trait is safe to implement, callers cannot rely on `n <= buf.len()` for safety.
580     /// Extra care needs to be taken when `unsafe` functions are used to access the read bytes.
581     /// Callers have to ensure that no unchecked out-of-bounds accesses are possible even if
582     /// `n > buf.len()`.
583     ///
584     /// No guarantees are provided about the contents of `buf` when this
585     /// function is called, implementations cannot rely on any property of the
586     /// contents of `buf` being true. It is recommended that *implementations*
587     /// only write data to `buf` instead of reading its contents.
588     ///
589     /// Correspondingly, however, *callers* of this method must not assume any guarantees
590     /// about how the implementation uses `buf`. The trait is safe to implement,
591     /// so it is possible that the code that's supposed to write to the buffer might also read
592     /// from it. It is your responsibility to make sure that `buf` is initialized
593     /// before calling `read`. Calling `read` with an uninitialized `buf` (of the kind one
594     /// obtains via [`MaybeUninit<T>`]) is not safe, and can lead to undefined behavior.
595     ///
596     /// [`MaybeUninit<T>`]: crate::mem::MaybeUninit
597     ///
598     /// # Errors
599     ///
600     /// If this function encounters any form of I/O or other error, an error
601     /// variant will be returned. If an error is returned then it must be
602     /// guaranteed that no bytes were read.
603     ///
604     /// An error of the [`ErrorKind::Interrupted`] kind is non-fatal and the read
605     /// operation should be retried if there is nothing else to do.
606     ///
607     /// # Examples
608     ///
609     /// [`File`]s implement `Read`:
610     ///
611     /// [`Ok(n)`]: Ok
612     /// [`File`]: crate::fs::File
613     /// [`TcpStream`]: crate::net::TcpStream
614     ///
615     /// ```no_run
616     /// use std::io;
617     /// use std::io::prelude::*;
618     /// use std::fs::File;
619     ///
620     /// fn main() -> io::Result<()> {
621     ///     let mut f = File::open("foo.txt")?;
622     ///     let mut buffer = [0; 10];
623     ///
624     ///     // read up to 10 bytes
625     ///     let n = f.read(&mut buffer[..])?;
626     ///
627     ///     println!("The bytes: {:?}", &buffer[..n]);
628     ///     Ok(())
629     /// }
630     /// ```
631     #[stable(feature = "rust1", since = "1.0.0")]
632     fn read(&mut self, buf: &mut [u8]) -> Result<usize>;
633
634     /// Like `read`, except that it reads into a slice of buffers.
635     ///
636     /// Data is copied to fill each buffer in order, with the final buffer
637     /// written to possibly being only partially filled. This method must
638     /// behave equivalently to a single call to `read` with concatenated
639     /// buffers.
640     ///
641     /// The default implementation calls `read` with either the first nonempty
642     /// buffer provided, or an empty one if none exists.
643     #[stable(feature = "iovec", since = "1.36.0")]
644     fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize> {
645         default_read_vectored(|b| self.read(b), bufs)
646     }
647
648     /// Determines if this `Read`er has an efficient `read_vectored`
649     /// implementation.
650     ///
651     /// If a `Read`er does not override the default `read_vectored`
652     /// implementation, code using it may want to avoid the method all together
653     /// and coalesce writes into a single buffer for higher performance.
654     ///
655     /// The default implementation returns `false`.
656     #[unstable(feature = "can_vector", issue = "69941")]
657     fn is_read_vectored(&self) -> bool {
658         false
659     }
660
661     /// Read all bytes until EOF in this source, placing them into `buf`.
662     ///
663     /// All bytes read from this source will be appended to the specified buffer
664     /// `buf`. This function will continuously call [`read()`] to append more data to
665     /// `buf` until [`read()`] returns either [`Ok(0)`] or an error of
666     /// non-[`ErrorKind::Interrupted`] kind.
667     ///
668     /// If successful, this function will return the total number of bytes read.
669     ///
670     /// # Errors
671     ///
672     /// If this function encounters an error of the kind
673     /// [`ErrorKind::Interrupted`] then the error is ignored and the operation
674     /// will continue.
675     ///
676     /// If any other read error is encountered then this function immediately
677     /// returns. Any bytes which have already been read will be appended to
678     /// `buf`.
679     ///
680     /// # Examples
681     ///
682     /// [`File`]s implement `Read`:
683     ///
684     /// [`read()`]: Read::read
685     /// [`Ok(0)`]: Ok
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 = Vec::new();
696     ///
697     ///     // read the whole file
698     ///     f.read_to_end(&mut buffer)?;
699     ///     Ok(())
700     /// }
701     /// ```
702     ///
703     /// (See also the [`std::fs::read`] convenience function for reading from a
704     /// file.)
705     ///
706     /// [`std::fs::read`]: crate::fs::read
707     #[stable(feature = "rust1", since = "1.0.0")]
708     fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
709         default_read_to_end(self, buf)
710     }
711
712     /// Read all bytes until EOF in this source, appending them to `buf`.
713     ///
714     /// If successful, this function returns the number of bytes which were read
715     /// and appended to `buf`.
716     ///
717     /// # Errors
718     ///
719     /// If the data in this stream is *not* valid UTF-8 then an error is
720     /// returned and `buf` is unchanged.
721     ///
722     /// See [`read_to_end`] for other error semantics.
723     ///
724     /// [`read_to_end`]: Read::read_to_end
725     ///
726     /// # Examples
727     ///
728     /// [`File`]s implement `Read`:
729     ///
730     /// [`File`]: crate::fs::File
731     ///
732     /// ```no_run
733     /// use std::io;
734     /// use std::io::prelude::*;
735     /// use std::fs::File;
736     ///
737     /// fn main() -> io::Result<()> {
738     ///     let mut f = File::open("foo.txt")?;
739     ///     let mut buffer = String::new();
740     ///
741     ///     f.read_to_string(&mut buffer)?;
742     ///     Ok(())
743     /// }
744     /// ```
745     ///
746     /// (See also the [`std::fs::read_to_string`] convenience function for
747     /// reading from a file.)
748     ///
749     /// [`std::fs::read_to_string`]: crate::fs::read_to_string
750     #[stable(feature = "rust1", since = "1.0.0")]
751     fn read_to_string(&mut self, buf: &mut String) -> Result<usize> {
752         default_read_to_string(self, buf)
753     }
754
755     /// Read the exact number of bytes required to fill `buf`.
756     ///
757     /// This function reads as many bytes as necessary to completely fill the
758     /// specified buffer `buf`.
759     ///
760     /// No guarantees are provided about the contents of `buf` when this
761     /// function is called, implementations cannot rely on any property of the
762     /// contents of `buf` being true. It is recommended that implementations
763     /// only write data to `buf` instead of reading its contents. The
764     /// documentation on [`read`] has a more detailed explanation on this
765     /// subject.
766     ///
767     /// # Errors
768     ///
769     /// If this function encounters an error of the kind
770     /// [`ErrorKind::Interrupted`] then the error is ignored and the operation
771     /// will continue.
772     ///
773     /// If this function encounters an "end of file" before completely filling
774     /// the buffer, it returns an error of the kind [`ErrorKind::UnexpectedEof`].
775     /// The contents of `buf` are unspecified in this case.
776     ///
777     /// If any other read error is encountered then this function immediately
778     /// returns. The contents of `buf` are unspecified in this case.
779     ///
780     /// If this function returns an error, it is unspecified how many bytes it
781     /// has read, but it will never read more than would be necessary to
782     /// completely fill the buffer.
783     ///
784     /// # Examples
785     ///
786     /// [`File`]s implement `Read`:
787     ///
788     /// [`read`]: Read::read
789     /// [`File`]: crate::fs::File
790     ///
791     /// ```no_run
792     /// use std::io;
793     /// use std::io::prelude::*;
794     /// use std::fs::File;
795     ///
796     /// fn main() -> io::Result<()> {
797     ///     let mut f = File::open("foo.txt")?;
798     ///     let mut buffer = [0; 10];
799     ///
800     ///     // read exactly 10 bytes
801     ///     f.read_exact(&mut buffer)?;
802     ///     Ok(())
803     /// }
804     /// ```
805     #[stable(feature = "read_exact", since = "1.6.0")]
806     fn read_exact(&mut self, buf: &mut [u8]) -> Result<()> {
807         default_read_exact(self, buf)
808     }
809
810     /// Pull some bytes from this source into the specified buffer.
811     ///
812     /// This is equivalent to the [`read`](Read::read) method, except that it is passed a [`ReadBuf`] rather than `[u8]` to allow use
813     /// with uninitialized buffers. The new data will be appended to any existing contents of `buf`.
814     ///
815     /// The default implementation delegates to `read`.
816     #[unstable(feature = "read_buf", issue = "78485")]
817     fn read_buf(&mut self, buf: &mut ReadBuf<'_>) -> Result<()> {
818         default_read_buf(|b| self.read(b), buf)
819     }
820
821     /// Read the exact number of bytes required to fill `buf`.
822     ///
823     /// This is equivalent to the [`read_exact`](Read::read_exact) method, except that it is passed a [`ReadBuf`] rather than `[u8]` to
824     /// allow use with uninitialized buffers.
825     #[unstable(feature = "read_buf", issue = "78485")]
826     fn read_buf_exact(&mut self, buf: &mut ReadBuf<'_>) -> Result<()> {
827         while buf.remaining() > 0 {
828             let prev_filled = buf.filled().len();
829             match self.read_buf(buf) {
830                 Ok(()) => {}
831                 Err(e) if e.kind() == ErrorKind::Interrupted => continue,
832                 Err(e) => return Err(e),
833             }
834
835             if buf.filled().len() == prev_filled {
836                 return Err(Error::new(ErrorKind::UnexpectedEof, "failed to fill buffer"));
837             }
838         }
839
840         Ok(())
841     }
842
843     /// Creates a "by reference" adaptor for this instance of `Read`.
844     ///
845     /// The returned adapter also implements `Read` and will simply borrow this
846     /// current reader.
847     ///
848     /// # Examples
849     ///
850     /// [`File`]s implement `Read`:
851     ///
852     /// [`File`]: crate::fs::File
853     ///
854     /// ```no_run
855     /// use std::io;
856     /// use std::io::Read;
857     /// use std::fs::File;
858     ///
859     /// fn main() -> io::Result<()> {
860     ///     let mut f = File::open("foo.txt")?;
861     ///     let mut buffer = Vec::new();
862     ///     let mut other_buffer = Vec::new();
863     ///
864     ///     {
865     ///         let reference = f.by_ref();
866     ///
867     ///         // read at most 5 bytes
868     ///         reference.take(5).read_to_end(&mut buffer)?;
869     ///
870     ///     } // drop our &mut reference so we can use f again
871     ///
872     ///     // original file still usable, read the rest
873     ///     f.read_to_end(&mut other_buffer)?;
874     ///     Ok(())
875     /// }
876     /// ```
877     #[stable(feature = "rust1", since = "1.0.0")]
878     fn by_ref(&mut self) -> &mut Self
879     where
880         Self: Sized,
881     {
882         self
883     }
884
885     /// Transforms this `Read` instance to an [`Iterator`] over its bytes.
886     ///
887     /// The returned type implements [`Iterator`] where the [`Item`] is
888     /// <code>[Result]<[u8], [io::Error]></code>.
889     /// The yielded item is [`Ok`] if a byte was successfully read and [`Err`]
890     /// otherwise. EOF is mapped to returning [`None`] from this iterator.
891     ///
892     /// # Examples
893     ///
894     /// [`File`]s implement `Read`:
895     ///
896     /// [`Item`]: Iterator::Item
897     /// [`File`]: crate::fs::File "fs::File"
898     /// [Result]: crate::result::Result "Result"
899     /// [io::Error]: self::Error "io::Error"
900     ///
901     /// ```no_run
902     /// use std::io;
903     /// use std::io::prelude::*;
904     /// use std::fs::File;
905     ///
906     /// fn main() -> io::Result<()> {
907     ///     let mut f = File::open("foo.txt")?;
908     ///
909     ///     for byte in f.bytes() {
910     ///         println!("{}", byte.unwrap());
911     ///     }
912     ///     Ok(())
913     /// }
914     /// ```
915     #[stable(feature = "rust1", since = "1.0.0")]
916     fn bytes(self) -> Bytes<Self>
917     where
918         Self: Sized,
919     {
920         Bytes { inner: self }
921     }
922
923     /// Creates an adapter which will chain this stream with another.
924     ///
925     /// The returned `Read` instance will first read all bytes from this object
926     /// until EOF is encountered. Afterwards the output is equivalent to the
927     /// output of `next`.
928     ///
929     /// # Examples
930     ///
931     /// [`File`]s implement `Read`:
932     ///
933     /// [`File`]: crate::fs::File
934     ///
935     /// ```no_run
936     /// use std::io;
937     /// use std::io::prelude::*;
938     /// use std::fs::File;
939     ///
940     /// fn main() -> io::Result<()> {
941     ///     let mut f1 = File::open("foo.txt")?;
942     ///     let mut f2 = File::open("bar.txt")?;
943     ///
944     ///     let mut handle = f1.chain(f2);
945     ///     let mut buffer = String::new();
946     ///
947     ///     // read the value into a String. We could use any Read method here,
948     ///     // this is just one example.
949     ///     handle.read_to_string(&mut buffer)?;
950     ///     Ok(())
951     /// }
952     /// ```
953     #[stable(feature = "rust1", since = "1.0.0")]
954     fn chain<R: Read>(self, next: R) -> Chain<Self, R>
955     where
956         Self: Sized,
957     {
958         Chain { first: self, second: next, done_first: false }
959     }
960
961     /// Creates an adapter which will read at most `limit` bytes from it.
962     ///
963     /// This function returns a new instance of `Read` which will read at most
964     /// `limit` bytes, after which it will always return EOF ([`Ok(0)`]). Any
965     /// read errors will not count towards the number of bytes read and future
966     /// calls to [`read()`] may succeed.
967     ///
968     /// # Examples
969     ///
970     /// [`File`]s implement `Read`:
971     ///
972     /// [`File`]: crate::fs::File
973     /// [`Ok(0)`]: Ok
974     /// [`read()`]: Read::read
975     ///
976     /// ```no_run
977     /// use std::io;
978     /// use std::io::prelude::*;
979     /// use std::fs::File;
980     ///
981     /// fn main() -> io::Result<()> {
982     ///     let mut f = File::open("foo.txt")?;
983     ///     let mut buffer = [0; 5];
984     ///
985     ///     // read at most five bytes
986     ///     let mut handle = f.take(5);
987     ///
988     ///     handle.read(&mut buffer)?;
989     ///     Ok(())
990     /// }
991     /// ```
992     #[stable(feature = "rust1", since = "1.0.0")]
993     fn take(self, limit: u64) -> Take<Self>
994     where
995         Self: Sized,
996     {
997         Take { inner: self, limit }
998     }
999 }
1000
1001 /// Read all bytes from a [reader][Read] into a new [`String`].
1002 ///
1003 /// This is a convenience function for [`Read::read_to_string`]. Using this
1004 /// function avoids having to create a variable first and provides more type
1005 /// safety since you can only get the buffer out if there were no errors. (If you
1006 /// use [`Read::read_to_string`] you have to remember to check whether the read
1007 /// succeeded because otherwise your buffer will be empty or only partially full.)
1008 ///
1009 /// # Performance
1010 ///
1011 /// The downside of this function's increased ease of use and type safety is
1012 /// that it gives you less control over performance. For example, you can't
1013 /// pre-allocate memory like you can using [`String::with_capacity`] and
1014 /// [`Read::read_to_string`]. Also, you can't re-use the buffer if an error
1015 /// occurs while reading.
1016 ///
1017 /// In many cases, this function's performance will be adequate and the ease of use
1018 /// and type safety tradeoffs will be worth it. However, there are cases where you
1019 /// need more control over performance, and in those cases you should definitely use
1020 /// [`Read::read_to_string`] directly.
1021 ///
1022 /// Note that in some special cases, such as when reading files, this function will
1023 /// pre-allocate memory based on the size of the input it is reading. In those
1024 /// cases, the performance should be as good as if you had used
1025 /// [`Read::read_to_string`] with a manually pre-allocated buffer.
1026 ///
1027 /// # Errors
1028 ///
1029 /// This function forces you to handle errors because the output (the `String`)
1030 /// is wrapped in a [`Result`]. See [`Read::read_to_string`] for the errors
1031 /// that can occur. If any error occurs, you will get an [`Err`], so you
1032 /// don't have to worry about your buffer being empty or partially full.
1033 ///
1034 /// # Examples
1035 ///
1036 /// ```no_run
1037 /// #![feature(io_read_to_string)]
1038 ///
1039 /// # use std::io;
1040 /// fn main() -> io::Result<()> {
1041 ///     let stdin = io::read_to_string(&mut io::stdin())?;
1042 ///     println!("Stdin was:");
1043 ///     println!("{}", stdin);
1044 ///     Ok(())
1045 /// }
1046 /// ```
1047 #[unstable(feature = "io_read_to_string", issue = "80218")]
1048 pub fn read_to_string<R: Read>(reader: &mut R) -> Result<String> {
1049     let mut buf = String::new();
1050     reader.read_to_string(&mut buf)?;
1051     Ok(buf)
1052 }
1053
1054 /// A buffer type used with `Read::read_vectored`.
1055 ///
1056 /// It is semantically a wrapper around an `&mut [u8]`, but is guaranteed to be
1057 /// ABI compatible with the `iovec` type on Unix platforms and `WSABUF` on
1058 /// Windows.
1059 #[stable(feature = "iovec", since = "1.36.0")]
1060 #[repr(transparent)]
1061 pub struct IoSliceMut<'a>(sys::io::IoSliceMut<'a>);
1062
1063 #[stable(feature = "iovec-send-sync", since = "1.44.0")]
1064 unsafe impl<'a> Send for IoSliceMut<'a> {}
1065
1066 #[stable(feature = "iovec-send-sync", since = "1.44.0")]
1067 unsafe impl<'a> Sync for IoSliceMut<'a> {}
1068
1069 #[stable(feature = "iovec", since = "1.36.0")]
1070 impl<'a> fmt::Debug for IoSliceMut<'a> {
1071     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1072         fmt::Debug::fmt(self.0.as_slice(), fmt)
1073     }
1074 }
1075
1076 impl<'a> IoSliceMut<'a> {
1077     /// Creates a new `IoSliceMut` wrapping a byte slice.
1078     ///
1079     /// # Panics
1080     ///
1081     /// Panics on Windows if the slice is larger than 4GB.
1082     #[stable(feature = "iovec", since = "1.36.0")]
1083     #[inline]
1084     pub fn new(buf: &'a mut [u8]) -> IoSliceMut<'a> {
1085         IoSliceMut(sys::io::IoSliceMut::new(buf))
1086     }
1087
1088     /// Advance the internal cursor of the slice.
1089     ///
1090     /// Also see [`IoSliceMut::advance_slices`] to advance the cursors of
1091     /// multiple buffers.
1092     ///
1093     /// # Examples
1094     ///
1095     /// ```
1096     /// #![feature(io_slice_advance)]
1097     ///
1098     /// use std::io::IoSliceMut;
1099     /// use std::ops::Deref;
1100     ///
1101     /// let mut data = [1; 8];
1102     /// let mut buf = IoSliceMut::new(&mut data);
1103     ///
1104     /// // Mark 3 bytes as read.
1105     /// buf.advance(3);
1106     /// assert_eq!(buf.deref(), [1; 5].as_ref());
1107     /// ```
1108     #[unstable(feature = "io_slice_advance", issue = "62726")]
1109     #[inline]
1110     pub fn advance(&mut self, n: usize) {
1111         self.0.advance(n)
1112     }
1113
1114     /// Advance the internal cursor of the slices.
1115     ///
1116     /// # Notes
1117     ///
1118     /// Elements in the slice may be modified if the cursor is not advanced to
1119     /// the end of the slice. For example if we have a slice of buffers with 2
1120     /// `IoSliceMut`s, both of length 8, and we advance the cursor by 10 bytes
1121     /// the first `IoSliceMut` will be untouched however the second will be
1122     /// modified to remove the first 2 bytes (10 - 8).
1123     ///
1124     /// # Examples
1125     ///
1126     /// ```
1127     /// #![feature(io_slice_advance)]
1128     ///
1129     /// use std::io::IoSliceMut;
1130     /// use std::ops::Deref;
1131     ///
1132     /// let mut buf1 = [1; 8];
1133     /// let mut buf2 = [2; 16];
1134     /// let mut buf3 = [3; 8];
1135     /// let mut bufs = &mut [
1136     ///     IoSliceMut::new(&mut buf1),
1137     ///     IoSliceMut::new(&mut buf2),
1138     ///     IoSliceMut::new(&mut buf3),
1139     /// ][..];
1140     ///
1141     /// // Mark 10 bytes as read.
1142     /// IoSliceMut::advance_slices(&mut bufs, 10);
1143     /// assert_eq!(bufs[0].deref(), [2; 14].as_ref());
1144     /// assert_eq!(bufs[1].deref(), [3; 8].as_ref());
1145     /// ```
1146     #[unstable(feature = "io_slice_advance", issue = "62726")]
1147     #[inline]
1148     pub fn advance_slices(bufs: &mut &mut [IoSliceMut<'a>], n: usize) {
1149         // Number of buffers to remove.
1150         let mut remove = 0;
1151         // Total length of all the to be removed buffers.
1152         let mut accumulated_len = 0;
1153         for buf in bufs.iter() {
1154             if accumulated_len + buf.len() > n {
1155                 break;
1156             } else {
1157                 accumulated_len += buf.len();
1158                 remove += 1;
1159             }
1160         }
1161
1162         *bufs = &mut replace(bufs, &mut [])[remove..];
1163         if !bufs.is_empty() {
1164             bufs[0].advance(n - accumulated_len)
1165         }
1166     }
1167 }
1168
1169 #[stable(feature = "iovec", since = "1.36.0")]
1170 impl<'a> Deref for IoSliceMut<'a> {
1171     type Target = [u8];
1172
1173     #[inline]
1174     fn deref(&self) -> &[u8] {
1175         self.0.as_slice()
1176     }
1177 }
1178
1179 #[stable(feature = "iovec", since = "1.36.0")]
1180 impl<'a> DerefMut for IoSliceMut<'a> {
1181     #[inline]
1182     fn deref_mut(&mut self) -> &mut [u8] {
1183         self.0.as_mut_slice()
1184     }
1185 }
1186
1187 /// A buffer type used with `Write::write_vectored`.
1188 ///
1189 /// It is semantically a wrapper around a `&[u8]`, but is guaranteed to be
1190 /// ABI compatible with the `iovec` type on Unix platforms and `WSABUF` on
1191 /// Windows.
1192 #[stable(feature = "iovec", since = "1.36.0")]
1193 #[derive(Copy, Clone)]
1194 #[repr(transparent)]
1195 pub struct IoSlice<'a>(sys::io::IoSlice<'a>);
1196
1197 #[stable(feature = "iovec-send-sync", since = "1.44.0")]
1198 unsafe impl<'a> Send for IoSlice<'a> {}
1199
1200 #[stable(feature = "iovec-send-sync", since = "1.44.0")]
1201 unsafe impl<'a> Sync for IoSlice<'a> {}
1202
1203 #[stable(feature = "iovec", since = "1.36.0")]
1204 impl<'a> fmt::Debug for IoSlice<'a> {
1205     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1206         fmt::Debug::fmt(self.0.as_slice(), fmt)
1207     }
1208 }
1209
1210 impl<'a> IoSlice<'a> {
1211     /// Creates a new `IoSlice` wrapping a byte slice.
1212     ///
1213     /// # Panics
1214     ///
1215     /// Panics on Windows if the slice is larger than 4GB.
1216     #[stable(feature = "iovec", since = "1.36.0")]
1217     #[must_use]
1218     #[inline]
1219     pub fn new(buf: &'a [u8]) -> IoSlice<'a> {
1220         IoSlice(sys::io::IoSlice::new(buf))
1221     }
1222
1223     /// Advance the internal cursor of the slice.
1224     ///
1225     /// Also see [`IoSlice::advance_slices`] to advance the cursors of multiple
1226     /// buffers.
1227     ///
1228     /// # Examples
1229     ///
1230     /// ```
1231     /// #![feature(io_slice_advance)]
1232     ///
1233     /// use std::io::IoSlice;
1234     /// use std::ops::Deref;
1235     ///
1236     /// let mut data = [1; 8];
1237     /// let mut buf = IoSlice::new(&mut data);
1238     ///
1239     /// // Mark 3 bytes as read.
1240     /// buf.advance(3);
1241     /// assert_eq!(buf.deref(), [1; 5].as_ref());
1242     /// ```
1243     #[unstable(feature = "io_slice_advance", issue = "62726")]
1244     #[inline]
1245     pub fn advance(&mut self, n: usize) {
1246         self.0.advance(n)
1247     }
1248
1249     /// Advance the internal cursor of the slices.
1250     ///
1251     /// # Notes
1252     ///
1253     /// Elements in the slice may be modified if the cursor is not advanced to
1254     /// the end of the slice. For example if we have a slice of buffers with 2
1255     /// `IoSlice`s, both of length 8, and we advance the cursor by 10 bytes the
1256     /// first `IoSlice` will be untouched however the second will be modified to
1257     /// remove the first 2 bytes (10 - 8).
1258     ///
1259     /// # Examples
1260     ///
1261     /// ```
1262     /// #![feature(io_slice_advance)]
1263     ///
1264     /// use std::io::IoSlice;
1265     /// use std::ops::Deref;
1266     ///
1267     /// let buf1 = [1; 8];
1268     /// let buf2 = [2; 16];
1269     /// let buf3 = [3; 8];
1270     /// let mut bufs = &mut [
1271     ///     IoSlice::new(&buf1),
1272     ///     IoSlice::new(&buf2),
1273     ///     IoSlice::new(&buf3),
1274     /// ][..];
1275     ///
1276     /// // Mark 10 bytes as written.
1277     /// IoSlice::advance_slices(&mut bufs, 10);
1278     /// assert_eq!(bufs[0].deref(), [2; 14].as_ref());
1279     /// assert_eq!(bufs[1].deref(), [3; 8].as_ref());
1280     #[unstable(feature = "io_slice_advance", issue = "62726")]
1281     #[inline]
1282     pub fn advance_slices(bufs: &mut &mut [IoSlice<'a>], n: usize) {
1283         // Number of buffers to remove.
1284         let mut remove = 0;
1285         // Total length of all the to be removed buffers.
1286         let mut accumulated_len = 0;
1287         for buf in bufs.iter() {
1288             if accumulated_len + buf.len() > n {
1289                 break;
1290             } else {
1291                 accumulated_len += buf.len();
1292                 remove += 1;
1293             }
1294         }
1295
1296         *bufs = &mut replace(bufs, &mut [])[remove..];
1297         if !bufs.is_empty() {
1298             bufs[0].advance(n - accumulated_len)
1299         }
1300     }
1301 }
1302
1303 #[stable(feature = "iovec", since = "1.36.0")]
1304 impl<'a> Deref for IoSlice<'a> {
1305     type Target = [u8];
1306
1307     #[inline]
1308     fn deref(&self) -> &[u8] {
1309         self.0.as_slice()
1310     }
1311 }
1312
1313 /// A trait for objects which are byte-oriented sinks.
1314 ///
1315 /// Implementors of the `Write` trait are sometimes called 'writers'.
1316 ///
1317 /// Writers are defined by two required methods, [`write`] and [`flush`]:
1318 ///
1319 /// * The [`write`] method will attempt to write some data into the object,
1320 ///   returning how many bytes were successfully written.
1321 ///
1322 /// * The [`flush`] method is useful for adapters and explicit buffers
1323 ///   themselves for ensuring that all buffered data has been pushed out to the
1324 ///   'true sink'.
1325 ///
1326 /// Writers are intended to be composable with one another. Many implementors
1327 /// throughout [`std::io`] take and provide types which implement the `Write`
1328 /// trait.
1329 ///
1330 /// [`write`]: Write::write
1331 /// [`flush`]: Write::flush
1332 /// [`std::io`]: self
1333 ///
1334 /// # Examples
1335 ///
1336 /// ```no_run
1337 /// use std::io::prelude::*;
1338 /// use std::fs::File;
1339 ///
1340 /// fn main() -> std::io::Result<()> {
1341 ///     let data = b"some bytes";
1342 ///
1343 ///     let mut pos = 0;
1344 ///     let mut buffer = File::create("foo.txt")?;
1345 ///
1346 ///     while pos < data.len() {
1347 ///         let bytes_written = buffer.write(&data[pos..])?;
1348 ///         pos += bytes_written;
1349 ///     }
1350 ///     Ok(())
1351 /// }
1352 /// ```
1353 ///
1354 /// The trait also provides convenience methods like [`write_all`], which calls
1355 /// `write` in a loop until its entire input has been written.
1356 ///
1357 /// [`write_all`]: Write::write_all
1358 #[stable(feature = "rust1", since = "1.0.0")]
1359 #[doc(notable_trait)]
1360 #[cfg_attr(not(test), rustc_diagnostic_item = "IoWrite")]
1361 pub trait Write {
1362     /// Write a buffer into this writer, returning how many bytes were written.
1363     ///
1364     /// This function will attempt to write the entire contents of `buf`, but
1365     /// the entire write might not succeed, or the write may also generate an
1366     /// error. A call to `write` represents *at most one* attempt to write to
1367     /// any wrapped object.
1368     ///
1369     /// Calls to `write` are not guaranteed to block waiting for data to be
1370     /// written, and a write which would otherwise block can be indicated through
1371     /// an [`Err`] variant.
1372     ///
1373     /// If the return value is [`Ok(n)`] then it must be guaranteed that
1374     /// `n <= buf.len()`. A return value of `0` typically means that the
1375     /// underlying object is no longer able to accept bytes and will likely not
1376     /// be able to in the future as well, or that the buffer provided is empty.
1377     ///
1378     /// # Errors
1379     ///
1380     /// Each call to `write` may generate an I/O error indicating that the
1381     /// operation could not be completed. If an error is returned then no bytes
1382     /// in the buffer were written to this writer.
1383     ///
1384     /// It is **not** considered an error if the entire buffer could not be
1385     /// written to this writer.
1386     ///
1387     /// An error of the [`ErrorKind::Interrupted`] kind is non-fatal and the
1388     /// write operation should be retried if there is nothing else to do.
1389     ///
1390     /// # Examples
1391     ///
1392     /// ```no_run
1393     /// use std::io::prelude::*;
1394     /// use std::fs::File;
1395     ///
1396     /// fn main() -> std::io::Result<()> {
1397     ///     let mut buffer = File::create("foo.txt")?;
1398     ///
1399     ///     // Writes some prefix of the byte string, not necessarily all of it.
1400     ///     buffer.write(b"some bytes")?;
1401     ///     Ok(())
1402     /// }
1403     /// ```
1404     ///
1405     /// [`Ok(n)`]: Ok
1406     #[stable(feature = "rust1", since = "1.0.0")]
1407     fn write(&mut self, buf: &[u8]) -> Result<usize>;
1408
1409     /// Like [`write`], except that it writes from a slice of buffers.
1410     ///
1411     /// Data is copied from each buffer in order, with the final buffer
1412     /// read from possibly being only partially consumed. This method must
1413     /// behave as a call to [`write`] with the buffers concatenated would.
1414     ///
1415     /// The default implementation calls [`write`] with either the first nonempty
1416     /// buffer provided, or an empty one if none exists.
1417     ///
1418     /// # Examples
1419     ///
1420     /// ```no_run
1421     /// use std::io::IoSlice;
1422     /// use std::io::prelude::*;
1423     /// use std::fs::File;
1424     ///
1425     /// fn main() -> std::io::Result<()> {
1426     ///     let mut data1 = [1; 8];
1427     ///     let mut data2 = [15; 8];
1428     ///     let io_slice1 = IoSlice::new(&mut data1);
1429     ///     let io_slice2 = IoSlice::new(&mut data2);
1430     ///
1431     ///     let mut buffer = File::create("foo.txt")?;
1432     ///
1433     ///     // Writes some prefix of the byte string, not necessarily all of it.
1434     ///     buffer.write_vectored(&[io_slice1, io_slice2])?;
1435     ///     Ok(())
1436     /// }
1437     /// ```
1438     ///
1439     /// [`write`]: Write::write
1440     #[stable(feature = "iovec", since = "1.36.0")]
1441     fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> Result<usize> {
1442         default_write_vectored(|b| self.write(b), bufs)
1443     }
1444
1445     /// Determines if this `Write`r has an efficient [`write_vectored`]
1446     /// implementation.
1447     ///
1448     /// If a `Write`r does not override the default [`write_vectored`]
1449     /// implementation, code using it may want to avoid the method all together
1450     /// and coalesce writes into a single buffer for higher performance.
1451     ///
1452     /// The default implementation returns `false`.
1453     ///
1454     /// [`write_vectored`]: Write::write_vectored
1455     #[unstable(feature = "can_vector", issue = "69941")]
1456     fn is_write_vectored(&self) -> bool {
1457         false
1458     }
1459
1460     /// Flush this output stream, ensuring that all intermediately buffered
1461     /// contents reach their destination.
1462     ///
1463     /// # Errors
1464     ///
1465     /// It is considered an error if not all bytes could be written due to
1466     /// I/O errors or EOF being reached.
1467     ///
1468     /// # Examples
1469     ///
1470     /// ```no_run
1471     /// use std::io::prelude::*;
1472     /// use std::io::BufWriter;
1473     /// use std::fs::File;
1474     ///
1475     /// fn main() -> std::io::Result<()> {
1476     ///     let mut buffer = BufWriter::new(File::create("foo.txt")?);
1477     ///
1478     ///     buffer.write_all(b"some bytes")?;
1479     ///     buffer.flush()?;
1480     ///     Ok(())
1481     /// }
1482     /// ```
1483     #[stable(feature = "rust1", since = "1.0.0")]
1484     fn flush(&mut self) -> Result<()>;
1485
1486     /// Attempts to write an entire buffer into this writer.
1487     ///
1488     /// This method will continuously call [`write`] until there is no more data
1489     /// to be written or an error of non-[`ErrorKind::Interrupted`] kind is
1490     /// returned. This method will not return until the entire buffer has been
1491     /// successfully written or such an error occurs. The first error that is
1492     /// not of [`ErrorKind::Interrupted`] kind generated from this method will be
1493     /// returned.
1494     ///
1495     /// If the buffer contains no data, this will never call [`write`].
1496     ///
1497     /// # Errors
1498     ///
1499     /// This function will return the first error of
1500     /// non-[`ErrorKind::Interrupted`] kind that [`write`] returns.
1501     ///
1502     /// [`write`]: Write::write
1503     ///
1504     /// # Examples
1505     ///
1506     /// ```no_run
1507     /// use std::io::prelude::*;
1508     /// use std::fs::File;
1509     ///
1510     /// fn main() -> std::io::Result<()> {
1511     ///     let mut buffer = File::create("foo.txt")?;
1512     ///
1513     ///     buffer.write_all(b"some bytes")?;
1514     ///     Ok(())
1515     /// }
1516     /// ```
1517     #[stable(feature = "rust1", since = "1.0.0")]
1518     fn write_all(&mut self, mut buf: &[u8]) -> Result<()> {
1519         while !buf.is_empty() {
1520             match self.write(buf) {
1521                 Ok(0) => {
1522                     return Err(Error::new_const(
1523                         ErrorKind::WriteZero,
1524                         &"failed to write whole buffer",
1525                     ));
1526                 }
1527                 Ok(n) => buf = &buf[n..],
1528                 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
1529                 Err(e) => return Err(e),
1530             }
1531         }
1532         Ok(())
1533     }
1534
1535     /// Attempts to write multiple buffers into this writer.
1536     ///
1537     /// This method will continuously call [`write_vectored`] until there is no
1538     /// more data to be written or an error of non-[`ErrorKind::Interrupted`]
1539     /// kind is returned. This method will not return until all buffers have
1540     /// been successfully written or such an error occurs. The first error that
1541     /// is not of [`ErrorKind::Interrupted`] kind generated from this method
1542     /// will be returned.
1543     ///
1544     /// If the buffer contains no data, this will never call [`write_vectored`].
1545     ///
1546     /// # Notes
1547     ///
1548     /// Unlike [`write_vectored`], this takes a *mutable* reference to
1549     /// a slice of [`IoSlice`]s, not an immutable one. That's because we need to
1550     /// modify the slice to keep track of the bytes already written.
1551     ///
1552     /// Once this function returns, the contents of `bufs` are unspecified, as
1553     /// this depends on how many calls to [`write_vectored`] were necessary. It is
1554     /// best to understand this function as taking ownership of `bufs` and to
1555     /// not use `bufs` afterwards. The underlying buffers, to which the
1556     /// [`IoSlice`]s point (but not the [`IoSlice`]s themselves), are unchanged and
1557     /// can be reused.
1558     ///
1559     /// [`write_vectored`]: Write::write_vectored
1560     ///
1561     /// # Examples
1562     ///
1563     /// ```
1564     /// #![feature(write_all_vectored)]
1565     /// # fn main() -> std::io::Result<()> {
1566     ///
1567     /// use std::io::{Write, IoSlice};
1568     ///
1569     /// let mut writer = Vec::new();
1570     /// let bufs = &mut [
1571     ///     IoSlice::new(&[1]),
1572     ///     IoSlice::new(&[2, 3]),
1573     ///     IoSlice::new(&[4, 5, 6]),
1574     /// ];
1575     ///
1576     /// writer.write_all_vectored(bufs)?;
1577     /// // Note: the contents of `bufs` is now undefined, see the Notes section.
1578     ///
1579     /// assert_eq!(writer, &[1, 2, 3, 4, 5, 6]);
1580     /// # Ok(()) }
1581     /// ```
1582     #[unstable(feature = "write_all_vectored", issue = "70436")]
1583     fn write_all_vectored(&mut self, mut bufs: &mut [IoSlice<'_>]) -> Result<()> {
1584         // Guarantee that bufs is empty if it contains no data,
1585         // to avoid calling write_vectored if there is no data to be written.
1586         IoSlice::advance_slices(&mut bufs, 0);
1587         while !bufs.is_empty() {
1588             match self.write_vectored(bufs) {
1589                 Ok(0) => {
1590                     return Err(Error::new_const(
1591                         ErrorKind::WriteZero,
1592                         &"failed to write whole buffer",
1593                     ));
1594                 }
1595                 Ok(n) => IoSlice::advance_slices(&mut bufs, n),
1596                 Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
1597                 Err(e) => return Err(e),
1598             }
1599         }
1600         Ok(())
1601     }
1602
1603     /// Writes a formatted string into this writer, returning any error
1604     /// encountered.
1605     ///
1606     /// This method is primarily used to interface with the
1607     /// [`format_args!()`] macro, and it is rare that this should
1608     /// explicitly be called. The [`write!()`] macro should be favored to
1609     /// invoke this method instead.
1610     ///
1611     /// This function internally uses the [`write_all`] method on
1612     /// this trait and hence will continuously write data so long as no errors
1613     /// are received. This also means that partial writes are not indicated in
1614     /// this signature.
1615     ///
1616     /// [`write_all`]: Write::write_all
1617     ///
1618     /// # Errors
1619     ///
1620     /// This function will return any I/O error reported while formatting.
1621     ///
1622     /// # Examples
1623     ///
1624     /// ```no_run
1625     /// use std::io::prelude::*;
1626     /// use std::fs::File;
1627     ///
1628     /// fn main() -> std::io::Result<()> {
1629     ///     let mut buffer = File::create("foo.txt")?;
1630     ///
1631     ///     // this call
1632     ///     write!(buffer, "{:.*}", 2, 1.234567)?;
1633     ///     // turns into this:
1634     ///     buffer.write_fmt(format_args!("{:.*}", 2, 1.234567))?;
1635     ///     Ok(())
1636     /// }
1637     /// ```
1638     #[stable(feature = "rust1", since = "1.0.0")]
1639     fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> Result<()> {
1640         // Create a shim which translates a Write to a fmt::Write and saves
1641         // off I/O errors. instead of discarding them
1642         struct Adapter<'a, T: ?Sized + 'a> {
1643             inner: &'a mut T,
1644             error: Result<()>,
1645         }
1646
1647         impl<T: Write + ?Sized> fmt::Write for Adapter<'_, T> {
1648             fn write_str(&mut self, s: &str) -> fmt::Result {
1649                 match self.inner.write_all(s.as_bytes()) {
1650                     Ok(()) => Ok(()),
1651                     Err(e) => {
1652                         self.error = Err(e);
1653                         Err(fmt::Error)
1654                     }
1655                 }
1656             }
1657         }
1658
1659         let mut output = Adapter { inner: self, error: Ok(()) };
1660         match fmt::write(&mut output, fmt) {
1661             Ok(()) => Ok(()),
1662             Err(..) => {
1663                 // check if the error came from the underlying `Write` or not
1664                 if output.error.is_err() {
1665                     output.error
1666                 } else {
1667                     Err(Error::new_const(ErrorKind::Uncategorized, &"formatter error"))
1668                 }
1669             }
1670         }
1671     }
1672
1673     /// Creates a "by reference" adapter for this instance of `Write`.
1674     ///
1675     /// The returned adapter also implements `Write` and will simply borrow this
1676     /// current writer.
1677     ///
1678     /// # Examples
1679     ///
1680     /// ```no_run
1681     /// use std::io::Write;
1682     /// use std::fs::File;
1683     ///
1684     /// fn main() -> std::io::Result<()> {
1685     ///     let mut buffer = File::create("foo.txt")?;
1686     ///
1687     ///     let reference = buffer.by_ref();
1688     ///
1689     ///     // we can use reference just like our original buffer
1690     ///     reference.write_all(b"some bytes")?;
1691     ///     Ok(())
1692     /// }
1693     /// ```
1694     #[stable(feature = "rust1", since = "1.0.0")]
1695     fn by_ref(&mut self) -> &mut Self
1696     where
1697         Self: Sized,
1698     {
1699         self
1700     }
1701 }
1702
1703 /// The `Seek` trait provides a cursor which can be moved within a stream of
1704 /// bytes.
1705 ///
1706 /// The stream typically has a fixed size, allowing seeking relative to either
1707 /// end or the current offset.
1708 ///
1709 /// # Examples
1710 ///
1711 /// [`File`]s implement `Seek`:
1712 ///
1713 /// [`File`]: crate::fs::File
1714 ///
1715 /// ```no_run
1716 /// use std::io;
1717 /// use std::io::prelude::*;
1718 /// use std::fs::File;
1719 /// use std::io::SeekFrom;
1720 ///
1721 /// fn main() -> io::Result<()> {
1722 ///     let mut f = File::open("foo.txt")?;
1723 ///
1724 ///     // move the cursor 42 bytes from the start of the file
1725 ///     f.seek(SeekFrom::Start(42))?;
1726 ///     Ok(())
1727 /// }
1728 /// ```
1729 #[stable(feature = "rust1", since = "1.0.0")]
1730 pub trait Seek {
1731     /// Seek to an offset, in bytes, in a stream.
1732     ///
1733     /// A seek beyond the end of a stream is allowed, but behavior is defined
1734     /// by the implementation.
1735     ///
1736     /// If the seek operation completed successfully,
1737     /// this method returns the new position from the start of the stream.
1738     /// That position can be used later with [`SeekFrom::Start`].
1739     ///
1740     /// # Errors
1741     ///
1742     /// Seeking can fail, for example because it might involve flushing a buffer.
1743     ///
1744     /// Seeking to a negative offset is considered an error.
1745     #[stable(feature = "rust1", since = "1.0.0")]
1746     fn seek(&mut self, pos: SeekFrom) -> Result<u64>;
1747
1748     /// Rewind to the beginning of a stream.
1749     ///
1750     /// This is a convenience method, equivalent to `seek(SeekFrom::Start(0))`.
1751     ///
1752     /// # Errors
1753     ///
1754     /// Rewinding can fail, for example because it might involve flushing a buffer.
1755     ///
1756     /// # Example
1757     ///
1758     /// ```no_run
1759     /// use std::io::{Read, Seek, Write};
1760     /// use std::fs::OpenOptions;
1761     ///
1762     /// let mut f = OpenOptions::new()
1763     ///     .write(true)
1764     ///     .read(true)
1765     ///     .create(true)
1766     ///     .open("foo.txt").unwrap();
1767     ///
1768     /// let hello = "Hello!\n";
1769     /// write!(f, "{}", hello).unwrap();
1770     /// f.rewind().unwrap();
1771     ///
1772     /// let mut buf = String::new();
1773     /// f.read_to_string(&mut buf).unwrap();
1774     /// assert_eq!(&buf, hello);
1775     /// ```
1776     #[stable(feature = "seek_rewind", since = "1.55.0")]
1777     fn rewind(&mut self) -> Result<()> {
1778         self.seek(SeekFrom::Start(0))?;
1779         Ok(())
1780     }
1781
1782     /// Returns the length of this stream (in bytes).
1783     ///
1784     /// This method is implemented using up to three seek operations. If this
1785     /// method returns successfully, the seek position is unchanged (i.e. the
1786     /// position before calling this method is the same as afterwards).
1787     /// However, if this method returns an error, the seek position is
1788     /// unspecified.
1789     ///
1790     /// If you need to obtain the length of *many* streams and you don't care
1791     /// about the seek position afterwards, you can reduce the number of seek
1792     /// operations by simply calling `seek(SeekFrom::End(0))` and using its
1793     /// return value (it is also the stream length).
1794     ///
1795     /// Note that length of a stream can change over time (for example, when
1796     /// data is appended to a file). So calling this method multiple times does
1797     /// not necessarily return the same length each time.
1798     ///
1799     /// # Example
1800     ///
1801     /// ```no_run
1802     /// #![feature(seek_stream_len)]
1803     /// use std::{
1804     ///     io::{self, Seek},
1805     ///     fs::File,
1806     /// };
1807     ///
1808     /// fn main() -> io::Result<()> {
1809     ///     let mut f = File::open("foo.txt")?;
1810     ///
1811     ///     let len = f.stream_len()?;
1812     ///     println!("The file is currently {} bytes long", len);
1813     ///     Ok(())
1814     /// }
1815     /// ```
1816     #[unstable(feature = "seek_stream_len", issue = "59359")]
1817     fn stream_len(&mut self) -> Result<u64> {
1818         let old_pos = self.stream_position()?;
1819         let len = self.seek(SeekFrom::End(0))?;
1820
1821         // Avoid seeking a third time when we were already at the end of the
1822         // stream. The branch is usually way cheaper than a seek operation.
1823         if old_pos != len {
1824             self.seek(SeekFrom::Start(old_pos))?;
1825         }
1826
1827         Ok(len)
1828     }
1829
1830     /// Returns the current seek position from the start of the stream.
1831     ///
1832     /// This is equivalent to `self.seek(SeekFrom::Current(0))`.
1833     ///
1834     /// # Example
1835     ///
1836     /// ```no_run
1837     /// use std::{
1838     ///     io::{self, BufRead, BufReader, Seek},
1839     ///     fs::File,
1840     /// };
1841     ///
1842     /// fn main() -> io::Result<()> {
1843     ///     let mut f = BufReader::new(File::open("foo.txt")?);
1844     ///
1845     ///     let before = f.stream_position()?;
1846     ///     f.read_line(&mut String::new())?;
1847     ///     let after = f.stream_position()?;
1848     ///
1849     ///     println!("The first line was {} bytes long", after - before);
1850     ///     Ok(())
1851     /// }
1852     /// ```
1853     #[stable(feature = "seek_convenience", since = "1.51.0")]
1854     fn stream_position(&mut self) -> Result<u64> {
1855         self.seek(SeekFrom::Current(0))
1856     }
1857 }
1858
1859 /// Enumeration of possible methods to seek within an I/O object.
1860 ///
1861 /// It is used by the [`Seek`] trait.
1862 #[derive(Copy, PartialEq, Eq, Clone, Debug)]
1863 #[stable(feature = "rust1", since = "1.0.0")]
1864 pub enum SeekFrom {
1865     /// Sets the offset to the provided number of bytes.
1866     #[stable(feature = "rust1", since = "1.0.0")]
1867     Start(#[stable(feature = "rust1", since = "1.0.0")] u64),
1868
1869     /// Sets the offset to the size of this object plus the specified number of
1870     /// bytes.
1871     ///
1872     /// It is possible to seek beyond the end of an object, but it's an error to
1873     /// seek before byte 0.
1874     #[stable(feature = "rust1", since = "1.0.0")]
1875     End(#[stable(feature = "rust1", since = "1.0.0")] i64),
1876
1877     /// Sets the offset to the current position plus the specified number of
1878     /// bytes.
1879     ///
1880     /// It is possible to seek beyond the end of an object, but it's an error to
1881     /// seek before byte 0.
1882     #[stable(feature = "rust1", since = "1.0.0")]
1883     Current(#[stable(feature = "rust1", since = "1.0.0")] i64),
1884 }
1885
1886 fn read_until<R: BufRead + ?Sized>(r: &mut R, delim: u8, buf: &mut Vec<u8>) -> Result<usize> {
1887     let mut read = 0;
1888     loop {
1889         let (done, used) = {
1890             let available = match r.fill_buf() {
1891                 Ok(n) => n,
1892                 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
1893                 Err(e) => return Err(e),
1894             };
1895             match memchr::memchr(delim, available) {
1896                 Some(i) => {
1897                     buf.extend_from_slice(&available[..=i]);
1898                     (true, i + 1)
1899                 }
1900                 None => {
1901                     buf.extend_from_slice(available);
1902                     (false, available.len())
1903                 }
1904             }
1905         };
1906         r.consume(used);
1907         read += used;
1908         if done || used == 0 {
1909             return Ok(read);
1910         }
1911     }
1912 }
1913
1914 /// A `BufRead` is a type of `Read`er which has an internal buffer, allowing it
1915 /// to perform extra ways of reading.
1916 ///
1917 /// For example, reading line-by-line is inefficient without using a buffer, so
1918 /// if you want to read by line, you'll need `BufRead`, which includes a
1919 /// [`read_line`] method as well as a [`lines`] iterator.
1920 ///
1921 /// # Examples
1922 ///
1923 /// A locked standard input implements `BufRead`:
1924 ///
1925 /// ```no_run
1926 /// use std::io;
1927 /// use std::io::prelude::*;
1928 ///
1929 /// let stdin = io::stdin();
1930 /// for line in stdin.lock().lines() {
1931 ///     println!("{}", line.unwrap());
1932 /// }
1933 /// ```
1934 ///
1935 /// If you have something that implements [`Read`], you can use the [`BufReader`
1936 /// type][`BufReader`] to turn it into a `BufRead`.
1937 ///
1938 /// For example, [`File`] implements [`Read`], but not `BufRead`.
1939 /// [`BufReader`] to the rescue!
1940 ///
1941 /// [`File`]: crate::fs::File
1942 /// [`read_line`]: BufRead::read_line
1943 /// [`lines`]: BufRead::lines
1944 ///
1945 /// ```no_run
1946 /// use std::io::{self, BufReader};
1947 /// use std::io::prelude::*;
1948 /// use std::fs::File;
1949 ///
1950 /// fn main() -> io::Result<()> {
1951 ///     let f = File::open("foo.txt")?;
1952 ///     let f = BufReader::new(f);
1953 ///
1954 ///     for line in f.lines() {
1955 ///         println!("{}", line.unwrap());
1956 ///     }
1957 ///
1958 ///     Ok(())
1959 /// }
1960 /// ```
1961 #[stable(feature = "rust1", since = "1.0.0")]
1962 pub trait BufRead: Read {
1963     /// Returns the contents of the internal buffer, filling it with more data
1964     /// from the inner reader if it is empty.
1965     ///
1966     /// This function is a lower-level call. It needs to be paired with the
1967     /// [`consume`] method to function properly. When calling this
1968     /// method, none of the contents will be "read" in the sense that later
1969     /// calling `read` may return the same contents. As such, [`consume`] must
1970     /// be called with the number of bytes that are consumed from this buffer to
1971     /// ensure that the bytes are never returned twice.
1972     ///
1973     /// [`consume`]: BufRead::consume
1974     ///
1975     /// An empty buffer returned indicates that the stream has reached EOF.
1976     ///
1977     /// # Errors
1978     ///
1979     /// This function will return an I/O error if the underlying reader was
1980     /// read, but returned an error.
1981     ///
1982     /// # Examples
1983     ///
1984     /// A locked standard input implements `BufRead`:
1985     ///
1986     /// ```no_run
1987     /// use std::io;
1988     /// use std::io::prelude::*;
1989     ///
1990     /// let stdin = io::stdin();
1991     /// let mut stdin = stdin.lock();
1992     ///
1993     /// let buffer = stdin.fill_buf().unwrap();
1994     ///
1995     /// // work with buffer
1996     /// println!("{:?}", buffer);
1997     ///
1998     /// // ensure the bytes we worked with aren't returned again later
1999     /// let length = buffer.len();
2000     /// stdin.consume(length);
2001     /// ```
2002     #[stable(feature = "rust1", since = "1.0.0")]
2003     fn fill_buf(&mut self) -> Result<&[u8]>;
2004
2005     /// Tells this buffer that `amt` bytes have been consumed from the buffer,
2006     /// so they should no longer be returned in calls to `read`.
2007     ///
2008     /// This function is a lower-level call. It needs to be paired with the
2009     /// [`fill_buf`] method to function properly. This function does
2010     /// not perform any I/O, it simply informs this object that some amount of
2011     /// its buffer, returned from [`fill_buf`], has been consumed and should
2012     /// no longer be returned. As such, this function may do odd things if
2013     /// [`fill_buf`] isn't called before calling it.
2014     ///
2015     /// The `amt` must be `<=` the number of bytes in the buffer returned by
2016     /// [`fill_buf`].
2017     ///
2018     /// # Examples
2019     ///
2020     /// Since `consume()` is meant to be used with [`fill_buf`],
2021     /// that method's example includes an example of `consume()`.
2022     ///
2023     /// [`fill_buf`]: BufRead::fill_buf
2024     #[stable(feature = "rust1", since = "1.0.0")]
2025     fn consume(&mut self, amt: usize);
2026
2027     /// Check if the underlying `Read` has any data left to be read.
2028     ///
2029     /// This function may fill the buffer to check for data,
2030     /// so this functions returns `Result<bool>`, not `bool`.
2031     ///
2032     /// Default implementation calls `fill_buf` and checks that
2033     /// returned slice is empty (which means that there is no data left,
2034     /// since EOF is reached).
2035     ///
2036     /// Examples
2037     ///
2038     /// ```
2039     /// #![feature(buf_read_has_data_left)]
2040     /// use std::io;
2041     /// use std::io::prelude::*;
2042     ///
2043     /// let stdin = io::stdin();
2044     /// let mut stdin = stdin.lock();
2045     ///
2046     /// while stdin.has_data_left().unwrap() {
2047     ///     let mut line = String::new();
2048     ///     stdin.read_line(&mut line).unwrap();
2049     ///     // work with line
2050     ///     println!("{:?}", line);
2051     /// }
2052     /// ```
2053     #[unstable(feature = "buf_read_has_data_left", reason = "recently added", issue = "86423")]
2054     fn has_data_left(&mut self) -> Result<bool> {
2055         self.fill_buf().map(|b| !b.is_empty())
2056     }
2057
2058     /// Read all bytes into `buf` until the delimiter `byte` or EOF is reached.
2059     ///
2060     /// This function will read bytes from the underlying stream until the
2061     /// delimiter or EOF is found. Once found, all bytes up to, and including,
2062     /// the delimiter (if found) will be appended to `buf`.
2063     ///
2064     /// If successful, this function will return the total number of bytes read.
2065     ///
2066     /// This function is blocking and should be used carefully: it is possible for
2067     /// an attacker to continuously send bytes without ever sending the delimiter
2068     /// or EOF.
2069     ///
2070     /// # Errors
2071     ///
2072     /// This function will ignore all instances of [`ErrorKind::Interrupted`] and
2073     /// will otherwise return any errors returned by [`fill_buf`].
2074     ///
2075     /// If an I/O error is encountered then all bytes read so far will be
2076     /// present in `buf` and its length will have been adjusted appropriately.
2077     ///
2078     /// [`fill_buf`]: BufRead::fill_buf
2079     ///
2080     /// # Examples
2081     ///
2082     /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
2083     /// this example, we use [`Cursor`] to read all the bytes in a byte slice
2084     /// in hyphen delimited segments:
2085     ///
2086     /// ```
2087     /// use std::io::{self, BufRead};
2088     ///
2089     /// let mut cursor = io::Cursor::new(b"lorem-ipsum");
2090     /// let mut buf = vec![];
2091     ///
2092     /// // cursor is at 'l'
2093     /// let num_bytes = cursor.read_until(b'-', &mut buf)
2094     ///     .expect("reading from cursor won't fail");
2095     /// assert_eq!(num_bytes, 6);
2096     /// assert_eq!(buf, b"lorem-");
2097     /// buf.clear();
2098     ///
2099     /// // cursor is at 'i'
2100     /// let num_bytes = cursor.read_until(b'-', &mut buf)
2101     ///     .expect("reading from cursor won't fail");
2102     /// assert_eq!(num_bytes, 5);
2103     /// assert_eq!(buf, b"ipsum");
2104     /// buf.clear();
2105     ///
2106     /// // cursor is at EOF
2107     /// let num_bytes = cursor.read_until(b'-', &mut buf)
2108     ///     .expect("reading from cursor won't fail");
2109     /// assert_eq!(num_bytes, 0);
2110     /// assert_eq!(buf, b"");
2111     /// ```
2112     #[stable(feature = "rust1", since = "1.0.0")]
2113     fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> Result<usize> {
2114         read_until(self, byte, buf)
2115     }
2116
2117     /// Read all bytes until a newline (the `0xA` byte) is reached, and append
2118     /// them to the provided buffer.
2119     ///
2120     /// This function will read bytes from the underlying stream until the
2121     /// newline delimiter (the `0xA` byte) or EOF is found. Once found, all bytes
2122     /// up to, and including, the delimiter (if found) will be appended to
2123     /// `buf`.
2124     ///
2125     /// If successful, this function will return the total number of bytes read.
2126     ///
2127     /// If this function returns [`Ok(0)`], the stream has reached EOF.
2128     ///
2129     /// This function is blocking and should be used carefully: it is possible for
2130     /// an attacker to continuously send bytes without ever sending a newline
2131     /// or EOF.
2132     ///
2133     /// [`Ok(0)`]: Ok
2134     ///
2135     /// # Errors
2136     ///
2137     /// This function has the same error semantics as [`read_until`] and will
2138     /// also return an error if the read bytes are not valid UTF-8. If an I/O
2139     /// error is encountered then `buf` may contain some bytes already read in
2140     /// the event that all data read so far was valid UTF-8.
2141     ///
2142     /// [`read_until`]: BufRead::read_until
2143     ///
2144     /// # Examples
2145     ///
2146     /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
2147     /// this example, we use [`Cursor`] to read all the lines in a byte slice:
2148     ///
2149     /// ```
2150     /// use std::io::{self, BufRead};
2151     ///
2152     /// let mut cursor = io::Cursor::new(b"foo\nbar");
2153     /// let mut buf = String::new();
2154     ///
2155     /// // cursor is at 'f'
2156     /// let num_bytes = cursor.read_line(&mut buf)
2157     ///     .expect("reading from cursor won't fail");
2158     /// assert_eq!(num_bytes, 4);
2159     /// assert_eq!(buf, "foo\n");
2160     /// buf.clear();
2161     ///
2162     /// // cursor is at 'b'
2163     /// let num_bytes = cursor.read_line(&mut buf)
2164     ///     .expect("reading from cursor won't fail");
2165     /// assert_eq!(num_bytes, 3);
2166     /// assert_eq!(buf, "bar");
2167     /// buf.clear();
2168     ///
2169     /// // cursor is at EOF
2170     /// let num_bytes = cursor.read_line(&mut buf)
2171     ///     .expect("reading from cursor won't fail");
2172     /// assert_eq!(num_bytes, 0);
2173     /// assert_eq!(buf, "");
2174     /// ```
2175     #[stable(feature = "rust1", since = "1.0.0")]
2176     fn read_line(&mut self, buf: &mut String) -> Result<usize> {
2177         // Note that we are not calling the `.read_until` method here, but
2178         // rather our hardcoded implementation. For more details as to why, see
2179         // the comments in `read_to_end`.
2180         unsafe { append_to_string(buf, |b| read_until(self, b'\n', b)) }
2181     }
2182
2183     /// Returns an iterator over the contents of this reader split on the byte
2184     /// `byte`.
2185     ///
2186     /// The iterator returned from this function will return instances of
2187     /// <code>[io::Result]<[Vec]\<u8>></code>. Each vector returned will *not* have
2188     /// the delimiter byte at the end.
2189     ///
2190     /// This function will yield errors whenever [`read_until`] would have
2191     /// also yielded an error.
2192     ///
2193     /// [io::Result]: self::Result "io::Result"
2194     /// [`read_until`]: BufRead::read_until
2195     ///
2196     /// # Examples
2197     ///
2198     /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
2199     /// this example, we use [`Cursor`] to iterate over all hyphen delimited
2200     /// segments in a byte slice
2201     ///
2202     /// ```
2203     /// use std::io::{self, BufRead};
2204     ///
2205     /// let cursor = io::Cursor::new(b"lorem-ipsum-dolor");
2206     ///
2207     /// let mut split_iter = cursor.split(b'-').map(|l| l.unwrap());
2208     /// assert_eq!(split_iter.next(), Some(b"lorem".to_vec()));
2209     /// assert_eq!(split_iter.next(), Some(b"ipsum".to_vec()));
2210     /// assert_eq!(split_iter.next(), Some(b"dolor".to_vec()));
2211     /// assert_eq!(split_iter.next(), None);
2212     /// ```
2213     #[stable(feature = "rust1", since = "1.0.0")]
2214     fn split(self, byte: u8) -> Split<Self>
2215     where
2216         Self: Sized,
2217     {
2218         Split { buf: self, delim: byte }
2219     }
2220
2221     /// Returns an iterator over the lines of this reader.
2222     ///
2223     /// The iterator returned from this function will yield instances of
2224     /// <code>[io::Result]<[String]></code>. Each string returned will *not* have a newline
2225     /// byte (the `0xA` byte) or `CRLF` (`0xD`, `0xA` bytes) at the end.
2226     ///
2227     /// [io::Result]: self::Result "io::Result"
2228     ///
2229     /// # Examples
2230     ///
2231     /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
2232     /// this example, we use [`Cursor`] to iterate over all the lines in a byte
2233     /// slice.
2234     ///
2235     /// ```
2236     /// use std::io::{self, BufRead};
2237     ///
2238     /// let cursor = io::Cursor::new(b"lorem\nipsum\r\ndolor");
2239     ///
2240     /// let mut lines_iter = cursor.lines().map(|l| l.unwrap());
2241     /// assert_eq!(lines_iter.next(), Some(String::from("lorem")));
2242     /// assert_eq!(lines_iter.next(), Some(String::from("ipsum")));
2243     /// assert_eq!(lines_iter.next(), Some(String::from("dolor")));
2244     /// assert_eq!(lines_iter.next(), None);
2245     /// ```
2246     ///
2247     /// # Errors
2248     ///
2249     /// Each line of the iterator has the same error semantics as [`BufRead::read_line`].
2250     #[stable(feature = "rust1", since = "1.0.0")]
2251     fn lines(self) -> Lines<Self>
2252     where
2253         Self: Sized,
2254     {
2255         Lines { buf: self }
2256     }
2257 }
2258
2259 /// Adapter to chain together two readers.
2260 ///
2261 /// This struct is generally created by calling [`chain`] on a reader.
2262 /// Please see the documentation of [`chain`] for more details.
2263 ///
2264 /// [`chain`]: Read::chain
2265 #[stable(feature = "rust1", since = "1.0.0")]
2266 #[derive(Debug)]
2267 pub struct Chain<T, U> {
2268     first: T,
2269     second: U,
2270     done_first: bool,
2271 }
2272
2273 impl<T, U> Chain<T, U> {
2274     /// Consumes the `Chain`, returning the wrapped readers.
2275     ///
2276     /// # Examples
2277     ///
2278     /// ```no_run
2279     /// use std::io;
2280     /// use std::io::prelude::*;
2281     /// use std::fs::File;
2282     ///
2283     /// fn main() -> io::Result<()> {
2284     ///     let mut foo_file = File::open("foo.txt")?;
2285     ///     let mut bar_file = File::open("bar.txt")?;
2286     ///
2287     ///     let chain = foo_file.chain(bar_file);
2288     ///     let (foo_file, bar_file) = chain.into_inner();
2289     ///     Ok(())
2290     /// }
2291     /// ```
2292     #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2293     pub fn into_inner(self) -> (T, U) {
2294         (self.first, self.second)
2295     }
2296
2297     /// Gets references to the underlying readers in this `Chain`.
2298     ///
2299     /// # Examples
2300     ///
2301     /// ```no_run
2302     /// use std::io;
2303     /// use std::io::prelude::*;
2304     /// use std::fs::File;
2305     ///
2306     /// fn main() -> io::Result<()> {
2307     ///     let mut foo_file = File::open("foo.txt")?;
2308     ///     let mut bar_file = File::open("bar.txt")?;
2309     ///
2310     ///     let chain = foo_file.chain(bar_file);
2311     ///     let (foo_file, bar_file) = chain.get_ref();
2312     ///     Ok(())
2313     /// }
2314     /// ```
2315     #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2316     pub fn get_ref(&self) -> (&T, &U) {
2317         (&self.first, &self.second)
2318     }
2319
2320     /// Gets mutable references to the underlying readers in this `Chain`.
2321     ///
2322     /// Care should be taken to avoid modifying the internal I/O state of the
2323     /// underlying readers as doing so may corrupt the internal state of this
2324     /// `Chain`.
2325     ///
2326     /// # Examples
2327     ///
2328     /// ```no_run
2329     /// use std::io;
2330     /// use std::io::prelude::*;
2331     /// use std::fs::File;
2332     ///
2333     /// fn main() -> io::Result<()> {
2334     ///     let mut foo_file = File::open("foo.txt")?;
2335     ///     let mut bar_file = File::open("bar.txt")?;
2336     ///
2337     ///     let mut chain = foo_file.chain(bar_file);
2338     ///     let (foo_file, bar_file) = chain.get_mut();
2339     ///     Ok(())
2340     /// }
2341     /// ```
2342     #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2343     pub fn get_mut(&mut self) -> (&mut T, &mut U) {
2344         (&mut self.first, &mut self.second)
2345     }
2346 }
2347
2348 #[stable(feature = "rust1", since = "1.0.0")]
2349 impl<T: Read, U: Read> Read for Chain<T, U> {
2350     fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
2351         if !self.done_first {
2352             match self.first.read(buf)? {
2353                 0 if !buf.is_empty() => self.done_first = true,
2354                 n => return Ok(n),
2355             }
2356         }
2357         self.second.read(buf)
2358     }
2359
2360     fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize> {
2361         if !self.done_first {
2362             match self.first.read_vectored(bufs)? {
2363                 0 if bufs.iter().any(|b| !b.is_empty()) => self.done_first = true,
2364                 n => return Ok(n),
2365             }
2366         }
2367         self.second.read_vectored(bufs)
2368     }
2369 }
2370
2371 #[stable(feature = "chain_bufread", since = "1.9.0")]
2372 impl<T: BufRead, U: BufRead> BufRead for Chain<T, U> {
2373     fn fill_buf(&mut self) -> Result<&[u8]> {
2374         if !self.done_first {
2375             match self.first.fill_buf()? {
2376                 buf if buf.is_empty() => {
2377                     self.done_first = true;
2378                 }
2379                 buf => return Ok(buf),
2380             }
2381         }
2382         self.second.fill_buf()
2383     }
2384
2385     fn consume(&mut self, amt: usize) {
2386         if !self.done_first { self.first.consume(amt) } else { self.second.consume(amt) }
2387     }
2388 }
2389
2390 impl<T, U> SizeHint for Chain<T, U> {
2391     #[inline]
2392     fn lower_bound(&self) -> usize {
2393         SizeHint::lower_bound(&self.first) + SizeHint::lower_bound(&self.second)
2394     }
2395
2396     #[inline]
2397     fn upper_bound(&self) -> Option<usize> {
2398         match (SizeHint::upper_bound(&self.first), SizeHint::upper_bound(&self.second)) {
2399             (Some(first), Some(second)) => first.checked_add(second),
2400             _ => None,
2401         }
2402     }
2403 }
2404
2405 /// Reader adapter which limits the bytes read from an underlying reader.
2406 ///
2407 /// This struct is generally created by calling [`take`] on a reader.
2408 /// Please see the documentation of [`take`] for more details.
2409 ///
2410 /// [`take`]: Read::take
2411 #[stable(feature = "rust1", since = "1.0.0")]
2412 #[derive(Debug)]
2413 pub struct Take<T> {
2414     inner: T,
2415     limit: u64,
2416 }
2417
2418 impl<T> Take<T> {
2419     /// Returns the number of bytes that can be read before this instance will
2420     /// return EOF.
2421     ///
2422     /// # Note
2423     ///
2424     /// This instance may reach `EOF` after reading fewer bytes than indicated by
2425     /// this method if the underlying [`Read`] instance reaches EOF.
2426     ///
2427     /// # Examples
2428     ///
2429     /// ```no_run
2430     /// use std::io;
2431     /// use std::io::prelude::*;
2432     /// use std::fs::File;
2433     ///
2434     /// fn main() -> io::Result<()> {
2435     ///     let f = File::open("foo.txt")?;
2436     ///
2437     ///     // read at most five bytes
2438     ///     let handle = f.take(5);
2439     ///
2440     ///     println!("limit: {}", handle.limit());
2441     ///     Ok(())
2442     /// }
2443     /// ```
2444     #[stable(feature = "rust1", since = "1.0.0")]
2445     pub fn limit(&self) -> u64 {
2446         self.limit
2447     }
2448
2449     /// Sets the number of bytes that can be read before this instance will
2450     /// return EOF. This is the same as constructing a new `Take` instance, so
2451     /// the amount of bytes read and the previous limit value don't matter when
2452     /// calling this method.
2453     ///
2454     /// # Examples
2455     ///
2456     /// ```no_run
2457     /// use std::io;
2458     /// use std::io::prelude::*;
2459     /// use std::fs::File;
2460     ///
2461     /// fn main() -> io::Result<()> {
2462     ///     let f = File::open("foo.txt")?;
2463     ///
2464     ///     // read at most five bytes
2465     ///     let mut handle = f.take(5);
2466     ///     handle.set_limit(10);
2467     ///
2468     ///     assert_eq!(handle.limit(), 10);
2469     ///     Ok(())
2470     /// }
2471     /// ```
2472     #[stable(feature = "take_set_limit", since = "1.27.0")]
2473     pub fn set_limit(&mut self, limit: u64) {
2474         self.limit = limit;
2475     }
2476
2477     /// Consumes the `Take`, returning the wrapped reader.
2478     ///
2479     /// # Examples
2480     ///
2481     /// ```no_run
2482     /// use std::io;
2483     /// use std::io::prelude::*;
2484     /// use std::fs::File;
2485     ///
2486     /// fn main() -> io::Result<()> {
2487     ///     let mut file = File::open("foo.txt")?;
2488     ///
2489     ///     let mut buffer = [0; 5];
2490     ///     let mut handle = file.take(5);
2491     ///     handle.read(&mut buffer)?;
2492     ///
2493     ///     let file = handle.into_inner();
2494     ///     Ok(())
2495     /// }
2496     /// ```
2497     #[stable(feature = "io_take_into_inner", since = "1.15.0")]
2498     pub fn into_inner(self) -> T {
2499         self.inner
2500     }
2501
2502     /// Gets a reference to the underlying reader.
2503     ///
2504     /// # Examples
2505     ///
2506     /// ```no_run
2507     /// use std::io;
2508     /// use std::io::prelude::*;
2509     /// use std::fs::File;
2510     ///
2511     /// fn main() -> io::Result<()> {
2512     ///     let mut file = File::open("foo.txt")?;
2513     ///
2514     ///     let mut buffer = [0; 5];
2515     ///     let mut handle = file.take(5);
2516     ///     handle.read(&mut buffer)?;
2517     ///
2518     ///     let file = handle.get_ref();
2519     ///     Ok(())
2520     /// }
2521     /// ```
2522     #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2523     pub fn get_ref(&self) -> &T {
2524         &self.inner
2525     }
2526
2527     /// Gets a mutable reference to the underlying reader.
2528     ///
2529     /// Care should be taken to avoid modifying the internal I/O state of the
2530     /// underlying reader as doing so may corrupt the internal limit of this
2531     /// `Take`.
2532     ///
2533     /// # Examples
2534     ///
2535     /// ```no_run
2536     /// use std::io;
2537     /// use std::io::prelude::*;
2538     /// use std::fs::File;
2539     ///
2540     /// fn main() -> io::Result<()> {
2541     ///     let mut file = File::open("foo.txt")?;
2542     ///
2543     ///     let mut buffer = [0; 5];
2544     ///     let mut handle = file.take(5);
2545     ///     handle.read(&mut buffer)?;
2546     ///
2547     ///     let file = handle.get_mut();
2548     ///     Ok(())
2549     /// }
2550     /// ```
2551     #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2552     pub fn get_mut(&mut self) -> &mut T {
2553         &mut self.inner
2554     }
2555 }
2556
2557 #[stable(feature = "rust1", since = "1.0.0")]
2558 impl<T: Read> Read for Take<T> {
2559     fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
2560         // Don't call into inner reader at all at EOF because it may still block
2561         if self.limit == 0 {
2562             return Ok(0);
2563         }
2564
2565         let max = cmp::min(buf.len() as u64, self.limit) as usize;
2566         let n = self.inner.read(&mut buf[..max])?;
2567         self.limit -= n as u64;
2568         Ok(n)
2569     }
2570
2571     fn read_buf(&mut self, buf: &mut ReadBuf<'_>) -> Result<()> {
2572         // Don't call into inner reader at all at EOF because it may still block
2573         if self.limit == 0 {
2574             return Ok(());
2575         }
2576
2577         let prev_filled = buf.filled_len();
2578
2579         if self.limit <= buf.remaining() as u64 {
2580             // if we just use an as cast to convert, limit may wrap around on a 32 bit target
2581             let limit = cmp::min(self.limit, usize::MAX as u64) as usize;
2582
2583             let extra_init = cmp::min(limit as usize, buf.initialized_len() - buf.filled_len());
2584
2585             // SAFETY: no uninit data is written to ibuf
2586             let ibuf = unsafe { &mut buf.unfilled_mut()[..limit] };
2587
2588             let mut sliced_buf = ReadBuf::uninit(ibuf);
2589
2590             // SAFETY: extra_init bytes of ibuf are known to be initialized
2591             unsafe {
2592                 sliced_buf.assume_init(extra_init);
2593             }
2594
2595             self.inner.read_buf(&mut sliced_buf)?;
2596
2597             let new_init = sliced_buf.initialized_len();
2598             let filled = sliced_buf.filled_len();
2599
2600             // sliced_buf / ibuf must drop here
2601
2602             // SAFETY: new_init bytes of buf's unfilled buffer have been initialized
2603             unsafe {
2604                 buf.assume_init(new_init);
2605             }
2606
2607             buf.add_filled(filled);
2608
2609             self.limit -= filled as u64;
2610         } else {
2611             self.inner.read_buf(buf)?;
2612
2613             //inner may unfill
2614             self.limit -= buf.filled_len().saturating_sub(prev_filled) as u64;
2615         }
2616
2617         Ok(())
2618     }
2619 }
2620
2621 #[stable(feature = "rust1", since = "1.0.0")]
2622 impl<T: BufRead> BufRead for Take<T> {
2623     fn fill_buf(&mut self) -> Result<&[u8]> {
2624         // Don't call into inner reader at all at EOF because it may still block
2625         if self.limit == 0 {
2626             return Ok(&[]);
2627         }
2628
2629         let buf = self.inner.fill_buf()?;
2630         let cap = cmp::min(buf.len() as u64, self.limit) as usize;
2631         Ok(&buf[..cap])
2632     }
2633
2634     fn consume(&mut self, amt: usize) {
2635         // Don't let callers reset the limit by passing an overlarge value
2636         let amt = cmp::min(amt as u64, self.limit) as usize;
2637         self.limit -= amt as u64;
2638         self.inner.consume(amt);
2639     }
2640 }
2641
2642 impl<T> SizeHint for Take<T> {
2643     #[inline]
2644     fn lower_bound(&self) -> usize {
2645         cmp::min(SizeHint::lower_bound(&self.inner) as u64, self.limit) as usize
2646     }
2647
2648     #[inline]
2649     fn upper_bound(&self) -> Option<usize> {
2650         match SizeHint::upper_bound(&self.inner) {
2651             Some(upper_bound) => Some(cmp::min(upper_bound as u64, self.limit) as usize),
2652             None => self.limit.try_into().ok(),
2653         }
2654     }
2655 }
2656
2657 /// An iterator over `u8` values of a reader.
2658 ///
2659 /// This struct is generally created by calling [`bytes`] on a reader.
2660 /// Please see the documentation of [`bytes`] for more details.
2661 ///
2662 /// [`bytes`]: Read::bytes
2663 #[stable(feature = "rust1", since = "1.0.0")]
2664 #[derive(Debug)]
2665 pub struct Bytes<R> {
2666     inner: R,
2667 }
2668
2669 #[stable(feature = "rust1", since = "1.0.0")]
2670 impl<R: Read> Iterator for Bytes<R> {
2671     type Item = Result<u8>;
2672
2673     fn next(&mut self) -> Option<Result<u8>> {
2674         let mut byte = 0;
2675         loop {
2676             return match self.inner.read(slice::from_mut(&mut byte)) {
2677                 Ok(0) => None,
2678                 Ok(..) => Some(Ok(byte)),
2679                 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
2680                 Err(e) => Some(Err(e)),
2681             };
2682         }
2683     }
2684
2685     fn size_hint(&self) -> (usize, Option<usize>) {
2686         SizeHint::size_hint(&self.inner)
2687     }
2688 }
2689
2690 trait SizeHint {
2691     fn lower_bound(&self) -> usize;
2692
2693     fn upper_bound(&self) -> Option<usize>;
2694
2695     fn size_hint(&self) -> (usize, Option<usize>) {
2696         (self.lower_bound(), self.upper_bound())
2697     }
2698 }
2699
2700 impl<T> SizeHint for T {
2701     #[inline]
2702     default fn lower_bound(&self) -> usize {
2703         0
2704     }
2705
2706     #[inline]
2707     default fn upper_bound(&self) -> Option<usize> {
2708         None
2709     }
2710 }
2711
2712 impl<T> SizeHint for &mut T {
2713     #[inline]
2714     fn lower_bound(&self) -> usize {
2715         SizeHint::lower_bound(*self)
2716     }
2717
2718     #[inline]
2719     fn upper_bound(&self) -> Option<usize> {
2720         SizeHint::upper_bound(*self)
2721     }
2722 }
2723
2724 impl<T> SizeHint for Box<T> {
2725     #[inline]
2726     fn lower_bound(&self) -> usize {
2727         SizeHint::lower_bound(&**self)
2728     }
2729
2730     #[inline]
2731     fn upper_bound(&self) -> Option<usize> {
2732         SizeHint::upper_bound(&**self)
2733     }
2734 }
2735
2736 impl SizeHint for &[u8] {
2737     #[inline]
2738     fn lower_bound(&self) -> usize {
2739         self.len()
2740     }
2741
2742     #[inline]
2743     fn upper_bound(&self) -> Option<usize> {
2744         Some(self.len())
2745     }
2746 }
2747
2748 /// An iterator over the contents of an instance of `BufRead` split on a
2749 /// particular byte.
2750 ///
2751 /// This struct is generally created by calling [`split`] on a `BufRead`.
2752 /// Please see the documentation of [`split`] for more details.
2753 ///
2754 /// [`split`]: BufRead::split
2755 #[stable(feature = "rust1", since = "1.0.0")]
2756 #[derive(Debug)]
2757 pub struct Split<B> {
2758     buf: B,
2759     delim: u8,
2760 }
2761
2762 #[stable(feature = "rust1", since = "1.0.0")]
2763 impl<B: BufRead> Iterator for Split<B> {
2764     type Item = Result<Vec<u8>>;
2765
2766     fn next(&mut self) -> Option<Result<Vec<u8>>> {
2767         let mut buf = Vec::new();
2768         match self.buf.read_until(self.delim, &mut buf) {
2769             Ok(0) => None,
2770             Ok(_n) => {
2771                 if buf[buf.len() - 1] == self.delim {
2772                     buf.pop();
2773                 }
2774                 Some(Ok(buf))
2775             }
2776             Err(e) => Some(Err(e)),
2777         }
2778     }
2779 }
2780
2781 /// An iterator over the lines of an instance of `BufRead`.
2782 ///
2783 /// This struct is generally created by calling [`lines`] on a `BufRead`.
2784 /// Please see the documentation of [`lines`] for more details.
2785 ///
2786 /// [`lines`]: BufRead::lines
2787 #[stable(feature = "rust1", since = "1.0.0")]
2788 #[derive(Debug)]
2789 pub struct Lines<B> {
2790     buf: B,
2791 }
2792
2793 #[stable(feature = "rust1", since = "1.0.0")]
2794 impl<B: BufRead> Iterator for Lines<B> {
2795     type Item = Result<String>;
2796
2797     fn next(&mut self) -> Option<Result<String>> {
2798         let mut buf = String::new();
2799         match self.buf.read_line(&mut buf) {
2800             Ok(0) => None,
2801             Ok(_n) => {
2802                 if buf.ends_with('\n') {
2803                     buf.pop();
2804                     if buf.ends_with('\r') {
2805                         buf.pop();
2806                     }
2807                 }
2808                 Some(Ok(buf))
2809             }
2810             Err(e) => Some(Err(e)),
2811         }
2812     }
2813 }