use std::{any::TypeId, mem::ManuallyDrop}; /// Safe cast using [`TypeId`]. #[inline] pub fn cast(t: T) -> Result { if TypeId::of::() == TypeId::of::() { union U { t: ManuallyDrop, r: ManuallyDrop, } // SAFETY: we've confirmed the types are the same. Ok(unsafe { ManuallyDrop::into_inner(U { t: ManuallyDrop::new(t) }.r) }) } else { Err(t) } } #[cfg(test)] mod test { use super::*; #[test] fn test_cast() { assert_eq!(cast::<_, &'static str>("foo"), Ok("foo")); assert_eq!(cast::<_, &'static str>(4), Err(4)); } }