Skip to main content

alloc/io/
read.rs

1use core::cmp;
2use core::mem::{DropGuard, MaybeUninit};
3
4use crate::io::{
5    BorrowedBuf, BorrowedCursor, Bytes, Chain, Error, IoSliceMut, Result, Take, bytes, chain, take,
6};
7use crate::string::String;
8use crate::vec::Vec;
9
10/// The `Read` trait allows for reading bytes from a source.
11///
12/// Implementors of the `Read` trait are called 'readers'.
13///
14/// Readers are defined by one required method, [`read()`]. Each call to [`read()`]
15/// will attempt to pull bytes from this source into a provided buffer. A
16/// number of other methods are implemented in terms of [`read()`], giving
17/// implementors a number of ways to read bytes while only needing to implement
18/// a single method.
19///
20/// Readers are intended to be composable with one another. Many implementors
21/// throughout [`std::io`] take and provide types which implement the `Read`
22/// trait.
23///
24/// Please note that each call to [`read()`] may involve a system call, and
25/// `BufReader`, will be more efficient.
26/// therefore, using something that implements [`BufRead`], such as
27///
28/// [`BufRead`]: crate::io::BufRead
29///
30/// Repeated calls to the reader use the same cursor, so for example
31/// calling `read_to_end` twice on a `File` will only return the file's
32/// contents once. It's recommended to first call `rewind()` in that case.
33///
34/// # Examples
35///
36/// `File`s implement `Read`:
37///
38/// ```no_run
39/// use std::io;
40/// use std::io::prelude::*;
41/// use std::fs::File;
42///
43/// fn main() -> io::Result<()> {
44///     let mut f = File::open("foo.txt")?;
45///     let mut buffer = [0; 10];
46///
47///     // read up to 10 bytes
48///     f.read(&mut buffer)?;
49///
50///     let mut buffer = Vec::new();
51///     // read the whole file
52///     f.read_to_end(&mut buffer)?;
53///
54///     // read into a String, so that you don't need to do the conversion.
55///     let mut buffer = String::new();
56///     f.read_to_string(&mut buffer)?;
57///
58///     // and more! See the other methods for more details.
59///     Ok(())
60/// }
61/// ```
62///
63/// Read from [`&str`] because [`&[u8]`][prim@slice] implements `Read`:
64///
65/// ```no_run
66/// # use std::io;
67/// use std::io::prelude::*;
68///
69/// fn main() -> io::Result<()> {
70///     let mut b = "This string will be read".as_bytes();
71///     let mut buffer = [0; 10];
72///
73///     // read up to 10 bytes
74///     b.read(&mut buffer)?;
75///
76///     // etc... it works exactly as a File does!
77///     Ok(())
78/// }
79/// ```
80///
81/// [`read()`]: Read::read
82/// [`&str`]: prim@str
83/// [`std::io`]: crate::io
84#[stable(feature = "rust1", since = "1.0.0")]
85#[doc(notable_trait)]
86#[cfg_attr(not(test), rustc_diagnostic_item = "IoRead")]
87#[rustc_must_implement_one_of(read, read_buf)]
88pub trait Read {
89    /// Pull some bytes from this source into the specified buffer, returning
90    /// how many bytes were read.
91    ///
92    /// This function does not provide any guarantees about whether it blocks
93    /// waiting for data, but if an object needs to block for a read and cannot,
94    /// it will typically signal this via an [`Err`] return value.
95    ///
96    /// If the return value of this method is [`Ok(n)`], then implementations must
97    /// guarantee that `0 <= n <= buf.len()`. A nonzero `n` value indicates
98    /// that the buffer `buf` has been filled in with `n` bytes of data from this
99    /// source. If `n` is `0`, then it can indicate one of two scenarios:
100    ///
101    /// 1. This reader has reached its "end of file" and will likely no longer
102    ///    be able to produce bytes. Note that this does not mean that the
103    ///    reader will *always* no longer be able to produce bytes. As an example,
104    ///    on Linux, this method will call the `recv` syscall for a `TcpStream`,
105    ///    where returning zero indicates the connection was shut down correctly. While
106    ///    for `File`, it is possible to reach the end of file and get zero as result,
107    ///    but if more data is appended to the file, future calls to `read` will return
108    ///    more data.
109    /// 2. The buffer specified was 0 bytes in length.
110    ///
111    /// It is not an error if the returned value `n` is smaller than the buffer size,
112    /// even when the reader is not at the end of the stream yet.
113    /// This may happen for example because fewer bytes are actually available right now
114    /// (e. g. being close to end-of-file) or because read() was interrupted by a signal.
115    ///
116    /// As this trait is safe to implement, callers in unsafe code cannot rely on
117    /// `n <= buf.len()` for safety.
118    /// Extra care needs to be taken when `unsafe` functions are used to access the read bytes.
119    /// Callers have to ensure that no unchecked out-of-bounds accesses are possible even if
120    /// `n > buf.len()`.
121    ///
122    /// *Implementations* of this method can make no assumptions about the contents of `buf` when
123    /// this function is called. It is recommended that implementations only write data to `buf`
124    /// instead of reading its contents.
125    ///
126    /// Correspondingly, however, *callers* of this method in unsafe code must not assume
127    /// any guarantees about how the implementation uses `buf`. The trait is safe to implement,
128    /// so it is possible that the code that's supposed to write to the buffer might also read
129    /// from it. It is your responsibility to make sure that `buf` is initialized
130    /// before calling `read`. Calling `read` with an uninitialized `buf` (of the kind one
131    /// obtains via [`MaybeUninit<T>`]) is not safe, and can lead to undefined behavior.
132    ///
133    /// [`MaybeUninit<T>`]: core::mem::MaybeUninit
134    ///
135    /// # Errors
136    ///
137    /// If this function encounters any form of I/O or other error, an error
138    /// variant will be returned. If an error is returned then it must be
139    /// guaranteed that no bytes were read.
140    ///
141    /// An error of the [`ErrorKind::Interrupted`] kind is non-fatal and the read
142    /// operation should be retried if there is nothing else to do.
143    ///
144    /// # Examples
145    ///
146    /// `File`s implement `Read`:
147    ///
148    /// [`Ok(n)`]: Ok
149    /// [`ErrorKind::Interrupted`]: crate::io::ErrorKind::Interrupted
150    ///
151    /// ```no_run
152    /// use std::io;
153    /// use std::io::prelude::*;
154    /// use std::fs::File;
155    ///
156    /// fn main() -> io::Result<()> {
157    ///     let mut f = File::open("foo.txt")?;
158    ///     let mut buffer = [0; 10];
159    ///
160    ///     // read up to 10 bytes
161    ///     let n = f.read(&mut buffer[..])?;
162    ///
163    ///     println!("The bytes: {:?}", &buffer[..n]);
164    ///     Ok(())
165    /// }
166    /// ```
167    #[stable(feature = "rust1", since = "1.0.0")]
168    fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
169        let mut buf = BorrowedBuf::from(buf);
170        self.read_buf(buf.unfilled()).map(|()| buf.len())
171    }
172
173    /// Like `read`, except that it reads into a slice of buffers.
174    ///
175    /// Data is copied to fill each buffer in order, with the final buffer
176    /// written to possibly being only partially filled. This method must
177    /// behave equivalently to a single call to `read` with concatenated
178    /// buffers.
179    ///
180    /// The default implementation calls `read` with either the first nonempty
181    /// buffer provided, or an empty one if none exists.
182    #[stable(feature = "iovec", since = "1.36.0")]
183    fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize> {
184        default_read_vectored(|b| self.read(b), bufs)
185    }
186
187    /// Determines if this `Read`er has an efficient `read_vectored`
188    /// implementation.
189    ///
190    /// If a `Read`er does not override the default `read_vectored`
191    /// implementation, code using it may want to avoid the method all together
192    /// and coalesce writes into a single buffer for higher performance.
193    ///
194    /// The default implementation returns `false`.
195    #[unstable(feature = "can_vector", issue = "69941")]
196    fn is_read_vectored(&self) -> bool {
197        false
198    }
199
200    /// Reads all bytes until EOF in this source, placing them into `buf`.
201    ///
202    /// All bytes read from this source will be appended to the specified buffer
203    /// `buf`. This function will continuously call [`read()`] to append more data to
204    /// `buf` until [`read()`] returns either [`Ok(0)`] or an error of
205    /// non-[`ErrorKind::Interrupted`] kind.
206    ///
207    /// If successful, this function will return the total number of bytes read.
208    ///
209    /// # Errors
210    ///
211    /// If this function encounters an error of the kind
212    /// [`ErrorKind::Interrupted`] then the error is ignored and the operation
213    /// will continue.
214    ///
215    /// If any other read error is encountered then this function immediately
216    /// returns. Any bytes which have already been read will be appended to
217    /// `buf`.
218    ///
219    /// # Examples
220    ///
221    /// `File`s implement `Read`:
222    ///
223    /// [`Ok(0)`]: Ok
224    /// [`ErrorKind::Interrupted`]: crate::io::ErrorKind::Interrupted
225    /// [`read()`]: Read::read
226    ///
227    /// ```no_run
228    /// use std::io;
229    /// use std::io::prelude::*;
230    /// use std::fs::File;
231    ///
232    /// fn main() -> io::Result<()> {
233    ///     let mut f = File::open("foo.txt")?;
234    ///     let mut buffer = Vec::new();
235    ///
236    ///     // read the whole file
237    ///     f.read_to_end(&mut buffer)?;
238    ///     Ok(())
239    /// }
240    /// ```
241    ///
242    /// (See also the `std::fs::read` convenience function for reading from a
243    /// file.)
244    ///
245    /// ## Implementing `read_to_end`
246    ///
247    /// When implementing the `io::Read` trait, it is recommended to allocate
248    /// memory using [`Vec::try_reserve`]. However, this behavior is not guaranteed
249    /// by all implementations, and `read_to_end` may not handle out-of-memory
250    /// situations gracefully.
251    ///
252    /// ```no_run
253    /// # #![expect(dead_code)]
254    /// # use std::io::{self, BufRead};
255    /// # struct Example { example_datasource: io::Empty } impl Example {
256    /// # fn get_some_data_for_the_example(&self) -> &'static [u8] { &[] }
257    /// fn read_to_end(&mut self, dest_vec: &mut Vec<u8>) -> io::Result<usize> {
258    ///     let initial_vec_len = dest_vec.len();
259    ///     loop {
260    ///         let src_buf = self.example_datasource.fill_buf()?;
261    ///         if src_buf.is_empty() {
262    ///             break;
263    ///         }
264    ///         dest_vec.try_reserve(src_buf.len())?;
265    ///         dest_vec.extend_from_slice(src_buf);
266    ///
267    ///         // Any irreversible side effects should happen after `try_reserve` succeeds,
268    ///         // to avoid losing data on allocation error.
269    ///         let read = src_buf.len();
270    ///         self.example_datasource.consume(read);
271    ///     }
272    ///     Ok(dest_vec.len() - initial_vec_len)
273    /// }
274    /// # }
275    /// ```
276    ///
277    /// # Usage Notes
278    ///
279    /// `read_to_end` attempts to read a source until EOF, but many sources are continuous streams
280    /// that do not send EOF. In these cases, `read_to_end` will block indefinitely. Standard input
281    /// is one such stream which may be finite if piped, but is typically continuous. For example,
282    /// `cat file | my-rust-program` will correctly terminate with an `EOF` upon closure of cat.
283    /// Reading user input or running programs that remain open indefinitely will never terminate
284    /// the stream with `EOF` (e.g. `yes | my-rust-program`).
285    ///
286    /// Using `.lines()` with a `BufReader` or using [`read`] can provide a better solution
287    ///
288    /// [`read`]: Read::read
289    /// [`Vec::try_reserve`]: crate::vec::Vec::try_reserve
290    #[stable(feature = "rust1", since = "1.0.0")]
291    fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
292        default_read_to_end(self, buf, None)
293    }
294
295    /// Reads all bytes until EOF in this source, appending them to `buf`.
296    ///
297    /// If successful, this function returns the number of bytes which were read
298    /// and appended to `buf`.
299    ///
300    /// # Errors
301    ///
302    /// If the data in this stream is *not* valid UTF-8 then an error is
303    /// returned and `buf` is unchanged.
304    ///
305    /// See [`read_to_end`] for other error semantics.
306    ///
307    /// [`read_to_end`]: Read::read_to_end
308    ///
309    /// # Examples
310    ///
311    /// `File`s implement `Read`:
312    ///
313    /// ```no_run
314    /// use std::io;
315    /// use std::io::prelude::*;
316    /// use std::fs::File;
317    ///
318    /// fn main() -> io::Result<()> {
319    ///     let mut f = File::open("foo.txt")?;
320    ///     let mut buffer = String::new();
321    ///
322    ///     f.read_to_string(&mut buffer)?;
323    ///     Ok(())
324    /// }
325    /// ```
326    ///
327    /// (See also the `std::fs::read_to_string` convenience function for
328    /// reading from a file.)
329    ///
330    /// # Usage Notes
331    ///
332    /// `read_to_string` attempts to read a source until EOF, but many sources are continuous streams
333    /// that do not send EOF. In these cases, `read_to_string` will block indefinitely. Standard input
334    /// is one such stream which may be finite if piped, but is typically continuous. For example,
335    /// `cat file | my-rust-program` will correctly terminate with an `EOF` upon closure of cat.
336    /// Reading user input or running programs that remain open indefinitely will never terminate
337    /// the stream with `EOF` (e.g. `yes | my-rust-program`).
338    ///
339    /// Using `.lines()` with a `BufReader` or using [`read`] can provide a better solution
340    ///
341    /// [`read`]: Read::read
342    #[stable(feature = "rust1", since = "1.0.0")]
343    fn read_to_string(&mut self, buf: &mut String) -> Result<usize> {
344        default_read_to_string(self, buf, None)
345    }
346
347    /// Reads the exact number of bytes required to fill `buf`.
348    ///
349    /// This function reads as many bytes as necessary to completely fill the
350    /// specified buffer `buf`.
351    ///
352    /// *Implementations* of this method can make no assumptions about the contents of `buf` when
353    /// this function is called. It is recommended that implementations only write data to `buf`
354    /// instead of reading its contents. The documentation on [`read`] has a more detailed
355    /// explanation of this subject.
356    ///
357    /// # Errors
358    ///
359    /// If this function encounters an error of the kind
360    /// [`ErrorKind::Interrupted`] then the error is ignored and the operation
361    /// will continue.
362    ///
363    /// If this function encounters an "end of file" before completely filling
364    /// the buffer, it returns an error of the kind [`ErrorKind::UnexpectedEof`].
365    /// The contents of `buf` are unspecified in this case.
366    ///
367    /// If any other read error is encountered then this function immediately
368    /// returns. The contents of `buf` are unspecified in this case.
369    ///
370    /// If this function returns an error, it is unspecified how many bytes it
371    /// has read, but it will never read more than would be necessary to
372    /// completely fill the buffer.
373    ///
374    /// # Examples
375    ///
376    /// `File`s implement `Read`:
377    ///
378    /// [`ErrorKind::Interrupted`]: crate::io::ErrorKind::Interrupted
379    /// [`ErrorKind::UnexpectedEof`]: crate::io::ErrorKind::UnexpectedEof
380    /// [`read`]: Read::read
381    ///
382    /// ```no_run
383    /// use std::io;
384    /// use std::io::prelude::*;
385    /// use std::fs::File;
386    ///
387    /// fn main() -> io::Result<()> {
388    ///     let mut f = File::open("foo.txt")?;
389    ///     let mut buffer = [0; 10];
390    ///
391    ///     // read exactly 10 bytes
392    ///     f.read_exact(&mut buffer)?;
393    ///     Ok(())
394    /// }
395    /// ```
396    #[stable(feature = "read_exact", since = "1.6.0")]
397    fn read_exact(&mut self, buf: &mut [u8]) -> Result<()> {
398        default_read_exact(self, buf)
399    }
400
401    /// Pull some bytes from this source into the specified buffer.
402    ///
403    /// This is equivalent to the [`read`](Read::read) method, except that it is passed a [`BorrowedCursor`] rather than `[u8]` to allow use
404    /// with uninitialized buffers. The new data will be appended to any existing contents of `buf`.
405    ///
406    /// The default implementation delegates to `read`.
407    ///
408    /// This method makes it possible to return both data and an error but it is advised against.
409    #[unstable(feature = "read_buf", issue = "78485")]
410    fn read_buf(&mut self, buf: BorrowedCursor<'_, u8>) -> Result<()> {
411        default_read_buf(|b| self.read(b), buf)
412    }
413
414    /// Reads the exact number of bytes required to fill `cursor`.
415    ///
416    /// This is similar to the [`read_exact`](Read::read_exact) method, except
417    /// that it is passed a [`BorrowedCursor`] rather than `[u8]` to allow use
418    /// with uninitialized buffers.
419    ///
420    /// # Errors
421    ///
422    /// If this function encounters an error of the kind [`ErrorKind::Interrupted`]
423    /// then the error is ignored and the operation will continue.
424    ///
425    /// If this function encounters an "end of file" before completely filling
426    /// the buffer, it returns an error of the kind [`ErrorKind::UnexpectedEof`].
427    ///
428    /// If any other read error is encountered then this function immediately
429    /// returns.
430    ///
431    /// If this function returns an error, all bytes read will be appended to `cursor`.
432    ///
433    /// [`ErrorKind::Interrupted`]: crate::io::ErrorKind::Interrupted
434    /// [`ErrorKind::UnexpectedEof`]: crate::io::ErrorKind::UnexpectedEof
435    #[unstable(feature = "read_buf", issue = "78485")]
436    fn read_buf_exact(&mut self, cursor: BorrowedCursor<'_, u8>) -> Result<()> {
437        default_read_buf_exact(self, cursor)
438    }
439
440    /// Creates a "by reference" adapter for this instance of `Read`.
441    ///
442    /// The returned adapter also implements `Read` and will simply borrow this
443    /// current reader.
444    ///
445    /// # Examples
446    ///
447    /// `File`s implement `Read`:
448    ///
449    /// ```no_run
450    /// use std::io;
451    /// use std::io::Read;
452    /// use std::fs::File;
453    ///
454    /// fn main() -> io::Result<()> {
455    ///     let mut f = File::open("foo.txt")?;
456    ///     let mut buffer = Vec::new();
457    ///     let mut other_buffer = Vec::new();
458    ///
459    ///     {
460    ///         let reference = f.by_ref();
461    ///
462    ///         // read at most 5 bytes
463    ///         reference.take(5).read_to_end(&mut buffer)?;
464    ///
465    ///     } // drop our &mut reference so we can use f again
466    ///
467    ///     // original file still usable, read the rest
468    ///     f.read_to_end(&mut other_buffer)?;
469    ///     Ok(())
470    /// }
471    /// ```
472    #[stable(feature = "rust1", since = "1.0.0")]
473    fn by_ref(&mut self) -> &mut Self
474    where
475        Self: Sized,
476    {
477        self
478    }
479
480    /// Transforms this `Read` instance to an [`Iterator`] over its bytes.
481    ///
482    /// The returned type implements [`Iterator`] where the [`Item`] is
483    /// <code>[Result]<[u8], [io::Error]></code>.
484    /// The yielded item is [`Ok`] if a byte was successfully read and [`Err`]
485    /// otherwise. EOF is mapped to returning [`None`] from this iterator.
486    ///
487    /// The default implementation calls `read` for each byte,
488    /// which can be very inefficient for data that's not in memory,
489    /// such as `File`. Consider using a `BufReader` in such cases.
490    ///
491    /// # Examples
492    ///
493    /// `File`s implement `Read`:
494    ///
495    /// [`Item`]: Iterator::Item
496    /// [Result]: core::result::Result "Result"
497    /// [io::Error]: crate::io::Error "io::Error"
498    ///
499    /// ```no_run
500    /// use std::io;
501    /// use std::io::prelude::*;
502    /// use std::io::BufReader;
503    /// use std::fs::File;
504    ///
505    /// fn main() -> io::Result<()> {
506    ///     let f = BufReader::new(File::open("foo.txt")?);
507    ///
508    ///     for byte in f.bytes() {
509    ///         println!("{}", byte?);
510    ///     }
511    ///     Ok(())
512    /// }
513    /// ```
514    #[stable(feature = "rust1", since = "1.0.0")]
515    fn bytes(self) -> Bytes<Self>
516    where
517        Self: Sized,
518    {
519        bytes(self)
520    }
521
522    /// Creates an adapter which will chain this stream with another.
523    ///
524    /// The returned `Read` instance will first read all bytes from this object
525    /// until EOF is encountered. Afterwards the output is equivalent to the
526    /// output of `next`.
527    ///
528    /// # Examples
529    ///
530    /// `File`s implement `Read`:
531    ///
532    /// ```no_run
533    /// use std::io;
534    /// use std::io::prelude::*;
535    /// use std::fs::File;
536    ///
537    /// fn main() -> io::Result<()> {
538    ///     let f1 = File::open("foo.txt")?;
539    ///     let f2 = File::open("bar.txt")?;
540    ///
541    ///     let mut handle = f1.chain(f2);
542    ///     let mut buffer = String::new();
543    ///
544    ///     // read the value into a String. We could use any Read method here,
545    ///     // this is just one example.
546    ///     handle.read_to_string(&mut buffer)?;
547    ///     Ok(())
548    /// }
549    /// ```
550    #[stable(feature = "rust1", since = "1.0.0")]
551    fn chain<R: Read>(self, next: R) -> Chain<Self, R>
552    where
553        Self: Sized,
554    {
555        chain(self, next)
556    }
557
558    /// Creates an adapter which will read at most `limit` bytes from it.
559    ///
560    /// This function returns a new instance of `Read` which will read at most
561    /// `limit` bytes, after which it will always return EOF ([`Ok(0)`]). Any
562    /// read errors will not count towards the number of bytes read and future
563    /// calls to [`read()`] may succeed.
564    ///
565    /// # Examples
566    ///
567    /// `File`s implement `Read`:
568    ///
569    /// [`Ok(0)`]: Ok
570    /// [`read()`]: Read::read
571    ///
572    /// ```no_run
573    /// use std::io;
574    /// use std::io::prelude::*;
575    /// use std::fs::File;
576    ///
577    /// fn main() -> io::Result<()> {
578    ///     let f = File::open("foo.txt")?;
579    ///     let mut buffer = [0; 5];
580    ///
581    ///     // read at most five bytes
582    ///     let mut handle = f.take(5);
583    ///
584    ///     handle.read(&mut buffer)?;
585    ///     Ok(())
586    /// }
587    /// ```
588    #[stable(feature = "rust1", since = "1.0.0")]
589    fn take(self, limit: u64) -> Take<Self>
590    where
591        Self: Sized,
592    {
593        take(self, limit)
594    }
595
596    /// Read and return a fixed array of bytes from this source.
597    ///
598    /// This function uses an array sized based on a const generic size known at compile time. You
599    /// can specify the size with turbofish (`reader.read_array::<8>()`), or let type inference
600    /// determine the number of bytes needed based on how the return value gets used. For instance,
601    /// this function works well with functions like [`u64::from_le_bytes`] to turn an array of
602    /// bytes into an integer of the same size.
603    ///
604    /// Like `read_exact`, if this function encounters an "end of file" before reading the desired
605    /// number of bytes, it returns an error of the kind [`ErrorKind::UnexpectedEof`].
606    ///
607    /// [`ErrorKind::UnexpectedEof`]: crate::io::ErrorKind::UnexpectedEof
608    ///
609    /// ```
610    /// #![feature(read_array)]
611    /// use std::io::Cursor;
612    /// use std::io::prelude::*;
613    ///
614    /// fn main() -> std::io::Result<()> {
615    ///     let mut buf = Cursor::new([1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3, 2]);
616    ///     let x = u64::from_le_bytes(buf.read_array()?);
617    ///     let y = u32::from_be_bytes(buf.read_array()?);
618    ///     let z = u16::from_be_bytes(buf.read_array()?);
619    ///     assert_eq!(x, 0x807060504030201);
620    ///     assert_eq!(y, 0x9080706);
621    ///     assert_eq!(z, 0x504);
622    ///     Ok(())
623    /// }
624    /// ```
625    #[unstable(feature = "read_array", issue = "148848")]
626    fn read_array<const N: usize>(&mut self) -> Result<[u8; N]>
627    where
628        Self: Sized,
629    {
630        let mut buf = [MaybeUninit::uninit(); N];
631        let mut borrowed_buf = BorrowedBuf::from(buf.as_mut_slice());
632        self.read_buf_exact(borrowed_buf.unfilled())?;
633        // Guard against incorrect `read_buf_exact` implementations.
634        assert_eq!(borrowed_buf.len(), N);
635        Ok(unsafe { MaybeUninit::array_assume_init(buf) })
636    }
637
638    /// Read and return a type (e.g. an integer) in little-endian order.
639    ///
640    /// You can specify the type with turbofish (`reader.read_le::<u64>()`), or let type inference
641    /// determine the type based on how the return value gets used.
642    ///
643    /// Like `read_exact`, if this function encounters an "end of file" before reading the desired
644    /// number of bytes, it returns an error of the kind [`ErrorKind::UnexpectedEof`].
645    ///
646    /// [`ErrorKind::UnexpectedEof`]: crate::io::ErrorKind::UnexpectedEof
647    ///
648    /// ```
649    /// #![feature(read_le)]
650    /// use std::io::Cursor;
651    /// use std::io::prelude::*;
652    ///
653    /// fn main() -> std::io::Result<()> {
654    ///     let mut buf = Cursor::new([1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3, 2]);
655    ///     let x: u64 = buf.read_le()?;
656    ///     let y: u32 = buf.read_le()?;
657    ///     let z = buf.read_le::<u16>()?;
658    ///     assert_eq!(x, 0x807060504030201);
659    ///     assert_eq!(y, 0x6070809);
660    ///     assert_eq!(z, 0x405);
661    ///     Ok(())
662    /// }
663    /// ```
664    #[unstable(feature = "read_le", issue = "156984")]
665    #[inline]
666    fn read_le<T: FromEndianBytes>(&mut self) -> Result<T>
667    where
668        Self: Sized,
669    {
670        T::read_le_from(self)
671    }
672
673    /// Read and return a type (e.g. an integer) in big-endian order.
674    ///
675    /// You can specify the type with turbofish (`reader.read_be::<u64>()`), or let type inference
676    /// determine the type based on how the return value gets used.
677    ///
678    /// Like `read_exact`, if this function encounters an "end of file" before reading the desired
679    /// number of bytes, it returns an error of the kind [`ErrorKind::UnexpectedEof`].
680    ///
681    /// [`ErrorKind::UnexpectedEof`]: crate::io::ErrorKind::UnexpectedEof
682    ///
683    /// ```
684    /// #![feature(read_le)]
685    /// use std::io::Cursor;
686    /// use std::io::prelude::*;
687    ///
688    /// fn main() -> std::io::Result<()> {
689    ///     let mut buf = Cursor::new([1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3, 2]);
690    ///     let x: u64 = buf.read_be()?;
691    ///     let y: u32 = buf.read_be()?;
692    ///     let z = buf.read_be::<u16>()?;
693    ///     assert_eq!(x, 0x102030405060708);
694    ///     assert_eq!(y, 0x9080706);
695    ///     assert_eq!(z, 0x504);
696    ///     Ok(())
697    /// }
698    /// ```
699    #[unstable(feature = "read_le", issue = "156984")]
700    #[inline]
701    fn read_be<T: FromEndianBytes>(&mut self) -> Result<T>
702    where
703        Self: Sized,
704    {
705        T::read_be_from(self)
706    }
707}
708
709/// Reads all bytes from a [reader][Read] into a new [`String`].
710///
711/// This is a convenience function for [`Read::read_to_string`]. Using this
712/// function avoids having to create a variable first and provides more type
713/// safety since you can only get the buffer out if there were no errors. (If you
714/// use [`Read::read_to_string`] you have to remember to check whether the read
715/// succeeded because otherwise your buffer will be empty or only partially full.)
716///
717/// # Performance
718///
719/// The downside of this function's increased ease of use and type safety is
720/// that it gives you less control over performance. For example, you can't
721/// pre-allocate memory like you can using [`String::with_capacity`] and
722/// [`Read::read_to_string`]. Also, you can't re-use the buffer if an error
723/// occurs while reading.
724///
725/// In many cases, this function's performance will be adequate and the ease of use
726/// and type safety tradeoffs will be worth it. However, there are cases where you
727/// need more control over performance, and in those cases you should definitely use
728/// [`Read::read_to_string`] directly.
729///
730/// Note that in some special cases, such as when reading files, this function will
731/// pre-allocate memory based on the size of the input it is reading. In those
732/// cases, the performance should be as good as if you had used
733/// [`Read::read_to_string`] with a manually pre-allocated buffer.
734///
735/// # Errors
736///
737/// This function forces you to handle errors because the output (the `String`)
738/// is wrapped in a [`Result`]. See [`Read::read_to_string`] for the errors
739/// that can occur. If any error occurs, you will get an [`Err`], so you
740/// don't have to worry about your buffer being empty or partially full.
741///
742/// # Examples
743///
744/// ```no_run
745/// # use std::io;
746/// fn main() -> io::Result<()> {
747///     let stdin = io::read_to_string(io::stdin())?;
748///     println!("Stdin was:");
749///     println!("{stdin}");
750///     Ok(())
751/// }
752/// ```
753///
754/// # Usage Notes
755///
756/// `read_to_string` attempts to read a source until EOF, but many sources are continuous streams
757/// that do not send EOF. In these cases, `read_to_string` will block indefinitely. Standard input
758/// is one such stream which may be finite if piped, but is typically continuous. For example,
759/// `cat file | my-rust-program` will correctly terminate with an `EOF` upon closure of cat.
760/// Reading user input or running programs that remain open indefinitely will never terminate
761/// the stream with `EOF` (e.g. `yes | my-rust-program`).
762///
763/// Using `.lines()` with a `BufReader` or using [`read`] can provide a better solution
764///
765/// [`read`]: Read::read
766///
767#[stable(feature = "io_read_to_string", since = "1.65.0")]
768pub fn read_to_string<R: Read>(mut reader: R) -> Result<String> {
769    let mut buf = String::new();
770    reader.read_to_string(&mut buf)?;
771    Ok(buf)
772}
773
774/// Bare metal platforms usually have very small amounts of RAM
775/// (in the order of hundreds of KB)
776#[doc(hidden)]
777#[unstable(feature = "core_io_internals", reason = "exposed only for libstd", issue = "none")]
778pub const DEFAULT_BUF_SIZE: usize = cfg_select! {
779    target_os = "espidf" => { 512 },
780    _ => { 8 * 1024 }
781};
782
783/// Several `read_to_string` and `read_line` methods in the standard library will
784/// append data into a `String` buffer, but we need to be pretty careful when
785/// doing this. The implementation will just call `.as_mut_vec()` and then
786/// delegate to a byte-oriented reading method, but we must ensure that when
787/// returning we never leave `buf` in a state such that it contains invalid UTF-8
788/// in its bounds.
789///
790/// To this end, we use an RAII guard (to protect against panics) which updates
791/// the length of the string when it is dropped. This guard initially truncates
792/// the string to the prior length and only after we've validated that the
793/// new contents are valid UTF-8 do we allow it to set a longer length.
794///
795/// The unsafety in this function is twofold:
796///
797/// 1. We're looking at the raw bytes of `buf`, so we take on the burden of UTF-8
798///    checks.
799/// 2. We're passing a raw buffer to the function `f`, and it is expected that
800///    the function only *appends* bytes to the buffer. We'll get undefined
801///    behavior if existing bytes are overwritten to have non-UTF-8 data.
802pub(super) unsafe fn append_to_string<F>(buf: &mut String, f: F) -> Result<usize>
803where
804    F: FnOnce(&mut Vec<u8>) -> Result<usize>,
805{
806    let len_original = buf.len();
807    // SAFETY: invalid UTF-8 discarded before return or unwind
808    let buf_vec = unsafe { buf.as_mut_vec() };
809    let mut g = DropGuard::new((len_original, buf_vec), |(len, buf)| unsafe {
810        buf.set_len(len);
811    });
812    let ret = f(g.1);
813
814    // SAFETY: the caller promises to only append data to `buf`
815    let appended = unsafe { g.1.get_unchecked(g.0..) };
816    if str::from_utf8(appended).is_err() {
817        ret.and_then(|_| Err(Error::INVALID_UTF8))
818    } else {
819        g.0 = g.1.len();
820        ret
821    }
822}
823
824/// Here we must serve many masters with conflicting goals:
825///
826/// - avoid allocating unless necessary
827/// - avoid overallocating if we know the exact size (#89165)
828/// - avoid passing large buffers to readers that always initialize the free capacity if they perform short reads (#23815, #23820)
829/// - pass large buffers to readers that do not initialize the spare capacity. this can amortize per-call overheads
830/// - and finally pass not-too-small and not-too-large buffers to Windows read APIs because they manage to suffer from both problems
831///   at the same time, i.e. small reads suffer from syscall overhead, all reads incur costs proportional to buffer size (#110650)
832#[doc(hidden)]
833#[unstable(feature = "core_io_internals", reason = "exposed only for libstd", issue = "none")]
834pub fn default_read_to_end<R: Read + ?Sized>(
835    r: &mut R,
836    buf: &mut Vec<u8>,
837    size_hint: Option<usize>,
838) -> Result<usize> {
839    let start_len = buf.len();
840    let start_cap = buf.capacity();
841    // Optionally limit the maximum bytes read on each iteration.
842    // This adds an arbitrary fiddle factor to allow for more data than we expect.
843    let mut max_read_size = size_hint
844        .and_then(|s| s.checked_add(1024)?.checked_next_multiple_of(DEFAULT_BUF_SIZE))
845        .unwrap_or(DEFAULT_BUF_SIZE);
846
847    const PROBE_SIZE: usize = 32;
848
849    fn small_probe_read<R: Read + ?Sized>(r: &mut R, buf: &mut Vec<u8>) -> Result<usize> {
850        let mut probe = [0u8; PROBE_SIZE];
851
852        loop {
853            cfg_select! {
854                no_global_oom_handling => {
855                    // Without global OOM handling we must proactively allocate the buffer
856                    // to avoid failing after already reading data.
857                    buf.try_reserve(PROBE_SIZE)?;
858                }
859                _ => {}
860            }
861
862            match r.read(&mut probe) {
863                Ok(n) => {
864                    cfg_select! {
865                        no_global_oom_handling => {
866                            // there is no way to recover from allocation failure here
867                            // because the data has already been read.
868                            buf.try_extend_from_slice_of_bytes(&probe[..n])?;
869                        }
870                        _ => {
871                            // there is no way to recover from allocation failure here
872                            // because the data has already been read.
873                            buf.extend_from_slice(&probe[..n]);
874                        }
875                    }
876                    return Ok(n);
877                }
878                Err(ref e) if e.is_interrupted() => continue,
879                Err(e) => return Err(e),
880            }
881        }
882    }
883
884    // avoid inflating empty/small vecs before we have determined that there's anything to read
885    if (size_hint.is_none() || size_hint == Some(0)) && buf.capacity() - buf.len() < PROBE_SIZE {
886        let read = small_probe_read(r, buf)?;
887
888        if read == 0 {
889            return Ok(0);
890        }
891    }
892
893    loop {
894        if buf.len() == buf.capacity() && buf.capacity() == start_cap {
895            // The buffer might be an exact fit. Let's read into a probe buffer
896            // and see if it returns `Ok(0)`. If so, we've avoided an
897            // unnecessary doubling of the capacity. But if not, append the
898            // probe buffer to the primary buffer and let its capacity grow.
899            let read = small_probe_read(r, buf)?;
900
901            if read == 0 {
902                return Ok(buf.len() - start_len);
903            }
904        }
905
906        if buf.len() == buf.capacity() {
907            // buf is full, need more space
908            buf.try_reserve(PROBE_SIZE)?;
909        }
910
911        let mut spare = buf.spare_capacity_mut();
912        let buf_len = cmp::min(spare.len(), max_read_size);
913        spare = &mut spare[..buf_len];
914        let mut read_buf: BorrowedBuf<'_, u8> = spare.into();
915
916        // Note that we don't track already initialized bytes here, but this is fine
917        // because we explicitly limit the read size
918        let mut cursor = read_buf.unfilled();
919        let result = loop {
920            match r.read_buf(cursor.reborrow()) {
921                Err(e) if e.is_interrupted() => continue,
922                // Do not stop now in case of error: we might have received both data
923                // and an error
924                res => break res,
925            }
926        };
927
928        let bytes_read = cursor.written();
929        let is_init = read_buf.is_init();
930
931        // SAFETY: BorrowedBuf's invariants mean this much memory is initialized.
932        unsafe {
933            let new_len = bytes_read + buf.len();
934            buf.set_len(new_len);
935        }
936
937        // Now that all data is pushed to the vector, we can fail without data loss
938        result?;
939
940        if bytes_read == 0 {
941            return Ok(buf.len() - start_len);
942        }
943
944        // Use heuristics to determine the max read size if no initial size hint was provided
945        if size_hint.is_none() {
946            // The reader is returning short reads but it doesn't call ensure_init().
947            // In that case we no longer need to restrict read sizes to avoid
948            // initialization costs.
949            // When reading from disk we usually don't get any short reads except at EOF.
950            // So we wait for at least 2 short reads before uncapping the read buffer;
951            // this helps with the Windows issue.
952            if !is_init {
953                max_read_size = usize::MAX;
954            }
955            // we have passed a larger buffer than previously and the
956            // reader still hasn't returned a short read
957            else if buf_len >= max_read_size && bytes_read == buf_len {
958                max_read_size = max_read_size.saturating_mul(2);
959            }
960        }
961    }
962}
963
964#[doc(hidden)]
965#[unstable(feature = "core_io_internals", reason = "exposed only for libstd", issue = "none")]
966pub fn default_read_to_string<R: Read + ?Sized>(
967    r: &mut R,
968    buf: &mut String,
969    size_hint: Option<usize>,
970) -> Result<usize> {
971    // Note that we do *not* call `r.read_to_end()` here. We are passing
972    // `&mut Vec<u8>` (the raw contents of `buf`) into the `read_to_end`
973    // method to fill it up. An arbitrary implementation could overwrite the
974    // entire contents of the vector, not just append to it (which is what
975    // we are expecting).
976    //
977    // To prevent extraneously checking the UTF-8-ness of the entire buffer
978    // we pass it to our hardcoded `default_read_to_end` implementation which
979    // we know is guaranteed to only read data into the end of the buffer.
980    unsafe { append_to_string(buf, |b| default_read_to_end(r, b, size_hint)) }
981}
982
983#[doc(hidden)]
984#[unstable(feature = "core_io_internals", reason = "exposed only for libstd", issue = "none")]
985pub fn default_read_vectored<F>(read: F, bufs: &mut [IoSliceMut<'_>]) -> Result<usize>
986where
987    F: FnOnce(&mut [u8]) -> Result<usize>,
988{
989    let buf = bufs.iter_mut().find(|b| !b.is_empty()).map_or(&mut [][..], |b| &mut **b);
990    read(buf)
991}
992
993pub(super) fn default_read_exact<R: Read + ?Sized>(this: &mut R, mut buf: &mut [u8]) -> Result<()> {
994    while !buf.is_empty() {
995        match this.read(buf) {
996            Ok(0) => break,
997            Ok(n) => {
998                buf = &mut buf[n..];
999            }
1000            Err(ref e) if e.is_interrupted() => {}
1001            Err(e) => return Err(e),
1002        }
1003    }
1004    if !buf.is_empty() { Err(Error::READ_EXACT_EOF) } else { Ok(()) }
1005}
1006
1007#[doc(hidden)]
1008#[unstable(feature = "core_io_internals", reason = "exposed only for libstd", issue = "none")]
1009pub fn default_read_buf<F>(read: F, mut cursor: BorrowedCursor<'_, u8>) -> Result<()>
1010where
1011    F: FnOnce(&mut [u8]) -> Result<usize>,
1012{
1013    let n = read(cursor.ensure_init())?;
1014    cursor.advance_checked(n);
1015    Ok(())
1016}
1017
1018pub(super) fn default_read_buf_exact<R: Read + ?Sized>(
1019    this: &mut R,
1020    mut cursor: BorrowedCursor<'_, u8>,
1021) -> Result<()> {
1022    while cursor.capacity() > 0 {
1023        let prev_written = cursor.written();
1024        match this.read_buf(cursor.reborrow()) {
1025            Ok(()) => {}
1026            Err(e) if e.is_interrupted() => continue,
1027            Err(e) => return Err(e),
1028        }
1029
1030        if cursor.written() == prev_written {
1031            return Err(Error::READ_EXACT_EOF);
1032        }
1033    }
1034
1035    Ok(())
1036}
1037
1038/// Trait for types that can be converted from a fixed-size byte array with a specified endianness
1039#[unstable(feature = "read_le_be_internals", reason = "internals", issue = "none")]
1040// Once we can use associated consts in the types of method parameters, rewrite this to have
1041// `from_le_bytes` and `from_be_bytes` methods, move it to `core`, and make it public.
1042pub impl(self) trait FromEndianBytes: Sized {
1043    #[doc(hidden)]
1044    fn read_le_from(r: &mut impl Read) -> Result<Self>;
1045
1046    #[doc(hidden)]
1047    fn read_be_from(r: &mut impl Read) -> Result<Self>;
1048}
1049
1050macro_rules! impl_from_endian_bytes {
1051    ($($t:ty),*$(,)?) => {$(
1052        #[unstable(feature = "read_le_be_internals", reason = "internals", issue = "none")]
1053        impl FromEndianBytes for $t {
1054            #[inline]
1055            fn read_le_from(r: &mut impl Read) -> Result<Self> {
1056                Ok(<$t>::from_le_bytes(r.read_array()?))
1057            }
1058
1059            #[inline]
1060            fn read_be_from(r: &mut impl Read) -> Result<Self> {
1061                Ok(<$t>::from_be_bytes(r.read_array()?))
1062            }
1063        }
1064    )*};
1065}
1066
1067impl_from_endian_bytes!(u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize, f32, f64);