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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
use std::marker::PhantomData;
use std::mem::{transmute_copy, ManuallyDrop};

/// Indicates that a type [covariantly](https://doc.rust-lang.org/nomicon/subtyping.html)
/// references a set of lifetime parameters, and when these parameters are all replaced with `'a`,
/// the resulting type is `Target`. Consequentially, if the type outlives `'a`, it can be directly
/// coerced to `Target` by applying covariance.
///
/// This trait can be trivially implemented for any type by setting `Target` to be `Self`. However,
/// in order to maximize its usefulness, it should operate on as many lifetime parameters as
/// possible.
///
/// This trait can be automatically derived. When deriving on a type with no lifetime parameters,
/// the trivial implementation will be used (i.e. `Target = Self`). Otherwise, it will operate
/// on the first lifetime parameter in the generic parameters list. Deriving will fail if the
/// type is not covariant in this parameter.
///
/// # Safety
///
/// The implementor is responsible for ensuring that for all `'a` where `T: 'a`,
/// `<T as Lower<'a>>::Target` is a subtype of `T`.
pub unsafe trait Lower<'a> {
    /// The type resulting from substituting the covariant lifetime parameters in `Self` for `'a`.
    type Target: Lower<'a, Target = Self::Target> + ?Sized + 'a;

    /// Applies convariance in order to shorten the internal lifetime parameters in a reference.
    fn lower_ref<'b>(&'b self) -> &'b Self::Target
    where
        Self: 'a,
        'a: 'b,
    {
        // SAFETY: The implementor of the trait is responsible for ensuring that `Target` is
        // a covariant specialization of `Self`. Assuming this, we can directly coerce `Self` to
        // `Target`.
        unsafe { transmute_copy(&self) }
    }
}

unsafe impl<'a, 'b, T: Lower<'b> + ?Sized> Lower<'b> for &'a T {
    type Target = &'b <T as Lower<'b>>::Target;
}

unsafe impl<'a, 'b, T: 'b + ?Sized> Lower<'b> for &'a mut T {
    type Target = &'b mut T;
    fn lower_ref<'c>(&'c self) -> &'c Self::Target
    where
        'a: 'b,
        'b: 'c,
    {
        self
    }
}

unsafe impl<'a, T: Lower<'a> + ?Sized> Lower<'a> for Box<T> {
    type Target = Box<<T as Lower<'a>>::Target>;
}

unsafe impl<'a, T: Lower<'a>> Lower<'a> for [T]
where
    <T as Lower<'a>>::Target: Sized,
{
    type Target = [<T as Lower<'a>>::Target];
}

unsafe impl<'a, T: Lower<'a>, const N: usize> Lower<'a> for [T; N]
where
    <T as Lower<'a>>::Target: Sized,
{
    type Target = [<T as Lower<'a>>::Target; N];
}

unsafe impl<'a, A: Lower<'a>, B: Lower<'a> + ?Sized> Lower<'a> for (A, B)
where
    <A as Lower<'a>>::Target: Sized,
{
    type Target = (<A as Lower<'a>>::Target, <B as Lower<'a>>::Target);
}

unsafe impl<'a, A: Lower<'a>, B: Lower<'a>, C: Lower<'a> + ?Sized> Lower<'a> for (A, B, C)
where
    <A as Lower<'a>>::Target: Sized,
    <B as Lower<'a>>::Target: Sized,
{
    type Target = (
        <A as Lower<'a>>::Target,
        <B as Lower<'a>>::Target,
        <C as Lower<'a>>::Target,
    );
}

unsafe impl<'a, A: Lower<'a>, B: Lower<'a>, C: Lower<'a>, D: Lower<'a> + ?Sized> Lower<'a>
    for (A, B, C, D)
where
    <A as Lower<'a>>::Target: Sized,
    <B as Lower<'a>>::Target: Sized,
    <C as Lower<'a>>::Target: Sized,
{
    type Target = (
        <A as Lower<'a>>::Target,
        <B as Lower<'a>>::Target,
        <C as Lower<'a>>::Target,
        <D as Lower<'a>>::Target,
    );
}

macro_rules! impl_trivial_lower {
    ($t:ty) => {
        unsafe impl<'a> Lower<'a> for $t {
            type Target = $t;
            fn lower_ref<'b>(&'b self) -> &'b Self::Target
            where
                Self: 'a,
                'a: 'b,
            {
                self
            }
        }
    };
}

impl_trivial_lower!(());
impl_trivial_lower!(bool);
impl_trivial_lower!(char);
impl_trivial_lower!(f32);
impl_trivial_lower!(f64);
impl_trivial_lower!(i8);
impl_trivial_lower!(i16);
impl_trivial_lower!(i32);
impl_trivial_lower!(i64);
impl_trivial_lower!(i128);
impl_trivial_lower!(isize);
impl_trivial_lower!(u8);
impl_trivial_lower!(u16);
impl_trivial_lower!(u32);
impl_trivial_lower!(u64);
impl_trivial_lower!(u128);
impl_trivial_lower!(usize);
impl_trivial_lower!(std::num::NonZeroI8);
impl_trivial_lower!(std::num::NonZeroI16);
impl_trivial_lower!(std::num::NonZeroI32);
impl_trivial_lower!(std::num::NonZeroI64);
impl_trivial_lower!(std::num::NonZeroI128);
impl_trivial_lower!(std::num::NonZeroIsize);
impl_trivial_lower!(std::num::NonZeroU8);
impl_trivial_lower!(std::num::NonZeroU16);
impl_trivial_lower!(std::num::NonZeroU32);
impl_trivial_lower!(std::num::NonZeroU64);
impl_trivial_lower!(std::num::NonZeroU128);
impl_trivial_lower!(std::num::NonZeroUsize);
impl_trivial_lower!(std::sync::atomic::AtomicI8);
impl_trivial_lower!(std::sync::atomic::AtomicI16);
impl_trivial_lower!(std::sync::atomic::AtomicI32);
impl_trivial_lower!(std::sync::atomic::AtomicI64);
impl_trivial_lower!(std::sync::atomic::AtomicIsize);
impl_trivial_lower!(std::sync::atomic::AtomicU8);
impl_trivial_lower!(std::sync::atomic::AtomicU16);
impl_trivial_lower!(std::sync::atomic::AtomicU32);
impl_trivial_lower!(std::sync::atomic::AtomicU64);
impl_trivial_lower!(std::sync::atomic::AtomicUsize);
impl_trivial_lower!(str);
impl_trivial_lower!(String);
impl_trivial_lower!(std::ffi::CStr);
impl_trivial_lower!(std::ffi::CString);
impl_trivial_lower!(std::ffi::OsStr);
impl_trivial_lower!(std::ffi::OsString);

/// A value of `T` with its lifetime shortened to `'a`. This is isomorphic to
/// `<T as Lower<'a>>::Target`, but provides additional information to the compiler to assist
/// type inferencing.
pub struct Lowered<'a, T: 'a> {
    pub(crate) value: T,
    pub(crate) marker: PhantomData<&'a ()>,
}

impl<'a, T: 'a> Lowered<'a, T> {
    /// Constructs a [`Lowered`] from its wrapped value.
    ///
    /// The type signature of this function may look a bit odd, but it was carefully crafted
    /// to assist type inferencing and minimize spurious compiler errors. You can think of
    /// this function as taking a `<T as Lower<'a>>::Target`.
    pub fn new<'b, O>(value: O) -> Self
    where
        'b: 'a,
        O: Lower<'b, Target = T> + 'a,
    {
        let value = unsafe { transmute_copy(&*ManuallyDrop::new(value)) };
        Lowered {
            value,
            marker: PhantomData,
        }
    }

    /// Constructs a [`Lowered`] from its wrapped value.
    pub fn new_direct(value: <T as Lower<'a>>::Target) -> Self
    where
        T: Lower<'a>,
        <T as Lower<'a>>::Target: Sized,
    {
        let value = unsafe { transmute_copy(&*ManuallyDrop::new(value)) };
        Lowered {
            value,
            marker: PhantomData,
        }
    }

    /// Unpacks this [`Lowered`] wrapper.
    pub fn unwrap(lowered: Self) -> <T as Lower<'a>>::Target
    where
        T: Lower<'a>,
        <T as Lower<'a>>::Target: Sized,
    {
        unsafe { transmute_copy(&*ManuallyDrop::new(lowered.value)) }
    }
}

impl<'a, T: Lower<'a>> std::ops::Deref for Lowered<'a, T> {
    type Target = <T as Lower<'a>>::Target;
    fn deref(&self) -> &Self::Target {
        // Although we could use `lower_ref` to safely implement this, that would not be
        // technically correct. `value` is logically a `<T as Lower<'a>>::Target`, not a `T`, so
        // it doesn't make sense to lower it.
        unsafe { transmute_copy(&&self.value) }
    }
}

impl<'a, T: Lower<'a>> std::ops::DerefMut for Lowered<'a, T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        unsafe { transmute_copy(&&mut self.value) }
    }
}

unsafe impl<'a, 'b, T: 'a + 'b> Lower<'b> for Lowered<'a, T> {
    type Target = Lowered<'b, T>;
    fn lower_ref<'c>(&'c self) -> &'c Self::Target
    where
        'a: 'b,
        'b: 'c,
    {
        self
    }
}