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

Use ManuallyDrop instead of mem::forget #675

Merged
merged 3 commits into from
Mar 14, 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
26 changes: 12 additions & 14 deletions src/bytes_mut.rs
Original file line number Diff line number Diff line change
Expand Up @@ -244,23 +244,22 @@ impl BytesMut {
/// ```
#[inline]
pub fn freeze(self) -> Bytes {
if self.kind() == KIND_VEC {
let bytes = ManuallyDrop::new(self);
if bytes.kind() == KIND_VEC {
// Just re-use `Bytes` internal Vec vtable
unsafe {
let off = self.get_vec_pos();
let vec = rebuild_vec(self.ptr.as_ptr(), self.len, self.cap, off);
mem::forget(self);
let off = bytes.get_vec_pos();
let vec = rebuild_vec(bytes.ptr.as_ptr(), bytes.len, bytes.cap, off);
let mut b: Bytes = vec.into();
b.advance(off);
b
}
} else {
debug_assert_eq!(self.kind(), KIND_ARC);
debug_assert_eq!(bytes.kind(), KIND_ARC);

let ptr = self.ptr.as_ptr();
let len = self.len;
let data = AtomicPtr::new(self.data.cast());
mem::forget(self);
let ptr = bytes.ptr.as_ptr();
let len = bytes.len;
let data = AtomicPtr::new(bytes.data.cast());
unsafe { Bytes::with_vtable(ptr, len, data, &SHARED_VTABLE) }
}
}
Expand Down Expand Up @@ -829,11 +828,11 @@ impl BytesMut {
// internal change could make a simple pattern (`BytesMut::from(vec)`)
// suddenly a lot more expensive.
#[inline]
pub(crate) fn from_vec(mut vec: Vec<u8>) -> BytesMut {
pub(crate) fn from_vec(vec: Vec<u8>) -> BytesMut {
let mut vec = ManuallyDrop::new(vec);
let ptr = vptr(vec.as_mut_ptr());
let len = vec.len();
let cap = vec.capacity();
mem::forget(vec);

let original_capacity_repr = original_capacity_to_repr(cap);
let data = (original_capacity_repr << ORIGINAL_CAPACITY_OFFSET) | KIND_VEC;
Expand Down Expand Up @@ -1618,6 +1617,7 @@ impl PartialEq<Bytes> for BytesMut {
impl From<BytesMut> for Vec<u8> {
fn from(bytes: BytesMut) -> Self {
let kind = bytes.kind();
let bytes = ManuallyDrop::new(bytes);

let mut vec = if kind == KIND_VEC {
unsafe {
Expand All @@ -1634,7 +1634,7 @@ impl From<BytesMut> for Vec<u8> {

vec
} else {
return bytes.deref().to_vec();
return ManuallyDrop::into_inner(bytes).deref().to_vec();
}
};

Expand All @@ -1645,8 +1645,6 @@ impl From<BytesMut> for Vec<u8> {
vec.set_len(len);
}

mem::forget(bytes);

vec
}
}
Expand Down