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
use crate::HandleType;
use std::{fmt::*, hash::Hash};
use std::{hash::Hasher, marker::PhantomData};
/// Opaque handle type represented using integer values internally.
pub struct Handle<T, K = u32>
where
    T: ?Sized,
    K: HandleType,
    Self: Sized,
{
    pub value: K,
    /// Satisfy type check and drop check.
    _phantom: PhantomData<fn(*const T)>,
}

impl<T, K> Clone for Handle<T, K>
where
    T: ?Sized,
    K: HandleType,
{
    fn clone(&self) -> Self {
        Self {
            value: self.value,
            _phantom: PhantomData,
        }
    }
}

impl<T, K> Debug for Handle<T, K>
where
    K: HandleType + Debug,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.debug_struct(&format!("Handle<{}>", std::any::type_name::<T>()))
            .field("value", &self.value)
            .finish()
    }
}

impl<T, K> Copy for Handle<T, K>
where
    T: ?Sized,
    K: HandleType,
{
}

impl<T, K> From<K> for Handle<T, K>
where
    T: ?Sized,
    K: HandleType,
{
    fn from(value: K) -> Self {
        Self {
            value,
            _phantom: PhantomData,
        }
    }
}

impl<T, K> Eq for Handle<T, K>
where
    T: ?Sized,
    K: HandleType,
{
}
impl<T, K> PartialEq for Handle<T, K>
where
    T: ?Sized,
    K: HandleType,
{
    fn eq(&self, other: &Self) -> bool {
        self.value == other.value
    }
}

impl<T, K> Hash for Handle<T, K>
where
    T: ?Sized,
    K: HandleType,
{
    fn hash<H>(&self, h: &mut H)
    where
        H: Hasher,
    {
        self.value.hash(h);
    }
}

unsafe impl<T, K> Send for Handle<T, K>
where
    T: ?Sized,
    K: HandleType + Send,
{
}
unsafe impl<T, K> Sync for Handle<T, K>
where
    T: ?Sized,
    K: HandleType + Sync,
{
}