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
use core::marker::PhantomData;
use core::mem::ManuallyDrop;

use crate::{CompactBorrow, CompactBorrowMut};

/// Compact representation of `T`. Only one-pointer wide.
///
/// It behaves like `T` for `Drop`, `Clone`, `Hash`, `Eq`, `Ord`, ...
#[repr(transparent)]
pub struct Compact<T>
where
    T: From<Compact<T>>,
    Compact<T>: From<T>,
{
    data: *const u8,
    marker: PhantomData<T>,
}

impl<T> Compact<T>
where
    T: From<Compact<T>>,
    Compact<T>: From<T>,
{
    /// Returns the underlying raw data.
    #[inline]
    pub fn as_raw_data(&self) -> *const u8 {
        self.data
    }

    /// Alias of `T::from(self)`.
    #[inline]
    pub fn extract(self) -> T {
        self.into()
    }

    /// Maps a `&T` to `U` by applying a function to a temporarily created
    /// `T` value.
    ///
    /// Since the value is temporary, you cannot take references to it out
    /// from this function.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[cfg(feature = "alloc")] {
    /// use enum_ptr::{Compact, EnumPtr};
    ///
    /// #[derive(EnumPtr, Debug)]
    /// #[repr(C, usize)]
    /// enum Foo {
    ///     A(Box<i32>),
    ///     B(Box<u32>),
    /// }
    ///
    /// let mut foo: Compact<_> = Foo::A(Box::new(1)).into();
    /// let result = foo.map_ref(|f| match f {
    ///     Foo::A(r) => **r,
    ///     _ => unreachable!(),
    /// });
    /// assert_eq!(result, 1);
    /// # }
    /// ```
    #[inline]
    pub fn map_ref<U>(&self, f: impl FnOnce(&T) -> U) -> U {
        f(&ManuallyDrop::new(T::from(Self { ..*self })))
    }

    /// Maps a `&mut T` to `U` by applying a function to a temporarily created
    /// `T` value.
    ///
    /// Since the value is temporary, you cannot take references to it out
    /// from this function.
    ///
    /// # Safety
    ///
    /// See issue [#3](https://github.com/QuarticCat/enum-ptr/issues/3).
    ///
    /// # Examples
    ///
    /// ```
    /// # #[cfg(feature = "alloc")] {
    /// use enum_ptr::{Compact, EnumPtr};
    ///
    /// #[derive(EnumPtr, Debug, PartialEq, Eq)]
    /// #[repr(C, usize)]
    /// enum Foo {
    ///     A(Box<i32>),
    ///     B(Box<u32>),
    /// }
    ///
    /// let mut foo: Compact<_> = Foo::A(Box::new(1)).into();
    /// unsafe {
    ///     foo.map_mut(|f| match f {
    ///         Foo::A(r) => **r = 2,
    ///         _ => unreachable!(),
    ///     });
    /// }
    /// assert_eq!(foo.extract(), Foo::A(Box::new(2)));
    /// # }
    /// ```
    #[inline]
    pub unsafe fn map_mut<U>(&mut self, f: impl FnOnce(&mut T) -> U) -> U {
        f(&mut ManuallyDrop::new(T::from(Self { ..*self })))
    }

    // /// Replaces the wrapped value with a new one computed from f, returning
    // /// the old value, without deinitializing either one.
    // ///
    // /// # Examples
    // ///
    // /// ```
    // /// # #[cfg(feature = "alloc")] {
    // /// use enum_ptr::{Compact, EnumPtr};
    // ///
    // /// #[derive(EnumPtr, Debug, PartialEq, Eq)]
    // /// #[repr(C, usize)]
    // /// enum Foo {
    // ///     A(Box<i32>),
    // ///     B(Box<u32>),
    // /// }
    // ///
    // /// let mut foo: Compact<_> = Foo::A(Box::new(1)).into();
    // /// let old = foo.replace_with(|_| Foo::B(Box::new(2)));
    // /// assert_eq!(old, Foo::A(Box::new(1)));
    // /// assert_eq!(foo.extract(), Foo::B(Box::new(2)));
    // /// # }
    // /// ```
    // #[inline]
    // pub fn replace_with(&mut self, f: impl FnOnce(&mut T) -> T) -> T {
    //     let mut old = T::from(Self { ..*self });
    //     let new = f(&mut old);
    //     self.data = unsafe { crate::compact(new) };
    //     old
    // }
}

impl<T> Compact<T>
where
    T: From<Compact<T>> + CompactBorrow,
    Compact<T>: From<T>,
{
    /// Returns a reference type that acts like `&T`.
    ///
    /// Check [`EnumPtr`](crate::EnumPtr) for more details.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[cfg(feature = "alloc")] {
    /// use enum_ptr::{Compact, EnumPtr};
    ///
    /// #[derive(EnumPtr, Debug)]
    /// #[enum_ptr(borrow)] // required
    /// #[repr(C, usize)]
    /// enum Foo {               // enum FooRef<'enum_ptr> {
    ///     A(Box<i32>),         //     A(&'enum_ptr i32),
    ///     B(Option<Box<u32>>), //     B(Option<&'enum_ptr u32>),
    /// }                        // }
    ///
    /// let foo: Compact<_> = Foo::A(Box::new(1)).into();
    /// match foo.borrow() {
    ///     FooRef::A(inner) => assert_eq!(inner, &1),
    ///     _ => unreachable!(),
    /// }
    /// # }
    /// ```
    #[inline]
    pub fn borrow(&self) -> <T as CompactBorrow>::Target<'_> {
        CompactBorrow::borrow(self)
    }
}

impl<T> Compact<T>
where
    T: From<Compact<T>> + CompactBorrowMut,
    Compact<T>: From<T>,
{
    /// Returns a reference type that acts like `&mut T`.
    ///
    /// Check [`EnumPtr`](crate::EnumPtr) for more details.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[cfg(feature = "alloc")] {
    /// use enum_ptr::{Compact, EnumPtr};
    ///
    /// #[derive(EnumPtr, Debug)]
    /// #[enum_ptr(borrow_mut)] // required
    /// #[repr(C, usize)]
    /// enum Foo {               // enum FooRefMut<'enum_ptr> {
    ///     A(Box<i32>),         //     A(&'enum_ptr mut i32),
    ///     B(Option<Box<u32>>), //     B(Option<&'enum_ptr mut u32>),
    /// }                        // }
    ///
    /// let mut foo: Compact<_> = Foo::A(Box::new(1)).into();
    /// match foo.borrow_mut() {
    ///     FooRefMut::A(inner) => assert_eq!(inner, &mut 1),
    ///     _ => unreachable!(),
    /// }
    /// # }
    /// ```
    #[inline]
    pub fn borrow_mut(&mut self) -> <T as CompactBorrowMut>::Target<'_> {
        CompactBorrowMut::borrow_mut(self)
    }
}

impl<T> Drop for Compact<T>
where
    T: From<Compact<T>>,
    Compact<T>: From<T>,
{
    #[inline]
    fn drop(&mut self) {
        drop(T::from(Self { ..*self }));
    }
}

impl<T> Clone for Compact<T>
where
    T: From<Compact<T>> + Clone,
    Compact<T>: From<T>,
{
    #[inline]
    fn clone(&self) -> Self {
        self.map_ref(|this| this.clone().into())
    }
}

impl<T> PartialEq for Compact<T>
where
    T: From<Compact<T>> + PartialEq,
    Compact<T>: From<T>,
{
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.map_ref(|this| other.map_ref(|that| this.eq(that)))
    }
}

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

impl<T> PartialOrd for Compact<T>
where
    T: From<Compact<T>> + PartialOrd,
    Compact<T>: From<T>,
{
    #[inline]
    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 for Compact<T>
where
    T: From<Compact<T>> + Ord,
    Compact<T>: From<T>,
{
    #[inline]
    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
        self.map_ref(|this| other.map_ref(|that| this.cmp(that)))
    }
}

impl<T> core::fmt::Debug for Compact<T>
where
    T: From<Compact<T>> + core::fmt::Debug,
    Compact<T>: From<T>,
{
    #[inline]
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        self.map_ref(|this| this.fmt(f))
    }
}

impl<T> Default for Compact<T>
where
    T: From<Compact<T>> + Default,
    Compact<T>: From<T>,
{
    fn default() -> Self {
        T::default().into()
    }
}

impl<T> core::hash::Hash for Compact<T>
where
    T: From<Compact<T>> + core::hash::Hash,
    Compact<T>: From<T>,
{
    #[inline]
    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
        self.map_ref(|this| this.hash(state))
    }
}

unsafe impl<T> Send for Compact<T>
where
    T: From<Compact<T>> + Send,
    Compact<T>: From<T>,
{
}

unsafe impl<T> Sync for Compact<T>
where
    T: From<Compact<T>> + Sync,
    Compact<T>: From<T>,
{
}