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
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> Compact<T>
where
T: From<Compact<T>>,
Compact<T>: From<T>,
{
pub fn inner(&self) -> *const u8 {
self.data
}
pub fn extract(self) -> T {
self.into()
}
unsafe fn extract_copy(&self) -> T {
let this: Self = unsafe { transmute_copy(self) };
T::from(this)
}
pub fn map_ref<U>(&self, func: impl FnOnce(&T) -> U) -> U {
let this = unsafe { self.extract_copy() };
let ret = func(&this);
std::mem::forget(this);
ret
}
pub fn map_ref_mut<U>(&mut self, func: impl FnOnce(&mut T) -> U) -> U {
let mut this = unsafe { self.extract_copy() };
let ret = func(&mut this);
std::mem::forget(this);
ret
}
}
impl<T> Compact<T>
where
T: From<Compact<T>> + Clone,
Compact<T>: From<T>,
{
pub fn extract_clone(&self) -> T {
self.map_ref(|this| this.clone())
}
}
impl<T> Drop for Compact<T>
where
T: From<Compact<T>>,
Compact<T>: From<T>,
{
fn drop(&mut self) {
let _ = unsafe { self.extract_copy() };
}
}
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 {
self.map_ref(|this| this.fmt(f))
}
}
impl<T: Clone> Clone for Compact<T>
where
T: From<Compact<T>>,
Compact<T>: From<T>,
{
fn clone(&self) -> Self {
self.map_ref(|this| 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 {
self.map_ref(|this| other.map_ref(|that| this.eq(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> {
self.map_ref(|this| other.map_ref(|that| this.partial_cmp(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 {
self.map_ref(|this| other.map_ref(|that| this.cmp(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) {
self.map_ref(|this| this.hash(state))
}
}