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