File tree 1 file changed +24
-0
lines changed 1 file changed +24
-0
lines changed Original file line number Diff line number Diff line change @@ -770,6 +770,30 @@ pub trait Read {
770
770
/// file.)
771
771
///
772
772
/// [`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
773
797
#[ stable( feature = "rust1" , since = "1.0.0" ) ]
774
798
fn read_to_end ( & mut self , buf : & mut Vec < u8 > ) -> Result < usize > {
775
799
default_read_to_end ( self , buf, None )
You can’t perform that action at this time.
0 commit comments