From baa5053572ed9e88ca1058ec2b5a3f08046c5a40 Mon Sep 17 00:00:00 2001 From: Paolo Barbolini Date: Thu, 25 Apr 2024 09:08:16 +0200 Subject: [PATCH] Reuse capacity when possible in ::advance impl (#698) --- src/bytes_mut.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/bytes_mut.rs b/src/bytes_mut.rs index 0ea0272c5..35e19005a 100644 --- a/src/bytes_mut.rs +++ b/src/bytes_mut.rs @@ -1066,6 +1066,14 @@ 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`: {:?} <= {:?}",