Skip to main content

range_map/
lib.rs

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