Skip to main content

alloc/io/
read.rs

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