Skip to content

Commit

Permalink
implement BufReader::peek
Browse files Browse the repository at this point in the history
  • Loading branch information
lolbinarycat committed Jul 30, 2024
1 parent 595316b commit 789e60b
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
26 changes: 26 additions & 0 deletions library/std/src/io/buffered/bufreader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,32 @@ impl<R: Read> BufReader<R> {
pub fn with_capacity(capacity: usize, inner: R) -> BufReader<R> {
BufReader { inner, buf: Buffer::with_capacity(capacity) }
}

/// Attempt to look ahead `n` bytes.
///
/// `n` must be less than `capacity`.
///
/// ## Examples
///
/// ```rust
/// #![feature(bufreader_peek)]
/// use std::io::{Read, BufReader};
///
/// let mut bytes = &b"hello"[..];
/// let mut rdr = BufReader::with_capacity(6, &mut bytes);
/// assert_eq!(rdr.peek(2).unwrap(), b"he");
/// let mut s = String::new();
/// rdr.read_to_string(&mut s).unwrap();
/// assert_eq!(&s, "hello");
/// ```
#[unstable(feature = "bufreader_peek", issue = "128405")]
pub fn peek(&mut self, n: usize) -> io::Result<&[u8]> {
assert!(n < self.capacity());
while n > self.buf.buffer().len() {
self.buf.read_more(&mut self.inner)?;
}
Ok(&self.buf.buffer()[..n])
}
}

impl<R: ?Sized> BufReader<R> {
Expand Down
12 changes: 12 additions & 0 deletions library/std/src/io/buffered/bufreader/buffer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,18 @@ impl Buffer {
self.pos = self.pos.saturating_sub(amt);
}

pub fn read_more(&mut self, mut reader: impl Read) -> io::Result<()> {
let mut buf = BorrowedBuf::from(&mut self.buf[self.pos..]);
let old_init = self.initialized - self.pos;
unsafe {
buf.set_init(old_init);
}
reader.read_buf(buf.unfilled())?;
self.filled += buf.len();
self.initialized += buf.init_len() - old_init;
Ok(())
}

#[inline]
pub fn fill_buf(&mut self, mut reader: impl Read) -> io::Result<&[u8]> {
// If we've reached the end of our internal buffer then we need to fetch
Expand Down

0 comments on commit 789e60b

Please sign in to comment.