Skip to main content

range_map/
lib.rs

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