Skip to content

Commit

Permalink
Reuse capacity when possible in <BytesMut as Buf>::advance impl
Browse files Browse the repository at this point in the history
  • Loading branch information
paolobarbolini committed Apr 24, 2024
1 parent ce09d7d commit 26b7106
Showing 1 changed file with 9 additions and 0 deletions.
9 changes: 9 additions & 0 deletions src/bytes_mut.rs
Expand Up @@ -1066,12 +1066,21 @@ impl Buf for BytesMut {

#[inline]
fn advance(&mut self, cnt: usize) {
// Advancing by the length is the same as resetting the length to 0,
// except this way we get to reuse the full capacity.
if cnt == self.remaining() {
// SAFETY: Zero is not greater than the capacity.
unsafe { self.set_len(0) };
return;
}

assert!(
cnt <= self.remaining(),
"cannot advance past `remaining`: {:?} <= {:?}",
cnt,
self.remaining(),
);

unsafe {
// SAFETY: We've checked that `cnt` <= `self.remaining()` and we know that
// `self.remaining()` <= `self.cap`.
Expand Down

0 comments on commit 26b7106

Please sign in to comment.