coproduct 0.4.1

Generic coproduct type with minimal memory footprint
Documentation
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
use crate::{
    count::Count,
    public_traits::*,
    union::{union_transmute, IndexedClone, IndexedDebug, IndexedEq},
    EmptyUnion, Union,
};
use core::mem::ManuallyDrop;

#[cfg(feature = "type_inequality_hack")]
use crate::Merge;

/// Leaks memory if the contents are not Copy.
///
/// Do not use directly. Its only purpose is to avoid duplicating methods
/// for Copy and non-Copy coproducts.
struct LeakingCoproduct<T> {
    tag: u32,
    union: T,
}

impl<X: IndexedDebug> core::fmt::Debug for LeakingCoproduct<X> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        unsafe { self.union.ifmt(f, self.tag) }
    }
}

impl<T: IndexedEq> PartialEq for LeakingCoproduct<T> {
    fn eq(&self, other: &Self) -> bool {
        self.tag == other.tag && unsafe { self.union.ieq(&other.union, self.tag) }
    }
}

pub trait At<I, X> {
    fn inject(x: X) -> Self;

    fn uninject(self) -> Result<X, Self::Pruned>;

    type Pruned;
}

impl<I, X, U> At<I, X> for LeakingCoproduct<U>
where
    U: UnionAt<I, X>,
    I: Count,
{
    fn inject(x: X) -> Self {
        Self {
            tag: I::count(),
            union: U::inject(x),
        }
    }

    fn uninject(self) -> Result<X, Self::Pruned> {
        if self.tag == I::count() {
            Ok(unsafe { self.union.take() })
        } else {
            let tag = if self.tag < I::count() {
                self.tag
            } else {
                self.tag - 1
            };
            Err(LeakingCoproduct {
                tag,
                union: unsafe { union_transmute(self.union) },
            })
        }
    }

    type Pruned = LeakingCoproduct<U::Pruned>;
}

/// Implemented on Coproducts that Source can be embedded into.
pub trait Embed<Target, Indices> {
    fn embed(self) -> Target;
}

impl<Res> Embed<Res, EmptyUnion> for LeakingCoproduct<EmptyUnion> {
    fn embed(self) -> Res {
        match self.union {}
    }
}

impl<Res, IH, IT, H, T> Embed<Res, Union<IH, IT>> for LeakingCoproduct<Union<H, T>>
where
    Res: At<IH, H>,
    IH: Count,
    LeakingCoproduct<T>: Embed<Res, IT>,
{
    fn embed(self) -> Res {
        match self.take_head() {
            Ok(x) => Res::inject(x),
            Err(x) => x.embed(),
        }
    }
}

pub trait Split<Selection, Indices>: Sized {
    type Remainder;

    /// Extract a subset of the possible types in a coproduct (or get the remaining possibilities)
    fn split(self) -> Result<Selection, Self::Remainder>;
}

impl<ToSplit, THead, TTail, NHead: Count, NTail, Rem>
    Split<LeakingCoproduct<Union<THead, TTail>>, Union<NHead, NTail>> for ToSplit
where
    ToSplit: At<NHead, THead, Pruned = Rem>,
    Rem: Split<LeakingCoproduct<TTail>, NTail>,
{
    type Remainder = <Rem as Split<LeakingCoproduct<TTail>, NTail>>::Remainder;

    fn split(self) -> Result<LeakingCoproduct<Union<THead, TTail>>, Self::Remainder> {
        match self.uninject() {
            Ok(found) => Ok(LeakingCoproduct::inject(found)),
            Err(rest) => rest.split().map(|subset| LeakingCoproduct {
                tag: subset.tag + 1,
                union: Union {
                    tail: ManuallyDrop::new(subset.union),
                },
            }),
        }
    }
}

impl<ToSplit> Split<LeakingCoproduct<EmptyUnion>, EmptyUnion> for ToSplit {
    type Remainder = Self;

    #[inline(always)]
    fn split(self) -> Result<LeakingCoproduct<EmptyUnion>, Self::Remainder> {
        Err(self)
    }
}

impl<H, T> LeakingCoproduct<Union<H, T>> {
    fn take_head(self) -> Result<H, LeakingCoproduct<T>> {
        if self.tag == 0 {
            Ok(ManuallyDrop::into_inner(unsafe { self.union.head }))
        } else {
            Err(LeakingCoproduct {
                tag: self.tag - 1,
                union: ManuallyDrop::into_inner(unsafe { self.union.tail }),
            })
        }
    }
}

/// Unwrapping is a bit more difficult for Coproduct than for CopyableCoproduct,
/// so unwrap needs to be statically dispatched.
trait CoproductWrapper<T> {
    // Returning a LeakingCoproduct doesn't cause leaks as it is private,
    // which guarantees that library users won't get their hands on it.
    // It will either be wrapped again or destroyed by the take method.
    fn unwrap(self) -> LeakingCoproduct<T>;
}

macro_rules! define_methods {
    ($type: ident, $trait: ident) => {
        impl<I, X, U: $trait> At<I, X> for $type<U>
        where
            U: UnionAt<I, X>,
            U::Pruned: $trait,
            I: Count,
        {
            fn inject(x: X) -> Self {
                $type(LeakingCoproduct::inject(x))
            }

            fn uninject(self) -> Result<X, Self::Pruned> {
                self.unwrap().uninject().map_err($type)
            }

            type Pruned = $type<U::Pruned>;
        }

        impl<T: $trait> $type<T> {
            /// Create a new coproduct that holds the given value.
            pub fn inject<I, X>(x: X) -> Self
            where
                Self: At<I, X>,
            {
                <Self as At<I, X>>::inject(x)
            }

            /// If the coproduct contains an X, returns that value.
            /// Otherwise, returns the same coproduct, refined to indicate
            /// that it cannot contain X.
            ///
            /// This method can be used to do exhaustive case analysis on a
            /// coproduct:
            ///  ```
            /// # use coproduct::Coproduct;
            /// # struct Cat;
            /// # #[derive(Debug, PartialEq)]
            /// # struct Dog(&'static str);
            /// let animal: Coproduct!(Cat, Dog) = Coproduct::inject(Dog("Sparky"));
            ///
            /// let non_cat = match animal.uninject::<_, Cat>() {
            ///     Ok(_) => unreachable!(),
            ///     Err(non_cat) => non_cat,
            /// };
            /// match non_cat.uninject::<_, Dog>() {
            ///     Ok(dog) => assert_eq!(dog, Dog("Sparky")),
            ///     Err(non_animal) => {
            ///         // There are animals other than cats and dogs? Absurd!
            ///         non_animal.ex_falso()
            ///     }
            /// }
            ///  ```
            pub fn uninject<I, X>(self) -> Result<X, <Self as At<I, X>>::Pruned>
            where
                Self: At<I, X>,
            {
                <Self as At<I, X>>::uninject(self)
            }

            /// Convert a coproduct into another with more variants.
            pub fn embed<U, I>(self) -> U
            where
                Self: Embed<U, I>,
            {
                <Self as Embed<U, I>>::embed(self)
            }

            /// Split a coproduct into two disjoint sets. Returns the active one.
            pub fn split<U, I>(self) -> Result<U, <Self as Split<U, I>>::Remainder>
            where
                Self: Split<U, I>,
            {
                <Self as Split<U, I>>::split(self)
            }
        }

        impl<H, T> $type<Union<H, T>>
        where
            Union<H, T>: $trait,
            T: $trait,
        {
            /// Try to take the first variant out. On failure, return the
            /// remaining variants.
            pub fn take_head(self) -> Result<H, $type<T>> {
                self.unwrap().take_head().map_err($type)
            }
        }

        impl $type<EmptyUnion> {
            /// From falsehood, anything follows.
            ///
            /// Given a coproduct that cannot contain anything,
            /// just call this method.
            pub fn ex_falso<T>(&self) -> T {
                match self.0.union {}
            }
        }

        impl<T: $trait, I, U: $trait> Embed<$type<T>, I> for $type<U>
        where
            LeakingCoproduct<U>: Embed<LeakingCoproduct<T>, I>,
        {
            fn embed(self) -> $type<T> {
                $type(self.unwrap().embed())
            }
        }

        impl<T: $trait, I, U: $trait, Rem> Split<$type<T>, I> for $type<U>
        where
            LeakingCoproduct<U>: Split<LeakingCoproduct<T>, I, Remainder = LeakingCoproduct<Rem>>,
            Rem: $trait,
        {
            type Remainder = $type<Rem>;

            fn split(self) -> Result<$type<T>, $type<Rem>> {
                self.unwrap().split().map($type).map_err($type)
            }
        }

        #[cfg(feature = "type_inequality_hack")]
        impl<T: $trait, U: $trait, Ds> Merge<$type<T>, Ds> for $type<U>
        where
            U: Merge<T, Ds>,
            U::Merged: $trait,
        {
            type Merged = $type<U::Merged>;
        }

        impl<T> PartialEq for $type<T>
        where
            T: IndexedEq + $trait,
        {
            fn eq(&self, other: &Self) -> bool {
                self.0 == other.0
            }
        }

        impl<T: IndexedDebug + $trait> core::fmt::Debug for $type<T> {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                f.debug_tuple(stringify!($type)).field(&self.0).finish()
            }
        }
    };
}

/// A coproduct that can only hold copyable types.
#[derive(Copy, Clone)]
pub struct CopyableCoproduct<T>(LeakingCoproduct<T>)
where
    T: Copy;

impl<T: Copy> Clone for LeakingCoproduct<T> {
    fn clone(&self) -> Self {
        *self
    }
}
impl<T: Copy> Copy for LeakingCoproduct<T> {}

impl<T: Copy> CoproductWrapper<T> for CopyableCoproduct<T> {
    fn unwrap(self) -> LeakingCoproduct<T> {
        self.0
    }
}

define_methods!(CopyableCoproduct, Copy);

/// Builds a [CopyableCoproduct] that can hold the types given as arguments.
#[macro_export]
macro_rules! CopyableCoproduct {
    ( $( $t:ty ),+ ) => (
        $crate::CopyableCoproduct<$crate::MkUnion!( $( $t ),+ )>
    );
}

/// Can hold any type. You should use [CopyableCoproduct]
/// if your types are copyable.
pub struct Coproduct<T: IndexedDrop>(LeakingCoproduct<T>);

impl<T: IndexedClone + IndexedDrop> Clone for Coproduct<T> {
    fn clone(&self) -> Self {
        Self(LeakingCoproduct {
            tag: self.0.tag,
            union: unsafe { self.0.union.iclone(self.0.tag) },
        })
    }
}

impl<T: IndexedDrop> Drop for Coproduct<T> {
    fn drop(&mut self) {
        unsafe { self.0.union.idrop(self.0.tag) }
    }
}

impl<T: IndexedDrop> CoproductWrapper<T> for Coproduct<T> {
    fn unwrap(self) -> LeakingCoproduct<T> {
        // As Coproduct is Drop, moving out of it isn't possible,
        // which necessitates ptr::read.
        // self needs to be wrapped in ManuallyDrop because otherwise it would
        // be dropped here!
        let me = core::mem::ManuallyDrop::new(self);
        unsafe { core::ptr::read(&me.0) }
    }
}

define_methods!(Coproduct, IndexedDrop);

/// Create a coproduct containing X.
/// This standalone function more convenient than the method or trait when
/// writing very abstracted code.
pub fn inject<I, X, C>(x: X) -> C
where
    C: At<I, X>,
{
    C::inject(x)
}

/// Builds a [Coproduct] that can hold the types given as arguments.
#[macro_export]
macro_rules! Coproduct {
    ( $( $t:ty ),+ ) => (
        $crate::Coproduct<$crate::MkUnion!( $( $t ),+ )>
    );
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::union::*;

    #[test]
    fn inject_uninject() {
        let c = Coproduct::<Union<u8, EmptyUnion>>::inject(47);
        assert_eq!(c.uninject(), Ok(47));
    }

    #[test]
    fn leak_check() {
        // This produces a memory leak detected by Miri if Drop doesn't work
        let _: Coproduct!(String) = Coproduct::inject("hello".into());
    }

    #[test]
    fn embed_split() {
        let c: Coproduct!(u8, u16) = Coproduct::inject(42u16);
        let widened: Coproduct!(u8, u16, u32, u64) = c.clone().embed();
        assert_eq!(Ok(c), widened.split())
    }
}