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<'_, u8> = 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<'_, u8>) -> 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<'_, u8>,
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<'_, u8>) -> 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<'_, u8>) -> 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    /// Read and return a type (e.g. an integer) in little-endian order.
1271    ///
1272    /// You can specify the type with turbofish (`reader.read_le::<u64>()`), or let type inference
1273    /// determine the type based on how the return value gets used.
1274    ///
1275    /// Like `read_exact`, if this function encounters an "end of file" before reading the desired
1276    /// number of bytes, it returns an error of the kind [`ErrorKind::UnexpectedEof`].
1277    ///
1278    /// ```
1279    /// #![feature(read_le)]
1280    /// use std::io::Cursor;
1281    /// use std::io::prelude::*;
1282    ///
1283    /// fn main() -> std::io::Result<()> {
1284    ///     let mut buf = Cursor::new([1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3, 2]);
1285    ///     let x: u64 = buf.read_le()?;
1286    ///     let y: u32 = buf.read_le()?;
1287    ///     let z = buf.read_le::<u16>()?;
1288    ///     assert_eq!(x, 0x807060504030201);
1289    ///     assert_eq!(y, 0x6070809);
1290    ///     assert_eq!(z, 0x405);
1291    ///     Ok(())
1292    /// }
1293    /// ```
1294    #[unstable(feature = "read_le", issue = "156983")]
1295    #[inline]
1296    fn read_le<T: FromEndianBytes>(&mut self) -> Result<T>
1297    where
1298        Self: Sized,
1299    {
1300        T::read_le_from(self)
1301    }
1302
1303    /// Read and return a type (e.g. an integer) in big-endian order.
1304    ///
1305    /// You can specify the type with turbofish (`reader.read_be::<u64>()`), or let type inference
1306    /// determine the type based on how the return value gets used.
1307    ///
1308    /// Like `read_exact`, if this function encounters an "end of file" before reading the desired
1309    /// number of bytes, it returns an error of the kind [`ErrorKind::UnexpectedEof`].
1310    ///
1311    /// ```
1312    /// #![feature(read_le)]
1313    /// use std::io::Cursor;
1314    /// use std::io::prelude::*;
1315    ///
1316    /// fn main() -> std::io::Result<()> {
1317    ///     let mut buf = Cursor::new([1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3, 2]);
1318    ///     let x: u64 = buf.read_be()?;
1319    ///     let y: u32 = buf.read_be()?;
1320    ///     let z = buf.read_be::<u16>()?;
1321    ///     assert_eq!(x, 0x102030405060708);
1322    ///     assert_eq!(y, 0x9080706);
1323    ///     assert_eq!(z, 0x504);
1324    ///     Ok(())
1325    /// }
1326    /// ```
1327    #[unstable(feature = "read_le", issue = "156983")]
1328    #[inline]
1329    fn read_be<T: FromEndianBytes>(&mut self) -> Result<T>
1330    where
1331        Self: Sized,
1332    {
1333        T::read_be_from(self)
1334    }
1335}
1336
1337/// Reads all bytes from a [reader][Read] into a new [`String`].
1338///
1339/// This is a convenience function for [`Read::read_to_string`]. Using this
1340/// function avoids having to create a variable first and provides more type
1341/// safety since you can only get the buffer out if there were no errors. (If you
1342/// use [`Read::read_to_string`] you have to remember to check whether the read
1343/// succeeded because otherwise your buffer will be empty or only partially full.)
1344///
1345/// # Performance
1346///
1347/// The downside of this function's increased ease of use and type safety is
1348/// that it gives you less control over performance. For example, you can't
1349/// pre-allocate memory like you can using [`String::with_capacity`] and
1350/// [`Read::read_to_string`]. Also, you can't re-use the buffer if an error
1351/// occurs while reading.
1352///
1353/// In many cases, this function's performance will be adequate and the ease of use
1354/// and type safety tradeoffs will be worth it. However, there are cases where you
1355/// need more control over performance, and in those cases you should definitely use
1356/// [`Read::read_to_string`] directly.
1357///
1358/// Note that in some special cases, such as when reading files, this function will
1359/// pre-allocate memory based on the size of the input it is reading. In those
1360/// cases, the performance should be as good as if you had used
1361/// [`Read::read_to_string`] with a manually pre-allocated buffer.
1362///
1363/// # Errors
1364///
1365/// This function forces you to handle errors because the output (the `String`)
1366/// is wrapped in a [`Result`]. See [`Read::read_to_string`] for the errors
1367/// that can occur. If any error occurs, you will get an [`Err`], so you
1368/// don't have to worry about your buffer being empty or partially full.
1369///
1370/// # Examples
1371///
1372/// ```no_run
1373/// # use std::io;
1374/// fn main() -> io::Result<()> {
1375///     let stdin = io::read_to_string(io::stdin())?;
1376///     println!("Stdin was:");
1377///     println!("{stdin}");
1378///     Ok(())
1379/// }
1380/// ```
1381///
1382/// # Usage Notes
1383///
1384/// `read_to_string` attempts to read a source until EOF, but many sources are continuous streams
1385/// that do not send EOF. In these cases, `read_to_string` will block indefinitely. Standard input
1386/// is one such stream which may be finite if piped, but is typically continuous. For example,
1387/// `cat file | my-rust-program` will correctly terminate with an `EOF` upon closure of cat.
1388/// Reading user input or running programs that remain open indefinitely will never terminate
1389/// the stream with `EOF` (e.g. `yes | my-rust-program`).
1390///
1391/// Using `.lines()` with a [`BufReader`] or using [`read`] can provide a better solution
1392///
1393///[`read`]: Read::read
1394///
1395#[stable(feature = "io_read_to_string", since = "1.65.0")]
1396pub fn read_to_string<R: Read>(mut reader: R) -> Result<String> {
1397    let mut buf = String::new();
1398    reader.read_to_string(&mut buf)?;
1399    Ok(buf)
1400}
1401
1402/// A trait for objects which are byte-oriented sinks.
1403///
1404/// Implementors of the `Write` trait are sometimes called 'writers'.
1405///
1406/// Writers are defined by two required methods, [`write`] and [`flush`]:
1407///
1408/// * The [`write`] method will attempt to write some data into the object,
1409///   returning how many bytes were successfully written.
1410///
1411/// * The [`flush`] method is useful for adapters and explicit buffers
1412///   themselves for ensuring that all buffered data has been pushed out to the
1413///   'true sink'.
1414///
1415/// Writers are intended to be composable with one another. Many implementors
1416/// throughout [`std::io`] take and provide types which implement the `Write`
1417/// trait.
1418///
1419/// [`write`]: Write::write
1420/// [`flush`]: Write::flush
1421/// [`std::io`]: self
1422///
1423/// # Examples
1424///
1425/// ```no_run
1426/// use std::io::prelude::*;
1427/// use std::fs::File;
1428///
1429/// fn main() -> std::io::Result<()> {
1430///     let data = b"some bytes";
1431///
1432///     let mut pos = 0;
1433///     let mut buffer = File::create("foo.txt")?;
1434///
1435///     while pos < data.len() {
1436///         let bytes_written = buffer.write(&data[pos..])?;
1437///         pos += bytes_written;
1438///     }
1439///     Ok(())
1440/// }
1441/// ```
1442///
1443/// The trait also provides convenience methods like [`write_all`], which calls
1444/// `write` in a loop until its entire input has been written.
1445///
1446/// [`write_all`]: Write::write_all
1447#[stable(feature = "rust1", since = "1.0.0")]
1448#[doc(notable_trait)]
1449#[cfg_attr(not(test), rustc_diagnostic_item = "IoWrite")]
1450pub trait Write {
1451    /// Writes a buffer into this writer, returning how many bytes were written.
1452    ///
1453    /// This function will attempt to write the entire contents of `buf`, but
1454    /// the entire write might not succeed, or the write may also generate an
1455    /// error. Typically, a call to `write` represents one attempt to write to
1456    /// any wrapped object.
1457    ///
1458    /// Calls to `write` are not guaranteed to block waiting for data to be
1459    /// written, and a write which would otherwise block can be indicated through
1460    /// an [`Err`] variant.
1461    ///
1462    /// If this method consumed `n > 0` bytes of `buf` it must return [`Ok(n)`].
1463    /// If the return value is `Ok(n)` then `n` must satisfy `n <= buf.len()`.
1464    /// A return value of `Ok(0)` typically means that the underlying object is
1465    /// no longer able to accept bytes and will likely not be able to in the
1466    /// future as well, or that the buffer provided is empty.
1467    ///
1468    /// # Errors
1469    ///
1470    /// Each call to `write` may generate an I/O error indicating that the
1471    /// operation could not be completed. If an error is returned then no bytes
1472    /// in the buffer were written to this writer.
1473    ///
1474    /// It is **not** considered an error if the entire buffer could not be
1475    /// written to this writer.
1476    ///
1477    /// An error of the [`ErrorKind::Interrupted`] kind is non-fatal and the
1478    /// write operation should be retried if there is nothing else to do.
1479    ///
1480    /// # Examples
1481    ///
1482    /// ```no_run
1483    /// use std::io::prelude::*;
1484    /// use std::fs::File;
1485    ///
1486    /// fn main() -> std::io::Result<()> {
1487    ///     let mut buffer = File::create("foo.txt")?;
1488    ///
1489    ///     // Writes some prefix of the byte string, not necessarily all of it.
1490    ///     buffer.write(b"some bytes")?;
1491    ///     Ok(())
1492    /// }
1493    /// ```
1494    ///
1495    /// [`Ok(n)`]: Ok
1496    #[stable(feature = "rust1", since = "1.0.0")]
1497    fn write(&mut self, buf: &[u8]) -> Result<usize>;
1498
1499    /// Like [`write`], except that it writes from a slice of buffers.
1500    ///
1501    /// Data is copied from each buffer in order, with the final buffer
1502    /// read from possibly being only partially consumed. This method must
1503    /// behave as a call to [`write`] with the buffers concatenated would.
1504    ///
1505    /// The default implementation calls [`write`] with either the first nonempty
1506    /// buffer provided, or an empty one if none exists.
1507    ///
1508    /// # Examples
1509    ///
1510    /// ```no_run
1511    /// use std::io::IoSlice;
1512    /// use std::io::prelude::*;
1513    /// use std::fs::File;
1514    ///
1515    /// fn main() -> std::io::Result<()> {
1516    ///     let data1 = [1; 8];
1517    ///     let data2 = [15; 8];
1518    ///     let io_slice1 = IoSlice::new(&data1);
1519    ///     let io_slice2 = IoSlice::new(&data2);
1520    ///
1521    ///     let mut buffer = File::create("foo.txt")?;
1522    ///
1523    ///     // Writes some prefix of the byte string, not necessarily all of it.
1524    ///     buffer.write_vectored(&[io_slice1, io_slice2])?;
1525    ///     Ok(())
1526    /// }
1527    /// ```
1528    ///
1529    /// [`write`]: Write::write
1530    #[stable(feature = "iovec", since = "1.36.0")]
1531    fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> Result<usize> {
1532        default_write_vectored(|b| self.write(b), bufs)
1533    }
1534
1535    /// Determines if this `Write`r has an efficient [`write_vectored`]
1536    /// implementation.
1537    ///
1538    /// If a `Write`r does not override the default [`write_vectored`]
1539    /// implementation, code using it may want to avoid the method all together
1540    /// and coalesce writes into a single buffer for higher performance.
1541    ///
1542    /// The default implementation returns `false`.
1543    ///
1544    /// [`write_vectored`]: Write::write_vectored
1545    #[unstable(feature = "can_vector", issue = "69941")]
1546    fn is_write_vectored(&self) -> bool {
1547        false
1548    }
1549
1550    /// Flushes this output stream, ensuring that all intermediately buffered
1551    /// contents reach their destination.
1552    ///
1553    /// # Errors
1554    ///
1555    /// It is considered an error if not all bytes could be written due to
1556    /// I/O errors or EOF being reached.
1557    ///
1558    /// # Examples
1559    ///
1560    /// ```no_run
1561    /// use std::io::prelude::*;
1562    /// use std::io::BufWriter;
1563    /// use std::fs::File;
1564    ///
1565    /// fn main() -> std::io::Result<()> {
1566    ///     let mut buffer = BufWriter::new(File::create("foo.txt")?);
1567    ///
1568    ///     buffer.write_all(b"some bytes")?;
1569    ///     buffer.flush()?;
1570    ///     Ok(())
1571    /// }
1572    /// ```
1573    #[stable(feature = "rust1", since = "1.0.0")]
1574    fn flush(&mut self) -> Result<()>;
1575
1576    /// Attempts to write an entire buffer into this writer.
1577    ///
1578    /// This method will continuously call [`write`] until there is no more data
1579    /// to be written or an error of non-[`ErrorKind::Interrupted`] kind is
1580    /// returned. This method will not return until the entire buffer has been
1581    /// successfully written or such an error occurs. The first error that is
1582    /// not of [`ErrorKind::Interrupted`] kind generated from this method will be
1583    /// returned.
1584    ///
1585    /// If the buffer contains no data, this will never call [`write`].
1586    ///
1587    /// # Errors
1588    ///
1589    /// This function will return the first error of
1590    /// non-[`ErrorKind::Interrupted`] kind that [`write`] returns.
1591    ///
1592    /// [`write`]: Write::write
1593    ///
1594    /// # Examples
1595    ///
1596    /// ```no_run
1597    /// use std::io::prelude::*;
1598    /// use std::fs::File;
1599    ///
1600    /// fn main() -> std::io::Result<()> {
1601    ///     let mut buffer = File::create("foo.txt")?;
1602    ///
1603    ///     buffer.write_all(b"some bytes")?;
1604    ///     Ok(())
1605    /// }
1606    /// ```
1607    #[stable(feature = "rust1", since = "1.0.0")]
1608    fn write_all(&mut self, mut buf: &[u8]) -> Result<()> {
1609        while !buf.is_empty() {
1610            match self.write(buf) {
1611                Ok(0) => {
1612                    return Err(Error::WRITE_ALL_EOF);
1613                }
1614                Ok(n) => buf = &buf[n..],
1615                Err(ref e) if e.is_interrupted() => {}
1616                Err(e) => return Err(e),
1617            }
1618        }
1619        Ok(())
1620    }
1621
1622    /// Attempts to write multiple buffers into this writer.
1623    ///
1624    /// This method will continuously call [`write_vectored`] until there is no
1625    /// more data to be written or an error of non-[`ErrorKind::Interrupted`]
1626    /// kind is returned. This method will not return until all buffers have
1627    /// been successfully written or such an error occurs. The first error that
1628    /// is not of [`ErrorKind::Interrupted`] kind generated from this method
1629    /// will be returned.
1630    ///
1631    /// If the buffer contains no data, this will never call [`write_vectored`].
1632    ///
1633    /// # Notes
1634    ///
1635    /// Unlike [`write_vectored`], this takes a *mutable* reference to
1636    /// a slice of [`IoSlice`]s, not an immutable one. That's because we need to
1637    /// modify the slice to keep track of the bytes already written.
1638    ///
1639    /// Once this function returns, the contents of `bufs` are unspecified, as
1640    /// this depends on how many calls to [`write_vectored`] were necessary. It is
1641    /// best to understand this function as taking ownership of `bufs` and to
1642    /// not use `bufs` afterwards. The underlying buffers, to which the
1643    /// [`IoSlice`]s point (but not the [`IoSlice`]s themselves), are unchanged and
1644    /// can be reused.
1645    ///
1646    /// [`write_vectored`]: Write::write_vectored
1647    ///
1648    /// # Examples
1649    ///
1650    /// ```
1651    /// #![feature(write_all_vectored)]
1652    /// # fn main() -> std::io::Result<()> {
1653    ///
1654    /// use std::io::{Write, IoSlice};
1655    ///
1656    /// let mut writer = Vec::new();
1657    /// let bufs = &mut [
1658    ///     IoSlice::new(&[1]),
1659    ///     IoSlice::new(&[2, 3]),
1660    ///     IoSlice::new(&[4, 5, 6]),
1661    /// ];
1662    ///
1663    /// writer.write_all_vectored(bufs)?;
1664    /// // Note: the contents of `bufs` is now undefined, see the Notes section.
1665    ///
1666    /// assert_eq!(writer, &[1, 2, 3, 4, 5, 6]);
1667    /// # Ok(()) }
1668    /// ```
1669    #[unstable(feature = "write_all_vectored", issue = "70436")]
1670    fn write_all_vectored(&mut self, mut bufs: &mut [IoSlice<'_>]) -> Result<()> {
1671        // Guarantee that bufs is empty if it contains no data,
1672        // to avoid calling write_vectored if there is no data to be written.
1673        IoSlice::advance_slices(&mut bufs, 0);
1674        while !bufs.is_empty() {
1675            match self.write_vectored(bufs) {
1676                Ok(0) => {
1677                    return Err(Error::WRITE_ALL_EOF);
1678                }
1679                Ok(n) => IoSlice::advance_slices(&mut bufs, n),
1680                Err(ref e) if e.is_interrupted() => {}
1681                Err(e) => return Err(e),
1682            }
1683        }
1684        Ok(())
1685    }
1686
1687    /// Writes a formatted string into this writer, returning any error
1688    /// encountered.
1689    ///
1690    /// This method is primarily used to interface with the
1691    /// [`format_args!()`] macro, and it is rare that this should
1692    /// explicitly be called. The [`write!()`] macro should be favored to
1693    /// invoke this method instead.
1694    ///
1695    /// This function internally uses the [`write_all`] method on
1696    /// this trait and hence will continuously write data so long as no errors
1697    /// are received. This also means that partial writes are not indicated in
1698    /// this signature.
1699    ///
1700    /// [`write_all`]: Write::write_all
1701    ///
1702    /// # Errors
1703    ///
1704    /// This function will return any I/O error reported while formatting.
1705    ///
1706    /// # Examples
1707    ///
1708    /// ```no_run
1709    /// use std::io::prelude::*;
1710    /// use std::fs::File;
1711    ///
1712    /// fn main() -> std::io::Result<()> {
1713    ///     let mut buffer = File::create("foo.txt")?;
1714    ///
1715    ///     // this call
1716    ///     write!(buffer, "{:.*}", 2, 1.234567)?;
1717    ///     // turns into this:
1718    ///     buffer.write_fmt(format_args!("{:.*}", 2, 1.234567))?;
1719    ///     Ok(())
1720    /// }
1721    /// ```
1722    #[stable(feature = "rust1", since = "1.0.0")]
1723    fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> Result<()> {
1724        if let Some(s) = args.as_statically_known_str() {
1725            self.write_all(s.as_bytes())
1726        } else {
1727            default_write_fmt(self, args)
1728        }
1729    }
1730
1731    /// Creates a "by reference" adapter for this instance of `Write`.
1732    ///
1733    /// The returned adapter also implements `Write` and will simply borrow this
1734    /// current writer.
1735    ///
1736    /// # Examples
1737    ///
1738    /// ```no_run
1739    /// use std::io::Write;
1740    /// use std::fs::File;
1741    ///
1742    /// fn main() -> std::io::Result<()> {
1743    ///     let mut buffer = File::create("foo.txt")?;
1744    ///
1745    ///     let reference = buffer.by_ref();
1746    ///
1747    ///     // we can use reference just like our original buffer
1748    ///     reference.write_all(b"some bytes")?;
1749    ///     Ok(())
1750    /// }
1751    /// ```
1752    #[stable(feature = "rust1", since = "1.0.0")]
1753    fn by_ref(&mut self) -> &mut Self
1754    where
1755        Self: Sized,
1756    {
1757        self
1758    }
1759}
1760
1761/// The `Seek` trait provides a cursor which can be moved within a stream of
1762/// bytes.
1763///
1764/// The stream typically has a fixed size, allowing seeking relative to either
1765/// end or the current offset.
1766///
1767/// # Examples
1768///
1769/// [`File`]s implement `Seek`:
1770///
1771/// [`File`]: crate::fs::File
1772///
1773/// ```no_run
1774/// use std::io;
1775/// use std::io::prelude::*;
1776/// use std::fs::File;
1777/// use std::io::SeekFrom;
1778///
1779/// fn main() -> io::Result<()> {
1780///     let mut f = File::open("foo.txt")?;
1781///
1782///     // move the cursor 42 bytes from the start of the file
1783///     f.seek(SeekFrom::Start(42))?;
1784///     Ok(())
1785/// }
1786/// ```
1787#[stable(feature = "rust1", since = "1.0.0")]
1788#[cfg_attr(not(test), rustc_diagnostic_item = "IoSeek")]
1789pub trait Seek {
1790    /// Seek to an offset, in bytes, in a stream.
1791    ///
1792    /// A seek beyond the end of a stream is allowed, but behavior is defined
1793    /// by the implementation.
1794    ///
1795    /// If the seek operation completed successfully,
1796    /// this method returns the new position from the start of the stream.
1797    /// That position can be used later with [`SeekFrom::Start`].
1798    ///
1799    /// # Errors
1800    ///
1801    /// Seeking can fail, for example because it might involve flushing a buffer.
1802    ///
1803    /// Seeking to a negative offset is considered an error.
1804    #[stable(feature = "rust1", since = "1.0.0")]
1805    fn seek(&mut self, pos: SeekFrom) -> Result<u64>;
1806
1807    /// Rewind to the beginning of a stream.
1808    ///
1809    /// This is a convenience method, equivalent to `seek(SeekFrom::Start(0))`.
1810    ///
1811    /// # Errors
1812    ///
1813    /// Rewinding can fail, for example because it might involve flushing a buffer.
1814    ///
1815    /// # Example
1816    ///
1817    /// ```no_run
1818    /// use std::io::{Read, Seek, Write};
1819    /// use std::fs::OpenOptions;
1820    ///
1821    /// let mut f = OpenOptions::new()
1822    ///     .write(true)
1823    ///     .read(true)
1824    ///     .create(true)
1825    ///     .open("foo.txt")?;
1826    ///
1827    /// let hello = "Hello!\n";
1828    /// write!(f, "{hello}")?;
1829    /// f.rewind()?;
1830    ///
1831    /// let mut buf = String::new();
1832    /// f.read_to_string(&mut buf)?;
1833    /// assert_eq!(&buf, hello);
1834    /// # std::io::Result::Ok(())
1835    /// ```
1836    #[stable(feature = "seek_rewind", since = "1.55.0")]
1837    fn rewind(&mut self) -> Result<()> {
1838        self.seek(SeekFrom::Start(0))?;
1839        Ok(())
1840    }
1841
1842    /// Returns the length of this stream (in bytes).
1843    ///
1844    /// The default implementation uses up to three seek operations. If this
1845    /// method returns successfully, the seek position is unchanged (i.e. the
1846    /// position before calling this method is the same as afterwards).
1847    /// However, if this method returns an error, the seek position is
1848    /// unspecified.
1849    ///
1850    /// If you need to obtain the length of *many* streams and you don't care
1851    /// about the seek position afterwards, you can reduce the number of seek
1852    /// operations by simply calling `seek(SeekFrom::End(0))` and using its
1853    /// return value (it is also the stream length).
1854    ///
1855    /// Note that length of a stream can change over time (for example, when
1856    /// data is appended to a file). So calling this method multiple times does
1857    /// not necessarily return the same length each time.
1858    ///
1859    /// # Example
1860    ///
1861    /// ```no_run
1862    /// #![feature(seek_stream_len)]
1863    /// use std::{
1864    ///     io::{self, Seek},
1865    ///     fs::File,
1866    /// };
1867    ///
1868    /// fn main() -> io::Result<()> {
1869    ///     let mut f = File::open("foo.txt")?;
1870    ///
1871    ///     let len = f.stream_len()?;
1872    ///     println!("The file is currently {len} bytes long");
1873    ///     Ok(())
1874    /// }
1875    /// ```
1876    #[unstable(feature = "seek_stream_len", issue = "59359")]
1877    fn stream_len(&mut self) -> Result<u64> {
1878        stream_len_default(self)
1879    }
1880
1881    /// Returns the current seek position from the start of the stream.
1882    ///
1883    /// This is equivalent to `self.seek(SeekFrom::Current(0))`.
1884    ///
1885    /// # Example
1886    ///
1887    /// ```no_run
1888    /// use std::{
1889    ///     io::{self, BufRead, BufReader, Seek},
1890    ///     fs::File,
1891    /// };
1892    ///
1893    /// fn main() -> io::Result<()> {
1894    ///     let mut f = BufReader::new(File::open("foo.txt")?);
1895    ///
1896    ///     let before = f.stream_position()?;
1897    ///     f.read_line(&mut String::new())?;
1898    ///     let after = f.stream_position()?;
1899    ///
1900    ///     println!("The first line was {} bytes long", after - before);
1901    ///     Ok(())
1902    /// }
1903    /// ```
1904    #[stable(feature = "seek_convenience", since = "1.51.0")]
1905    fn stream_position(&mut self) -> Result<u64> {
1906        self.seek(SeekFrom::Current(0))
1907    }
1908
1909    /// Seeks relative to the current position.
1910    ///
1911    /// This is equivalent to `self.seek(SeekFrom::Current(offset))` but
1912    /// doesn't return the new position which can allow some implementations
1913    /// such as [`BufReader`] to perform more efficient seeks.
1914    ///
1915    /// # Example
1916    ///
1917    /// ```no_run
1918    /// use std::{
1919    ///     io::{self, Seek},
1920    ///     fs::File,
1921    /// };
1922    ///
1923    /// fn main() -> io::Result<()> {
1924    ///     let mut f = File::open("foo.txt")?;
1925    ///     f.seek_relative(10)?;
1926    ///     assert_eq!(f.stream_position()?, 10);
1927    ///     Ok(())
1928    /// }
1929    /// ```
1930    ///
1931    /// [`BufReader`]: crate::io::BufReader
1932    #[stable(feature = "seek_seek_relative", since = "1.80.0")]
1933    fn seek_relative(&mut self, offset: i64) -> Result<()> {
1934        self.seek(SeekFrom::Current(offset))?;
1935        Ok(())
1936    }
1937}
1938
1939pub(crate) fn stream_len_default<T: Seek + ?Sized>(self_: &mut T) -> Result<u64> {
1940    let old_pos = self_.stream_position()?;
1941    let len = self_.seek(SeekFrom::End(0))?;
1942
1943    // Avoid seeking a third time when we were already at the end of the
1944    // stream. The branch is usually way cheaper than a seek operation.
1945    if old_pos != len {
1946        self_.seek(SeekFrom::Start(old_pos))?;
1947    }
1948
1949    Ok(len)
1950}
1951
1952/// Enumeration of possible methods to seek within an I/O object.
1953///
1954/// It is used by the [`Seek`] trait.
1955#[derive(Copy, PartialEq, Eq, Clone, Debug)]
1956#[stable(feature = "rust1", since = "1.0.0")]
1957#[cfg_attr(not(test), rustc_diagnostic_item = "SeekFrom")]
1958pub enum SeekFrom {
1959    /// Sets the offset to the provided number of bytes.
1960    #[stable(feature = "rust1", since = "1.0.0")]
1961    Start(#[stable(feature = "rust1", since = "1.0.0")] u64),
1962
1963    /// Sets the offset to the size of this object plus the specified number of
1964    /// bytes.
1965    ///
1966    /// It is possible to seek beyond the end of an object, but it's an error to
1967    /// seek before byte 0.
1968    #[stable(feature = "rust1", since = "1.0.0")]
1969    End(#[stable(feature = "rust1", since = "1.0.0")] i64),
1970
1971    /// Sets the offset to the current position plus the specified number of
1972    /// bytes.
1973    ///
1974    /// It is possible to seek beyond the end of an object, but it's an error to
1975    /// seek before byte 0.
1976    #[stable(feature = "rust1", since = "1.0.0")]
1977    Current(#[stable(feature = "rust1", since = "1.0.0")] i64),
1978}
1979
1980/// Marks that a type `T` can have IO traits such as [`Seek`], [`Write`], etc. automatically
1981/// implemented for handle types like [`Arc`][arc] as well.
1982///
1983/// This trait should only be implemented for types where `<&T as Trait>::method(&mut &value, ..)`
1984/// would be identical to `<T as Trait>::method(&mut value, ..)`.
1985///
1986/// [`File`][file] passes this test, as operations on `&File` and `File` both affect
1987/// the same underlying file.
1988/// `[u8]` fails, because any modification to `&mut &[u8]` would only affect a temporary
1989/// and be lost after the method has been called.
1990///
1991/// [file]: crate::fs::File
1992/// [arc]: crate::sync::Arc
1993pub(crate) trait IoHandle {}
1994
1995fn read_until<R: BufRead + ?Sized>(r: &mut R, delim: u8, buf: &mut Vec<u8>) -> Result<usize> {
1996    let mut read = 0;
1997    loop {
1998        let (done, used) = {
1999            let available = match r.fill_buf() {
2000                Ok(n) => n,
2001                Err(ref e) if e.is_interrupted() => continue,
2002                Err(e) => return Err(e),
2003            };
2004            match memchr::memchr(delim, available) {
2005                Some(i) => {
2006                    buf.extend_from_slice(&available[..=i]);
2007                    (true, i + 1)
2008                }
2009                None => {
2010                    buf.extend_from_slice(available);
2011                    (false, available.len())
2012                }
2013            }
2014        };
2015        r.consume(used);
2016        read += used;
2017        if done || used == 0 {
2018            return Ok(read);
2019        }
2020    }
2021}
2022
2023fn skip_until<R: BufRead + ?Sized>(r: &mut R, delim: u8) -> Result<usize> {
2024    let mut read = 0;
2025    loop {
2026        let (done, used) = {
2027            let available = match r.fill_buf() {
2028                Ok(n) => n,
2029                Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
2030                Err(e) => return Err(e),
2031            };
2032            match memchr::memchr(delim, available) {
2033                Some(i) => (true, i + 1),
2034                None => (false, available.len()),
2035            }
2036        };
2037        r.consume(used);
2038        read += used;
2039        if done || used == 0 {
2040            return Ok(read);
2041        }
2042    }
2043}
2044
2045/// A `BufRead` is a type of `Read`er which has an internal buffer, allowing it
2046/// to perform extra ways of reading.
2047///
2048/// For example, reading line-by-line is inefficient without using a buffer, so
2049/// if you want to read by line, you'll need `BufRead`, which includes a
2050/// [`read_line`] method as well as a [`lines`] iterator.
2051///
2052/// # Examples
2053///
2054/// A locked standard input implements `BufRead`:
2055///
2056/// ```no_run
2057/// use std::io;
2058/// use std::io::prelude::*;
2059///
2060/// let stdin = io::stdin();
2061/// for line in stdin.lock().lines() {
2062///     println!("{}", line?);
2063/// }
2064/// # std::io::Result::Ok(())
2065/// ```
2066///
2067/// If you have something that implements [`Read`], you can use the [`BufReader`
2068/// type][`BufReader`] to turn it into a `BufRead`.
2069///
2070/// For example, [`File`] implements [`Read`], but not `BufRead`.
2071/// [`BufReader`] to the rescue!
2072///
2073/// [`File`]: crate::fs::File
2074/// [`read_line`]: BufRead::read_line
2075/// [`lines`]: BufRead::lines
2076///
2077/// ```no_run
2078/// use std::io::{self, BufReader};
2079/// use std::io::prelude::*;
2080/// use std::fs::File;
2081///
2082/// fn main() -> io::Result<()> {
2083///     let f = File::open("foo.txt")?;
2084///     let f = BufReader::new(f);
2085///
2086///     for line in f.lines() {
2087///         let line = line?;
2088///         println!("{line}");
2089///     }
2090///
2091///     Ok(())
2092/// }
2093/// ```
2094#[stable(feature = "rust1", since = "1.0.0")]
2095#[cfg_attr(not(test), rustc_diagnostic_item = "IoBufRead")]
2096pub trait BufRead: Read {
2097    /// Returns the contents of the internal buffer, filling it with more data, via `Read` methods, if empty.
2098    ///
2099    /// This is a lower-level method and is meant to be used together with [`consume`],
2100    /// which can be used to mark bytes that should not be returned by subsequent calls to `read`.
2101    ///
2102    /// [`consume`]: BufRead::consume
2103    ///
2104    /// Returns an empty buffer when the stream has reached EOF.
2105    ///
2106    /// # Errors
2107    ///
2108    /// This function will return an I/O error if a `Read` method was called, but returned an error.
2109    ///
2110    /// # Examples
2111    ///
2112    /// A locked standard input implements `BufRead`:
2113    ///
2114    /// ```no_run
2115    /// use std::io;
2116    /// use std::io::prelude::*;
2117    ///
2118    /// let stdin = io::stdin();
2119    /// let mut stdin = stdin.lock();
2120    ///
2121    /// let buffer = stdin.fill_buf()?;
2122    ///
2123    /// // work with buffer
2124    /// println!("{buffer:?}");
2125    ///
2126    /// // mark the bytes we worked with as read
2127    /// let length = buffer.len();
2128    /// stdin.consume(length);
2129    /// # std::io::Result::Ok(())
2130    /// ```
2131    #[stable(feature = "rust1", since = "1.0.0")]
2132    fn fill_buf(&mut self) -> Result<&[u8]>;
2133
2134    /// Marks the given `amount` of additional bytes from the internal buffer as having been read.
2135    /// Subsequent calls to `read` only return bytes that have not been marked as read.
2136    ///
2137    /// This is a lower-level method and is meant to be used together with [`fill_buf`],
2138    /// which can be used to fill the internal buffer via `Read` methods.
2139    ///
2140    /// It is a logic error if `amount` exceeds the number of unread bytes in the internal buffer, which is returned by [`fill_buf`].
2141    ///
2142    /// # Examples
2143    ///
2144    /// Since `consume()` is meant to be used with [`fill_buf`],
2145    /// that method's example includes an example of `consume()`.
2146    ///
2147    /// [`fill_buf`]: BufRead::fill_buf
2148    #[stable(feature = "rust1", since = "1.0.0")]
2149    fn consume(&mut self, amount: usize);
2150
2151    /// Checks if there is any data left to be `read`.
2152    ///
2153    /// This function may fill the buffer to check for data,
2154    /// so this function returns `Result<bool>`, not `bool`.
2155    ///
2156    /// The default implementation calls `fill_buf` and checks that the
2157    /// returned slice is empty (which means that there is no data left,
2158    /// since EOF is reached).
2159    ///
2160    /// # Errors
2161    ///
2162    /// This function will return an I/O error if a `Read` method was called, but returned an error.
2163    ///
2164    /// Examples
2165    ///
2166    /// ```
2167    /// #![feature(buf_read_has_data_left)]
2168    /// use std::io;
2169    /// use std::io::prelude::*;
2170    ///
2171    /// let stdin = io::stdin();
2172    /// let mut stdin = stdin.lock();
2173    ///
2174    /// while stdin.has_data_left()? {
2175    ///     let mut line = String::new();
2176    ///     stdin.read_line(&mut line)?;
2177    ///     // work with line
2178    ///     println!("{line:?}");
2179    /// }
2180    /// # std::io::Result::Ok(())
2181    /// ```
2182    #[unstable(feature = "buf_read_has_data_left", issue = "86423")]
2183    fn has_data_left(&mut self) -> Result<bool> {
2184        self.fill_buf().map(|b| !b.is_empty())
2185    }
2186
2187    /// Reads all bytes into `buf` until the delimiter `byte` or EOF is reached.
2188    ///
2189    /// This function will read bytes from the underlying stream until the
2190    /// delimiter or EOF is found. Once found, all bytes up to, and including,
2191    /// the delimiter (if found) will be appended to `buf`.
2192    ///
2193    /// If successful, this function will return the total number of bytes read.
2194    ///
2195    /// This function is blocking and should be used carefully: it is possible for
2196    /// an attacker to continuously send bytes without ever sending the delimiter
2197    /// or EOF.
2198    ///
2199    /// # Errors
2200    ///
2201    /// This function will ignore all instances of [`ErrorKind::Interrupted`] and
2202    /// will otherwise return any errors returned by [`fill_buf`].
2203    ///
2204    /// If an I/O error is encountered then all bytes read so far will be
2205    /// present in `buf` and its length will have been adjusted appropriately.
2206    ///
2207    /// [`fill_buf`]: BufRead::fill_buf
2208    ///
2209    /// # Examples
2210    ///
2211    /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
2212    /// this example, we use [`Cursor`] to read all the bytes in a byte slice
2213    /// in hyphen delimited segments:
2214    ///
2215    /// ```
2216    /// use std::io::{self, BufRead};
2217    ///
2218    /// let mut cursor = io::Cursor::new(b"lorem-ipsum");
2219    /// let mut buf = vec![];
2220    ///
2221    /// // cursor is at 'l'
2222    /// let num_bytes = cursor.read_until(b'-', &mut buf)
2223    ///     .expect("reading from cursor won't fail");
2224    /// assert_eq!(num_bytes, 6);
2225    /// assert_eq!(buf, b"lorem-");
2226    /// buf.clear();
2227    ///
2228    /// // cursor is at 'i'
2229    /// let num_bytes = cursor.read_until(b'-', &mut buf)
2230    ///     .expect("reading from cursor won't fail");
2231    /// assert_eq!(num_bytes, 5);
2232    /// assert_eq!(buf, b"ipsum");
2233    /// buf.clear();
2234    ///
2235    /// // cursor is at EOF
2236    /// let num_bytes = cursor.read_until(b'-', &mut buf)
2237    ///     .expect("reading from cursor won't fail");
2238    /// assert_eq!(num_bytes, 0);
2239    /// assert_eq!(buf, b"");
2240    /// ```
2241    #[stable(feature = "rust1", since = "1.0.0")]
2242    fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> Result<usize> {
2243        read_until(self, byte, buf)
2244    }
2245
2246    /// Skips all bytes until the delimiter `byte` or EOF is reached.
2247    ///
2248    /// This function will read (and discard) bytes from the underlying stream until the
2249    /// delimiter or EOF is found.
2250    ///
2251    /// If successful, this function will return the total number of bytes read,
2252    /// including the delimiter byte if found.
2253    ///
2254    /// This is useful for efficiently skipping data such as NUL-terminated strings
2255    /// in binary file formats without buffering.
2256    ///
2257    /// This function is blocking and should be used carefully: it is possible for
2258    /// an attacker to continuously send bytes without ever sending the delimiter
2259    /// or EOF.
2260    ///
2261    /// # Errors
2262    ///
2263    /// This function will ignore all instances of [`ErrorKind::Interrupted`] and
2264    /// will otherwise return any errors returned by [`fill_buf`].
2265    ///
2266    /// If an I/O error is encountered then all bytes read so far will be
2267    /// present in `buf` and its length will have been adjusted appropriately.
2268    ///
2269    /// [`fill_buf`]: BufRead::fill_buf
2270    ///
2271    /// # Examples
2272    ///
2273    /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
2274    /// this example, we use [`Cursor`] to read some NUL-terminated information
2275    /// about Ferris from a binary string, skipping the fun fact:
2276    ///
2277    /// ```
2278    /// use std::io::{self, BufRead};
2279    ///
2280    /// let mut cursor = io::Cursor::new(b"Ferris\0Likes long walks on the beach\0Crustacean\0!");
2281    ///
2282    /// // read name
2283    /// let mut name = Vec::new();
2284    /// let num_bytes = cursor.read_until(b'\0', &mut name)
2285    ///     .expect("reading from cursor won't fail");
2286    /// assert_eq!(num_bytes, 7);
2287    /// assert_eq!(name, b"Ferris\0");
2288    ///
2289    /// // skip fun fact
2290    /// let num_bytes = cursor.skip_until(b'\0')
2291    ///     .expect("reading from cursor won't fail");
2292    /// assert_eq!(num_bytes, 30);
2293    ///
2294    /// // read animal type
2295    /// let mut animal = Vec::new();
2296    /// let num_bytes = cursor.read_until(b'\0', &mut animal)
2297    ///     .expect("reading from cursor won't fail");
2298    /// assert_eq!(num_bytes, 11);
2299    /// assert_eq!(animal, b"Crustacean\0");
2300    ///
2301    /// // reach EOF
2302    /// let num_bytes = cursor.skip_until(b'\0')
2303    ///     .expect("reading from cursor won't fail");
2304    /// assert_eq!(num_bytes, 1);
2305    /// ```
2306    #[stable(feature = "bufread_skip_until", since = "1.83.0")]
2307    fn skip_until(&mut self, byte: u8) -> Result<usize> {
2308        skip_until(self, byte)
2309    }
2310
2311    /// Reads all bytes until a newline (the `0xA` byte) is reached, and append
2312    /// them to the provided `String` buffer.
2313    ///
2314    /// Previous content of the buffer will be preserved. To avoid appending to
2315    /// the buffer, you need to [`clear`] it first.
2316    ///
2317    /// This function will read bytes from the underlying stream until the
2318    /// newline delimiter (the `0xA` byte) or EOF is found. Once found, all bytes
2319    /// up to, and including, the delimiter (if found) will be appended to
2320    /// `buf`.
2321    ///
2322    /// If successful, this function will return the total number of bytes read.
2323    ///
2324    /// If this function returns [`Ok(0)`], the stream has reached EOF.
2325    ///
2326    /// This function is blocking and should be used carefully: it is possible for
2327    /// an attacker to continuously send bytes without ever sending a newline
2328    /// or EOF. You can use [`take`] to limit the maximum number of bytes read.
2329    ///
2330    /// [`Ok(0)`]: Ok
2331    /// [`clear`]: String::clear
2332    /// [`take`]: crate::io::Read::take
2333    ///
2334    /// # Errors
2335    ///
2336    /// This function has the same error semantics as [`read_until`] and will
2337    /// also return an error if the read bytes are not valid UTF-8. If an I/O
2338    /// error is encountered then `buf` may contain some bytes already read in
2339    /// the event that all data read so far was valid UTF-8.
2340    ///
2341    /// [`read_until`]: BufRead::read_until
2342    ///
2343    /// # Examples
2344    ///
2345    /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
2346    /// this example, we use [`Cursor`] to read all the lines in a byte slice:
2347    ///
2348    /// ```
2349    /// use std::io::{self, BufRead};
2350    ///
2351    /// let mut cursor = io::Cursor::new(b"foo\nbar");
2352    /// let mut buf = String::new();
2353    ///
2354    /// // cursor is at 'f'
2355    /// let num_bytes = cursor.read_line(&mut buf)
2356    ///     .expect("reading from cursor won't fail");
2357    /// assert_eq!(num_bytes, 4);
2358    /// assert_eq!(buf, "foo\n");
2359    /// buf.clear();
2360    ///
2361    /// // cursor is at 'b'
2362    /// let num_bytes = cursor.read_line(&mut buf)
2363    ///     .expect("reading from cursor won't fail");
2364    /// assert_eq!(num_bytes, 3);
2365    /// assert_eq!(buf, "bar");
2366    /// buf.clear();
2367    ///
2368    /// // cursor is at EOF
2369    /// let num_bytes = cursor.read_line(&mut buf)
2370    ///     .expect("reading from cursor won't fail");
2371    /// assert_eq!(num_bytes, 0);
2372    /// assert_eq!(buf, "");
2373    /// ```
2374    #[stable(feature = "rust1", since = "1.0.0")]
2375    fn read_line(&mut self, buf: &mut String) -> Result<usize> {
2376        // Note that we are not calling the `.read_until` method here, but
2377        // rather our hardcoded implementation. For more details as to why, see
2378        // the comments in `default_read_to_string`.
2379        unsafe { append_to_string(buf, |b| read_until(self, b'\n', b)) }
2380    }
2381
2382    /// Returns an iterator over the contents of this reader split on the byte
2383    /// `byte`.
2384    ///
2385    /// The iterator returned from this function will return instances of
2386    /// <code>[io::Result]<[Vec]\<u8>></code>. Each vector returned will *not* have
2387    /// the delimiter byte at the end.
2388    ///
2389    /// This function will yield errors whenever [`read_until`] would have
2390    /// also yielded an error.
2391    ///
2392    /// [io::Result]: self::Result "io::Result"
2393    /// [`read_until`]: BufRead::read_until
2394    ///
2395    /// # Examples
2396    ///
2397    /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
2398    /// this example, we use [`Cursor`] to iterate over all hyphen delimited
2399    /// segments in a byte slice
2400    ///
2401    /// ```
2402    /// use std::io::{self, BufRead};
2403    ///
2404    /// let cursor = io::Cursor::new(b"lorem-ipsum-dolor");
2405    ///
2406    /// let mut split_iter = cursor.split(b'-').map(|l| l.unwrap());
2407    /// assert_eq!(split_iter.next(), Some(b"lorem".to_vec()));
2408    /// assert_eq!(split_iter.next(), Some(b"ipsum".to_vec()));
2409    /// assert_eq!(split_iter.next(), Some(b"dolor".to_vec()));
2410    /// assert_eq!(split_iter.next(), None);
2411    /// ```
2412    #[stable(feature = "rust1", since = "1.0.0")]
2413    fn split(self, byte: u8) -> Split<Self>
2414    where
2415        Self: Sized,
2416    {
2417        Split { buf: self, delim: byte }
2418    }
2419
2420    /// Returns an iterator over the lines of this reader.
2421    ///
2422    /// The iterator returned from this function will yield instances of
2423    /// <code>[io::Result]<[String]></code>. Each string returned will *not* have a newline
2424    /// byte (the `0xA` byte) or `CRLF` (`0xD`, `0xA` bytes) at the end.
2425    ///
2426    /// [io::Result]: self::Result "io::Result"
2427    ///
2428    /// # Examples
2429    ///
2430    /// [`std::io::Cursor`][`Cursor`] is a type that implements `BufRead`. In
2431    /// this example, we use [`Cursor`] to iterate over all the lines in a byte
2432    /// slice.
2433    ///
2434    /// ```
2435    /// use std::io::{self, BufRead};
2436    ///
2437    /// let cursor = io::Cursor::new(b"lorem\nipsum\r\ndolor");
2438    ///
2439    /// let mut lines_iter = cursor.lines().map(|l| l.unwrap());
2440    /// assert_eq!(lines_iter.next(), Some(String::from("lorem")));
2441    /// assert_eq!(lines_iter.next(), Some(String::from("ipsum")));
2442    /// assert_eq!(lines_iter.next(), Some(String::from("dolor")));
2443    /// assert_eq!(lines_iter.next(), None);
2444    /// ```
2445    ///
2446    /// # Errors
2447    ///
2448    /// Each line of the iterator has the same error semantics as [`BufRead::read_line`].
2449    #[stable(feature = "rust1", since = "1.0.0")]
2450    fn lines(self) -> Lines<Self>
2451    where
2452        Self: Sized,
2453    {
2454        Lines { buf: self }
2455    }
2456}
2457
2458#[stable(feature = "rust1", since = "1.0.0")]
2459impl<T: Read, U: Read> Read for Chain<T, U> {
2460    fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
2461        if !self.done_first {
2462            match self.first.read(buf)? {
2463                0 if !buf.is_empty() => self.done_first = true,
2464                n => return Ok(n),
2465            }
2466        }
2467        self.second.read(buf)
2468    }
2469
2470    fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize> {
2471        if !self.done_first {
2472            match self.first.read_vectored(bufs)? {
2473                0 if bufs.iter().any(|b| !b.is_empty()) => self.done_first = true,
2474                n => return Ok(n),
2475            }
2476        }
2477        self.second.read_vectored(bufs)
2478    }
2479
2480    #[inline]
2481    fn is_read_vectored(&self) -> bool {
2482        self.first.is_read_vectored() || self.second.is_read_vectored()
2483    }
2484
2485    fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
2486        let mut read = 0;
2487        if !self.done_first {
2488            read += self.first.read_to_end(buf)?;
2489            self.done_first = true;
2490        }
2491        read += self.second.read_to_end(buf)?;
2492        Ok(read)
2493    }
2494
2495    // We don't override `read_to_string` here because an UTF-8 sequence could
2496    // be split between the two parts of the chain
2497
2498    fn read_buf(&mut self, mut buf: BorrowedCursor<'_, u8>) -> Result<()> {
2499        if buf.capacity() == 0 {
2500            return Ok(());
2501        }
2502
2503        if !self.done_first {
2504            let old_len = buf.written();
2505            self.first.read_buf(buf.reborrow())?;
2506
2507            if buf.written() != old_len {
2508                return Ok(());
2509            } else {
2510                self.done_first = true;
2511            }
2512        }
2513        self.second.read_buf(buf)
2514    }
2515}
2516
2517#[stable(feature = "chain_bufread", since = "1.9.0")]
2518impl<T: BufRead, U: BufRead> BufRead for Chain<T, U> {
2519    fn fill_buf(&mut self) -> Result<&[u8]> {
2520        if !self.done_first {
2521            match self.first.fill_buf()? {
2522                buf if buf.is_empty() => self.done_first = true,
2523                buf => return Ok(buf),
2524            }
2525        }
2526        self.second.fill_buf()
2527    }
2528
2529    fn consume(&mut self, amt: usize) {
2530        if !self.done_first { self.first.consume(amt) } else { self.second.consume(amt) }
2531    }
2532
2533    fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> Result<usize> {
2534        let mut read = 0;
2535        if !self.done_first {
2536            let n = self.first.read_until(byte, buf)?;
2537            read += n;
2538
2539            match buf.last() {
2540                Some(b) if *b == byte && n != 0 => return Ok(read),
2541                _ => self.done_first = true,
2542            }
2543        }
2544        read += self.second.read_until(byte, buf)?;
2545        Ok(read)
2546    }
2547
2548    // We don't override `read_line` here because an UTF-8 sequence could be
2549    // split between the two parts of the chain
2550}
2551
2552impl<T, U> SizeHint for Chain<T, U> {
2553    #[inline]
2554    fn lower_bound(&self) -> usize {
2555        SizeHint::lower_bound(&self.first) + SizeHint::lower_bound(&self.second)
2556    }
2557
2558    #[inline]
2559    fn upper_bound(&self) -> Option<usize> {
2560        match (SizeHint::upper_bound(&self.first), SizeHint::upper_bound(&self.second)) {
2561            (Some(first), Some(second)) => first.checked_add(second),
2562            _ => None,
2563        }
2564    }
2565}
2566
2567#[stable(feature = "rust1", since = "1.0.0")]
2568impl<T: Read> Read for Take<T> {
2569    fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
2570        // Don't call into inner reader at all at EOF because it may still block
2571        if self.limit == 0 {
2572            return Ok(0);
2573        }
2574
2575        let max = cmp::min(buf.len() as u64, self.limit) as usize;
2576        let n = self.inner.read(&mut buf[..max])?;
2577        assert!(n as u64 <= self.limit, "number of read bytes exceeds limit");
2578        self.limit -= n as u64;
2579        Ok(n)
2580    }
2581
2582    fn read_buf(&mut self, mut buf: BorrowedCursor<'_, u8>) -> Result<()> {
2583        // Don't call into inner reader at all at EOF because it may still block
2584        if self.limit == 0 {
2585            return Ok(());
2586        }
2587
2588        if self.limit < buf.capacity() as u64 {
2589            // The condition above guarantees that `self.limit` fits in `usize`.
2590            let limit = self.limit as usize;
2591
2592            let is_init = buf.is_init();
2593
2594            // SAFETY: no uninit data is written to ibuf
2595            let mut sliced_buf = BorrowedBuf::from(unsafe { &mut buf.as_mut()[..limit] });
2596
2597            if is_init {
2598                // SAFETY: `sliced_buf` is a subslice of `buf`, so if `buf` was initialized then
2599                // `sliced_buf` is.
2600                unsafe { sliced_buf.set_init() };
2601            }
2602
2603            let result = self.inner.read_buf(sliced_buf.unfilled());
2604
2605            let did_init_up_to_limit = sliced_buf.is_init();
2606            let filled = sliced_buf.len();
2607
2608            // sliced_buf must drop here
2609
2610            // Avoid accidentally quadratic behaviour by initializing the whole
2611            // cursor if only part of it was initialized.
2612            if did_init_up_to_limit && !is_init {
2613                // SAFETY: No uninit data will be written.
2614                let unfilled_before_advance = unsafe { buf.as_mut() };
2615
2616                unfilled_before_advance[limit..].write_filled(0);
2617
2618                // SAFETY: `unfilled_before_advance[..limit]` was initialized by `T::read_buf`, and
2619                // `unfilled_before_advance[limit..]` was just initialized.
2620                unsafe { buf.set_init() };
2621            }
2622
2623            unsafe {
2624                // SAFETY: filled bytes have been filled
2625                buf.advance(filled);
2626            }
2627
2628            self.limit -= filled as u64;
2629
2630            result
2631        } else {
2632            let written = buf.written();
2633            let result = self.inner.read_buf(buf.reborrow());
2634            self.limit -= (buf.written() - written) as u64;
2635            result
2636        }
2637    }
2638}
2639
2640#[stable(feature = "rust1", since = "1.0.0")]
2641impl<T: BufRead> BufRead for Take<T> {
2642    fn fill_buf(&mut self) -> Result<&[u8]> {
2643        // Don't call into inner reader at all at EOF because it may still block
2644        if self.limit == 0 {
2645            return Ok(&[]);
2646        }
2647
2648        let buf = self.inner.fill_buf()?;
2649        let cap = cmp::min(buf.len() as u64, self.limit) as usize;
2650        Ok(&buf[..cap])
2651    }
2652
2653    fn consume(&mut self, amt: usize) {
2654        // Don't let callers reset the limit by passing an overlarge value
2655        let amt = cmp::min(amt as u64, self.limit) as usize;
2656        self.limit -= amt as u64;
2657        self.inner.consume(amt);
2658    }
2659}
2660
2661impl<T> SizeHint for Take<T> {
2662    #[inline]
2663    fn lower_bound(&self) -> usize {
2664        cmp::min(SizeHint::lower_bound(&self.inner) as u64, self.limit) as usize
2665    }
2666
2667    #[inline]
2668    fn upper_bound(&self) -> Option<usize> {
2669        match SizeHint::upper_bound(&self.inner) {
2670            Some(upper_bound) => Some(cmp::min(upper_bound as u64, self.limit) as usize),
2671            None => self.limit.try_into().ok(),
2672        }
2673    }
2674}
2675
2676#[stable(feature = "seek_io_take", since = "1.89.0")]
2677impl<T: Seek> Seek for Take<T> {
2678    fn seek(&mut self, pos: SeekFrom) -> Result<u64> {
2679        let new_position = match pos {
2680            SeekFrom::Start(v) => Some(v),
2681            SeekFrom::Current(v) => self.position().checked_add_signed(v),
2682            SeekFrom::End(v) => self.len.checked_add_signed(v),
2683        };
2684        let new_position = match new_position {
2685            Some(v) if v <= self.len => v,
2686            _ => return Err(ErrorKind::InvalidInput.into()),
2687        };
2688        while new_position != self.position() {
2689            if let Some(offset) = new_position.checked_signed_diff(self.position()) {
2690                self.inner.seek_relative(offset)?;
2691                self.limit = self.limit.wrapping_sub(offset as u64);
2692                break;
2693            }
2694            let offset = if new_position > self.position() { i64::MAX } else { i64::MIN };
2695            self.inner.seek_relative(offset)?;
2696            self.limit = self.limit.wrapping_sub(offset as u64);
2697        }
2698        Ok(new_position)
2699    }
2700
2701    fn stream_len(&mut self) -> Result<u64> {
2702        Ok(self.len)
2703    }
2704
2705    fn stream_position(&mut self) -> Result<u64> {
2706        Ok(self.position())
2707    }
2708
2709    fn seek_relative(&mut self, offset: i64) -> Result<()> {
2710        if !self.position().checked_add_signed(offset).is_some_and(|p| p <= self.len) {
2711            return Err(ErrorKind::InvalidInput.into());
2712        }
2713        self.inner.seek_relative(offset)?;
2714        self.limit = self.limit.wrapping_sub(offset as u64);
2715        Ok(())
2716    }
2717}
2718
2719/// An iterator over `u8` values of a reader.
2720///
2721/// This struct is generally created by calling [`bytes`] on a reader.
2722/// Please see the documentation of [`bytes`] for more details.
2723///
2724/// [`bytes`]: Read::bytes
2725#[stable(feature = "rust1", since = "1.0.0")]
2726#[derive(Debug)]
2727pub struct Bytes<R> {
2728    inner: R,
2729}
2730
2731#[stable(feature = "rust1", since = "1.0.0")]
2732impl<R: Read> Iterator for Bytes<R> {
2733    type Item = Result<u8>;
2734
2735    // Not `#[inline]`. This function gets inlined even without it, but having
2736    // the inline annotation can result in worse code generation. See #116785.
2737    fn next(&mut self) -> Option<Result<u8>> {
2738        SpecReadByte::spec_read_byte(&mut self.inner)
2739    }
2740
2741    #[inline]
2742    fn size_hint(&self) -> (usize, Option<usize>) {
2743        SizeHint::size_hint(&self.inner)
2744    }
2745}
2746
2747/// For the specialization of `Bytes::next`.
2748trait SpecReadByte {
2749    fn spec_read_byte(&mut self) -> Option<Result<u8>>;
2750}
2751
2752impl<R> SpecReadByte for R
2753where
2754    Self: Read,
2755{
2756    #[inline]
2757    default fn spec_read_byte(&mut self) -> Option<Result<u8>> {
2758        inlined_slow_read_byte(self)
2759    }
2760}
2761
2762/// Reads a single byte in a slow, generic way. This is used by the default
2763/// `spec_read_byte`.
2764#[inline]
2765fn inlined_slow_read_byte<R: Read>(reader: &mut R) -> Option<Result<u8>> {
2766    let mut byte = 0;
2767    loop {
2768        return match reader.read(slice::from_mut(&mut byte)) {
2769            Ok(0) => None,
2770            Ok(..) => Some(Ok(byte)),
2771            Err(ref e) if e.is_interrupted() => continue,
2772            Err(e) => Some(Err(e)),
2773        };
2774    }
2775}
2776
2777// Used by `BufReader::spec_read_byte`, for which the `inline(never)` is
2778// important.
2779#[inline(never)]
2780fn uninlined_slow_read_byte<R: Read>(reader: &mut R) -> Option<Result<u8>> {
2781    inlined_slow_read_byte(reader)
2782}
2783
2784trait SizeHint {
2785    fn lower_bound(&self) -> usize;
2786
2787    fn upper_bound(&self) -> Option<usize>;
2788
2789    fn size_hint(&self) -> (usize, Option<usize>) {
2790        (self.lower_bound(), self.upper_bound())
2791    }
2792}
2793
2794impl<T: ?Sized> SizeHint for T {
2795    #[inline]
2796    default fn lower_bound(&self) -> usize {
2797        0
2798    }
2799
2800    #[inline]
2801    default fn upper_bound(&self) -> Option<usize> {
2802        None
2803    }
2804}
2805
2806impl<T> SizeHint for &mut T {
2807    #[inline]
2808    fn lower_bound(&self) -> usize {
2809        SizeHint::lower_bound(*self)
2810    }
2811
2812    #[inline]
2813    fn upper_bound(&self) -> Option<usize> {
2814        SizeHint::upper_bound(*self)
2815    }
2816}
2817
2818impl<T> SizeHint for Box<T> {
2819    #[inline]
2820    fn lower_bound(&self) -> usize {
2821        SizeHint::lower_bound(&**self)
2822    }
2823
2824    #[inline]
2825    fn upper_bound(&self) -> Option<usize> {
2826        SizeHint::upper_bound(&**self)
2827    }
2828}
2829
2830impl SizeHint for &[u8] {
2831    #[inline]
2832    fn lower_bound(&self) -> usize {
2833        self.len()
2834    }
2835
2836    #[inline]
2837    fn upper_bound(&self) -> Option<usize> {
2838        Some(self.len())
2839    }
2840}
2841
2842/// An iterator over the contents of an instance of `BufRead` split on a
2843/// particular byte.
2844///
2845/// This struct is generally created by calling [`split`] on a `BufRead`.
2846/// Please see the documentation of [`split`] for more details.
2847///
2848/// [`split`]: BufRead::split
2849#[stable(feature = "rust1", since = "1.0.0")]
2850#[derive(Debug)]
2851#[cfg_attr(not(test), rustc_diagnostic_item = "IoSplit")]
2852pub struct Split<B> {
2853    buf: B,
2854    delim: u8,
2855}
2856
2857#[stable(feature = "rust1", since = "1.0.0")]
2858impl<B: BufRead> Iterator for Split<B> {
2859    type Item = Result<Vec<u8>>;
2860
2861    fn next(&mut self) -> Option<Result<Vec<u8>>> {
2862        let mut buf = Vec::new();
2863        match self.buf.read_until(self.delim, &mut buf) {
2864            Ok(0) => None,
2865            Ok(_n) => {
2866                if buf[buf.len() - 1] == self.delim {
2867                    buf.pop();
2868                }
2869                Some(Ok(buf))
2870            }
2871            Err(e) => Some(Err(e)),
2872        }
2873    }
2874}
2875
2876/// An iterator over the lines of an instance of `BufRead`.
2877///
2878/// This struct is generally created by calling [`lines`] on a `BufRead`.
2879/// Please see the documentation of [`lines`] for more details.
2880///
2881/// [`lines`]: BufRead::lines
2882#[stable(feature = "rust1", since = "1.0.0")]
2883#[derive(Debug)]
2884#[cfg_attr(not(test), rustc_diagnostic_item = "IoLines")]
2885pub struct Lines<B> {
2886    buf: B,
2887}
2888
2889#[stable(feature = "rust1", since = "1.0.0")]
2890impl<B: BufRead> Iterator for Lines<B> {
2891    type Item = Result<String>;
2892
2893    fn next(&mut self) -> Option<Result<String>> {
2894        let mut buf = String::new();
2895        match self.buf.read_line(&mut buf) {
2896            Ok(0) => None,
2897            Ok(_n) => {
2898                if buf.ends_with('\n') {
2899                    buf.pop();
2900                    if buf.ends_with('\r') {
2901                        buf.pop();
2902                    }
2903                }
2904                Some(Ok(buf))
2905            }
2906            Err(e) => Some(Err(e)),
2907        }
2908    }
2909}
2910
2911/// Trait for types that can be converted from a fixed-size byte array with a specified endianness
2912#[unstable(feature = "read_le_be_internals", reason = "internals", issue = "none")]
2913// Once we can use associated consts in the types of method parameters, rewrite this to have
2914// `from_le_bytes` and `from_be_bytes` methods, move it to `core`, and make it public.
2915pub trait FromEndianBytes: crate::sealed::Sealed + Sized {
2916    #[doc(hidden)]
2917    fn read_le_from(r: &mut impl Read) -> Result<Self>;
2918
2919    #[doc(hidden)]
2920    fn read_be_from(r: &mut impl Read) -> Result<Self>;
2921}
2922
2923macro_rules! impl_from_endian_bytes {
2924    ($($t:ty),*$(,)?) => {$(
2925        #[unstable(feature = "read_le_be_internals", reason = "internals", issue = "none")]
2926        impl FromEndianBytes for $t {
2927            #[inline]
2928            fn read_le_from(r: &mut impl Read) -> Result<Self> {
2929                Ok(<$t>::from_le_bytes(r.read_array()?))
2930            }
2931
2932            #[inline]
2933            fn read_be_from(r: &mut impl Read) -> Result<Self> {
2934                Ok(<$t>::from_be_bytes(r.read_array()?))
2935            }
2936        }
2937    )*};
2938}
2939
2940impl_from_endian_bytes!(u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize, f32, f64);