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
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
#[doc(hidden)]
#[macro_export]
macro_rules! multimap_base_impl {
    ($keys:ty) => {
        /// Creates an empty multimap.
        ///
        /// The multimap is initially created with a capacity of 0, so it will
        /// not allocate until it is first inserted into.
        #[must_use]
        pub fn new() -> Self {
            Self {
                inner: <$keys>::new(),
                len: 0,
            }
        }

        /// Creates an empty multimap with the specified key capacity.
        ///
        /// The multimap will be able to hold at least `capacity` keys without
        /// reallocating. If `capacity` is 0, the multimap will not allocate.
        #[must_use]
        pub fn with_key_capacity(capacity: usize) -> Self {
            Self {
                inner: <$keys>::with_capacity(capacity),
                len: 0,
            }
        }
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! multimap_base2_impl {
    ($keys:tt) => {
        /// Creates an empty multimap which will use the given hash builder to hash
        /// keys.
        #[inline]
        pub fn with_hasher(hash_builder: S) -> Self {
            Self::with_key_capacity_and_hasher(0, hash_builder)
        }

        /// Creates an empty multimap with the specified capacity, using `hash_builder`
        /// to hash the keys.
        #[inline]
        pub fn with_key_capacity_and_hasher(n: usize, hash_builder: S) -> Self {
            Self {
                inner: $keys::with_capacity_and_hasher(n, hash_builder),
                len: 0,
            }
        }

        /// Returns the number of keys the multimap can hold without reallocating.
        #[inline]
        pub fn key_capacity(&self) -> usize {
            self.inner.capacity()
        }

        // TODO values_mut()

        // TODO iter_mut()

        /// Returns the number of elements in the multimap.
        ///
        /// Note that the number of elements in the multimap may not be the
        /// same as the number of keys in the multimap. See
        /// [`Self::keys_len()`].
        pub const fn len(&self) -> usize {
            self.len
        }

        /// Returns `true` if the multimap contains no elements.
        pub const fn is_empty(&self) -> bool {
            self.len == 0
        }

        /// Returns the number of keys in the multimap.
        ///
        /// Note that the number of keys in the multimap may not be the
        /// same as the number of elements in the multimap. See
        /// [`Self::len()`].
        pub fn keys_len(&self) -> usize {
            self.inner.len()
        }
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! multimap_mutators_impl {
    ($keys:ty, $values:ty, $values_ctx:expr, $values_class:tt, ($($keys_ref:tt)*), ($($values_ref:tt)*)) => {

        // TODO this method will have to be split out as it won't be needed in all implementations
        /// Reserve capacity for `additional` more keys.
        #[inline]
        pub fn reserve(&mut self, additional: usize) {
            self.inner.reserve(additional);
        }

        /// Shrinks the capacity of the multimap's keys as much as possible.
        /// It will drop down as much as possible while maintaining the
        /// internal rules and possibly leaving some space in accordance with
        /// the resize policy.
        #[inline]
        pub fn shrink_keys_to_fit(&mut self) {
            self.inner.shrink_to_fit();
        }

        /// Shrinks the capacity of the multimap's values as much as possible.
        /// It will drop down as much as possible while maintaining the
        /// internal rules and possibly leaving some space in accordance with
        /// the resize policy.
        pub fn shrink_values_to_fit(&mut self) {
            self.inner.iter_mut().for_each(|(_,values)| values.shrink_to_fit());
        }

        // TODO add shrink_keys_to for Hash*Multimaps
        // TODO add shrink_values_to for Vec, HashSet

        // TODO add entry()

        #[doc = concat!("Return a reference to the ", stringify!($values_class), " stored for `key`, if it is present, else `None`.")]
        #[inline]
        pub fn get<Q>(&self, key: &Q) -> Option<&$values>
        where
            Q: ?Sized,
            $($keys_ref)*,
        {
            self.inner.get(key)
        }

        /// Return references to the key-values pair stored for `key`, if it is
        /// present, else `None`.
        pub fn get_key_values<Q>(&self, key: &Q) -> Option<(&K, &$values)>
        where
            Q: ?Sized,
            $($keys_ref)*,
        {
            self.inner.get_key_value(key)
        }

        /// Returns `true` if the map contains a value for the specified key.
        #[inline]
        pub fn contains_key<Q>(&self, key: &Q) -> bool
        where
            Q: ?Sized,
            $($keys_ref)*,
        {
            self.get(key).is_some()
        }

        // TODO add get_mut() --> only if it is possible to keep internal `len` consistent

        $crate::insert!($values_class $values_ctx);

        /// Retains only the elements specified by the predicate.
        ///
        /// In other words, remove all pairs `(k, v)` such that `f(&k, &v)`
        /// returns `false`.
        #[inline]
        pub fn retain<F>(&mut self, f: F)
        where
            F: Fn(&K, &V) -> bool
        {
            self.inner.retain(|k,values| {
                values.retain(|x| {
                    let retain = f(k,x);
                    if !retain {
                        self.len -= 1;
                    }
                    retain
                });
                !values.is_empty()
            });
        }

        //////////////////////////////////////
        /// Multimap specific methods
        //////////////////////////////////////

        /// Return `true` if an equivalent `key` and `value` combination exists in
        /// the multimap.
        pub fn contains<Q, R>(&self, key: &Q, value: &R) -> bool
        where
            Q: ?Sized,
            R: ?Sized,
            $($keys_ref)*,
            $($values_ref)*,
        {
            if let Some(values) = self.inner.get(key) {
                $crate::values_contains!($values_class, values, value)
            } else {
                false
            }
        }

        /// Return a borrow of the underlying map.
        pub const fn as_map(&self) -> &$keys {
            &self.inner
        }

        /// Return the underlying map, the multimap cannot be used after
        /// calling this.
        pub fn into_map(self) -> $keys {
            self.inner
        }
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! multimap_remove_impl {
    (unordered, $values:ty, $values_class:tt, ($($keys_ref:tt)*), ($($values_ref:tt)*)) => {
        /// Remove the key and all associated values from the multimap.
        ///
        /// Returns values if at least one value is associated to `key`,
        /// returns `None` otherwise.
        #[inline]
        pub fn remove_key<Q>(&mut self, key: &Q) -> Option<$values>
        where
            Q: ?Sized,
            $($keys_ref)*
        {
            self.inner.remove(key).map(|values| {
                self.len -= values.len();
                values
            })
        }

        /// Removes the key and all associated values from the multimap.
        ///
        /// Returns the entry (key and all associated values) if at least one
        /// value is associated to `key`, returns `None` otherwise.
        #[inline]
        pub fn remove_key_entry<Q>(&mut self, key: &Q) -> Option<(K, $values)>
        where
            Q: ?Sized,
            $($keys_ref)*
        {
            self.inner.remove_entry(key).map( |(key,values)| {
                self.len -= values.len();
                (key,values)
            })
        }

        /// Remove the entry from the multimap, and return it if it was present.
        pub fn remove<Q, R>(&mut self, key: &Q, value: &R) -> Option<V>
        where
            Q: ?Sized,
            R: ?Sized,
            $($keys_ref)*,
            $($values_ref)*,
        {
            if let Some(values) = self.inner.get_mut(key) {
                let value = $crate::values_remove!(unordered, $values_class, values, value);
                if value.is_some() {
                    if values.is_empty() {
                        self.inner.remove(key);
                    }
                    self.len -= 1;
                }
                value
            } else {
                None
            }
        }

    };
    (ordered, $values:ty, $values_class:tt, ($($keys_ref:tt)*), ($($values_ref:tt)*)) => {
        /// Remove the key and all associated values from the multimap.
        ///
        /// Like [`IndexMap::swap_remove`], the key is removed by swapping it
        /// with the last element of the map and popping it off. **This
        /// perturbs the position of what used to be the last element!**
        ///
        /// Returns values if at least one value is associated to `key`,
        /// returns `None` otherwise.
        #[inline]
        pub fn swap_remove_key<Q>(&mut self, key: &Q) -> Option<$values>
        where
            Q: ?Sized,
            $($keys_ref)*
        {
            self.inner.swap_remove(key).map(|values| {
                self.len -= values.len();
                values
            })
        }

        /// Remove the key and all associated values from the multimap.
        ///
        /// Like [`IndexMap::shift_remove`], the key is removed by shifting all
        /// of the elements that follow it, preserving their relative order.
        /// **This perturbs the index of all of those elements!**
        ///
        /// Returns values if at least one value is associated to `key`,
        /// returns `None` otherwise.
        #[inline]
        pub fn shift_remove_key<Q>(&mut self, key: &Q) -> Option<$values>
        where
            Q: ?Sized,
            $($keys_ref)*
        {
            self.inner.shift_remove(key).map(|values| {
                self.len -= values.len();
                values
            })
        }

        /// Removes the key and all associated values from the multimap.
        ///
        /// Like [`IndexMap::swap_remove`], the key is removed by swapping it
        /// with the last element of the map and popping it off. **This
        /// perturbs the position of what used to be the last element!**
        ///
        /// Returns the entry (key and all associated values) if at least one
        /// value is associated to `key`, returns `None` otherwise.
        #[inline]
        pub fn swap_remove_key_entry<Q>(&mut self, key: &Q) -> Option<(K, $values)>
        where
            Q: ?Sized,
            $($keys_ref)*
        {
            self.inner.swap_remove_entry(key).map( |(key,values)| {
                self.len -= values.len();
                (key,values)
            })
        }

        /// Removes the key and all associated values from the multimap.
        ///
        /// Like [`IndexMap::shift_remove`], the key is removed by shifting all
        /// of the elements that follow it, preserving their relative order.
        /// **This perturbs the index of all of those elements!**
        ///
        /// Returns the entry (key and all associated values) if at least one
        /// value is associated to `key`, returns `None` otherwise.
        #[inline]
        pub fn shift_remove_key_entry<Q>(&mut self, key: &Q) -> Option<(K, $values)>
        where
            Q: ?Sized,
            $($keys_ref)*
        {
            self.inner.shift_remove_entry(key).map( |(key,values)| {
                self.len -= values.len();
                (key,values)
            })
        }

        /// Remove the entry from the multimap, and return it if it was present.
        ///
        /// Like [`IndexMap::swap_remove`], the pair is removed by swapping it
        /// with the last element of the map and popping it off. **This
        /// perturbs the position of what used to be the last element!**
        pub fn swap_remove<Q, R>(&mut self, key: &Q, value: &R) -> Option<V>
        where
            Q: ?Sized,
            R: ?Sized,
            $($keys_ref)*,
            $($values_ref)*,
        {
            if let Some(values) = self.inner.get_mut(key) {
                let value = $crate::values_remove!(ordered, swap, $values_class, values, value);
                if value.is_some() {
                    if values.is_empty() {
                        self.inner.swap_remove(key);
                    }
                    self.len -= 1;
                }
                value
            } else {
                None
            }
        }

        /// Remove the entry from the multimap, and return it if it was present.
        ///
        /// Like [`IndexMap::shift_remove`], the pair is removed by shifting all
        /// of the elements that follow it, preserving their relative order.
        /// **This perturbs the index of all of those elements!**
        pub fn shift_remove<Q, R>(&mut self, key: &Q, value: &R) -> Option<V>
        where
            Q: ?Sized,
            R: ?Sized,
            $($keys_ref)*,
            $($values_ref)*,
        {
            if let Some(values) = self.inner.get_mut(key) {
                let value = $crate::values_remove!(ordered, shift, $values_class, values, value);
                if value.is_some() {
                    if values.is_empty() {
                        self.inner.shift_remove(key);
                    }
                    self.len -= 1;
                }
                value
            } else {
                None
            }
        }
    }
}

//////////////////////////////////////
// IndexMap keys specific methods
//////////////////////////////////////

#[doc(hidden)]
#[macro_export]
macro_rules! index_multimap_impl {
    ($keys:ty, $values:ty, $values_ctx:expr, $values_class:tt, ($($keys_ref:tt)*), ($($values_ref:tt)*)) => {

        insert_full!($values_class $values_ctx);

        /// Return item index, key, and values.
        pub fn get_full<Q>(&self, key: &Q) -> Option<(usize, &K, &$values)>
        where
            Q: ?Sized,
            $($keys_ref)*,
        {
            self.inner.get_full(key)
        }

        /// Return key index if it exists in the map.
        pub fn get_key_index<Q>(&self, key: &Q) -> Option<usize>
        where
            Q: ?Sized,
            $($keys_ref)*,
        {
            if self.is_empty() {
                None
            } else {
                self.inner.get_index_of(key)
            }
        }

        /// Get a key-value pair by index, if it is present, else None.
        pub fn get_index(&self, index: usize) -> Option<(&K, &$values)> {
            if index >= self.inner.len() {
                None
            } else {
                self.inner.get_index(index)
            }
        }


    };
}

// TODO add get_full_mut()
// TODO add swap_remove()
// TODO add swap_remove_entry()
// TODO add swap_remove_full()
// TODO add shift_remove()
// TODO add shift_remove_entry()
// TODO add shift_remove_full()
// TODO add pop()
// TODO add sort_keys()
// TODO add sort_by()
// TODO add sorted_by()
// TODO add reverse()

// TODO add get_index()
// TODO add get_index_mut()
// TODO add first()
// TODO add first_mut()
// TODO add last()
// TODO add last_mut()
// TODO add swap_remove_index()
// TODO add shift_remove_index()
// TODO add swap_indices()

//////////////////////////////////////
/// *Set values specific methods
//////////////////////////////////////

// TODO add difference()
// TODO add symmetric_difference()
// TODO add intersection()
// TODO add union()
// TODO add is_disjoint()
// TODO add is_subset()
// TODO add is_superset()

//////////////////////////////////////
/// Vec / IndexSet values specific methods
//////////////////////////////////////

// TODO add sort_values()
// TODO add sort_values_by()
// TODO consider adding more mutators

#[doc(hidden)]
#[macro_export]
macro_rules! insert {
    (set $values_ctx:expr) => {
        /// Insert the value into the multimap.
        ///
        /// If an equivalent entry already exists in the multimap, it returns
        /// `false` leaving the original value in the set and without altering its
        /// insertion order. Otherwise, it inserts the new entry and returns `true`.
        #[inline]
        pub fn insert(&mut self, key: K, value: V) -> bool {
            if self
                .inner
                .entry(key)
                .or_insert_with(|| $values_ctx)
                .insert(value)
            {
                self.len += 1;
                true
            } else {
                false
            }
        }
    };

    (vec_equal $values_ctx:expr) => {
        $crate::vec_insert!($values_ctx);
    };
    (vec_equivalent $values_ctx:expr) => {
        $crate::vec_insert!($values_ctx);
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! vec_insert {
    ($values_ctx:expr) => {
        /// Insert the value into the multimap.
        ///
        /// Allows duplicates.
        #[inline]
        pub fn insert(&mut self, key: K, value: V) {
            self.inner
                .entry(key)
                .or_insert_with(|| $values_ctx)
                .push(value);
            self.len += 1;
        }
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! insert_full {
    (set $values_ctx:expr) => {
        /// Insert a key-value pair in the multimap, and get its indices.
        ///
        /// If an equivalent key already exists in the multimap, the key
        /// remains and retains its place in the order. Additionally, if an
        /// equivalent value already exists for that particular key the value
        /// remains and retains its place in the order, and `false` is
        /// returned.
        ///
        /// If no equivalent key existed in the multimap the new key is
        /// inserted last in order. If no equivalent value existed in the
        /// multimap for this key, the value is inserted last in order.
        ///
        /// Returns `(key index, values index, success)` where success is
        /// `true` if the multimap changes as a result of calling this method.
        pub fn insert_full(&mut self, key: K, value: V) -> (usize, usize, bool) {
            match self.inner.get_full_mut(&key) {
                Some((keys_index, _, values)) => {
                    let (values_index, success) = values.insert_full(value);
                    if success {
                        self.len += 1;
                    }
                    (keys_index, values_index, success)
                }
                None => {
                    let mut values = $values_ctx;
                    values.insert(value);
                    let (keys_index, _) = self.inner.insert_full(key, values);
                    self.len += 1;
                    (keys_index, 0, true)
                }
            }
        }
    };
    (vec $values_ctx:expr) => {
        /// Insert a key-value pair in the multimap, and get its indices.
        ///
        /// If an equivalent key already exists in the multimap, the key
        /// remains and retains its place in the order. If no equivalent key
        /// existed in the multimap the new key is inserted last in order.
        ///
        /// The value is inserted last in order in the values for this
        /// particular key (duplicates are allowed).
        ///
        /// Returns `(key index, values index)`
        pub fn insert_full(&mut self, key: K, value: V) -> (usize, usize) {
            match self.inner.get_full_mut(&key) {
                Some((keys_index, _, values)) => {
                    let values_index = values.len();
                    values.push(value);
                    self.len += 1;
                    (keys_index, values_index)
                }
                None => {
                    let values = vec![value];
                    let (keys_index, _) = self.inner.insert_full(key, values);
                    self.len += 1;
                    (keys_index, 0)
                }
            }
        }
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! values_contains {
    (set, $values:ident, $value:ident) => {
        $values.contains($value)
    };

    (vec_equivalent, $values:ident, $value:ident) => {
        $values.iter().find(|x| $value.equivalent(x)).is_some()
    };

    (vec_equal, $values:ident, $value:ident) => {
        $values.iter().find(|&x| $value == x.borrow()).is_some()
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! values_remove {
    // ordered keys, values set
    (ordered, swap, set, $values:ident, $value:ident) => {
        $values.swap_take($value)
    };
    (ordered, shift, set, $values:ident, $value:ident) => {
        $values.shift_take($value)
    };
    // ordered keys, values vec
    (ordered, shift, vec_equivalent, $values:ident, $value:ident) => {
        $values
            .iter()
            .position(|x| $value.equivalent(x))
            .map(|index| $values.remove(index)) // Vec::remove() shifts
    };
    (ordered, swap, vec_equivalent, $values:ident, $value:ident) => {
        $values
            .iter()
            .position(|x| $value.equivalent(x))
            .map(|index| $values.swap_remove(index))
    };
    // unordered keys, values set
    (unordered, set, $values:ident, $value:ident) => {
        $values.take($value)
    };
    // unordered keys, values vec
    (unordered, vec_equal, $values:ident, $value:ident) => {
        $values
            .iter()
            .position(|x| $value == x.borrow())
            .map(|index| $values.remove(index))
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! multimap_extend {
    ($type:tt, ($($generic_ids:tt)*), $inner_keys_type:tt, $inner_values_type:ty, ($($keys:tt)*), ($($values:tt)*), ($($keys_get:tt)*) )=> {
        impl<$($generic_ids)*> Extend<(K, V)> for $type<$($generic_ids)*>
        where
            $($keys)*,
            $($values)*,
            S: BuildHasher + Default,
        {
            fn extend<I: IntoIterator<Item = (K, V)>>(&mut self, iterable: I) {
                let iter = iterable.into_iter();
                let reserve = (iter.size_hint().0 + 1) / 2;
                self.reserve(reserve);
                iter.for_each(move |(k, v)| {
                    self.insert(k, v);
                });
            }
        }

        impl<'a, $($generic_ids)*> Extend<(&'a K, &'a V)> for $type<$($generic_ids)*>
        where
            $($keys)* + Copy,
            $($values)* + Copy,
            S: BuildHasher + Default,
        {
            fn extend<I: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iterable: I) {
                self.extend(iterable.into_iter().map(|(&key, &value)| (key, value)));
            }
        }

        impl<$($generic_ids)*> FromIterator<(K, V)> for $type<$($generic_ids)*>
        where
            $($keys)*,
            $($values)*,
            S: BuildHasher + Default,
        {
            fn from_iter<I: IntoIterator<Item = (K, V)>>(iterable: I) -> Self {
                let iter = iterable.into_iter();
                let (low, _) = iter.size_hint();
                // TODO this resizing has a high chance of over provisioning
                let mut map = Self::with_key_capacity_and_hasher(low, <_>::default());
                map.extend(iter);
                map
            }
        }

        impl<$($generic_ids)*> From<$inner_keys_type<K,$inner_values_type,S>> for $type<$($generic_ids)*>
        where
            $($keys)*,
            $($values)*,
            S: BuildHasher + Default,
        {
            fn from(mut map: $inner_keys_type<K,$inner_values_type,S>) -> Self {
                map.retain(|_k, v| !v.is_empty());
                let len = map.iter().map(|(_k, v)| v.len()).sum();
                $type { inner: map, len }
            }
        }

        impl<$($generic_ids)*> Default for $type<$($generic_ids)*>
        where
            S: Default,
        {
            /// Creates an empty multimap, with the `Default` value for the hasher.
            #[inline]
            fn default() -> $type<$($generic_ids)*> {
                $type::with_hasher(Default::default())
            }
        }

        impl<K, Q: ?Sized, V, S> std::ops::Index<&Q> for $type<$($generic_ids)*>
        where
            $($keys_get)*,
            $($values)*,
            S: BuildHasher + Default,
        {
            type Output = $inner_values_type;

            /// Returns a reference to the values container corresponding to the supplied key.
            ///
            /// # Panics
            ///
            /// Panics if the key is not present in the multimap.
            #[inline]
            fn index(&self, key: &Q) -> &$inner_values_type {
                self.get(key).expect("no entry found for key")
            }
        }
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! multimap_eq {
    ($type:tt, ($($values_generics:tt)*)) => {
        impl<K, V1, S1, V2, S2> PartialEq<$type<K, V2, S2>> for $type<K, V1, S1>
        where
            K: Hash + Eq,
            V1: $($values_generics)* + PartialEq<V2> + Borrow<V2>,
            V2: $($values_generics)* + PartialEq<V1> + Borrow<V1>,
            S1: BuildHasher + Default,
            S2: BuildHasher + Default,
        {
            fn eq(&self, other: &$type<K, V2, S2>) -> bool {
                if self.len() != other.len() {
                    return false;
                }
                self.iter().all(|(key, value)| other.contains(key, value))
            }
        }

        impl<K, V, S> Eq for $type<K, V, S>
        where
            K: Eq + Hash,
            V: $($values_generics)*,
            S: BuildHasher + Default,
        {
        }
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! impl_iter {
    ($type:tt, ($($generic_ids:tt)*), $outer_iter:ty, $inner_iter:ty) => {
        /// An iterator over the entries of a multimap.
        ///
        /// This struct is created by the `iter` method on multimap.
        pub struct Iter<'a, $($generic_ids)*> where K: 'a, V: 'a{
            outer: $outer_iter,
            inner: Option<(&'a K, $inner_iter)>,
            len: usize,
        }

        impl<'a, $($generic_ids)*> Iterator for Iter<'a, $($generic_ids)*> {
            type Item = (&'a K, &'a V);

            fn next(&mut self) -> Option<Self::Item> {
                if let Some((current_key, inner_iter)) = &mut self.inner {
                    let next = inner_iter.next();

                    if let Some(next_value) = next {
                        Some((current_key, next_value))
                    } else {
                        if let Some((key, values)) = self.outer.next() {
                            let mut new_inner_iter = values.iter();
                            let v = new_inner_iter.next().unwrap();
                            self.inner = Some((key, new_inner_iter));

                            Some((key, v))
                        } else {
                            None
                        }
                    }
                } else {
                    None
                }
            }
        }

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

        impl<$($generic_ids)*> std::iter::FusedIterator for Iter<'_, $($generic_ids)*> {}

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

        impl<$($generic_ids)*> std::fmt::Debug for Iter<'_, $($generic_ids)*>
        where
            K: std::fmt::Debug,
            V: std::fmt::Debug,
        {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                f.debug_list().entries(self.clone()).finish()
            }
        }

        /// An iterator over the values of a multimap.
        ///
        /// This `struct` is created by the `values` method on multimap.
        pub struct Values<'a, $($generic_ids)*>{
            inner: Iter<'a, $($generic_ids)*>,
        }

        impl<'a, $($generic_ids)*> Iterator for Values<'a, $($generic_ids)*>
        {
            type Item = &'a V;

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

        impl<$($generic_ids)*> ExactSizeIterator for Values<'_, $($generic_ids)*> {
            fn len(&self) -> usize {
                self.inner.len()
            }
        }

        impl<$($generic_ids)*> std::iter::FusedIterator for Values<'_, $($generic_ids)*> {}

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

        impl<$($generic_ids)*> std::fmt::Debug for Values<'_, $($generic_ids)*>
        where
            V: std::fmt::Debug,
        {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                f.debug_list().entries(self.clone()).finish()
            }
        }

        impl<K, V, S> $type<K, V, S> {
            /// Return an iterator over the key-value pairs of the multimap.
            pub fn iter(&self) -> Iter<'_, $($generic_ids)*> {
                let mut iter = self.inner.iter();
                let inner = iter.next().map(|(k, v)| (k, v.iter()));
                Iter {
                    outer: iter,
                    inner,
                    len: self.len,
                }
            }

            /// Return an iterator over the values of the multimap.
            pub fn values(&self) -> Values<'_, $($generic_ids)*> {
                Values {
                    inner: self.iter(),
                }
            }
        }

        impl<'a, K, V, S> IntoIterator for &'a $type<K, V, S> {
            type IntoIter = Iter<'a, $($generic_ids)*>;
            type Item = (&'a K, &'a V);
            fn into_iter(self) -> Self::IntoIter {
                self.iter()
            }
        }
    }
}

#[doc(hidden)]
#[macro_export]
macro_rules! impl_keys {
    ($type:tt, ($($generic_ids:tt)*), $inner_iter:ty) => {
        /// An iterator over the keys of a multimap.
        ///
        /// This `struct` is created by the `keys` method on multimap.
        pub struct Keys<'a, $($generic_ids)*> {
            inner: $inner_iter,
        }

        impl<'a, $($generic_ids)*> Iterator for Keys<'a, $($generic_ids)*> {
            type Item = &'a K;

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

        impl<$($generic_ids)*> ExactSizeIterator for Keys<'_, $($generic_ids)*> {
            fn len(&self) -> usize {
                self.inner.len()
            }
        }

        impl<$($generic_ids)*> std::iter::FusedIterator for Keys<'_, $($generic_ids)*> {}

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

        impl<$($generic_ids)*> std::fmt::Debug for Keys<'_, $($generic_ids)*>
        where
            K: std::fmt::Debug,
        {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                f.debug_list().entries(self.clone()).finish()
            }
        }

        impl<K, V, S> $type<K, V, S> {
            /// Return an iterator over the keys of the multimap.
            pub fn keys(&self) -> Keys<'_, $($generic_ids)*> {
                Keys {
                    inner: self.inner.keys(),
                }
            }
        }
    }
}

#[doc(hidden)]
#[macro_export]
macro_rules! impl_into_iterator {
    ($type:tt, ($($generic_ids:tt)*), $outer_iter:ty, $inner_iter:ty) => {
        /// An owning iterator over the entries of a multimap.
        #[derive(Debug)]
        pub struct IntoIter<$($generic_ids)*> {
            outer: $outer_iter,
            inner: Option<(K, $inner_iter)>,
            len: usize,
        }

        impl<$($generic_ids)*> Iterator for IntoIter<$($generic_ids)*>
        where
            K: Clone,
        {
            type Item = (K, V);

            fn next(&mut self) -> Option<Self::Item> {
                if let Some((current_key, inner_iter)) = &mut self.inner {
                    let next = inner_iter.next();

                    if let Some(next_value) = next {
                        Some((current_key.clone(), next_value))
                    } else {
                        if let Some((key, values)) = self.outer.next() {
                            let mut new_inner_iter = values.into_iter();
                            let v = new_inner_iter.next().unwrap();
                            self.inner = Some((key.clone(), new_inner_iter));

                            Some((key, v))
                        } else {
                            None
                        }
                    }
                } else {
                    None
                }
            }
        }

        impl<$($generic_ids)*> ExactSizeIterator for IntoIter<$($generic_ids)*>
        where
            K: Clone,
        {
            fn len(&self) -> usize {
                self.len
            }
        }

        impl<$($generic_ids)*> std::iter::FusedIterator for IntoIter<$($generic_ids)*>
        where
           K: Clone,
        {}

        impl<K, V, S> IntoIterator for $type<K, V, S>
        where
            K: Clone,
        {
            type Item = (K, V);

            type IntoIter = IntoIter<$($generic_ids)*>;

            fn into_iter(self) -> Self::IntoIter {
                let mut iter = self.inner.into_iter();
                let inner = iter.next().map(|(k, v)| (k, v.into_iter()));
                IntoIter {
                    outer: iter,
                    inner,
                    len: self.len,
                }
            }
        }

        /// An owning iterator over the values of a multimap.
        ///
        /// This `struct` is created by the `into_values` method on multimap.
        #[derive(Debug)]
        pub struct IntoValues<$($generic_ids)*> {
            outer: $outer_iter,
            inner: Option<$inner_iter>,
            len: usize,
        }

        impl<$($generic_ids)*> Iterator for IntoValues<$($generic_ids)*>        {
            type Item = V;

            fn next(&mut self) -> Option<Self::Item> {
                if let Some(inner_iter) = &mut self.inner {
                    let next = inner_iter.next();

                    if let Some(next_value) = next {
                        Some(next_value)
                    } else {
                        if let Some((_key, values)) = self.outer.next() {
                            let mut new_inner_iter = values.into_iter();
                            let v = new_inner_iter.next().unwrap();
                            self.inner = Some(new_inner_iter);
                            Some(v)
                        } else {
                            None
                        }
                    }
                } else {
                    None
                }
            }
        }

        impl<$($generic_ids)*> ExactSizeIterator for IntoValues<$($generic_ids)*> {
            fn len(&self) -> usize {
                self.len
            }
        }

        impl<$($generic_ids)*> std::iter::FusedIterator for IntoValues<$($generic_ids)*> {}

        impl<K, V, S> $type<K, V, S> {
            /// Return an iterator over the values of the multimap.
            pub fn into_values(self) -> IntoValues<$($generic_ids)*> {
                let mut iter = self.inner.into_iter();
                let inner = iter.next().map(|(_k, v)| v.into_iter());
                IntoValues {
                    outer: iter,
                    inner,
                    len: self.len,
                }
            }
        }
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! impl_into_keys {
    ($type:tt, ($($generic_ids:tt)*), $inner_iter:ty) => {
        /// An owning iterator over the keys of a multimap.
        ///
        /// This `struct` is created by the `into_keys` method on multimap.
        #[derive(Debug)]
        pub struct IntoKeys<$($generic_ids)*> {
            inner: $inner_iter,
        }

        impl<$($generic_ids)*> Iterator for IntoKeys<$($generic_ids)*> {
            type Item = K;

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

        impl<$($generic_ids)*> ExactSizeIterator for IntoKeys<$($generic_ids)*> {
            fn len(&self) -> usize {
                self.inner.len()
            }
        }

        impl<$($generic_ids)*> std::iter::FusedIterator for IntoKeys<$($generic_ids)*> {}

        impl<K, V, S> $type<K, V, S> {
            /// Return an owning iterator over the keys of the multimap.
            pub fn into_keys(self) -> IntoKeys<$($generic_ids)*> {
                IntoKeys {
                    inner: self.inner.into_keys(),
                }
            }
        }
    }
}