Initial commit

This commit is contained in:
Michael Pfaff 2023-06-29 00:37:23 -04:00
commit d3a4abe336
Signed by: michael
GPG Key ID: CF402C4A012AA9D4
3 changed files with 25 additions and 0 deletions

2
.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
/target
Cargo.lock

6
Cargo.toml Normal file
View File

@ -0,0 +1,6 @@
[package]
name = "typeid-cast"
version = "0.1.0"
edition = "2021"
[dependencies]

17
src/lib.rs Normal file
View File

@ -0,0 +1,17 @@
use std::{any::TypeId, mem::ManuallyDrop};
/// Safe cast using [`TypeId`].
#[inline]
pub fn cast<T: 'static, R: 'static>(t: T) -> Result<R, T> {
if TypeId::of::<T>() == TypeId::of::<R>() {
union U<T, R> {
t: ManuallyDrop<T>,
r: ManuallyDrop<R>,
}
// SAFETY: we've confirmed the types are the same.
Ok(unsafe { ManuallyDrop::into_inner(U { t: ManuallyDrop::new(t) }.r) })
} else {
Err(t)
}
}