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

use crate::hkt::Invariant;

use super::type_name;

/// [`TypeId`] for lifetime containing types.
///
/// This type supports a max of two lifetimes `'lt` and `'ctx`.
/// Which are expected to be used like `dyn Trait<'ctx> + 'lt`.
///
/// [`TypeId`] only allows `'static` types.
/// This ID type splits the borrows out so that the borrow checker can check
/// them independently. This does mean we must check the lifetimes at compile time.
/// When `id_a == id_b` then the types are equal including the lifetimes.
/// As such unsafe code can use this property to transmute values.
#[derive(Copy, Clone)]
pub struct WithLtTypeId<'lt> {
    /// We are invariant over 'lt so the borrow checker checks it for
    /// equality when doing `==`.
    _lt: Invariant<'lt>,

    /// Type ID of the higher ranked type.
    higher_type_id: TypeId,

    /// Name of the lifetime containing type for better error messages.
    #[cfg(feature = "better_errors")]
    name: &'static str,
}

impl<'lt> WithLtTypeId<'lt> {
    pub fn of<'u, T: ?Sized + type_name::WithLt<'u, 'lt>>() -> Self
    where
        'lt: 'u,
    {
        Self {
            _lt: Invariant::NEW,

            // We get the TypeId of the 'static higher ranked type.
            higher_type_id: TypeId::of::<type_name::Raised<'u, 'lt, T>>(),

            #[cfg(feature = "better_errors")]
            name: core::any::type_name::<T>(),
        }
    }
}

impl<'lt> core::fmt::Debug for WithLtTypeId<'lt> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        #[cfg(feature = "better_errors")]
        {
            core::fmt::Display::fmt(self.name, f)
        }

        #[cfg(not(feature = "better_errors"))]
        {
            core::fmt::Debug::fmt(&self.higher_type_id, f)
        }
    }
}

impl<'lt> PartialEq for WithLtTypeId<'lt> {
    fn eq(&self, other: &Self) -> bool {
        self.higher_type_id == other.higher_type_id
    }
}

impl<'lt> Eq for WithLtTypeId<'lt> {}

impl<'lt> PartialOrd for WithLtTypeId<'lt> {
    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
        Some(self.higher_type_id.cmp(&other.higher_type_id))
    }
}

impl<'lt> Ord for WithLtTypeId<'lt> {
    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
        self.higher_type_id.cmp(&other.higher_type_id)
    }
}

impl<'lt> core::hash::Hash for WithLtTypeId<'lt> {
    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
        self.higher_type_id.hash(state);
    }
}