properly handle EOF in BufReader::peek · qinheping/verify-rust-std@335236c (original) (raw)

Original file line number Diff line number Diff line change
@@ -99,7 +99,10 @@ impl<R: Read> BufReader {
99 99 impl<R: Read + ?Sized> BufReader<R> {
100 100 /// Attempt to look ahead `n` bytes.
101 101 ///
102 - /// `n` must be less than `capacity`.
102 + /// `n` must be less than or equal to `capacity`.
103 + ///
104 + /// the returned slice may be less than `n` bytes long if
105 + /// end of file is reached.
103 106 ///
104 107 /// ## Examples
105 108 ///
@@ -117,6 +120,7 @@ impl<R: Read + ?Sized> BufReader {
117 120 /// let mut s = String::new();
118 121 /// rdr.read_to_string(&mut s).unwrap();
119 122 /// assert_eq!(&s, "hello");
123 + /// assert_eq!(rdr.peek(1).unwrap().len(), 0);
120 124 /// ```
121 125 #[unstable(feature = "bufreader_peek", issue = "128405")]
122 126 pub fn peek(&mut self, n: usize) -> io::Result<&[u8]> {
@@ -125,7 +129,11 @@ impl<R: Read + ?Sized> BufReader {
125 129 if self.buf.pos() > 0 {
126 130 self.buf.backshift();
127 131 }
128 -self.buf.read_more(&mut self.inner)?;
132 +let new = self.buf.read_more(&mut self.inner)?;
133 +if new == 0 {
134 +// end of file, no more bytes to read
135 +return Ok(&self.buf.buffer()[..]);
136 +}
129 137 debug_assert_eq!(self.buf.pos(), 0);
130 138 }
131 139 Ok(&self.buf.buffer()[..n])