From cb7f8449b5efc7022dc592b3a1d7dd33079f4c8f Mon Sep 17 00:00:00 2001 From: Alice Ryhl Date: Fri, 26 Apr 2024 09:24:05 +0200 Subject: [PATCH] Tweak clear and truncate length modifications (#700) --- src/bytes_mut.rs | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/src/bytes_mut.rs b/src/bytes_mut.rs index 75762996a..b01bb1adc 100644 --- a/src/bytes_mut.rs +++ b/src/bytes_mut.rs @@ -422,11 +422,9 @@ impl BytesMut { /// assert_eq!(buf, b"hello"[..]); /// ``` pub fn truncate(&mut self, len: usize) { - if len < self.len() { - unsafe { - // SAFETY: Shrinking the buffer cannot expose uninitialized bytes. - self.set_len(len); - } + if len <= self.len() { + // SAFETY: Shrinking the buffer cannot expose uninitialized bytes. + unsafe { self.set_len(len) }; } } @@ -442,7 +440,8 @@ impl BytesMut { /// assert!(buf.is_empty()); /// ``` pub fn clear(&mut self) { - self.truncate(0); + // SAFETY: Setting the length to zero cannot expose uninitialized bytes. + unsafe { self.set_len(0) }; } /// Resizes the buffer so that `len` is equal to `new_len`. @@ -1069,8 +1068,7 @@ impl Buf for BytesMut { // 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) }; + self.clear(); return; }