Skip to content

Commit

Permalink
Fixed double drop in unty
Browse files Browse the repository at this point in the history
  • Loading branch information
Victor Koenders committed Sep 23, 2023
1 parent 582794d commit 7f5b35e
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 7f5b35e

Please sign in to comment.