Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Resize refactor #696

Merged
merged 8 commits into from Apr 24, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
26 changes: 17 additions & 9 deletions src/bytes_mut.rs
Expand Up @@ -468,18 +468,26 @@ impl BytesMut {
/// assert_eq!(&buf[..], &[0x1, 0x1, 0x3, 0x3]);
/// ```
pub fn resize(&mut self, new_len: usize, value: u8) {
let len = self.len();
if new_len > len {
let additional = new_len - len;
self.reserve(additional);
unsafe {
let dst = self.chunk_mut().as_mut_ptr();
ptr::write_bytes(dst, value, additional);
self.set_len(new_len);
}
let additional = if let Some(additional) = new_len.checked_sub(self.len()) {
additional
} else {
self.truncate(new_len);
return;
};

if additional == 0 {
return;
}

self.reserve(additional);
let dst = self.spare_capacity_mut().as_mut_ptr();
// SAFETY: `spare_capacity_mut` returns a valid, properly aligned pointer and we've
// reserved enough space to write `additional` bytes.
unsafe { ptr::write_bytes(dst, value, additional) };

// SAFETY: There are at least `new_len` initialized bytes in the buffer so no
// uninitialized bytes are being exposed.
unsafe { self.set_len(new_len) };
}

/// Sets the length of the buffer.
Expand Down