Debian Codegraph @

debian/rust-vendor/codspeed-divan-compat/src/compat/util/ty.rs

raw
1 use std::{
2 any::{Any, TypeId},
3 marker::PhantomData,
4 };
5
6 /// Returns a [`TypeId`] for any type regardless of whether it is `'static`.
7 ///
8 /// Note that **this is not the same** as [`TypeId::of`].
9 #[inline]
10 pub(crate) fn proxy_type_id<T: ?Sized>() -> TypeId {
11 // Return the type ID of a generic closure.
12 Any::type_id(&|| PhantomData::<T>)
13 }
14 /// Returns `true` if the given types are equal.
15 #[inline]
16 pub(crate) fn is_type_eq<A: ?Sized, B: ?Sized>() -> bool {
17 proxy_type_id::<A>() == proxy_type_id::<B>()
18 }
19
20 /// Convenience trait for type conversions.
21 pub(crate) trait TypeCast {
22 /// Converts a reference if `self` is an instance of `T`.
23 ///
24 /// We require `T: 'static` since we want to ensure when providing a type
25 /// that any lifetimes are static, such as `Cow<str>`.
26 #[inline]
27 fn cast_ref<T: 'static>(&self) -> Option<&T> {
28 if is_type_eq::<Self, T>() {
29 // SAFETY: `self` is `&T`.
30 Some(unsafe { &*(self as *const Self as *const T) })
31 } else {
32 None
33 }
34 }
35 }
36
37 impl<A> TypeCast for A {}