Skip to content

Commit 120793a

Browse files
committed
implement BufReader::peek
1 parent 595316b commit 120793a

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

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

+27
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,33 @@ impl<R: Read> BufReader<R> {
9494
pub fn with_capacity(capacity: usize, inner: R) -> BufReader<R> {
9595
BufReader { inner, buf: Buffer::with_capacity(capacity) }
9696
}
97+
98+
99+
/// Attempt to look ahead `n` bytes.
100+
///
101+
/// `n` must be less than `capacity`.
102+
///
103+
/// ## Examples
104+
///
105+
/// ```rust
106+
/// #![feature(bufreader_peek)]
107+
/// use std::io::{Read, BufReader};
108+
///
109+
/// let mut bytes = &b"hello"[..];
110+
/// let mut rdr = BufReader::with_capacity(6, &mut bytes);
111+
/// assert_eq!(rdr.peek(2).unwrap(), b"he");
112+
/// let mut s = String::new();
113+
/// rdr.read_to_string(&mut s).unwrap();
114+
/// assert_eq!(&s, "hello");
115+
/// ```
116+
#[unstable(feature = "bufreader_peek", issue = "128405")]
117+
pub fn peek(&mut self, n: usize) -> io::Result<&[u8]> {
118+
assert!(n < self.capacity());
119+
while n > self.buf.buffer().len() {
120+
self.buf.read_more(&mut self.inner)?;
121+
}
122+
Ok(&self.buf.buffer()[..n])
123+
}
97124
}
98125

99126
impl<R: ?Sized> BufReader<R> {

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

+12
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,18 @@ impl Buffer {
9797
self.pos = self.pos.saturating_sub(amt);
9898
}
9999

100+
pub fn read_more(&mut self, mut reader: impl Read) -> io::Result<()> {
101+
let mut buf = BorrowedBuf::from(&mut self.buf[self.pos..]);
102+
let old_init = self.initialized-self.pos;
103+
unsafe {
104+
buf.set_init(old_init);
105+
}
106+
reader.read_buf(buf.unfilled())?;
107+
self.filled += buf.len();
108+
self.initialized += buf.init_len() - old_init;
109+
Ok(())
110+
}
111+
100112
#[inline]
101113
pub fn fill_buf(&mut self, mut reader: impl Read) -> io::Result<&[u8]> {
102114
// If we've reached the end of our internal buffer then we need to fetch

0 commit comments

Comments
 (0)