Skip to content

Commit 335236c

Browse files
committed
properly handle EOF in BufReader::peek
previously this would cause an infinite loop due to it being unable to read `n` bytes.
1 parent 2699de6 commit 335236c

File tree

2 files changed

+12
-4
lines changed

2 files changed

+12
-4
lines changed

std/src/io/buffered/bufreader.rs

+10-2
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,10 @@ impl<R: Read> BufReader<R> {
9999
impl<R: Read + ?Sized> BufReader<R> {
100100
/// Attempt to look ahead `n` bytes.
101101
///
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.
103106
///
104107
/// ## Examples
105108
///
@@ -117,6 +120,7 @@ impl<R: Read + ?Sized> BufReader<R> {
117120
/// let mut s = String::new();
118121
/// rdr.read_to_string(&mut s).unwrap();
119122
/// assert_eq!(&s, "hello");
123+
/// assert_eq!(rdr.peek(1).unwrap().len(), 0);
120124
/// ```
121125
#[unstable(feature = "bufreader_peek", issue = "128405")]
122126
pub fn peek(&mut self, n: usize) -> io::Result<&[u8]> {
@@ -125,7 +129,11 @@ impl<R: Read + ?Sized> BufReader<R> {
125129
if self.buf.pos() > 0 {
126130
self.buf.backshift();
127131
}
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+
}
129137
debug_assert_eq!(self.buf.pos(), 0);
130138
}
131139
Ok(&self.buf.buffer()[..n])

std/src/io/buffered/bufreader/buffer.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ impl Buffer {
9898
}
9999

100100
/// Read more bytes into the buffer without discarding any of its contents
101-
pub fn read_more(&mut self, mut reader: impl Read) -> io::Result<()> {
101+
pub fn read_more(&mut self, mut reader: impl Read) -> io::Result<usize> {
102102
let mut buf = BorrowedBuf::from(&mut self.buf[self.pos..]);
103103
let old_init = self.initialized - self.pos;
104104
unsafe {
@@ -107,7 +107,7 @@ impl Buffer {
107107
reader.read_buf(buf.unfilled())?;
108108
self.filled += buf.len();
109109
self.initialized += buf.init_len() - old_init;
110-
Ok(())
110+
Ok(buf.len())
111111
}
112112

113113
/// Remove bytes that have already been read from the buffer.

0 commit comments

Comments
 (0)