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

Bytes: Use ManuallyDrop instead of mem::forget #678

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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 11 additions & 9 deletions src/bytes.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use core::iter::FromIterator;
use core::mem::{self, ManuallyDrop};
use core::ops::{Deref, RangeBounds};
use core::{cmp, fmt, hash, mem, ptr, slice, usize};
use core::{cmp, fmt, hash, ptr, slice, usize};

use alloc::{
alloc::{dealloc, Layout},
Expand Down Expand Up @@ -828,13 +829,15 @@ impl From<&'static str> for Bytes {
}

impl From<Vec<u8>> for Bytes {
fn from(mut vec: Vec<u8>) -> Bytes {
fn from(vec: Vec<u8>) -> Bytes {
let mut vec = ManuallyDrop::new(vec);
let ptr = vec.as_mut_ptr();
let len = vec.len();
let cap = vec.capacity();

// Avoid an extra allocation if possible.
if len == cap {
let vec = ManuallyDrop::into_inner(vec);
return Bytes::from(vec.into_boxed_slice());
}

Expand All @@ -843,7 +846,6 @@ impl From<Vec<u8>> for Bytes {
cap,
ref_cnt: AtomicUsize::new(1),
});
mem::forget(vec);

let shared = Box::into_raw(shared);
// The pointer should be aligned, so this assert should
Expand Down Expand Up @@ -900,7 +902,7 @@ impl From<String> for Bytes {

impl From<Bytes> for Vec<u8> {
fn from(bytes: Bytes) -> Vec<u8> {
let bytes = mem::ManuallyDrop::new(bytes);
let bytes = ManuallyDrop::new(bytes);
unsafe { (bytes.vtable.to_vec)(&bytes.data, bytes.ptr, bytes.len) }
}
}
Expand Down Expand Up @@ -1116,11 +1118,11 @@ unsafe fn shared_to_vec_impl(shared: *mut Shared, ptr: *const u8, len: usize) ->
.compare_exchange(1, 0, Ordering::AcqRel, Ordering::Relaxed)
.is_ok()
{
let buf = (*shared).buf;
let cap = (*shared).cap;

// Deallocate Shared
drop(Box::from_raw(shared as *mut mem::ManuallyDrop<Shared>));
// Deallocate the `Shared` instance without running its destructor.
let shared = *Box::from_raw(shared);
let shared = ManuallyDrop::new(shared);
let buf = shared.buf;
let cap = shared.cap;

// Copy back buffer
ptr::copy(ptr, buf, len);
Expand Down