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
use std::any::TypeId;

/// An equivalent of [TypeId] for non-`'static` types. Use
/// [impl_universal_type_id!] macro to implement.
pub unsafe trait UniversalTypeId {
    /// Returns [TypeId][std::any::TypeId] of `Self`.
    fn universal_type_id() -> TypeId;
    /// Returns [TypeId][std::any::TypeId] of a value.
    fn universal_type_id_of(&self) -> TypeId {
        Self::universal_type_id()
    }
}

#[macro_export]
/// Implement `UniversalTypeId` for arbitrary named generic type.
///
/// # Example
///
/// ``` no_run
/// # use lofi::impl_universal_type_id;
/// struct Foo<'a, 'b, T: 'a, U: 'b>(&'a T, &'b U);
///
/// impl_universal_type_id!(Foo<'a, 'b, T, U>);
/// ```
macro_rules! impl_universal_type_id {
    ($type:ident<$($lts:lifetime),* $(, $tys:ident)* $(,)?>) => {
        unsafe impl<$($lts,)* $($tys,)*> $crate::UniversalTypeId for $type<$($lts,)* $($tys,)*>
        where
            $($tys: 'static,)*
        {
            fn universal_type_id() -> core::any::TypeId {
                core::any::TypeId::of::<
                    $crate::impl_universal_type_id!(@t $type [] [$( $lts ),*] [$( $tys ),*])
                >()
            }
        }
    };
    (@t $type:ident [$($stat:lifetime),*] [$lt:lifetime $(, $rest:lifetime)*] [$($tys:ident),*]) => {
        $crate::impl_universal_type_id!(@t $type [$($stat,)* 'static] [$($rest),*] [$($tys),*])
    };
    (@t $type:ident [$($stat:lifetime),*] [] [$($tys:ident),*]) => {
        $type< $($stat,)* $($tys),*>
    };
}

unsafe impl UniversalTypeId for () {
    fn universal_type_id() -> TypeId { TypeId::of::<()>() }
}