Skip to content

Commit 5fa1926

Browse files
committed
Add Buffer::consume_with to enable direct buffer access with one check
1 parent 5e5ce43 commit 5fa1926

File tree

2 files changed

+18
-3
lines changed

2 files changed

+18
-3
lines changed

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

+1-3
Original file line numberDiff line numberDiff line change
@@ -290,9 +290,7 @@ impl<R: Read> Read for BufReader<R> {
290290
// generation for the common path where the buffer has enough bytes to fill the passed-in
291291
// buffer.
292292
fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
293-
if let Some(claimed) = self.buffer().get(..buf.len()) {
294-
buf.copy_from_slice(claimed);
295-
self.consume(claimed.len());
293+
if self.buf.consume_with(buf.len(), |claimed| buf.copy_from_slice(claimed)) {
296294
return Ok(());
297295
}
298296

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

+17
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,23 @@ impl Buffer {
6262
self.pos = cmp::min(self.pos + amt, self.filled);
6363
}
6464

65+
/// If there are `amt` bytes available in the buffer, pass a slice containing those bytes to
66+
/// `visitor` and return true. If there are not enough bytes available, return false.
67+
#[inline]
68+
pub fn consume_with<V>(&mut self, amt: usize, mut visitor: V) -> bool
69+
where
70+
V: FnMut(&[u8]),
71+
{
72+
if let Some(claimed) = self.buffer().get(..amt) {
73+
visitor(claimed);
74+
// If the indexing into self.buffer() succeeds, amt must be a valid increment.
75+
self.pos += amt;
76+
true
77+
} else {
78+
false
79+
}
80+
}
81+
6582
#[inline]
6683
pub fn unconsume(&mut self, amt: usize) {
6784
self.pos = self.pos.saturating_sub(amt);

0 commit comments

Comments
 (0)