Skip to content

Commit 98f7d4c

Browse files
committed
Document read_to_end memory handling non-guarantee
1 parent 75e1065 commit 98f7d4c

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

library/std/src/io/mod.rs

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -770,6 +770,30 @@ pub trait Read {
770770
/// file.)
771771
///
772772
/// [`std::fs::read`]: crate::fs::read
773+
///
774+
/// ## Implementing `read_to_end`
775+
///
776+
/// When implementing the `io::Read` trait, it is recommended to allocate
777+
/// memory using [`Vec::try_reserve`]. However, this behavior is not guaranteed
778+
/// by all implementations, and `read_to_end` may not handle out-of-memory
779+
/// situations gracefully.
780+
///
781+
/// ```no_run
782+
/// # use std::io;
783+
/// # struct Example; impl Example {
784+
/// # fn read_some_data_for_the_example(&self) -> &'static [u8] { &[] }
785+
/// fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
786+
/// let data_read = self.read_some_data_for_the_example();
787+
///
788+
/// buf.try_reserve(data_read.len()).map_err(|_| io::ErrorKind::OutOfMemory)?;
789+
/// buf.extend_from_slice(data_read);
790+
///
791+
/// Ok(data_read.len())
792+
/// }
793+
/// # }
794+
/// ```
795+
///
796+
/// [`Vec::try_reserve`]: crate::vec::Vec::try_reserve
773797
#[stable(feature = "rust1", since = "1.0.0")]
774798
fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
775799
default_read_to_end(self, buf, None)

0 commit comments

Comments
 (0)