more_collections 0.14.3

Additional collections not found in std::collections
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
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
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
use std::collections::hash_map::RandomState;
use std::fmt;
use std::fmt::Debug;
use std::fmt::Formatter;
use std::hash::BuildHasher;
use std::iter::Chain;
use std::iter::FusedIterator;

use ::core::hash::Hash;
use indexmap::Equivalent;
use smallvec::SmallVec;

use crate::small_map;
use crate::SmallMap;

/// A set-like container that can store a specified number of elements inline.
///
/// `SmallSet` shares most of its API with, and behaves like,
/// [`IndexSet`](indexmap::IndexSet). It can store a limited amount of data
/// inline, backed by [`SmallVec`]. If the data exceeds the
/// limit `C`, `SmallSet` will move _all_ its data over to the heap in the form
/// of an `IndexSet`. For performance reasons, transitions between heap and
/// inline storage should generally be avoided.
///
/// The `SmallSet` datastructure is meant for situations where the data does not
/// exceed `C` _most of the time_ but it still needs to support cases where the
/// data _does_ exceed `C`.
///
/// # Example
///
/// ```
/// use more_collections::SmallSet;
///
/// let mut set = SmallSet::<usize, 3>::new();
/// // The set can hold up to three items inline
/// set.insert(0);
/// set.insert(1);
/// set.insert(2);
/// assert_eq!(3, set.len());
/// assert!(set.is_inline());
///
/// // Adding the fourth element will move the set to the heap
/// set.insert(3);
/// assert_eq!(4, set.len());
/// assert!(!set.is_inline());
/// ```
#[derive(Default, Clone)]
pub struct SmallSet<T, const C: usize, S = RandomState> {
    data: SmallMap<T, (), C, S>,
}

impl<T, const C: usize> SmallSet<T, C> {
    /// Create a new set.
    #[must_use]
    pub fn new() -> Self {
        Self {
            data: SmallMap::new(),
        }
    }

    // Helper method for macro, don't use directly.
    #[doc(hidden)]
    pub const fn from_const_unchecked(inline: SmallVec<[(T, ()); C]>) -> Self {
        Self {
            data: SmallMap::from_const_unchecked(inline),
        }
    }
}

impl<T, const C: usize, S> SmallSet<T, C, S> {
    /// The number of values stored in the set.
    pub fn len(&self) -> usize {
        self.data.len()
    }

    /// Returns `true` if the set is empty.
    pub fn is_empty(&self) -> bool {
        self.data.is_empty()
    }

    /// The memory capacity that will be allocated inline. If the nubmer of
    /// values exceeds the inline capacity, the set will move to the heap.
    pub const fn inline_capacity(&self) -> usize {
        self.data.inline_capacity()
    }

    /// Is the data contained by this set stored inline (`true`) or on the heap
    /// (`false`).
    pub const fn is_inline(&self) -> bool {
        self.data.is_inline()
    }

    /// Returns an iterator over the values in insertion order.
    pub fn iter(&'_ self) -> Iter<'_, T> {
        Iter {
            inner: self.data.iter(),
        }
    }

    // Helper method for macro, don't use directly.
    #[doc(hidden)]
    pub const fn from_const_unchecked_with_hasher(inline: SmallVec<[(T, ()); C]>) -> Self {
        Self {
            data: SmallMap::from_const_unchecked_with_hasher(inline),
        }
    }
}

impl<T, const C: usize, S> SmallSet<T, C, S>
where
    T: Hash + Eq,
    S: BuildHasher + Default,
{
    /// Inserts the specified value into this set.
    ///
    /// If an equivalent item already exists in the set, it returns `false`
    /// leaving the original value in the set and without altering its insertion
    /// order. Otherwise, it inserts the new item and returns `true`.
    ///
    /// If a new value is added that causes the size of the `SmallSet` to exceed
    /// the inline capacity, all existing data and the new value is moved to the
    /// heap.
    ///
    /// Computational complexity:
    ///  - inline: O(n)
    ///  - heap: O(1)
    pub fn insert(&mut self, value: T) -> bool {
        self.data.insert(value, ()).is_some()
    }

    /// Inserts the specified value into this set, and get their index.
    ///
    /// If an equivalent item already exists in the set, it returns the index of
    /// the existing item and `false`, leaving the original value in the set and
    /// without altering its insertion order. Otherwise, it inserts the new
    /// item and returns the index of the inserted item and `true`.
    ///
    /// If a new value is added that causes the size of the `SmallSet` to exceed
    /// the inline capacity, all existing data and the new value is moved to the
    /// heap.
    ///
    /// Computational complexity:
    ///  - inline: O(n)
    ///  - heap: O(1)
    pub fn insert_full(&mut self, value: T) -> (usize, bool) {
        let (index, value) = self.data.insert_full(value, ());
        (index, value.is_some())
    }
}

impl<T, const C: usize, S> SmallSet<T, C, S>
where
    T: Hash + Eq,
    S: BuildHasher,
{
    pub const fn from_keys(map: SmallMap<T, (), C, S>) -> Self {
        SmallSet { data: map }
    }

    /// Get a value by index, if it is present, else `None`.
    ///
    /// Computational complexity: O(1)
    pub fn get_index(&self, index: usize) -> Option<&T> {
        self.data.get_index(index).map(|(k, _v)| k)
    }

    /// Return the item index, if it exists in the set, else `None`.
    ///
    /// Computational complexity:
    ///  - inline: O(n)
    ///  - heap: O(1)
    pub fn get_index_of<Q>(&self, key: &Q) -> Option<usize>
    where
        Q: Hash + Equivalent<T> + ?Sized,
    {
        self.data.get_index_of(key)
    }

    /// Remove the key-value pair equivalent to `key` and return
    /// its value.
    ///
    /// **NOTE:** This is equivalent to `.swap_remove(key)`, if you need to
    /// preserve the order of the keys in the map, use `.shift_remove(key)`
    /// instead.
    ///
    /// Computes in **O(1)** time (average).
    pub fn remove<Q>(&mut self, key: &Q) -> bool
    where
        Q: Hash + Equivalent<T> + ?Sized,
    {
        self.data.remove(key).is_some()
    }

    /// Return an iterator over the values that are in `self` but not `other`.
    ///
    /// Values are produced in the same order that they appear in `self`.
    pub fn difference<'a, const C2: usize, S2>(
        &'a self,
        other: &'a SmallSet<T, C2, S2>,
    ) -> Difference<'a, T, C2, S2>
    where
        S2: BuildHasher,
    {
        Difference {
            iter: self.iter(),
            other,
        }
    }

    /// Return an iterator over the values that are in `self` or `other`,
    /// but not in both.
    ///
    /// Values from `self` are produced in their original order, followed by
    /// values from `other` in their original order.
    pub fn symmetric_difference<'a, const C2: usize, S2>(
        &'a self,
        other: &'a SmallSet<T, C2, S2>,
    ) -> SymmetricDifference<'a, T, C, S, C2, S2>
    where
        S2: BuildHasher,
    {
        let diff1 = self.difference(other);
        let diff2 = other.difference(self);
        SymmetricDifference {
            iter: diff1.chain(diff2),
        }
    }

    /// Return an iterator over the values that are in both `self` and `other`.
    ///
    /// Values are produced in the same order that they appear in `self`.
    pub fn intersection<'a, const C2: usize, S2>(
        &'a self,
        other: &'a SmallSet<T, C2, S2>,
    ) -> Intersection<'a, T, C2, S2>
    where
        S2: BuildHasher,
    {
        Intersection {
            iter: self.iter(),
            other,
        }
    }

    /// Return an iterator over all values that are in `self` or `other`.
    ///
    /// Values from `self` are produced in their original order, followed by
    /// values that are unique to `other` in their original order.
    pub fn union<'a, const C2: usize, S2>(
        &'a self,
        other: &'a SmallSet<T, C2, S2>,
    ) -> Union<'a, T, C, S>
    where
        S2: BuildHasher,
    {
        Union {
            iter: self.iter().chain(other.difference(self)),
        }
    }

    /// Return `true` if an equivalent to `value` exists in the set.
    ///
    /// Computational complexity:
    ///  - inline: O(n)
    ///  - heap: O(1)
    pub fn contains<Q>(&self, value: &Q) -> bool
    where
        Q: Hash + Equivalent<T> + ?Sized,
    {
        self.data.contains_key(value)
    }
}

impl<T, const C: usize, S> Hash for SmallSet<T, C, S>
where
    T: Hash + Eq,
{
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.data.hash(state);
    }
}
impl<T, const C: usize, S> Eq for SmallSet<T, C, S> where T: Hash + Eq {}
impl<T, const C: usize, S> PartialEq for SmallSet<T, C, S>
where
    T: Hash + Eq,
{
    fn eq(&self, other: &Self) -> bool {
        self.data == other.data
    }
}

pub struct Iter<'a, T> {
    inner: small_map::Iter<'a, T, ()>,
}

impl<'a, T> Iterator for Iter<'a, T> {
    type Item = &'a T;

    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next().map(|(t, ())| t)
    }
}

impl<T> ExactSizeIterator for Iter<'_, T> {
    fn len(&self) -> usize {
        self.inner.len()
    }
}

impl<T> DoubleEndedIterator for Iter<'_, T> {
    fn next_back(&mut self) -> Option<Self::Item> {
        self.inner.next_back().map(|(t, ())| t)
    }
}

impl<T> FusedIterator for Iter<'_, T> {}

// FIXME(#26925) Remove in favor of `#[derive(Clone)]`
impl<T> Clone for Iter<'_, T> {
    fn clone(&self) -> Self {
        Self {
            inner: self.inner.clone(),
        }
    }
}

impl<T: Debug> Debug for Iter<'_, T> {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.debug_list().entries(self.clone()).finish()
    }
}

impl<T, const C: usize, S> IntoIterator for SmallSet<T, C, S> {
    type Item = T;

    type IntoIter = IntoIter<T, C>;

    fn into_iter(self) -> Self::IntoIter {
        IntoIter {
            inner: self.data.into_iter(),
        }
    }
}

impl<'a, T, const C: usize, S> IntoIterator for &'a SmallSet<T, C, S> {
    type IntoIter = Iter<'a, T>;
    type Item = &'a T;
    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

#[derive(Debug)]
pub struct IntoIter<T, const C: usize> {
    inner: small_map::IntoIter<T, (), C>,
}

impl<T, const C: usize> Iterator for IntoIter<T, C> {
    type Item = T;

    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next().map(|(k, ())| k)
    }
}

impl<T, const C: usize> ExactSizeIterator for IntoIter<T, C> {
    fn len(&self) -> usize {
        self.inner.len()
    }
}

impl<T, const C: usize> FusedIterator for IntoIter<T, C> {}

impl<T, const C: usize, S> FromIterator<T> for SmallSet<T, C, S>
where
    T: Hash + Eq,
    S: BuildHasher + Default,
{
    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
        Self {
            data: iter.into_iter().map(|i| (i, ())).collect(),
        }
    }
}

impl<T, const C: usize, S> Debug for SmallSet<T, C, S>
where
    T: Hash + Eq + Debug,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.debug_set().entries(self.iter()).finish()
    }
}

pub struct Difference<'a, T, const C: usize, S> {
    iter: Iter<'a, T>,
    other: &'a SmallSet<T, C, S>,
}

impl<'a, T, const C: usize, S> Iterator for Difference<'a, T, C, S>
where
    T: Eq + Hash,
    S: BuildHasher,
{
    type Item = &'a T;

    fn next(&mut self) -> Option<Self::Item> {
        self.iter.find(|item| !self.other.contains(*item))
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        (0, self.iter.size_hint().1)
    }
}

impl<T, const C: usize, S> DoubleEndedIterator for Difference<'_, T, C, S>
where
    T: Eq + Hash,
    S: BuildHasher,
{
    fn next_back(&mut self) -> Option<Self::Item> {
        self.iter.rfind(|item| !self.other.contains(*item))
    }
}

impl<T, const C: usize, S> FusedIterator for Difference<'_, T, C, S>
where
    T: Eq + Hash,
    S: BuildHasher,
{
}

// FIXME(#26925) Remove in favor of `#[derive(Clone)]`
impl<T, const C: usize, S> Clone for Difference<'_, T, C, S> {
    fn clone(&self) -> Self {
        Self {
            iter: self.iter.clone(),
            other: self.other,
        }
    }
}

impl<T, const C: usize, S> Debug for Difference<'_, T, C, S>
where
    T: Debug + Eq + Hash,
    S: BuildHasher,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.debug_list().entries(self.clone()).finish()
    }
}

pub struct SymmetricDifference<'a, T, const C1: usize, S1, const C2: usize, S2> {
    iter: Chain<Difference<'a, T, C2, S2>, Difference<'a, T, C1, S1>>,
}

impl<'a, T, const C1: usize, S1, const C2: usize, S2> Iterator
    for SymmetricDifference<'a, T, C1, S1, C2, S2>
where
    T: Eq + Hash,
    S1: BuildHasher,
    S2: BuildHasher,
{
    type Item = &'a T;

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

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.iter.size_hint()
    }

    fn fold<B, F>(self, init: B, f: F) -> B
    where
        F: FnMut(B, Self::Item) -> B,
    {
        self.iter.fold(init, f)
    }
}

impl<T, const C1: usize, S1, const C2: usize, S2> DoubleEndedIterator
    for SymmetricDifference<'_, T, C1, S1, C2, S2>
where
    T: Eq + Hash,
    S1: BuildHasher,
    S2: BuildHasher,
{
    fn next_back(&mut self) -> Option<Self::Item> {
        self.iter.next_back()
    }

    fn rfold<B, F>(self, init: B, f: F) -> B
    where
        F: FnMut(B, Self::Item) -> B,
    {
        self.iter.rfold(init, f)
    }
}

impl<T, const C1: usize, S1, const C2: usize, S2> FusedIterator
    for SymmetricDifference<'_, T, C1, S1, C2, S2>
where
    T: Eq + Hash,
    S1: BuildHasher,
    S2: BuildHasher,
{
}

// FIXME(#26925) Remove in favor of `#[derive(Clone)]`
impl<T, const C1: usize, S1, const C2: usize, S2> Clone
    for SymmetricDifference<'_, T, C1, S1, C2, S2>
where
    T: Eq + Hash,
    S1: BuildHasher,
    S2: BuildHasher,
{
    fn clone(&self) -> Self {
        Self {
            iter: self.iter.clone(),
        }
    }
}

impl<T, const C1: usize, S1, const C2: usize, S2> Debug
    for SymmetricDifference<'_, T, C1, S1, C2, S2>
where
    T: Eq + Hash + Debug,
    S1: BuildHasher,
    S2: BuildHasher,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.debug_list().entries(self.clone()).finish()
    }
}

pub struct Intersection<'a, T, const C: usize, S> {
    iter: Iter<'a, T>,
    other: &'a SmallSet<T, C, S>,
}

impl<'a, T, const C: usize, S> Iterator for Intersection<'a, T, C, S>
where
    T: Eq + Hash,
    S: BuildHasher,
{
    type Item = &'a T;

    fn next(&mut self) -> Option<Self::Item> {
        self.iter.find(|item| self.other.contains(*item))
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        (0, self.iter.size_hint().1)
    }
}

impl<T, const C: usize, S> DoubleEndedIterator for Intersection<'_, T, C, S>
where
    T: Eq + Hash,
    S: BuildHasher,
{
    fn next_back(&mut self) -> Option<Self::Item> {
        self.iter.rfind(|item| self.other.contains(*item))
    }
}

impl<T, const C: usize, S> FusedIterator for Intersection<'_, T, C, S>
where
    T: Eq + Hash,
    S: BuildHasher,
{
}

// FIXME(#26925) Remove in favor of `#[derive(Clone)]`
impl<T, const C: usize, S> Clone for Intersection<'_, T, C, S>
where
    T: Eq + Hash,
    S: BuildHasher,
{
    fn clone(&self) -> Self {
        Self {
            iter: self.iter.clone(),
            other: self.other,
        }
    }
}

impl<T, const C: usize, S> Debug for Intersection<'_, T, C, S>
where
    T: Debug + Eq + Hash,
    S: BuildHasher,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.debug_list().entries(self.clone()).finish()
    }
}

pub struct Union<'a, T, const C: usize, S> {
    iter: Chain<Iter<'a, T>, Difference<'a, T, C, S>>,
}

impl<'a, T, const C: usize, S> Iterator for Union<'a, T, C, S>
where
    T: Eq + Hash,
    S: BuildHasher,
{
    type Item = &'a T;

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

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.iter.size_hint()
    }

    fn fold<B, F>(self, init: B, f: F) -> B
    where
        F: FnMut(B, Self::Item) -> B,
    {
        self.iter.fold(init, f)
    }
}

impl<T, const C: usize, S> DoubleEndedIterator for Union<'_, T, C, S>
where
    T: Eq + Hash,
    S: BuildHasher,
{
    fn next_back(&mut self) -> Option<Self::Item> {
        self.iter.next_back()
    }

    fn rfold<B, F>(self, init: B, f: F) -> B
    where
        F: FnMut(B, Self::Item) -> B,
    {
        self.iter.rfold(init, f)
    }
}

impl<T, const C: usize, S> FusedIterator for Union<'_, T, C, S>
where
    T: Eq + Hash,
    S: BuildHasher,
{
}

// FIXME(#26925) Remove in favor of `#[derive(Clone)]`
impl<T, const C: usize, S> Clone for Union<'_, T, C, S>
where
    T: Eq + Hash,
    S: BuildHasher,
{
    fn clone(&self) -> Self {
        Self {
            iter: self.iter.clone(),
        }
    }
}

impl<T, const C: usize, S> Debug for Union<'_, T, C, S>
where
    T: Debug + Eq + Hash,
    S: BuildHasher,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.debug_list().entries(self.clone()).finish()
    }
}

/// Create a [`SmallSet`] with with the specified values.
#[macro_export]
macro_rules! smallset {
    ($($x:expr),*$(,)*) => ({
        let map = $crate::smallmap!( $($x => (),)* );
        $crate::SmallSet::from_keys(map)
    });
}

/// Create a [`SmallSet`] with inline capacity equal to the number of values.
#[macro_export]
macro_rules! smallset_inline {
    ($($key:expr),*$(,)*) => ({
        let vec = smallvec::smallvec_inline!( $(($key, ()),)*);
        debug_assert_eq!(
            vec.len(),
            vec
                .iter()
                .map(|(k, _v)| k)
                .collect::<std::collections::HashSet<_>>()
                .len(),
            "smallset_inline! cannot be initialized with duplicate keys"
        );
        $crate::SmallSet::from_const_unchecked(vec)
    });
}

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

    #[test]
    fn test_len_and_inline_capacity() {
        let mut set = SmallSet::<usize, 1>::new();
        assert_eq!(0, set.len());
        assert_eq!(0, set.iter().len());
        set.insert(0);
        assert_eq!(1, set.len());
        assert_eq!(1, set.iter().len());

        let set: SmallSet<_, 10> = smallset! {0, 1, 4};
        assert_eq!(3, set.len());
        assert_eq!(10, set.inline_capacity());

        let set = smallset_inline! {0, 1, 4 };
        assert_eq!(3, set.len());
        assert_eq!(3, set.iter().len());
        assert_eq!(3, set.inline_capacity());
    }

    #[test]
    fn smallset_macro_removes_duplicates() {
        let set: SmallSet<_, 10> = smallset! { 0 , 0};
        assert_eq!(1, set.len());
    }

    #[test]
    #[should_panic(expected = "smallset_inline! cannot be initialized with duplicate keys")]
    fn smallset_inline_macro_fails_on_duplicates() {
        smallset_inline! { 0 , 0 };
    }

    #[test]
    fn iter_iterates_in_insertion_order() {
        fn test<const C: usize>(inline: bool) {
            let inline_map: SmallSet<_, C> = smallset! {
                1, 0, 4
            };
            assert_eq!(inline, inline_map.is_inline());
            assert_eq!(
                vec![&1, &0, &4],
                inline_map.iter().collect::<Vec<_>>(),
                "iter() does not return values in the correct order"
            );
            assert_eq!(
                vec![1, 0, 4],
                inline_map.into_iter().collect::<Vec<_>>(),
                "into_iter() does not return values in the correct order"
            );
        }
        test::<1>(false);
        test::<3>(true);
    }

    #[test]
    fn insert_and_insert_full_tests() {
        // Test cases:
        // | Value               | Memory       | Insertion position |
        // | ------------------- | ------------ | ------------------ |
        // | new                 | Stay inline  | Last               |
        // | new                 | Move to heap | Last               |
        // | new                 | Stay on heap | Last               |
        // | already existing    | Stay inline  | Same as existing   |
        // | already existing    | Stay on heap | Same as existing   |

        struct TestCase {
            name: &'static str,
            initial_values: Vec<usize>,
            insert_value: usize,
            expected_inline_before: bool,
            expected_inline_after: bool,
            expected_values: Vec<usize>,
            expected_return: (usize, bool),
        }
        let values = [10, 5, 86, 93];
        let test_cases = [
            TestCase {
                name: "new key/value, stay inline",
                initial_values: values[0..2].to_vec(),
                insert_value: 7,
                expected_inline_before: true,
                expected_inline_after: true,
                expected_values: vec![10, 5, 7],
                expected_return: (2, false),
            },
            TestCase {
                name: "new key/value, move to heap",
                initial_values: values[0..3].to_vec(),
                insert_value: 7,
                expected_inline_before: true,
                expected_inline_after: false,
                expected_values: vec![10, 5, 86, 7],
                expected_return: (3, false),
            },
            TestCase {
                name: "new key/value, stay on heap",
                initial_values: values[0..4].to_vec(),
                insert_value: 7,
                expected_inline_before: false,
                expected_inline_after: false,
                expected_values: vec![10, 5, 86, 93, 7],
                expected_return: (4, false),
            },
            TestCase {
                name: "overwrite existing key/value, stay inline",
                initial_values: values[0..3].to_vec(),
                insert_value: 5,
                expected_inline_before: true,
                expected_inline_after: true,
                expected_values: vec![10, 5, 86],
                expected_return: (1, true),
            },
            TestCase {
                name: "overwrite existing key/value, stay on heap",
                initial_values: values[0..4].to_vec(),
                insert_value: 10,
                expected_inline_before: false,
                expected_inline_after: false,
                expected_values: vec![10, 5, 86, 93],
                expected_return: (0, true),
            },
        ];

        for test_case in test_cases {
            let mut small_set_1 = SmallSet::<usize, 3>::new();
            for v in test_case.initial_values {
                small_set_1.insert(v);
            }
            let mut small_set_2 = small_set_1.clone();

            for set in [&small_set_1, &small_set_2] {
                assert_eq!(
                    test_case.expected_inline_before,
                    set.is_inline(),
                    "inline state before insertion in SmallSet does not match expected in test '{}'",
                    test_case.name
                );
            }

            let actual_return_1 = small_set_1.insert(test_case.insert_value);
            let actual_return_2 = small_set_2.insert_full(test_case.insert_value);
            assert_eq!(
                test_case.expected_return.1, actual_return_1,
                "return of insertion in SmallMap does not match expected return in test '{}'",
                test_case.name
            );
            assert_eq!(
                test_case.expected_return, actual_return_2,
                "return of insertion_full in SmallMap does not match expected return in test '{}'",
                test_case.name
            );

            for set in [small_set_1, small_set_2] {
                assert_eq!(
                    test_case.expected_inline_after,
                    set.is_inline(),
                    "inline state after insertion in SmallSet does not match expected in test '{}'",
                    test_case.name
                );
                assert_eq!(
                    test_case.expected_values,
                    set.iter().copied().collect::<Vec<_>>(),
                    "values in SmallSet do not match expected values in test '{}'",
                    test_case.name
                );
            }
        }
    }

    #[test]
    fn equality_is_consistent() {
        let set1: SmallSet<_, 3> = smallset! {0, 1, 4 };
        let set2 = smallset_inline! {0, 1, 4 };
        let set3 = SmallSet::<_, 3>::from_iter(vec![0, 1, 4]);
        let mut set4 = SmallSet::<_, 3>::new();
        set4.insert(0);
        set4.insert(1);
        set4.insert(4);

        assert_eq!(set1, set2);
        assert_eq!(set1, set3);
        assert_eq!(set1, set4);

        assert_eq!(set2, set3);
        assert_eq!(set2, set4);

        assert_eq!(set3, set4);
    }

    #[test]
    fn empty_small_maps_are_equal() {
        let set1: SmallSet<usize, 3> = smallset! {};
        let set2: SmallSet<usize, 3> = smallset! {};
        assert_eq!(set1, set2);
    }

    #[test]
    fn debug_string_test() {
        let actual = format!("{:?}", smallset_inline! {0, 1, 2});
        let expected = "{0, 1, 2}";
        assert_eq!(expected, actual);
    }

    #[test]
    fn test_difference() {
        fn test<const C1: usize, const C2: usize>(inline_a: bool, inline_b: bool) {
            let set_a: SmallSet<&'static str, C1> = smallset! {"2", "1", "3", "b"};
            let set_b: SmallSet<&'static str, C2> = smallset! {"2", "d", "1", "3", "a"};
            assert_eq!(inline_a, set_a.is_inline());
            assert_eq!(inline_b, set_b.is_inline());

            let diff_a = set_a.difference(&set_b).copied().collect::<Vec<_>>();
            assert_eq!(vec!["b"], diff_a);
            let diff_b = set_b.difference(&set_a).copied().collect::<Vec<_>>();
            assert_eq!(vec!["d", "a"], diff_b);
            let diff_b_reverse = set_b.difference(&set_a).copied().rev().collect::<Vec<_>>();
            assert_eq!(vec!["a", "d"], diff_b_reverse);

            assert_eq!(0, set_a.difference(&set_a).count());
        }
        test::<1, 1>(false, false);
        test::<1, 5>(false, true);
        test::<4, 5>(true, true);
        test::<4, 4>(true, false);
    }

    #[test]
    fn test_symmetric_difference() {
        fn test<const C1: usize, const C2: usize>(inline_a: bool, inline_b: bool) {
            let set_a: SmallSet<&'static str, C1> = smallset! {"2", "1", "3", "b"};
            let set_b: SmallSet<&'static str, C2> = smallset! {"2", "d", "1", "3", "a"};
            assert_eq!(inline_a, set_a.is_inline());
            assert_eq!(inline_b, set_b.is_inline());

            let diff_a = set_a
                .symmetric_difference(&set_b)
                .copied()
                .collect::<Vec<_>>();
            assert_eq!(vec!["b", "d", "a"], diff_a);
            let diff_b = set_b
                .symmetric_difference(&set_a)
                .copied()
                .collect::<Vec<_>>();
            assert_eq!(vec!["d", "a", "b"], diff_b);
            let diff_b_reverse = set_b
                .symmetric_difference(&set_a)
                .copied()
                .rev()
                .collect::<Vec<_>>();
            assert_eq!(vec!["b", "a", "d"], diff_b_reverse);

            assert_eq!(0, set_a.symmetric_difference(&set_a).count());
        }
        test::<1, 1>(false, false);
        test::<1, 5>(false, true);
        test::<4, 5>(true, true);
        test::<4, 4>(true, false);
    }

    #[test]
    fn test_intersection() {
        fn test<const C1: usize, const C2: usize>(inline_a: bool, inline_b: bool) {
            let set_a: SmallSet<&'static str, C1> = smallset! {"2", "1", "3", "b"};
            let set_b: SmallSet<&'static str, C2> = smallset! {"1", "d", "3", "2", "a"};
            assert_eq!(inline_a, set_a.is_inline());
            assert_eq!(inline_b, set_b.is_inline());

            let diff_a = set_a.intersection(&set_b).copied().collect::<Vec<_>>();
            assert_eq!(vec!["2", "1", "3"], diff_a);
            let diff_b = set_b.intersection(&set_a).copied().collect::<Vec<_>>();
            assert_eq!(vec!["1", "3", "2"], diff_b);
            let diff_b_reverse = set_b
                .intersection(&set_a)
                .copied()
                .rev()
                .collect::<Vec<_>>();
            assert_eq!(vec!["2", "3", "1"], diff_b_reverse);

            assert_eq!(
                vec!["2", "1", "3", "b"],
                set_a.intersection(&set_a).copied().collect::<Vec<_>>()
            );
        }
        test::<1, 1>(false, false);
        test::<1, 5>(false, true);
        test::<4, 5>(true, true);
        test::<4, 4>(true, false);
    }

    #[test]
    fn test_union() {
        fn test<const C1: usize, const C2: usize>(inline_a: bool, inline_b: bool) {
            let set_a: SmallSet<&'static str, C1> = smallset! {"2", "1", "3", "b"};
            let set_b: SmallSet<&'static str, C2> = smallset! {"1", "d", "3", "2", "a"};
            assert_eq!(inline_a, set_a.is_inline());
            assert_eq!(inline_b, set_b.is_inline());

            let diff_a = set_a.union(&set_b).copied().collect::<Vec<_>>();
            assert_eq!(vec!["2", "1", "3", "b", "d", "a"], diff_a);
            let diff_b = set_b.union(&set_a).copied().collect::<Vec<_>>();
            assert_eq!(vec!["1", "d", "3", "2", "a", "b"], diff_b);
            let diff_b_reverse = set_b.union(&set_a).copied().rev().collect::<Vec<_>>();
            assert_eq!(vec!["b", "a", "2", "3", "d", "1"], diff_b_reverse);

            assert_eq!(
                vec!["2", "1", "3", "b"],
                set_a.union(&set_a).copied().collect::<Vec<_>>()
            );
        }
        test::<1, 1>(false, false);
        test::<1, 5>(false, true);
        test::<4, 5>(true, true);
        test::<4, 4>(true, false);
    }

    #[test]
    fn get_index_of_and_contains_test() {
        fn test<const C: usize>(inline: bool) {
            let set: SmallSet<&'static str, C> = smallset! {"2", "1", "3"};
            assert_eq!(inline, set.is_inline());

            assert_eq!(None, set.get_index_of(&"0"));
            assert!(!set.contains(&"0"));
            assert_eq!(None, set.get_index_of(&MyType(0)));
            assert!(!set.contains(&MyType(0)));

            assert_eq!(Some(1), set.get_index_of(&"1"));
            assert!(set.contains(&"1"));
            assert_eq!(Some(1), set.get_index_of(&MyType(1)));
            assert!(set.contains(&MyType(1)));
            assert_eq!(Some(0), set.get_index_of(&"2"));
            assert!(set.contains(&"2"));
            assert_eq!(Some(0), set.get_index_of(&MyType(2)));
            assert!(set.contains(&MyType(2)));
            assert_eq!(Some(2), set.get_index_of(&"3"));
            assert!(set.contains(&"3"));
            assert_eq!(Some(2), set.get_index_of(&MyType(3)));
            assert!(set.contains(&MyType(3)));
        }
        test::<1>(false);
        test::<3>(true);
    }

    // Type for testing equivalence to String
    struct MyType(usize);

    // Hash needs to be equivalent to String::hash
    impl Hash for MyType {
        fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
            self.0.to_string().hash(state);
        }
    }

    impl Equivalent<&'static str> for MyType {
        fn equivalent(&self, key: &&'static str) -> bool {
            &self.0.to_string() == key
        }
    }
}