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    /// Remove the entry with the given cursor from the map.
1617    #[must_use]
1618    fn remove_at(&mut self, cursor: Cursor) -> Option<V> {
1619        let result = self.node.remove(cursor);
1620        match result {
1621            RemoveResult::NotFound => None,
1622            RemoveResult::Removed(RemoveState { removed_value, .. }) => Some(removed_value),
1623            RemoveResult::Underflow(RemoveState { removed_value, .. }) => {
1624                match &mut self.node {
1625                    Node::Leaf(_) => {
1626                        // Nothing we can do about an underflow of a single leaf node at the root.
1627                    }
1628                    Node::Internal(node) => {
1629                        // If the root has underflown to a trivial list, we can shrink the tree.
1630                        if node.children.len() == 1 {
1631                            self.node = node.children.get(0);
1632                        }
1633                    }
1634                }
1635                Some(removed_value)
1636            }
1637        }
1638    }
1639
1640    /// Iterate through the keys and values stored in the map.
1641    pub fn iter(&self) -> Iter<'_, K, V> {
1642        Iter {
1643            forward: Cursor::with_index(0),
1644            backward: Cursor::with_index(self.node.len()),
1645            root: &self.node,
1646        }
1647    }
1648
1649    /// Create the cursor stack for the start bound of the given range.
1650    fn find_start_bound(&self, bounds: &impl RangeBounds<K>) -> Cursor {
1651        let key = match bounds.start_bound() {
1652            Bound::Included(key) => key,
1653            Bound::Excluded(key) => key,
1654            Bound::Unbounded => {
1655                return Cursor::with_index(0);
1656            }
1657        };
1658        self.find(key, CursorPosition::Left)
1659    }
1660
1661    /// Create the cursor stack for the end bound of the given range.
1662    fn find_end_bound(&self, bounds: &impl RangeBounds<K>) -> Cursor {
1663        let key = match bounds.end_bound() {
1664            Bound::Included(key) => key,
1665            Bound::Excluded(key) => key,
1666            Bound::Unbounded => {
1667                return Cursor::with_index(self.node.len());
1668            }
1669        };
1670        self.find(key, CursorPosition::Right)
1671    }
1672
1673    /// Iterate through the keys and values stored in the given range in the map.
1674    pub fn range(&self, bounds: impl RangeBounds<K>) -> Iter<'_, K, V> {
1675        let forward = self.find_start_bound(&bounds);
1676        let backward = self.find_end_bound(&bounds);
1677        Iter { forward, backward, root: &self.node }
1678    }
1679
1680    /// Find the first range in the map that starts at or after the given key.
1681    pub fn find_at_or_after(&self, key: K) -> Option<(&Range<K>, &V)> {
1682        let mut iter = self.range(key..).filter(move |(range, _)| key <= range.start);
1683        iter.next()
1684    }
1685}
1686
1687#[cfg(test)]
1688mod test {
1689    use super::*;
1690
1691    #[::fuchsia::test]
1692    fn test_empty() {
1693        let mut map = RangeMap::<u32, i32>::default();
1694
1695        assert!(map.get(12).is_none());
1696        let _ = map.remove(10..34);
1697        // This is a test to make sure we can handle reversed ranges
1698        #[allow(clippy::reversed_empty_ranges)]
1699        let _ = map.remove(34..10);
1700    }
1701
1702    #[::fuchsia::test]
1703    fn test_is_empty() {
1704        let mut map = RangeMap::<u32, i32>::default();
1705
1706        // Test empty map
1707        assert!(map.is_empty());
1708
1709        // Test map with 5 entries
1710        for i in 0..5 {
1711            let start = i * 10;
1712            let end = start + 5;
1713            let _ = map.insert(start..end, i as i32);
1714        }
1715        assert!(!map.is_empty());
1716
1717        // Remove all entries
1718        for i in 0..5 {
1719            let start = i * 10;
1720            let end = start + 5;
1721            let _ = map.remove(start..end);
1722        }
1723        assert!(map.is_empty());
1724
1725        // Test map with 50 entries
1726        for i in 0..50 {
1727            let start = i * 10;
1728            let end = start + 5;
1729            let _ = map.insert(start..end, i as i32);
1730        }
1731        assert!(!map.is_empty());
1732
1733        // Remove all entries
1734        for i in 0..50 {
1735            let start = i * 10;
1736            let end = start + 5;
1737            let _ = map.remove(start..end);
1738        }
1739        assert!(map.is_empty());
1740    }
1741
1742    #[::fuchsia::test]
1743    fn test_insert_into_empty() {
1744        let mut map = RangeMap::<u32, i32>::default();
1745
1746        let _ = map.insert(10..34, -14);
1747
1748        assert_eq!((&(10..34), &-14), map.get(12).unwrap());
1749        assert_eq!((&(10..34), &-14), map.get(10).unwrap());
1750        assert!(map.get(9).is_none());
1751        assert_eq!((&(10..34), &-14), map.get(33).unwrap());
1752        assert!(map.get(34).is_none());
1753    }
1754
1755    #[::fuchsia::test]
1756    fn test_iter() {
1757        let mut map = RangeMap::<u32, i32>::default();
1758
1759        let _ = map.insert(10..34, -14);
1760        let _ = map.insert(74..92, -12);
1761
1762        let mut iter = map.iter();
1763
1764        assert_eq!(iter.next().expect("missing elem"), (&(10..34), &-14));
1765        assert_eq!(iter.next().expect("missing elem"), (&(74..92), &-12));
1766
1767        assert!(iter.next().is_none());
1768
1769        let entry = map.find_at_or_after(10);
1770        assert_eq!(entry.expect("missing elem"), (&(10..34), &-14));
1771        let entry = map.find_at_or_after(11);
1772        assert_eq!(entry.expect("missing elem"), (&(74..92), &-12));
1773        let entry = map.find_at_or_after(74);
1774        assert_eq!(entry.expect("missing elem"), (&(74..92), &-12));
1775        let entry = map.find_at_or_after(75);
1776        assert_eq!(entry, None);
1777
1778        assert_eq!(map.range(..9).collect::<Vec<_>>(), vec![]);
1779        assert_eq!(map.range(..34).collect::<Vec<_>>(), vec![(&(10..34), &-14)]);
1780        assert_eq!(map.range(..74).collect::<Vec<_>>(), vec![(&(10..34), &-14)]);
1781        assert_eq!(map.range(..75).collect::<Vec<_>>(), vec![(&(10..34), &-14), (&(74..92), &-12)]);
1782        assert_eq!(map.range(..91).collect::<Vec<_>>(), vec![(&(10..34), &-14), (&(74..92), &-12)]);
1783        assert_eq!(map.range(..92).collect::<Vec<_>>(), vec![(&(10..34), &-14), (&(74..92), &-12)]);
1784    }
1785
1786    #[::fuchsia::test]
1787    fn test_remove_overlapping_edge() {
1788        let mut map = RangeMap::<u32, i32>::default();
1789
1790        let _ = map.insert(10..34, -14);
1791
1792        let _ = map.remove(2..11);
1793        assert_eq!((&(11..34), &-14), map.get(11).unwrap());
1794
1795        let _ = map.remove(33..42);
1796        assert_eq!((&(11..33), &-14), map.get(12).unwrap());
1797    }
1798
1799    #[::fuchsia::test]
1800    fn test_remove_middle_splits_range() {
1801        let mut map = RangeMap::<u32, i32>::default();
1802
1803        let _ = map.insert(10..34, -14);
1804        let _ = map.remove(15..18);
1805
1806        assert_eq!((&(10..15), &-14), map.get(12).unwrap());
1807        assert_eq!((&(18..34), &-14), map.get(20).unwrap());
1808    }
1809
1810    #[::fuchsia::test]
1811    fn test_remove_upper_half_of_split_range_leaves_lower_range() {
1812        let mut map = RangeMap::<u32, i32>::default();
1813
1814        let _ = map.insert(10..34, -14);
1815        let _ = map.remove(15..18);
1816        let _ = map.insert(2..7, -21);
1817        let _ = map.remove(20..42);
1818
1819        assert_eq!((&(2..7), &-21), map.get(5).unwrap());
1820        assert_eq!((&(10..15), &-14), map.get(12).unwrap());
1821    }
1822
1823    #[::fuchsia::test]
1824    fn test_range_map_overlapping_insert() {
1825        let mut map = RangeMap::<u32, i32>::default();
1826
1827        let _ = map.insert(2..7, -21);
1828        let _ = map.insert(5..9, -42);
1829        let _ = map.insert(1..3, -43);
1830        let _ = map.insert(6..8, -44);
1831
1832        assert_eq!((&(1..3), &-43), map.get(2).unwrap());
1833        assert_eq!((&(3..5), &-21), map.get(4).unwrap());
1834        assert_eq!((&(5..6), &-42), map.get(5).unwrap());
1835        assert_eq!((&(6..8), &-44), map.get(7).unwrap());
1836    }
1837
1838    #[::fuchsia::test]
1839    fn test_intersect_single() {
1840        let mut map = RangeMap::<u32, i32>::default();
1841
1842        let _ = map.insert(2..7, -10);
1843
1844        let mut iter = map.range(3..4);
1845        assert_eq!(iter.next(), Some((&(2..7), &-10)));
1846        assert_eq!(iter.next(), None);
1847
1848        let mut iter = map.range(2..3);
1849        assert_eq!(iter.next(), Some((&(2..7), &-10)));
1850        assert_eq!(iter.next(), None);
1851
1852        let mut iter = map.range(1..4);
1853        assert_eq!(iter.next(), Some((&(2..7), &-10)));
1854        assert_eq!(iter.next(), None);
1855
1856        let mut iter = map.range(1..2);
1857        assert_eq!(iter.next(), None);
1858
1859        let mut iter = map.range(6..7);
1860        assert_eq!(iter.next(), Some((&(2..7), &-10)));
1861        assert_eq!(iter.next(), None);
1862    }
1863
1864    #[::fuchsia::test]
1865    fn test_intersect_multiple() {
1866        let mut map = RangeMap::<u32, i32>::default();
1867
1868        let _ = map.insert(2..7, -10);
1869        let _ = map.insert(7..9, -20);
1870        let _ = map.insert(10..11, -30);
1871
1872        let mut iter = map.range(3..8);
1873        assert_eq!(iter.next(), Some((&(2..7), &-10)));
1874        assert_eq!(iter.next(), Some((&(7..9), &-20)));
1875        assert_eq!(iter.next(), None);
1876
1877        let mut iter = map.range(3..11);
1878        assert_eq!(iter.next(), Some((&(2..7), &-10)));
1879        assert_eq!(iter.next(), Some((&(7..9), &-20)));
1880        assert_eq!(iter.next(), Some((&(10..11), &-30)));
1881        assert_eq!(iter.next(), None);
1882    }
1883
1884    #[::fuchsia::test]
1885    fn test_intersect_no_gaps() {
1886        let mut map = RangeMap::<u32, i32>::default();
1887
1888        let _ = map.insert(0..1, -10);
1889        let _ = map.insert(1..2, -20);
1890        let _ = map.insert(2..3, -30);
1891
1892        let mut iter = map.range(0..3);
1893        assert_eq!(iter.next(), Some((&(0..1), &-10)));
1894        assert_eq!(iter.next(), Some((&(1..2), &-20)));
1895        assert_eq!(iter.next(), Some((&(2..3), &-30)));
1896        assert_eq!(iter.next(), None);
1897    }
1898
1899    #[test]
1900    fn test_merging() {
1901        let mut map = RangeMap::<u32, i32>::default();
1902
1903        let _ = map.insert(1..2, -10);
1904        assert_eq!(map.iter().collect::<Vec<_>>(), vec![(&(1..2), &-10)]);
1905        let _ = map.insert(3..4, -10);
1906        assert_eq!(map.iter().collect::<Vec<_>>(), vec![(&(1..2), &-10), (&(3..4), &-10)]);
1907        let _ = map.insert(2..3, -10);
1908        assert_eq!(map.iter().collect::<Vec<_>>(), vec![(&(1..4), &-10)]);
1909        let _ = map.insert(0..1, -10);
1910        assert_eq!(map.iter().collect::<Vec<_>>(), vec![(&(0..4), &-10)]);
1911        let _ = map.insert(4..5, -10);
1912        assert_eq!(map.iter().collect::<Vec<_>>(), vec![(&(0..5), &-10)]);
1913        let _ = map.insert(2..3, -20);
1914        assert_eq!(
1915            map.iter().collect::<Vec<_>>(),
1916            vec![(&(0..2), &-10), (&(2..3), &-20), (&(3..5), &-10)]
1917        );
1918    }
1919
1920    #[test]
1921    fn test_remove_multiple_ranges_exact_query() {
1922        let first = 15..21;
1923        let second = first.end..29;
1924
1925        let mut map = RangeMap::default();
1926        let _ = map.insert(first.clone(), 1);
1927        let _ = map.insert(second.clone(), 2);
1928
1929        assert_eq!(map.remove(first.start..second.end), &[1, 2]);
1930    }
1931
1932    #[::fuchsia::test]
1933    fn test_large_insert_and_remove() {
1934        let mut map = RangeMap::<u32, i32>::default();
1935        let num_entries = 1000;
1936
1937        // Insert a large number of entries
1938        for i in 0..num_entries {
1939            let start = i as u32 * 10;
1940            let end = start + 5;
1941            let value = i as i32;
1942            let _ = map.insert(start..end, value);
1943        }
1944
1945        // Verify that all inserted entries can be retrieved
1946        for i in 0..num_entries {
1947            let start = i as u32 * 10;
1948            let end = start + 5;
1949            let point = start + 2;
1950            if let Some((range, value)) = map.get(point) {
1951                assert!(range.start <= point && point < range.end);
1952                assert_eq!(*range, start..end);
1953                assert_eq!(*value, i as i32);
1954            } else {
1955                panic!("Expected to find a range for point {}", point);
1956            }
1957        }
1958
1959        // Remove a large number of entries
1960        for i in 0..num_entries {
1961            let start = i as u32 * 10;
1962            let end = start + 5;
1963            let _ = map.remove(start..end);
1964        }
1965
1966        // Verify that the map is empty after removing all entries
1967        assert!(map.is_empty());
1968    }
1969
1970    #[::fuchsia::test]
1971    fn test_large_insert_and_remove_overlapping() {
1972        let mut map = RangeMap::<u32, i32>::default();
1973        let num_entries = 1000;
1974
1975        // Insert a large number of entries with overlapping ranges
1976        for i in 0..num_entries {
1977            let start = i as u32 * 5;
1978            let end = start + 20;
1979            let value = i as i32;
1980            let _ = map.insert(start..end, value);
1981        }
1982
1983        // Verify that all inserted entries can be retrieved
1984        for i in 0..num_entries {
1985            let point = i as u32 * 5 + 1;
1986            if let Some((range, value)) = map.get(point) {
1987                assert!(range.start <= point && point < range.end);
1988                assert_eq!(*value, i as i32);
1989            } else {
1990                panic!("Expected to find a range for point {}", point);
1991            }
1992        }
1993
1994        // Remove a large number of entries with overlapping ranges
1995        for i in 0..num_entries {
1996            let start = i as u32 * 5;
1997            let end = start + 20;
1998            let _ = map.remove(start..end);
1999        }
2000
2001        // Verify that the map is empty after removing all entries
2002        assert!(map.is_empty());
2003    }
2004
2005    #[::fuchsia::test]
2006    fn test_large_insert_and_get_specific_points() {
2007        let mut map = RangeMap::<u32, i32>::default();
2008        let num_entries = 1000;
2009        let mut inserted_ranges = Vec::new();
2010
2011        // Insert a large number of entries
2012        for i in 0..num_entries {
2013            let start = i as u32 * 10;
2014            let end = start + 5;
2015            let value = i as i32;
2016            let _ = map.insert(start..end, value);
2017            inserted_ranges.push((start..end, value));
2018        }
2019
2020        // Verify that specific points can be retrieved correctly
2021        for (range, value) in &inserted_ranges {
2022            let point = range.start + 2;
2023            let (retrieved_range, retrieved_value) = map.get(point).unwrap();
2024            assert_eq!(retrieved_range, range);
2025            assert_eq!(retrieved_value, value);
2026        }
2027    }
2028
2029    #[::fuchsia::test]
2030    fn test_large_insert_and_iter() {
2031        let mut map = RangeMap::<u32, i32>::default();
2032        let num_entries = 1000;
2033        let mut inserted_ranges = Vec::new();
2034
2035        // Insert a large number of entries
2036        for i in 0..num_entries {
2037            let start = i as u32 * 10;
2038            let end = start + 5;
2039            let value = i as i32;
2040            let _ = map.insert(start..end, value);
2041            inserted_ranges.push((start..end, value));
2042        }
2043
2044        // Verify that iter() returns all inserted entries
2045        let mut iter_ranges: Vec<(&Range<u32>, &i32)> = map.iter().collect();
2046        iter_ranges.sort_by_key(|(range, _)| range.start);
2047        let mut inserted_ranges_sorted: Vec<(Range<u32>, i32)> = inserted_ranges.clone();
2048        inserted_ranges_sorted.sort_by_key(|(range, _)| range.start);
2049
2050        assert_eq!(iter_ranges.len(), inserted_ranges_sorted.len());
2051        for (i, (range, value)) in iter_ranges.iter().enumerate() {
2052            assert_eq!(*range, &inserted_ranges_sorted[i].0);
2053            assert_eq!(*value, &inserted_ranges_sorted[i].1);
2054        }
2055    }
2056
2057    #[::fuchsia::test]
2058    fn test_large_insert_and_range() {
2059        let mut map = RangeMap::<u32, i32>::default();
2060        let num_entries = 1000;
2061
2062        // Insert a large number of entries
2063        for i in 0..num_entries {
2064            let start = i as u32 * 10;
2065            let end = start + 5;
2066            let value = i as i32;
2067            let _ = map.insert(start..end, value);
2068        }
2069
2070        // Verify range(start_point..)
2071        let start_point = 5000;
2072        let mut iter = map.range(start_point..);
2073        while let Some((range, _)) = iter.next() {
2074            assert!(range.start >= start_point);
2075        }
2076    }
2077
2078    #[::fuchsia::test]
2079    fn test_large_insert_and_iter_ending_at() {
2080        let mut map = RangeMap::<u32, i32>::default();
2081        let num_entries = 1000;
2082
2083        // Insert a large number of entries
2084        for i in 0..num_entries {
2085            let start = i as u32 * 10;
2086            let end = start + 5;
2087            let value = i as i32;
2088            let _ = map.insert(start..end, value);
2089        }
2090
2091        // Verify range(..end_point)
2092        let end_point = 5000;
2093        let mut iter = map.range(..end_point);
2094        while let Some((range, _)) = iter.next() {
2095            assert!(range.start < end_point);
2096        }
2097    }
2098
2099    #[::fuchsia::test]
2100    fn test_large_insert_and_intersection() {
2101        let mut map = RangeMap::<u32, i32>::default();
2102        let num_entries = 1000;
2103
2104        // Insert a large number of entries
2105        for i in 0..num_entries {
2106            let start = i as u32 * 10;
2107            let end = start + 5;
2108            let value = i as i32;
2109            let _ = map.insert(start..end, value);
2110        }
2111
2112        // Verify intersection()
2113        let intersect_start = 4000;
2114        let intersect_end = 4050;
2115        let mut iter = map.range(intersect_start..intersect_end);
2116        while let Some((range, _)) = iter.next() {
2117            assert!(range.start < intersect_end && range.end > intersect_start);
2118        }
2119    }
2120
2121    #[::fuchsia::test]
2122    fn test_large_insert_and_last_range() {
2123        let mut map = RangeMap::<u32, i32>::default();
2124        let num_entries = 1000;
2125        let mut last_range = None;
2126
2127        // Insert a large number of entries
2128        for i in 0..num_entries {
2129            let start = i as u32 * 10;
2130            let end = start + 5;
2131            let value = i as i32;
2132            let _ = map.insert(start..end, value);
2133            last_range = Some(start..end);
2134        }
2135
2136        // Verify last_range()
2137        if let Some(expected_last_range) = last_range {
2138            assert_eq!(map.last_range().unwrap(), &expected_last_range);
2139        }
2140    }
2141
2142    #[::fuchsia::test]
2143    fn test_large_insert_and_remove_alternating() {
2144        let mut map = RangeMap::<u32, i32>::default();
2145        let num_entries = 1000;
2146
2147        // Insert and remove entries in an alternating pattern
2148        for i in 0..num_entries {
2149            let start = i as u32 * 10;
2150            let end = start + 5;
2151            let value = i as i32;
2152            let _ = map.insert(start..end, value);
2153
2154            if i % 2 == 0 {
2155                // Remove every other entry
2156                let _ = map.remove(start..end);
2157            }
2158        }
2159
2160        // Verify that only the non-removed entries remain
2161        for i in 0..num_entries {
2162            let start = i as u32 * 10;
2163            let end = start + 5;
2164            let point = start + 2;
2165            if i % 2 != 0 {
2166                if let Some((range, value)) = map.get(point) {
2167                    assert!(range.start <= point && point < range.end);
2168                    assert_eq!(*range, start..end);
2169                    assert_eq!(*value, i as i32);
2170                } else {
2171                    panic!("Expected to find a range for point {}", point);
2172                }
2173            } else {
2174                assert!(map.get(point).is_none());
2175            }
2176        }
2177    }
2178
2179    #[::fuchsia::test]
2180    fn test_large_insert_and_remove_multiple_times() {
2181        let mut map = RangeMap::<u32, i32>::default();
2182        let num_entries = 200;
2183        let num_iterations = 5;
2184
2185        for _ in 0..num_iterations {
2186            // Insert a large number of entries
2187            for i in 0..num_entries {
2188                let start = i as u32 * 10;
2189                let end = start + 5;
2190                let value = i as i32;
2191                let _ = map.insert(start..end, value);
2192            }
2193
2194            // Remove a large number of entries
2195            for i in 0..num_entries {
2196                let start = i as u32 * 10;
2197                let end = start + 5;
2198                let _ = map.remove(start..end);
2199            }
2200        }
2201
2202        // Verify that the map is empty after multiple insert/remove cycles
2203        assert!(map.is_empty());
2204    }
2205
2206    #[::fuchsia::test]
2207    fn test_leaf_node_split() {
2208        let mut map = RangeMap::<u32, i32>::default();
2209
2210        // Fill the leaf node to capacity
2211        for i in 0..NODE_CAPACITY {
2212            let start = i as u32 * 10;
2213            let end = start + 5;
2214            let _ = map.insert(start..end, i as i32);
2215        }
2216
2217        // Verify the initial state
2218        assert_eq!(map.node.len(), NODE_CAPACITY);
2219
2220        {
2221            let mut map = map.clone();
2222
2223            // Insert a value that causes a split in the first half
2224            let split_start = 15;
2225            let split_end = 20;
2226            let _ = map.insert(split_start..split_end, -1);
2227
2228            // Verify the split
2229            assert!(matches!(map.node, Node::Internal(_)));
2230            if let Node::Internal(internal) = &map.node {
2231                assert_eq!(internal.children.len(), 2);
2232                assert!(internal.children.size_at(0) >= NODE_CAPACITY / 2);
2233                assert!(internal.children.size_at(1) >= NODE_CAPACITY / 2);
2234            }
2235        }
2236
2237        {
2238            let mut map = map.clone();
2239
2240            // Insert a value that causes a split in the second half
2241            let split_start = (NODE_CAPACITY as u32 * 10) + 5;
2242            let split_end = split_start + 5;
2243            let _ = map.insert(split_start..split_end, -2);
2244
2245            // Verify the second split
2246            if let Node::Internal(internal) = &map.node {
2247                assert_eq!(internal.children.len(), 2);
2248                assert!(internal.children.size_at(0) >= NODE_CAPACITY / 2);
2249            }
2250        }
2251    }
2252
2253    #[::fuchsia::test]
2254    fn test_merging_ranges_with_equal_values() {
2255        let mut map = RangeMap::<u32, i32>::default();
2256
2257        // Insert some initial ranges
2258        let _ = map.insert(10..20, 100);
2259        let _ = map.insert(30..40, 200);
2260        let _ = map.insert(50..60, 100);
2261
2262        // Merge adjacent ranges with equal values
2263        let _ = map.insert(20..30, 100);
2264        assert_eq!(map.get(15).unwrap(), (&(10..30), &100));
2265        assert_eq!(map.get(35).unwrap(), (&(30..40), &200));
2266        assert_eq!(map.get(55).unwrap(), (&(50..60), &100));
2267
2268        // Merge non-adjacent ranges with equal values
2269        let _ = map.insert(40..50, 100);
2270        assert_eq!(map.get(15).unwrap(), (&(10..30), &100));
2271        assert_eq!(map.get(35).unwrap(), (&(30..40), &200));
2272        assert_eq!(map.get(45).unwrap(), (&(40..60), &100));
2273
2274        // Insert a range with a different value
2275        let _ = map.insert(60..70, 300);
2276        assert_eq!(map.get(65).unwrap(), (&(60..70), &300));
2277
2278        // Merge a range with a different value
2279        let _ = map.insert(70..80, 300);
2280        assert_eq!(map.get(65).unwrap(), (&(60..80), &300));
2281
2282        // Merge a range with a different value at the beginning
2283        let _ = map.insert(0..10, 400);
2284        assert_eq!(map.get(5).unwrap(), (&(0..10), &400));
2285
2286        // Merge a range with a different value at the end
2287        let _ = map.insert(80..90, 400);
2288        assert_eq!(map.get(85).unwrap(), (&(80..90), &400));
2289
2290        // Merge a range with a different value in the middle
2291        let _ = map.insert(90..100, 400);
2292        assert_eq!(map.get(95).unwrap(), (&(80..100), &400));
2293        let _ = map.insert(100..110, 400);
2294        assert_eq!(map.get(95).unwrap(), (&(80..110), &400));
2295        let _ = map.insert(110..120, 400);
2296        assert_eq!(map.get(95).unwrap(), (&(80..120), &400));
2297
2298        // Merge a range with a different value in the middle
2299        let _ = map.insert(10..90, 400);
2300        assert_eq!(map.get(5).unwrap(), (&(0..120), &400));
2301    }
2302
2303    #[::fuchsia::test]
2304    fn test_large_insert_and_remove_with_gaps() {
2305        let mut map = RangeMap::<u32, i32>::default();
2306        let num_entries = 500;
2307
2308        // Insert entries with gaps
2309        for i in 0..num_entries {
2310            let start = i as u32 * 20;
2311            let end = start + 5;
2312            let value = i as i32;
2313            let _ = map.insert(start..end, value);
2314        }
2315
2316        // Remove entries with gaps
2317        for i in 0..num_entries {
2318            if i % 2 == 0 {
2319                let start = i as u32 * 20;
2320                let end = start + 5;
2321                let _ = map.remove(start..end);
2322            }
2323        }
2324
2325        // Verify the state of the map
2326        for i in 0..num_entries {
2327            let start = i as u32 * 20;
2328            let end = start + 5;
2329            let point = start + 2;
2330
2331            if i % 2 != 0 {
2332                if let Some((range, value)) = map.get(point) {
2333                    assert!(range.start <= point && point < range.end);
2334                    assert_eq!(*range, start..end);
2335                    assert_eq!(*value, i as i32);
2336                } else {
2337                    panic!("Expected to find a range for point {}", point);
2338                }
2339            } else {
2340                assert!(map.get(point).is_none());
2341            }
2342        }
2343    }
2344
2345    #[::fuchsia::test]
2346    fn test_critical_removal() {
2347        fn range_for(i: u32) -> Range<u32> {
2348            let start = i * 20;
2349            let end = start + 5;
2350            start..end
2351        }
2352
2353        // Index 0 cannot be the critical index.
2354        for critial_index in 1..100 {
2355            let mut map = RangeMap::<u32, i32>::default();
2356
2357            // Insert enough entries for force a split somewhere.
2358            for i in 0..100 {
2359                let value = i as i32;
2360                let _ = map.insert(range_for(i), value);
2361            }
2362
2363            // We don't know whether the split will occur at the critical index, but we try all the
2364            // possible indices to ensure that we test an index at which a split occurred.
2365            let critical_range = range_for(critial_index);
2366            let _ = map.remove(critical_range.clone());
2367
2368            // We now insert a range that spans the critical point. This range will be inserted to
2369            // left of the split.
2370            let value = -10 as i32;
2371            let spanning_range = (critical_range.start - 2)..(critical_range.start + 2);
2372            let _ = map.insert(spanning_range.clone(), value);
2373
2374            // Check to see if we can find the range by looking before the critical point.
2375            let key_before_split = critical_range.start - 1;
2376            assert_eq!(map.get(key_before_split), Some((&spanning_range, &value)));
2377
2378            // Check to see if we can find the range by looking after the critical point.
2379            let key_after_split = critical_range.start + 1;
2380            assert_eq!(map.get(key_after_split), Some((&spanning_range, &value)));
2381        }
2382    }
2383
2384    #[::fuchsia::test]
2385    fn test_find_gap_end_empty() {
2386        let map = RangeMap::<u32, i32>::default();
2387        assert_eq!(map.find_gap_end(10, &100), 100);
2388    }
2389
2390    #[::fuchsia::test]
2391    fn test_find_gap_end_single_range() {
2392        let mut map = RangeMap::<u32, i32>::default();
2393        let _ = map.insert(10..20, 1);
2394        assert_eq!(map.find_gap_end(10, &100), 100);
2395    }
2396
2397    #[::fuchsia::test]
2398    fn test_find_gap_end_multiple_ranges() {
2399        let mut map = RangeMap::<u32, i32>::default();
2400        let _ = map.insert(10..20, 1);
2401        let _ = map.insert(40..50, 2);
2402        let _ = map.insert(60..70, 3);
2403
2404        // Test finding gaps of various sizes
2405        assert_eq!(map.find_gap_end(5, &80), 80);
2406        assert_eq!(map.find_gap_end(10, &80), 80);
2407        assert_eq!(map.find_gap_end(11, &80), 40);
2408        assert_eq!(map.find_gap_end(20, &80), 40);
2409        assert_eq!(map.find_gap_end(21, &80), 10);
2410
2411        // Test finding gaps of various sizes with a lower bound
2412        assert_eq!(map.find_gap_end(5, &10), 10);
2413        assert_eq!(map.find_gap_end(5, &20), 10);
2414        assert_eq!(map.find_gap_end(5, &30), 30);
2415        assert_eq!(map.find_gap_end(5, &40), 40);
2416        assert_eq!(map.find_gap_end(5, &50), 40);
2417        assert_eq!(map.find_gap_end(5, &60), 60);
2418        assert_eq!(map.find_gap_end(5, &70), 60);
2419        assert_eq!(map.find_gap_end(5, &80), 80);
2420        assert_eq!(map.find_gap_end(5, &90), 90);
2421        assert_eq!(map.find_gap_end(5, &100), 100);
2422    }
2423
2424    #[::fuchsia::test]
2425    fn test_find_gap_end_rightmost() {
2426        let mut map = RangeMap::<u32, i32>::default();
2427        let _ = map.insert(10..20, 1);
2428        let _ = map.insert(30..40, 2);
2429        let _ = map.insert(50..60, 3);
2430        let _ = map.insert(70..80, 4);
2431
2432        // All gaps are size 10, should find the rightmost one
2433        assert_eq!(map.find_gap_end(10, &10), 10);
2434        assert_eq!(map.find_gap_end(10, &20), 10);
2435        assert_eq!(map.find_gap_end(10, &30), 30);
2436        assert_eq!(map.find_gap_end(10, &40), 30);
2437        assert_eq!(map.find_gap_end(10, &50), 50);
2438        assert_eq!(map.find_gap_end(10, &60), 50);
2439        assert_eq!(map.find_gap_end(10, &70), 70);
2440        assert_eq!(map.find_gap_end(10, &80), 70);
2441        assert_eq!(map.find_gap_end(10, &90), 90);
2442        assert_eq!(map.find_gap_end(10, &100), 100);
2443    }
2444
2445    #[::fuchsia::test]
2446    fn test_find_gap_end_large_map() {
2447        let mut map = RangeMap::<u32, i32>::default();
2448        let num_entries = 1000;
2449
2450        fn range_for(i: u32) -> Range<u32> {
2451            let start = i * (8000 - i) as u32;
2452            let end = start + 10;
2453            start..end
2454        }
2455
2456        // Insert ranges with decreasing gap sizes
2457        for i in 0..num_entries {
2458            let _ = map.insert(range_for(i), i as i32);
2459        }
2460
2461        let upper_bound = range_for(num_entries - 1).end;
2462
2463        for i in 0..num_entries - 1 {
2464            let current_range = range_for(i);
2465            let next_range = range_for(i + 1);
2466            let gap_size = current_range.end.measure_gap(&next_range.start);
2467            assert_eq!(map.find_gap_end(gap_size, &upper_bound), next_range.start);
2468        }
2469    }
2470
2471    #[::fuchsia::test]
2472    fn test_find_gap_end_after_removal() {
2473        let mut map = RangeMap::<u32, i32>::default();
2474        let _ = map.insert(10..20, 1);
2475        let _ = map.insert(30..40, 2);
2476        let _ = map.insert(50..60, 3);
2477
2478        assert_eq!(map.find_gap_end(12, &60), 10);
2479
2480        let _ = map.remove(30..35);
2481        assert_eq!(map.find_gap_end(12, &60), 35);
2482    }
2483
2484    #[::fuchsia::test]
2485    fn test_find_gap_end_adjacent_ranges() {
2486        let mut map = RangeMap::<u32, i32>::default();
2487        let _ = map.insert(10..20, 1);
2488        let _ = map.insert(20..30, 2);
2489        let _ = map.insert(30..40, 3);
2490
2491        // No gaps between ranges
2492        assert_eq!(map.find_gap_end(1, &100), 100);
2493    }
2494
2495    #[::fuchsia::test]
2496    fn test_find_gap_end_merging() {
2497        let mut map = RangeMap::<u32, i32>::default();
2498        let _ = map.insert(10..20, 1);
2499        let _ = map.insert(30..40, 2);
2500        let _ = map.insert(50..60, 2); // Same value as previous range
2501
2502        // Initially should find the last gap
2503        assert_eq!(map.find_gap_end(10, &100), 100);
2504
2505        // Merge the last two ranges
2506        let _ = map.insert(40..50, 1);
2507
2508        // Now should find the first gap
2509        assert_eq!(map.find_gap_end(10, &100), 100);
2510    }
2511
2512    #[::fuchsia::test]
2513    fn test_remove_empty_node() {
2514        let mut map = RangeMap::<u32, i32>::default();
2515
2516        // Fill two leaf nodes to capacity.
2517        for i in 0..(NODE_CAPACITY * 2) {
2518            let start = i as u32 * 10;
2519            let end = start + 1;
2520            let _ = map.insert(start..end, i as i32 * 100);
2521        }
2522
2523        // Insert at the right edge of the left leaf node, causing us to create a middle leaf node
2524        // with a single element.
2525        let i = NODE_CAPACITY - 1;
2526        let start = i as u32 * 10 + 2;
2527        let end = start + 1;
2528        let critical_range = start..end;
2529        let _ = map.insert(critical_range.clone(), i as i32 * 1000);
2530
2531        {
2532            // Remove the lone entry from the middle leaf node, ensuring that we pass our internal
2533            // validation checks in that scenario.
2534            let mut map = map.clone();
2535            let _ = map.remove(critical_range.clone());
2536        }
2537
2538        {
2539            let mut map = map.clone();
2540
2541            // Remove a bunch of nodes from the left side to encourage rebalancing from the right.
2542            for i in 0..(NODE_CAPACITY / 2 - 1) {
2543                let start = i as u32 * 10;
2544                let end = start + 1;
2545                let _ = map.remove(start..end);
2546            }
2547
2548            // Again, we remove the lone entry from the middle leaf node. This check is similar to
2549            // the previous check, but now the left leaf node has fewer elements, which would have
2550            // caused us to rebalance to the right in a previous version of this data structure.
2551            let _ = map.remove(critical_range);
2552        }
2553    }
2554
2555    #[::fuchsia::test]
2556    fn test_insert_overwrites_completely() {
2557        let mut map = RangeMap::<u32, i32>::default();
2558        let _ = map.insert(10..20, 1);
2559        let removed = map.insert(10..20, 10);
2560        assert_eq!(removed, vec![1]);
2561    }
2562
2563    #[::fuchsia::test]
2564    fn test_insert_overwrites_partially() {
2565        let mut map = RangeMap::<u32, i32>::default();
2566        let _ = map.insert(30..40, 2);
2567        let removed = map.insert(35..45, 20);
2568        assert_eq!(removed, vec![2]);
2569        assert_eq!(
2570            map.get(32),
2571            Some((&(30..35), &2)),
2572            "remaining part of overwritten range should exist"
2573        );
2574    }
2575
2576    #[::fuchsia::test]
2577    fn test_insert_overwrites_multiple() {
2578        let mut map = RangeMap::<u32, i32>::default();
2579        let _ = map.insert(10..20, 1);
2580        let _ = map.insert(30..40, 2);
2581        let _ = map.insert(50..60, 3);
2582
2583        let removed = map.insert(15..55, 30);
2584        let mut removed = removed;
2585        removed.sort();
2586        assert_eq!(removed, vec![1, 2, 3]);
2587    }
2588
2589    #[::fuchsia::test]
2590    fn test_insert_merge_does_not_return_values() {
2591        let mut map = RangeMap::<u32, i32>::default();
2592
2593        let _ = map.insert(10..20, 1);
2594
2595        let removed = map.insert(20..30, 1);
2596        assert!(removed.is_empty(), "merging right should not return removed values");
2597        assert_eq!(map.get(15), Some((&(10..30), &1)));
2598
2599        let removed = map.insert(0..10, 1);
2600        assert!(removed.is_empty(), "merging left should not return removed values");
2601        assert_eq!(map.get(15), Some((&(0..30), &1)));
2602    }
2603}