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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
// NB: Last updated for Rust 1.40 parity. All impls are in rustdoc gutter order.
// Forwarding impls are provided for impls provided on Box.

#![no_std]
#[cfg(feature = "alloc")]
extern crate alloc;

#[cfg(feature = "alloc")]
use alloc::{boxed::Box, rc::Rc, sync::Arc};
use core::{
    cmp::Ordering,
    fmt::{self, Debug, Display, Formatter, Pointer},
    hash::{Hash, Hasher},
    iter::FusedIterator,
    marker::PhantomData,
    mem::ManuallyDrop,
    ops::{Deref, DerefMut},
    ptr,
};

/// A thin, type-erased pointer.
pub type ErasedPtr = ptr::NonNull<Erased>;
pub(crate) use priv_in_pub::Erased;

mod priv_in_pub {
    pub struct Erased; // extern type Erased
}

/// A (smart) pointer type that can be type-erased (making a thin pointer).
///
/// When implementing this trait,
/// you should implement it for all `Erasable` pointee types.
pub unsafe trait ErasablePtr {
    /// Turn this erasable pointer into an erased pointer.
    ///
    /// To retrieve the original pointer, use `unerase`.
    fn erase(this: Self) -> ErasedPtr;
    /// Unerase this erased pointer.
    ///
    /// # Safety
    ///
    /// The erased pointer must have been created by `erase`.
    unsafe fn unerase(this: ErasedPtr) -> Self;
}

/// A pointee type that can be type-erased (making a thin pointer).
pub unsafe trait Erasable {
    /// Turn this erasable pointer into an erased pointer.
    ///
    /// To retreive the original pointer, use `unerase`.
    fn erase(this: ptr::NonNull<Self>) -> ErasedPtr { erase(this) }
    /// Unerase this erased pointer.
    ///
    /// # Safety
    ///
    /// The erased pointer must have been created by `erase`.
    unsafe fn unerase(this: ErasedPtr) -> ptr::NonNull<Self>;
}

/// Erase a pointer.
pub fn erase<T: ?Sized>(ptr: ptr::NonNull<T>) -> ErasedPtr {
    unsafe { ptr::NonNull::new_unchecked(ptr.as_ptr() as *mut Erased) }
}

/// Wrapper struct to create thin pointer types.
pub struct Thin<P: ErasablePtr> {
    ptr: ErasedPtr,
    marker: PhantomData<P>,
}

unsafe impl<P: ErasablePtr> Send for Thin<P> where P: Send {}
unsafe impl<P: ErasablePtr> Sync for Thin<P> where P: Sync {}

impl<P: ErasablePtr> From<P> for Thin<P> {
    fn from(this: P) -> Self {
        Thin {
            ptr: P::erase(this),
            marker: PhantomData,
        }
    }
}

impl<P: ErasablePtr> Thin<P> {
    fn inner(this: &Self) -> ManuallyDrop<P> {
        unsafe { ManuallyDrop::new(P::unerase(this.ptr)) }
    }

    // noinspection RsSelfConvention
    // `From` can't be impl'd because it's an impl on an uncovered type
    // `Into` can't be impl'd because it theoretically conflicts with the reflexive impl
    /// Extract the wrapped pointer.
    pub fn into_inner(this: Self) -> P {
        unsafe { P::unerase(ManuallyDrop::new(this).ptr) }
    }

    /// Run a closure with a borrow of the real pointer.
    pub fn with<F, T>(this: &Self, f: F) -> T
    where
        F: FnOnce(&P) -> T,
    {
        f(&Thin::inner(this))
    }

    /// Run a closure with a mutable borrow of the real pointer.
    pub fn with_mut<F, T>(this: &mut Self, f: F) -> T
    where
        F: FnOnce(&mut P) -> T,
    {
        f(&mut Thin::inner(this))
    }
}

impl<P: ErasablePtr> Drop for Thin<P> {
    fn drop(&mut self) {
        unsafe { P::unerase(self.ptr) };
    }
}

// ~~~ Box<T> like impls ~~~ //

impl<P: ErasablePtr, T: ?Sized> AsMut<T> for Thin<P>
where
    P: AsMut<T>,
{
    fn as_mut(&mut self) -> &mut T {
        unsafe { Thin::with_mut(self, |p| erase_lt_mut(p.as_mut())) }
    }
}

impl<P: ErasablePtr, T: ?Sized> AsRef<T> for Thin<P>
where
    P: AsRef<T>,
{
    fn as_ref(&self) -> &T {
        unsafe { Thin::with(self, |p| erase_lt(p.as_ref())) }
    }
}

// BorrowMut conflicts with reflexive impl
// CoerceUnsized is unstable

impl<P: ErasablePtr> Debug for Thin<P>
where
    P: Debug,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        Thin::with(self, |p| p.fmt(f))
    }
}

impl<P: ErasablePtr> Deref for Thin<P>
where
    P: Deref,
{
    type Target = P::Target;
    fn deref(&self) -> &P::Target {
        unsafe { Thin::with(self, |p| erase_lt(p)) }
    }
}

impl<P: ErasablePtr> DerefMut for Thin<P>
where
    P: DerefMut,
{
    fn deref_mut(&mut self) -> &mut P::Target {
        unsafe { Thin::with_mut(self, |p| erase_lt_mut(p)) }
    }
}

// impl DispatchFromDyn

impl<P: ErasablePtr> Display for Thin<P>
where
    P: Display,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        Thin::with(self, |p| p.fmt(f))
    }
}

impl<P: ErasablePtr> DoubleEndedIterator for Thin<P>
where
    P: DoubleEndedIterator,
{
    fn next_back(&mut self) -> Option<Self::Item> {
        Thin::with_mut(self, |p| p.next_back())
    }

    fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
        Thin::with_mut(self, |p| p.nth_back(n))
    }
}

impl<P: ErasablePtr> Eq for Thin<P> where P: Eq {}

impl<P: ErasablePtr> ExactSizeIterator for Thin<P> where P: ExactSizeIterator {}

// impl Fn, FnMut, FnOnce

impl<P: ErasablePtr> FusedIterator for Thin<P> where P: FusedIterator {}

// Skip Future; not sure of the exact desired semantics here

// impl Generator

impl<P: ErasablePtr> Hash for Thin<P>
where
    P: Hash,
{
    fn hash<H: Hasher>(&self, state: &mut H) {
        Thin::with(self, |p| p.hash(state))
    }
}

impl<P: ErasablePtr> Hasher for Thin<P>
where
    P: Hasher,
{
    fn finish(&self) -> u64 {
        Thin::with(self, |p| p.finish())
    }

    fn write(&mut self, bytes: &[u8]) {
        Thin::with_mut(self, |p| p.write(bytes))
    }

    fn write_u8(&mut self, i: u8) {
        Thin::with_mut(self, |p| p.write_u8(i))
    }

    fn write_u16(&mut self, i: u16) {
        Thin::with_mut(self, |p| p.write_u16(i))
    }

    fn write_u32(&mut self, i: u32) {
        Thin::with_mut(self, |p| p.write_u32(i))
    }

    fn write_u64(&mut self, i: u64) {
        Thin::with_mut(self, |p| p.write_u64(i))
    }

    fn write_u128(&mut self, i: u128) {
        Thin::with_mut(self, |p| p.write_u128(i))
    }

    fn write_usize(&mut self, i: usize) {
        Thin::with_mut(self, |p| p.write_usize(i))
    }

    fn write_i8(&mut self, i: i8) {
        Thin::with_mut(self, |p| p.write_i8(i))
    }

    fn write_i16(&mut self, i: i16) {
        Thin::with_mut(self, |p| p.write_i16(i))
    }

    fn write_i32(&mut self, i: i32) {
        Thin::with_mut(self, |p| p.write_i32(i))
    }

    fn write_i64(&mut self, i: i64) {
        Thin::with_mut(self, |p| p.write_i64(i))
    }

    fn write_i128(&mut self, i: i128) {
        Thin::with_mut(self, |p| p.write_i128(i))
    }

    fn write_isize(&mut self, i: isize) {
        Thin::with_mut(self, |p| p.write_isize(i))
    }
}

impl<P: ErasablePtr> Iterator for Thin<P>
where
    P: Iterator,
{
    type Item = P::Item;

    fn next(&mut self) -> Option<Self::Item> {
        Thin::with_mut(self, |p| p.next())
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        Thin::with(self, |p| p.size_hint())
    }

    fn nth(&mut self, n: usize) -> Option<Self::Item> {
        Thin::with_mut(self, |p| p.nth(n))
    }
}

impl<P: ErasablePtr> Ord for Thin<P>
where
    P: Ord,
{
    fn cmp(&self, other: &Thin<P>) -> Ordering {
        Thin::with(self, |p| Thin::with(other, |other| p.cmp(other)))
    }
}

impl<P: ErasablePtr> PartialEq for Thin<P>
where
    P: PartialEq,
{
    fn eq(&self, other: &Thin<P>) -> bool {
        Thin::with(self, |p| Thin::with(other, |other| p.eq(other)))
    }
}

impl<P: ErasablePtr> PartialOrd for Thin<P>
where
    P: PartialOrd,
{
    fn partial_cmp(&self, other: &Thin<P>) -> Option<Ordering> {
        Thin::with(self, |p| Thin::with(other, |other| p.partial_cmp(other)))
    }
}

impl<P: ErasablePtr> Pointer for Thin<P>
where
    P: Pointer,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        Thin::with(self, |p| p.fmt(f))
    }
}

// ~~~ impl Eraseable ~~~ //

unsafe impl<T> Erasable for T {
    unsafe fn unerase(this: ErasedPtr) -> ptr::NonNull<T> {
        this.cast()
    }
}

unsafe impl<T: ?Sized> ErasablePtr for ptr::NonNull<T>
where
    T: Erasable,
{
    fn erase(this: Self) -> ErasedPtr {
        T::erase(this)
    }

    unsafe fn unerase(this: ErasedPtr) -> Self {
        T::unerase(this)
    }
}

unsafe impl<T: ?Sized> ErasablePtr for &'_ T
where
    T: Erasable,
{
    fn erase(this: Self) -> ErasedPtr {
        T::erase(this.into())
    }

    unsafe fn unerase(this: ErasedPtr) -> Self {
        &*T::unerase(this).as_ptr()
    }
}

unsafe impl<T: ?Sized> ErasablePtr for &'_ mut T
where
    T: Erasable,
{
    fn erase(this: Self) -> ErasedPtr {
        T::erase(this.into())
    }

    unsafe fn unerase(this: ErasedPtr) -> Self {
        &mut *T::unerase(this).as_ptr()
    }
}

#[cfg(feature = "alloc")]
macro_rules! impl_erasable {
    (for<$T:ident> $($ty:ty),* $(,)?) => {$(
        unsafe impl<$T: ?Sized> ErasablePtr for $ty
        where
            T: Erasable,
        {
            fn erase(this: Self) -> ErasedPtr {
                let ptr = unsafe { ptr::NonNull::new_unchecked(<$ty>::into_raw(this) as *mut _) };
                T::erase(ptr)
            }

            unsafe fn unerase(this: ErasedPtr) -> Self {
                Self::from_raw(T::unerase(this).as_ptr())
            }
        }
    )*}
}

// Weak raw isn't stable yet
#[cfg(feature = "alloc")]
#[rustfmt::skip] // rust-lang/rustfmt#3929
impl_erasable!(for<T>
    Box<T>,
    Arc<T>,
    // sync::Weak<T>,
    Rc<T>,
    // rc::Weak<T>
);

unsafe fn erase_lt<'a, 'b, T: ?Sized>(this: &'a T) -> &'b T {
    &*(this as *const T)
}

unsafe fn erase_lt_mut<'a, 'b, T: ?Sized>(this: &'a mut T) -> &'b mut T {
    &mut *(this as *mut T)
}