1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
#![no_std]
//! A crate that allows you to untype your types.
//!
//! This provides 2 functions:
//!
//! [`type_equal`] allows you to check if two types are the same.
//!
//! [`unty`] allows you to downcast a generic type into a concrete type.
//!
//! This is mostly useful for generic functions, e.g.
//!
//! ```
//! # use unty::*;
//! pub fn foo<S>(s: S) {
//! if let Ok(a) = unsafe { unty::<S, u8>(s) } {
//! println!("It is an u8 with value {a}");
//! } else {
//! println!("it is not an u8");
//! }
//! }
//! foo(10u8); // will print "it is an u8"
//! foo("test"); // will print "it is not an u8"
//! ```
//!
//! Note that both of these functions may give false positives if both types have lifetimes. There currently is not a way to prevent this. See [`type_equal`] for more information.
//!
//! ```no_run
//! # fn foo<'a>(input: &'a str) {
//! # use unty::*;
//! assert!(type_equal::<&'a str, &'static str>()); // these are not actually the same
//! if let Ok(str) = unsafe { unty::<&'a str, &'static str>(input) } {
//! // this will extend the &'a str lifetime to be &'static, which is not allowed.
//! // the compiler may now light your PC on fire.
//! }
//! # }
//! ```
use core::{any::TypeId, marker::PhantomData, mem};
/// Untypes your types. For documentation see the root of this crate.
///
/// # Safety
///
/// 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 x = mem::ManuallyDrop::new(x);
Ok(mem::transmute_copy::<Src, Target>(&x))
} else {
Err(x)
}
}
/// Checks to see if the two types are equal.
///
/// ```
/// # use unty::type_equal;
/// assert!(type_equal::<u8, u8>());
/// assert!(!type_equal::<u8, u16>());
///
/// fn is_string<T>(_t: T) -> bool {
/// type_equal::<T, String>()
/// }
///
/// assert!(is_string(String::new()));
/// assert!(!is_string("")); // `&'static str`, not `String`
/// ```
///
/// Note that this may give false positives if both of the types have lifetimes. Currently it is not possible to determine the difference between `&'a str` and `&'b str`.
///
/// ```
/// # use unty::type_equal;
/// # fn foo<'a, 'b>(a: &'a str, b: &'b str) {
/// assert!(type_equal::<&'a str, &'b str>()); // actual different types, this is not safe to transmute
/// # }
/// # foo("", "");
/// ```
pub fn type_equal<Src: ?Sized, Target: ?Sized>() -> bool {
non_static_type_id::<Src>() == non_static_type_id::<Target>()
}
// Code by dtolnay in a bincode issue:
// https://github.com/bincode-org/bincode/issues/665#issue-1903241159
fn non_static_type_id<T: ?Sized>() -> TypeId {
trait NonStaticAny {
fn get_type_id(&self) -> TypeId
where
Self: 'static;
}
impl<T: ?Sized> NonStaticAny for PhantomData<T> {
fn get_type_id(&self) -> TypeId
where
Self: 'static,
{
TypeId::of::<T>()
}
}
let phantom_data = PhantomData::<T>;
NonStaticAny::get_type_id(unsafe {
mem::transmute::<&dyn NonStaticAny, &(dyn NonStaticAny + 'static)>(&phantom_data)
})
}
#[test]
fn test_double_drop() {
use core::sync::atomic::{AtomicUsize, Ordering};
#[derive(Debug)]
struct Ty;
static COUNTER: AtomicUsize = AtomicUsize::new(0);
impl Drop for Ty {
fn drop(&mut self) {
COUNTER.fetch_add(1, Ordering::Relaxed);
}
}
fn foo<T: core::fmt::Debug>(t: T) {
unsafe { unty::<T, Ty>(t) }.unwrap();
}
foo(Ty);
assert_eq!(COUNTER.load(Ordering::Relaxed), 1);
}