Skip to content

Commit

Permalink
Merge pull request #5 from dtolnay-contrib/invalid
Browse files Browse the repository at this point in the history
Fix read from invalidated ptr
  • Loading branch information
VictorKoenders authored Sep 24, 2023
2 parents 2f2379c + f47bf78 commit f8e4ddb
Showing 1 changed file with 7 additions and 4 deletions.
11 changes: 7 additions & 4 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,11 @@
//! # }
//! ```
use core::{any::TypeId, marker::PhantomData, mem};
use core::{
any::TypeId,
marker::PhantomData,
mem::{self, ManuallyDrop},
};

/// Untypes your types. For documentation see the root of this crate.
///
Expand All @@ -36,9 +40,8 @@ use core::{any::TypeId, marker::PhantomData, mem};
/// This should not be used with types with lifetimes.
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))
let x = ManuallyDrop::new(x);
Ok(mem::transmute_copy::<Src, Target>(&x))
} else {
Err(x)
}
Expand Down

0 comments on commit f8e4ddb

Please sign in to comment.