Skip to content

Commit

Permalink
Rollup merge of rust-lang#137832 - wgwoods:fix-bufreader-peek, r=joboet
Browse files Browse the repository at this point in the history
Fix crash in BufReader::peek()

`bufreader_peek` tracking issue: rust-lang#128405

This fixes a logic error in `Buffer::read_more()` that would make `BufReader::peek()` expose uninitialized data and/or segfault if `read_more()` was called with a partially-full buffer and a non-empty inner reader.
  • Loading branch information
matthiaskrgr authored Mar 7, 2025
2 parents d986027 + 6d07144 commit a98df54
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 5 deletions.
6 changes: 3 additions & 3 deletions library/std/src/io/buffered/bufreader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,16 +118,16 @@ impl<R: Read + ?Sized> BufReader<R> {
/// #![feature(bufreader_peek)]
/// use std::io::{Read, BufReader};
///
/// let mut bytes = &b"oh, hello"[..];
/// let mut bytes = &b"oh, hello there"[..];
/// let mut rdr = BufReader::with_capacity(6, &mut bytes);
/// assert_eq!(rdr.peek(2).unwrap(), b"oh");
/// let mut buf = [0; 4];
/// rdr.read(&mut buf[..]).unwrap();
/// assert_eq!(&buf, b"oh, ");
/// assert_eq!(rdr.peek(2).unwrap(), b"he");
/// assert_eq!(rdr.peek(5).unwrap(), b"hello");
/// let mut s = String::new();
/// rdr.read_to_string(&mut s).unwrap();
/// assert_eq!(&s, "hello");
/// assert_eq!(&s, "hello there");
/// assert_eq!(rdr.peek(1).unwrap().len(), 0);
/// ```
#[unstable(feature = "bufreader_peek", issue = "128405")]
Expand Down
4 changes: 2 additions & 2 deletions library/std/src/io/buffered/bufreader/buffer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -109,8 +109,8 @@ impl Buffer {

/// Read more bytes into the buffer without discarding any of its contents
pub fn read_more(&mut self, mut reader: impl Read) -> io::Result<usize> {
let mut buf = BorrowedBuf::from(&mut self.buf[self.pos..]);
let old_init = self.initialized - self.pos;
let mut buf = BorrowedBuf::from(&mut self.buf[self.filled..]);
let old_init = self.initialized - self.filled;
unsafe {
buf.set_init(old_init);
}
Expand Down

0 comments on commit a98df54

Please sign in to comment.