range_map/
lib.rs

1// Copyright 2025 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5use arrayvec::ArrayVec;
6use std::cmp::{Eq, PartialEq};
7use std::fmt;
8use std::fmt::{Debug, Formatter};
9use std::ops::{Bound, Range, RangeBounds};
10use std::sync::Arc;
11
12/// The `B` constant for the btree.
13///
14/// Controls the size of the nodes inside the tree.
15const B: usize = 6;
16
17/// The capacity of nodes in the btree.
18const NODE_CAPACITY: usize = 2 * B;
19
20/// A trait for types that can calculate the gap between two values.
21pub trait Gap {
22    /// Measure the gap between two values.
23    fn measure_gap(&self, other: &Self) -> u64;
24}
25
26impl Gap for u32 {
27    fn measure_gap(&self, other: &Self) -> u64 {
28        if *self > *other {
29            (*self - *other) as u64
30        } else {
31            (*other - *self) as u64
32        }
33    }
34}
35
36/// A location inside the btree.
37#[derive(Debug, Default, Clone, Copy)]
38struct Cursor {
39    /// The number of valid indices in the `indices` array.
40    depth: u8,
41
42    /// The indices of the entry, ordered from leaf to root.
43    indices: [u8; 7],
44}
45
46impl Cursor {
47    /// Create a cursor with a single index.
48    fn with_index(index: usize) -> Self {
49        let mut cursor = Self::default();
50        cursor.push(index);
51        cursor
52    }
53
54    /// Whether the cursor is empty.
55    ///
56    /// A cursor is empty if it contains no more indices. This happens when a traversal has reached
57    /// a leaf node.
58    fn is_empty(&self) -> bool {
59        self.depth == 0
60    }
61
62    /// Push an index onto the front of the cursor.
63    ///
64    /// The front of the cursor is towards the root of the tree.
65    fn push(&mut self, index: usize) {
66        self.indices[self.depth as usize] = index as u8;
67        self.depth += 1;
68    }
69
70    /// Push an index onto the back of the cursor.
71    ///
72    /// The back of the cursor is towards the leaves of the tree.
73    fn push_back(&mut self, index: usize) {
74        self.indices.rotate_right(1);
75        self.indices[0] = index as u8;
76        self.depth += 1;
77    }
78
79    /// Pop an index off the front of the cursor.
80    ///
81    /// The front of the cursor is towards the root of the tree.
82    fn pop(&mut self) -> Option<usize> {
83        if self.depth == 0 {
84            None
85        } else {
86            self.depth -= 1;
87            Some(self.indices[self.depth as usize] as usize)
88        }
89    }
90
91    /// Pop an index off the back of the cursor.
92    ///
93    /// The back of the cursor is towards the leaves of the tree.
94    fn pop_back(&mut self) -> Option<usize> {
95        if self.depth == 0 {
96            None
97        } else {
98            self.depth -= 1;
99            let index = self.indices[0] as usize;
100            self.indices.rotate_left(1);
101            Some(index)
102        }
103    }
104
105    /// The backmost index in the cursor.
106    ///
107    /// The back of the cursor is towards the leaves of the tree.
108    ///
109    /// Assumes the cursor is non-empty.
110    fn back(&self) -> usize {
111        self.indices[0] as usize
112    }
113
114    /// Increment the backmost index in the cursor.
115    ///
116    /// The back of the cursor is towards the leaves of the tree.
117    ///
118    /// Assumes the cursor is non-empty.
119    fn increment_back(&mut self) {
120        self.indices[0] += 1;
121    }
122
123    /// Decrement the backmost index in the cursor.
124    ///
125    /// The back of the cursor is towards the leaves of the tree.
126    ///
127    /// Assumes the cursor is non-empty.
128    fn decrement_back(&mut self) {
129        self.indices[0] -= 1;
130    }
131}
132
133impl PartialEq for Cursor {
134    fn eq(&self, other: &Self) -> bool {
135        if self.depth != other.depth {
136            return false;
137        }
138        for i in 0..self.depth {
139            if self.indices[i as usize] != other.indices[i as usize] {
140                return false;
141            }
142        }
143        true
144    }
145}
146
147impl Eq for Cursor {}
148
149/// Where to place the cursor relative to the given key.
150enum CursorPosition {
151    /// The given key represents a left edge of a range.
152    ///
153    /// Place the cursor to the left of a range containing the cursor.
154    Left,
155
156    /// The given key represents a right edge of a range.
157    ///
158    /// Place the cursor to the right of a range containing the cursor.
159    Right,
160}
161
162/// Search of the given key in the given array of ranges.
163///
164/// If the array contains a range that contains the key, returns the index of that range.
165/// Otherwise, returns the index at which the given key could be inserted into the array to
166/// maintain the ordering.
167fn binary_search<K: Ord>(key: &K, keys: &ArrayVec<Range<K>, NODE_CAPACITY>) -> usize {
168    let mut left = 0usize;
169    let mut right = keys.len();
170    while left < right {
171        let mid = left + (right - left) / 2;
172        // TODO: Consider `get_unchecked`.
173        let range = &keys[mid];
174        if key < &range.start {
175            // This range is too large.
176            right = mid;
177        } else if key < &range.end {
178            // We found the range that contains this key.
179            return mid;
180        } else {
181            // The key might be found in the next range.
182            left = mid + 1;
183        }
184    }
185    // The key falls between two ranges. Return the index at which this key could be inserted to
186    // maintain the ordering.
187    left
188}
189
190/// A leaf node in the btree.
191///
192/// Stores a flat map of keys to values, with the `i`th entry in the keys array corresponding to
193/// the `i`th entry in the values array. The balancing rules of the btree ensure that every
194/// non-root leaf has between N and N/2 entries populated.
195#[derive(Clone)]
196struct NodeLeaf<K: Ord + Copy + Gap, V: Clone> {
197    /// The maximum gap between keys in this leaf node.
198    max_gap: u64,
199
200    /// The keys stored in this leaf node.
201    ///
202    /// We store the key in a dense array to improve cache performance during lookups. We often
203    /// need to binary-search the keys in a given leaf node, which means having those keys close
204    /// together improves cache performance.
205    keys: ArrayVec<Range<K>, NODE_CAPACITY>,
206
207    /// The value stored in this leaf node.
208    values: ArrayVec<V, NODE_CAPACITY>,
209}
210
211/// Shows the map structure of the leaf node.
212impl<K, V> Debug for NodeLeaf<K, V>
213where
214    K: Debug + Ord + Copy + Gap,
215    V: Debug + Clone,
216{
217    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
218        f.debug_map().entries(self.keys.iter().zip(self.values.iter())).finish()
219    }
220}
221
222/// The result of performing an insertion into a btree node.
223enum InsertResult<K: Ord + Copy + Gap, V: Clone> {
224    /// The value was successfully inserted into an empty slot.
225    Inserted,
226
227    /// The value was inserted into an empty slot in a leaf node but that insertion caused the
228    /// leaf node to exceed its capacity and split into two leaf nodes. The existing leaf node
229    /// now holds the entries to the left of the split and the entries to the right of the split
230    /// are returned. The split occurred at the returned key.
231    SplitLeaf(K, Arc<NodeLeaf<K, V>>),
232
233    /// The value was inserted into an empty slot in a subtree but that insertion caused the
234    /// internal node to exceed its capacity and split into two internal nodes. The internal node
235    /// now holds the entries to the left of the split and the entries to the right of the split
236    /// are returned. The split occurred at the returned key.
237    SplitInternal(K, Arc<NodeInternal<K, V>>),
238}
239
240/// State information returned from the removal operation.
241struct RemoveState<K: Ord + Copy + Gap, V: Clone> {
242    /// The minimal key for this subtree, if available.
243    ///
244    /// If the minimal key for this subtree is not available, then the minimal key is guaranteed
245    /// to be unchanged by this operation.
246    maybe_split_key: Option<K>,
247
248    /// The value previously stored at this key.
249    removed_value: V,
250}
251
252/// The intermediate result of a remove operation.
253///
254/// The root of the CowTree converts this result value into `Option<T>`, per the usual map
255/// interface.
256enum RemoveResult<K: Ord + Copy + Gap, V: Clone> {
257    /// The key the client asked to remove was not found in the map.
258    NotFound,
259
260    /// The key was successfully removed from the map.
261    ///
262    Removed(RemoveState<K, V>),
263
264    /// The key was removed from the map but the node that previously contained that node no longer
265    /// has sufficient children.
266    ///
267    /// The caller is responsible for rebalancing its children to ensure that each node has at
268    /// least this minimum number of children. If the balance invariant can be resolved locally,
269    /// the caller should return `Removed` to its caller. If rebalancing the local children
270    /// causes this node to have fewer than the minimum number of children, the caller should
271    /// return `Underflow` to its caller.
272    Underflow(RemoveState<K, V>),
273}
274
275impl<K, V> NodeLeaf<K, V>
276where
277    K: Ord + Copy + Gap,
278    V: Clone,
279{
280    /// Create a new leaf node.
281    fn new(keys: ArrayVec<Range<K>, NODE_CAPACITY>, values: ArrayVec<V, NODE_CAPACITY>) -> Self {
282        let mut node = Self { max_gap: 0, keys, values };
283        node.update_max_gap();
284        node
285    }
286
287    /// Create an empty leaf node.
288    ///
289    /// Empty leaf nodes are used only at the root of the tree.
290    fn empty() -> Self {
291        Self { max_gap: 0, keys: ArrayVec::new(), values: ArrayVec::new() }
292    }
293
294    /// Gets the index in this leaf that corresponds to the given cursor.
295    ///
296    /// Assumes the cursor contains exactly one index.
297    ///
298    /// Returns `None` if the cursor points beyond the end if this node.
299    fn get_index(&self, mut cursor: Cursor) -> Option<usize> {
300        let index = cursor.pop().expect("Cursor has sufficient depth");
301        assert!(cursor.is_empty(), "Cursor has excess depth");
302        if index >= self.keys.len() {
303            return None;
304        }
305        Some(index)
306    }
307
308    /// Search this leaf for the given key and return both the key and the value found.
309    fn get_key_value(&self, cursor: Cursor) -> Option<(&Range<K>, &V)> {
310        if let Some(index) = self.get_index(cursor) {
311            let key = &self.keys[index];
312            let value = &self.values[index];
313            Some((key, value))
314        } else {
315            None
316        }
317    }
318
319    /// The last key/value pair stored in this leaf.
320    fn last_key_value(&self) -> Option<(&Range<K>, &V)> {
321        let key = self.keys.last()?;
322        let value = self.values.last()?;
323        Some((key, value))
324    }
325
326    /// Find the given key in this node.
327    ///
328    /// Updates `cursor` to point to the position indicated by `position`.
329    fn find(&self, key: &K, position: CursorPosition, cursor: &mut Cursor) {
330        let index = binary_search(key, &self.keys);
331        match position {
332            CursorPosition::Left => {
333                cursor.push(index);
334            }
335            CursorPosition::Right => {
336                if let Some(range) = self.keys.get(index) {
337                    if *key > range.start {
338                        cursor.push(index + 1);
339                        return;
340                    }
341                }
342                cursor.push(index);
343            }
344        }
345    }
346
347    /// Compute the maximum gap for this node.
348    fn compute_max_gap(&self) -> u64 {
349        let mut max_gap = 0;
350        for i in 0..self.keys.len() {
351            if i + 1 < self.keys.len() {
352                max_gap = max_gap.max(self.keys[i].end.measure_gap(&self.keys[i + 1].start));
353            }
354        }
355        max_gap
356    }
357
358    /// Validates that the cached max_gap value matches what we would compute now.
359    #[cfg(test)]
360    fn validate_max_gap(&self) {
361        let computed = self.compute_max_gap();
362        assert_eq!(computed, self.max_gap);
363    }
364
365    /// Update the maximum gap for this node.
366    fn update_max_gap(&mut self) {
367        self.max_gap = self.compute_max_gap();
368    }
369
370    /// Measure the gap between the last key in this node and the first key in the other node.
371    fn measure_gap(&self, other: &Self) -> u64 {
372        // We know that `self.keys` is not empty because this function is only called when there is
373        // more than one leaf node. The only situation in which `self.keys` is empty is when the
374        // tree is empty, in which case there is only a single empty leaf node.
375        self.keys[self.keys.len() - 1].end.measure_gap(&other.keys[0].start)
376    }
377
378    /// Get the range of keys in this node.
379    fn key_range(&self) -> Range<K> {
380        self.keys[0].start..self.keys[self.keys.len() - 1].end
381    }
382
383    /// Insert the given entry at the location indicated by `cursor`.
384    ///
385    /// Inserting a value into a leaf node might cause this node to split into two leaf nodes.
386    fn insert(&mut self, mut cursor: Cursor, range: Range<K>, value: V) -> InsertResult<K, V> {
387        let index = cursor.pop().expect("valid cursor");
388        let result = if self.keys.len() == NODE_CAPACITY {
389            if index == NODE_CAPACITY {
390                let mut keys = ArrayVec::new();
391                let mut values = ArrayVec::new();
392                let key = range.start;
393                keys.push(range);
394                values.push(value);
395                return InsertResult::SplitLeaf(key, Arc::new(Self::new(keys, values)));
396            }
397            let middle = NODE_CAPACITY / 2;
398            assert!(middle > 0);
399            let mut right = Self::new(
400                self.keys.drain(middle..).collect(),
401                self.values.drain(middle..).collect(),
402            );
403            if index <= middle {
404                self.keys.insert(index, range);
405                self.values.insert(index, value);
406            } else {
407                right.keys.insert(index - middle, range);
408                right.values.insert(index - middle, value);
409                right.update_max_gap();
410            }
411            InsertResult::SplitLeaf(right.keys[0].start, Arc::new(right))
412        } else {
413            self.keys.insert(index, range);
414            self.values.insert(index, value);
415            InsertResult::Inserted
416        };
417        self.update_max_gap();
418        result
419    }
420
421    /// Remove the entry indicated by `cursor`.
422    fn remove(&mut self, cursor: Cursor) -> RemoveResult<K, V> {
423        if let Some(index) = self.get_index(cursor) {
424            self.keys.remove(index);
425            let removed_value = self.values.remove(index);
426            let maybe_split_key = self.keys.first().map(|range| range.start);
427            self.update_max_gap();
428            if self.keys.len() < NODE_CAPACITY / 2 {
429                RemoveResult::Underflow(RemoveState { maybe_split_key, removed_value })
430            } else {
431                RemoveResult::Removed(RemoveState { maybe_split_key, removed_value })
432            }
433        } else {
434            RemoveResult::NotFound
435        }
436    }
437
438    /// Find a gap that is at least as large as the given gap and is less than the given upper bound.
439    ///
440    /// Returns the end of the gap, which might above or below the node.
441    fn find_gap_end(&self, gap: u64, upper_bound: &K) -> K {
442        if self.keys.is_empty() {
443            return *upper_bound;
444        }
445
446        let node_end = &self.keys[self.keys.len() - 1].end;
447        if node_end <= upper_bound && node_end.measure_gap(upper_bound) >= gap {
448            return *upper_bound;
449        }
450
451        if self.max_gap >= gap {
452            for (i, _key) in self.keys.iter().enumerate().rev() {
453                if i > 0 {
454                    let start = &self.keys[i - 1].end;
455                    if start >= upper_bound {
456                        continue;
457                    }
458                    let end = upper_bound.min(&self.keys[i].start);
459                    if start.measure_gap(end) >= gap {
460                        return *end;
461                    }
462                }
463            }
464        }
465
466        let node_start = &self.keys[0].start;
467        *upper_bound.min(node_start)
468    }
469}
470
471/// The children of an internal node in the btree.
472#[derive(Clone, Debug)]
473enum ChildList<K: Ord + Copy + Gap, V: Clone> {
474    /// Used when an internal node has leaf nodes as children.
475    Leaf(ArrayVec<Arc<NodeLeaf<K, V>>, NODE_CAPACITY>),
476
477    /// Used when an internal node has other internal nodes as children.
478    Internal(ArrayVec<Arc<NodeInternal<K, V>>, NODE_CAPACITY>),
479}
480
481impl<K, V> ChildList<K, V>
482where
483    K: Ord + Copy + Gap,
484    V: Clone,
485{
486    /// Create a child list that has no children.
487    fn new_empty(&self) -> Self {
488        match self {
489            ChildList::Leaf(_) => ChildList::Leaf(ArrayVec::new()),
490            ChildList::Internal(_) => ChildList::Internal(ArrayVec::new()),
491        }
492    }
493
494    /// The number of children for this node.
495    fn len(&self) -> usize {
496        match self {
497            ChildList::Leaf(children) => children.len(),
498            ChildList::Internal(children) => children.len(),
499        }
500    }
501
502    /// The number of gradchildren located at the child with the given index.
503    fn size_at(&self, i: usize) -> usize {
504        match self {
505            ChildList::Leaf(children) => children[i].keys.len(),
506            ChildList::Internal(children) => children[i].children.len(),
507        }
508    }
509
510    /// Obtain the child located at the given index.
511    fn get(&self, i: usize) -> Node<K, V> {
512        match self {
513            ChildList::Leaf(children) => Node::Leaf(children[i].clone()),
514            ChildList::Internal(children) => Node::Internal(children[i].clone()),
515        }
516    }
517
518    /// Get a reference to the child located at the given index.
519    fn get_ref(&self, i: usize) -> NodeRef<'_, K, V> {
520        match self {
521            ChildList::Leaf(children) => NodeRef::Leaf(&children[i]),
522            ChildList::Internal(children) => NodeRef::Internal(&children[i]),
523        }
524    }
525
526    /// Get the range of keys in the subtree rooted at this node.
527    fn subtree_key_range(&self) -> Range<K> {
528        match self {
529            ChildList::Leaf(children) => {
530                children[0].key_range().start..children[children.len() - 1].key_range().end
531            }
532            ChildList::Internal(children) => {
533                children[0].subtree_key_range.start
534                    ..children[children.len() - 1].subtree_key_range.end
535            }
536        }
537    }
538
539    /// Removes all the entries starting at the given index from the child list.
540    ///
541    /// The removed entries are returned in a new child list.
542    fn split_off(&mut self, index: usize) -> Self {
543        match self {
544            ChildList::Leaf(children) => ChildList::Leaf(children.drain(index..).collect()),
545            ChildList::Internal(children) => ChildList::Internal(children.drain(index..).collect()),
546        }
547    }
548
549    /// Removes all the entries prior to the given index from the child list.
550    ///
551    /// The removed entries are returned in a new child list.
552    fn split_off_front(&mut self, index: usize) -> Self {
553        match self {
554            ChildList::Leaf(children) => ChildList::Leaf(children.drain(..index).collect()),
555            ChildList::Internal(children) => ChildList::Internal(children.drain(..index).collect()),
556        }
557    }
558
559    /// Insert a child into the child list.
560    ///
561    /// The type of child node must match the type of the child list.
562    fn insert(&mut self, index: usize, child: Node<K, V>) {
563        match self {
564            ChildList::Leaf(children) => {
565                let Node::Leaf(leaf) = child else {
566                    unreachable!("Inserting a non-leaf into an internal node for leaf nodes.");
567                };
568                children.insert(index, leaf);
569            }
570            ChildList::Internal(children) => {
571                let Node::Internal(internal) = child else {
572                    unreachable!(
573                        "Inserting a non-internal into an internal node for internal nodes."
574                    );
575                };
576                children.insert(index, internal);
577            }
578        }
579    }
580
581    /// Remove the child at the given index from the child list.
582    fn remove(&mut self, index: usize) {
583        match self {
584            ChildList::Leaf(children) => {
585                children.remove(index);
586            }
587            ChildList::Internal(children) => {
588                children.remove(index);
589            }
590        }
591    }
592
593    /// Add the children from the given `ChildList` to this child list.
594    fn extend(&mut self, other: &Self) {
595        match (self, other) {
596            (ChildList::Leaf(self_children), ChildList::Leaf(other_children)) => {
597                self_children.extend(other_children.iter().cloned());
598            }
599            (ChildList::Internal(self_children), ChildList::Internal(other_children)) => {
600                self_children.extend(other_children.iter().cloned());
601            }
602            _ => unreachable!("Type mismatch while extending a child list."),
603        }
604    }
605}
606
607/// An internal node in the btree.
608#[derive(Clone, Debug)]
609struct NodeInternal<K: Ord + Copy + Gap, V: Clone> {
610    /// The maximum gap between keys in this internal node.
611    max_gap: u64,
612
613    /// The range of keys stored in the subtree rooted at this node.
614    subtree_key_range: Range<K>,
615
616    /// A cache of the keys that partition the keys in the children.
617    /// The key at index `i` is the smallest key stored in the subtree
618    /// of the `i`+1 child.
619    ///
620    /// We only ever store CAPACITY - 1 keys in this array.
621    keys: ArrayVec<K, NODE_CAPACITY>,
622
623    /// The children of this node.
624    children: ChildList<K, V>,
625}
626
627/// Get mutable references to two entries in a slice.
628///
629/// When rebalancing nodes, we need to mutate two nodes at the same time. Normally, if you take a
630/// mutable reference to one element of an array, the borrow checker prevents you from taking a
631/// mutable reference to a second element of the same array.
632///
633/// The nightly version of `std::primitive::slice` has `get_many_mut` to let you get mutable
634/// references to multiple elements. However, without that interface, the recommended approach for
635/// avoiding `unsafe` is to use `split_at_mut`.
636fn get_two_mut<T>(slice: &mut [T], i: usize, j: usize) -> (&mut T, &mut T) {
637    if i < j {
638        let (a, b) = slice.split_at_mut(j);
639        (&mut a[i], &mut b[0])
640    } else {
641        let (a, b) = slice.split_at_mut(i);
642        (&mut b[0], &mut a[j])
643    }
644}
645
646impl<K, V> NodeInternal<K, V>
647where
648    K: Ord + Copy + Gap,
649    V: Clone,
650{
651    /// Create a new internal node.
652    fn new(keys: ArrayVec<K, NODE_CAPACITY>, children: ChildList<K, V>) -> Self {
653        let mut node =
654            Self { max_gap: 0, subtree_key_range: children.subtree_key_range(), keys, children };
655        node.update_max_gap();
656        node
657    }
658
659    /// The index of the child that might contain the given key.
660    ///
661    /// Searches the cached keys at this node to determine which child node might contain the given
662    /// key.
663    fn get_child_index(&self, key: &K) -> usize {
664        let p = self.keys.partition_point(|k| k < key);
665        if self.keys.get(p) == Some(key) {
666            // If the query key exactly matches the split key, then we need to look for this key to
667            // the right of the split.
668            p + 1
669        } else {
670            // Otherwise, we look to the left of the split.
671            p
672        }
673    }
674
675    /// Search this subtree for the given key and return both the key and the value found.
676    fn get_key_value(&self, mut cursor: Cursor) -> Option<(&Range<K>, &V)> {
677        let index = cursor.pop().expect("valid cursor");
678        match &self.children {
679            ChildList::Leaf(children) => children[index].get_key_value(cursor),
680            ChildList::Internal(children) => children[index].get_key_value(cursor),
681        }
682    }
683
684    /// Returns a reference to the node that contains the entry indicated by the cursor.
685    ///
686    /// Assumes the cursor points a descendant of this node.
687    fn get_containing_node(&self, mut cursor: Cursor) -> NodeRef<'_, K, V> {
688        debug_assert!(cursor.depth >= 2);
689        let index = cursor.pop().expect("valid cursor");
690        if cursor.depth == 1 {
691            return self.children.get_ref(index);
692        }
693        match &self.children {
694            ChildList::Leaf(_) => unreachable!("leaf nodes do not have children"),
695            ChildList::Internal(children) => children[index].get_containing_node(cursor),
696        }
697    }
698
699    /// The last key/value pair stored in this subtree.
700    fn last_key_value(&self) -> Option<(&Range<K>, &V)> {
701        match &self.children {
702            ChildList::Leaf(children) => {
703                children.last().expect("child lists are always non-empty").last_key_value()
704            }
705            ChildList::Internal(children) => {
706                children.last().expect("child lists are always non-empty").last_key_value()
707            }
708        }
709    }
710
711    /// Find the given key in this node.
712    ///
713    /// Updates `cursor` to point to the position indicated by `position`.
714    fn find(&self, key: &K, position: CursorPosition, cursor: &mut Cursor) {
715        let index = self.get_child_index(&key);
716        match &self.children {
717            ChildList::Leaf(children) => children[index].find(key, position, cursor),
718            ChildList::Internal(children) => children[index].find(key, position, cursor),
719        }
720        cursor.push(index);
721    }
722
723    /// Compute the maximum gap for this node.
724    fn compute_max_gap(&self) -> u64 {
725        let mut max_gap = 0;
726        match &self.children {
727            ChildList::Leaf(children) => {
728                for i in 0..children.len() {
729                    max_gap = max_gap.max(children[i].max_gap);
730                    if i < children.len() - 1 {
731                        max_gap = max_gap.max(children[i].measure_gap(&children[i + 1]));
732                    }
733                }
734            }
735            ChildList::Internal(children) => {
736                for i in 0..children.len() {
737                    max_gap = max_gap.max(children[i].max_gap);
738                    if i < children.len() - 1 {
739                        max_gap = max_gap.max(children[i].measure_gap(&children[i + 1]));
740                    }
741                }
742            }
743        }
744        max_gap
745    }
746
747    /// Validates that the cached max_gap value matches what we would compute now,
748    /// and recursively validates all children.
749    #[cfg(test)]
750    fn validate_max_gap(&self) {
751        let computed = self.compute_max_gap();
752        assert_eq!(computed, self.max_gap);
753
754        // Recursively validate children
755        match &self.children {
756            ChildList::Leaf(children) => {
757                for child in children {
758                    child.validate_max_gap();
759                }
760            }
761            ChildList::Internal(children) => {
762                for child in children {
763                    child.validate_max_gap();
764                }
765            }
766        }
767    }
768
769    /// Checks that the keys stored in this node are actually the leftmost edge of the
770    /// corresponding children. Specifically, key `i` should be the `start` of the range of the
771    /// zeroth entry in of child `i+1`.
772    ///
773    /// Panics if the node (or a descendant) does not validate.
774    #[cfg(test)]
775    fn validate_keys(&self) -> K {
776        let mut first_key = None;
777        match &self.children {
778            ChildList::Leaf(children) => {
779                for (i, child) in children.iter().enumerate() {
780                    let child_key = child.keys[0].start;
781                    if i == 0 {
782                        first_key = Some(child_key);
783                    } else {
784                        assert!(child_key == self.keys[i - 1]);
785                    }
786                }
787            }
788            ChildList::Internal(children) => {
789                for (i, child) in children.iter().enumerate() {
790                    let child_key = child.validate_keys();
791                    if i == 0 {
792                        first_key = Some(child_key);
793                    } else {
794                        assert!(child_key == self.keys[i - 1]);
795                    }
796                }
797            }
798        }
799
800        first_key.expect("internal nodes must be non-empty")
801    }
802
803    /// Update the maximum gap for this node.
804    fn update_max_gap(&mut self) {
805        self.subtree_key_range = self.children.subtree_key_range();
806        self.max_gap = self.compute_max_gap();
807    }
808
809    /// Measure the gap between the last key in this node and the first key in the other node.
810    fn measure_gap(&self, other: &Self) -> u64 {
811        self.subtree_key_range.end.measure_gap(&other.subtree_key_range.start)
812    }
813
814    /// Insert the given child node at `index` in this node.
815    ///
816    /// `key` must be the smallest key that occurs in the `child` subtree.
817    ///
818    /// The caller must ensure that the child is inserted in the correct location.
819    fn insert_child(&mut self, index: usize, key: K, child: Node<K, V>) -> InsertResult<K, V> {
820        let n = self.children.len();
821        if n == NODE_CAPACITY {
822            // TODO: This branch is incorrect. We need to check for NODE_CAPACITY - 1 because the
823            // index indicates the location of the existing child that split, which will never be
824            // beyond the end of the array.
825            if index == NODE_CAPACITY {
826                let mut children = self.children.new_empty();
827                children.insert(0, child);
828                let right = Self::new(ArrayVec::new(), children);
829                return InsertResult::SplitInternal(key, Arc::new(right));
830            }
831            let middle = NODE_CAPACITY / 2;
832            assert!(middle > 0);
833            let mut internal =
834                Self::new(self.keys.drain(middle..).collect(), self.children.split_off(middle));
835            let split_key = self.keys.pop().unwrap();
836            if index < middle {
837                self.keys.insert(index, key);
838                self.children.insert(index + 1, child);
839            } else {
840                internal.keys.insert(index - middle, key);
841                internal.children.insert(index - middle + 1, child);
842            }
843            debug_assert!(self.keys.len() + 1 == self.children.len());
844            debug_assert!(internal.keys.len() + 1 == internal.children.len());
845            internal.update_max_gap();
846            InsertResult::SplitInternal(split_key, Arc::new(internal))
847        } else {
848            self.keys.insert(index, key);
849            self.children.insert(index + 1, child);
850            debug_assert!(self.keys.len() + 1 == self.children.len());
851            InsertResult::Inserted
852        }
853    }
854
855    /// Insert the given entry at the location indicated by `cursor`.
856    ///
857    /// Inserting a value into an internal node might cause this node to split into two internal
858    /// nodes.
859    fn insert(&mut self, mut cursor: Cursor, range: Range<K>, value: V) -> InsertResult<K, V> {
860        let index = cursor.pop().expect("valid cursor");
861        let result = match &mut self.children {
862            ChildList::Leaf(children) => {
863                Arc::make_mut(&mut children[index]).insert(cursor, range, value)
864            }
865            ChildList::Internal(children) => {
866                Arc::make_mut(&mut children[index]).insert(cursor, range, value)
867            }
868        };
869        let result = match result {
870            InsertResult::Inserted => InsertResult::Inserted,
871            InsertResult::SplitLeaf(key, right) => self.insert_child(index, key, Node::Leaf(right)),
872            InsertResult::SplitInternal(key, right) => {
873                self.insert_child(index, key, Node::Internal(right))
874            }
875        };
876        self.update_max_gap();
877        result
878    }
879
880    /// Determine whether to rebalance the child with the given index to the left or to the right.
881    ///
882    /// Given a choice, we will rebalance the child with its larger neighbor.
883    ///
884    /// The indices returned are always sequential.
885    fn select_children_to_rebalance(&self, index: usize) -> (usize, usize) {
886        if index == 0 {
887            (index, index + 1)
888        } else if index == self.children.len() - 1 {
889            (index - 1, index)
890        } else {
891            let left_index = index - 1;
892            let left_size = self.children.size_at(left_index);
893            let right_index = index + 1;
894            let right_size = self.children.size_at(right_index);
895            if left_size > right_size {
896                (left_index, index)
897            } else {
898                (index, right_index)
899            }
900        }
901    }
902    /// Rebalance the child at the given index.
903    ///
904    /// If the child and its neighbor are sufficiently small, this function will merge them into a
905    /// single node.
906    fn rebalance_child(&mut self, index: usize) {
907        // Cannot rebalance if we have fewer than two children. This situation occurs only at the
908        // root of the tree.
909        if self.children.len() < 2 {
910            return;
911        }
912        let (left, right) = self.select_children_to_rebalance(index);
913        let left_size = self.children.size_at(left);
914        debug_assert!(left_size > 0);
915        let right_size = self.children.size_at(right);
916        debug_assert!(right_size > 0);
917        let n = left_size + right_size;
918        match &mut self.children {
919            ChildList::Leaf(children) => {
920                let (left_shared_node, right_shared_node) = get_two_mut(children, left, right);
921                let left_node = Arc::make_mut(left_shared_node);
922                if n <= NODE_CAPACITY {
923                    // Merge the right node into the left node.
924                    left_node.keys.extend(right_shared_node.keys.iter().cloned());
925                    left_node.values.extend(right_shared_node.values.iter().cloned());
926                    left_node.update_max_gap();
927                    self.keys.remove(left);
928                    self.children.remove(right);
929                } else {
930                    // Rebalance the elements between the nodes.
931                    let split = n / 2;
932                    let right_node = Arc::make_mut(right_shared_node);
933                    if left_node.values.len() < split {
934                        // Move elements from right to left.
935                        let move_count = split - left_node.values.len();
936                        left_node.keys.extend(right_node.keys.drain(..move_count));
937                        left_node.values.extend(right_node.values.drain(..move_count));
938                    } else {
939                        // Move elements from left to right.
940                        let mut keys = ArrayVec::new();
941                        keys.extend(left_node.keys.drain(split..));
942                        keys.extend(right_node.keys.iter().cloned());
943                        right_node.keys = keys;
944
945                        let mut values = ArrayVec::new();
946                        values.extend(left_node.values.drain(split..));
947                        values.extend(right_node.values.iter().cloned());
948                        right_node.values = values;
949                    }
950                    left_node.update_max_gap();
951                    right_node.update_max_gap();
952                    // Update the split key to reflect the new division between the nodes.
953                    self.keys[left] = right_node.keys[0].start;
954                }
955            }
956            ChildList::Internal(children) => {
957                let (left_shard_node, right_shared_node) = get_two_mut(children, left, right);
958                let left_node = Arc::make_mut(left_shard_node);
959                let old_split_key = &self.keys[left];
960                if n <= NODE_CAPACITY {
961                    // Merge the right node into the left node.
962                    left_node.keys.push(old_split_key.clone());
963                    left_node.keys.extend(right_shared_node.keys.iter().cloned());
964                    left_node.children.extend(&right_shared_node.children);
965                    left_node.update_max_gap();
966                    debug_assert!(left_node.keys.len() + 1 == left_node.children.len());
967                    self.keys.remove(left);
968                    self.children.remove(right);
969                } else {
970                    // Rebalance the elements between the nodes.
971                    let split = n / 2;
972                    let split_key;
973                    let right_node = Arc::make_mut(right_shared_node);
974                    if left_node.children.len() < split {
975                        // Move elements from right to left.
976                        let move_count = split - left_node.children.len();
977                        left_node.keys.push(old_split_key.clone());
978                        left_node.keys.extend(right_node.keys.drain(..move_count));
979                        split_key =
980                            left_node.keys.pop().expect("must have moved at least one element");
981
982                        left_node.children.extend(&right_node.children.split_off_front(move_count));
983                        debug_assert!(left_node.keys.len() + 1 == left_node.children.len());
984                    } else {
985                        // Move elements from left to right.
986                        let mut it = left_node.keys.drain((split - 1)..);
987                        split_key = it.next().expect("must be moving at least one element");
988                        let mut keys = ArrayVec::new();
989                        keys.extend(it);
990                        keys.push(old_split_key.clone());
991                        keys.extend(right_node.keys.iter().cloned());
992                        right_node.keys = keys;
993
994                        let mut children = right_node.children.new_empty();
995                        children.extend(&left_node.children.split_off(split));
996                        children.extend(&right_node.children);
997                        right_node.children = children;
998                        debug_assert!(left_node.keys.len() + 1 == left_node.children.len());
999                        debug_assert!(right_node.keys.len() + 1 == right_node.children.len());
1000                    }
1001                    left_node.update_max_gap();
1002                    right_node.update_max_gap();
1003                    // Update the split key to reflect the new division between the nodes.
1004                    self.keys[left] = split_key;
1005                }
1006            }
1007        }
1008    }
1009
1010    /// Remove the entry indicated by `cursor`.
1011    fn remove(&mut self, mut cursor: Cursor) -> RemoveResult<K, V> {
1012        let index = cursor.pop().expect("valid cursor");
1013        let result = match &mut self.children {
1014            ChildList::Leaf(children) => Arc::make_mut(&mut children[index]).remove(cursor),
1015            ChildList::Internal(children) => Arc::make_mut(&mut children[index]).remove(cursor),
1016        };
1017        match result {
1018            RemoveResult::NotFound => RemoveResult::NotFound,
1019            RemoveResult::Removed(RemoveState { mut maybe_split_key, removed_value }) => {
1020                if let Some(key) = maybe_split_key {
1021                    if index > 0 {
1022                        self.keys[index - 1] = key;
1023                        maybe_split_key = None;
1024                    }
1025                }
1026                self.update_max_gap();
1027                RemoveResult::Removed(RemoveState { maybe_split_key, removed_value })
1028            }
1029            RemoveResult::Underflow(RemoveState { mut maybe_split_key, removed_value }) => {
1030                if let Some(key) = maybe_split_key {
1031                    if index > 0 {
1032                        self.keys[index - 1] = key;
1033                        maybe_split_key = None;
1034                    }
1035                }
1036                // If the child underflowed to zero we can simply remove the child rather than
1037                // rebalancing existing nodes.
1038                if self.children.size_at(index) == 0 {
1039                    // If the child underflowed to zero elements, the child cannot have a split key
1040                    // because the child has no keys.
1041                    debug_assert!(maybe_split_key.is_none());
1042                    self.children.remove(index);
1043                    if index == 0 {
1044                        // When we remove the first child, we need to return the split key for the
1045                        // new first child to our parent.
1046                        maybe_split_key = Some(self.keys.remove(0));
1047                    } else {
1048                        // Otherwise, we can just remove the split key associated with the removed
1049                        // child.
1050                        self.keys.remove(index - 1);
1051                    }
1052                } else {
1053                    self.rebalance_child(index);
1054                }
1055                self.update_max_gap();
1056                if self.children.len() < NODE_CAPACITY / 2 {
1057                    RemoveResult::Underflow(RemoveState { maybe_split_key, removed_value })
1058                } else {
1059                    RemoveResult::Removed(RemoveState { maybe_split_key, removed_value })
1060                }
1061            }
1062        }
1063    }
1064
1065    /// Find a gap that is at least as large as the given gap and is less than the given upper bound.
1066    ///
1067    /// Returns the end of the gap, which might above or below the node.
1068    fn find_gap_end(&self, gap: u64, upper_bound: &K) -> K {
1069        let node_start = &self.subtree_key_range.start;
1070        if node_start > upper_bound {
1071            return *upper_bound;
1072        }
1073
1074        let node_end = &self.subtree_key_range.end;
1075        if node_end <= upper_bound && node_end.measure_gap(upper_bound) >= gap {
1076            return *upper_bound;
1077        }
1078
1079        if self.max_gap >= gap {
1080            match &self.children {
1081                ChildList::Leaf(children) => {
1082                    let mut child_upper_bound = *upper_bound;
1083                    for (i, child) in children.iter().enumerate().rev() {
1084                        if child.key_range().start >= *upper_bound {
1085                            continue;
1086                        }
1087                        let end = child.find_gap_end(gap, &child_upper_bound);
1088                        if i > 0 {
1089                            let start = children[i - 1].key_range().end;
1090                            if start.measure_gap(&end) < gap {
1091                                child_upper_bound = start;
1092                                continue;
1093                            }
1094                        }
1095                        return end;
1096                    }
1097                }
1098                ChildList::Internal(children) => {
1099                    let mut child_upper_bound = *upper_bound;
1100                    for (i, child) in children.iter().enumerate().rev() {
1101                        if child.subtree_key_range.start >= *upper_bound {
1102                            continue;
1103                        }
1104                        let end = child.find_gap_end(gap, &child_upper_bound);
1105                        if i > 0 {
1106                            let start = children[i - 1].subtree_key_range.end;
1107                            if start.measure_gap(&end) < gap {
1108                                child_upper_bound = start;
1109                                continue;
1110                            }
1111                        }
1112                        return end;
1113                    }
1114                }
1115            }
1116        }
1117
1118        *node_start
1119    }
1120}
1121
1122/// A node in the btree.
1123#[derive(Clone, Debug)]
1124enum Node<K: Ord + Copy + Gap, V: Clone> {
1125    /// An internal node.
1126    Internal(Arc<NodeInternal<K, V>>),
1127
1128    /// A leaf node.
1129    Leaf(Arc<NodeLeaf<K, V>>),
1130}
1131
1132impl<K, V> Node<K, V>
1133where
1134    K: Ord + Copy + Gap,
1135    V: Clone,
1136{
1137    /// The number of children stored at this node.
1138    fn len(&self) -> usize {
1139        match self {
1140            Node::Internal(node) => node.children.len(),
1141            Node::Leaf(node) => node.keys.len(),
1142        }
1143    }
1144
1145    /// Search this node for the given key and return both the key and the value found.
1146    fn get_key_value(&self, cursor: Cursor) -> Option<(&Range<K>, &V)> {
1147        match self {
1148            Node::Leaf(node) => node.get_key_value(cursor),
1149            Node::Internal(node) => node.get_key_value(cursor),
1150        }
1151    }
1152
1153    /// The last key/value pair stored in this node.
1154    fn last_key_value(&self) -> Option<(&Range<K>, &V)> {
1155        match self {
1156            Node::Leaf(node) => node.last_key_value(),
1157            Node::Internal(node) => node.last_key_value(),
1158        }
1159    }
1160
1161    /// Converts a reference into a Node into a NodeRef.
1162    fn as_ref(&self) -> NodeRef<'_, K, V> {
1163        match self {
1164            Node::Internal(node) => NodeRef::Internal(node),
1165            Node::Leaf(node) => NodeRef::Leaf(node),
1166        }
1167    }
1168
1169    /// Returns a reference to the node that contains the entry indicated by the cursor.
1170    ///
1171    /// Assumes the cursor is non-empty.
1172    fn get_containing_node(&self, cursor: Cursor) -> NodeRef<'_, K, V> {
1173        assert!(cursor.depth > 0);
1174        if cursor.depth == 1 {
1175            return self.as_ref();
1176        }
1177        match self {
1178            Node::Internal(node) => node.get_containing_node(cursor),
1179            Node::Leaf(_) => unreachable!("leaf nodes do not have children"),
1180        }
1181    }
1182
1183    /// Insert the given value at the location indicated by `cursor`.
1184    ///
1185    /// If the insertion causes this node to split, the node will always split into two instances
1186    /// of the same type of node.
1187    fn insert(&mut self, cursor: Cursor, range: Range<K>, value: V) -> InsertResult<K, V> {
1188        match self {
1189            Node::Internal(node) => Arc::make_mut(node).insert(cursor, range, value),
1190            Node::Leaf(node) => Arc::make_mut(node).insert(cursor, range, value),
1191        }
1192    }
1193
1194    /// Remove the entry indicated by `cursor`.
1195    fn remove(&mut self, cursor: Cursor) -> RemoveResult<K, V> {
1196        match self {
1197            Node::Internal(node) => Arc::make_mut(node).remove(cursor),
1198            Node::Leaf(node) => Arc::make_mut(node).remove(cursor),
1199        }
1200    }
1201
1202    /// Find the given key in this node.
1203    ///
1204    /// Updates `cursor` to point to the position indicated by `position`.
1205    fn find(&self, key: &K, position: CursorPosition, cursor: &mut Cursor) {
1206        match self {
1207            Node::Internal(node) => node.find(key, position, cursor),
1208            Node::Leaf(node) => node.find(key, position, cursor),
1209        }
1210    }
1211
1212    /// Find a gap that is at least as large as the given gap and is less than the given upper bound.
1213    ///
1214    /// Returns the end of the gap, which might above or below the node.
1215    fn find_gap_end(&self, gap: u64, upper_bound: &K) -> K {
1216        match self {
1217            Node::Leaf(node) => node.find_gap_end(gap, upper_bound),
1218            Node::Internal(node) => node.find_gap_end(gap, upper_bound),
1219        }
1220    }
1221
1222    #[cfg(test)]
1223    fn validate_max_gap(&self) {
1224        match self {
1225            Node::Leaf(node) => node.validate_max_gap(),
1226            Node::Internal(node) => node.validate_max_gap(),
1227        }
1228    }
1229
1230    /// If this node is an internal node, validates that the keys held by this node are correct.
1231    ///
1232    /// Panics if the node (or a descendant) does not validate.
1233    #[cfg(test)]
1234    fn validate_keys(&self) {
1235        if let Node::Internal(node) = self {
1236            node.validate_keys();
1237        }
1238    }
1239}
1240
1241/// A node in the btree.
1242#[derive(Clone, Debug)]
1243enum NodeRef<'a, K: Ord + Copy + Gap, V: Clone> {
1244    /// An internal node.
1245    Internal(&'a Arc<NodeInternal<K, V>>),
1246
1247    /// A leaf node.
1248    Leaf(&'a Arc<NodeLeaf<K, V>>),
1249}
1250
1251impl<'a, K, V> NodeRef<'a, K, V>
1252where
1253    K: Ord + Copy + Gap,
1254    V: Clone,
1255{
1256    /// The number of children stored at this node.
1257    fn len(&self) -> usize {
1258        match self {
1259            NodeRef::Internal(node) => node.children.len(),
1260            NodeRef::Leaf(node) => node.keys.len(),
1261        }
1262    }
1263}
1264
1265/// An iterator over the key-value pairs stored in a RangeMap.
1266#[derive(Debug)]
1267pub struct Iter<'a, K: Ord + Copy + Gap, V: Clone> {
1268    /// The state of the forward iteration.
1269    ///
1270    /// The cursor points to the next entry to enumerate.
1271    forward: Cursor,
1272
1273    /// The state of the backward iteration.
1274    ///
1275    /// The cursor points to the child that was most recently iterated or just past the end of the
1276    /// entry list if no entries have been enumerated from this leaf yet.
1277    backward: Cursor,
1278
1279    /// The root node of the tree.
1280    root: &'a Node<K, V>,
1281}
1282
1283impl<'a, K, V> Iter<'a, K, V>
1284where
1285    K: Ord + Copy + Gap,
1286    V: Clone,
1287{
1288    /// Whether the iterator is complete.
1289    ///
1290    /// Iteration stops when the forward and backward cursors meet.
1291    fn is_done(&self) -> bool {
1292        self.forward == self.backward
1293    }
1294}
1295
1296impl<'a, K, V> Iterator for Iter<'a, K, V>
1297where
1298    K: Ord + Copy + Gap,
1299    V: Clone,
1300{
1301    type Item = (&'a Range<K>, &'a V);
1302
1303    fn next(&mut self) -> Option<Self::Item> {
1304        while !self.is_done() {
1305            match self.root.get_containing_node(self.forward) {
1306                NodeRef::Leaf(leaf) => {
1307                    let index = self.forward.back();
1308                    if index < leaf.keys.len() {
1309                        let key = &leaf.keys[index];
1310                        let value = &leaf.values[index];
1311                        self.forward.increment_back();
1312                        return Some((key, value));
1313                    } else {
1314                        self.forward.pop_back();
1315                        self.forward.increment_back();
1316                    }
1317                }
1318                NodeRef::Internal(internal) => {
1319                    let index = self.forward.back();
1320                    if index < internal.children.len() {
1321                        self.forward.push_back(0);
1322                    } else {
1323                        self.forward.pop_back();
1324                        self.forward.increment_back();
1325                    }
1326                }
1327            }
1328        }
1329        None
1330    }
1331}
1332
1333impl<'a, K, V> DoubleEndedIterator for Iter<'a, K, V>
1334where
1335    K: Ord + Copy + Gap,
1336    V: Clone,
1337{
1338    fn next_back(&mut self) -> Option<Self::Item> {
1339        while !self.is_done() {
1340            match self.root.get_containing_node(self.backward) {
1341                NodeRef::Leaf(leaf) => {
1342                    let index = self.backward.back();
1343                    if index > 0 {
1344                        let key = &leaf.keys[index - 1];
1345                        let value = &leaf.values[index - 1];
1346                        self.backward.decrement_back();
1347                        return Some((key, value));
1348                    } else {
1349                        self.backward.pop_back();
1350                    }
1351                }
1352                NodeRef::Internal(internal) => {
1353                    let index = self.backward.back();
1354                    if index > 0 {
1355                        let child = internal.children.get_ref(index - 1);
1356                        self.backward.decrement_back();
1357                        self.backward.push_back(child.len());
1358                    } else {
1359                        self.backward.pop_back();
1360                    }
1361                }
1362            }
1363        }
1364        None
1365    }
1366}
1367
1368/// A map from ranges to values.
1369///
1370/// This map can be cloned efficiently. If the map is modified after being cloned, the relevant
1371/// parts of the map's internal structure will be copied lazily.
1372#[derive(Clone, Debug)]
1373pub struct RangeMap<K: Ord + Copy + Gap, V: Clone + Eq> {
1374    /// The root node of the tree.
1375    ///
1376    /// The root node is either a leaf of an internal node, depending on the number of entries in
1377    /// the map.
1378    node: Node<K, V>,
1379}
1380
1381impl<K, V> Default for RangeMap<K, V>
1382where
1383    K: Ord + Copy + Gap,
1384    V: Clone + Eq,
1385{
1386    fn default() -> Self {
1387        Self { node: Node::Leaf(Arc::new(NodeLeaf::empty())) }
1388    }
1389}
1390
1391impl<K, V> RangeMap<K, V>
1392where
1393    K: Ord + Copy + Gap,
1394    V: Clone + Eq,
1395{
1396    /// Whether this map contains any entries.
1397    pub fn is_empty(&self) -> bool {
1398        match &self.node {
1399            Node::Leaf(node) => node.keys.is_empty(),
1400            Node::Internal(_) => false,
1401        }
1402    }
1403
1404    /// Find the given key in this node.
1405    ///
1406    /// Returns a Cursor that points to the position indicated by `position`.
1407    fn find(&self, key: &K, position: CursorPosition) -> Cursor {
1408        let mut cursor = Cursor::default();
1409        self.node.find(key, position, &mut cursor);
1410        cursor
1411    }
1412
1413    /// If the entry indicated by the cursor contains `key`, returns the range and value stored at
1414    /// that entry.
1415    fn get_if_contains_key(&self, key: &K, cursor: Cursor) -> Option<(&Range<K>, &V)> {
1416        if let Some((range, value)) = self.node.get_key_value(cursor) {
1417            if range.contains(key) {
1418                return Some((range, value));
1419            }
1420        }
1421        None
1422    }
1423
1424    /// Searches the map for a range that contains the given key.
1425    ///
1426    /// Returns the range and value if such a range is found.
1427    pub fn get(&self, key: K) -> Option<(&Range<K>, &V)> {
1428        self.get_if_contains_key(&key, self.find(&key, CursorPosition::Left))
1429    }
1430
1431    /// The last range stored in this map.
1432    pub fn last_range(&self) -> Option<&Range<K>> {
1433        self.node.last_key_value().map(|(key, _)| key)
1434    }
1435
1436    /// Searches the map for a range that contains the given key.
1437    ///
1438    /// If such a range is found, returns a cursor to that entry, the range, and the value.
1439    fn get_cursor_key_value(&mut self, key: &K) -> Option<(Cursor, Range<K>, V)> {
1440        let cursor = self.find(key, CursorPosition::Left);
1441        self.get_if_contains_key(key, cursor)
1442            .map(|(range, value)| (cursor, range.clone(), value.clone()))
1443    }
1444
1445    /// Find a gap that is at least as large as the given gap and is less than the given upper bound.
1446    ///
1447    /// Returns the end of the gap, which might above or below the entries in the map.
1448    pub fn find_gap_end(&self, gap: u64, upper_bound: &K) -> K {
1449        self.node.find_gap_end(gap, upper_bound)
1450    }
1451
1452    /// Remove the entry with the given key from the map.
1453    ///
1454    /// If the key was present in the map, returns the value previously stored at the given key.
1455    pub fn remove(&mut self, range: Range<K>) -> Vec<V> {
1456        let mut removed_values = vec![];
1457
1458        if range.end <= range.start {
1459            return removed_values;
1460        }
1461
1462        if let Some((cursor, old_range, v)) = self.get_cursor_key_value(&range.start) {
1463            // Remove that range from the map.
1464            removed_values.push(self.remove_at(cursor).expect("entry should exist"));
1465
1466            // If the removed range extends after the end of the given range,
1467            // re-insert the part of the old range that extends beyond the end
1468            // of the given range.
1469            if old_range.end > range.end {
1470                self.insert_range_internal(range.end..old_range.end, v.clone());
1471            }
1472
1473            // If the removed range extends before the start of the given
1474            // range, re-insert the part of the old range that extends before
1475            // the start of the given range.
1476            if old_range.start < range.start {
1477                self.insert_range_internal(old_range.start..range.start, v);
1478            }
1479
1480            // Notice that we can end up splitting the old range into two
1481            // separate ranges if the old range extends both beyond the given
1482            // range and before the given range.
1483        }
1484
1485        if let Some((cursor, old_range, v)) = self.get_cursor_key_value(&range.end) {
1486            // If the old range starts before the removed range, we need to trim the old range.
1487            // TODO: Optimize with replace once available.
1488            if old_range.start < range.end {
1489                // Remove that range from the map.
1490                removed_values.push(self.remove_at(cursor).expect("entry should exist"));
1491
1492                // If the removed range extends after the end of the given range,
1493                // re-insert the part of the old range that extends beyond the end
1494                // of the given range.
1495                if old_range.end > range.end {
1496                    self.insert_range_internal(range.end..old_range.end, v);
1497                }
1498            }
1499        }
1500
1501        let doomed = self.range(range.start..range.end).map(|(r, _)| r.start).collect::<Vec<_>>();
1502        for key in doomed {
1503            let cursor = self.find(&key, CursorPosition::Left);
1504            removed_values.push(self.remove_at(cursor).expect("entry should exist"));
1505        }
1506
1507        #[cfg(test)]
1508        self.node.validate_max_gap();
1509
1510        #[cfg(test)]
1511        self.node.validate_keys();
1512
1513        removed_values
1514    }
1515
1516    /// Insert the given range and value at the location indicated by the cursor.
1517    fn insert_at(&mut self, cursor: Cursor, range: Range<K>, value: V) -> Option<V> {
1518        let result = self.node.insert(cursor, range, value);
1519        match result {
1520            InsertResult::Inserted => None,
1521            InsertResult::SplitLeaf(key, right) => {
1522                let mut keys = ArrayVec::new();
1523                let mut children = ArrayVec::new();
1524                keys.push(key);
1525                let Node::Leaf(left) = self.node.clone() else {
1526                    unreachable!("non-leaf node split into leaf node");
1527                };
1528                children.push(left);
1529                children.push(right);
1530                self.node =
1531                    Node::Internal(Arc::new(NodeInternal::new(keys, ChildList::Leaf(children))));
1532                None
1533            }
1534            InsertResult::SplitInternal(key, right) => {
1535                let mut keys = ArrayVec::new();
1536                let mut children = ArrayVec::new();
1537                keys.push(key);
1538                let Node::Internal(left) = self.node.clone() else {
1539                    unreachable!("non-internal node split into internal node");
1540                };
1541                children.push(left);
1542                children.push(right);
1543                let mut new_internal = NodeInternal::new(keys, ChildList::Internal(children));
1544                new_internal.update_max_gap();
1545                self.node = Node::Internal(Arc::new(new_internal));
1546                None
1547            }
1548        }
1549    }
1550
1551    /// Insert the given range and value.
1552    ///
1553    /// Assumes the range is empty and that adjacent ranges have different values.
1554    fn insert_range_internal(&mut self, range: Range<K>, value: V) -> Option<V> {
1555        assert!(range.end > range.start);
1556        let cursor = self.find(&range.start, CursorPosition::Left);
1557        self.insert_at(cursor, range, value)
1558    }
1559
1560    /// Inserts a range with the given value.
1561    ///
1562    /// The keys included in the given range are now associated with the given
1563    /// value. If those keys were previously associated with another value,
1564    /// are no longer associated with that previous value.
1565    ///
1566    /// This method can cause one or more values in the map to be dropped if
1567    /// the all of the keys associated with those values are contained within
1568    /// the given range.
1569    ///
1570    /// If the inserted range is directly adjacent to another range with an equal value, the
1571    /// inserted range will be merged with the adjacent ranges.
1572    pub fn insert(&mut self, mut range: Range<K>, value: V) {
1573        if range.end <= range.start {
1574            return;
1575        }
1576        self.remove(range.clone());
1577
1578        // Check for a range directly before this one. If it exists, it will be the last range with
1579        // start < range.start.
1580        if let Some((prev_range, prev_value)) = self.range(..range.start).next_back() {
1581            if prev_range.end == range.start && value == *prev_value {
1582                let cursor = self.find(&prev_range.start, CursorPosition::Left);
1583                range.start = prev_range.start;
1584                self.remove_at(cursor);
1585            }
1586        }
1587
1588        // Check for a range directly after. If it exists, we can look it up by exact start value
1589        // of range.end.
1590        if let Some((cursor, next_range, next_value)) = self.get_cursor_key_value(&range.end) {
1591            if next_range.start == range.end && value == next_value {
1592                range.end = next_range.end;
1593                self.remove_at(cursor);
1594            }
1595        }
1596
1597        self.insert_range_internal(range, value);
1598
1599        #[cfg(test)]
1600        self.node.validate_max_gap();
1601
1602        #[cfg(test)]
1603        self.node.validate_keys();
1604    }
1605
1606    /// Remove the entry with the given cursor from the map.
1607    fn remove_at(&mut self, cursor: Cursor) -> Option<V> {
1608        let result = self.node.remove(cursor);
1609        match result {
1610            RemoveResult::NotFound => None,
1611            RemoveResult::Removed(RemoveState { removed_value, .. }) => Some(removed_value),
1612            RemoveResult::Underflow(RemoveState { removed_value, .. }) => {
1613                match &mut self.node {
1614                    Node::Leaf(_) => {
1615                        // Nothing we can do about an underflow of a single leaf node at the root.
1616                    }
1617                    Node::Internal(node) => {
1618                        // If the root has underflown to a trivial list, we can shrink the tree.
1619                        if node.children.len() == 1 {
1620                            self.node = node.children.get(0);
1621                        }
1622                    }
1623                }
1624                Some(removed_value)
1625            }
1626        }
1627    }
1628
1629    /// Iterate through the keys and values stored in the map.
1630    pub fn iter(&self) -> Iter<'_, K, V> {
1631        Iter {
1632            forward: Cursor::with_index(0),
1633            backward: Cursor::with_index(self.node.len()),
1634            root: &self.node,
1635        }
1636    }
1637
1638    /// Create the cursor stack for the start bound of the given range.
1639    fn find_start_bound(&self, bounds: &impl RangeBounds<K>) -> Cursor {
1640        let key = match bounds.start_bound() {
1641            Bound::Included(key) => key,
1642            Bound::Excluded(key) => key,
1643            Bound::Unbounded => {
1644                return Cursor::with_index(0);
1645            }
1646        };
1647        self.find(key, CursorPosition::Left)
1648    }
1649
1650    /// Create the cursor stack for the end bound of the given range.
1651    fn find_end_bound(&self, bounds: &impl RangeBounds<K>) -> Cursor {
1652        let key = match bounds.end_bound() {
1653            Bound::Included(key) => key,
1654            Bound::Excluded(key) => key,
1655            Bound::Unbounded => {
1656                return Cursor::with_index(self.node.len());
1657            }
1658        };
1659        self.find(key, CursorPosition::Right)
1660    }
1661
1662    /// Iterate through the keys and values stored in the given range in the map.
1663    pub fn range(&self, bounds: impl RangeBounds<K>) -> Iter<'_, K, V> {
1664        let forward = self.find_start_bound(&bounds);
1665        let backward = self.find_end_bound(&bounds);
1666        Iter { forward, backward, root: &self.node }
1667    }
1668
1669    /// Find the first range in the map that starts at or after the given key.
1670    pub fn find_at_or_after(&self, key: K) -> Option<(&Range<K>, &V)> {
1671        let mut iter = self.range(key..).filter(move |(range, _)| key <= range.start);
1672        iter.next()
1673    }
1674}
1675
1676#[cfg(test)]
1677mod test {
1678    use super::*;
1679
1680    #[::fuchsia::test]
1681    fn test_empty() {
1682        let mut map = RangeMap::<u32, i32>::default();
1683
1684        assert!(map.get(12).is_none());
1685        map.remove(10..34);
1686        // This is a test to make sure we can handle reversed ranges
1687        #[allow(clippy::reversed_empty_ranges)]
1688        map.remove(34..10);
1689    }
1690
1691    #[::fuchsia::test]
1692    fn test_is_empty() {
1693        let mut map = RangeMap::<u32, i32>::default();
1694
1695        // Test empty map
1696        assert!(map.is_empty());
1697
1698        // Test map with 5 entries
1699        for i in 0..5 {
1700            let start = i * 10;
1701            let end = start + 5;
1702            map.insert(start..end, i as i32);
1703        }
1704        assert!(!map.is_empty());
1705
1706        // Remove all entries
1707        for i in 0..5 {
1708            let start = i * 10;
1709            let end = start + 5;
1710            map.remove(start..end);
1711        }
1712        assert!(map.is_empty());
1713
1714        // Test map with 50 entries
1715        for i in 0..50 {
1716            let start = i * 10;
1717            let end = start + 5;
1718            map.insert(start..end, i as i32);
1719        }
1720        assert!(!map.is_empty());
1721
1722        // Remove all entries
1723        for i in 0..50 {
1724            let start = i * 10;
1725            let end = start + 5;
1726            map.remove(start..end);
1727        }
1728        assert!(map.is_empty());
1729    }
1730
1731    #[::fuchsia::test]
1732    fn test_insert_into_empty() {
1733        let mut map = RangeMap::<u32, i32>::default();
1734
1735        map.insert(10..34, -14);
1736
1737        assert_eq!((&(10..34), &-14), map.get(12).unwrap());
1738        assert_eq!((&(10..34), &-14), map.get(10).unwrap());
1739        assert!(map.get(9).is_none());
1740        assert_eq!((&(10..34), &-14), map.get(33).unwrap());
1741        assert!(map.get(34).is_none());
1742    }
1743
1744    #[::fuchsia::test]
1745    fn test_iter() {
1746        let mut map = RangeMap::<u32, i32>::default();
1747
1748        map.insert(10..34, -14);
1749        map.insert(74..92, -12);
1750
1751        let mut iter = map.iter();
1752
1753        assert_eq!(iter.next().expect("missing elem"), (&(10..34), &-14));
1754        assert_eq!(iter.next().expect("missing elem"), (&(74..92), &-12));
1755
1756        assert!(iter.next().is_none());
1757
1758        let entry = map.find_at_or_after(10);
1759        assert_eq!(entry.expect("missing elem"), (&(10..34), &-14));
1760        let entry = map.find_at_or_after(11);
1761        assert_eq!(entry.expect("missing elem"), (&(74..92), &-12));
1762        let entry = map.find_at_or_after(74);
1763        assert_eq!(entry.expect("missing elem"), (&(74..92), &-12));
1764        let entry = map.find_at_or_after(75);
1765        assert_eq!(entry, None);
1766
1767        assert_eq!(map.range(..9).collect::<Vec<_>>(), vec![]);
1768        assert_eq!(map.range(..34).collect::<Vec<_>>(), vec![(&(10..34), &-14)]);
1769        assert_eq!(map.range(..74).collect::<Vec<_>>(), vec![(&(10..34), &-14)]);
1770        assert_eq!(map.range(..75).collect::<Vec<_>>(), vec![(&(10..34), &-14), (&(74..92), &-12)]);
1771        assert_eq!(map.range(..91).collect::<Vec<_>>(), vec![(&(10..34), &-14), (&(74..92), &-12)]);
1772        assert_eq!(map.range(..92).collect::<Vec<_>>(), vec![(&(10..34), &-14), (&(74..92), &-12)]);
1773    }
1774
1775    #[::fuchsia::test]
1776    fn test_remove_overlapping_edge() {
1777        let mut map = RangeMap::<u32, i32>::default();
1778
1779        map.insert(10..34, -14);
1780
1781        map.remove(2..11);
1782        assert_eq!((&(11..34), &-14), map.get(11).unwrap());
1783
1784        map.remove(33..42);
1785        assert_eq!((&(11..33), &-14), map.get(12).unwrap());
1786    }
1787
1788    #[::fuchsia::test]
1789    fn test_remove_middle_splits_range() {
1790        let mut map = RangeMap::<u32, i32>::default();
1791
1792        map.insert(10..34, -14);
1793        map.remove(15..18);
1794
1795        assert_eq!((&(10..15), &-14), map.get(12).unwrap());
1796        assert_eq!((&(18..34), &-14), map.get(20).unwrap());
1797    }
1798
1799    #[::fuchsia::test]
1800    fn test_remove_upper_half_of_split_range_leaves_lower_range() {
1801        let mut map = RangeMap::<u32, i32>::default();
1802
1803        map.insert(10..34, -14);
1804        map.remove(15..18);
1805        map.insert(2..7, -21);
1806        map.remove(20..42);
1807
1808        assert_eq!((&(2..7), &-21), map.get(5).unwrap());
1809        assert_eq!((&(10..15), &-14), map.get(12).unwrap());
1810    }
1811
1812    #[::fuchsia::test]
1813    fn test_range_map_overlapping_insert() {
1814        let mut map = RangeMap::<u32, i32>::default();
1815
1816        map.insert(2..7, -21);
1817        map.insert(5..9, -42);
1818        map.insert(1..3, -43);
1819        map.insert(6..8, -44);
1820
1821        assert_eq!((&(1..3), &-43), map.get(2).unwrap());
1822        assert_eq!((&(3..5), &-21), map.get(4).unwrap());
1823        assert_eq!((&(5..6), &-42), map.get(5).unwrap());
1824        assert_eq!((&(6..8), &-44), map.get(7).unwrap());
1825    }
1826
1827    #[::fuchsia::test]
1828    fn test_intersect_single() {
1829        let mut map = RangeMap::<u32, i32>::default();
1830
1831        map.insert(2..7, -10);
1832
1833        let mut iter = map.range(3..4);
1834        assert_eq!(iter.next(), Some((&(2..7), &-10)));
1835        assert_eq!(iter.next(), None);
1836
1837        let mut iter = map.range(2..3);
1838        assert_eq!(iter.next(), Some((&(2..7), &-10)));
1839        assert_eq!(iter.next(), None);
1840
1841        let mut iter = map.range(1..4);
1842        assert_eq!(iter.next(), Some((&(2..7), &-10)));
1843        assert_eq!(iter.next(), None);
1844
1845        let mut iter = map.range(1..2);
1846        assert_eq!(iter.next(), None);
1847
1848        let mut iter = map.range(6..7);
1849        assert_eq!(iter.next(), Some((&(2..7), &-10)));
1850        assert_eq!(iter.next(), None);
1851    }
1852
1853    #[::fuchsia::test]
1854    fn test_intersect_multiple() {
1855        let mut map = RangeMap::<u32, i32>::default();
1856
1857        map.insert(2..7, -10);
1858        map.insert(7..9, -20);
1859        map.insert(10..11, -30);
1860
1861        let mut iter = map.range(3..8);
1862        assert_eq!(iter.next(), Some((&(2..7), &-10)));
1863        assert_eq!(iter.next(), Some((&(7..9), &-20)));
1864        assert_eq!(iter.next(), None);
1865
1866        let mut iter = map.range(3..11);
1867        assert_eq!(iter.next(), Some((&(2..7), &-10)));
1868        assert_eq!(iter.next(), Some((&(7..9), &-20)));
1869        assert_eq!(iter.next(), Some((&(10..11), &-30)));
1870        assert_eq!(iter.next(), None);
1871    }
1872
1873    #[::fuchsia::test]
1874    fn test_intersect_no_gaps() {
1875        let mut map = RangeMap::<u32, i32>::default();
1876
1877        map.insert(0..1, -10);
1878        map.insert(1..2, -20);
1879        map.insert(2..3, -30);
1880
1881        let mut iter = map.range(0..3);
1882        assert_eq!(iter.next(), Some((&(0..1), &-10)));
1883        assert_eq!(iter.next(), Some((&(1..2), &-20)));
1884        assert_eq!(iter.next(), Some((&(2..3), &-30)));
1885        assert_eq!(iter.next(), None);
1886    }
1887
1888    #[test]
1889    fn test_merging() {
1890        let mut map = RangeMap::<u32, i32>::default();
1891
1892        map.insert(1..2, -10);
1893        assert_eq!(map.iter().collect::<Vec<_>>(), vec![(&(1..2), &-10)]);
1894        map.insert(3..4, -10);
1895        assert_eq!(map.iter().collect::<Vec<_>>(), vec![(&(1..2), &-10), (&(3..4), &-10)]);
1896        map.insert(2..3, -10);
1897        assert_eq!(map.iter().collect::<Vec<_>>(), vec![(&(1..4), &-10)]);
1898        map.insert(0..1, -10);
1899        assert_eq!(map.iter().collect::<Vec<_>>(), vec![(&(0..4), &-10)]);
1900        map.insert(4..5, -10);
1901        assert_eq!(map.iter().collect::<Vec<_>>(), vec![(&(0..5), &-10)]);
1902        map.insert(2..3, -20);
1903        assert_eq!(
1904            map.iter().collect::<Vec<_>>(),
1905            vec![(&(0..2), &-10), (&(2..3), &-20), (&(3..5), &-10)]
1906        );
1907    }
1908
1909    #[test]
1910    fn test_remove_multiple_ranges_exact_query() {
1911        let first = 15..21;
1912        let second = first.end..29;
1913
1914        let mut map = RangeMap::default();
1915        map.insert(first.clone(), 1);
1916        map.insert(second.clone(), 2);
1917
1918        assert_eq!(map.remove(first.start..second.end), &[1, 2]);
1919    }
1920
1921    #[::fuchsia::test]
1922    fn test_large_insert_and_remove() {
1923        let mut map = RangeMap::<u32, i32>::default();
1924        let num_entries = 1000;
1925
1926        // Insert a large number of entries
1927        for i in 0..num_entries {
1928            let start = i as u32 * 10;
1929            let end = start + 5;
1930            let value = i as i32;
1931            map.insert(start..end, value);
1932        }
1933
1934        // Verify that all inserted entries can be retrieved
1935        for i in 0..num_entries {
1936            let start = i as u32 * 10;
1937            let end = start + 5;
1938            let point = start + 2;
1939            if let Some((range, value)) = map.get(point) {
1940                assert!(range.start <= point && point < range.end);
1941                assert_eq!(*range, start..end);
1942                assert_eq!(*value, i as i32);
1943            } else {
1944                panic!("Expected to find a range for point {}", point);
1945            }
1946        }
1947
1948        // Remove a large number of entries
1949        for i in 0..num_entries {
1950            let start = i as u32 * 10;
1951            let end = start + 5;
1952            map.remove(start..end);
1953        }
1954
1955        // Verify that the map is empty after removing all entries
1956        assert!(map.is_empty());
1957    }
1958
1959    #[::fuchsia::test]
1960    fn test_large_insert_and_remove_overlapping() {
1961        let mut map = RangeMap::<u32, i32>::default();
1962        let num_entries = 1000;
1963
1964        // Insert a large number of entries with overlapping ranges
1965        for i in 0..num_entries {
1966            let start = i as u32 * 5;
1967            let end = start + 20;
1968            let value = i as i32;
1969            map.insert(start..end, value);
1970        }
1971
1972        // Verify that all inserted entries can be retrieved
1973        for i in 0..num_entries {
1974            let point = i as u32 * 5 + 1;
1975            if let Some((range, value)) = map.get(point) {
1976                assert!(range.start <= point && point < range.end);
1977                assert_eq!(*value, i as i32);
1978            } else {
1979                panic!("Expected to find a range for point {}", point);
1980            }
1981        }
1982
1983        // Remove a large number of entries with overlapping ranges
1984        for i in 0..num_entries {
1985            let start = i as u32 * 5;
1986            let end = start + 20;
1987            map.remove(start..end);
1988        }
1989
1990        // Verify that the map is empty after removing all entries
1991        assert!(map.is_empty());
1992    }
1993
1994    #[::fuchsia::test]
1995    fn test_large_insert_and_get_specific_points() {
1996        let mut map = RangeMap::<u32, i32>::default();
1997        let num_entries = 1000;
1998        let mut inserted_ranges = Vec::new();
1999
2000        // Insert a large number of entries
2001        for i in 0..num_entries {
2002            let start = i as u32 * 10;
2003            let end = start + 5;
2004            let value = i as i32;
2005            map.insert(start..end, value);
2006            inserted_ranges.push((start..end, value));
2007        }
2008
2009        // Verify that specific points can be retrieved correctly
2010        for (range, value) in &inserted_ranges {
2011            let point = range.start + 2;
2012            let (retrieved_range, retrieved_value) = map.get(point).unwrap();
2013            assert_eq!(retrieved_range, range);
2014            assert_eq!(retrieved_value, value);
2015        }
2016    }
2017
2018    #[::fuchsia::test]
2019    fn test_large_insert_and_iter() {
2020        let mut map = RangeMap::<u32, i32>::default();
2021        let num_entries = 1000;
2022        let mut inserted_ranges = Vec::new();
2023
2024        // Insert a large number of entries
2025        for i in 0..num_entries {
2026            let start = i as u32 * 10;
2027            let end = start + 5;
2028            let value = i as i32;
2029            map.insert(start..end, value);
2030            inserted_ranges.push((start..end, value));
2031        }
2032
2033        // Verify that iter() returns all inserted entries
2034        let mut iter_ranges: Vec<(&Range<u32>, &i32)> = map.iter().collect();
2035        iter_ranges.sort_by_key(|(range, _)| range.start);
2036        let mut inserted_ranges_sorted: Vec<(Range<u32>, i32)> = inserted_ranges.clone();
2037        inserted_ranges_sorted.sort_by_key(|(range, _)| range.start);
2038
2039        assert_eq!(iter_ranges.len(), inserted_ranges_sorted.len());
2040        for (i, (range, value)) in iter_ranges.iter().enumerate() {
2041            assert_eq!(*range, &inserted_ranges_sorted[i].0);
2042            assert_eq!(*value, &inserted_ranges_sorted[i].1);
2043        }
2044    }
2045
2046    #[::fuchsia::test]
2047    fn test_large_insert_and_range() {
2048        let mut map = RangeMap::<u32, i32>::default();
2049        let num_entries = 1000;
2050
2051        // Insert a large number of entries
2052        for i in 0..num_entries {
2053            let start = i as u32 * 10;
2054            let end = start + 5;
2055            let value = i as i32;
2056            map.insert(start..end, value);
2057        }
2058
2059        // Verify range(start_point..)
2060        let start_point = 5000;
2061        let mut iter = map.range(start_point..);
2062        while let Some((range, _)) = iter.next() {
2063            assert!(range.start >= start_point);
2064        }
2065    }
2066
2067    #[::fuchsia::test]
2068    fn test_large_insert_and_iter_ending_at() {
2069        let mut map = RangeMap::<u32, i32>::default();
2070        let num_entries = 1000;
2071
2072        // Insert a large number of entries
2073        for i in 0..num_entries {
2074            let start = i as u32 * 10;
2075            let end = start + 5;
2076            let value = i as i32;
2077            map.insert(start..end, value);
2078        }
2079
2080        // Verify range(..end_point)
2081        let end_point = 5000;
2082        let mut iter = map.range(..end_point);
2083        while let Some((range, _)) = iter.next() {
2084            assert!(range.start < end_point);
2085        }
2086    }
2087
2088    #[::fuchsia::test]
2089    fn test_large_insert_and_intersection() {
2090        let mut map = RangeMap::<u32, i32>::default();
2091        let num_entries = 1000;
2092
2093        // Insert a large number of entries
2094        for i in 0..num_entries {
2095            let start = i as u32 * 10;
2096            let end = start + 5;
2097            let value = i as i32;
2098            map.insert(start..end, value);
2099        }
2100
2101        // Verify intersection()
2102        let intersect_start = 4000;
2103        let intersect_end = 4050;
2104        let mut iter = map.range(intersect_start..intersect_end);
2105        while let Some((range, _)) = iter.next() {
2106            assert!((range.start < intersect_end && range.end > intersect_start));
2107        }
2108    }
2109
2110    #[::fuchsia::test]
2111    fn test_large_insert_and_last_range() {
2112        let mut map = RangeMap::<u32, i32>::default();
2113        let num_entries = 1000;
2114        let mut last_range = None;
2115
2116        // Insert a large number of entries
2117        for i in 0..num_entries {
2118            let start = i as u32 * 10;
2119            let end = start + 5;
2120            let value = i as i32;
2121            map.insert(start..end, value);
2122            last_range = Some(start..end);
2123        }
2124
2125        // Verify last_range()
2126        if let Some(expected_last_range) = last_range {
2127            assert_eq!(map.last_range().unwrap(), &expected_last_range);
2128        }
2129    }
2130
2131    #[::fuchsia::test]
2132    fn test_large_insert_and_remove_alternating() {
2133        let mut map = RangeMap::<u32, i32>::default();
2134        let num_entries = 1000;
2135
2136        // Insert and remove entries in an alternating pattern
2137        for i in 0..num_entries {
2138            let start = i as u32 * 10;
2139            let end = start + 5;
2140            let value = i as i32;
2141            map.insert(start..end, value);
2142
2143            if i % 2 == 0 {
2144                // Remove every other entry
2145                map.remove(start..end);
2146            }
2147        }
2148
2149        // Verify that only the non-removed entries remain
2150        for i in 0..num_entries {
2151            let start = i as u32 * 10;
2152            let end = start + 5;
2153            let point = start + 2;
2154            if i % 2 != 0 {
2155                if let Some((range, value)) = map.get(point) {
2156                    assert!(range.start <= point && point < range.end);
2157                    assert_eq!(*range, start..end);
2158                    assert_eq!(*value, i as i32);
2159                } else {
2160                    panic!("Expected to find a range for point {}", point);
2161                }
2162            } else {
2163                assert!(map.get(point).is_none());
2164            }
2165        }
2166    }
2167
2168    #[::fuchsia::test]
2169    fn test_large_insert_and_remove_multiple_times() {
2170        let mut map = RangeMap::<u32, i32>::default();
2171        let num_entries = 200;
2172        let num_iterations = 5;
2173
2174        for _ in 0..num_iterations {
2175            // Insert a large number of entries
2176            for i in 0..num_entries {
2177                let start = i as u32 * 10;
2178                let end = start + 5;
2179                let value = i as i32;
2180                map.insert(start..end, value);
2181            }
2182
2183            // Remove a large number of entries
2184            for i in 0..num_entries {
2185                let start = i as u32 * 10;
2186                let end = start + 5;
2187                map.remove(start..end);
2188            }
2189        }
2190
2191        // Verify that the map is empty after multiple insert/remove cycles
2192        assert!(map.is_empty());
2193    }
2194
2195    #[::fuchsia::test]
2196    fn test_leaf_node_split() {
2197        let mut map = RangeMap::<u32, i32>::default();
2198
2199        // Fill the leaf node to capacity
2200        for i in 0..NODE_CAPACITY {
2201            let start = i as u32 * 10;
2202            let end = start + 5;
2203            map.insert(start..end, i as i32);
2204        }
2205
2206        // Verify the initial state
2207        assert_eq!(map.node.len(), NODE_CAPACITY);
2208
2209        {
2210            let mut map = map.clone();
2211
2212            // Insert a value that causes a split in the first half
2213            let split_start = 15;
2214            let split_end = 20;
2215            map.insert(split_start..split_end, -1);
2216
2217            // Verify the split
2218            assert!(matches!(map.node, Node::Internal(_)));
2219            if let Node::Internal(internal) = &map.node {
2220                assert_eq!(internal.children.len(), 2);
2221                assert!(internal.children.size_at(0) >= NODE_CAPACITY / 2);
2222                assert!(internal.children.size_at(1) >= NODE_CAPACITY / 2);
2223            }
2224        }
2225
2226        {
2227            let mut map = map.clone();
2228
2229            // Insert a value that causes a split in the second half
2230            let split_start = (NODE_CAPACITY as u32 * 10) + 5;
2231            let split_end = split_start + 5;
2232            map.insert(split_start..split_end, -2);
2233
2234            // Verify the second split
2235            if let Node::Internal(internal) = &map.node {
2236                assert_eq!(internal.children.len(), 2);
2237                assert!(internal.children.size_at(0) >= NODE_CAPACITY / 2);
2238            }
2239        }
2240    }
2241
2242    #[::fuchsia::test]
2243    fn test_merging_ranges_with_equal_values() {
2244        let mut map = RangeMap::<u32, i32>::default();
2245
2246        // Insert some initial ranges
2247        map.insert(10..20, 100);
2248        map.insert(30..40, 200);
2249        map.insert(50..60, 100);
2250
2251        // Merge adjacent ranges with equal values
2252        map.insert(20..30, 100);
2253        assert_eq!(map.get(15).unwrap(), (&(10..30), &100));
2254        assert_eq!(map.get(35).unwrap(), (&(30..40), &200));
2255        assert_eq!(map.get(55).unwrap(), (&(50..60), &100));
2256
2257        // Merge non-adjacent ranges with equal values
2258        map.insert(40..50, 100);
2259        assert_eq!(map.get(15).unwrap(), (&(10..30), &100));
2260        assert_eq!(map.get(35).unwrap(), (&(30..40), &200));
2261        assert_eq!(map.get(45).unwrap(), (&(40..60), &100));
2262
2263        // Insert a range with a different value
2264        map.insert(60..70, 300);
2265        assert_eq!(map.get(65).unwrap(), (&(60..70), &300));
2266
2267        // Merge a range with a different value
2268        map.insert(70..80, 300);
2269        assert_eq!(map.get(65).unwrap(), (&(60..80), &300));
2270
2271        // Merge a range with a different value at the beginning
2272        map.insert(0..10, 400);
2273        assert_eq!(map.get(5).unwrap(), (&(0..10), &400));
2274
2275        // Merge a range with a different value at the end
2276        map.insert(80..90, 400);
2277        assert_eq!(map.get(85).unwrap(), (&(80..90), &400));
2278
2279        // Merge a range with a different value in the middle
2280        map.insert(90..100, 400);
2281        assert_eq!(map.get(95).unwrap(), (&(80..100), &400));
2282        map.insert(100..110, 400);
2283        assert_eq!(map.get(95).unwrap(), (&(80..110), &400));
2284        map.insert(110..120, 400);
2285        assert_eq!(map.get(95).unwrap(), (&(80..120), &400));
2286
2287        // Merge a range with a different value in the middle
2288        map.insert(10..90, 400);
2289        assert_eq!(map.get(5).unwrap(), (&(0..120), &400));
2290    }
2291
2292    #[::fuchsia::test]
2293    fn test_large_insert_and_remove_with_gaps() {
2294        let mut map = RangeMap::<u32, i32>::default();
2295        let num_entries = 500;
2296
2297        // Insert entries with gaps
2298        for i in 0..num_entries {
2299            let start = i as u32 * 20;
2300            let end = start + 5;
2301            let value = i as i32;
2302            map.insert(start..end, value);
2303        }
2304
2305        // Remove entries with gaps
2306        for i in 0..num_entries {
2307            if i % 2 == 0 {
2308                let start = i as u32 * 20;
2309                let end = start + 5;
2310                map.remove(start..end);
2311            }
2312        }
2313
2314        // Verify the state of the map
2315        for i in 0..num_entries {
2316            let start = i as u32 * 20;
2317            let end = start + 5;
2318            let point = start + 2;
2319
2320            if i % 2 != 0 {
2321                if let Some((range, value)) = map.get(point) {
2322                    assert!(range.start <= point && point < range.end);
2323                    assert_eq!(*range, start..end);
2324                    assert_eq!(*value, i as i32);
2325                } else {
2326                    panic!("Expected to find a range for point {}", point);
2327                }
2328            } else {
2329                assert!(map.get(point).is_none());
2330            }
2331        }
2332    }
2333
2334    #[::fuchsia::test]
2335    fn test_critical_removal() {
2336        fn range_for(i: u32) -> Range<u32> {
2337            let start = i * 20;
2338            let end = start + 5;
2339            start..end
2340        }
2341
2342        // Index 0 cannot be the critical index.
2343        for critial_index in 1..100 {
2344            let mut map = RangeMap::<u32, i32>::default();
2345
2346            // Insert enough entries for force a split somewhere.
2347            for i in 0..100 {
2348                let value = i as i32;
2349                map.insert(range_for(i), value);
2350            }
2351
2352            // We don't know whether the split will occur at the critical index, but we try all the
2353            // possible indices to ensure that we test an index at which a split occurred.
2354            let critical_range = range_for(critial_index);
2355            map.remove(critical_range.clone());
2356
2357            // We now insert a range that spans the critical point. This range will be inserted to
2358            // left of the split.
2359            let value = -10 as i32;
2360            let spanning_range = (critical_range.start - 2)..(critical_range.start + 2);
2361            map.insert(spanning_range.clone(), value);
2362
2363            // Check to see if we can find the range by looking before the critical point.
2364            let key_before_split = critical_range.start - 1;
2365            assert_eq!(map.get(key_before_split), Some((&spanning_range, &value)));
2366
2367            // Check to see if we can find the range by looking after the critical point.
2368            let key_after_split = critical_range.start + 1;
2369            assert_eq!(map.get(key_after_split), Some((&spanning_range, &value)));
2370        }
2371    }
2372
2373    #[::fuchsia::test]
2374    fn test_find_gap_end_empty() {
2375        let map = RangeMap::<u32, i32>::default();
2376        assert_eq!(map.find_gap_end(10, &100), 100);
2377    }
2378
2379    #[::fuchsia::test]
2380    fn test_find_gap_end_single_range() {
2381        let mut map = RangeMap::<u32, i32>::default();
2382        map.insert(10..20, 1);
2383        assert_eq!(map.find_gap_end(10, &100), 100);
2384    }
2385
2386    #[::fuchsia::test]
2387    fn test_find_gap_end_multiple_ranges() {
2388        let mut map = RangeMap::<u32, i32>::default();
2389        map.insert(10..20, 1);
2390        map.insert(40..50, 2);
2391        map.insert(60..70, 3);
2392
2393        // Test finding gaps of various sizes
2394        assert_eq!(map.find_gap_end(5, &80), 80);
2395        assert_eq!(map.find_gap_end(10, &80), 80);
2396        assert_eq!(map.find_gap_end(11, &80), 40);
2397        assert_eq!(map.find_gap_end(20, &80), 40);
2398        assert_eq!(map.find_gap_end(21, &80), 10);
2399
2400        // Test finding gaps of various sizes with a lower bound
2401        assert_eq!(map.find_gap_end(5, &10), 10);
2402        assert_eq!(map.find_gap_end(5, &20), 10);
2403        assert_eq!(map.find_gap_end(5, &30), 30);
2404        assert_eq!(map.find_gap_end(5, &40), 40);
2405        assert_eq!(map.find_gap_end(5, &50), 40);
2406        assert_eq!(map.find_gap_end(5, &60), 60);
2407        assert_eq!(map.find_gap_end(5, &70), 60);
2408        assert_eq!(map.find_gap_end(5, &80), 80);
2409        assert_eq!(map.find_gap_end(5, &90), 90);
2410        assert_eq!(map.find_gap_end(5, &100), 100);
2411    }
2412
2413    #[::fuchsia::test]
2414    fn test_find_gap_end_rightmost() {
2415        let mut map = RangeMap::<u32, i32>::default();
2416        map.insert(10..20, 1);
2417        map.insert(30..40, 2);
2418        map.insert(50..60, 3);
2419        map.insert(70..80, 4);
2420
2421        // All gaps are size 10, should find the rightmost one
2422        assert_eq!(map.find_gap_end(10, &10), 10);
2423        assert_eq!(map.find_gap_end(10, &20), 10);
2424        assert_eq!(map.find_gap_end(10, &30), 30);
2425        assert_eq!(map.find_gap_end(10, &40), 30);
2426        assert_eq!(map.find_gap_end(10, &50), 50);
2427        assert_eq!(map.find_gap_end(10, &60), 50);
2428        assert_eq!(map.find_gap_end(10, &70), 70);
2429        assert_eq!(map.find_gap_end(10, &80), 70);
2430        assert_eq!(map.find_gap_end(10, &90), 90);
2431        assert_eq!(map.find_gap_end(10, &100), 100);
2432    }
2433
2434    #[::fuchsia::test]
2435    fn test_find_gap_end_large_map() {
2436        let mut map = RangeMap::<u32, i32>::default();
2437        let num_entries = 1000;
2438
2439        fn range_for(i: u32) -> Range<u32> {
2440            let start = i * (8000 - i) as u32;
2441            let end = start + 10;
2442            start..end
2443        }
2444
2445        // Insert ranges with decreasing gap sizes
2446        for i in 0..num_entries {
2447            map.insert(range_for(i), i as i32);
2448        }
2449
2450        let upper_bound = range_for(num_entries - 1).end;
2451
2452        for i in 0..num_entries - 1 {
2453            let current_range = range_for(i);
2454            let next_range = range_for(i + 1);
2455            let gap_size = current_range.end.measure_gap(&next_range.start);
2456            assert_eq!(map.find_gap_end(gap_size, &upper_bound), next_range.start);
2457        }
2458    }
2459
2460    #[::fuchsia::test]
2461    fn test_find_gap_end_after_removal() {
2462        let mut map = RangeMap::<u32, i32>::default();
2463        map.insert(10..20, 1);
2464        map.insert(30..40, 2);
2465        map.insert(50..60, 3);
2466
2467        assert_eq!(map.find_gap_end(12, &60), 10);
2468
2469        map.remove(30..35);
2470        assert_eq!(map.find_gap_end(12, &60), 35);
2471    }
2472
2473    #[::fuchsia::test]
2474    fn test_find_gap_end_adjacent_ranges() {
2475        let mut map = RangeMap::<u32, i32>::default();
2476        map.insert(10..20, 1);
2477        map.insert(20..30, 2);
2478        map.insert(30..40, 3);
2479
2480        // No gaps between ranges
2481        assert_eq!(map.find_gap_end(1, &100), 100);
2482    }
2483
2484    #[::fuchsia::test]
2485    fn test_find_gap_end_merging() {
2486        let mut map = RangeMap::<u32, i32>::default();
2487        map.insert(10..20, 1);
2488        map.insert(30..40, 2);
2489        map.insert(50..60, 2); // Same value as previous range
2490
2491        // Initially should find the last gap
2492        assert_eq!(map.find_gap_end(10, &100), 100);
2493
2494        // Merge the last two ranges
2495        map.insert(40..50, 1);
2496
2497        // Now should find the first gap
2498        assert_eq!(map.find_gap_end(10, &100), 100);
2499    }
2500
2501    #[::fuchsia::test]
2502    fn test_remove_empty_node() {
2503        let mut map = RangeMap::<u32, i32>::default();
2504
2505        // Fill two leaf nodes to capacity.
2506        for i in 0..(NODE_CAPACITY * 2) {
2507            let start = i as u32 * 10;
2508            let end = start + 1;
2509            map.insert(start..end, i as i32 * 100);
2510        }
2511
2512        // Insert at the right edge of the left leaf node, causing us to create a middle leaf node
2513        // with a single element.
2514        let i = NODE_CAPACITY - 1;
2515        let start = i as u32 * 10 + 2;
2516        let end = start + 1;
2517        let critical_range = start..end;
2518        map.insert(critical_range.clone(), i as i32 * 1000);
2519
2520        {
2521            // Remove the lone entry from the middle leaf node, ensuring that we pass our internal
2522            // validation checks in that scenario.
2523            let mut map = map.clone();
2524            map.remove(critical_range.clone());
2525        }
2526
2527        {
2528            let mut map = map.clone();
2529
2530            // Remove a bunch of nodes from the left side to encourage rebalancing from the right.
2531            for i in 0..(NODE_CAPACITY / 2 - 1) {
2532                let start = i as u32 * 10;
2533                let end = start + 1;
2534                map.remove(start..end);
2535            }
2536
2537            // Again, we remove the lone entry from the middle leaf node. This check is similar to
2538            // the previous check, but now the left leaf node has fewer elements, which would have
2539            // caused us to rebalance to the right in a previous version of this data structure.
2540            map.remove(critical_range);
2541        }
2542    }
2543}