Skip to content

Commit 9d3ec1c

Browse files
braddunbarDarksonn
andauthored
Resize refactor (#696)
* use checked_sub * return when additional == 0 * move safe operation out of unsafe block * use spare_capacity_mut instead of chunk_mut We don't need to check capacity because it's already been reserved above. * Add safety comments * refactor to use guard clauses This would be better written with let-else, but we won't get that until `MSRV >= 1.65.x`. * use if-let instead of unwrap * reduce scope of unsafe blocks Co-authored-by: Alice Ryhl <aliceryhl@google.com> --------- Co-authored-by: Alice Ryhl <aliceryhl@google.com>
1 parent 4e2c9c0 commit 9d3ec1c

File tree

1 file changed

+17
-9
lines changed

1 file changed

+17
-9
lines changed

src/bytes_mut.rs

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -468,18 +468,26 @@ impl BytesMut {
468468
/// assert_eq!(&buf[..], &[0x1, 0x1, 0x3, 0x3]);
469469
/// ```
470470
pub fn resize(&mut self, new_len: usize, value: u8) {
471-
let len = self.len();
472-
if new_len > len {
473-
let additional = new_len - len;
474-
self.reserve(additional);
475-
unsafe {
476-
let dst = self.chunk_mut().as_mut_ptr();
477-
ptr::write_bytes(dst, value, additional);
478-
self.set_len(new_len);
479-
}
471+
let additional = if let Some(additional) = new_len.checked_sub(self.len()) {
472+
additional
480473
} else {
481474
self.truncate(new_len);
475+
return;
476+
};
477+
478+
if additional == 0 {
479+
return;
482480
}
481+
482+
self.reserve(additional);
483+
let dst = self.spare_capacity_mut().as_mut_ptr();
484+
// SAFETY: `spare_capacity_mut` returns a valid, properly aligned pointer and we've
485+
// reserved enough space to write `additional` bytes.
486+
unsafe { ptr::write_bytes(dst, value, additional) };
487+
488+
// SAFETY: There are at least `new_len` initialized bytes in the buffer so no
489+
// uninitialized bytes are being exposed.
490+
unsafe { self.set_len(new_len) };
483491
}
484492

485493
/// Sets the length of the buffer.

0 commit comments

Comments
 (0)