From 26b7106b1daf44b5cc850830d4a0f99d0e9a740c Mon Sep 17 00:00:00 2001 From: Paolo Barbolini Date: Tue, 23 Apr 2024 21:55:34 +0200 Subject: [PATCH] Reuse capacity when possible in ::advance impl --- src/bytes_mut.rs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/bytes_mut.rs b/src/bytes_mut.rs index 0ea0272c5..2d77092a8 100644 --- a/src/bytes_mut.rs +++ b/src/bytes_mut.rs @@ -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`.