Skip to main content

std/io/
mod.rs

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