Tweak clear and truncate length modifications (#700)

This commit is contained in:
Alice Ryhl
2024-04-26 09:24:05 +02:00
committed by GitHub
parent a8806c2457
commit cb7f8449b5
+6 -8
View File
@@ -422,11 +422,9 @@ impl BytesMut {
/// assert_eq!(buf, b"hello"[..]); /// assert_eq!(buf, b"hello"[..]);
/// ``` /// ```
pub fn truncate(&mut self, len: usize) { pub fn truncate(&mut self, len: usize) {
if len < self.len() { if len <= self.len() {
unsafe { // SAFETY: Shrinking the buffer cannot expose uninitialized bytes.
// SAFETY: Shrinking the buffer cannot expose uninitialized bytes. unsafe { self.set_len(len) };
self.set_len(len);
}
} }
} }
@@ -442,7 +440,8 @@ impl BytesMut {
/// assert!(buf.is_empty()); /// assert!(buf.is_empty());
/// ``` /// ```
pub fn clear(&mut self) { 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`. /// 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, // Advancing by the length is the same as resetting the length to 0,
// except this way we get to reuse the full capacity. // except this way we get to reuse the full capacity.
if cnt == self.remaining() { if cnt == self.remaining() {
// SAFETY: Zero is not greater than the capacity. self.clear();
unsafe { self.set_len(0) };
return; return;
} }