Skip to content

Commit 53e0550

Browse files
committed
Use ManuallyDrop to avoid allocation
1 parent 069ce5a commit 53e0550

File tree

1 file changed

+5
-4
lines changed

1 file changed

+5
-4
lines changed

src/lib.rs

+5-4
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ assert!(nums[0] == "2");
4747
use std::convert::TryFrom;
4848
use std::error::Error;
4949
use std::fmt;
50+
use std::mem::ManuallyDrop;
5051
use std::os::raw::c_void;
5152
use std::panic::AssertUnwindSafe;
5253
use std::time::Duration;
@@ -114,7 +115,7 @@ where
114115
{
115116
#[derive(Debug)]
116117
struct SyncContext<F, T> {
117-
closure: *mut F,
118+
closure: ManuallyDrop<F>,
118119
result: Option<std::thread::Result<T>>,
119120
}
120121

@@ -123,12 +124,12 @@ where
123124
F: FnOnce() -> T,
124125
{
125126
let sync_context: &mut SyncContext<F, T> = unsafe { &mut *(context as *mut _) };
126-
let closure = unsafe { Box::from_raw(sync_context.closure) };
127+
let closure = unsafe { ManuallyDrop::take(&mut sync_context.closure) };
127128
sync_context.result = Some(std::panic::catch_unwind(AssertUnwindSafe(closure)));
128129
}
129130

130131
let mut sync_context: SyncContext<F, T> = SyncContext {
131-
closure: Box::into_raw(Box::new(closure)),
132+
closure: ManuallyDrop::new(closure),
132133
result: None,
133134
};
134135
let func: dispatch_function_t = work_execute_closure::<F, T>;
@@ -139,7 +140,7 @@ where
139140
Ok(res) => {
140141
if res.is_none() {
141142
// if the closure didn't run (for example when using `Once`), free the box
142-
std::mem::drop(unsafe { Box::from_raw(sync_context.closure) });
143+
unsafe { ManuallyDrop::drop(&mut sync_context.closure); };
143144
}
144145
res
145146
}

0 commit comments

Comments
 (0)