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