Skip to content

Commit 0d4cc7f

Browse files
authored
Bytes: Use ManuallyDrop instead of mem::forget (#678)
1 parent ce8d8a0 commit 0d4cc7f

File tree

1 file changed

+11
-9
lines changed

1 file changed

+11
-9
lines changed

src/bytes.rs

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
use core::iter::FromIterator;
2+
use core::mem::{self, ManuallyDrop};
23
use core::ops::{Deref, RangeBounds};
3-
use core::{cmp, fmt, hash, mem, ptr, slice, usize};
4+
use core::{cmp, fmt, hash, ptr, slice, usize};
45

56
use alloc::{
67
alloc::{dealloc, Layout},
@@ -828,13 +829,15 @@ impl From<&'static str> for Bytes {
828829
}
829830

830831
impl From<Vec<u8>> for Bytes {
831-
fn from(mut vec: Vec<u8>) -> Bytes {
832+
fn from(vec: Vec<u8>) -> Bytes {
833+
let mut vec = ManuallyDrop::new(vec);
832834
let ptr = vec.as_mut_ptr();
833835
let len = vec.len();
834836
let cap = vec.capacity();
835837

836838
// Avoid an extra allocation if possible.
837839
if len == cap {
840+
let vec = ManuallyDrop::into_inner(vec);
838841
return Bytes::from(vec.into_boxed_slice());
839842
}
840843

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

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

901903
impl From<Bytes> for Vec<u8> {
902904
fn from(bytes: Bytes) -> Vec<u8> {
903-
let bytes = mem::ManuallyDrop::new(bytes);
905+
let bytes = ManuallyDrop::new(bytes);
904906
unsafe { (bytes.vtable.to_vec)(&bytes.data, bytes.ptr, bytes.len) }
905907
}
906908
}
@@ -1116,11 +1118,11 @@ unsafe fn shared_to_vec_impl(shared: *mut Shared, ptr: *const u8, len: usize) ->
11161118
.compare_exchange(1, 0, Ordering::AcqRel, Ordering::Relaxed)
11171119
.is_ok()
11181120
{
1119-
let buf = (*shared).buf;
1120-
let cap = (*shared).cap;
1121-
1122-
// Deallocate Shared
1123-
drop(Box::from_raw(shared as *mut mem::ManuallyDrop<Shared>));
1121+
// Deallocate the `Shared` instance without running its destructor.
1122+
let shared = *Box::from_raw(shared);
1123+
let shared = ManuallyDrop::new(shared);
1124+
let buf = shared.buf;
1125+
let cap = shared.cap;
11241126

11251127
// Copy back buffer
11261128
ptr::copy(ptr, buf, len);

0 commit comments

Comments
 (0)