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
use core::mem::transmute_copy;

#[repr(transparent)]
pub struct Compact<T>
where
    T: From<Compact<T>>,
    Compact<T>: From<T>,
{
    _data: *const u8,
    phantom: core::marker::PhantomData<T>,
}

impl<T> Drop for Compact<T>
where
    T: From<Compact<T>>,
    Compact<T>: From<T>,
{
    fn drop(&mut self) {
        let this: Self = unsafe { transmute_copy(self) };
        let _ = T::from(this);
    }
}

impl<T: core::fmt::Debug> core::fmt::Debug for Compact<T>
where
    T: From<Compact<T>>,
    Compact<T>: From<T>,
{
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let this: Self = unsafe { transmute_copy(self) };
        T::from(this).fmt(f)
    }
}

impl<T: Clone> Clone for Compact<T>
where
    T: From<Compact<T>>,
    Compact<T>: From<T>,
{
    fn clone(&self) -> Self {
        let this: Self = unsafe { transmute_copy(self) };
        #[allow(clippy::redundant_clone)] // intended
        T::from(this).clone().into()
    }
}

impl<T: PartialEq> PartialEq for Compact<T>
where
    T: From<Compact<T>>,
    Compact<T>: From<T>,
{
    fn eq(&self, other: &Self) -> bool {
        let this: Self = unsafe { transmute_copy(self) };
        let that: Self = unsafe { transmute_copy(other) };
        T::from(this).eq(&T::from(that))
    }
}

impl<T: Eq> Eq for Compact<T>
where
    T: From<Compact<T>>,
    Compact<T>: From<T>,
{
}

impl<T: PartialOrd> PartialOrd for Compact<T>
where
    T: From<Compact<T>>,
    Compact<T>: From<T>,
{
    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
        let this: Self = unsafe { transmute_copy(self) };
        let that: Self = unsafe { transmute_copy(other) };
        T::from(this).partial_cmp(&T::from(that))
    }
}

impl<T: Ord> Ord for Compact<T>
where
    T: From<Compact<T>>,
    Compact<T>: From<T>,
{
    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
        let this: Self = unsafe { transmute_copy(self) };
        let that: Self = unsafe { transmute_copy(other) };
        T::from(this).cmp(&T::from(that))
    }
}

impl<T: core::hash::Hash> core::hash::Hash for Compact<T>
where
    T: From<Compact<T>>,
    Compact<T>: From<T>,
{
    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
        let this: Self = unsafe { transmute_copy(self) };
        T::from(this).hash(state);
    }
}