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
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
//! A map from byte strings to arbitrary values, based on a prefix tree.

use core::mem;
use core::iter::FusedIterator;
use core::fmt::{self, Debug, Formatter};
use core::ops::{Index, BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign};


/// An ordered map from byte strings to arbitrary values, based on a prefix tree.
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct PrefixTreeMap<K, V> {
    root: Node<K, V>,
    len: usize,
}

impl<K, V> Default for PrefixTreeMap<K, V> {
    fn default() -> Self {
        PrefixTreeMap::new()
    }
}

impl<K, V> PrefixTreeMap<K, V> {
    /// Creates an empty map. The same as `Default`.
    pub const fn new() -> Self {
        PrefixTreeMap { root: Node::root(), len: 0 }
    }

    /// Returns the number of entries (key-value pairs) in the map.
    pub const fn len(&self) -> usize {
        self.len
    }

    /// Returns `true` if and only if this map contains no key-value pairs.
    pub const fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// Return a reference to the original key and value, if found.
    pub fn get_entry<Q>(&self, key: &Q) -> Option<(&K, &V)>
    where
        Q: ?Sized + AsRef<[u8]>,
    {
        self.root
            .search(key.as_ref().iter().copied())
            .and_then(Node::item)
    }

    /// Return a reference to the original key and a mutable reference to the value, if found.
    pub fn get_entry_mut<Q>(&mut self, key: &Q) -> Option<(&K, &mut V)>
    where
        Q: ?Sized + AsRef<[u8]>,
    {
        self.root
            .search_mut(key.as_ref().iter().copied())
            .and_then(Node::item_mut)
    }

    /// Return a reference to the value, if found.
    pub fn get<Q>(&self, key: &Q) -> Option<&V>
    where
        Q: ?Sized + AsRef<[u8]>,
    {
        self.root
            .search(key.as_ref().iter().copied())
            .and_then(Node::value)
    }

    /// Return a mutable reference to the value, if found.
    pub fn get_mut<Q>(&mut self, key: &Q) -> Option<&mut V>
    where
        Q: ?Sized + AsRef<[u8]>,
    {
        self.root
            .search_mut(key.as_ref().iter().copied())
            .and_then(Node::value_mut)
    }

    /// Returns `true` if and only if the given key is found in the map.
    pub fn contains_key<Q>(&self, key: &Q) -> bool
    where
        Q: ?Sized + AsRef<[u8]>,
    {
        self.root
            .search(key.as_ref().iter().copied())
            .is_some_and(|node| node.item.is_some())
    }

    /// If the key exists in the map, return the original key and the correpsonding value.
    pub fn remove_entry<Q>(&mut self, key: &Q) -> Option<(K, V)>
    where
        Q: ?Sized + AsRef<[u8]>,
    {
        let node = self.root.search_mut(key.as_ref().iter().copied())?;
        let item = node.item.take()?;
        self.len -= 1;
        Some(item)
    }

    /// If the key exists in the map, return the corresponding value.
    pub fn remove<Q>(&mut self, key: &Q) -> Option<V>
    where
        Q: ?Sized + AsRef<[u8]>,
    {
        self.remove_entry(key).map(|(_key, value)| value)
    }

    /// An iterator over pairs of references to keys and the corresponding values.
    ///
    /// Iteration proceeds in lexicographic order, as determined by the byte sequence of keys.
    pub fn iter(&self) -> Iter<'_, K, V> {
        Iter { iter: self.root.iter(), len: self.len }
    }

    /// An iterator over the owned keys.
    ///
    /// Iteration proceeds in lexicographic order, as determined by the byte sequence of keys.
    pub fn into_keys(self) -> IntoKeys<K, V> {
        IntoKeys { iter: self.into_iter() }
    }

    /// An iterator over the borrowed keys.
    ///
    /// Iteration proceeds in lexicographic order, as determined by the byte sequence of keys.
    pub fn keys(&self) -> Keys<'_, K, V> {
        Keys { iter: self.iter() }
    }

    /// An iterator over the owned values.
    ///
    /// Iteration proceeds in lexicographic order, as determined by the byte sequence of keys.
    pub fn into_values(self) -> IntoValues<K, V> {
        IntoValues { iter: self.into_iter() }
    }

    /// An iterator over the borrowed values.
    ///
    /// Iteration proceeds in lexicographic order, as determined by the byte sequence of keys.
    pub fn values(&self) -> Values<'_, K, V> {
        Values { iter: self.iter() }
    }

    /// An iterator over owned key-value pairs of which the key starts with the given prefix.
    ///
    /// Iteration proceeds in lexicographic order, as determined by the byte sequence of keys.
    pub fn into_prefix_iter<Q>(mut self, prefix: &Q) -> NodeIntoIter<K, V>
    where
        Q: ?Sized + AsRef<[u8]>
    {
        self.root
            .search_mut(prefix.as_ref().iter().copied())
            .map(|node| mem::take(node).into_iter())
            .unwrap_or_default()
    }

    /// An iterator over borrowed key-value pairs of which the key starts with the given prefix.
    ///
    /// Iteration proceeds in lexicographic order, as determined by the byte sequence of keys.
    pub fn prefix_iter<Q>(&self, prefix: &Q) -> NodeIter<'_, K, V>
    where
        Q: ?Sized + AsRef<[u8]>
    {
        self.root
            .search(prefix.as_ref().iter().copied())
            .map(Node::iter)
            .unwrap_or_default()
    }

    /// Removes all internal nodes that do not contain an entry.
    ///
    /// This is useful for freeing up memory and speeding up iteration after
    /// removing many key-value pairs from the map and/or after creating many
    /// spurious nodes using the entry API (by not inserting into the nodes
    /// created by `.entry()`).
    pub fn compact(&mut self) {
        self.root.compact();
    }
}

impl<K, V> PrefixTreeMap<K, V>
where
    K: AsRef<[u8]>
{
    /// Return an object representing the (vacant or occupied) node of the tree
    /// corresponding to the given key.
    ///
    /// This always creates a new node, even if you don't end up inserting into
    /// it. Avoid creating many spurious entries, or call [`PrefixTreeMap::compact`]
    /// to remove useless (empty) nodes.
    pub fn entry(&mut self, key: K) -> Entry<'_, K, V> {
        let node = self.root.search_or_insert(key.as_ref().iter().copied());
        let slot = &mut node.item;
        let len = &mut self.len;

        if slot.is_some() {
            Entry::Occupied(OccupiedEntry { slot, len })
        } else {
            Entry::Vacant(VacantEntry { key, slot, len })
        }
    }

    /// Replaces and returns the previous value, if any.
    ///
    /// This leaves the key in the map untouched if it already exists.
    pub fn insert(&mut self, key: K, value: V) -> Option<V> {
        match self.entry(key) {
            Entry::Vacant(entry) => {
                entry.insert(value);
                None
            }
            Entry::Occupied(mut entry) => Some(entry.insert(value))
        }
    }

    /// Takes the union of `self` with another set of elements.
    /// Elements that already exist in `self` will be overwritten by `other`.
    pub fn union<I>(mut self, other: I) -> Self
    where
        I: IntoIterator<Item = (K, V)>,
    {
        self.union_in_place(other);
        self
    }

    /// Takes the union of `self` with another set of elements.
    /// Elements that already exist in `self` will be overwritten by `other`.
    pub fn union_in_place<I>(&mut self, other: I)
    where
        I: IntoIterator<Item = (K, V)>,
    {
        for (key, value) in other {
            self.insert(key, value);
        }
    }

    /// Takes the intersection of `self` with another set of elements.
    /// The intersection is solely based on the keys.
    pub fn intersection<I>(mut self, other: I) -> Self
    where
        I: IntoIterator,
        I::Item: AsRef<[u8]>,
    {
        other
            .into_iter()
            .filter_map(|key| self.remove_entry(&key))
            .collect()
    }

    /// Removes the items corresponding to keys in `other` from `self`.
    pub fn difference<I>(mut self, other: I) -> Self
    where
        I: IntoIterator,
        I::Item: AsRef<[u8]>,
    {
        self.difference_in_place(other);
        self
    }

    /// Removes the items corresponding to keys in `other` from `self`.
    pub fn difference_in_place<I>(&mut self, other: I)
    where
        I: IntoIterator,
        I::Item: AsRef<[u8]>,
    {
        for key in other {
            self.remove(&key);
        }
    }

    /// Add elements that are missing from `self`, and remove elements contained in `self`.
    ///
    /// Containment is tested by comparing keys only. Values are not checked for equality.
    pub fn symmetric_difference<I>(mut self, other: I) -> Self
    where
        I: IntoIterator<Item = (K, V)>,
    {
        self.symmetric_difference_in_place(other);
        self
    }

    /// Add elements that are missing from `self`, and remove elements contained in `self`.
    ///
    /// Containment is tested by comparing keys only. Values are not checked for equality.
    pub fn symmetric_difference_in_place<I>(&mut self, other: I)
    where
        I: IntoIterator<Item = (K, V)>,
    {
        for (key, value) in other {
            match self.entry(key) {
                Entry::Occupied(entry) => { entry.remove(); }
                Entry::Vacant(entry) => { entry.insert(value); }
            }
        }
    }
}

impl<K, V, Q> Index<&Q> for PrefixTreeMap<K, V>
where
    K: AsRef<[u8]>,
    Q: ?Sized + AsRef<[u8]>
{
    type Output = V;

    fn index(&self, key: &Q) -> &Self::Output {
        self.get(key).expect("key not found in PrefixTreeMap")
    }
}

impl<K, V, const N: usize> From<[(K, V); N]> for PrefixTreeMap<K, V>
where
    K: AsRef<[u8]>
{
    fn from(items: [(K, V); N]) -> Self {
        items.into_iter().collect()
    }
}

impl<K, V> FromIterator<(K, V)> for PrefixTreeMap<K, V>
where
    K: AsRef<[u8]>
{
    fn from_iter<I>(iter: I) -> Self
    where
        I: IntoIterator<Item = (K, V)>
    {
        let mut map = PrefixTreeMap::default();
        map.extend(iter);
        map
    }
}

impl<K, V> Extend<(K, V)> for PrefixTreeMap<K, V>
where
    K: AsRef<[u8]>
{
    fn extend<I>(&mut self, iter: I)
    where
        I: IntoIterator<Item = (K, V)>
    {
        self.union_in_place(iter);
    }
}

impl<K, V> IntoIterator for PrefixTreeMap<K, V> {
    type IntoIter = IntoIter<K, V>;
    type Item = (K, V);

    fn into_iter(self) -> Self::IntoIter {
        IntoIter {
            iter: self.root.into_iter(),
            len: self.len,
        }
    }
}

impl<'a, K, V> IntoIterator for &'a PrefixTreeMap<K, V> {
    type IntoIter = Iter<'a, K, V>;
    type Item = (&'a K, &'a V);

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

/// Creates the intersection of `self` and `other`.
impl<I, K, V> BitAndAssign<I> for PrefixTreeMap<K, V>
where
    I: IntoIterator,
    I::Item: AsRef<[u8]>,
    K: AsRef<[u8]>,
{
    fn bitand_assign(&mut self, other: I) {
        let map = mem::take(self);
        *self = map.intersection(other);
    }
}

/// Creates the union of `self` and `other`.
impl<I, K, V> BitOrAssign<I> for PrefixTreeMap<K, V>
where
    I: IntoIterator<Item = (K, V)>,
    K: AsRef<[u8]>,
{
    fn bitor_assign(&mut self, other: I) {
        self.union_in_place(other);
    }
}

/// Creates the symmetric difference of `self` and `other`.
impl<I, K, V> BitXorAssign<I> for PrefixTreeMap<K, V>
where
    I: IntoIterator<Item = (K, V)>,
    K: AsRef<[u8]>,
{
    fn bitxor_assign(&mut self, other: I) {
        self.symmetric_difference_in_place(other);
    }
}

/// Creates the intersection of `self` and `other`.
impl<I, K, V> BitAnd<I> for PrefixTreeMap<K, V>
where
    I: IntoIterator,
    I::Item: AsRef<[u8]>,
    K: AsRef<[u8]>,
{
    type Output = Self;

    fn bitand(self, other: I) -> Self::Output {
        self.intersection(other)
    }
}

/// Creates the union of `self` and `other`.
impl<I, K, V> BitOr<I> for PrefixTreeMap<K, V>
where
    I: IntoIterator<Item = (K, V)>,
    K: AsRef<[u8]>,
{
    type Output = Self;

    fn bitor(mut self, other: I) -> Self::Output {
        self |= other;
        self
    }
}

/// Creates the symmetric difference of `self` and `other`.
impl<I, K, V> BitXor<I> for PrefixTreeMap<K, V>
where
    I: IntoIterator<Item = (K, V)>,
    K: AsRef<[u8]>,
{
    type Output = Self;

    fn bitxor(mut self, other: I) -> Self::Output {
        self ^= other;
        self
    }
}

impl<K, V> Debug for PrefixTreeMap<K, V>
where
    K: Debug,
    V: Debug,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.debug_map().entries(self).finish()
    }
}

#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
struct Node<K, V> {
    item: Option<(K, V)>,
    key_fragment: u8,
    children: Vec<Node<K, V>>,
}

impl<K, V> Node<K, V> {
    const fn root() -> Self {
        // key of root doesn't matter so we are free to use any value
        Node::with_key_fragment(0)
    }

    const fn with_key_fragment(key_fragment: u8) -> Self {
        Node {
            item: None,
            key_fragment,
            children: Vec::new(),
        }
    }

    /// Deletes leaves/subtrees with only empty nodes. A node is empty
    /// if its item is `None` and all of its children are empty.
    fn compact(&mut self) -> bool {
        let mut has_useful_children = false;

        self.children.retain_mut(|child| {
            let is_useful = child.compact();
            has_useful_children |= is_useful;
            is_useful
        });

        has_useful_children || self.item.is_some()
    }
}

impl<K, V> Node<K, V> {
    fn value(&self) -> Option<&V> {
        self.item.as_ref().map(|(_key, value)| value)
    }

    fn value_mut(&mut self) -> Option<&mut V> {
        self.item.as_mut().map(|(_key, value)| value)
    }

    fn item(&self) -> Option<(&K, &V)> {
        self.item.as_ref().map(|(key, value)| (key, value))
    }

    fn item_mut(&mut self) -> Option<(&K, &mut V)> {
        self.item.as_mut().map(|(key, value)| (&*key, value))
    }

    fn search<B>(&self, mut bytes: B) -> Option<&Self>
    where
        B: Iterator<Item = u8>,
    {
        let Some(byte) = bytes.next() else {
            return Some(self);
        };

        let index = self.children.binary_search_by_key(&byte, |node| node.key_fragment).ok()?;

        self.children[index].search(bytes)
    }

    fn search_mut<B>(&mut self, mut bytes: B) -> Option<&mut Self>
    where
        B: Iterator<Item = u8>,
    {
        let Some(byte) = bytes.next() else {
            return Some(self);
        };

        let index = self.children.binary_search_by_key(&byte, |node| node.key_fragment).ok()?;

        self.children[index].search_mut(bytes)
    }

    fn search_or_insert<B>(&mut self, mut bytes: B) -> &mut Self
    where
        B: Iterator<Item = u8>,
    {
        let Some(byte) = bytes.next() else {
            return self;
        };

        let index = match self.children.binary_search_by_key(&byte, |node| node.key_fragment) {
            Ok(index) => index,
            Err(index) => {
                self.children.insert(index, Node::with_key_fragment(byte));
                index
            }
        };

        self.children[index].search_or_insert(bytes)
    }

    fn into_iter(self) -> NodeIntoIter<K, V> {
        let item = self.item;
        let mut children_iter = self.children.into_iter();
        let curr_child_iter = children_iter.next().map(|node| {
            Box::new(node.into_iter())
        });

        NodeIntoIter {
            item,
            children_iter,
            curr_child_iter,
        }
    }

    fn iter(&self) -> NodeIter<'_, K, V> {
        let item = self.item.as_ref();
        let mut children_iter = self.children.iter();
        let curr_child_iter = children_iter.next().map(|node| {
            Box::new(node.iter())
        });

        NodeIter {
            item,
            children_iter,
            curr_child_iter,
        }
    }
}

/// The default impl returns the same value as `Node::root()`,
/// and its only purpose is to make `mem::take()` work.
impl<K, V> Default for Node<K, V> {
    fn default() -> Self {
        Node::root()
    }
}

/// An entry, representing a vacant or occupied node in the tree,
/// corresponding to a specific key.
///
/// The API is almost exactly the same as that of [`std::collections::btree_map::Entry`].
#[derive(Debug)]
pub enum Entry<'a, K, V> {
    Vacant(VacantEntry<'a, K, V>),
    Occupied(OccupiedEntry<'a, K, V>),
}

impl<'a, K, V> Entry<'a, K, V> {
    pub fn key(&self) -> &K {
        match self {
            Entry::Vacant(entry) => entry.key(),
            Entry::Occupied(entry) => entry.key(),
        }
    }

    pub fn or_insert_with_key<F>(self, default: F) -> &'a mut V
    where
        F: FnOnce(&K) -> V
    {
        match self {
            Entry::Vacant(entry) => {
                let value = default(&entry.key);
                entry.insert(value)
            }
            Entry::Occupied(entry) => entry.into_mut(),
        }
    }

    pub fn or_insert_with<F>(self, default: F) -> &'a mut V
    where
        F: FnOnce() -> V
    {
        self.or_insert_with_key(|_| default())
    }

    // this trips Clippy up for some reason? Clearly I can't just call myself unconditionally...
    #[allow(clippy::unwrap_or_default)]
    pub fn or_default(self) -> &'a mut V
    where
        V: Default
    {
        self.or_insert_with(V::default)
    }

    pub fn or_insert(self, value: V) -> &'a mut V {
        self.or_insert_with_key(|_| value)
    }

    pub fn and_modify<F>(self, f: F) -> Self
    where
        F: FnOnce(&mut V)
    {
        if let Entry::Occupied(mut entry) = self {
            f(entry.get_mut());
            Entry::Occupied(entry)
        } else {
            self
        }
    }

    pub fn remove_entry(self) -> Option<(K, V)> {
        if let Entry::Occupied(entry) = self {
            Some(entry.remove_entry())
        } else {
            None
        }
    }

    pub fn remove(self) -> Option<V> {
        if let Entry::Occupied(entry) = self {
            Some(entry.remove())
        } else {
            None
        }
    }
}

/// An entry that does not yet correspond to a value.
#[derive(Debug)]
pub struct VacantEntry<'a, K, V> {
    key: K,
    /// always starts out as `None` upon construction
    slot: &'a mut Option<(K, V)>,
    len: &'a mut usize,
}

impl<'a, K, V> VacantEntry<'a, K, V> {
    pub fn insert(self, value: V) -> &'a mut V {
        let (_key, value) = self.slot.insert((self.key, value));
        *self.len += 1;
        value
    }

    pub fn into_key(self) -> K {
        self.key
    }

    pub fn key(&self) -> &K {
        &self.key
    }
}

/// An entry that already contains a value.
#[derive(Debug)]
pub struct OccupiedEntry<'a, K, V> {
    /// always starts out as `Some` upon construction
    slot: &'a mut Option<(K, V)>,
    len: &'a mut usize,
}

impl<'a, K, V> OccupiedEntry<'a, K, V> {
    pub fn key(&self) -> &K {
        &self.slot.as_ref().expect("item in occupied entry").0
    }

    pub fn get(&self) -> &V {
        &self.slot.as_ref().expect("item in occupied entry").1
    }

    pub fn get_mut(&mut self) -> &mut V {
        &mut self.slot.as_mut().expect("item in occupied entry").1
    }

    pub fn into_mut(self) -> &'a mut V {
        &mut self.slot.as_mut().expect("item in occupied entry").1
    }

    /// Replaces the inner value with `value` and returns the old value.
    pub fn insert(&mut self, value: V) -> V {
        mem::replace(self.get_mut(), value)
    }

    pub fn remove_entry(self) -> (K, V) {
        *self.len -= 1;
        self.slot.take().expect("item in occupied entry")
    }

    pub fn remove(self) -> V {
        self.remove_entry().1
    }
}

/// Iterator over an owned subtree.
#[derive(Clone, Debug)]
pub struct NodeIntoIter<K, V> {
    item: Option<(K, V)>,
    children_iter: std::vec::IntoIter<Node<K, V>>,
    curr_child_iter: Option<Box<NodeIntoIter<K, V>>>,
}

impl<K, V> Default for NodeIntoIter<K, V> {
    fn default() -> Self {
        NodeIntoIter {
            item: None,
            children_iter: Vec::new().into_iter(),
            curr_child_iter: None,
        }
    }
}

impl<K, V> Iterator for NodeIntoIter<K, V> {
    type Item = (K, V);

    fn next(&mut self) -> Option<Self::Item> {
        // First, we yield our own item
        if let Some(item) = self.item.take() {
            return Some(item);
        }

        // Failing that (either because there was no value in the first place,
        // or because we already emitted the item), we recurse into our current
        // child.
        if let Some(curr_child_next_item) = self.curr_child_iter.as_mut().and_then(Iterator::next) {
            return Some(curr_child_next_item);
        }

        // Once we exhaused the current child, move on to the next child.
        // If there aren't more children left, terminate the iteration.
        // Otherwise, find the next child with recurse and call next once more, to try again.
        //
        let next_child = self.children_iter.next()?;
        let next_child_into_iter = next_child.into_iter();

        // reuse the allocation if possible
        if let Some(curr_child_iter) = self.curr_child_iter.as_mut() {
            **curr_child_iter = next_child_into_iter;
        } else {
            self.curr_child_iter = Some(Box::new(next_child_into_iter));
        }

        self.next()
    }
}

impl<K, V> FusedIterator for NodeIntoIter<K, V> {}

/// Iterator over a borrowed subtree.
#[derive(Debug)]
pub struct NodeIter<'a, K, V> {
    item: Option<&'a (K, V)>,
    children_iter: core::slice::Iter<'a, Node<K, V>>,
    curr_child_iter: Option<Box<NodeIter<'a, K, V>>>,
}

impl<K, V> Default for NodeIter<'_, K, V> {
    fn default() -> Self {
        NodeIter {
            item: None,
            children_iter: [].iter(),
            curr_child_iter: None,
        }
    }
}

impl<K, V> Clone for NodeIter<'_, K, V> {
    fn clone(&self) -> Self {
        NodeIter {
            item: self.item,
            children_iter: self.children_iter.clone(),
            curr_child_iter: self.curr_child_iter.clone(),
        }
    }
}

impl<'a, K, V> Iterator for NodeIter<'a, K, V> {
    type Item = (&'a K, &'a V);

    fn next(&mut self) -> Option<Self::Item> {
        // First, we yield our own item
        if let Some((key, value)) = self.item.take() {
            return Some((key, value));
        }

        // Failing that (either because there was no value in the first place,
        // or because we already emitted the item), we recurse into our current
        // child.
        if let Some(curr_child_next_item) = self.curr_child_iter.as_mut().and_then(Iterator::next) {
            return Some(curr_child_next_item);
        }

        // Once we exhaused the current child, move on to the next child.
        // If there aren't more children left, terminate the iteration.
        // Otherwise, find the next child with recurse and call next once more, to try again.
        //
        let next_child = self.children_iter.next()?;
        let next_child_iter = next_child.iter();

        // reuse the allocation if possible
        if let Some(curr_child_iter) = self.curr_child_iter.as_mut() {
            **curr_child_iter = next_child_iter;
        } else {
            self.curr_child_iter = Some(Box::new(next_child_iter));
        }

        self.next()
    }
}

impl<K, V> FusedIterator for NodeIter<'_, K, V> {}

/// Iterator over all the values of the tree.
#[derive(Clone, Debug)]
pub struct IntoIter<K, V> {
    iter: NodeIntoIter<K, V>,
    len: usize,
}

impl<K, V> Default for IntoIter<K, V> {
    fn default() -> Self {
        IntoIter {
            iter: NodeIntoIter::default(),
            len: 0,
        }
    }
}

impl<K, V> Iterator for IntoIter<K, V> {
    type Item = (K, V);

    fn next(&mut self) -> Option<Self::Item> {
        let item = self.iter.next()?;
        self.len -= 1;
        Some(item)
    }

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

impl<K, V> FusedIterator for IntoIter<K, V> {}

impl<K, V> ExactSizeIterator for IntoIter<K, V> {
    fn len(&self) -> usize {
        self.len
    }
}

/// Iterator over references to the values of the tree.
#[derive(Debug)]
pub struct Iter<'a, K, V> {
    iter: NodeIter<'a, K, V>,
    len: usize,
}

impl<K, V> Default for Iter<'_, K, V> {
    fn default() -> Self {
        Iter {
            iter: NodeIter::default(),
            len: 0,
        }
    }
}

impl<K, V> Clone for Iter<'_, K, V> {
    fn clone(&self) -> Self {
        Iter {
            iter: self.iter.clone(),
            len: self.len,
        }
    }
}

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

    fn next(&mut self) -> Option<Self::Item> {
        let item = self.iter.next()?;
        self.len -= 1;
        Some(item)
    }

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

impl<K, V> FusedIterator for Iter<'_, K, V> {}

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

/// Iterator over the owned keys.
#[derive(Clone, Debug)]
pub struct IntoKeys<K, V> {
    iter: IntoIter<K, V>,
}

impl<K, V> Default for IntoKeys<K, V> {
    fn default() -> Self {
        IntoKeys {
            iter: IntoIter::default(),
        }
    }
}

impl<K, V> Iterator for IntoKeys<K, V> {
    type Item = K;

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

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

impl<K, V> FusedIterator for IntoKeys<K, V> {}

impl<K, V> ExactSizeIterator for IntoKeys<K, V> {
    fn len(&self) -> usize {
        self.iter.len()
    }
}

/// Iterator over the borrowed keys.
#[derive(Debug)]
pub struct Keys<'a, K, V> {
    iter: Iter<'a, K, V>,
}

impl<K, V> Default for Keys<'_, K, V> {
    fn default() -> Self {
        Keys {
            iter: Iter::default(),
        }
    }
}

impl<K, V> Clone for Keys<'_, K, V> {
    fn clone(&self) -> Self {
        Keys { iter: self.iter.clone() }
    }
}

impl<'a, K, V> Iterator for Keys<'a, K, V> {
    type Item = &'a K;

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

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

impl<K, V> FusedIterator for Keys<'_, K, V> {}

impl<K, V> ExactSizeIterator for Keys<'_, K, V> {
    fn len(&self) -> usize {
        self.iter.len()
    }
}

/// Iterator over the owned values.
#[derive(Clone, Debug)]
pub struct IntoValues<K, V> {
    iter: IntoIter<K, V>,
}

impl<K, V> Default for IntoValues<K, V> {
    fn default() -> Self {
        IntoValues {
            iter: IntoIter::default(),
        }
    }
}

impl<K, V> Iterator for IntoValues<K, V> {
    type Item = V;

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

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

impl<K, V> FusedIterator for IntoValues<K, V> {}

impl<K, V> ExactSizeIterator for IntoValues<K, V> {
    fn len(&self) -> usize {
        self.iter.len()
    }
}

/// Iterator over the borrowed values.
#[derive(Debug)]
pub struct Values<'a, K, V> {
    iter: Iter<'a, K, V>,
}

impl<K, V> Default for Values<'_, K, V> {
    fn default() -> Self {
        Values {
            iter: Iter::default(),
        }
    }
}

impl<K, V> Clone for Values<'_, K, V> {
    fn clone(&self) -> Self {
        Values { iter: self.iter.clone() }
    }
}

impl<'a, K, V> Iterator for Values<'a, K, V> {
    type Item = &'a V;

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

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

impl<K, V> FusedIterator for Values<'_, K, V> {}

impl<K, V> ExactSizeIterator for Values<'_, K, V> {
    fn len(&self) -> usize {
        self.iter.len()
    }
}

#[cfg(feature = "serde")]
#[doc(hidden)]
pub mod serde {
    use core::marker::PhantomData;
    use serde::{
        ser::{Serialize, Serializer},
        de::{Deserialize, Deserializer, Visitor, MapAccess},
    };
    use crate::map::PrefixTreeMap;


    impl<K, V> Serialize for PrefixTreeMap<K, V>
    where
        K: Serialize,
        V: Serialize,
    {
        fn serialize<S: Serializer>(&self, ser: S) -> Result<S::Ok, S::Error> {
            ser.collect_map(self)
        }
    }

    impl<'de, K, V> Deserialize<'de> for PrefixTreeMap<K, V>
    where
        K: Deserialize<'de> + AsRef<[u8]>,
        V: Deserialize<'de>,
    {
        fn deserialize<D: Deserializer<'de>>(de: D) -> Result<Self, D::Error> {
            de.deserialize_map(PrefixTreeMapVisitor(PhantomData))
        }
    }


    struct PrefixTreeMapVisitor<K, V>(PhantomData<(K, V)>);

    impl<'de, K, V> Visitor<'de> for PrefixTreeMapVisitor<K, V>
    where
        K: Deserialize<'de> + AsRef<[u8]>,
        V: Deserialize<'de>,
    {
        type Value = PrefixTreeMap<K, V>;

        fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
            f.write_str("map")
        }

        fn visit_map<A: MapAccess<'de>>(self, mut acc: A) -> Result<Self::Value, A::Error> {
            let mut map = PrefixTreeMap::new();

            while let Some((key, value)) = acc.next_entry()? {
                map.insert(key, value);
            }

            Ok(map)
        }
    }

    #[cfg(test)]
    mod tests {
        use std::collections::BTreeMap;
        use crate::map::PrefixTreeMap;

        #[test]
        fn serde_roundtrip() {
            let orig = PrefixTreeMap::from([
                ("hey".to_owned(), 123),
                ("hay".to_owned(), 456),
                ("how".to_owned(), 789),
                ("hog".to_owned(), 444),
            ]);
            let json = serde_json::to_string_pretty(&orig).unwrap();
            let dupe: PrefixTreeMap<String, u64> = serde_json::from_str(&json).unwrap();

            assert_eq!(orig, dupe);
        }

        #[test]
        fn std_to_pfx() {
            let std_map = BTreeMap::from([
                ("a".to_owned(), 100),
                ("ab".to_owned(), 110),
                ("abc".to_owned(), 111),
                ("d".to_owned(), 200),
                ("de".to_owned(), 210),
                ("def".to_owned(), 211),
            ]);
            let json = serde_json::to_string_pretty(&std_map).unwrap();
            let pfx_map: PrefixTreeMap<String, i32> = serde_json::from_str(&json).unwrap();

            assert!(pfx_map.iter().eq(&std_map));
        }

        #[test]
        fn pfx_to_std() {
            let pfx_map = PrefixTreeMap::from([
                ("a".to_owned(), 100),
                ("ab".to_owned(), 110),
                ("abc".to_owned(), 111),
                ("d".to_owned(), 200),
                ("de".to_owned(), 210),
                ("def".to_owned(), 211),
            ]);
            let json = serde_json::to_string_pretty(&pfx_map).unwrap();
            let std_map: BTreeMap<String, i32> = serde_json::from_str(&json).unwrap();

            assert!(std_map.iter().eq(&pfx_map));
        }
    }
}