From d3a4abe33670338c0a870a0e351697f43d2a385d Mon Sep 17 00:00:00 2001 From: Michael Pfaff Date: Thu, 29 Jun 2023 00:37:23 -0400 Subject: [PATCH] Initial commit --- .gitignore | 2 ++ Cargo.toml | 6 ++++++ src/lib.rs | 17 +++++++++++++++++ 3 files changed, 25 insertions(+) create mode 100644 .gitignore create mode 100644 Cargo.toml create mode 100644 src/lib.rs diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..96ef6c0 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +/target +Cargo.lock diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..f70160e --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "typeid-cast" +version = "0.1.0" +edition = "2021" + +[dependencies] diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..ccde957 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,17 @@ +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) + } +}