Skip to content

Commit

Permalink
Fix buffer invalidation at BufReader.read_vectored
Browse files Browse the repository at this point in the history
  • Loading branch information
André Vicente Milack committed Mar 6, 2019
1 parent 96e361f commit c36d91c
Showing 1 changed file with 11 additions and 9 deletions.
20 changes: 11 additions & 9 deletions src/libstd/io/buffered.rs
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,13 @@ impl<R: Read> BufReader<R> {
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn into_inner(self) -> R { self.inner }

/// Invalidates all data in the internal buffer.
#[inline]
fn discard_buffer(&mut self) {
self.pos = 0;
self.cap = 0;
}
}

impl<R: Seek> BufReader<R> {
Expand Down Expand Up @@ -225,9 +232,7 @@ impl<R: Read> Read for BufReader<R> {
// (larger than our internal buffer), bypass our internal buffer
// entirely.
if self.pos == self.cap && buf.len() >= self.buf.len() {
// Empty the buffer
self.cap = 0;
self.pos = 0;
self.discard_buffer();
return self.inner.read(buf);
}
let nread = {
Expand All @@ -241,6 +246,7 @@ impl<R: Read> Read for BufReader<R> {
fn read_vectored(&mut self, bufs: &mut [IoVecMut<'_>]) -> io::Result<usize> {
let total_len = bufs.iter().map(|b| b.len()).sum::<usize>();
if self.pos == self.cap && total_len >= self.buf.len() {
self.discard_buffer();
return self.inner.read_vectored(bufs);
}
let nread = {
Expand Down Expand Up @@ -326,18 +332,14 @@ impl<R: Seek> Seek for BufReader<R> {
} else {
// seek backwards by our remainder, and then by the offset
self.inner.seek(SeekFrom::Current(-remainder))?;
// Empty the buffer
self.cap = 0;
self.pos = 0;
self.discard_buffer();
result = self.inner.seek(SeekFrom::Current(n))?;
}
} else {
// Seeking with Start/End doesn't care about our buffer length.
result = self.inner.seek(pos)?;
}
// Empty the buffer
self.cap = 0;
self.pos = 0;
self.discard_buffer();
Ok(result)
}
}
Expand Down

0 comments on commit c36d91c

Please sign in to comment.