Skip to main content

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