Skip to main content

std/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//! ## I/O Safety
242//!
243//! Rust follows an I/O safety discipline that is comparable to its memory safety discipline. This
244//! means that file descriptors can be *exclusively owned*. (Here, "file descriptor" is meant to
245//! subsume similar concepts that exist across a wide range of operating systems even if they might
246//! use a different name, such as "handle".) An exclusively owned file descriptor is one that no
247//! other code is allowed to access in any way, but the owner is allowed to access and even close
248//! it any time. A type that owns its file descriptor should usually close it in its `drop`
249//! function. Types like [`File`] own their file descriptor. Similarly, file descriptors
250//! can be *borrowed*, granting the temporary right to perform operations on this file descriptor.
251//! This indicates that the file descriptor will not be closed for the lifetime of the borrow, but
252//! it does *not* imply any right to close this file descriptor, since it will likely be owned by
253//! someone else.
254//!
255//! The platform-specific parts of the Rust standard library expose types that reflect these
256//! concepts, see [`os::unix`] and [`os::windows`].
257//!
258//! To uphold I/O safety, it is crucial that no code acts on file descriptors it does not own or
259//! borrow, and no code closes file descriptors it does not own. In other words, a safe function
260//! that takes a regular integer, treats it as a file descriptor, and acts on it, is *unsound*.
261//!
262//! Not upholding I/O safety and acting on a file descriptor without proof of ownership can lead to
263//! misbehavior and even Undefined Behavior in code that relies on ownership of its file
264//! descriptors: a closed file descriptor could be re-allocated, so the original owner of that file
265//! descriptor is now working on the wrong file. Some code might even rely on fully encapsulating
266//! its file descriptors with no operations being performed by any other part of the program.
267//!
268//! Note that exclusive ownership of a file descriptor does *not* imply exclusive ownership of the
269//! underlying kernel object that the file descriptor references (also called "open file description" on
270//! some operating systems). File descriptors basically work like [`Arc`]: when you receive an owned
271//! file descriptor, you cannot know whether there are any other file descriptors that reference the
272//! same kernel object. However, when you create a new kernel object, you know that you are holding
273//! the only reference to it. Just be careful not to lend it to anyone, since they can obtain a
274//! clone and then you can no longer know what the reference count is! In that sense, [`OwnedFd`] is
275//! like `Arc` and [`BorrowedFd<'a>`] is like `&'a Arc` (and similar for the Windows types). In
276//! particular, given a `BorrowedFd<'a>`, you are not allowed to close the file descriptor -- just
277//! like how, given a `&'a Arc`, you are not allowed to decrement the reference count and
278//! potentially free the underlying object. There is no equivalent to `Box` for file descriptors in
279//! the standard library (that would be a type that guarantees that the reference count is `1`),
280//! however, it would be possible for a crate to define a type with those semantics.
281//!
282//! [`File`]: crate::fs::File
283//! [`TcpStream`]: crate::net::TcpStream
284//! [`io::stdout`]: stdout
285//! [`io::Result`]: self::Result
286//! [`?` operator]: ../../book/appendix-02-operators.html
287//! [`Result`]: crate::result::Result
288//! [`.unwrap()`]: crate::result::Result::unwrap
289//! [`os::unix`]: ../os/unix/io/index.html
290//! [`os::windows`]: ../os/windows/io/index.html
291//! [`OwnedFd`]: ../os/fd/struct.OwnedFd.html
292//! [`BorrowedFd<'a>`]: ../os/fd/struct.BorrowedFd.html
293//! [`Arc`]: crate::sync::Arc
294
295#![stable(feature = "rust1", since = "1.0.0")]
296
297#[cfg(test)]
298mod tests;
299
300#[unstable(feature = "read_buf", issue = "78485")]
301pub use core::io::{BorrowedBuf, BorrowedCursor};
302use core::slice::memchr;
303
304#[stable(feature = "bufwriter_into_parts", since = "1.56.0")]
305pub use self::buffered::WriterPanicked;
306#[unstable(feature = "raw_os_error_ty", issue = "107792")]
307pub use self::error::RawOsError;
308#[doc(hidden)]
309#[unstable(feature = "io_const_error_internals", issue = "none")]
310pub use self::error::SimpleMessage;
311#[unstable(feature = "io_const_error", issue = "133448")]
312pub use self::error::const_error;
313#[stable(feature = "anonymous_pipe", since = "1.87.0")]
314pub use self::pipe::{PipeReader, PipeWriter, pipe};
315#[stable(feature = "is_terminal", since = "1.70.0")]
316pub use self::stdio::IsTerminal;
317pub(crate) use self::stdio::attempt_print_to_stderr;
318#[unstable(feature = "print_internals", issue = "none")]
319#[doc(hidden)]
320pub use self::stdio::{_eprint, _print};
321#[unstable(feature = "internal_output_capture", issue = "none")]
322#[doc(no_inline, hidden)]
323pub use self::stdio::{set_output_capture, try_set_output_capture};
324#[stable(feature = "rust1", since = "1.0.0")]
325pub use self::{
326    buffered::{BufReader, BufWriter, IntoInnerError, LineWriter},
327    copy::copy,
328    cursor::Cursor,
329    error::{Error, ErrorKind, Result},
330    stdio::{Stderr, StderrLock, Stdin, StdinLock, Stdout, StdoutLock, stderr, stdin, stdout},
331    util::{Empty, Repeat, Sink, empty, repeat, sink},
332};
333use crate::mem::{MaybeUninit, take};
334use crate::ops::{Deref, DerefMut};
335use crate::{cmp, fmt, slice, str, sys};
336
337mod buffered;
338pub(crate) mod copy;
339mod cursor;
340mod error;
341mod impls;
342mod pipe;
343pub mod prelude;
344mod stdio;
345mod util;
346
347const DEFAULT_BUF_SIZE: usize = crate::sys::io::DEFAULT_BUF_SIZE;
348
349pub(crate) use stdio::cleanup;
350
351struct Guard<'a> {
352    buf: &'a mut Vec<u8>,
353    len: usize,
354}
355
356impl Drop for Guard<'_> {
357    fn drop(&mut self) {
358        unsafe {
359            self.buf.set_len(self.len);
360        }
361    }
362}
363
364// Several `read_to_string` and `read_line` methods in the standard library will
365// append data into a `String` buffer, but we need to be pretty careful when
366// doing this. The implementation will just call `.as_mut_vec()` and then
367// delegate to a byte-oriented reading method, but we must ensure that when
368// returning we never leave `buf` in a state such that it contains invalid UTF-8
369// in its bounds.
370//
371// To this end, we use an RAII guard (to protect against panics) which updates
372// the length of the string when it is dropped. This guard initially truncates
373// the string to the prior length and only after we've validated that the
374// new contents are valid UTF-8 do we allow it to set a longer length.
375//
376// The unsafety in this function is twofold:
377//
378// 1. We're looking at the raw bytes of `buf`, so we take on the burden of UTF-8
379//    checks.
380// 2. We're passing a raw buffer to the function `f`, and it is expected that
381//    the function only *appends* bytes to the buffer. We'll get undefined
382//    behavior if existing bytes are overwritten to have non-UTF-8 data.
383pub(crate) unsafe fn append_to_string<F>(buf: &mut String, f: F) -> Result<usize>
384where
385    F: FnOnce(&mut Vec<u8>) -> Result<usize>,
386{
387    let mut g = Guard { len: buf.len(), buf: unsafe { buf.as_mut_vec() } };
388    let ret = f(g.buf);
389
390    // SAFETY: the caller promises to only append data to `buf`
391    let appended = unsafe { g.buf.get_unchecked(g.len..) };
392    if str::from_utf8(appended).is_err() {
393        ret.and_then(|_| Err(Error::INVALID_UTF8))
394    } else {
395        g.len = g.buf.len();
396        ret
397    }
398}
399
400// Here we must serve many masters with conflicting goals:
401//
402// - avoid allocating unless necessary
403// - avoid overallocating if we know the exact size (#89165)
404// - avoid passing large buffers to readers that always initialize the free capacity if they perform short reads (#23815, #23820)
405// - pass large buffers to readers that do not initialize the spare capacity. this can amortize per-call overheads
406// - and finally pass not-too-small and not-too-large buffers to Windows read APIs because they manage to suffer from both problems
407//   at the same time, i.e. small reads suffer from syscall overhead, all reads incur costs proportional to buffer size (#110650)
408//
409pub(crate) fn default_read_to_end<R: Read + ?Sized>(
410    r: &mut R,
411    buf: &mut Vec<u8>,
412    size_hint: Option<usize>,
413) -> Result<usize> {
414    let start_len = buf.len();
415    let start_cap = buf.capacity();
416    // Optionally limit the maximum bytes read on each iteration.
417    // This adds an arbitrary fiddle factor to allow for more data than we expect.
418    let mut max_read_size = size_hint
419        .and_then(|s| s.checked_add(1024)?.checked_next_multiple_of(DEFAULT_BUF_SIZE))
420        .unwrap_or(DEFAULT_BUF_SIZE);
421
422    const PROBE_SIZE: usize = 32;
423
424    fn small_probe_read<R: Read + ?Sized>(r: &mut R, buf: &mut Vec<u8>) -> Result<usize> {
425        let mut probe = [0u8; PROBE_SIZE];
426
427        loop {
428            match r.read(&mut probe) {
429                Ok(n) => {
430                    // there is no way to recover from allocation failure here
431                    // because the data has already been read.
432                    buf.extend_from_slice(&probe[..n]);
433                    return Ok(n);
434                }
435                Err(ref e) if e.is_interrupted() => continue,
436                Err(e) => return Err(e),
437            }
438        }
439    }
440
441    // avoid inflating empty/small vecs before we have determined that there's anything to read
442    if (size_hint.is_none() || size_hint == Some(0)) && buf.capacity() - buf.len() < PROBE_SIZE {
443        let read = small_probe_read(r, buf)?;
444
445        if read == 0 {
446            return Ok(0);
447        }
448    }
449
450    loop {
451        if buf.len() == buf.capacity() && buf.capacity() == start_cap {
452            // The buffer might be an exact fit. Let's read into a probe buffer
453            // and see if it returns `Ok(0)`. If so, we've avoided an
454            // unnecessary doubling of the capacity. But if not, append the
455            // probe buffer to the primary buffer and let its capacity grow.
456            let read = small_probe_read(r, buf)?;
457
458            if read == 0 {
459                return Ok(buf.len() - start_len);
460            }
461        }
462
463        if buf.len() == buf.capacity() {
464            // buf is full, need more space
465            buf.try_reserve(PROBE_SIZE)?;
466        }
467
468        let mut spare = buf.spare_capacity_mut();
469        let buf_len = cmp::min(spare.len(), max_read_size);
470        spare = &mut spare[..buf_len];
471        let mut read_buf: BorrowedBuf<'_> = spare.into();
472
473        // Note that we don't track already initialized bytes here, but this is fine
474        // because we explicitly limit the read size
475        let mut cursor = read_buf.unfilled();
476        let result = loop {
477            match r.read_buf(cursor.reborrow()) {
478                Err(e) if e.is_interrupted() => continue,
479                // Do not stop now in case of error: we might have received both data
480                // and an error
481                res => break res,
482            }
483        };
484
485        let bytes_read = cursor.written();
486        let is_init = read_buf.is_init();
487
488        // SAFETY: BorrowedBuf's invariants mean this much memory is initialized.
489        unsafe {
490            let new_len = bytes_read + buf.len();
491            buf.set_len(new_len);
492        }
493
494        // Now that all data is pushed to the vector, we can fail without data loss
495        result?;
496
497        if bytes_read == 0 {
498            return Ok(buf.len() - start_len);
499        }
500
501        // Use heuristics to determine the max read size if no initial size hint was provided
502        if size_hint.is_none() {
503            // The reader is returning short reads but it doesn't call ensure_init().
504            // In that case we no longer need to restrict read sizes to avoid
505            // initialization costs.
506            // When reading from disk we usually don't get any short reads except at EOF.
507            // So we wait for at least 2 short reads before uncapping the read buffer;
508            // this helps with the Windows issue.
509            if !is_init {
510                max_read_size = usize::MAX;
511            }
512            // we have passed a larger buffer than previously and the
513            // reader still hasn't returned a short read
514            else if buf_len >= max_read_size && bytes_read == buf_len {
515                max_read_size = max_read_size.saturating_mul(2);
516            }
517        }
518    }
519}
520
521pub(crate) fn default_read_to_string<R: Read + ?Sized>(
522    r: &mut R,
523    buf: &mut String,
524    size_hint: Option<usize>,
525) -> Result<usize> {
526    // Note that we do *not* call `r.read_to_end()` here. We are passing
527    // `&mut Vec<u8>` (the raw contents of `buf`) into the `read_to_end`
528    // method to fill it up. An arbitrary implementation could overwrite the
529    // entire contents of the vector, not just append to it (which is what
530    // we are expecting).
531    //
532    // To prevent extraneously checking the UTF-8-ness of the entire buffer
533    // we pass it to our hardcoded `default_read_to_end` implementation which
534    // we know is guaranteed to only read data into the end of the buffer.
535    unsafe { append_to_string(buf, |b| default_read_to_end(r, b, size_hint)) }
536}
537
538pub(crate) fn default_read_vectored<F>(read: F, bufs: &mut [IoSliceMut<'_>]) -> Result<usize>
539where
540    F: FnOnce(&mut [u8]) -> Result<usize>,
541{
542    let buf = bufs.iter_mut().find(|b| !b.is_empty()).map_or(&mut [][..], |b| &mut **b);
543    read(buf)
544}
545
546pub(crate) fn default_write_vectored<F>(write: F, bufs: &[IoSlice<'_>]) -> Result<usize>
547where
548    F: FnOnce(&[u8]) -> Result<usize>,
549{
550    let buf = bufs.iter().find(|b| !b.is_empty()).map_or(&[][..], |b| &**b);
551    write(buf)
552}
553
554pub(crate) fn default_read_exact<R: Read + ?Sized>(this: &mut R, mut buf: &mut [u8]) -> Result<()> {
555    while !buf.is_empty() {
556        match this.read(buf) {
557            Ok(0) => break,
558            Ok(n) => {
559                buf = &mut buf[n..];
560            }
561            Err(ref e) if e.is_interrupted() => {}
562            Err(e) => return Err(e),
563        }
564    }
565    if !buf.is_empty() { Err(Error::READ_EXACT_EOF) } else { Ok(()) }
566}
567
568pub(crate) fn default_read_buf<F>(read: F, mut cursor: BorrowedCursor<'_>) -> Result<()>
569where
570    F: FnOnce(&mut [u8]) -> Result<usize>,
571{
572    let n = read(cursor.ensure_init())?;
573    cursor.advance_checked(n);
574    Ok(())
575}
576
577pub(crate) fn default_read_buf_exact<R: Read + ?Sized>(
578    this: &mut R,
579    mut cursor: BorrowedCursor<'_>,
580) -> Result<()> {
581    while cursor.capacity() > 0 {
582        let prev_written = cursor.written();
583        match this.read_buf(cursor.reborrow()) {
584            Ok(()) => {}
585            Err(e) if e.is_interrupted() => continue,
586            Err(e) => return Err(e),
587        }
588
589        if cursor.written() == prev_written {
590            return Err(Error::READ_EXACT_EOF);
591        }
592    }
593
594    Ok(())
595}
596
597pub(crate) fn default_write_fmt<W: Write + ?Sized>(
598    this: &mut W,
599    args: fmt::Arguments<'_>,
600) -> Result<()> {
601    // Create a shim which translates a `Write` to a `fmt::Write` and saves off
602    // I/O errors, instead of discarding them.
603    struct Adapter<'a, T: ?Sized + 'a> {
604        inner: &'a mut T,
605        error: Result<()>,
606    }
607
608    impl<T: Write + ?Sized> fmt::Write for Adapter<'_, T> {
609        fn write_str(&mut self, s: &str) -> fmt::Result {
610            match self.inner.write_all(s.as_bytes()) {
611                Ok(()) => Ok(()),
612                Err(e) => {
613                    self.error = Err(e);
614                    Err(fmt::Error)
615                }
616            }
617        }
618    }
619
620    let mut output = Adapter { inner: this, error: Ok(()) };
621    match fmt::write(&mut output, args) {
622        Ok(()) => Ok(()),
623        Err(..) => {
624            // Check whether the error came from the underlying `Write`.
625            if output.error.is_err() {
626                output.error
627            } else {
628                // This shouldn't happen: the underlying stream did not error,
629                // but somehow the formatter still errored?
630                panic!(
631                    "a formatting trait implementation returned an error when the underlying stream did not"
632                );
633            }
634        }
635    }
636}
637
638/// The `Read` trait allows for reading bytes from a source.
639///
640/// Implementors of the `Read` trait are called 'readers'.
641///
642/// Readers are defined by one required method, [`read()`]. Each call to [`read()`]
643/// will attempt to pull bytes from this source into a provided buffer. A
644/// number of other methods are implemented in terms of [`read()`], giving
645/// implementors a number of ways to read bytes while only needing to implement
646/// a single method.
647///
648/// Readers are intended to be composable with one another. Many implementors
649/// throughout [`std::io`] take and provide types which implement the `Read`
650/// trait.
651///
652/// Please note that each call to [`read()`] may involve a system call, and
653/// therefore, using something that implements [`BufRead`], such as
654/// [`BufReader`], will be more efficient.
655///
656/// Repeated calls to the reader use the same cursor, so for example
657/// calling `read_to_end` twice on a [`File`] will only return the file's
658/// contents once. It's recommended to first call `rewind()` in that case.
659///
660/// # Examples
661///
662/// [`File`]s implement `Read`:
663///
664/// ```no_run
665/// use std::io;
666/// use std::io::prelude::*;
667/// use std::fs::File;
668///
669/// fn main() -> io::Result<()> {
670///     let mut f = File::open("foo.txt")?;
671///     let mut buffer = [0; 10];
672///
673///     // read up to 10 bytes
674///     f.read(&mut buffer)?;
675///
676///     let mut buffer = Vec::new();
677///     // read the whole file
678///     f.read_to_end(&mut buffer)?;
679///
680///     // read into a String, so that you don't need to do the conversion.
681///     let mut buffer = String::new();
682///     f.read_to_string(&mut buffer)?;
683///
684///     // and more! See the other methods for more details.
685///     Ok(())
686/// }
687/// ```
688///
689/// Read from [`&str`] because [`&[u8]`][prim@slice] implements `Read`:
690///
691/// ```no_run
692/// # use std::io;
693/// use std::io::prelude::*;
694///
695/// fn main() -> io::Result<()> {
696///     let mut b = "This string will be read".as_bytes();
697///     let mut buffer = [0; 10];
698///
699///     // read up to 10 bytes
700///     b.read(&mut buffer)?;
701///
702///     // etc... it works exactly as a File does!
703///     Ok(())
704/// }
705/// ```
706///
707/// [`read()`]: Read::read
708/// [`&str`]: prim@str
709/// [`std::io`]: self
710/// [`File`]: crate::fs::File
711#[stable(feature = "rust1", since = "1.0.0")]
712#[doc(notable_trait)]
713#[cfg_attr(not(test), rustc_diagnostic_item = "IoRead")]
714pub trait Read {
715    /// Pull some bytes from this source into the specified buffer, returning
716    /// how many bytes were read.
717    ///
718    /// This function does not provide any guarantees about whether it blocks
719    /// waiting for data, but if an object needs to block for a read and cannot,
720    /// it will typically signal this via an [`Err`] return value.
721    ///
722    /// If the return value of this method is [`Ok(n)`], then implementations must
723    /// guarantee that `0 <= n <= buf.len()`. A nonzero `n` value indicates
724    /// that the buffer `buf` has been filled in with `n` bytes of data from this
725    /// source. If `n` is `0`, then it can indicate one of two scenarios:
726    ///
727    /// 1. This reader has reached its "end of file" and will likely no longer
728    ///    be able to produce bytes. Note that this does not mean that the
729    ///    reader will *always* no longer be able to produce bytes. As an example,
730    ///    on Linux, this method will call the `recv` syscall for a [`TcpStream`],
731    ///    where returning zero indicates the connection was shut down correctly. While
732    ///    for [`File`], it is possible to reach the end of file and get zero as result,
733    ///    but if more data is appended to the file, future calls to `read` will return
734    ///    more data.
735    /// 2. The buffer specified was 0 bytes in length.
736    ///
737    /// It is not an error if the returned value `n` is smaller than the buffer size,
738    /// even when the reader is not at the end of the stream yet.
739    /// This may happen for example because fewer bytes are actually available right now
740    /// (e. g. being close to end-of-file) or because read() was interrupted by a signal.
741    ///
742    /// As this trait is safe to implement, callers in unsafe code cannot rely on
743    /// `n <= buf.len()` for safety.
744    /// Extra care needs to be taken when `unsafe` functions are used to access the read bytes.
745    /// Callers have to ensure that no unchecked out-of-bounds accesses are possible even if
746    /// `n > buf.len()`.
747    ///
748    /// *Implementations* of this method can make no assumptions about the contents of `buf` when
749    /// this function is called. It is recommended that implementations only write data to `buf`
750    /// instead of reading its contents.
751    ///
752    /// Correspondingly, however, *callers* of this method in unsafe code must not assume
753    /// any guarantees about how the implementation uses `buf`. The trait is safe to implement,
754    /// so it is possible that the code that's supposed to write to the buffer might also read
755    /// from it. It is your responsibility to make sure that `buf` is initialized
756    /// before calling `read`. Calling `read` with an uninitialized `buf` (of the kind one
757    /// obtains via [`MaybeUninit<T>`]) is not safe, and can lead to undefined behavior.
758    ///
759    /// [`MaybeUninit<T>`]: crate::mem::MaybeUninit
760    ///
761    /// # Errors
762    ///
763    /// If this function encounters any form of I/O or other error, an error
764    /// variant will be returned. If an error is returned then it must be
765    /// guaranteed that no bytes were read.
766    ///
767    /// An error of the [`ErrorKind::Interrupted`] kind is non-fatal and the read
768    /// operation should be retried if there is nothing else to do.
769    ///
770    /// # Examples
771    ///
772    /// [`File`]s implement `Read`:
773    ///
774    /// [`Ok(n)`]: Ok
775    /// [`File`]: crate::fs::File
776    /// [`TcpStream`]: crate::net::TcpStream
777    ///
778    /// ```no_run
779    /// use std::io;
780    /// use std::io::prelude::*;
781    /// use std::fs::File;
782    ///
783    /// fn main() -> io::Result<()> {
784    ///     let mut f = File::open("foo.txt")?;
785    ///     let mut buffer = [0; 10];
786    ///
787    ///     // read up to 10 bytes
788    ///     let n = f.read(&mut buffer[..])?;
789    ///
790    ///     println!("The bytes: {:?}", &buffer[..n]);
791    ///     Ok(())
792    /// }
793    /// ```
794    #[stable(feature = "rust1", since = "1.0.0")]
795    fn read(&mut self, buf: &mut [u8]) -> Result<usize>;
796
797    /// Like `read`, except that it reads into a slice of buffers.
798    ///
799    /// Data is copied to fill each buffer in order, with the final buffer
800    /// written to possibly being only partially filled. This method must
801    /// behave equivalently to a single call to `read` with concatenated
802    /// buffers.
803    ///
804    /// The default implementation calls `read` with either the first nonempty
805    /// buffer provided, or an empty one if none exists.
806    #[stable(feature = "iovec", since = "1.36.0")]
807    fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize> {
808        default_read_vectored(|b| self.read(b), bufs)
809    }
810
811    /// Determines if this `Read`er has an efficient `read_vectored`
812    /// implementation.
813    ///
814    /// If a `Read`er does not override the default `read_vectored`
815    /// implementation, code using it may want to avoid the method all together
816    /// and coalesce writes into a single buffer for higher performance.
817    ///
818    /// The default implementation returns `false`.
819    #[unstable(feature = "can_vector", issue = "69941")]
820    fn is_read_vectored(&self) -> bool {
821        false
822    }
823
824    /// Reads all bytes until EOF in this source, placing them into `buf`.
825    ///
826    /// All bytes read from this source will be appended to the specified buffer
827    /// `buf`. This function will continuously call [`read()`] to append more data to
828    /// `buf` until [`read()`] returns either [`Ok(0)`] or an error of
829    /// non-[`ErrorKind::Interrupted`] kind.
830    ///
831    /// If successful, this function will return the total number of bytes read.
832    ///
833    /// # Errors
834    ///
835    /// If this function encounters an error of the kind
836    /// [`ErrorKind::Interrupted`] then the error is ignored and the operation
837    /// will continue.
838    ///
839    /// If any other read error is encountered then this function immediately
840    /// returns. Any bytes which have already been read will be appended to
841    /// `buf`.
842    ///
843    /// # Examples
844    ///
845    /// [`File`]s implement `Read`:
846    ///
847    /// [`read()`]: Read::read
848    /// [`Ok(0)`]: Ok
849    /// [`File`]: crate::fs::File
850    ///
851    /// ```no_run
852    /// use std::io;
853    /// use std::io::prelude::*;
854    /// use std::fs::File;
855    ///
856    /// fn main() -> io::Result<()> {
857    ///     let mut f = File::open("foo.txt")?;
858    ///     let mut buffer = Vec::new();
859    ///
860    ///     // read the whole file
861    ///     f.read_to_end(&mut buffer)?;
862    ///     Ok(())
863    /// }
864    /// ```
865    ///
866    /// (See also the [`std::fs::read`] convenience function for reading from a
867    /// file.)
868    ///
869    /// [`std::fs::read`]: crate::fs::read
870    ///
871    /// ## Implementing `read_to_end`
872    ///
873    /// When implementing the `io::Read` trait, it is recommended to allocate
874    /// memory using [`Vec::try_reserve`]. However, this behavior is not guaranteed
875    /// by all implementations, and `read_to_end` may not handle out-of-memory
876    /// situations gracefully.
877    ///
878    /// ```no_run
879    /// # use std::io::{self, BufRead};
880    /// # struct Example { example_datasource: io::Empty } impl Example {
881    /// # fn get_some_data_for_the_example(&self) -> &'static [u8] { &[] }
882    /// fn read_to_end(&mut self, dest_vec: &mut Vec<u8>) -> io::Result<usize> {
883    ///     let initial_vec_len = dest_vec.len();
884    ///     loop {
885    ///         let src_buf = self.example_datasource.fill_buf()?;
886    ///         if src_buf.is_empty() {
887    ///             break;
888    ///         }
889    ///         dest_vec.try_reserve(src_buf.len())?;
890    ///         dest_vec.extend_from_slice(src_buf);
891    ///
892    ///         // Any irreversible side effects should happen after `try_reserve` succeeds,
893    ///         // to avoid losing data on allocation error.
894    ///         let read = src_buf.len();
895    ///         self.example_datasource.consume(read);
896    ///     }
897    ///     Ok(dest_vec.len() - initial_vec_len)
898    /// }
899    /// # }
900    /// ```
901    ///
902    /// # Usage Notes
903    ///
904    /// `read_to_end` attempts to read a source until EOF, but many sources are continuous streams
905    /// that do not send EOF. In these cases, `read_to_end` will block indefinitely. Standard input
906    /// is one such stream which may be finite if piped, but is typically continuous. For example,
907    /// `cat file | my-rust-program` will correctly terminate with an `EOF` upon closure of cat.
908    /// Reading user input or running programs that remain open indefinitely will never terminate
909    /// the stream with `EOF` (e.g. `yes | my-rust-program`).
910    ///
911    /// Using `.lines()` with a [`BufReader`] or using [`read`] can provide a better solution
912    ///
913    ///[`read`]: Read::read
914    ///
915    /// [`Vec::try_reserve`]: crate::vec::Vec::try_reserve
916    #[stable(feature = "rust1", since = "1.0.0")]
917    fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
918        default_read_to_end(self, buf, None)
919    }
920
921    /// Reads all bytes until EOF in this source, appending them to `buf`.
922    ///
923    /// If successful, this function returns the number of bytes which were read
924    /// and appended to `buf`.
925    ///
926    /// # Errors
927    ///
928    /// If the data in this stream is *not* valid UTF-8 then an error is
929    /// returned and `buf` is unchanged.
930    ///
931    /// See [`read_to_end`] for other error semantics.
932    ///
933    /// [`read_to_end`]: Read::read_to_end
934    ///
935    /// # Examples
936    ///
937    /// [`File`]s implement `Read`:
938    ///
939    /// [`File`]: crate::fs::File
940    ///
941    /// ```no_run
942    /// use std::io;
943    /// use std::io::prelude::*;
944    /// use std::fs::File;
945    ///
946    /// fn main() -> io::Result<()> {
947    ///     let mut f = File::open("foo.txt")?;
948    ///     let mut buffer = String::new();
949    ///
950    ///     f.read_to_string(&mut buffer)?;
951    ///     Ok(())
952    /// }
953    /// ```
954    ///
955    /// (See also the [`std::fs::read_to_string`] convenience function for
956    /// reading from a file.)
957    ///
958    /// # Usage Notes
959    ///
960    /// `read_to_string` attempts to read a source until EOF, but many sources are continuous streams
961    /// that do not send EOF. In these cases, `read_to_string` will block indefinitely. Standard input
962    /// is one such stream which may be finite if piped, but is typically continuous. For example,
963    /// `cat file | my-rust-program` will correctly terminate with an `EOF` upon closure of cat.
964    /// Reading user input or running programs that remain open indefinitely will never terminate
965    /// the stream with `EOF` (e.g. `yes | my-rust-program`).
966    ///
967    /// Using `.lines()` with a [`BufReader`] or using [`read`] can provide a better solution
968    ///
969    ///[`read`]: Read::read
970    ///
971    /// [`std::fs::read_to_string`]: crate::fs::read_to_string
972    #[stable(feature = "rust1", since = "1.0.0")]
973    fn read_to_string(&mut self, buf: &mut String) -> Result<usize> {
974        default_read_to_string(self, buf, None)
975    }
976
977    /// Reads the exact number of bytes required to fill `buf`.
978    ///
979    /// This function reads as many bytes as necessary to completely fill the
980    /// specified buffer `buf`.
981    ///
982    /// *Implementations* of this method can make no assumptions about the contents of `buf` when
983    /// this function is called. It is recommended that implementations only write data to `buf`
984    /// instead of reading its contents. The documentation on [`read`] has a more detailed
985    /// explanation of this subject.
986    ///
987    /// # Errors
988    ///
989    /// If this function encounters an error of the kind
990    /// [`ErrorKind::Interrupted`] then the error is ignored and the operation
991    /// will continue.
992    ///
993    /// If this function encounters an "end of file" before completely filling
994    /// the buffer, it returns an error of the kind [`ErrorKind::UnexpectedEof`].
995    /// The contents of `buf` are unspecified in this case.
996    ///
997    /// If any other read error is encountered then this function immediately
998    /// returns. The contents of `buf` are unspecified in this case.
999    ///
1000    /// If this function returns an error, it is unspecified how many bytes it
1001    /// has read, but it will never read more than would be necessary to
1002    /// completely fill the buffer.
1003    ///
1004    /// # Examples
1005    ///
1006    /// [`File`]s implement `Read`:
1007    ///
1008    /// [`read`]: Read::read
1009    /// [`File`]: crate::fs::File
1010    ///
1011    /// ```no_run
1012    /// use std::io;
1013    /// use std::io::prelude::*;
1014    /// use std::fs::File;
1015    ///
1016    /// fn main() -> io::Result<()> {
1017    ///     let mut f = File::open("foo.txt")?;
1018    ///     let mut buffer = [0; 10];
1019    ///
1020    ///     // read exactly 10 bytes
1021    ///     f.read_exact(&mut buffer)?;
1022    ///     Ok(())
1023    /// }
1024    /// ```
1025    #[stable(feature = "read_exact", since = "1.6.0")]
1026    fn read_exact(&mut self, buf: &mut [u8]) -> Result<()> {
1027        default_read_exact(self, buf)
1028    }
1029
1030    /// Pull some bytes from this source into the specified buffer.
1031    ///
1032    /// This is equivalent to the [`read`](Read::read) method, except that it is passed a [`BorrowedCursor`] rather than `[u8]` to allow use
1033    /// with uninitialized buffers. The new data will be appended to any existing contents of `buf`.
1034    ///
1035    /// The default implementation delegates to `read`.
1036    ///
1037    /// This method makes it possible to return both data and an error but it is advised against.
1038    #[unstable(feature = "read_buf", issue = "78485")]
1039    fn read_buf(&mut self, buf: BorrowedCursor<'_>) -> Result<()> {
1040        default_read_buf(|b| self.read(b), buf)
1041    }
1042
1043    /// Reads the exact number of bytes required to fill `cursor`.
1044    ///
1045    /// This is similar to the [`read_exact`](Read::read_exact) method, except
1046    /// that it is passed a [`BorrowedCursor`] rather than `[u8]` to allow use
1047    /// with uninitialized buffers.
1048    ///
1049    /// # Errors
1050    ///
1051    /// If this function encounters an error of the kind [`ErrorKind::Interrupted`]
1052    /// then the error is ignored and the operation will continue.
1053    ///
1054    /// If this function encounters an "end of file" before completely filling
1055    /// the buffer, it returns an error of the kind [`ErrorKind::UnexpectedEof`].
1056    ///
1057    /// If any other read error is encountered then this function immediately
1058    /// returns.
1059    ///
1060    /// If this function returns an error, all bytes read will be appended to `cursor`.
1061    #[unstable(feature = "read_buf", issue = "78485")]
1062    fn read_buf_exact(&mut self, cursor: BorrowedCursor<'_>) -> Result<()> {
1063        default_read_buf_exact(self, cursor)
1064    }
1065
1066    /// Creates a "by reference" adapter for this instance of `Read`.
1067    ///
1068    /// The returned adapter also implements `Read` and will simply borrow this
1069    /// current reader.
1070    ///
1071    /// # Examples
1072    ///
1073    /// [`File`]s implement `Read`:
1074    ///
1075    /// [`File`]: crate::fs::File
1076    ///
1077    /// ```no_run
1078    /// use std::io;
1079    /// use std::io::Read;
1080    /// use std::fs::File;
1081    ///
1082    /// fn main() -> io::Result<()> {
1083    ///     let mut f = File::open("foo.txt")?;
1084    ///     let mut buffer = Vec::new();
1085    ///     let mut other_buffer = Vec::new();
1086    ///
1087    ///     {
1088    ///         let reference = f.by_ref();
1089    ///
1090    ///         // read at most 5 bytes
1091    ///         reference.take(5).read_to_end(&mut buffer)?;
1092    ///
1093    ///     } // drop our &mut reference so we can use f again
1094    ///
1095    ///     // original file still usable, read the rest
1096    ///     f.read_to_end(&mut other_buffer)?;
1097    ///     Ok(())
1098    /// }
1099    /// ```
1100    #[stable(feature = "rust1", since = "1.0.0")]
1101    fn by_ref(&mut self) -> &mut Self
1102    where
1103        Self: Sized,
1104    {
1105        self
1106    }
1107
1108    /// Transforms this `Read` instance to an [`Iterator`] over its bytes.
1109    ///
1110    /// The returned type implements [`Iterator`] where the [`Item`] is
1111    /// <code>[Result]<[u8], [io::Error]></code>.
1112    /// The yielded item is [`Ok`] if a byte was successfully read and [`Err`]
1113    /// otherwise. EOF is mapped to returning [`None`] from this iterator.
1114    ///
1115    /// The default implementation calls `read` for each byte,
1116    /// which can be very inefficient for data that's not in memory,
1117    /// such as [`File`]. Consider using a [`BufReader`] in such cases.
1118    ///
1119    /// # Examples
1120    ///
1121    /// [`File`]s implement `Read`:
1122    ///
1123    /// [`Item`]: Iterator::Item
1124    /// [`File`]: crate::fs::File "fs::File"
1125    /// [Result]: crate::result::Result "Result"
1126    /// [io::Error]: self::Error "io::Error"
1127    ///
1128    /// ```no_run
1129    /// use std::io;
1130    /// use std::io::prelude::*;
1131    /// use std::io::BufReader;
1132    /// use std::fs::File;
1133    ///
1134    /// fn main() -> io::Result<()> {
1135    ///     let f = BufReader::new(File::open("foo.txt")?);
1136    ///
1137    ///     for byte in f.bytes() {
1138    ///         println!("{}", byte?);
1139    ///     }
1140    ///     Ok(())
1141    /// }
1142    /// ```
1143    #[stable(feature = "rust1", since = "1.0.0")]
1144    fn bytes(self) -> Bytes<Self>
1145    where
1146        Self: Sized,
1147    {
1148        Bytes { inner: self }
1149    }
1150
1151    /// Creates an adapter which will chain this stream with another.
1152    ///
1153    /// The returned `Read` instance will first read all bytes from this object
1154    /// until EOF is encountered. Afterwards the output is equivalent to the
1155    /// output of `next`.
1156    ///
1157    /// # Examples
1158    ///
1159    /// [`File`]s implement `Read`:
1160    ///
1161    /// [`File`]: crate::fs::File
1162    ///
1163    /// ```no_run
1164    /// use std::io;
1165    /// use std::io::prelude::*;
1166    /// use std::fs::File;
1167    ///
1168    /// fn main() -> io::Result<()> {
1169    ///     let f1 = File::open("foo.txt")?;
1170    ///     let f2 = File::open("bar.txt")?;
1171    ///
1172    ///     let mut handle = f1.chain(f2);
1173    ///     let mut buffer = String::new();
1174    ///
1175    ///     // read the value into a String. We could use any Read method here,
1176    ///     // this is just one example.
1177    ///     handle.read_to_string(&mut buffer)?;
1178    ///     Ok(())
1179    /// }
1180    /// ```
1181    #[stable(feature = "rust1", since = "1.0.0")]
1182    fn chain<R: Read>(self, next: R) -> Chain<Self, R>
1183    where
1184        Self: Sized,
1185    {
1186        Chain { first: self, second: next, done_first: false }
1187    }
1188
1189    /// Creates an adapter which will read at most `limit` bytes from it.
1190    ///
1191    /// This function returns a new instance of `Read` which will read at most
1192    /// `limit` bytes, after which it will always return EOF ([`Ok(0)`]). Any
1193    /// read errors will not count towards the number of bytes read and future
1194    /// calls to [`read()`] may succeed.
1195    ///
1196    /// # Examples
1197    ///
1198    /// [`File`]s implement `Read`:
1199    ///
1200    /// [`File`]: crate::fs::File
1201    /// [`Ok(0)`]: Ok
1202    /// [`read()`]: Read::read
1203    ///
1204    /// ```no_run
1205    /// use std::io;
1206    /// use std::io::prelude::*;
1207    /// use std::fs::File;
1208    ///
1209    /// fn main() -> io::Result<()> {
1210    ///     let f = File::open("foo.txt")?;
1211    ///     let mut buffer = [0; 5];
1212    ///
1213    ///     // read at most five bytes
1214    ///     let mut handle = f.take(5);
1215    ///
1216    ///     handle.read(&mut buffer)?;
1217    ///     Ok(())
1218    /// }
1219    /// ```
1220    #[stable(feature = "rust1", since = "1.0.0")]
1221    fn take(self, limit: u64) -> Take<Self>
1222    where
1223        Self: Sized,
1224    {
1225        Take { inner: self, len: limit, limit }
1226    }
1227
1228    /// Read and return a fixed array of bytes from this source.
1229    ///
1230    /// This function uses an array sized based on a const generic size known at compile time. You
1231    /// can specify the size with turbofish (`reader.read_array::<8>()`), or let type inference
1232    /// determine the number of bytes needed based on how the return value gets used. For instance,
1233    /// this function works well with functions like [`u64::from_le_bytes`] to turn an array of
1234    /// bytes into an integer of the same size.
1235    ///
1236    /// Like `read_exact`, if this function encounters an "end of file" before reading the desired
1237    /// number of bytes, it returns an error of the kind [`ErrorKind::UnexpectedEof`].
1238    ///
1239    /// ```
1240    /// #![feature(read_array)]
1241    /// use std::io::Cursor;
1242    /// use std::io::prelude::*;
1243    ///
1244    /// fn main() -> std::io::Result<()> {
1245    ///     let mut buf = Cursor::new([1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3, 2]);
1246    ///     let x = u64::from_le_bytes(buf.read_array()?);
1247    ///     let y = u32::from_be_bytes(buf.read_array()?);
1248    ///     let z = u16::from_be_bytes(buf.read_array()?);
1249    ///     assert_eq!(x, 0x807060504030201);
1250    ///     assert_eq!(y, 0x9080706);
1251    ///     assert_eq!(z, 0x504);
1252    ///     Ok(())
1253    /// }
1254    /// ```
1255    #[unstable(feature = "read_array", issue = "148848")]
1256    fn read_array<const N: usize>(&mut self) -> Result<[u8; N]>
1257    where
1258        Self: Sized,
1259    {
1260        let mut buf = [MaybeUninit::uninit(); N];
1261        let mut borrowed_buf = BorrowedBuf::from(buf.as_mut_slice());
1262        self.read_buf_exact(borrowed_buf.unfilled())?;
1263        // Guard against incorrect `read_buf_exact` implementations.
1264        assert_eq!(borrowed_buf.len(), N);
1265        Ok(unsafe { MaybeUninit::array_assume_init(buf) })
1266    }
1267}
1268
1269/// Reads all bytes from a [reader][Read] into a new [`String`].
1270///
1271/// This is a convenience function for [`Read::read_to_string`]. Using this
1272/// function avoids having to create a variable first and provides more type
1273/// safety since you can only get the buffer out if there were no errors. (If you
1274/// use [`Read::read_to_string`] you have to remember to check whether the read
1275/// succeeded because otherwise your buffer will be empty or only partially full.)
1276///
1277/// # Performance
1278///
1279/// The downside of this function's increased ease of use and type safety is
1280/// that it gives you less control over performance. For example, you can't
1281/// pre-allocate memory like you can using [`String::with_capacity`] and
1282/// [`Read::read_to_string`]. Also, you can't re-use the buffer if an error
1283/// occurs while reading.
1284///
1285/// In many cases, this function's performance will be adequate and the ease of use
1286/// and type safety tradeoffs will be worth it. However, there are cases where you
1287/// need more control over performance, and in those cases you should definitely use
1288/// [`Read::read_to_string`] directly.
1289///
1290/// Note that in some special cases, such as when reading files, this function will
1291/// pre-allocate memory based on the size of the input it is reading. In those
1292/// cases, the performance should be as good as if you had used
1293/// [`Read::read_to_string`] with a manually pre-allocated buffer.
1294///
1295/// # Errors
1296///
1297/// This function forces you to handle errors because the output (the `String`)
1298/// is wrapped in a [`Result`]. See [`Read::read_to_string`] for the errors
1299/// that can occur. If any error occurs, you will get an [`Err`], so you
1300/// don't have to worry about your buffer being empty or partially full.
1301///
1302/// # Examples
1303///
1304/// ```no_run
1305/// # use std::io;
1306/// fn main() -> io::Result<()> {
1307///     let stdin = io::read_to_string(io::stdin())?;
1308///     println!("Stdin was:");
1309///     println!("{stdin}");
1310///     Ok(())
1311/// }
1312/// ```
1313///
1314/// # Usage Notes
1315///
1316/// `read_to_string` attempts to read a source until EOF, but many sources are continuous streams
1317/// that do not send EOF. In these cases, `read_to_string` will block indefinitely. Standard input
1318/// is one such stream which may be finite if piped, but is typically continuous. For example,
1319/// `cat file | my-rust-program` will correctly terminate with an `EOF` upon closure of cat.
1320/// Reading user input or running programs that remain open indefinitely will never terminate
1321/// the stream with `EOF` (e.g. `yes | my-rust-program`).
1322///
1323/// Using `.lines()` with a [`BufReader`] or using [`read`] can provide a better solution
1324///
1325///[`read`]: Read::read
1326///
1327#[stable(feature = "io_read_to_string", since = "1.65.0")]
1328pub fn read_to_string<R: Read>(mut reader: R) -> Result<String> {
1329    let mut buf = String::new();
1330    reader.read_to_string(&mut buf)?;
1331    Ok(buf)
1332}
1333
1334/// A buffer type used with `Read::read_vectored`.
1335///
1336/// It is semantically a wrapper around a `&mut [u8]`, but is guaranteed to be
1337/// ABI compatible with the `iovec` type on Unix platforms and `WSABUF` on
1338/// Windows.
1339#[stable(feature = "iovec", since = "1.36.0")]
1340#[repr(transparent)]
1341pub struct IoSliceMut<'a>(sys::io::IoSliceMut<'a>);
1342
1343#[stable(feature = "iovec_send_sync", since = "1.44.0")]
1344unsafe impl<'a> Send for IoSliceMut<'a> {}
1345
1346#[stable(feature = "iovec_send_sync", since = "1.44.0")]
1347unsafe impl<'a> Sync for IoSliceMut<'a> {}
1348
1349#[stable(feature = "iovec", since = "1.36.0")]
1350impl<'a> fmt::Debug for IoSliceMut<'a> {
1351    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1352        fmt::Debug::fmt(self.0.as_slice(), fmt)
1353    }
1354}
1355
1356impl<'a> IoSliceMut<'a> {
1357    /// Creates a new `IoSliceMut` wrapping a byte slice.
1358    ///
1359    /// # Panics
1360    ///
1361    /// Panics on Windows if the slice is larger than 4GB.
1362    #[stable(feature = "iovec", since = "1.36.0")]
1363    #[inline]
1364    pub fn new(buf: &'a mut [u8]) -> IoSliceMut<'a> {
1365        IoSliceMut(sys::io::IoSliceMut::new(buf))
1366    }
1367
1368    /// Advance the internal cursor of the slice.
1369    ///
1370    /// Also see [`IoSliceMut::advance_slices`] to advance the cursors of
1371    /// multiple buffers.
1372    ///
1373    /// # Panics
1374    ///
1375    /// Panics when trying to advance beyond the end of the slice.
1376    ///
1377    /// # Examples
1378    ///
1379    /// ```
1380    /// use std::io::IoSliceMut;
1381    /// use std::ops::Deref;
1382    ///
1383    /// let mut data = [1; 8];
1384    /// let mut buf = IoSliceMut::new(&mut data);
1385    ///
1386    /// // Mark 3 bytes as read.
1387    /// buf.advance(3);
1388    /// assert_eq!(buf.deref(), [1; 5].as_ref());
1389    /// ```
1390    #[stable(feature = "io_slice_advance", since = "1.81.0")]
1391    #[inline]
1392    pub fn advance(&mut self, n: usize) {
1393        self.0.advance(n)
1394    }
1395
1396    /// Advance a slice of slices.
1397    ///
1398    /// Shrinks the slice to remove any `IoSliceMut`s that are fully advanced over.
1399    /// If the cursor ends up in the middle of an `IoSliceMut`, it is modified
1400    /// to start at that cursor.
1401    ///
1402    /// For example, if we have a slice of two 8-byte `IoSliceMut`s, and we advance by 10 bytes,
1403    /// the result will only include the second `IoSliceMut`, advanced by 2 bytes.
1404    ///
1405    /// # Panics
1406    ///
1407    /// Panics when trying to advance beyond the end of the slices.
1408    ///
1409    /// # Examples
1410    ///
1411    /// ```
1412    /// use std::io::IoSliceMut;
1413    /// use std::ops::Deref;
1414    ///
1415    /// let mut buf1 = [1; 8];
1416    /// let mut buf2 = [2; 16];
1417    /// let mut buf3 = [3; 8];
1418    /// let mut bufs = &mut [
1419    ///     IoSliceMut::new(&mut buf1),
1420    ///     IoSliceMut::new(&mut buf2),
1421    ///     IoSliceMut::new(&mut buf3),
1422    /// ][..];
1423    ///
1424    /// // Mark 10 bytes as read.
1425    /// IoSliceMut::advance_slices(&mut bufs, 10);
1426    /// assert_eq!(bufs[0].deref(), [2; 14].as_ref());
1427    /// assert_eq!(bufs[1].deref(), [3; 8].as_ref());
1428    /// ```
1429    #[stable(feature = "io_slice_advance", since = "1.81.0")]
1430    #[inline]
1431    pub fn advance_slices(bufs: &mut &mut [IoSliceMut<'a>], n: usize) {
1432        // Number of buffers to remove.
1433        let mut remove = 0;
1434        // Remaining length before reaching n.
1435        let mut left = n;
1436        for buf in bufs.iter() {
1437            if let Some(remainder) = left.checked_sub(buf.len()) {
1438                left = remainder;
1439                remove += 1;
1440            } else {
1441                break;
1442            }
1443        }
1444
1445        *bufs = &mut take(bufs)[remove..];
1446        if bufs.is_empty() {
1447            assert!(left == 0, "advancing io slices beyond their length");
1448        } else {
1449            bufs[0].advance(left);
1450        }
1451    }
1452
1453    /// Get the underlying bytes as a mutable slice with the original lifetime.
1454    ///
1455    /// # Examples
1456    ///
1457    /// ```
1458    /// #![feature(io_slice_as_bytes)]
1459    /// use std::io::IoSliceMut;
1460    ///
1461    /// let mut data = *b"abcdef";
1462    /// let io_slice = IoSliceMut::new(&mut data);
1463    /// io_slice.into_slice()[0] = b'A';
1464    ///
1465    /// assert_eq!(&data, b"Abcdef");
1466    /// ```
1467    #[unstable(feature = "io_slice_as_bytes", issue = "132818")]
1468    pub const fn into_slice(self) -> &'a mut [u8] {
1469        self.0.into_slice()
1470    }
1471}
1472
1473#[stable(feature = "iovec", since = "1.36.0")]
1474impl<'a> Deref for IoSliceMut<'a> {
1475    type Target = [u8];
1476
1477    #[inline]
1478    fn deref(&self) -> &[u8] {
1479        self.0.as_slice()
1480    }
1481}
1482
1483#[stable(feature = "iovec", since = "1.36.0")]
1484impl<'a> DerefMut for IoSliceMut<'a> {
1485    #[inline]
1486    fn deref_mut(&mut self) -> &mut [u8] {
1487        self.0.as_mut_slice()
1488    }
1489}
1490
1491/// A buffer type used with `Write::write_vectored`.
1492///
1493/// It is semantically a wrapper around a `&[u8]`, but is guaranteed to be
1494/// ABI compatible with the `iovec` type on Unix platforms and `WSABUF` on
1495/// Windows.
1496#[stable(feature = "iovec", since = "1.36.0")]
1497#[derive(Copy, Clone)]
1498#[repr(transparent)]
1499pub struct IoSlice<'a>(sys::io::IoSlice<'a>);
1500
1501#[stable(feature = "iovec_send_sync", since = "1.44.0")]
1502unsafe impl<'a> Send for IoSlice<'a> {}
1503
1504#[stable(feature = "iovec_send_sync", since = "1.44.0")]
1505unsafe impl<'a> Sync for IoSlice<'a> {}
1506
1507#[stable(feature = "iovec", since = "1.36.0")]
1508impl<'a> fmt::Debug for IoSlice<'a> {
1509    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1510        fmt::Debug::fmt(self.0.as_slice(), fmt)
1511    }
1512}
1513
1514impl<'a> IoSlice<'a> {
1515    /// Creates a new `IoSlice` wrapping a byte slice.
1516    ///
1517    /// # Panics
1518    ///
1519    /// Panics on Windows if the slice is larger than 4GB.
1520    #[stable(feature = "iovec", since = "1.36.0")]
1521    #[must_use]
1522    #[inline]
1523    pub fn new(buf: &'a [u8]) -> IoSlice<'a> {
1524        IoSlice(sys::io::IoSlice::new(buf))
1525    }
1526
1527    /// Advance the internal cursor of the slice.
1528    ///
1529    /// Also see [`IoSlice::advance_slices`] to advance the cursors of multiple
1530    /// buffers.
1531    ///
1532    /// # Panics
1533    ///
1534    /// Panics when trying to advance beyond the end of the slice.
1535    ///
1536    /// # Examples
1537    ///
1538    /// ```
1539    /// use std::io::IoSlice;
1540    /// use std::ops::Deref;
1541    ///
1542    /// let data = [1; 8];
1543    /// let mut buf = IoSlice::new(&data);
1544    ///
1545    /// // Mark 3 bytes as read.
1546    /// buf.advance(3);
1547    /// assert_eq!(buf.deref(), [1; 5].as_ref());
1548    /// ```
1549    #[stable(feature = "io_slice_advance", since = "1.81.0")]
1550    #[inline]
1551    pub fn advance(&mut self, n: usize) {
1552        self.0.advance(n)
1553    }
1554
1555    /// Advance a slice of slices.
1556    ///
1557    /// Shrinks the slice to remove any `IoSlice`s that are fully advanced over.
1558    /// If the cursor ends up in the middle of an `IoSlice`, it is modified
1559    /// to start at that cursor.
1560    ///
1561    /// For example, if we have a slice of two 8-byte `IoSlice`s, and we advance by 10 bytes,
1562    /// the result will only include the second `IoSlice`, advanced by 2 bytes.
1563    ///
1564    /// # Panics
1565    ///
1566    /// Panics when trying to advance beyond the end of the slices.
1567    ///
1568    /// # Examples
1569    ///
1570    /// ```
1571    /// use std::io::IoSlice;
1572    /// use std::ops::Deref;
1573    ///
1574    /// let buf1 = [1; 8];
1575    /// let buf2 = [2; 16];
1576    /// let buf3 = [3; 8];
1577    /// let mut bufs = &mut [
1578    ///     IoSlice::new(&buf1),
1579    ///     IoSlice::new(&buf2),
1580    ///     IoSlice::new(&buf3),
1581    /// ][..];
1582    ///
1583    /// // Mark 10 bytes as written.
1584    /// IoSlice::advance_slices(&mut bufs, 10);
1585    /// assert_eq!(bufs[0].deref(), [2; 14].as_ref());
1586    /// assert_eq!(bufs[1].deref(), [3; 8].as_ref());
1587    #[stable(feature = "io_slice_advance", since = "1.81.0")]
1588    #[inline]
1589    pub fn advance_slices(bufs: &mut &mut [IoSlice<'a>], n: usize) {
1590        // Number of buffers to remove.
1591        let mut remove = 0;
1592        // Remaining length before reaching n. This prevents overflow
1593        // that could happen if the length of slices in `bufs` were instead
1594        // accumulated. Those slice may be aliased and, if they are large
1595        // enough, their added length may overflow a `usize`.
1596        let mut left = n;
1597        for buf in bufs.iter() {
1598            if let Some(remainder) = left.checked_sub(buf.len()) {
1599                left = remainder;
1600                remove += 1;
1601            } else {
1602                break;
1603            }
1604        }
1605
1606        *bufs = &mut take(bufs)[remove..];
1607        if bufs.is_empty() {
1608            assert!(left == 0, "advancing io slices beyond their length");
1609        } else {
1610            bufs[0].advance(left);
1611        }
1612    }
1613
1614    /// Get the underlying bytes as a slice with the original lifetime.
1615    ///
1616    /// This doesn't borrow from `self`, so is less restrictive than calling
1617    /// `.deref()`, which does.
1618    ///
1619    /// # Examples
1620    ///
1621    /// ```
1622    /// #![feature(io_slice_as_bytes)]
1623    /// use std::io::IoSlice;
1624    ///
1625    /// let data = b"abcdef";
1626    ///
1627    /// let mut io_slice = IoSlice::new(data);
1628    /// let tail = &io_slice.as_slice()[3..];
1629    ///
1630    /// // This works because `tail` doesn't borrow `io_slice`
1631    /// io_slice = IoSlice::new(tail);
1632    ///
1633    /// assert_eq!(io_slice.as_slice(), b"def");
1634    /// ```
1635    #[unstable(feature = "io_slice_as_bytes", issue = "132818")]
1636    pub const fn as_slice(self) -> &'a [u8] {
1637        self.0.as_slice()
1638    }
1639}
1640
1641#[stable(feature = "iovec", since = "1.36.0")]
1642impl<'a> Deref for IoSlice<'a> {
1643    type Target = [u8];
1644
1645    #[inline]
1646    fn deref(&self) -> &[u8] {
1647        self.0.as_slice()
1648    }
1649}
1650
1651/// A trait for objects which are byte-oriented sinks.
1652///
1653/// Implementors of the `Write` trait are sometimes called 'writers'.
1654///
1655/// Writers are defined by two required methods, [`write`] and [`flush`]:
1656///
1657/// * The [`write`] method will attempt to write some data into the object,
1658///   returning how many bytes were successfully written.
1659///
1660/// * The [`flush`] method is useful for adapters and explicit buffers
1661///   themselves for ensuring that all buffered data has been pushed out to the
1662///   'true sink'.
1663///
1664/// Writers are intended to be composable with one another. Many implementors
1665/// throughout [`std::io`] take and provide types which implement the `Write`
1666/// trait.
1667///
1668/// [`write`]: Write::write
1669/// [`flush`]: Write::flush
1670/// [`std::io`]: self
1671///
1672/// # Examples
1673///
1674/// ```no_run
1675/// use std::io::prelude::*;
1676/// use std::fs::File;
1677///
1678/// fn main() -> std::io::Result<()> {
1679///     let data = b"some bytes";
1680///
1681///     let mut pos = 0;
1682///     let mut buffer = File::create("foo.txt")?;
1683///
1684///     while pos < data.len() {
1685///         let bytes_written = buffer.write(&data[pos..])?;
1686///         pos += bytes_written;
1687///     }
1688///     Ok(())
1689/// }
1690/// ```
1691///
1692/// The trait also provides convenience methods like [`write_all`], which calls
1693/// `write` in a loop until its entire input has been written.
1694///
1695/// [`write_all`]: Write::write_all
1696#[stable(feature = "rust1", since = "1.0.0")]
1697#[doc(notable_trait)]
1698#[cfg_attr(not(test), rustc_diagnostic_item = "IoWrite")]
1699pub trait Write {
1700    /// Writes a buffer into this writer, returning how many bytes were written.
1701    ///
1702    /// This function will attempt to write the entire contents of `buf`, but
1703    /// the entire write might not succeed, or the write may also generate an
1704    /// error. Typically, a call to `write` represents one attempt to write to
1705    /// any wrapped object.
1706    ///
1707    /// Calls to `write` are not guaranteed to block waiting for data to be
1708    /// written, and a write which would otherwise block can be indicated through
1709    /// an [`Err`] variant.
1710    ///
1711    /// If this method consumed `n > 0` bytes of `buf` it must return [`Ok(n)`].
1712    /// If the return value is `Ok(n)` then `n` must satisfy `n <= buf.len()`.
1713    /// A return value of `Ok(0)` typically means that the underlying object is
1714    /// no longer able to accept bytes and will likely not be able to in the
1715    /// future as well, or that the buffer provided is empty.
1716    ///
1717    /// # Errors
1718    ///
1719    /// Each call to `write` may generate an I/O error indicating that the
1720    /// operation could not be completed. If an error is returned then no bytes
1721    /// in the buffer were written to this writer.
1722    ///
1723    /// It is **not** considered an error if the entire buffer could not be
1724    /// written to this writer.
1725    ///
1726    /// An error of the [`ErrorKind::Interrupted`] kind is non-fatal and the
1727    /// write operation should be retried if there is nothing else to do.
1728    ///
1729    /// # Examples
1730    ///
1731    /// ```no_run
1732    /// use std::io::prelude::*;
1733    /// use std::fs::File;
1734    ///
1735    /// fn main() -> std::io::Result<()> {
1736    ///     let mut buffer = File::create("foo.txt")?;
1737    ///
1738    ///     // Writes some prefix of the byte string, not necessarily all of it.
1739    ///     buffer.write(b"some bytes")?;
1740    ///     Ok(())
1741    /// }
1742    /// ```
1743    ///
1744    /// [`Ok(n)`]: Ok
1745    #[stable(feature = "rust1", since = "1.0.0")]
1746    fn write(&mut self, buf: &[u8]) -> Result<usize>;
1747
1748    /// Like [`write`], except that it writes from a slice of buffers.
1749    ///
1750    /// Data is copied from each buffer in order, with the final buffer
1751    /// read from possibly being only partially consumed. This method must
1752    /// behave as a call to [`write`] with the buffers concatenated would.
1753    ///
1754    /// The default implementation calls [`write`] with either the first nonempty
1755    /// buffer provided, or an empty one if none exists.
1756    ///
1757    /// # Examples
1758    ///
1759    /// ```no_run
1760    /// use std::io::IoSlice;
1761    /// use std::io::prelude::*;
1762    /// use std::fs::File;
1763    ///
1764    /// fn main() -> std::io::Result<()> {
1765    ///     let data1 = [1; 8];
1766    ///     let data2 = [15; 8];
1767    ///     let io_slice1 = IoSlice::new(&data1);
1768    ///     let io_slice2 = IoSlice::new(&data2);
1769    ///
1770    ///     let mut buffer = File::create("foo.txt")?;
1771    ///
1772    ///     // Writes some prefix of the byte string, not necessarily all of it.
1773    ///     buffer.write_vectored(&[io_slice1, io_slice2])?;
1774    ///     Ok(())
1775    /// }
1776    /// ```
1777    ///
1778    /// [`write`]: Write::write
1779    #[stable(feature = "iovec", since = "1.36.0")]
1780    fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> Result<usize> {
1781        default_write_vectored(|b| self.write(b), bufs)
1782    }
1783
1784    /// Determines if this `Write`r has an efficient [`write_vectored`]
1785    /// implementation.
1786    ///
1787    /// If a `Write`r does not override the default [`write_vectored`]
1788    /// implementation, code using it may want to avoid the method all together
1789    /// and coalesce writes into a single buffer for higher performance.
1790    ///
1791    /// The default implementation returns `false`.
1792    ///
1793    /// [`write_vectored`]: Write::write_vectored
1794    #[unstable(feature = "can_vector", issue = "69941")]
1795    fn is_write_vectored(&self) -> bool {
1796        false
1797    }
1798
1799    /// Flushes this output stream, ensuring that all intermediately buffered
1800    /// contents reach their destination.
1801    ///
1802    /// # Errors
1803    ///
1804    /// It is considered an error if not all bytes could be written due to
1805    /// I/O errors or EOF being reached.
1806    ///
1807    /// # Examples
1808    ///
1809    /// ```no_run
1810    /// use std::io::prelude::*;
1811    /// use std::io::BufWriter;
1812    /// use std::fs::File;
1813    ///
1814    /// fn main() -> std::io::Result<()> {
1815    ///     let mut buffer = BufWriter::new(File::create("foo.txt")?);
1816    ///
1817    ///     buffer.write_all(b"some bytes")?;
1818    ///     buffer.flush()?;
1819    ///     Ok(())
1820    /// }
1821    /// ```
1822    #[stable(feature = "rust1", since = "1.0.0")]
1823    fn flush(&mut self) -> Result<()>;
1824
1825    /// Attempts to write an entire buffer into this writer.
1826    ///
1827    /// This method will continuously call [`write`] until there is no more data
1828    /// to be written or an error of non-[`ErrorKind::Interrupted`] kind is
1829    /// returned. This method will not return until the entire buffer has been
1830    /// successfully written or such an error occurs. The first error that is
1831    /// not of [`ErrorKind::Interrupted`] kind generated from this method will be
1832    /// returned.
1833    ///
1834    /// If the buffer contains no data, this will never call [`write`].
1835    ///
1836    /// # Errors
1837    ///
1838    /// This function will return the first error of
1839    /// non-[`ErrorKind::Interrupted`] kind that [`write`] returns.
1840    ///
1841    /// [`write`]: Write::write
1842    ///
1843    /// # Examples
1844    ///
1845    /// ```no_run
1846    /// use std::io::prelude::*;
1847    /// use std::fs::File;
1848    ///
1849    /// fn main() -> std::io::Result<()> {
1850    ///     let mut buffer = File::create("foo.txt")?;
1851    ///
1852    ///     buffer.write_all(b"some bytes")?;
1853    ///     Ok(())
1854    /// }
1855    /// ```
1856    #[stable(feature = "rust1", since = "1.0.0")]
1857    fn write_all(&mut self, mut buf: &[u8]) -> Result<()> {
1858        while !buf.is_empty() {
1859            match self.write(buf) {
1860                Ok(0) => {
1861                    return Err(Error::WRITE_ALL_EOF);
1862                }
1863                Ok(n) => buf = &buf[n..],
1864                Err(ref e) if e.is_interrupted() => {}
1865                Err(e) => return Err(e),
1866            }
1867        }
1868        Ok(())
1869    }
1870
1871    /// Attempts to write multiple buffers into this writer.
1872    ///
1873    /// This method will continuously call [`write_vectored`] until there is no
1874    /// more data to be written or an error of non-[`ErrorKind::Interrupted`]
1875    /// kind is returned. This method will not return until all buffers have
1876    /// been successfully written or such an error occurs. The first error that
1877    /// is not of [`ErrorKind::Interrupted`] kind generated from this method
1878    /// will be returned.
1879    ///
1880    /// If the buffer contains no data, this will never call [`write_vectored`].
1881    ///
1882    /// # Notes
1883    ///
1884    /// Unlike [`write_vectored`], this takes a *mutable* reference to
1885    /// a slice of [`IoSlice`]s, not an immutable one. That's because we need to
1886    /// modify the slice to keep track of the bytes already written.
1887    ///
1888    /// Once this function returns, the contents of `bufs` are unspecified, as
1889    /// this depends on how many calls to [`write_vectored`] were necessary. It is
1890    /// best to understand this function as taking ownership of `bufs` and to
1891    /// not use `bufs` afterwards. The underlying buffers, to which the
1892    /// [`IoSlice`]s point (but not the [`IoSlice`]s themselves), are unchanged and
1893    /// can be reused.
1894    ///
1895    /// [`write_vectored`]: Write::write_vectored
1896    ///
1897    /// # Examples
1898    ///
1899    /// ```
1900    /// #![feature(write_all_vectored)]
1901    /// # fn main() -> std::io::Result<()> {
1902    ///
1903    /// use std::io::{Write, IoSlice};
1904    ///
1905    /// let mut writer = Vec::new();
1906    /// let bufs = &mut [
1907    ///     IoSlice::new(&[1]),
1908    ///     IoSlice::new(&[2, 3]),
1909    ///     IoSlice::new(&[4, 5, 6]),
1910    /// ];
1911    ///
1912    /// writer.write_all_vectored(bufs)?;
1913    /// // Note: the contents of `bufs` is now undefined, see the Notes section.
1914    ///
1915    /// assert_eq!(writer, &[1, 2, 3, 4, 5, 6]);
1916    /// # Ok(()) }
1917    /// ```
1918    #[unstable(feature = "write_all_vectored", issue = "70436")]
1919    fn write_all_vectored(&mut self, mut bufs: &mut [IoSlice<'_>]) -> Result<()> {
1920        // Guarantee that bufs is empty if it contains no data,
1921        // to avoid calling write_vectored if there is no data to be written.
1922        IoSlice::advance_slices(&mut bufs, 0);
1923        while !bufs.is_empty() {
1924            match self.write_vectored(bufs) {
1925                Ok(0) => {
1926                    return Err(Error::WRITE_ALL_EOF);
1927                }
1928                Ok(n) => IoSlice::advance_slices(&mut bufs, n),
1929                Err(ref e) if e.is_interrupted() => {}
1930                Err(e) => return Err(e),
1931            }
1932        }
1933        Ok(())
1934    }
1935
1936    /// Writes a formatted string into this writer, returning any error
1937    /// encountered.
1938    ///
1939    /// This method is primarily used to interface with the
1940    /// [`format_args!()`] macro, and it is rare that this should
1941    /// explicitly be called. The [`write!()`] macro should be favored to
1942    /// invoke this method instead.
1943    ///
1944    /// This function internally uses the [`write_all`] method on
1945    /// this trait and hence will continuously write data so long as no errors
1946    /// are received. This also means that partial writes are not indicated in
1947    /// this signature.
1948    ///
1949    /// [`write_all`]: Write::write_all
1950    ///
1951    /// # Errors
1952    ///
1953    /// This function will return any I/O error reported while formatting.
1954    ///
1955    /// # Examples
1956    ///
1957    /// ```no_run
1958    /// use std::io::prelude::*;
1959    /// use std::fs::File;
1960    ///
1961    /// fn main() -> std::io::Result<()> {
1962    ///     let mut buffer = File::create("foo.txt")?;
1963    ///
1964    ///     // this call
1965    ///     write!(buffer, "{:.*}", 2, 1.234567)?;
1966    ///     // turns into this:
1967    ///     buffer.write_fmt(format_args!("{:.*}", 2, 1.234567))?;
1968    ///     Ok(())
1969    /// }
1970    /// ```
1971    #[stable(feature = "rust1", since = "1.0.0")]
1972    fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> Result<()> {
1973        if let Some(s) = args.as_statically_known_str() {
1974            self.write_all(s.as_bytes())
1975        } else {
1976            default_write_fmt(self, args)
1977        }
1978    }
1979
1980    /// Creates a "by reference" adapter for this instance of `Write`.
1981    ///
1982    /// The returned adapter also implements `Write` and will simply borrow this
1983    /// current writer.
1984    ///
1985    /// # Examples
1986    ///
1987    /// ```no_run
1988    /// use std::io::Write;
1989    /// use std::fs::File;
1990    ///
1991    /// fn main() -> std::io::Result<()> {
1992    ///     let mut buffer = File::create("foo.txt")?;
1993    ///
1994    ///     let reference = buffer.by_ref();
1995    ///
1996    ///     // we can use reference just like our original buffer
1997    ///     reference.write_all(b"some bytes")?;
1998    ///     Ok(())
1999    /// }
2000    /// ```
2001    #[stable(feature = "rust1", since = "1.0.0")]
2002    fn by_ref(&mut self) -> &mut Self
2003    where
2004        Self: Sized,
2005    {
2006        self
2007    }
2008}
2009
2010/// The `Seek` trait provides a cursor which can be moved within a stream of
2011/// bytes.
2012///
2013/// The stream typically has a fixed size, allowing seeking relative to either
2014/// end or the current offset.
2015///
2016/// # Examples
2017///
2018/// [`File`]s implement `Seek`:
2019///
2020/// [`File`]: crate::fs::File
2021///
2022/// ```no_run
2023/// use std::io;
2024/// use std::io::prelude::*;
2025/// use std::fs::File;
2026/// use std::io::SeekFrom;
2027///
2028/// fn main() -> io::Result<()> {
2029///     let mut f = File::open("foo.txt")?;
2030///
2031///     // move the cursor 42 bytes from the start of the file
2032///     f.seek(SeekFrom::Start(42))?;
2033///     Ok(())
2034/// }
2035/// ```
2036#[stable(feature = "rust1", since = "1.0.0")]
2037#[cfg_attr(not(test), rustc_diagnostic_item = "IoSeek")]
2038pub trait Seek {
2039    /// Seek to an offset, in bytes, in a stream.
2040    ///
2041    /// A seek beyond the end of a stream is allowed, but behavior is defined
2042    /// by the implementation.
2043    ///
2044    /// If the seek operation completed successfully,
2045    /// this method returns the new position from the start of the stream.
2046    /// That position can be used later with [`SeekFrom::Start`].
2047    ///
2048    /// # Errors
2049    ///
2050    /// Seeking can fail, for example because it might involve flushing a buffer.
2051    ///
2052    /// Seeking to a negative offset is considered an error.
2053    #[stable(feature = "rust1", since = "1.0.0")]
2054    fn seek(&mut self, pos: SeekFrom) -> Result<u64>;
2055
2056    /// Rewind to the beginning of a stream.
2057    ///
2058    /// This is a convenience method, equivalent to `seek(SeekFrom::Start(0))`.
2059    ///
2060    /// # Errors
2061    ///
2062    /// Rewinding can fail, for example because it might involve flushing a buffer.
2063    ///
2064    /// # Example
2065    ///
2066    /// ```no_run
2067    /// use std::io::{Read, Seek, Write};
2068    /// use std::fs::OpenOptions;
2069    ///
2070    /// let mut f = OpenOptions::new()
2071    ///     .write(true)
2072    ///     .read(true)
2073    ///     .create(true)
2074    ///     .open("foo.txt")?;
2075    ///
2076    /// let hello = "Hello!\n";
2077    /// write!(f, "{hello}")?;
2078    /// f.rewind()?;
2079    ///
2080    /// let mut buf = String::new();
2081    /// f.read_to_string(&mut buf)?;
2082    /// assert_eq!(&buf, hello);
2083    /// # std::io::Result::Ok(())
2084    /// ```
2085    #[stable(feature = "seek_rewind", since = "1.55.0")]
2086    fn rewind(&mut self) -> Result<()> {
2087        self.seek(SeekFrom::Start(0))?;
2088        Ok(())
2089    }
2090
2091    /// Returns the length of this stream (in bytes).
2092    ///
2093    /// The default implementation uses up to three seek operations. If this
2094    /// method returns successfully, the seek position is unchanged (i.e. the
2095    /// position before calling this method is the same as afterwards).
2096    /// However, if this method returns an error, the seek position is
2097    /// unspecified.
2098    ///
2099    /// If you need to obtain the length of *many* streams and you don't care
2100    /// about the seek position afterwards, you can reduce the number of seek
2101    /// operations by simply calling `seek(SeekFrom::End(0))` and using its
2102    /// return value (it is also the stream length).
2103    ///
2104    /// Note that length of a stream can change over time (for example, when
2105    /// data is appended to a file). So calling this method multiple times does
2106    /// not necessarily return the same length each time.
2107    ///
2108    /// # Example
2109    ///
2110    /// ```no_run
2111    /// #![feature(seek_stream_len)]
2112    /// use std::{
2113    ///     io::{self, Seek},
2114    ///     fs::File,
2115    /// };
2116    ///
2117    /// fn main() -> io::Result<()> {
2118    ///     let mut f = File::open("foo.txt")?;
2119    ///
2120    ///     let len = f.stream_len()?;
2121    ///     println!("The file is currently {len} bytes long");
2122    ///     Ok(())
2123    /// }
2124    /// ```
2125    #[unstable(feature = "seek_stream_len", issue = "59359")]
2126    fn stream_len(&mut self) -> Result<u64> {
2127        stream_len_default(self)
2128    }
2129
2130    /// Returns the current seek position from the start of the stream.
2131    ///
2132    /// This is equivalent to `self.seek(SeekFrom::Current(0))`.
2133    ///
2134    /// # Example
2135    ///
2136    /// ```no_run
2137    /// use std::{
2138    ///     io::{self, BufRead, BufReader, Seek},
2139    ///     fs::File,
2140    /// };
2141    ///
2142    /// fn main() -> io::Result<()> {
2143    ///     let mut f = BufReader::new(File::open("foo.txt")?);
2144    ///
2145    ///     let before = f.stream_position()?;
2146    ///     f.read_line(&mut String::new())?;
2147    ///     let after = f.stream_position()?;
2148    ///
2149    ///     println!("The first line was {} bytes long", after - before);
2150    ///     Ok(())
2151    /// }
2152    /// ```
2153    #[stable(feature = "seek_convenience", since = "1.51.0")]
2154    fn stream_position(&mut self) -> Result<u64> {
2155        self.seek(SeekFrom::Current(0))
2156    }
2157
2158    /// Seeks relative to the current position.
2159    ///
2160    /// This is equivalent to `self.seek(SeekFrom::Current(offset))` but
2161    /// doesn't return the new position which can allow some implementations
2162    /// such as [`BufReader`] to perform more efficient seeks.
2163    ///
2164    /// # Example
2165    ///
2166    /// ```no_run
2167    /// use std::{
2168    ///     io::{self, Seek},
2169    ///     fs::File,
2170    /// };
2171    ///
2172    /// fn main() -> io::Result<()> {
2173    ///     let mut f = File::open("foo.txt")?;
2174    ///     f.seek_relative(10)?;
2175    ///     assert_eq!(f.stream_position()?, 10);
2176    ///     Ok(())
2177    /// }
2178    /// ```
2179    ///
2180    /// [`BufReader`]: crate::io::BufReader
2181    #[stable(feature = "seek_seek_relative", since = "1.80.0")]
2182    fn seek_relative(&mut self, offset: i64) -> Result<()> {
2183        self.seek(SeekFrom::Current(offset))?;
2184        Ok(())
2185    }
2186}
2187
2188pub(crate) fn stream_len_default<T: Seek + ?Sized>(self_: &mut T) -> Result<u64> {
2189    let old_pos = self_.stream_position()?;
2190    let len = self_.seek(SeekFrom::End(0))?;
2191
2192    // Avoid seeking a third time when we were already at the end of the
2193    // stream. The branch is usually way cheaper than a seek operation.
2194    if old_pos != len {
2195        self_.seek(SeekFrom::Start(old_pos))?;
2196    }
2197
2198    Ok(len)
2199}
2200
2201/// Enumeration of possible methods to seek within an I/O object.
2202///
2203/// It is used by the [`Seek`] trait.
2204#[derive(Copy, PartialEq, Eq, Clone, Debug)]
2205#[stable(feature = "rust1", since = "1.0.0")]
2206#[cfg_attr(not(test), rustc_diagnostic_item = "SeekFrom")]
2207pub enum SeekFrom {
2208    /// Sets the offset to the provided number of bytes.
2209    #[stable(feature = "rust1", since = "1.0.0")]
2210    Start(#[stable(feature = "rust1", since = "1.0.0")] u64),
2211
2212    /// Sets the offset to the size of this object plus the specified number of
2213    /// bytes.
2214    ///
2215    /// It is possible to seek beyond the end of an object, but it's an error to
2216    /// seek before byte 0.
2217    #[stable(feature = "rust1", since = "1.0.0")]
2218    End(#[stable(feature = "rust1", since = "1.0.0")] i64),
2219
2220    /// Sets the offset to the current position plus the specified number of
2221    /// bytes.
2222    ///
2223    /// It is possible to seek beyond the end of an object, but it's an error to
2224    /// seek before byte 0.
2225    #[stable(feature = "rust1", since = "1.0.0")]
2226    Current(#[stable(feature = "rust1", since = "1.0.0")] i64),
2227}
2228
2229fn read_until<R: BufRead + ?Sized>(r: &mut R, delim: u8, buf: &mut Vec<u8>) -> Result<usize> {
2230    let mut read = 0;
2231    loop {
2232        let (done, used) = {
2233            let available = match r.fill_buf() {
2234                Ok(n) => n,
2235                Err(ref e) if e.is_interrupted() => continue,
2236                Err(e) => return Err(e),
2237            };
2238            match memchr::memchr(delim, available) {
2239                Some(i) => {
2240                    buf.extend_from_slice(&available[..=i]);
2241                    (true, i + 1)
2242                }
2243                None => {
2244                    buf.extend_from_slice(available);
2245                    (false, available.len())
2246                }
2247            }
2248        };
2249        r.consume(used);
2250        read += used;
2251        if done || used == 0 {
2252            return Ok(read);
2253        }
2254    }
2255}
2256
2257fn skip_until<R: BufRead + ?Sized>(r: &mut R, delim: u8) -> Result<usize> {
2258    let mut read = 0;
2259    loop {
2260        let (done, used) = {
2261            let available = match r.fill_buf() {
2262                Ok(n) => n,
2263                Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
2264                Err(e) => return Err(e),
2265            };
2266            match memchr::memchr(delim, available) {
2267                Some(i) => (true, i + 1),
2268                None => (false, available.len()),
2269            }
2270        };
2271        r.consume(used);
2272        read += used;
2273        if done || used == 0 {
2274            return Ok(read);
2275        }
2276    }
2277}
2278
2279/// A `BufRead` is a type of `Read`er which has an internal buffer, allowing it
2280/// to perform extra ways of reading.
2281///
2282/// For example, reading line-by-line is inefficient without using a buffer, so
2283/// if you want to read by line, you'll need `BufRead`, which includes a
2284/// [`read_line`] method as well as a [`lines`] iterator.
2285///
2286/// # Examples
2287///
2288/// A locked standard input implements `BufRead`:
2289///
2290/// ```no_run
2291/// use std::io;
2292/// use std::io::prelude::*;
2293///
2294/// let stdin = io::stdin();
2295/// for line in stdin.lock().lines() {
2296///     println!("{}", line?);
2297/// }
2298/// # std::io::Result::Ok(())
2299/// ```
2300///
2301/// If you have something that implements [`Read`], you can use the [`BufReader`
2302/// type][`BufReader`] to turn it into a `BufRead`.
2303///
2304/// For example, [`File`] implements [`Read`], but not `BufRead`.
2305/// [`BufReader`] to the rescue!
2306///
2307/// [`File`]: crate::fs::File
2308/// [`read_line`]: BufRead::read_line
2309/// [`lines`]: BufRead::lines
2310///
2311/// ```no_run
2312/// use std::io::{self, BufReader};
2313/// use std::io::prelude::*;
2314/// use std::fs::File;
2315///
2316/// fn main() -> io::Result<()> {
2317///     let f = File::open("foo.txt")?;
2318///     let f = BufReader::new(f);
2319///
2320///     for line in f.lines() {
2321///         let line = line?;
2322///         println!("{line}");
2323///     }
2324///
2325///     Ok(())
2326/// }
2327/// ```
2328#[stable(feature = "rust1", since = "1.0.0")]
2329#[cfg_attr(not(test), rustc_diagnostic_item = "IoBufRead")]
2330pub trait BufRead: Read {
2331    /// Returns the contents of the internal buffer, filling it with more data, via `Read` methods, if empty.
2332    ///
2333    /// This is a lower-level method and is meant to be used together with [`consume`],
2334    /// which can be used to mark bytes that should not be returned by subsequent calls to `read`.
2335    ///
2336    /// [`consume`]: BufRead::consume
2337    ///
2338    /// Returns an empty buffer when the stream has reached EOF.
2339    ///
2340    /// # Errors
2341    ///
2342    /// This function will return an I/O error if a `Read` method was called, but returned an error.
2343    ///
2344    /// # Examples
2345    ///
2346    /// A locked standard input implements `BufRead`:
2347    ///
2348    /// ```no_run
2349    /// use std::io;
2350    /// use std::io::prelude::*;
2351    ///
2352    /// let stdin = io::stdin();
2353    /// let mut stdin = stdin.lock();
2354    ///
2355    /// let buffer = stdin.fill_buf()?;
2356    ///
2357    /// // work with buffer
2358    /// println!("{buffer:?}");
2359    ///
2360    /// // mark the bytes we worked with as read
2361    /// let length = buffer.len();
2362    /// stdin.consume(length);
2363    /// # std::io::Result::Ok(())
2364    /// ```
2365    #[stable(feature = "rust1", since = "1.0.0")]
2366    fn fill_buf(&mut self) -> Result<&[u8]>;
2367
2368    /// Marks the given `amount` of additional bytes from the internal buffer as having been read.
2369    /// Subsequent calls to `read` only return bytes that have not been marked as read.
2370    ///
2371    /// This is a lower-level method and is meant to be used together with [`fill_buf`],
2372    /// which can be used to fill the internal buffer via `Read` methods.
2373    ///
2374    /// It is a logic error if `amount` exceeds the number of unread bytes in the internal buffer, which is returned by [`fill_buf`].
2375    ///
2376    /// # Examples
2377    ///
2378    /// Since `consume()` is meant to be used with [`fill_buf`],
2379    /// that method's example includes an example of `consume()`.
2380    ///
2381    /// [`fill_buf`]: BufRead::fill_buf
2382    #[stable(feature = "rust1", since = "1.0.0")]
2383    fn consume(&mut self, amount: usize);
2384
2385    /// Checks if there is any data left to be `read`.
2386    ///
2387    /// This function may fill the buffer to check for data,
2388    /// so this function returns `Result<bool>`, not `bool`.
2389    ///
2390    /// The default implementation calls `fill_buf` and checks that the
2391    /// returned slice is empty (which means that there is no data left,
2392    /// since EOF is reached).
2393    ///
2394    /// # Errors
2395    ///
2396    /// This function will return an I/O error if a `Read` method was called, but returned an error.
2397    ///
2398    /// Examples
2399    ///
2400    /// ```
2401    /// #![feature(buf_read_has_data_left)]
2402    /// use std::io;
2403    /// use std::io::prelude::*;
2404    ///
2405    /// let stdin = io::stdin();
2406    /// let mut stdin = stdin.lock();
2407    ///
2408    /// while stdin.has_data_left()? {
2409    ///     let mut line = String::new();
2410    ///     stdin.read_line(&mut line)?;
2411    ///     // work with line
2412    ///     println!("{line:?}");
2413    /// }
2414    /// # std::io::Result::Ok(())
2415    /// ```
2416    #[unstable(feature = "buf_read_has_data_left", issue = "86423")]
2417    fn has_data_left(&mut self) -> Result<bool> {
2418        self.fill_buf().map(|b| !b.is_empty())
2419    }
2420
2421    /// Reads all bytes into `buf` until the delimiter `byte` or EOF is reached.
2422    ///
2423    /// This function will read bytes from the underlying stream until the
2424    /// delimiter or EOF is found. Once found, all bytes up to, and including,
2425    /// the delimiter (if found) will be appended to `buf`.
2426    ///
2427    /// If successful, this function will return the total number of bytes read.
2428    ///
2429    /// This function is blocking and should be used carefully: it is possible for
2430    /// an attacker to continuously send bytes without ever sending the delimiter
2431    /// or EOF.
2432    ///
2433    /// # Errors
2434    ///
2435    /// This function will ignore all instances of [`ErrorKind::Interrupted`] and
2436    /// will otherwise return any errors returned by [`fill_buf`].
2437    ///
2438    /// If an I/O error is encountered then all bytes read so far will be
2439    /// present in `buf` and its length will have been adjusted appropriately.
2440    ///
2441    /// [`fill_buf`]: BufRead::fill_buf
2442    ///
2443    /// # Examples
2444    ///
2445    /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
2446    /// this example, we use [`Cursor`] to read all the bytes in a byte slice
2447    /// in hyphen delimited segments:
2448    ///
2449    /// ```
2450    /// use std::io::{self, BufRead};
2451    ///
2452    /// let mut cursor = io::Cursor::new(b"lorem-ipsum");
2453    /// let mut buf = vec![];
2454    ///
2455    /// // cursor is at 'l'
2456    /// let num_bytes = cursor.read_until(b'-', &mut buf)
2457    ///     .expect("reading from cursor won't fail");
2458    /// assert_eq!(num_bytes, 6);
2459    /// assert_eq!(buf, b"lorem-");
2460    /// buf.clear();
2461    ///
2462    /// // cursor is at 'i'
2463    /// let num_bytes = cursor.read_until(b'-', &mut buf)
2464    ///     .expect("reading from cursor won't fail");
2465    /// assert_eq!(num_bytes, 5);
2466    /// assert_eq!(buf, b"ipsum");
2467    /// buf.clear();
2468    ///
2469    /// // cursor is at EOF
2470    /// let num_bytes = cursor.read_until(b'-', &mut buf)
2471    ///     .expect("reading from cursor won't fail");
2472    /// assert_eq!(num_bytes, 0);
2473    /// assert_eq!(buf, b"");
2474    /// ```
2475    #[stable(feature = "rust1", since = "1.0.0")]
2476    fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> Result<usize> {
2477        read_until(self, byte, buf)
2478    }
2479
2480    /// Skips all bytes until the delimiter `byte` or EOF is reached.
2481    ///
2482    /// This function will read (and discard) bytes from the underlying stream until the
2483    /// delimiter or EOF is found.
2484    ///
2485    /// If successful, this function will return the total number of bytes read,
2486    /// including the delimiter byte if found.
2487    ///
2488    /// This is useful for efficiently skipping data such as NUL-terminated strings
2489    /// in binary file formats without buffering.
2490    ///
2491    /// This function is blocking and should be used carefully: it is possible for
2492    /// an attacker to continuously send bytes without ever sending the delimiter
2493    /// or EOF.
2494    ///
2495    /// # Errors
2496    ///
2497    /// This function will ignore all instances of [`ErrorKind::Interrupted`] and
2498    /// will otherwise return any errors returned by [`fill_buf`].
2499    ///
2500    /// If an I/O error is encountered then all bytes read so far will be
2501    /// present in `buf` and its length will have been adjusted appropriately.
2502    ///
2503    /// [`fill_buf`]: BufRead::fill_buf
2504    ///
2505    /// # Examples
2506    ///
2507    /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
2508    /// this example, we use [`Cursor`] to read some NUL-terminated information
2509    /// about Ferris from a binary string, skipping the fun fact:
2510    ///
2511    /// ```
2512    /// use std::io::{self, BufRead};
2513    ///
2514    /// let mut cursor = io::Cursor::new(b"Ferris\0Likes long walks on the beach\0Crustacean\0!");
2515    ///
2516    /// // read name
2517    /// let mut name = Vec::new();
2518    /// let num_bytes = cursor.read_until(b'\0', &mut name)
2519    ///     .expect("reading from cursor won't fail");
2520    /// assert_eq!(num_bytes, 7);
2521    /// assert_eq!(name, b"Ferris\0");
2522    ///
2523    /// // skip fun fact
2524    /// let num_bytes = cursor.skip_until(b'\0')
2525    ///     .expect("reading from cursor won't fail");
2526    /// assert_eq!(num_bytes, 30);
2527    ///
2528    /// // read animal type
2529    /// let mut animal = Vec::new();
2530    /// let num_bytes = cursor.read_until(b'\0', &mut animal)
2531    ///     .expect("reading from cursor won't fail");
2532    /// assert_eq!(num_bytes, 11);
2533    /// assert_eq!(animal, b"Crustacean\0");
2534    ///
2535    /// // reach EOF
2536    /// let num_bytes = cursor.skip_until(b'\0')
2537    ///     .expect("reading from cursor won't fail");
2538    /// assert_eq!(num_bytes, 1);
2539    /// ```
2540    #[stable(feature = "bufread_skip_until", since = "1.83.0")]
2541    fn skip_until(&mut self, byte: u8) -> Result<usize> {
2542        skip_until(self, byte)
2543    }
2544
2545    /// Reads all bytes until a newline (the `0xA` byte) is reached, and append
2546    /// them to the provided `String` buffer.
2547    ///
2548    /// Previous content of the buffer will be preserved. To avoid appending to
2549    /// the buffer, you need to [`clear`] it first.
2550    ///
2551    /// This function will read bytes from the underlying stream until the
2552    /// newline delimiter (the `0xA` byte) or EOF is found. Once found, all bytes
2553    /// up to, and including, the delimiter (if found) will be appended to
2554    /// `buf`.
2555    ///
2556    /// If successful, this function will return the total number of bytes read.
2557    ///
2558    /// If this function returns [`Ok(0)`], the stream has reached EOF.
2559    ///
2560    /// This function is blocking and should be used carefully: it is possible for
2561    /// an attacker to continuously send bytes without ever sending a newline
2562    /// or EOF. You can use [`take`] to limit the maximum number of bytes read.
2563    ///
2564    /// [`Ok(0)`]: Ok
2565    /// [`clear`]: String::clear
2566    /// [`take`]: crate::io::Read::take
2567    ///
2568    /// # Errors
2569    ///
2570    /// This function has the same error semantics as [`read_until`] and will
2571    /// also return an error if the read bytes are not valid UTF-8. If an I/O
2572    /// error is encountered then `buf` may contain some bytes already read in
2573    /// the event that all data read so far was valid UTF-8.
2574    ///
2575    /// [`read_until`]: BufRead::read_until
2576    ///
2577    /// # Examples
2578    ///
2579    /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
2580    /// this example, we use [`Cursor`] to read all the lines in a byte slice:
2581    ///
2582    /// ```
2583    /// use std::io::{self, BufRead};
2584    ///
2585    /// let mut cursor = io::Cursor::new(b"foo\nbar");
2586    /// let mut buf = String::new();
2587    ///
2588    /// // cursor is at 'f'
2589    /// let num_bytes = cursor.read_line(&mut buf)
2590    ///     .expect("reading from cursor won't fail");
2591    /// assert_eq!(num_bytes, 4);
2592    /// assert_eq!(buf, "foo\n");
2593    /// buf.clear();
2594    ///
2595    /// // cursor is at 'b'
2596    /// let num_bytes = cursor.read_line(&mut buf)
2597    ///     .expect("reading from cursor won't fail");
2598    /// assert_eq!(num_bytes, 3);
2599    /// assert_eq!(buf, "bar");
2600    /// buf.clear();
2601    ///
2602    /// // cursor is at EOF
2603    /// let num_bytes = cursor.read_line(&mut buf)
2604    ///     .expect("reading from cursor won't fail");
2605    /// assert_eq!(num_bytes, 0);
2606    /// assert_eq!(buf, "");
2607    /// ```
2608    #[stable(feature = "rust1", since = "1.0.0")]
2609    fn read_line(&mut self, buf: &mut String) -> Result<usize> {
2610        // Note that we are not calling the `.read_until` method here, but
2611        // rather our hardcoded implementation. For more details as to why, see
2612        // the comments in `default_read_to_string`.
2613        unsafe { append_to_string(buf, |b| read_until(self, b'\n', b)) }
2614    }
2615
2616    /// Returns an iterator over the contents of this reader split on the byte
2617    /// `byte`.
2618    ///
2619    /// The iterator returned from this function will return instances of
2620    /// <code>[io::Result]<[Vec]\<u8>></code>. Each vector returned will *not* have
2621    /// the delimiter byte at the end.
2622    ///
2623    /// This function will yield errors whenever [`read_until`] would have
2624    /// also yielded an error.
2625    ///
2626    /// [io::Result]: self::Result "io::Result"
2627    /// [`read_until`]: BufRead::read_until
2628    ///
2629    /// # Examples
2630    ///
2631    /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
2632    /// this example, we use [`Cursor`] to iterate over all hyphen delimited
2633    /// segments in a byte slice
2634    ///
2635    /// ```
2636    /// use std::io::{self, BufRead};
2637    ///
2638    /// let cursor = io::Cursor::new(b"lorem-ipsum-dolor");
2639    ///
2640    /// let mut split_iter = cursor.split(b'-').map(|l| l.unwrap());
2641    /// assert_eq!(split_iter.next(), Some(b"lorem".to_vec()));
2642    /// assert_eq!(split_iter.next(), Some(b"ipsum".to_vec()));
2643    /// assert_eq!(split_iter.next(), Some(b"dolor".to_vec()));
2644    /// assert_eq!(split_iter.next(), None);
2645    /// ```
2646    #[stable(feature = "rust1", since = "1.0.0")]
2647    fn split(self, byte: u8) -> Split<Self>
2648    where
2649        Self: Sized,
2650    {
2651        Split { buf: self, delim: byte }
2652    }
2653
2654    /// Returns an iterator over the lines of this reader.
2655    ///
2656    /// The iterator returned from this function will yield instances of
2657    /// <code>[io::Result]<[String]></code>. Each string returned will *not* have a newline
2658    /// byte (the `0xA` byte) or `CRLF` (`0xD`, `0xA` bytes) at the end.
2659    ///
2660    /// [io::Result]: self::Result "io::Result"
2661    ///
2662    /// # Examples
2663    ///
2664    /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
2665    /// this example, we use [`Cursor`] to iterate over all the lines in a byte
2666    /// slice.
2667    ///
2668    /// ```
2669    /// use std::io::{self, BufRead};
2670    ///
2671    /// let cursor = io::Cursor::new(b"lorem\nipsum\r\ndolor");
2672    ///
2673    /// let mut lines_iter = cursor.lines().map(|l| l.unwrap());
2674    /// assert_eq!(lines_iter.next(), Some(String::from("lorem")));
2675    /// assert_eq!(lines_iter.next(), Some(String::from("ipsum")));
2676    /// assert_eq!(lines_iter.next(), Some(String::from("dolor")));
2677    /// assert_eq!(lines_iter.next(), None);
2678    /// ```
2679    ///
2680    /// # Errors
2681    ///
2682    /// Each line of the iterator has the same error semantics as [`BufRead::read_line`].
2683    #[stable(feature = "rust1", since = "1.0.0")]
2684    fn lines(self) -> Lines<Self>
2685    where
2686        Self: Sized,
2687    {
2688        Lines { buf: self }
2689    }
2690}
2691
2692/// Adapter to chain together two readers.
2693///
2694/// This struct is generally created by calling [`chain`] on a reader.
2695/// Please see the documentation of [`chain`] for more details.
2696///
2697/// [`chain`]: Read::chain
2698#[stable(feature = "rust1", since = "1.0.0")]
2699#[derive(Debug)]
2700pub struct Chain<T, U> {
2701    first: T,
2702    second: U,
2703    done_first: bool,
2704}
2705
2706impl<T, U> Chain<T, U> {
2707    /// Consumes the `Chain`, returning the wrapped readers.
2708    ///
2709    /// # Examples
2710    ///
2711    /// ```no_run
2712    /// use std::io;
2713    /// use std::io::prelude::*;
2714    /// use std::fs::File;
2715    ///
2716    /// fn main() -> io::Result<()> {
2717    ///     let mut foo_file = File::open("foo.txt")?;
2718    ///     let mut bar_file = File::open("bar.txt")?;
2719    ///
2720    ///     let chain = foo_file.chain(bar_file);
2721    ///     let (foo_file, bar_file) = chain.into_inner();
2722    ///     Ok(())
2723    /// }
2724    /// ```
2725    #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2726    pub fn into_inner(self) -> (T, U) {
2727        (self.first, self.second)
2728    }
2729
2730    /// Gets references to the underlying readers in this `Chain`.
2731    ///
2732    /// Care should be taken to avoid modifying the internal I/O state of the
2733    /// underlying readers as doing so may corrupt the internal state of this
2734    /// `Chain`.
2735    ///
2736    /// # Examples
2737    ///
2738    /// ```no_run
2739    /// use std::io;
2740    /// use std::io::prelude::*;
2741    /// use std::fs::File;
2742    ///
2743    /// fn main() -> io::Result<()> {
2744    ///     let mut foo_file = File::open("foo.txt")?;
2745    ///     let mut bar_file = File::open("bar.txt")?;
2746    ///
2747    ///     let chain = foo_file.chain(bar_file);
2748    ///     let (foo_file, bar_file) = chain.get_ref();
2749    ///     Ok(())
2750    /// }
2751    /// ```
2752    #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2753    pub fn get_ref(&self) -> (&T, &U) {
2754        (&self.first, &self.second)
2755    }
2756
2757    /// Gets mutable references to the underlying readers in this `Chain`.
2758    ///
2759    /// Care should be taken to avoid modifying the internal I/O state of the
2760    /// underlying readers as doing so may corrupt the internal state of this
2761    /// `Chain`.
2762    ///
2763    /// # Examples
2764    ///
2765    /// ```no_run
2766    /// use std::io;
2767    /// use std::io::prelude::*;
2768    /// use std::fs::File;
2769    ///
2770    /// fn main() -> io::Result<()> {
2771    ///     let mut foo_file = File::open("foo.txt")?;
2772    ///     let mut bar_file = File::open("bar.txt")?;
2773    ///
2774    ///     let mut chain = foo_file.chain(bar_file);
2775    ///     let (foo_file, bar_file) = chain.get_mut();
2776    ///     Ok(())
2777    /// }
2778    /// ```
2779    #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
2780    pub fn get_mut(&mut self) -> (&mut T, &mut U) {
2781        (&mut self.first, &mut self.second)
2782    }
2783}
2784
2785#[stable(feature = "rust1", since = "1.0.0")]
2786impl<T: Read, U: Read> Read for Chain<T, U> {
2787    fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
2788        if !self.done_first {
2789            match self.first.read(buf)? {
2790                0 if !buf.is_empty() => self.done_first = true,
2791                n => return Ok(n),
2792            }
2793        }
2794        self.second.read(buf)
2795    }
2796
2797    fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize> {
2798        if !self.done_first {
2799            match self.first.read_vectored(bufs)? {
2800                0 if bufs.iter().any(|b| !b.is_empty()) => self.done_first = true,
2801                n => return Ok(n),
2802            }
2803        }
2804        self.second.read_vectored(bufs)
2805    }
2806
2807    #[inline]
2808    fn is_read_vectored(&self) -> bool {
2809        self.first.is_read_vectored() || self.second.is_read_vectored()
2810    }
2811
2812    fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
2813        let mut read = 0;
2814        if !self.done_first {
2815            read += self.first.read_to_end(buf)?;
2816            self.done_first = true;
2817        }
2818        read += self.second.read_to_end(buf)?;
2819        Ok(read)
2820    }
2821
2822    // We don't override `read_to_string` here because an UTF-8 sequence could
2823    // be split between the two parts of the chain
2824
2825    fn read_buf(&mut self, mut buf: BorrowedCursor<'_>) -> Result<()> {
2826        if buf.capacity() == 0 {
2827            return Ok(());
2828        }
2829
2830        if !self.done_first {
2831            let old_len = buf.written();
2832            self.first.read_buf(buf.reborrow())?;
2833
2834            if buf.written() != old_len {
2835                return Ok(());
2836            } else {
2837                self.done_first = true;
2838            }
2839        }
2840        self.second.read_buf(buf)
2841    }
2842}
2843
2844#[stable(feature = "chain_bufread", since = "1.9.0")]
2845impl<T: BufRead, U: BufRead> BufRead for Chain<T, U> {
2846    fn fill_buf(&mut self) -> Result<&[u8]> {
2847        if !self.done_first {
2848            match self.first.fill_buf()? {
2849                buf if buf.is_empty() => self.done_first = true,
2850                buf => return Ok(buf),
2851            }
2852        }
2853        self.second.fill_buf()
2854    }
2855
2856    fn consume(&mut self, amt: usize) {
2857        if !self.done_first { self.first.consume(amt) } else { self.second.consume(amt) }
2858    }
2859
2860    fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> Result<usize> {
2861        let mut read = 0;
2862        if !self.done_first {
2863            let n = self.first.read_until(byte, buf)?;
2864            read += n;
2865
2866            match buf.last() {
2867                Some(b) if *b == byte && n != 0 => return Ok(read),
2868                _ => self.done_first = true,
2869            }
2870        }
2871        read += self.second.read_until(byte, buf)?;
2872        Ok(read)
2873    }
2874
2875    // We don't override `read_line` here because an UTF-8 sequence could be
2876    // split between the two parts of the chain
2877}
2878
2879impl<T, U> SizeHint for Chain<T, U> {
2880    #[inline]
2881    fn lower_bound(&self) -> usize {
2882        SizeHint::lower_bound(&self.first) + SizeHint::lower_bound(&self.second)
2883    }
2884
2885    #[inline]
2886    fn upper_bound(&self) -> Option<usize> {
2887        match (SizeHint::upper_bound(&self.first), SizeHint::upper_bound(&self.second)) {
2888            (Some(first), Some(second)) => first.checked_add(second),
2889            _ => None,
2890        }
2891    }
2892}
2893
2894/// Reader adapter which limits the bytes read from an underlying reader.
2895///
2896/// This struct is generally created by calling [`take`] on a reader.
2897/// Please see the documentation of [`take`] for more details.
2898///
2899/// [`take`]: Read::take
2900#[stable(feature = "rust1", since = "1.0.0")]
2901#[derive(Debug)]
2902pub struct Take<T> {
2903    inner: T,
2904    len: u64,
2905    limit: u64,
2906}
2907
2908impl<T> Take<T> {
2909    /// Returns the number of bytes that can be read before this instance will
2910    /// return EOF.
2911    ///
2912    /// # Note
2913    ///
2914    /// This instance may reach `EOF` after reading fewer bytes than indicated by
2915    /// this method if the underlying [`Read`] instance reaches EOF.
2916    ///
2917    /// # Examples
2918    ///
2919    /// ```no_run
2920    /// use std::io;
2921    /// use std::io::prelude::*;
2922    /// use std::fs::File;
2923    ///
2924    /// fn main() -> io::Result<()> {
2925    ///     let f = File::open("foo.txt")?;
2926    ///
2927    ///     // read at most five bytes
2928    ///     let handle = f.take(5);
2929    ///
2930    ///     println!("limit: {}", handle.limit());
2931    ///     Ok(())
2932    /// }
2933    /// ```
2934    #[stable(feature = "rust1", since = "1.0.0")]
2935    pub fn limit(&self) -> u64 {
2936        self.limit
2937    }
2938
2939    /// Returns the number of bytes read so far.
2940    #[unstable(feature = "seek_io_take_position", issue = "97227")]
2941    pub fn position(&self) -> u64 {
2942        self.len - self.limit
2943    }
2944
2945    /// Sets the number of bytes that can be read before this instance will
2946    /// return EOF. This is the same as constructing a new `Take` instance, so
2947    /// the amount of bytes read and the previous limit value don't matter when
2948    /// calling this method.
2949    ///
2950    /// # Examples
2951    ///
2952    /// ```no_run
2953    /// use std::io;
2954    /// use std::io::prelude::*;
2955    /// use std::fs::File;
2956    ///
2957    /// fn main() -> io::Result<()> {
2958    ///     let f = File::open("foo.txt")?;
2959    ///
2960    ///     // read at most five bytes
2961    ///     let mut handle = f.take(5);
2962    ///     handle.set_limit(10);
2963    ///
2964    ///     assert_eq!(handle.limit(), 10);
2965    ///     Ok(())
2966    /// }
2967    /// ```
2968    #[stable(feature = "take_set_limit", since = "1.27.0")]
2969    pub fn set_limit(&mut self, limit: u64) {
2970        self.len = limit;
2971        self.limit = limit;
2972    }
2973
2974    /// Consumes the `Take`, returning the wrapped reader.
2975    ///
2976    /// # Examples
2977    ///
2978    /// ```no_run
2979    /// use std::io;
2980    /// use std::io::prelude::*;
2981    /// use std::fs::File;
2982    ///
2983    /// fn main() -> io::Result<()> {
2984    ///     let mut file = File::open("foo.txt")?;
2985    ///
2986    ///     let mut buffer = [0; 5];
2987    ///     let mut handle = file.take(5);
2988    ///     handle.read(&mut buffer)?;
2989    ///
2990    ///     let file = handle.into_inner();
2991    ///     Ok(())
2992    /// }
2993    /// ```
2994    #[stable(feature = "io_take_into_inner", since = "1.15.0")]
2995    pub fn into_inner(self) -> T {
2996        self.inner
2997    }
2998
2999    /// Gets a reference to the underlying reader.
3000    ///
3001    /// Care should be taken to avoid modifying the internal I/O state of the
3002    /// underlying reader as doing so may corrupt the internal limit of this
3003    /// `Take`.
3004    ///
3005    /// # Examples
3006    ///
3007    /// ```no_run
3008    /// use std::io;
3009    /// use std::io::prelude::*;
3010    /// use std::fs::File;
3011    ///
3012    /// fn main() -> io::Result<()> {
3013    ///     let mut file = File::open("foo.txt")?;
3014    ///
3015    ///     let mut buffer = [0; 5];
3016    ///     let mut handle = file.take(5);
3017    ///     handle.read(&mut buffer)?;
3018    ///
3019    ///     let file = handle.get_ref();
3020    ///     Ok(())
3021    /// }
3022    /// ```
3023    #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
3024    pub fn get_ref(&self) -> &T {
3025        &self.inner
3026    }
3027
3028    /// Gets a mutable reference to the underlying reader.
3029    ///
3030    /// Care should be taken to avoid modifying the internal I/O state of the
3031    /// underlying reader as doing so may corrupt the internal limit of this
3032    /// `Take`.
3033    ///
3034    /// # Examples
3035    ///
3036    /// ```no_run
3037    /// use std::io;
3038    /// use std::io::prelude::*;
3039    /// use std::fs::File;
3040    ///
3041    /// fn main() -> io::Result<()> {
3042    ///     let mut file = File::open("foo.txt")?;
3043    ///
3044    ///     let mut buffer = [0; 5];
3045    ///     let mut handle = file.take(5);
3046    ///     handle.read(&mut buffer)?;
3047    ///
3048    ///     let file = handle.get_mut();
3049    ///     Ok(())
3050    /// }
3051    /// ```
3052    #[stable(feature = "more_io_inner_methods", since = "1.20.0")]
3053    pub fn get_mut(&mut self) -> &mut T {
3054        &mut self.inner
3055    }
3056}
3057
3058#[stable(feature = "rust1", since = "1.0.0")]
3059impl<T: Read> Read for Take<T> {
3060    fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
3061        // Don't call into inner reader at all at EOF because it may still block
3062        if self.limit == 0 {
3063            return Ok(0);
3064        }
3065
3066        let max = cmp::min(buf.len() as u64, self.limit) as usize;
3067        let n = self.inner.read(&mut buf[..max])?;
3068        assert!(n as u64 <= self.limit, "number of read bytes exceeds limit");
3069        self.limit -= n as u64;
3070        Ok(n)
3071    }
3072
3073    fn read_buf(&mut self, mut buf: BorrowedCursor<'_>) -> Result<()> {
3074        // Don't call into inner reader at all at EOF because it may still block
3075        if self.limit == 0 {
3076            return Ok(());
3077        }
3078
3079        if self.limit < buf.capacity() as u64 {
3080            // The condition above guarantees that `self.limit` fits in `usize`.
3081            let limit = self.limit as usize;
3082
3083            let is_init = buf.is_init();
3084
3085            // SAFETY: no uninit data is written to ibuf
3086            let ibuf = unsafe { &mut buf.as_mut()[..limit] };
3087
3088            let mut sliced_buf: BorrowedBuf<'_> = ibuf.into();
3089
3090            // SAFETY: extra_init bytes of ibuf are known to be initialized
3091            if is_init {
3092                unsafe { sliced_buf.set_init() };
3093            }
3094
3095            let mut cursor = sliced_buf.unfilled();
3096            let result = self.inner.read_buf(cursor.reborrow());
3097
3098            let should_init = cursor.is_init();
3099            let filled = sliced_buf.len();
3100
3101            // cursor / sliced_buf / ibuf must drop here
3102
3103            // Avoid accidentally quadratic behaviour by initializing the whole
3104            // cursor if only part of it was initialized.
3105            if should_init {
3106                // SAFETY: no uninit data is written
3107                let uninit = unsafe { &mut buf.as_mut()[limit..] };
3108                uninit.write_filled(0);
3109                // SAFETY: all bytes that were not initialized by `T::read_buf`
3110                // have just been written to.
3111                unsafe { buf.set_init() };
3112            }
3113
3114            unsafe {
3115                // SAFETY: filled bytes have been filled
3116                buf.advance(filled);
3117            }
3118
3119            self.limit -= filled as u64;
3120
3121            result
3122        } else {
3123            let written = buf.written();
3124            let result = self.inner.read_buf(buf.reborrow());
3125            self.limit -= (buf.written() - written) as u64;
3126            result
3127        }
3128    }
3129}
3130
3131#[stable(feature = "rust1", since = "1.0.0")]
3132impl<T: BufRead> BufRead for Take<T> {
3133    fn fill_buf(&mut self) -> Result<&[u8]> {
3134        // Don't call into inner reader at all at EOF because it may still block
3135        if self.limit == 0 {
3136            return Ok(&[]);
3137        }
3138
3139        let buf = self.inner.fill_buf()?;
3140        let cap = cmp::min(buf.len() as u64, self.limit) as usize;
3141        Ok(&buf[..cap])
3142    }
3143
3144    fn consume(&mut self, amt: usize) {
3145        // Don't let callers reset the limit by passing an overlarge value
3146        let amt = cmp::min(amt as u64, self.limit) as usize;
3147        self.limit -= amt as u64;
3148        self.inner.consume(amt);
3149    }
3150}
3151
3152impl<T> SizeHint for Take<T> {
3153    #[inline]
3154    fn lower_bound(&self) -> usize {
3155        cmp::min(SizeHint::lower_bound(&self.inner) as u64, self.limit) as usize
3156    }
3157
3158    #[inline]
3159    fn upper_bound(&self) -> Option<usize> {
3160        match SizeHint::upper_bound(&self.inner) {
3161            Some(upper_bound) => Some(cmp::min(upper_bound as u64, self.limit) as usize),
3162            None => self.limit.try_into().ok(),
3163        }
3164    }
3165}
3166
3167#[stable(feature = "seek_io_take", since = "1.89.0")]
3168impl<T: Seek> Seek for Take<T> {
3169    fn seek(&mut self, pos: SeekFrom) -> Result<u64> {
3170        let new_position = match pos {
3171            SeekFrom::Start(v) => Some(v),
3172            SeekFrom::Current(v) => self.position().checked_add_signed(v),
3173            SeekFrom::End(v) => self.len.checked_add_signed(v),
3174        };
3175        let new_position = match new_position {
3176            Some(v) if v <= self.len => v,
3177            _ => return Err(ErrorKind::InvalidInput.into()),
3178        };
3179        while new_position != self.position() {
3180            if let Some(offset) = new_position.checked_signed_diff(self.position()) {
3181                self.inner.seek_relative(offset)?;
3182                self.limit = self.limit.wrapping_sub(offset as u64);
3183                break;
3184            }
3185            let offset = if new_position > self.position() { i64::MAX } else { i64::MIN };
3186            self.inner.seek_relative(offset)?;
3187            self.limit = self.limit.wrapping_sub(offset as u64);
3188        }
3189        Ok(new_position)
3190    }
3191
3192    fn stream_len(&mut self) -> Result<u64> {
3193        Ok(self.len)
3194    }
3195
3196    fn stream_position(&mut self) -> Result<u64> {
3197        Ok(self.position())
3198    }
3199
3200    fn seek_relative(&mut self, offset: i64) -> Result<()> {
3201        if !self.position().checked_add_signed(offset).is_some_and(|p| p <= self.len) {
3202            return Err(ErrorKind::InvalidInput.into());
3203        }
3204        self.inner.seek_relative(offset)?;
3205        self.limit = self.limit.wrapping_sub(offset as u64);
3206        Ok(())
3207    }
3208}
3209
3210/// An iterator over `u8` values of a reader.
3211///
3212/// This struct is generally created by calling [`bytes`] on a reader.
3213/// Please see the documentation of [`bytes`] for more details.
3214///
3215/// [`bytes`]: Read::bytes
3216#[stable(feature = "rust1", since = "1.0.0")]
3217#[derive(Debug)]
3218pub struct Bytes<R> {
3219    inner: R,
3220}
3221
3222#[stable(feature = "rust1", since = "1.0.0")]
3223impl<R: Read> Iterator for Bytes<R> {
3224    type Item = Result<u8>;
3225
3226    // Not `#[inline]`. This function gets inlined even without it, but having
3227    // the inline annotation can result in worse code generation. See #116785.
3228    fn next(&mut self) -> Option<Result<u8>> {
3229        SpecReadByte::spec_read_byte(&mut self.inner)
3230    }
3231
3232    #[inline]
3233    fn size_hint(&self) -> (usize, Option<usize>) {
3234        SizeHint::size_hint(&self.inner)
3235    }
3236}
3237
3238/// For the specialization of `Bytes::next`.
3239trait SpecReadByte {
3240    fn spec_read_byte(&mut self) -> Option<Result<u8>>;
3241}
3242
3243impl<R> SpecReadByte for R
3244where
3245    Self: Read,
3246{
3247    #[inline]
3248    default fn spec_read_byte(&mut self) -> Option<Result<u8>> {
3249        inlined_slow_read_byte(self)
3250    }
3251}
3252
3253/// Reads a single byte in a slow, generic way. This is used by the default
3254/// `spec_read_byte`.
3255#[inline]
3256fn inlined_slow_read_byte<R: Read>(reader: &mut R) -> Option<Result<u8>> {
3257    let mut byte = 0;
3258    loop {
3259        return match reader.read(slice::from_mut(&mut byte)) {
3260            Ok(0) => None,
3261            Ok(..) => Some(Ok(byte)),
3262            Err(ref e) if e.is_interrupted() => continue,
3263            Err(e) => Some(Err(e)),
3264        };
3265    }
3266}
3267
3268// Used by `BufReader::spec_read_byte`, for which the `inline(never)` is
3269// important.
3270#[inline(never)]
3271fn uninlined_slow_read_byte<R: Read>(reader: &mut R) -> Option<Result<u8>> {
3272    inlined_slow_read_byte(reader)
3273}
3274
3275trait SizeHint {
3276    fn lower_bound(&self) -> usize;
3277
3278    fn upper_bound(&self) -> Option<usize>;
3279
3280    fn size_hint(&self) -> (usize, Option<usize>) {
3281        (self.lower_bound(), self.upper_bound())
3282    }
3283}
3284
3285impl<T: ?Sized> SizeHint for T {
3286    #[inline]
3287    default fn lower_bound(&self) -> usize {
3288        0
3289    }
3290
3291    #[inline]
3292    default fn upper_bound(&self) -> Option<usize> {
3293        None
3294    }
3295}
3296
3297impl<T> SizeHint for &mut T {
3298    #[inline]
3299    fn lower_bound(&self) -> usize {
3300        SizeHint::lower_bound(*self)
3301    }
3302
3303    #[inline]
3304    fn upper_bound(&self) -> Option<usize> {
3305        SizeHint::upper_bound(*self)
3306    }
3307}
3308
3309impl<T> SizeHint for Box<T> {
3310    #[inline]
3311    fn lower_bound(&self) -> usize {
3312        SizeHint::lower_bound(&**self)
3313    }
3314
3315    #[inline]
3316    fn upper_bound(&self) -> Option<usize> {
3317        SizeHint::upper_bound(&**self)
3318    }
3319}
3320
3321impl SizeHint for &[u8] {
3322    #[inline]
3323    fn lower_bound(&self) -> usize {
3324        self.len()
3325    }
3326
3327    #[inline]
3328    fn upper_bound(&self) -> Option<usize> {
3329        Some(self.len())
3330    }
3331}
3332
3333/// An iterator over the contents of an instance of `BufRead` split on a
3334/// particular byte.
3335///
3336/// This struct is generally created by calling [`split`] on a `BufRead`.
3337/// Please see the documentation of [`split`] for more details.
3338///
3339/// [`split`]: BufRead::split
3340#[stable(feature = "rust1", since = "1.0.0")]
3341#[derive(Debug)]
3342#[cfg_attr(not(test), rustc_diagnostic_item = "IoSplit")]
3343pub struct Split<B> {
3344    buf: B,
3345    delim: u8,
3346}
3347
3348#[stable(feature = "rust1", since = "1.0.0")]
3349impl<B: BufRead> Iterator for Split<B> {
3350    type Item = Result<Vec<u8>>;
3351
3352    fn next(&mut self) -> Option<Result<Vec<u8>>> {
3353        let mut buf = Vec::new();
3354        match self.buf.read_until(self.delim, &mut buf) {
3355            Ok(0) => None,
3356            Ok(_n) => {
3357                if buf[buf.len() - 1] == self.delim {
3358                    buf.pop();
3359                }
3360                Some(Ok(buf))
3361            }
3362            Err(e) => Some(Err(e)),
3363        }
3364    }
3365}
3366
3367/// An iterator over the lines of an instance of `BufRead`.
3368///
3369/// This struct is generally created by calling [`lines`] on a `BufRead`.
3370/// Please see the documentation of [`lines`] for more details.
3371///
3372/// [`lines`]: BufRead::lines
3373#[stable(feature = "rust1", since = "1.0.0")]
3374#[derive(Debug)]
3375#[cfg_attr(not(test), rustc_diagnostic_item = "IoLines")]
3376pub struct Lines<B> {
3377    buf: B,
3378}
3379
3380#[stable(feature = "rust1", since = "1.0.0")]
3381impl<B: BufRead> Iterator for Lines<B> {
3382    type Item = Result<String>;
3383
3384    fn next(&mut self) -> Option<Result<String>> {
3385        let mut buf = String::new();
3386        match self.buf.read_line(&mut buf) {
3387            Ok(0) => None,
3388            Ok(_n) => {
3389                if buf.ends_with('\n') {
3390                    buf.pop();
3391                    if buf.ends_with('\r') {
3392                        buf.pop();
3393                    }
3394                }
3395                Some(Ok(buf))
3396            }
3397            Err(e) => Some(Err(e)),
3398        }
3399    }
3400}