Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle out of memory errors in io::Read::read_to_end #116570

Closed
wants to merge 3 commits into from
Closed
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Document read_to_end memory handling non-guarantee
  • Loading branch information
kornelski committed Nov 7, 2023
commit 98f7d4cd1e024b356a3c49c3d40dc3442aa7d50f
24 changes: 24 additions & 0 deletions library/std/src/io/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -770,6 +770,30 @@ pub trait Read {
/// file.)
///
/// [`std::fs::read`]: crate::fs::read
///
/// ## Implementing `read_to_end`
///
/// When implementing the `io::Read` trait, it is recommended to allocate
/// memory using [`Vec::try_reserve`]. However, this behavior is not guaranteed
/// by all implementations, and `read_to_end` may not handle out-of-memory
/// situations gracefully.
///
/// ```no_run
/// # use std::io;
/// # struct Example; impl Example {
/// # fn read_some_data_for_the_example(&self) -> &'static [u8] { &[] }
/// fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
/// let data_read = self.read_some_data_for_the_example();
///
/// buf.try_reserve(data_read.len()).map_err(|_| io::ErrorKind::OutOfMemory)?;
/// buf.extend_from_slice(data_read);
///
/// Ok(data_read.len())
/// }
/// # }
/// ```
///
/// [`Vec::try_reserve`]: crate::vec::Vec::try_reserve
#[stable(feature = "rust1", since = "1.0.0")]
fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
default_read_to_end(self, buf, None)
Expand Down
Loading