Skip to content

Commit

Permalink
Merge pull request #2 from bincode-org/fix-double-drop
Browse files Browse the repository at this point in the history
Fixed double drop in unty
  • Loading branch information
VictorKoenders authored Sep 23, 2023
2 parents 582794d + 7f5b35e commit fd1e8a4
Showing 1 changed file with 22 additions and 0 deletions.
22 changes: 22 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ use core::{any::TypeId, marker::PhantomData, mem};
pub unsafe fn unty<Src, Target: 'static>(x: Src) -> Result<Target, Src> {
if type_equal::<Src, Target>() {
let ptr = &x as *const Src as *const Target;
mem::forget(x); // we're going to copy this, so don't run the destructor
Ok(core::ptr::read(ptr))
} else {
Err(x)
Expand Down Expand Up @@ -73,3 +74,24 @@ fn non_static_type_id<T: ?Sized>() -> TypeId {
mem::transmute::<&dyn NonStaticAny, &(dyn NonStaticAny + 'static)>(&phantom_data)
})
}

#[test]
fn test_double_drop() {
use core::sync::atomic::{AtomicUsize, Ordering};
#[derive(Debug)]
struct Ty;
static COUNTER: AtomicUsize = AtomicUsize::new(0);

impl Drop for Ty {
fn drop(&mut self) {
COUNTER.fetch_add(1, Ordering::Relaxed);
}
}

fn foo<T: core::fmt::Debug>(t: T) {
unsafe { unty::<T, Ty>(t) }.unwrap();
}

foo(Ty);
assert_eq!(COUNTER.load(Ordering::Relaxed), 1);
}

0 comments on commit fd1e8a4

Please sign in to comment.