@@ -462,7 +462,8 @@ pub(crate) fn default_read_to_end<R: Read + ?Sized>(
462462 }
463463
464464 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 ) ?;
466467 }
467468
468469 let mut spare = buf. spare_capacity_mut ( ) ;
@@ -815,6 +816,30 @@ pub trait Read {
815816 /// file.)
816817 ///
817818 /// [`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
818843 #[ stable( feature = "rust1" , since = "1.0.0" ) ]
819844 fn read_to_end ( & mut self , buf : & mut Vec < u8 > ) -> Result < usize > {
820845 default_read_to_end ( self , buf, None )
0 commit comments