blart 0.5.0

An implementation of an adaptive radix tree packaged as a BTreeMap replacement
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
//! This module contains types and functions relating to iterating over a
//! range of the [`TreeMap`].

use core::{
    cmp::Ordering,
    fmt,
    iter::FusedIterator,
    ops::{Bound, ControlFlow},
};

use crate::{
    allocator::{Allocator, Global},
    map::{NonEmptyTree, DEFAULT_PREFIX_LEN},
    raw::{
        match_concrete_node_ptr, maximum_unchecked, minimum_unchecked,
        AttemptOptimisticPrefixMatch, ConcreteNodePtr, InnerNode, LeafNode, NodePtr, OpaqueNodePtr,
        PessimisticMismatch, PrefixMatchBehavior, RawIterator,
    },
    AsBytes, TreeMap,
};

/// This struct contains details of where and why the search stopped in an inner
/// node.
pub(crate) struct InnerNodeSearchResult<K, V, const PREFIX_LEN: usize> {
    /// This is a pointer to the inner node where search stopped.
    pub node_ptr: OpaqueNodePtr<K, V, PREFIX_LEN>,

    /// The number of bytes of the key that were consumed, not including the
    /// byte that was used to look for a child node.
    pub current_depth: usize,

    /// This is a comparison from the full prefix of the inner node to the
    /// corresponding segment of the search key.
    pub node_prefix_comparison_to_search_key_segment: Ordering,

    /// This field indicates why the search stopped in the inner node.
    pub reason: InnerNodeSearchResultReason,
}

impl<K, V, const PREFIX_LEN: usize> fmt::Debug for InnerNodeSearchResult<K, V, PREFIX_LEN> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("InnerNodeSearchResult")
            .field("node_ptr", &self.node_ptr)
            .field("current_depth", &self.current_depth)
            .field(
                "node_prefix_comparison_to_search_key_segment",
                &self.node_prefix_comparison_to_search_key_segment,
            )
            .field("reason", &self.reason)
            .finish()
    }
}

/// These are search termination reasons specific to inner nodes.
#[derive(Debug)]
pub(crate) enum InnerNodeSearchResultReason {
    /// This variant means the search terminated in a mismatched prefix of an
    /// inner node.
    PrefixMismatch,
    /// This variant means the search terminated because the key was too short,
    /// not because of a mismatch with prefix or child key byte.
    InsufficientBytes,
    /// This variant means the search terminated in an inner node, when there
    /// was no corresponding child for a key byte.
    MissingChild,
}

/// This enum provides the different cases of search result when looking for a
/// starting/ending point for iteration.
pub(crate) enum TerminatingNodeSearchResult<K, V, const PREFIX_LEN: usize> {
    /// This variant means the search terminated at a leaf node.
    Leaf {
        /// The leaf node pointer where search terminated.
        leaf_ptr: NodePtr<PREFIX_LEN, LeafNode<K, V, PREFIX_LEN>>,
        /// The ordering of the leaf key bytes relative to the search bytes.
        leaf_key_comparison_to_search_key: Ordering,
    },
    /// This variant means the search terminated at an inner node.
    InnerNode(InnerNodeSearchResult<K, V, PREFIX_LEN>),
}

impl<K, V, const PREFIX_LEN: usize> fmt::Debug for TerminatingNodeSearchResult<K, V, PREFIX_LEN> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Leaf {
                leaf_ptr,
                leaf_key_comparison_to_search_key,
            } => f
                .debug_struct("Leaf")
                .field("leaf_ptr", leaf_ptr)
                .field(
                    "leaf_key_comparison_to_search_key",
                    leaf_key_comparison_to_search_key,
                )
                .finish(),
            Self::InnerNode(arg0) => f.debug_tuple("InnerNode").field(arg0).finish(),
        }
    }
}

/// Find the node (inner or leaf) that is identified by the given bytestring.
///
/// # Safety
///
/// This function cannot be called concurrently with any mutating operation
/// on `root` or any child node of `root`. This function will arbitrarily
/// read to any child in the given tree.
pub(crate) unsafe fn find_terminating_node<K: AsBytes, V, const PREFIX_LEN: usize>(
    root: OpaqueNodePtr<K, V, PREFIX_LEN>,
    key_bytes: &[u8],
) -> TerminatingNodeSearchResult<K, V, PREFIX_LEN> {
    /// This function will search some key bytes at a specific depth in the
    /// given inner node, returning different results depending on if the search
    /// terminated or needs to continue down the trie.
    ///
    /// If this function returns [`ControlFlow::Continue`] then the search
    /// continues down the trie, otherwise it terminates at this inner node.
    ///
    /// # Safety
    ///
    /// Callers must guarantee that there is no concurrent mutation of the given
    /// inner node for the duration of this function.
    unsafe fn check_prefix_lookup_child<K, V, N, const PREFIX_LEN: usize>(
        inner_ptr: NodePtr<PREFIX_LEN, N>,
        key_bytes: &[u8],
        current_depth: &mut usize,
        prefix_match_behavior: &mut PrefixMatchBehavior,
    ) -> ControlFlow<InnerNodeSearchResult<K, V, PREFIX_LEN>, OpaqueNodePtr<K, V, PREFIX_LEN>>
    where
        N: InnerNode<PREFIX_LEN, Key = K, Value = V>,
        K: AsBytes,
    {
        // SAFETY: The lifetime produced from this is bounded to this scope and does not
        // escape. Further, no other code mutates the node referenced, which is further
        // enforced the "no concurrent reads or writes" requirement on the
        // `check_prefix_lookup_child` function.
        let inner_node = unsafe { inner_ptr.as_ref() };
        let match_prefix =
            prefix_match_behavior.match_prefix(inner_node, &key_bytes[*current_depth..]);
        match match_prefix {
            Err(PessimisticMismatch { matched_bytes, .. }) => {
                let (full_prefix, _) = inner_node.read_full_prefix(*current_depth);
                let upper_bound = (*current_depth + full_prefix.len()).min(key_bytes.len());
                let key_segment = &key_bytes[(*current_depth)..upper_bound];

                let node_prefix_comparison_to_search_key_segment = full_prefix.cmp(key_segment);

                debug_assert_ne!(
                    node_prefix_comparison_to_search_key_segment,
                    Ordering::Equal,
                    "if there was a mismatch, the prefix must not be equal"
                );

                // We report a prefix mismatch if the prefix is longer that the remaining
                // portion of the key bytes. However, in the context of the
                // `InnerNodeSearchResultReason` running out of bytes is really a different
                // thing than a mismatch. We should only report mismatch as the reason if there
                // was an actual byte difference.
                let reason = if matched_bytes == key_bytes[*current_depth..].len() {
                    InnerNodeSearchResultReason::InsufficientBytes
                } else {
                    InnerNodeSearchResultReason::PrefixMismatch
                };

                ControlFlow::Break(InnerNodeSearchResult {
                    node_ptr: inner_ptr.to_opaque(),
                    current_depth: *current_depth,
                    reason,
                    node_prefix_comparison_to_search_key_segment,
                })
            },
            Ok(AttemptOptimisticPrefixMatch { matched_bytes, .. }) => {
                // Since the prefix matched, advance the depth by the size of the prefix
                *current_depth += matched_bytes;

                let next_key_fragment = if *current_depth < key_bytes.len() {
                    key_bytes[*current_depth]
                } else {
                    // the key has insufficient bytes, it is a prefix of an existing key. Thus, the
                    // key must not exist in the tree by the requirements of the insert function
                    // (any key in the tree must not be the prefix of any other key in the tree)
                    return ControlFlow::Break(InnerNodeSearchResult {
                        node_ptr: inner_ptr.to_opaque(),
                        current_depth: *current_depth,
                        reason: InnerNodeSearchResultReason::InsufficientBytes,
                        node_prefix_comparison_to_search_key_segment: Ordering::Equal,
                    });
                };

                let child_lookup = inner_node.lookup_child(next_key_fragment);

                match child_lookup {
                    Some(child_ptr) => {
                        // Since the prefix matched and it found a child, advance the depth by 1
                        // more key byte
                        *current_depth += 1;
                        ControlFlow::Continue(child_ptr)
                    },
                    None => ControlFlow::Break(InnerNodeSearchResult {
                        node_ptr: inner_ptr.to_opaque(),
                        current_depth: *current_depth,
                        reason: InnerNodeSearchResultReason::MissingChild,
                        node_prefix_comparison_to_search_key_segment: Ordering::Equal,
                    }),
                }
            },
        }
    }

    let mut current_node = root;
    let mut current_depth = 0;
    let mut prefix_match_behavior = PrefixMatchBehavior::default();

    loop {
        let next_node = match_concrete_node_ptr!(match (current_node.to_node_ptr()) {
            InnerNode(inner_ptr) => unsafe {
                // SAFETY: The safety requirement is covered by the safety documentation on the
                // containing function
                check_prefix_lookup_child(
                    inner_ptr,
                    key_bytes,
                    &mut current_depth,
                    &mut prefix_match_behavior,
                )
            },
            LeafNode(leaf_ptr) => {
                // SAFETY: The shared reference is bounded to this block and there are no
                // concurrent modifications, by the safety conditions of this function.
                let leaf_node = unsafe { leaf_ptr.as_ref() };

                let leaf_key_comparison_to_search_key =
                    prefix_match_behavior.compare_leaf_key(leaf_node, key_bytes, current_depth);

                return TerminatingNodeSearchResult::Leaf {
                    leaf_ptr,
                    leaf_key_comparison_to_search_key,
                };
            },
        });

        match next_node {
            ControlFlow::Continue(next_node) => {
                current_node = next_node;
            },
            ControlFlow::Break(reason) => {
                return TerminatingNodeSearchResult::InnerNode(reason);
            },
        }
    }
}

/// Panic if the given range bounds
#[track_caller]
pub(crate) fn validate_range_bounds(start_bound: &Bound<&[u8]>, end_bound: &Bound<&[u8]>) {
    match (*start_bound, *end_bound) {
        (Bound::Excluded(s), Bound::Excluded(e)) if s == e => {
            panic!("range start and end are equal and excluded: ({s:?})")
        },
        (Bound::Included(s) | Bound::Excluded(s), Bound::Included(e) | Bound::Excluded(e))
            if s > e =>
        {
            panic!("range start ({s:?}) is greater than range end ({e:?})")
        },
        _ => {},
    }
}

type KeyByteAndChild<K, V, const PREFIX_LEN: usize> = Option<(u8, OpaqueNodePtr<K, V, PREFIX_LEN>)>;

/// This function searches a trie for the smallest/largest leaf node that is
/// greater/less than the given bound.
///
/// If `is_start` is true, its looking for the smallest leaf node that is
/// greater than the given bound. If `is_start` is false, we're looking for the
/// greatest leaf node that is smaller than the given bound.
///
/// # Safety
///
/// Callers must guarantee that there is no concurrent mutation of the given
/// trie for the duration of this function.
pub(crate) unsafe fn find_leaf_pointer_for_bound<K: AsBytes, V, const PREFIX_LEN: usize>(
    tree: &NonEmptyTree<K, V, PREFIX_LEN>,
    bound: Bound<&[u8]>,
    is_start: bool,
) -> Option<NodePtr<PREFIX_LEN, LeafNode<K, V, PREFIX_LEN>>> {
    Some(match bound {
        Bound::Included(key_bytes) | Bound::Excluded(key_bytes) => {
            // SAFETY: Covered by function safety doc
            let terminating_node = unsafe { find_terminating_node(tree.root, key_bytes) };

            match terminating_node {
                TerminatingNodeSearchResult::Leaf {
                    leaf_ptr,
                    leaf_key_comparison_to_search_key,
                } => match leaf_key_comparison_to_search_key {
                    Ordering::Less => {
                        if is_start {
                            // SAFETY: Covered by function safety doc
                            let leaf = unsafe { leaf_ptr.as_ref() };
                            leaf.next?
                        } else {
                            leaf_ptr
                        }
                    },
                    Ordering::Equal => {
                        if matches!(bound, Bound::Excluded(_)) {
                            // SAFETY: Covered by function safety doc
                            let leaf = unsafe { leaf_ptr.as_ref() };
                            if is_start { leaf.next } else { leaf.previous }?
                        } else {
                            leaf_ptr
                        }
                    },
                    Ordering::Greater => {
                        if is_start {
                            leaf_ptr
                        } else {
                            // SAFETY: Covered by function safety doc
                            let leaf = unsafe { leaf_ptr.as_ref() };
                            leaf.previous?
                        }
                    },
                },
                TerminatingNodeSearchResult::InnerNode(InnerNodeSearchResult {
                    node_ptr,
                    current_depth,
                    reason,
                    node_prefix_comparison_to_search_key_segment,
                }) => match reason {
                    InnerNodeSearchResultReason::PrefixMismatch
                    | InnerNodeSearchResultReason::InsufficientBytes => {
                        match (is_start, node_prefix_comparison_to_search_key_segment) {
                            (true, Ordering::Equal | Ordering::Greater) => unsafe {
                                // SAFETY: Covered by function safety doc
                                minimum_unchecked(node_ptr)
                            },
                            (true, Ordering::Less) => unsafe {
                                // SAFETY: Covered by function safety doc
                                let max_leaf_ptr = maximum_unchecked(node_ptr);
                                let max_leaf = max_leaf_ptr.as_ref();
                                max_leaf.next?
                            },
                            (false, Ordering::Equal | Ordering::Less) => unsafe {
                                // SAFETY: Covered by function safety doc
                                maximum_unchecked(node_ptr)
                            },
                            (false, Ordering::Greater) => unsafe {
                                // SAFETY: Covered by function safety doc
                                let min_leaf_ptr = minimum_unchecked(node_ptr);
                                let min_leaf = min_leaf_ptr.as_ref();
                                min_leaf.previous?
                            },
                        }
                    },
                    InnerNodeSearchResultReason::MissingChild => {
                        fn access_closest_child<
                            const PREFIX_LEN: usize,
                            N: InnerNode<PREFIX_LEN>,
                        >(
                            inner_ptr: NodePtr<PREFIX_LEN, N>,
                            child_bounds: (Bound<u8>, Bound<u8>),
                            is_start: bool,
                        ) -> KeyByteAndChild<N::Key, N::Value, PREFIX_LEN> {
                            // SAFETY: Covered by function safety doc
                            let inner = unsafe { inner_ptr.as_ref() };
                            let mut child_it = inner.range(child_bounds);
                            if is_start {
                                child_it.next()
                            } else {
                                child_it.next_back()
                            }
                        }

                        let child_bounds = if is_start {
                            (bound.map(|_| key_bytes[current_depth]), Bound::Unbounded)
                        } else {
                            (Bound::Unbounded, bound.map(|_| key_bytes[current_depth]))
                        };
                        let possible_next_child =
                            match_concrete_node_ptr!(match (node_ptr.to_node_ptr()) {
                                InnerNode(inner_ptr) => {
                                    access_closest_child(inner_ptr, child_bounds, is_start)
                                },
                                LeafNode(_leaf) => unreachable!(
                                    "This branch is unreachable because the \
                                     TerminatingNodeSearchResult had the value InnerNode"
                                ),
                            });
                        let (_, next_child) = possible_next_child?;

                        if is_start {
                            // SAFETY: Covered by function safety doc
                            unsafe { minimum_unchecked(next_child) }
                        } else {
                            // SAFETY: Covered by function safety doc
                            unsafe { maximum_unchecked(next_child) }
                        }
                    },
                },
            }
        },
        Bound::Unbounded => {
            if is_start {
                tree.min_leaf
            } else {
                tree.max_leaf
            }
        },
    })
}

macro_rules! implement_range_iter {
    (
        $(#[$outer:meta])*
        struct $name:ident {
            tree: $tree_ty:ty,
            item: $item_ty:ty,
            $leaf_accessor_func:ident
        }
    ) => {
        $(#[$outer])*
        pub struct $name<'a, K, V, const PREFIX_LEN: usize = DEFAULT_PREFIX_LEN, A: Allocator = Global> {
            inner: RawIterator<K, V, PREFIX_LEN>,
            _tree: $tree_ty,
        }

        impl<'a, K: AsBytes, V, const PREFIX_LEN: usize, A: Allocator> $name<'a, K, V, PREFIX_LEN, A> {
            /// Create a new range iterator over the given tree, starting and ending
            /// according to the given bounds.
            ///
            /// # Panics
            ///
            /// This function will panic if `start_bound` is greater than `end_bound`.
            pub(crate) fn new(
                tree: $tree_ty,
                start_bound: Bound<&[u8]>,
                end_bound: Bound<&[u8]>,
            ) -> Self {
                let Some(tree_state) = &tree.state else {
                    return Self {
                        _tree: tree,
                        inner: RawIterator::empty(),
                    };
                };

                // Validation happens after the empty check so we can avoid panicking for invalid range
                // when the tree is empty. I believe this matches BTreeMap behavior.
                validate_range_bounds(&start_bound, &end_bound);

                // SAFETY: Since we have a (shared or mutable) reference to the original TreeMap, we know
                // there will be no concurrent mutation
                let possible_start =
                    unsafe { find_leaf_pointer_for_bound(tree_state, start_bound, true) };
                let Some(start) = possible_start else {
                    return Self {
                        _tree: tree,
                        inner: RawIterator::empty(),
                    };
                };

                // SAFETY: Since we have a (shared or mutable) reference to the original TreeMap, we know
                // there will be no concurrent mutation
                let possible_end =
                    unsafe { find_leaf_pointer_for_bound(tree_state, end_bound, false) };
                let Some(end) = possible_end else {
                    return Self {
                        _tree: tree,
                        inner: RawIterator::empty(),
                    };
                };

                // SAFETY: Since we have a (shared or mutable) reference to the original TreeMap, we know
                // there will be no concurrent mutation. Also, the reference lifetimes created
                // are bounded to this `unsafe` block, and don't overlap with any mutation.
                unsafe {
                    let start_leaf_bytes = start.as_key_ref().as_bytes();
                    let end_leaf_bytes = end.as_key_ref().as_bytes();

                    if start_leaf_bytes > end_leaf_bytes {
                        // Resolved start leaf is not less than or equal to resolved end leaf for
                        // iteration order
                        return Self {
                            _tree: tree,
                            inner: RawIterator::empty(),
                        };
                    }
                }

                Self {
                    _tree: tree,
                    // SAFETY: `start` is guaranteed to be less than or equal to `end` in the iteration
                    // order because of the check we do on the bytes of the resolved leaf pointers, just
                    // above this line
                    inner: unsafe { RawIterator::new(start, end) },
                }
            }
        }

        impl<'a, K, V, const PREFIX_LEN: usize, A: Allocator> Iterator for $name<'a, K, V, PREFIX_LEN, A> {
            type Item = $item_ty;

            fn next(&mut self) -> Option<Self::Item> {
                // SAFETY: This iterator has a reference (either shared or mutable) to the
                // original `TreeMap` it is iterating over, preventing any other modification.
                let leaf_ptr = unsafe { self.inner.next()? };

                // SAFETY: THe lifetimes returned from this function are returned as bounded by
                // lifetime 'a, meaning that they cannot outlive this iterator's reference
                // (shared or mutable) to the original TreeMap.
                Some(unsafe { leaf_ptr.$leaf_accessor_func() })
            }
        }

        impl<'a, K, V, const PREFIX_LEN: usize, A: Allocator> DoubleEndedIterator
            for $name<'a, K, V, PREFIX_LEN, A>
        {
            fn next_back(&mut self) -> Option<Self::Item> {
                // SAFETY: This iterator has a reference (either shared or mutable) to the
                // original `TreeMap` it is iterating over, preventing any other modification.
                let leaf_ptr = unsafe { self.inner.next_back()? };

                // SAFETY: THe lifetimes returned from this function are returned as bounded by
                // lifetime 'a, meaning that they cannot outlive this iterator's reference
                // (shared or mutable) to the original TreeMap.
                Some(unsafe { leaf_ptr.$leaf_accessor_func() })
            }
        }

        impl<'a, K, V, const PREFIX_LEN: usize, A: Allocator> FusedIterator for $name<'a, K, V, PREFIX_LEN, A> {}
    };
}

implement_range_iter!(
    /// An iterator over a sub-range of entries in a [`TreeMap`].
    ///
    /// This struct is created by the [`range`][TreeMap::range] method on `TreeMap`.
    /// See its documentation for more details.
    struct Range {
        tree: &'a TreeMap<K, V, PREFIX_LEN, A>,
        item: (&'a K, &'a V),
        as_key_value_ref
    }
);

// SAFETY: This iterator holds a shared reference to the underlying `TreeMap`
// and thus can be moved across threads if the `TreeMap<K, V>: Sync`.
unsafe impl<K, V, A, const PREFIX_LEN: usize> Send for Range<'_, K, V, PREFIX_LEN, A>
where
    K: Sync,
    V: Sync,
    A: Sync + Allocator,
{
}

// SAFETY: This iterator has no interior mutability and can be shared across
// thread so long as the reference `TreeMap<K, V>` can as well.
unsafe impl<K, V, A, const PREFIX_LEN: usize> Sync for Range<'_, K, V, PREFIX_LEN, A>
where
    K: Sync,
    V: Sync,
    A: Sync + Allocator,
{
}

implement_range_iter!(
    /// A mutable iterator over a sub-range of entries in a [`TreeMap`].
    ///
    /// This struct is created by the [`range_mut`][TreeMap::range_mut] method on `TreeMap`.
    /// See its documentation for more details.
    struct RangeMut {
        tree: &'a mut TreeMap<K, V, PREFIX_LEN, A>,
        item: (&'a K, &'a mut V),
        as_key_ref_value_mut
    }
);

// SAFETY: This iterator has a mutable reference to the underlying `TreeMap` and
// can be moved across threads if `&mut TreeMap<K, V>` is `Send`, which requires
// `TreeMap<K, V>` to be `Send` as well.
unsafe impl<K, V, A, const PREFIX_LEN: usize> Send for RangeMut<'_, K, V, PREFIX_LEN, A>
where
    K: Send,
    V: Send,
    A: Send + Allocator,
{
}

// SAFETY: This iterator uses no interior mutability and can be shared across
// threads so long as `TreeMap<K, V>: Sync`.
unsafe impl<K, V, A, const PREFIX_LEN: usize> Sync for RangeMut<'_, K, V, PREFIX_LEN, A>
where
    K: Sync,
    V: Sync,
    A: Sync + Allocator,
{
}

#[cfg(test)]
mod tests {
    use alloc::{boxed::Box, vec::Vec};

    use super::*;
    use crate::testing::{generate_key_with_prefix, swap, PrefixExpansion};

    #[test]
    fn iterators_are_send_sync() {
        fn is_send<T: Send>() {}
        fn is_sync<T: Sync>() {}

        fn range_is_send<'a, K: Sync + 'a, V: Sync + 'a, A: Sync + Allocator + 'a>() {
            is_send::<Range<'a, K, V, DEFAULT_PREFIX_LEN, A>>();
        }

        fn range_is_sync<'a, K: Sync + 'a, V: Sync + 'a, A: Sync + Allocator + 'a>() {
            is_sync::<Range<'a, K, V, DEFAULT_PREFIX_LEN, A>>();
        }

        range_is_send::<[u8; 3], usize, Global>();
        range_is_sync::<[u8; 3], usize, Global>();

        fn range_mut_is_send<'a, K: Send + 'a, V: Send + 'a, A: Send + Allocator + 'a>() {
            is_send::<RangeMut<'a, K, V, DEFAULT_PREFIX_LEN, A>>();
        }

        fn range_mut_is_sync<'a, K: Sync + 'a, V: Sync + 'a, A: Sync + Allocator + 'a>() {
            is_sync::<RangeMut<'a, K, V, DEFAULT_PREFIX_LEN, A>>();
        }

        range_mut_is_send::<[u8; 3], usize, Global>();
        range_mut_is_sync::<[u8; 3], usize, Global>();
    }

    fn fixture_tree() -> TreeMap<[u8; 3], usize> {
        [
            [0, 0, 0],
            [0, 0, u8::MAX],
            [0, u8::MAX, 0],
            [0, u8::MAX, u8::MAX],
            [127, 127, 0],
            [127, 127, 127],
            [127, 127, u8::MAX],
            [u8::MAX, 0, 0],
            [u8::MAX, 0, u8::MAX],
            [u8::MAX, u8::MAX, 0],
            [u8::MAX, u8::MAX, u8::MAX],
        ]
        .into_iter()
        .enumerate()
        .map(swap)
        .collect()
    }

    #[test]
    fn range_iteration_normal_tree() {
        let tree = fixture_tree();

        // Included on end of key range
        let mut it = Range::new(
            &tree,
            Bound::Included([u8::MAX, u8::MAX, u8::MAX].as_slice()),
            Bound::Unbounded,
        )
        .map(|(k, _)| k);
        assert_eq!(it.next().unwrap(), &[u8::MAX, u8::MAX, u8::MAX]);
        assert_eq!(it.next(), None);

        // Excluded on end of key range
        let mut it = Range::new(
            &tree,
            Bound::Excluded([u8::MAX, u8::MAX, u8::MAX].as_slice()),
            Bound::Unbounded,
        )
        .map(|(k, _)| k);
        assert_eq!(it.next(), None);

        // Included on start of key range
        let mut it = Range::new(
            &tree,
            Bound::Unbounded,
            Bound::Included([0, 0, 0].as_slice()),
        )
        .map(|(k, _)| k);
        assert_eq!(it.next().unwrap(), &[0, 0, 0]);
        assert_eq!(it.next(), None);

        // Excluded on start of key range
        let mut it = Range::new(
            &tree,
            Bound::Unbounded,
            Bound::Excluded([0, 0, 0].as_slice()),
        )
        .map(|(k, _)| k);
        assert_eq!(it.next(), None);
    }

    #[test]
    fn range_iteration_on_key_prefix() {
        let tree = fixture_tree();

        let mut it = Range::new(
            &tree,
            Bound::Included([0].as_slice()),
            Bound::Excluded([1].as_slice()),
        )
        .map(|(k, _)| k);

        assert_eq!(it.next().unwrap(), &[0, 0, 0]);
        assert_eq!(it.next().unwrap(), &[0, 0, u8::MAX]);
        assert_eq!(it.next().unwrap(), &[0, u8::MAX, 0]);
        assert_eq!(it.next().unwrap(), &[0, u8::MAX, u8::MAX]);
        assert_eq!(it.next(), None);
    }

    #[test]
    fn range_prefix_mismatch_or_insufficient_bytes_lower_bounds() {
        let tree = fixture_tree();

        let mut it = Range::new(
            &tree,
            Bound::Included([127, 126].as_slice()),
            Bound::Excluded([128].as_slice()),
        )
        .map(|(k, _)| k);

        // This should produce the 3 keys because the start key [127, 126] is ordered
        // before the key [127, 127, 0]
        assert!([127, 126].as_slice() < [127, 127, 0].as_slice());
        assert_eq!(it.next().unwrap(), &[127, 127, 0]);
        assert_eq!(it.next().unwrap(), &[127, 127, 127]);
        assert_eq!(it.next().unwrap(), &[127, 127, u8::MAX]);
        assert_eq!(it.next(), None);

        let mut it = Range::new(
            &tree,
            Bound::Included([127, 128].as_slice()),
            Bound::Excluded([128].as_slice()),
        )
        .map(|(k, _)| k);

        // This should produce no keys because the start key [127, 128] is ordered after
        // the key [127, 127, u8::MAX]
        assert!([127, 128].as_slice() > [127, 127, u8::MAX].as_slice());
        assert_eq!(it.next(), None);

        let mut it = Range::new(
            &tree,
            Bound::Included([127].as_slice()),
            Bound::Excluded([128].as_slice()),
        )
        .map(|(k, _)| k);

        // This should produce the 3 keys because the start key [127] is ordered
        // before the key [127, 127, 0]
        assert!([127].as_slice() < [127, 127, 0].as_slice());
        assert_eq!(it.next().unwrap(), &[127, 127, 0]);
        assert_eq!(it.next().unwrap(), &[127, 127, 127]);
        assert_eq!(it.next().unwrap(), &[127, 127, u8::MAX]);
        assert_eq!(it.next(), None);

        let mut it = Range::new(
            &tree,
            Bound::Included([127, 127].as_slice()),
            Bound::Excluded([128].as_slice()),
        )
        .map(|(k, _)| k);

        // This should produce the 3 keys because the start key [127, 127] is ordered
        // before the key [127, 127, 0]
        assert!([127, 127].as_slice() < [127, 127, 0].as_slice());
        assert_eq!(it.next().unwrap(), &[127, 127, 0]);
        assert_eq!(it.next().unwrap(), &[127, 127, 127]);
        assert_eq!(it.next().unwrap(), &[127, 127, u8::MAX]);
        assert_eq!(it.next(), None);
    }

    #[test]
    fn range_prefix_mismatch_or_insufficient_bytes_upper_bounds() {
        let tree = fixture_tree();

        let mut it = Range::new(
            &tree,
            Bound::Excluded([126].as_slice()),
            Bound::Excluded([128].as_slice()),
        )
        .map(|(k, _)| k);
        assert_eq!(it.next().unwrap(), &[127, 127, 0]);
        assert_eq!(it.next().unwrap(), &[127, 127, 127]);
        assert_eq!(it.next().unwrap(), &[127, 127, u8::MAX]);
        assert_eq!(it.next(), None);

        let mut it = Range::new(
            &tree,
            Bound::Excluded([126].as_slice()),
            Bound::Included([127, 127, u8::MAX].as_slice()),
        )
        .map(|(k, _)| k);
        assert_eq!(it.next().unwrap(), &[127, 127, 0]);
        assert_eq!(it.next().unwrap(), &[127, 127, 127]);
        assert_eq!(it.next().unwrap(), &[127, 127, u8::MAX]);
        assert_eq!(it.next(), None);

        let mut it = Range::new(
            &tree,
            Bound::Excluded([126].as_slice()),
            Bound::Included([127, 127, 0].as_slice()),
        )
        .map(|(k, _)| k);
        assert_eq!(it.next().unwrap(), &[127, 127, 0]);
        assert_eq!(it.next(), None);
    }

    #[test]
    fn empty_tree_empty_iterator() {
        let tree = TreeMap::<[u8; 3], usize>::new();

        let it = Range::new(
            &tree,
            Bound::Excluded([1, 1, 1].as_slice()),
            Bound::Excluded([1, 1, 1].as_slice()),
        );

        assert_eq!(it.count(), 0);
    }

    #[test]
    #[should_panic(expected = "range start and end are equal and excluded: ([1, 1, 1])")]
    fn equal_excluded_bounds_should_panic() {
        let tree = fixture_tree();

        let _it = Range::new(
            &tree,
            Bound::Excluded([1, 1, 1].as_slice()),
            Bound::Excluded([1, 1, 1].as_slice()),
        );
    }

    #[test]
    #[should_panic(expected = "range start ([1, 1, 1]) is greater than range end ([0, 0, 0])")]
    fn excluded_excluded_start_greater_than_end_should_panic() {
        let tree = fixture_tree();

        let _it = Range::new(
            &tree,
            Bound::Excluded([1, 1, 1].as_slice()),
            Bound::Excluded([0, 0, 0].as_slice()),
        );
    }

    #[test]
    #[should_panic(expected = "range start ([1, 1, 1]) is greater than range end ([0, 0, 0])")]
    fn included_included_start_greater_than_end_should_panic() {
        let tree = fixture_tree();

        let _it = Range::new(
            &tree,
            Bound::Included([1, 1, 1].as_slice()),
            Bound::Included([0, 0, 0].as_slice()),
        );
    }

    #[test]
    fn excluded_excluded_empty_range_should_be_empty() {
        let tree = fixture_tree();

        let it = Range::new(
            &tree,
            Bound::Excluded([127, 127, 127].as_slice()),
            Bound::Excluded([127, 127, 128].as_slice()),
        );

        assert_eq!(it.count(), 0);

        let it = Range::new(
            &tree,
            Bound::Excluded([127, 127, 126].as_slice()),
            Bound::Excluded([127, 127, 127].as_slice()),
        );

        assert_eq!(it.count(), 0);
    }

    #[test]
    fn included_included_range_on_middle() {
        let tree = fixture_tree();

        let mut it = Range::new(
            &tree,
            Bound::Included([126, 0, 0].as_slice()),
            Bound::Included([128, 0, 0].as_slice()),
        )
        .map(|(k, _)| k);

        assert_eq!(it.next().unwrap(), &[127, 127, 0]);
        assert_eq!(it.next().unwrap(), &[127, 127, 127]);
        assert_eq!(it.next().unwrap(), &[127, 127, u8::MAX]);
        assert_eq!(it.next(), None);
    }

    #[test]
    fn range_mut_mutate_some_keys() {
        let mut tree = fixture_tree();

        tree.values_mut().for_each(|value| *value = 0);

        tree.range_mut([126, 0, 0]..=[128u8, 0, 0])
            .for_each(|(_, value)| *value = 1024);

        assert_eq!(
            tree.into_iter().collect::<Vec<_>>(),
            [
                ([0, 0, 0], 0),
                ([0, 0, 255], 0),
                ([0, 255, 0], 0),
                ([0, 255, 255], 0),
                ([127, 127, 0], 1024),
                ([127, 127, 127], 1024),
                ([127, 127, 255], 1024),
                ([255, 0, 0], 0),
                ([255, 0, 255], 0),
                ([255, 255, 0], 0),
                ([255, 255, 255], 0)
            ]
        );
    }

    #[test]
    fn lookup_on_tree_with_implicit_prefix_bytes() {
        let mut tree = TreeMap::<_, _, 0>::with_prefix_len();

        for (key, value) in generate_key_with_prefix(
            [3, 3, 3],
            [PrefixExpansion {
                base_index: 0,
                expanded_length: 4,
            }],
        )
        .enumerate()
        .map(swap)
        {
            let _ = tree.try_insert(key, value).unwrap();
        }

        assert_eq!(
            tree.range(Box::from([0u8, 0, 0, 0, 0, 0])..Box::from([0u8, 0, 0, 0, 0, 4]))
                .collect::<Vec<_>>(),
            &[
                (&[0, 0, 0, 0, 0, 0].into(), &0),
                (&[0, 0, 0, 0, 0, 1].into(), &1),
                (&[0, 0, 0, 0, 0, 2].into(), &2),
                (&[0, 0, 0, 0, 0, 3].into(), &3)
            ]
        );

        assert_eq!(
            tree.range(Box::from([0u8, 0])..Box::from([0u8, 0, 0, 0, 0, 4]))
                .collect::<Vec<_>>(),
            &[
                (&[0, 0, 0, 0, 0, 0].into(), &0),
                (&[0, 0, 0, 0, 0, 1].into(), &1),
                (&[0, 0, 0, 0, 0, 2].into(), &2),
                (&[0, 0, 0, 0, 0, 3].into(), &3)
            ]
        );
    }
}