@@ -462,7 +462,8 @@ pub(crate) fn default_read_to_end<R: Read + ?Sized>(
462
462
}
463
463
464
464
if buf. len ( ) == buf. capacity ( ) {
465
- buf. reserve ( PROBE_SIZE ) ; // buf is full, need more space
465
+ // buf is full, need more space
466
+ buf. try_reserve ( PROBE_SIZE ) . map_err ( |_| ErrorKind :: OutOfMemory ) ?;
466
467
}
467
468
468
469
let mut spare = buf. spare_capacity_mut ( ) ;
@@ -815,6 +816,30 @@ pub trait Read {
815
816
/// file.)
816
817
///
817
818
/// [`std::fs::read`]: crate::fs::read
819
+ ///
820
+ /// ## Implementing `read_to_end`
821
+ ///
822
+ /// When implementing the `io::Read` trait, it is recommended to allocate
823
+ /// memory using [`Vec::try_reserve`]. However, this behavior is not guaranteed
824
+ /// by all implementations, and `read_to_end` may not handle out-of-memory
825
+ /// situations gracefully.
826
+ ///
827
+ /// ```no_run
828
+ /// # use std::io;
829
+ /// # struct Example; impl Example {
830
+ /// # fn read_some_data_for_the_example(&self) -> &'static [u8] { &[] }
831
+ /// fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
832
+ /// let data_read = self.read_some_data_for_the_example();
833
+ ///
834
+ /// buf.try_reserve(data_read.len()).map_err(|_| io::ErrorKind::OutOfMemory)?;
835
+ /// buf.extend_from_slice(data_read);
836
+ ///
837
+ /// Ok(data_read.len())
838
+ /// }
839
+ /// # }
840
+ /// ```
841
+ ///
842
+ /// [`Vec::try_reserve`]: crate::vec::Vec::try_reserve
818
843
#[ stable( feature = "rust1" , since = "1.0.0" ) ]
819
844
fn read_to_end ( & mut self , buf : & mut Vec < u8 > ) -> Result < usize > {
820
845
default_read_to_end ( self , buf, None )
0 commit comments