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