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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
//! Hereditarily finite sets [`Set`].

use crate::prelude::*;

/// A [hereditarily finite set](https://en.wikipedia.org/wiki/Hereditarily_finite_set), implemented
/// as a [`Mset`] where each multiset has no duplicate elements.
///
/// ## Invariants
///
/// These invariants should hold for any [`Set`]. **Unsafe code performs optimizations contingent on
/// these.**
///
/// - Every two elements in a [`Set`] must be distinct.
/// - Any element in a [`Set`] must be a valid [`Set`] also.
#[derive(Clone, Default, AsRef, Display, Into, PartialEq, Eq, PartialOrd)]
#[repr(transparent)]
pub struct Set(Mset);

// -------------------- Basic traits -------------------- //

impl From<Set> for Vec<Set> {
    fn from(set: Set) -> Self {
        // Safety: elements of `Set` are valid for `Set`.
        unsafe { Mset::cast_vec(set.0 .0) }
    }
}

/// Succintly writes a set as is stored in memory.
impl Debug for Set {
    fn fmt(&self, f: &mut Formatter) -> FmtResult {
        write!(f, "{:?}", self.mset())
    }
}

impl FromStr for Set {
    type Err = SetError;

    fn from_str(s: &str) -> Result<Self, SetError> {
        s.parse().map(Mset::into_set)
    }
}

// -------------------- Casting -------------------- //

/// Orders and deduplicates a set based on the corresponding keys.
///
/// The first buffer is an intermediary buffer for calculations. It must be empty when this function
/// is called, but is emptied at the end of it.
///
/// The second buffer is cleared within the function. At its output, it contains the set of
/// deduplicated keys with their indices in the original set.
///
/// ## Safety
///
/// Both `set` and `keys` must have the same number of elements.
unsafe fn dedup_by<T: Default, U: Ord + Copy>(
    set: &mut Vec<T>,
    keys: &[U],
    buf: &mut Vec<T>,
    buf_pairs: &mut Vec<(usize, U)>,
) {
    // Deduplicate set of key-value pairs.
    buf_pairs.clear();
    buf_pairs.extend(keys.iter().copied().enumerate());
    buf_pairs.sort_unstable_by_key(|(_, k)| *k);
    buf_pairs.dedup_by_key(|(_, k)| *k);

    // Add ordered entries to secondary buffer.
    for (i, _) in &*buf_pairs {
        let el = mem::take(set.get_unchecked_mut(*i));
        buf.push(el);
    }

    // Now put them in place.
    set.clear();
    set.append(buf);
}

impl Mset {
    /// Flattens a multiset into a set hereditarily.
    #[must_use]
    pub fn into_set(mut self) -> Set {
        let levels = Levels::new_mut(&mut self);
        let mut buf = Vec::new();
        let mut buf_pairs = Vec::new();

        // Safety: Since we're modifying sets from bottom to top, we can ensure our pointers are
        // still valid, as is our cardinality function.
        unsafe {
            levels.mod_ahu_gen(
                0,
                BTreeMap::new(),
                |sets, slice, &set| {
                    // Deduplicate the set.
                    dedup_by(&mut (*set).0, slice, &mut buf, &mut buf_pairs);
                    let children: SmallVec<_> = buf_pairs.iter().map(|(_, k)| *k).collect();
                    Some(btree_index(sets, children))
                },
                BTreeMap::clear,
            );
        }

        Set(self)
    }

    /// Checks whether the multiset is in fact a set. This property is checked hereditarily.
    ///
    /// See also [`Self::into_set`].
    #[must_use]
    pub fn is_set(&self) -> bool {
        Levels::new(self)
            .mod_ahu(
                1,
                BTreeMap::new(),
                |sets, slice, _| {
                    // Find duplicate elements.
                    slice.sort_unstable();
                    if has_consecutive(slice) {
                        return None;
                    }

                    let children: SmallVec<_> = slice.iter().copied().collect();
                    Some(btree_index(sets, children))
                },
                BTreeMap::clear,
            )
            .is_some()
    }

    /// Transmutes an [`Mset`] into a [`Set`], first checking the type invariants.
    #[must_use]
    pub fn into_set_checked(self) -> Option<Set> {
        if self.is_set() {
            Some(Set(self))
        } else {
            None
        }
    }

    /// Transmutes an [`Mset`] into a [`Set`] **without** checking the type invariants.
    ///
    /// ## Safety
    ///
    /// You must guarantee that the [`Mset`] satisfies the type invariants for [`Set`].
    #[must_use]
    pub unsafe fn into_set_unchecked(self) -> Set {
        Set(self)
    }

    /// Transmutes a [`Mset`] reference into a [`Set`] reference, first checking the type
    /// invariants.
    #[must_use]
    pub fn as_set_checked(&self) -> Option<&Set> {
        if self.is_set() {
            // Safety: both types have the same layout, and we just checked the invariant.
            Some(unsafe { &*(ptr::from_ref(self).cast()) })
        } else {
            None
        }
    }

    /// Transmutes a [`Mset`] reference into a [`Set`] reference **without** checking the type
    /// invariants.
    ///
    /// ## Safety
    ///
    /// You must guarantee that the [`Mset`] satisfies the type invariants for [`Set`].
    #[must_use]
    pub unsafe fn as_set_unchecked(&self) -> &Set {
        self.as_set_checked().unwrap_unchecked()
    }

    /// Transmutes a mutable [`Mset`] reference into a [`Set`] reference, first checking the type
    /// invariants.
    #[must_use]
    pub fn as_set_mut_checked(&mut self) -> Option<&mut Set> {
        if self.is_set() {
            // Safety: both types have the same layout, and we just checked the invariant.
            Some(unsafe { &mut *(ptr::from_mut(self).cast()) })
        } else {
            None
        }
    }

    /// Transmutes a mutable [`Mset`] reference into a [`Set`] reference **without** checking the
    /// type invariants.
    ///
    /// ## Safety
    ///
    /// You must guarantee that the [`Mset`] satisfies the type invariants for [`Set`].
    #[must_use]
    pub unsafe fn as_set_mut_unchecked(&mut self) -> &mut Set {
        self.as_set_mut_checked().unwrap_unchecked()
    }

    /// Converts `Vec<Mset>` into `Vec<Set>`.
    ///
    /// ## Safety
    ///
    /// You must guarantee that the [`Mset`] satisfy the type invariants for [`Set`].
    #[must_use]
    pub unsafe fn cast_vec(vec: Vec<Self>) -> Vec<Set> {
        crate::transmute_vec(vec)
    }
}

impl Set {
    /// Converts `Vec<Set>` into `Vec<Mset>`.
    #[must_use]
    pub fn cast_vec(vec: Vec<Self>) -> Vec<Mset> {
        // Safety: `Set` and `Mset` have the same layout.
        unsafe { crate::transmute_vec(vec) }
    }
}

// -------------------- Iterators -------------------- //

/// An auxiliary type to map [`Mset`] to [`Set`] within iterators.
///
/// ## Invariants
///
/// This can only be used with iterators coming from a [`Set`]. Note that this is guaranteed by all
/// of the public methods that generate this type.
pub struct Cast<I>(I);

impl Iterator for Cast<std::vec::IntoIter<Mset>> {
    type Item = Set;

    fn next(&mut self) -> Option<Self::Item> {
        self.0.next().map(Set)
    }
}

impl<'a> Iterator for Cast<slice::Iter<'a, Mset>> {
    type Item = &'a Set;

    fn next(&mut self) -> Option<Self::Item> {
        // Safety: we're iterating over a set.
        self.0.next().map(|s| unsafe { s.as_set_unchecked() })
    }
}

impl<'a> Iterator for Cast<slice::IterMut<'a, Mset>> {
    type Item = &'a mut Set;

    fn next(&mut self) -> Option<Self::Item> {
        // Safety: we're iterating over a set.
        self.0.next().map(|s| unsafe { s.as_set_mut_unchecked() })
    }
}

impl IntoIterator for Set {
    type Item = Set;
    type IntoIter = Cast<std::vec::IntoIter<Mset>>;

    fn into_iter(self) -> Self::IntoIter {
        Cast(self.0.into_iter())
    }
}

// The `iter` function is defined in SetTrait.
#[allow(clippy::into_iter_without_iter)]
impl<'a> IntoIterator for &'a Set {
    type Item = &'a Set;
    type IntoIter = Cast<slice::Iter<'a, Mset>>;

    fn into_iter(self) -> Self::IntoIter {
        Cast(self.0.iter())
    }
}

impl<'a> IntoIterator for &'a mut Set {
    type Item = &'a mut Set;
    type IntoIter = Cast<slice::IterMut<'a, Mset>>;

    fn into_iter(self) -> Self::IntoIter {
        Cast(self.0.iter_mut())
    }
}

// -------------------- SetTrait -------------------- //

impl crate::Seal for Set {}

impl SetTrait for Set {
    // -------------------- Basic methods -------------------- //

    fn as_slice(&self) -> &[Self] {
        let slice = self.0.as_slice();
        // Safety: Set and Mset have the same layout.
        unsafe { slice::from_raw_parts(slice.as_ptr().cast(), slice.len()) }
    }

    unsafe fn _as_mut_slice(&mut self) -> &mut [Self] {
        let slice = self.0.as_mut_slice();
        // Safety: Set and Mset have the same layout.
        slice::from_raw_parts_mut(slice.as_mut_ptr().cast(), slice.len())
    }

    fn as_vec(&self) -> &Vec<Mset> {
        self.0.as_vec()
    }

    unsafe fn _as_mut_vec(&mut self) -> &mut Vec<Mset> {
        self.0._as_mut_vec()
    }

    // -------------------- Constructions -------------------- //

    fn empty() -> Self {
        Self(Mset::empty())
    }

    fn with_capacity(capacity: usize) -> Self {
        Self(Mset::with_capacity(capacity))
    }

    fn singleton(self) -> Self {
        Self(self.0.singleton())
    }

    fn into_singleton(self) -> Option<Self> {
        self.0.into_singleton().map(Self)
    }

    fn insert_mut(&mut self, set: Self) {
        self.try_insert(set);
    }

    fn select_mut<P: FnMut(&Set) -> bool>(&mut self, mut pred: P) {
        self.0
            // Safety: we're iterating over a set.
            .select_mut(|set| pred(unsafe { set.as_set_unchecked() }));
    }

    fn count(&self, other: &Self) -> usize {
        usize::from(self.contains(other))
    }

    fn sum_vec(vec: Vec<Self>) -> Self {
        // Union of empty collection is Ø.
        if vec.is_empty() {
            return Self::empty();
        }

        let keys = Levels::new_iter(vec.iter().map(AsRef::as_ref))
            .unwrap()
            .ahu(1);
        let mut children = Mset::sum_vec(Set::cast_vec(vec));
        // Safety: `keys` has as many elements as `children`.
        unsafe {
            dedup_by(&mut children.0, &keys, &mut Vec::new(), &mut Vec::new());
        }

        Self(children)
    }

    fn union_vec(vec: Vec<Self>) -> Self {
        Self::sum_vec(vec)
    }

    fn inter_vec(mut vec: Vec<Self>) -> Option<Self> {
        // Check for trivial cases.
        match vec.len() {
            0 => return None,
            1 => return Some(vec.pop().unwrap()),
            _ => {}
        }

        let levels = Levels::new_iter(vec.iter().map(AsRef::as_ref)).unwrap();
        let next = levels.ahu(1);
        // Safety: the length of `next` is exactly the sum of cardinalities in the first level.
        let mut iter = unsafe { levels.children_slice(0, &next) };

        // Each entry stores the index where it's found within the first set, and a boolean for
        // whether it's been seen in every other set.
        //
        // Safety: we already know there's at least 2 sets.
        let fst = unsafe { iter.next().unwrap_unchecked() };
        let mut sets = BTreeMap::new();
        for (i, set) in fst.iter().enumerate() {
            if sets.insert(*set, (i, false)).is_some() {
                // Safety: sets don't have duplicates.
                unsafe { hint::unreachable_unchecked() }
            }
        }

        // Look for appearances in other sets.
        for slice in iter {
            for set in slice {
                match sets.entry(*set) {
                    Entry::Vacant(_) => {}
                    Entry::Occupied(mut entry) => {
                        entry.get_mut().1 = true;
                    }
                }
            }

            // Update counts.
            sets.retain(|_, (_, count)| {
                let retain = *count;
                *count = false;
                retain
            });
        }

        // Take elements from the first set, reuse some other set as a buffer.
        let mut fst = vec.swap_remove(0);
        let mut snd = vec.swap_remove(0);
        snd.clear();

        for (i, _) in sets.into_values() {
            // Safety: all the indices we built are valid for the first set.
            let set = mem::take(unsafe { fst._as_mut_slice().get_unchecked_mut(i) });
            snd.insert_mut(set);
        }

        Some(snd)
    }

    fn powerset(self) -> Self {
        Self(self.0.powerset())
    }

    fn nat(n: usize) -> Self {
        Self(Mset::nat(n))
    }

    fn zermelo(n: usize) -> Self {
        Self(Mset::zermelo(n))
    }

    fn neumann(n: usize) -> Self {
        Self(Mset::neumann(n))
    }

    fn into_choose(mut self) -> Option<Self> {
        self.0 .0.pop().map(
            // Safety: we're choosing a set.
            |s| unsafe { s.into_set_unchecked() },
        )
    }

    fn choose_uniq(&self) -> Option<&Self> {
        self.0.choose_uniq().map(
            // Safety: we're choosing a set.
            |s| unsafe { s.as_set_unchecked() },
        )
    }

    fn into_choose_uniq(self) -> Option<Self> {
        self.0.into_choose_uniq().map(
            // Safety: we're choosing a set.
            |s| unsafe { s.into_set_unchecked() },
        )
    }

    // -------------------- Relations -------------------- //

    /*
    fn disjoint_pairwise<'a, I: IntoIterator<Item = &'a Self>>(iter: I) -> bool {
        // Empty families are disjoint.
        let levels;
        if let Some(lev) = Levels::init_iter(iter.into_iter().map(AsRef::as_ref)) {
            levels = lev.fill();
        } else {
            return true;
        }

        // Empty sets are disjoint.
        let elements;
        if let Some(el) = levels.get(1) {
            elements = el;
        } else {
            return true;
        }

        let mut cur = Vec::new();
        let mut next = Vec::new();
        let mut sets = BTreeMap::new();

        // Compute AHU encodings for all but the elements of the union.
        for level in levels.iter().skip(2).rev() {
            sets.clear();

            // Safety: the length of `next` is exactly the sum of cardinalities in `level`.
            unsafe {
                Levels::step_ahu(level, &mut cur, &mut next, |slice, _| {
                    slice.sort_unstable();
                    let children = slice.iter().copied().collect::<SmallVec<_>>();
                    Some(btree_index(&mut sets, children))
                });
            }

            mem::swap(&mut cur, &mut next);
        }

        // Compute the encodings for the union. Return whether we find anything twice.
        let mut dummy: Vec<()> = Vec::new();
        sets.clear();

        // Safety: the length of next is exactly the sum of cardinalities in `elements`.
        unsafe {
            Levels::step_ahu(elements, &mut dummy, &mut next, |slice, _| {
                slice.sort_unstable();
                let children = slice.iter().copied().collect::<SmallVec<_>>();

                // The values don't matter, but we recycle our BTreeMap instead of creating a new
                // BTreeSet.
                if sets.insert(children, 0).is_some() {
                    None
                } else {
                    Some(())
                }
            })
        }
    }

    fn disjoint_iter<'a, I: IntoIterator<Item = &'a Self>>(_iter: I) -> bool {
        todo!()
    }
    */
}

impl Set {
    /// Returns a reference to the inner [`Mset`].
    #[must_use]
    pub const fn mset(&self) -> &Mset {
        &self.0
    }

    /// The set as a mutable slice.
    ///
    /// ## Safety
    ///
    /// You must preserve the type invariants for [`Set`]. In particular, you can't make two
    /// elements equal.
    pub unsafe fn as_mut_slice(&mut self) -> &mut [Self] {
        self._as_mut_slice()
    }

    /// A mutable reference to the inner vector.
    ///
    /// ## Safety
    ///
    /// You must preserve the type invariants for [`Set`]. In particular, you can't make two
    /// elements equal.
    pub unsafe fn as_mut_vec(&mut self) -> &mut Vec<Mset> {
        &mut self.0 .0
    }

    /// Mutably iterate over the elements of the set.
    ///
    /// ## Safety
    ///
    /// You must preserve the type invariants for [`Set`]. In particular, you can't make two
    /// elements equal.
    pub unsafe fn iter_mut(&mut self) -> slice::IterMut<Self> {
        self.as_mut_slice().iter_mut()
    }

    /// In-place set insertion x ∪ {y}. Does not check whether the set being inserted is already in
    /// the set.
    ///
    /// ## Safety
    ///
    /// You must guarantee that `other` does not belong to `self`. Doing otherwise breaks the type
    /// invariants for [`Set`].
    pub unsafe fn insert_mut_unchecked(&mut self, other: Self) {
        self.0.insert_mut(other.0);
    }

    /// Set insertion x ∪ {y}. Does not check whether the set being inserted is already in the set.
    ///
    /// ## Safety
    ///
    /// You must guarantee that `other` does not belong to `self`. Doing otherwise breaks the type
    /// invariants for [`Set`].
    #[must_use]
    pub unsafe fn insert_unchecked(mut self, other: Self) -> Self {
        self.insert_mut_unchecked(other);
        self
    }

    /// Inserts an element into a set in place. Returns whether the size of the set changed.
    pub fn try_insert(&mut self, set: Self) -> bool {
        let res = !self.contains(&set);
        if res {
            // Safety: we just performed the relevant check.
            unsafe {
                self.insert_mut_unchecked(set);
            }
        }
        res
    }
}

// -------------------- Ordered pairs -------------------- //

impl Set {
    /// Kuratowski pair (x, y) = {{x}, {x, y}}.
    #[must_use]
    pub fn kpair(self, other: Self) -> Self {
        self.clone().singleton().pair(self.pair(other))
    }

    /// A Kuratowski pair (x, x) = {{x}}.
    #[must_use]
    pub fn id_kpair(self) -> Self {
        self.singleton().singleton()
    }

    /// Decomposes a Kuratowski pair.
    #[must_use]
    pub fn ksplit(&self) -> Option<(&Self, &Self)> {
        match self.as_slice() {
            [set] => match set.as_slice() {
                [a] => Some((a, a)),
                _ => None,
            },
            [fst, snd] => match (fst.as_slice(), snd.as_slice()) {
                ([a], [b, c]) | ([b, c], [a]) => {
                    if a == b {
                        Some((a, c))
                    } else if a == c {
                        Some((a, b))
                    } else {
                        None
                    }
                }
                _ => None,
            },
            _ => None,
        }
    }

    /// Decomposes a Kuratowski pair.
    #[must_use]
    pub fn into_ksplit(mut self) -> Option<(Self, Self)> {
        // Safety: our usage of `as_mut_slice` causes no issues, as the set is dropped and discarded
        // when the method returns.
        unsafe {
            match self.as_mut_slice() {
                [set] => match set.as_mut_slice() {
                    [a] => Some((a.clone(), mem::take(a))),
                    _ => None,
                },
                [fst, snd] => match (fst.as_mut_slice(), snd.as_mut_slice()) {
                    ([a], [b, c]) | ([b, c], [a]) => {
                        if a == b {
                            Some((mem::take(a), mem::take(c)))
                        } else if a == c {
                            Some((mem::take(a), mem::take(b)))
                        } else {
                            None
                        }
                    }
                    _ => None,
                },
                _ => None,
            }
        }
    }

    /// Tagged or disjoint union.
    ///
    /// See [`Self::tag_union`].
    pub fn tag_union_iter<I: IntoIterator<Item = Self>>(iter: I) -> Self {
        let mut union = Self::empty();
        for set in iter {
            // Safety: since our original sets and the elements in them were distinct, so are our
            // pairs.
            unsafe {
                for element in &set.as_slice()[1..] {
                    union.insert_mut_unchecked(set.clone().kpair(element.clone()));
                }

                // Reuse `set` allocation.
                if let Some(fst) = set.as_slice().first().cloned() {
                    union.insert_mut_unchecked(set.kpair(fst));
                }
            }
        }

        union
    }

    /// Tagged or disjoint union over a vector.
    ///
    /// See [`Self::tag_union`].
    #[must_use]
    pub fn tag_union_vec(vec: Vec<Self>) -> Self {
        Self::tag_union_iter(vec)
    }

    /// Tagged or disjoint union.
    ///
    /// This returns the set of all pairs (x, y), where x is either of the two sets, and y is an
    /// element of it.
    ///
    /// Whereas the usual union can vary in cardinality, the tagged union of two sets always adds
    /// their cardinalities.
    #[must_use]
    pub fn tag_union(self, other: Self) -> Self {
        Self::tag_union_iter([self, other])
    }

    /// Cartesian product of sets.
    #[must_use]
    pub fn prod(mut self, mut other: Self) -> Self {
        // Ensure `self` is the smallest set.
        let c1 = self.card();
        let c2 = other.card();
        if c2 < c1 {
            mem::swap(&mut other, &mut self);
        }

        let mut prod = Self::with_capacity(c1 * c2);
        // Safety: these are ordered pairs of distinct pairs of elements.
        unsafe {
            for (i, fst) in self.iter().enumerate() {
                for (j, snd) in other.iter().enumerate() {
                    if i != j {
                        prod.insert_mut_unchecked(fst.clone().kpair(snd.clone()));
                    }
                }
            }

            // Re-use allocations.
            for (fst, snd) in self.into_iter().zip(other.into_iter()) {
                prod.insert_mut_unchecked(fst.kpair(snd));
            }
        }

        prod
    }
}

// -------------------- Functions -------------------- //

impl Set {
    /// Evaluates a function at a set. Returns `None` if the set is not in the domain.
    ///
    /// If `self` is not a function, the result will almost definitely be garbage.
    #[must_use]
    pub fn eval(&self, _set: &Self) -> Option<&Self> {
        // Set::filter_eq(self.iter().map_while(|s|s.ksplit()), set)

        None
    }

    /// Returns the identity function with domain `self`.
    #[must_use]
    pub fn id_func(self) -> Self {
        let res: Mset = self.into_iter().map(|s| s.id_kpair().0).collect();
        // Safety: all elements were originally sets and are distinct.
        unsafe { res.into_set_unchecked() }
    }

    /// Returns the constant function with domain `self` and value `cst`.
    #[must_use]
    pub fn const_func(self, cst: Set) -> Self {
        let len = self.card();
        let mut func = Set::with_capacity(len);
        let mut vec = self.into_vec();

        // Safety: all these pairs are distinct.
        unsafe {
            for set in vec.drain(1..) {
                func.insert_mut_unchecked(set.kpair(cst.clone()));
            }

            // Reuse `cst`.
            if let Some(fst) = vec.pop() {
                func.insert_mut_unchecked(fst.kpair(cst));
            }
        }

        func
    }

    /// Set of functions between two sets x → y.
    ///
    /// ## Panics
    ///
    /// This function will panic if you attempt to create a set that's too large. Note that this is
    /// quite easy to do, as |x → y| = |y|<sup>|x|</sup>.
    #[must_use]
    pub fn func(self, mut other: Self) -> Self {
        let dom_card = self.card();
        let cod_card = other.card();

        // The empty function is the only function with domain Ø.
        if dom_card == 0 {
            return Self::empty().singleton();
        }

        match cod_card {
            // No other function has codomain Ø.
            0 => return Self::empty(),
            // There is only one function into a singleton.
            1 => {
                // Safety: this is a singleton.
                return Self::const_func(self, unsafe {
                    other.into_singleton().unwrap_unchecked()
                })
                .singleton();
            }
            _ => {}
        }

        #[allow(clippy::cast_possible_truncation)]
        let size = cod_card.pow(dom_card.try_into().expect("domain too large"));
        let mut funcs = Self::with_capacity(size);

        // The indices in `other` into which we map the elements in `self`.
        let mut indices = vec![0; dom_card];
        for _ in 1..size {
            // Update indices.
            let mut idx = dom_card - 1;
            loop {
                // Safety: our indices essentially function as a base `cod_card` expansion. We exit
                // the outer loop just as all values are maxed out.
                unsafe {
                    let index = indices.get_unchecked_mut(idx);
                    *index += 1;
                    if *index == cod_card {
                        *index = 0;
                    } else {
                        break;
                    }

                    idx = idx.unchecked_sub(1);
                }
            }

            // Safety: all pairs within a single function have distinct first entries, and are thus
            // distinct. All the functions we build in general are distinct.
            unsafe {
                let mut func = Self::with_capacity(dom_card);
                for (i, &j) in indices.iter().enumerate() {
                    func.insert_mut_unchecked(
                        self.as_slice()
                            .get_unchecked(i)
                            .clone()
                            .kpair(other.as_slice().get_unchecked(j).clone()),
                    );
                }

                funcs.insert_mut_unchecked(func);
            }
        }

        // Reuse `self`.
        // Safety: same as above.
        unsafe {
            funcs.insert_mut_unchecked(Self::const_func(
                self,
                mem::take(other.as_mut_slice().get_unchecked_mut(0)),
            ));
        }
        funcs
    }
}