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