Initial commit
This commit is contained in:
commit
d3a4abe336
|
@ -0,0 +1,2 @@
|
|||
/target
|
||||
Cargo.lock
|
|
@ -0,0 +1,6 @@
|
|||
[package]
|
||||
name = "typeid-cast"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
|
@ -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)
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue