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(&mut self, key: &K) -> Option<(Cursor, Range<K>, V)> {
1475        let cursor = self.find(key, CursorPosition::Left);
1476        self.get_if_contains_key(key, cursor)
1477            .map(|(range, value)| (cursor, range.clone(), value.clone()))
1478    }
1479
1480    /// Find a gap that is at least as large as the given gap and is less than the given upper bound.
1481    ///
1482    /// Returns the end of the gap, which might above or below the entries in the map.
1483    pub fn find_gap_end(&self, gap: u64, upper_bound: &K) -> K {
1484        self.node.find_gap_end(gap, upper_bound)
1485    }
1486
1487    /// Remove the entry with the given key from the map.
1488    ///
1489    /// If the key was present in the map, returns the value previously stored at the given key.
1490    #[must_use]
1491    pub fn remove(&mut self, range: Range<K>) -> Vec<V> {
1492        let mut removed_values = vec![];
1493
1494        if range.end <= range.start {
1495            return removed_values;
1496        }
1497
1498        if let Some((cursor, old_range, v)) = self.get_cursor_key_value(&range.start) {
1499            // Remove that range from the map.
1500            removed_values.push(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);
1514            }
1515
1516            // Notice that we can end up splitting the old range into two
1517            // separate ranges if the old range extends both beyond the given
1518            // range and before the given range.
1519        }
1520
1521        if let Some((cursor, old_range, v)) = self.get_cursor_key_value(&range.end) {
1522            // If the old range starts before the removed range, we need to trim the old range.
1523            // TODO: Optimize with replace once available.
1524            if old_range.start < range.end {
1525                // Remove that range from the map.
1526                removed_values.push(self.remove_at(cursor).expect("entry should exist"));
1527
1528                // If the removed range extends after the end of the given range,
1529                // re-insert the part of the old range that extends beyond the end
1530                // of the given range.
1531                if old_range.end > range.end {
1532                    self.insert_range_internal(range.end..old_range.end, v);
1533                }
1534            }
1535        }
1536
1537        let doomed = self.range(range.start..range.end).map(|(r, _)| r.start).collect::<Vec<_>>();
1538        for key in doomed {
1539            let cursor = self.find(&key, CursorPosition::Left);
1540            removed_values.push(self.remove_at(cursor).expect("entry should exist"));
1541        }
1542
1543        #[cfg(test)]
1544        self.node.validate_max_gap();
1545
1546        #[cfg(test)]
1547        self.node.validate_keys();
1548
1549        removed_values
1550    }
1551
1552    /// Insert the given range and value at the location indicated by the cursor.
1553    fn insert_at(&mut self, cursor: Cursor, range: Range<K>, value: V) -> Option<V> {
1554        let result = self.node.insert(cursor, range, value);
1555        match result {
1556            InsertResult::Inserted => None,
1557            InsertResult::SplitLeaf(key, right) => {
1558                let mut keys = ArrayVec::new();
1559                let mut children = ArrayVec::new();
1560                keys.push(key);
1561                let Node::Leaf(left) = self.node.clone() else {
1562                    unreachable!("non-leaf node split into leaf node");
1563                };
1564                children.push(left);
1565                children.push(right);
1566                self.node =
1567                    Node::Internal(Arc::new(NodeInternal::new(keys, ChildList::Leaf(children))));
1568                None
1569            }
1570            InsertResult::SplitInternal(key, right) => {
1571                let mut keys = ArrayVec::new();
1572                let mut children = ArrayVec::new();
1573                keys.push(key);
1574                let Node::Internal(left) = self.node.clone() else {
1575                    unreachable!("non-internal node split into internal node");
1576                };
1577                children.push(left);
1578                children.push(right);
1579                let mut new_internal = NodeInternal::new(keys, ChildList::Internal(children));
1580                new_internal.update_max_gap();
1581                self.node = Node::Internal(Arc::new(new_internal));
1582                None
1583            }
1584        }
1585    }
1586
1587    /// Insert the given range and value.
1588    ///
1589    /// Assumes the range is empty and that adjacent ranges have different values.
1590    fn insert_range_internal(&mut self, range: Range<K>, value: V) -> Option<V> {
1591        assert!(range.end > range.start);
1592        let cursor = self.find(&range.start, CursorPosition::Left);
1593        self.insert_at(cursor, range, value)
1594    }
1595
1596    /// Inserts a range with the given value.
1597    ///
1598    /// The keys included in the given range are now associated with the given
1599    /// value. If those keys were previously associated with another value,
1600    /// are no longer associated with that previous value.
1601    ///
1602    /// This method can cause one or more values in the map to be dropped if
1603    /// the all of the keys associated with those values are contained within
1604    /// the given range.
1605    ///
1606    /// If the inserted range is directly adjacent to another range with an equal value, the
1607    /// inserted range will be merged with the adjacent ranges.
1608    #[must_use]
1609    pub fn insert(&mut self, mut range: Range<K>, value: V) -> Vec<V> {
1610        if range.end <= range.start {
1611            return vec![];
1612        }
1613        let removed_values = self.remove(range.clone());
1614
1615        // Check for a range directly before this one. If it exists, it will be the last range with
1616        // start < range.start.
1617        if let Some((prev_range, prev_value)) = self.range(..range.start).next_back() {
1618            if prev_range.end == range.start && value == *prev_value {
1619                let cursor = self.find(&prev_range.start, CursorPosition::Left);
1620                range.start = prev_range.start;
1621
1622                // Don't include these values in the "removed" values. The new value is equal to
1623                // the previous value and will be cleaned up if the new merged range is removed.
1624                let _ = self.remove_at(cursor);
1625            }
1626        }
1627
1628        // Check for a range directly after. If it exists, we can look it up by exact start value
1629        // of range.end.
1630        if let Some((cursor, next_range, next_value)) = self.get_cursor_key_value(&range.end) {
1631            if next_range.start == range.end && value == next_value {
1632                range.end = next_range.end;
1633
1634                // Don't include these values in the "removed" values. The new value is equal to
1635                // the previous value and will be cleaned up if the new merged range is removed.
1636                let _ = self.remove_at(cursor);
1637            }
1638        }
1639
1640        self.insert_range_internal(range, value);
1641
1642        #[cfg(test)]
1643        self.node.validate_max_gap();
1644
1645        #[cfg(test)]
1646        self.node.validate_keys();
1647
1648        removed_values
1649    }
1650
1651    /// Appends a range with the given value, assuming it does not overlap with any existing range
1652    /// and is inserted in sorted order.
1653    ///
1654    /// This method avoids the overhead of searching for overlapping ranges.
1655    /// If the inserted range is directly adjacent to the last range with an equal value, the
1656    /// inserted range will be merged with the adjacent range.
1657    pub fn append_non_overlapping(&mut self, mut range: Range<K>, value: V) -> bool {
1658        if range.end <= range.start {
1659            return false;
1660        }
1661
1662        // Check for a range directly before this one. Since we assume sorted insertion,
1663        // it will be the last range in the map.
1664        if let Some((prev_range, prev_value)) = self.node.last_key_value() {
1665            if prev_range.end == range.start && value == *prev_value {
1666                let cursor = self.find(&prev_range.start, CursorPosition::Left);
1667                range.start = prev_range.start;
1668
1669                // Remove the previous range before inserting the merged one.
1670                let _ = self.remove_at(cursor);
1671            } else if range.start < prev_range.end {
1672                // Overlaps with previous range.
1673                return false;
1674            }
1675        }
1676
1677        self.insert_range_internal(range, value);
1678
1679        #[cfg(test)]
1680        self.node.validate_max_gap();
1681
1682        #[cfg(test)]
1683        self.node.validate_keys();
1684
1685        true
1686    }
1687
1688    /// Remove the entry with the given cursor from the map.
1689    #[must_use]
1690    fn remove_at(&mut self, cursor: Cursor) -> Option<V> {
1691        let result = self.node.remove(cursor);
1692        match result {
1693            RemoveResult::NotFound => None,
1694            RemoveResult::Removed(RemoveState { removed_value, .. }) => Some(removed_value),
1695            RemoveResult::Underflow(RemoveState { removed_value, .. }) => {
1696                match &mut self.node {
1697                    Node::Leaf(_) => {
1698                        // Nothing we can do about an underflow of a single leaf node at the root.
1699                    }
1700                    Node::Internal(node) => {
1701                        // If the root has underflown to a trivial list, we can shrink the tree.
1702                        if node.children.len() == 1 {
1703                            self.node = node.children.get(0);
1704                        }
1705                    }
1706                }
1707                Some(removed_value)
1708            }
1709        }
1710    }
1711
1712    /// Iterate through the keys and values stored in the map.
1713    pub fn iter(&self) -> Iter<'_, K, V> {
1714        Iter {
1715            forward: Cursor::with_index(0),
1716            backward: Cursor::with_index(self.node.len()),
1717            root: &self.node,
1718        }
1719    }
1720
1721    /// Create the cursor stack for the start bound of the given range.
1722    fn find_start_bound(&self, bounds: &impl RangeBounds<K>) -> Cursor {
1723        let key = match bounds.start_bound() {
1724            Bound::Included(key) => key,
1725            Bound::Excluded(key) => key,
1726            Bound::Unbounded => {
1727                return Cursor::with_index(0);
1728            }
1729        };
1730        self.find(key, CursorPosition::Left)
1731    }
1732
1733    /// Create the cursor stack for the end bound of the given range.
1734    fn find_end_bound(&self, bounds: &impl RangeBounds<K>) -> Cursor {
1735        let key = match bounds.end_bound() {
1736            Bound::Included(key) => key,
1737            Bound::Excluded(key) => key,
1738            Bound::Unbounded => {
1739                return Cursor::with_index(self.node.len());
1740            }
1741        };
1742        self.find(key, CursorPosition::Right)
1743    }
1744
1745    /// Iterate through the keys and values stored in the given range in the map.
1746    pub fn range(&self, bounds: impl RangeBounds<K>) -> Iter<'_, K, V> {
1747        let forward = self.find_start_bound(&bounds);
1748        let backward = self.find_end_bound(&bounds);
1749        Iter { forward, backward, root: &self.node }
1750    }
1751
1752    /// Find the first range in the map that starts at or after the given key.
1753    pub fn find_at_or_after(&self, key: K) -> Option<(&Range<K>, &V)> {
1754        let mut iter = self.range(key..).filter(move |(range, _)| key <= range.start);
1755        iter.next()
1756    }
1757
1758    /// Updates the value of an exact range in-place.
1759    ///
1760    /// Returns true if the range was found and updated, false otherwise.
1761    pub fn update_exact<F, E>(&mut self, range: &Range<K>, f: F) -> Result<bool, E>
1762    where
1763        F: FnOnce(&mut V) -> Result<(), E>,
1764    {
1765        if range.end <= range.start {
1766            return Ok(false);
1767        }
1768        if let Some((cursor, old_range, _)) = self.get_cursor_key_value(&range.start) {
1769            if old_range.start == range.start && old_range.end == range.end {
1770                self.node.update(cursor, f)?;
1771
1772                // Check if the mutated value is equal to neighbors, and merge if needed.
1773                let mut needs_merge = false;
1774                let value = self.node.get_key_value(cursor).map(|(_, v)| v.clone());
1775                if let Some(value) = value {
1776                    if let Some((prev_range, prev_value)) = self.range(..range.start).next_back() {
1777                        if prev_range.end == range.start && value == *prev_value {
1778                            needs_merge = true;
1779                        }
1780                    }
1781                    if !needs_merge {
1782                        if let Some((_, next_range, next_value)) =
1783                            self.get_cursor_key_value(&range.end)
1784                        {
1785                            if next_range.start == range.end && value == next_value {
1786                                needs_merge = true;
1787                            }
1788                        }
1789                    }
1790                }
1791
1792                if needs_merge {
1793                    if let Some(value) = self.remove(range.clone()).pop() {
1794                        let _ = self.insert(range.clone(), value);
1795                    }
1796                }
1797                return Ok(true);
1798            }
1799        }
1800        Ok(false)
1801    }
1802}
1803
1804#[cfg(test)]
1805mod test {
1806    use super::*;
1807
1808    #[::fuchsia::test]
1809    fn test_empty() {
1810        let mut map = RangeMap::<u32, i32>::default();
1811
1812        assert!(map.get(12).is_none());
1813        let _ = map.remove(10..34);
1814        // This is a test to make sure we can handle reversed ranges
1815        #[allow(clippy::reversed_empty_ranges)]
1816        let _ = map.remove(34..10);
1817    }
1818
1819    #[::fuchsia::test]
1820    fn test_is_empty() {
1821        let mut map = RangeMap::<u32, i32>::default();
1822
1823        // Test empty map
1824        assert!(map.is_empty());
1825
1826        // Test map with 5 entries
1827        for i in 0..5 {
1828            let start = i * 10;
1829            let end = start + 5;
1830            let _ = map.insert(start..end, i as i32);
1831        }
1832        assert!(!map.is_empty());
1833
1834        // Remove all entries
1835        for i in 0..5 {
1836            let start = i * 10;
1837            let end = start + 5;
1838            let _ = map.remove(start..end);
1839        }
1840        assert!(map.is_empty());
1841
1842        // Test map with 50 entries
1843        for i in 0..50 {
1844            let start = i * 10;
1845            let end = start + 5;
1846            let _ = map.insert(start..end, i as i32);
1847        }
1848        assert!(!map.is_empty());
1849
1850        // Remove all entries
1851        for i in 0..50 {
1852            let start = i * 10;
1853            let end = start + 5;
1854            let _ = map.remove(start..end);
1855        }
1856        assert!(map.is_empty());
1857    }
1858
1859    #[::fuchsia::test]
1860    fn test_insert_into_empty() {
1861        let mut map = RangeMap::<u32, i32>::default();
1862
1863        let _ = map.insert(10..34, -14);
1864
1865        assert_eq!((&(10..34), &-14), map.get(12).unwrap());
1866        assert_eq!((&(10..34), &-14), map.get(10).unwrap());
1867        assert!(map.get(9).is_none());
1868        assert_eq!((&(10..34), &-14), map.get(33).unwrap());
1869        assert!(map.get(34).is_none());
1870    }
1871
1872    #[::fuchsia::test]
1873    fn test_append_non_overlapping() {
1874        let mut map = RangeMap::<u32, i32>::default();
1875
1876        assert!(!map.append_non_overlapping(10..10, 1));
1877        assert!(map.append_non_overlapping(10..20, 1));
1878        assert!(map.append_non_overlapping(20..30, 1)); // Should merge!
1879        assert!(map.append_non_overlapping(40..50, 2)); // Should not merge!
1880        assert!(!map.append_non_overlapping(15..25, 3)); // Should fail on overlap
1881
1882        assert_eq!((&(10..30), &1), map.get(15).unwrap());
1883        assert_eq!((&(10..30), &1), map.get(25).unwrap());
1884        assert_eq!((&(40..50), &2), map.get(45).unwrap());
1885        assert!(map.get(35).is_none());
1886    }
1887
1888    #[::fuchsia::test]
1889    fn test_iter() {
1890        let mut map = RangeMap::<u32, i32>::default();
1891
1892        let _ = map.insert(10..34, -14);
1893        let _ = map.insert(74..92, -12);
1894
1895        let mut iter = map.iter();
1896
1897        assert_eq!(iter.next().expect("missing elem"), (&(10..34), &-14));
1898        assert_eq!(iter.next().expect("missing elem"), (&(74..92), &-12));
1899
1900        assert!(iter.next().is_none());
1901
1902        let entry = map.find_at_or_after(10);
1903        assert_eq!(entry.expect("missing elem"), (&(10..34), &-14));
1904        let entry = map.find_at_or_after(11);
1905        assert_eq!(entry.expect("missing elem"), (&(74..92), &-12));
1906        let entry = map.find_at_or_after(74);
1907        assert_eq!(entry.expect("missing elem"), (&(74..92), &-12));
1908        let entry = map.find_at_or_after(75);
1909        assert_eq!(entry, None);
1910
1911        assert_eq!(map.range(..9).collect::<Vec<_>>(), vec![]);
1912        assert_eq!(map.range(..34).collect::<Vec<_>>(), vec![(&(10..34), &-14)]);
1913        assert_eq!(map.range(..74).collect::<Vec<_>>(), vec![(&(10..34), &-14)]);
1914        assert_eq!(map.range(..75).collect::<Vec<_>>(), vec![(&(10..34), &-14), (&(74..92), &-12)]);
1915        assert_eq!(map.range(..91).collect::<Vec<_>>(), vec![(&(10..34), &-14), (&(74..92), &-12)]);
1916        assert_eq!(map.range(..92).collect::<Vec<_>>(), vec![(&(10..34), &-14), (&(74..92), &-12)]);
1917    }
1918
1919    #[::fuchsia::test]
1920    fn test_remove_overlapping_edge() {
1921        let mut map = RangeMap::<u32, i32>::default();
1922
1923        let _ = map.insert(10..34, -14);
1924
1925        let _ = map.remove(2..11);
1926        assert_eq!((&(11..34), &-14), map.get(11).unwrap());
1927
1928        let _ = map.remove(33..42);
1929        assert_eq!((&(11..33), &-14), map.get(12).unwrap());
1930    }
1931
1932    #[::fuchsia::test]
1933    fn test_remove_middle_splits_range() {
1934        let mut map = RangeMap::<u32, i32>::default();
1935
1936        let _ = map.insert(10..34, -14);
1937        let _ = map.remove(15..18);
1938
1939        assert_eq!((&(10..15), &-14), map.get(12).unwrap());
1940        assert_eq!((&(18..34), &-14), map.get(20).unwrap());
1941    }
1942
1943    #[::fuchsia::test]
1944    fn test_remove_upper_half_of_split_range_leaves_lower_range() {
1945        let mut map = RangeMap::<u32, i32>::default();
1946
1947        let _ = map.insert(10..34, -14);
1948        let _ = map.remove(15..18);
1949        let _ = map.insert(2..7, -21);
1950        let _ = map.remove(20..42);
1951
1952        assert_eq!((&(2..7), &-21), map.get(5).unwrap());
1953        assert_eq!((&(10..15), &-14), map.get(12).unwrap());
1954    }
1955
1956    #[::fuchsia::test]
1957    fn test_range_map_overlapping_insert() {
1958        let mut map = RangeMap::<u32, i32>::default();
1959
1960        let _ = map.insert(2..7, -21);
1961        let _ = map.insert(5..9, -42);
1962        let _ = map.insert(1..3, -43);
1963        let _ = map.insert(6..8, -44);
1964
1965        assert_eq!((&(1..3), &-43), map.get(2).unwrap());
1966        assert_eq!((&(3..5), &-21), map.get(4).unwrap());
1967        assert_eq!((&(5..6), &-42), map.get(5).unwrap());
1968        assert_eq!((&(6..8), &-44), map.get(7).unwrap());
1969    }
1970
1971    #[::fuchsia::test]
1972    fn test_intersect_single() {
1973        let mut map = RangeMap::<u32, i32>::default();
1974
1975        let _ = map.insert(2..7, -10);
1976
1977        let mut iter = map.range(3..4);
1978        assert_eq!(iter.next(), Some((&(2..7), &-10)));
1979        assert_eq!(iter.next(), None);
1980
1981        let mut iter = map.range(2..3);
1982        assert_eq!(iter.next(), Some((&(2..7), &-10)));
1983        assert_eq!(iter.next(), None);
1984
1985        let mut iter = map.range(1..4);
1986        assert_eq!(iter.next(), Some((&(2..7), &-10)));
1987        assert_eq!(iter.next(), None);
1988
1989        let mut iter = map.range(1..2);
1990        assert_eq!(iter.next(), None);
1991
1992        let mut iter = map.range(6..7);
1993        assert_eq!(iter.next(), Some((&(2..7), &-10)));
1994        assert_eq!(iter.next(), None);
1995    }
1996
1997    #[::fuchsia::test]
1998    fn test_intersect_multiple() {
1999        let mut map = RangeMap::<u32, i32>::default();
2000
2001        let _ = map.insert(2..7, -10);
2002        let _ = map.insert(7..9, -20);
2003        let _ = map.insert(10..11, -30);
2004
2005        let mut iter = map.range(3..8);
2006        assert_eq!(iter.next(), Some((&(2..7), &-10)));
2007        assert_eq!(iter.next(), Some((&(7..9), &-20)));
2008        assert_eq!(iter.next(), None);
2009
2010        let mut iter = map.range(3..11);
2011        assert_eq!(iter.next(), Some((&(2..7), &-10)));
2012        assert_eq!(iter.next(), Some((&(7..9), &-20)));
2013        assert_eq!(iter.next(), Some((&(10..11), &-30)));
2014        assert_eq!(iter.next(), None);
2015    }
2016
2017    #[::fuchsia::test]
2018    fn test_intersect_no_gaps() {
2019        let mut map = RangeMap::<u32, i32>::default();
2020
2021        let _ = map.insert(0..1, -10);
2022        let _ = map.insert(1..2, -20);
2023        let _ = map.insert(2..3, -30);
2024
2025        let mut iter = map.range(0..3);
2026        assert_eq!(iter.next(), Some((&(0..1), &-10)));
2027        assert_eq!(iter.next(), Some((&(1..2), &-20)));
2028        assert_eq!(iter.next(), Some((&(2..3), &-30)));
2029        assert_eq!(iter.next(), None);
2030    }
2031
2032    #[test]
2033    fn test_merging() {
2034        let mut map = RangeMap::<u32, i32>::default();
2035
2036        let _ = map.insert(1..2, -10);
2037        assert_eq!(map.iter().collect::<Vec<_>>(), vec![(&(1..2), &-10)]);
2038        let _ = map.insert(3..4, -10);
2039        assert_eq!(map.iter().collect::<Vec<_>>(), vec![(&(1..2), &-10), (&(3..4), &-10)]);
2040        let _ = map.insert(2..3, -10);
2041        assert_eq!(map.iter().collect::<Vec<_>>(), vec![(&(1..4), &-10)]);
2042        let _ = map.insert(0..1, -10);
2043        assert_eq!(map.iter().collect::<Vec<_>>(), vec![(&(0..4), &-10)]);
2044        let _ = map.insert(4..5, -10);
2045        assert_eq!(map.iter().collect::<Vec<_>>(), vec![(&(0..5), &-10)]);
2046        let _ = map.insert(2..3, -20);
2047        assert_eq!(
2048            map.iter().collect::<Vec<_>>(),
2049            vec![(&(0..2), &-10), (&(2..3), &-20), (&(3..5), &-10)]
2050        );
2051    }
2052
2053    #[test]
2054    fn test_remove_multiple_ranges_exact_query() {
2055        let first = 15..21;
2056        let second = first.end..29;
2057
2058        let mut map = RangeMap::default();
2059        let _ = map.insert(first.clone(), 1);
2060        let _ = map.insert(second.clone(), 2);
2061
2062        assert_eq!(map.remove(first.start..second.end), &[1, 2]);
2063    }
2064
2065    #[::fuchsia::test]
2066    fn test_large_insert_and_remove() {
2067        let mut map = RangeMap::<u32, i32>::default();
2068        let num_entries = 1000;
2069
2070        // Insert a large number of entries
2071        for i in 0..num_entries {
2072            let start = i as u32 * 10;
2073            let end = start + 5;
2074            let value = i as i32;
2075            let _ = map.insert(start..end, value);
2076        }
2077
2078        // Verify that all inserted entries can be retrieved
2079        for i in 0..num_entries {
2080            let start = i as u32 * 10;
2081            let end = start + 5;
2082            let point = start + 2;
2083            if let Some((range, value)) = map.get(point) {
2084                assert!(range.start <= point && point < range.end);
2085                assert_eq!(*range, start..end);
2086                assert_eq!(*value, i as i32);
2087            } else {
2088                panic!("Expected to find a range for point {}", point);
2089            }
2090        }
2091
2092        // Remove a large number of entries
2093        for i in 0..num_entries {
2094            let start = i as u32 * 10;
2095            let end = start + 5;
2096            let _ = map.remove(start..end);
2097        }
2098
2099        // Verify that the map is empty after removing all entries
2100        assert!(map.is_empty());
2101    }
2102
2103    #[::fuchsia::test]
2104    fn test_large_insert_and_remove_overlapping() {
2105        let mut map = RangeMap::<u32, i32>::default();
2106        let num_entries = 1000;
2107
2108        // Insert a large number of entries with overlapping ranges
2109        for i in 0..num_entries {
2110            let start = i as u32 * 5;
2111            let end = start + 20;
2112            let value = i as i32;
2113            let _ = map.insert(start..end, value);
2114        }
2115
2116        // Verify that all inserted entries can be retrieved
2117        for i in 0..num_entries {
2118            let point = i as u32 * 5 + 1;
2119            if let Some((range, value)) = map.get(point) {
2120                assert!(range.start <= point && point < range.end);
2121                assert_eq!(*value, i as i32);
2122            } else {
2123                panic!("Expected to find a range for point {}", point);
2124            }
2125        }
2126
2127        // Remove a large number of entries with overlapping ranges
2128        for i in 0..num_entries {
2129            let start = i as u32 * 5;
2130            let end = start + 20;
2131            let _ = map.remove(start..end);
2132        }
2133
2134        // Verify that the map is empty after removing all entries
2135        assert!(map.is_empty());
2136    }
2137
2138    #[::fuchsia::test]
2139    fn test_large_insert_and_get_specific_points() {
2140        let mut map = RangeMap::<u32, i32>::default();
2141        let num_entries = 1000;
2142        let mut inserted_ranges = Vec::new();
2143
2144        // Insert a large number of entries
2145        for i in 0..num_entries {
2146            let start = i as u32 * 10;
2147            let end = start + 5;
2148            let value = i as i32;
2149            let _ = map.insert(start..end, value);
2150            inserted_ranges.push((start..end, value));
2151        }
2152
2153        // Verify that specific points can be retrieved correctly
2154        for (range, value) in &inserted_ranges {
2155            let point = range.start + 2;
2156            let (retrieved_range, retrieved_value) = map.get(point).unwrap();
2157            assert_eq!(retrieved_range, range);
2158            assert_eq!(retrieved_value, value);
2159        }
2160    }
2161
2162    #[::fuchsia::test]
2163    fn test_large_insert_and_iter() {
2164        let mut map = RangeMap::<u32, i32>::default();
2165        let num_entries = 1000;
2166        let mut inserted_ranges = Vec::new();
2167
2168        // Insert a large number of entries
2169        for i in 0..num_entries {
2170            let start = i as u32 * 10;
2171            let end = start + 5;
2172            let value = i as i32;
2173            let _ = map.insert(start..end, value);
2174            inserted_ranges.push((start..end, value));
2175        }
2176
2177        // Verify that iter() returns all inserted entries
2178        let mut iter_ranges: Vec<(&Range<u32>, &i32)> = map.iter().collect();
2179        iter_ranges.sort_by_key(|(range, _)| range.start);
2180        let mut inserted_ranges_sorted: Vec<(Range<u32>, i32)> = inserted_ranges.clone();
2181        inserted_ranges_sorted.sort_by_key(|(range, _)| range.start);
2182
2183        assert_eq!(iter_ranges.len(), inserted_ranges_sorted.len());
2184        for (i, (range, value)) in iter_ranges.iter().enumerate() {
2185            assert_eq!(*range, &inserted_ranges_sorted[i].0);
2186            assert_eq!(*value, &inserted_ranges_sorted[i].1);
2187        }
2188    }
2189
2190    #[::fuchsia::test]
2191    fn test_large_insert_and_range() {
2192        let mut map = RangeMap::<u32, i32>::default();
2193        let num_entries = 1000;
2194
2195        // Insert a large number of entries
2196        for i in 0..num_entries {
2197            let start = i as u32 * 10;
2198            let end = start + 5;
2199            let value = i as i32;
2200            let _ = map.insert(start..end, value);
2201        }
2202
2203        // Verify range(start_point..)
2204        let start_point = 5000;
2205        let mut iter = map.range(start_point..);
2206        while let Some((range, _)) = iter.next() {
2207            assert!(range.start >= start_point);
2208        }
2209    }
2210
2211    #[::fuchsia::test]
2212    fn test_large_insert_and_iter_ending_at() {
2213        let mut map = RangeMap::<u32, i32>::default();
2214        let num_entries = 1000;
2215
2216        // Insert a large number of entries
2217        for i in 0..num_entries {
2218            let start = i as u32 * 10;
2219            let end = start + 5;
2220            let value = i as i32;
2221            let _ = map.insert(start..end, value);
2222        }
2223
2224        // Verify range(..end_point)
2225        let end_point = 5000;
2226        let mut iter = map.range(..end_point);
2227        while let Some((range, _)) = iter.next() {
2228            assert!(range.start < end_point);
2229        }
2230    }
2231
2232    #[::fuchsia::test]
2233    fn test_large_insert_and_intersection() {
2234        let mut map = RangeMap::<u32, i32>::default();
2235        let num_entries = 1000;
2236
2237        // Insert a large number of entries
2238        for i in 0..num_entries {
2239            let start = i as u32 * 10;
2240            let end = start + 5;
2241            let value = i as i32;
2242            let _ = map.insert(start..end, value);
2243        }
2244
2245        // Verify intersection()
2246        let intersect_start = 4000;
2247        let intersect_end = 4050;
2248        let mut iter = map.range(intersect_start..intersect_end);
2249        while let Some((range, _)) = iter.next() {
2250            assert!(range.start < intersect_end && range.end > intersect_start);
2251        }
2252    }
2253
2254    #[::fuchsia::test]
2255    fn test_large_insert_and_last_range() {
2256        let mut map = RangeMap::<u32, i32>::default();
2257        let num_entries = 1000;
2258        let mut last_range = None;
2259
2260        // Insert a large number of entries
2261        for i in 0..num_entries {
2262            let start = i as u32 * 10;
2263            let end = start + 5;
2264            let value = i as i32;
2265            let _ = map.insert(start..end, value);
2266            last_range = Some(start..end);
2267        }
2268
2269        // Verify last_range()
2270        if let Some(expected_last_range) = last_range {
2271            assert_eq!(map.last_range().unwrap(), &expected_last_range);
2272        }
2273    }
2274
2275    #[::fuchsia::test]
2276    fn test_large_insert_and_remove_alternating() {
2277        let mut map = RangeMap::<u32, i32>::default();
2278        let num_entries = 1000;
2279
2280        // Insert and remove entries in an alternating pattern
2281        for i in 0..num_entries {
2282            let start = i as u32 * 10;
2283            let end = start + 5;
2284            let value = i as i32;
2285            let _ = map.insert(start..end, value);
2286
2287            if i % 2 == 0 {
2288                // Remove every other entry
2289                let _ = map.remove(start..end);
2290            }
2291        }
2292
2293        // Verify that only the non-removed entries remain
2294        for i in 0..num_entries {
2295            let start = i as u32 * 10;
2296            let end = start + 5;
2297            let point = start + 2;
2298            if i % 2 != 0 {
2299                if let Some((range, value)) = map.get(point) {
2300                    assert!(range.start <= point && point < range.end);
2301                    assert_eq!(*range, start..end);
2302                    assert_eq!(*value, i as i32);
2303                } else {
2304                    panic!("Expected to find a range for point {}", point);
2305                }
2306            } else {
2307                assert!(map.get(point).is_none());
2308            }
2309        }
2310    }
2311
2312    #[::fuchsia::test]
2313    fn test_large_insert_and_remove_multiple_times() {
2314        let mut map = RangeMap::<u32, i32>::default();
2315        let num_entries = 200;
2316        let num_iterations = 5;
2317
2318        for _ in 0..num_iterations {
2319            // Insert a large number of entries
2320            for i in 0..num_entries {
2321                let start = i as u32 * 10;
2322                let end = start + 5;
2323                let value = i as i32;
2324                let _ = map.insert(start..end, value);
2325            }
2326
2327            // Remove a large number of entries
2328            for i in 0..num_entries {
2329                let start = i as u32 * 10;
2330                let end = start + 5;
2331                let _ = map.remove(start..end);
2332            }
2333        }
2334
2335        // Verify that the map is empty after multiple insert/remove cycles
2336        assert!(map.is_empty());
2337    }
2338
2339    #[::fuchsia::test]
2340    fn test_leaf_node_split() {
2341        let mut map = RangeMap::<u32, i32>::default();
2342
2343        // Fill the leaf node to capacity
2344        for i in 0..NODE_CAPACITY {
2345            let start = i as u32 * 10;
2346            let end = start + 5;
2347            let _ = map.insert(start..end, i as i32);
2348        }
2349
2350        // Verify the initial state
2351        assert_eq!(map.node.len(), NODE_CAPACITY);
2352
2353        {
2354            let mut map = map.clone();
2355
2356            // Insert a value that causes a split in the first half
2357            let split_start = 15;
2358            let split_end = 20;
2359            let _ = map.insert(split_start..split_end, -1);
2360
2361            // Verify the split
2362            assert!(matches!(map.node, Node::Internal(_)));
2363            if let Node::Internal(internal) = &map.node {
2364                assert_eq!(internal.children.len(), 2);
2365                assert!(internal.children.size_at(0) >= NODE_CAPACITY / 2);
2366                assert!(internal.children.size_at(1) >= NODE_CAPACITY / 2);
2367            }
2368        }
2369
2370        {
2371            let mut map = map.clone();
2372
2373            // Insert a value that causes a split in the second half
2374            let split_start = (NODE_CAPACITY as u32 * 10) + 5;
2375            let split_end = split_start + 5;
2376            let _ = map.insert(split_start..split_end, -2);
2377
2378            // Verify the second split
2379            if let Node::Internal(internal) = &map.node {
2380                assert_eq!(internal.children.len(), 2);
2381                assert!(internal.children.size_at(0) >= NODE_CAPACITY / 2);
2382            }
2383        }
2384    }
2385
2386    #[::fuchsia::test]
2387    fn test_merging_ranges_with_equal_values() {
2388        let mut map = RangeMap::<u32, i32>::default();
2389
2390        // Insert some initial ranges
2391        let _ = map.insert(10..20, 100);
2392        let _ = map.insert(30..40, 200);
2393        let _ = map.insert(50..60, 100);
2394
2395        // Merge adjacent ranges with equal values
2396        let _ = map.insert(20..30, 100);
2397        assert_eq!(map.get(15).unwrap(), (&(10..30), &100));
2398        assert_eq!(map.get(35).unwrap(), (&(30..40), &200));
2399        assert_eq!(map.get(55).unwrap(), (&(50..60), &100));
2400
2401        // Merge non-adjacent ranges with equal values
2402        let _ = map.insert(40..50, 100);
2403        assert_eq!(map.get(15).unwrap(), (&(10..30), &100));
2404        assert_eq!(map.get(35).unwrap(), (&(30..40), &200));
2405        assert_eq!(map.get(45).unwrap(), (&(40..60), &100));
2406
2407        // Insert a range with a different value
2408        let _ = map.insert(60..70, 300);
2409        assert_eq!(map.get(65).unwrap(), (&(60..70), &300));
2410
2411        // Merge a range with a different value
2412        let _ = map.insert(70..80, 300);
2413        assert_eq!(map.get(65).unwrap(), (&(60..80), &300));
2414
2415        // Merge a range with a different value at the beginning
2416        let _ = map.insert(0..10, 400);
2417        assert_eq!(map.get(5).unwrap(), (&(0..10), &400));
2418
2419        // Merge a range with a different value at the end
2420        let _ = map.insert(80..90, 400);
2421        assert_eq!(map.get(85).unwrap(), (&(80..90), &400));
2422
2423        // Merge a range with a different value in the middle
2424        let _ = map.insert(90..100, 400);
2425        assert_eq!(map.get(95).unwrap(), (&(80..100), &400));
2426        let _ = map.insert(100..110, 400);
2427        assert_eq!(map.get(95).unwrap(), (&(80..110), &400));
2428        let _ = map.insert(110..120, 400);
2429        assert_eq!(map.get(95).unwrap(), (&(80..120), &400));
2430
2431        // Merge a range with a different value in the middle
2432        let _ = map.insert(10..90, 400);
2433        assert_eq!(map.get(5).unwrap(), (&(0..120), &400));
2434    }
2435
2436    #[::fuchsia::test]
2437    fn test_large_insert_and_remove_with_gaps() {
2438        let mut map = RangeMap::<u32, i32>::default();
2439        let num_entries = 500;
2440
2441        // Insert entries with gaps
2442        for i in 0..num_entries {
2443            let start = i as u32 * 20;
2444            let end = start + 5;
2445            let value = i as i32;
2446            let _ = map.insert(start..end, value);
2447        }
2448
2449        // Remove entries with gaps
2450        for i in 0..num_entries {
2451            if i % 2 == 0 {
2452                let start = i as u32 * 20;
2453                let end = start + 5;
2454                let _ = map.remove(start..end);
2455            }
2456        }
2457
2458        // Verify the state of the map
2459        for i in 0..num_entries {
2460            let start = i as u32 * 20;
2461            let end = start + 5;
2462            let point = start + 2;
2463
2464            if i % 2 != 0 {
2465                if let Some((range, value)) = map.get(point) {
2466                    assert!(range.start <= point && point < range.end);
2467                    assert_eq!(*range, start..end);
2468                    assert_eq!(*value, i as i32);
2469                } else {
2470                    panic!("Expected to find a range for point {}", point);
2471                }
2472            } else {
2473                assert!(map.get(point).is_none());
2474            }
2475        }
2476    }
2477
2478    #[::fuchsia::test]
2479    fn test_critical_removal() {
2480        fn range_for(i: u32) -> Range<u32> {
2481            let start = i * 20;
2482            let end = start + 5;
2483            start..end
2484        }
2485
2486        // Index 0 cannot be the critical index.
2487        for critial_index in 1..100 {
2488            let mut map = RangeMap::<u32, i32>::default();
2489
2490            // Insert enough entries for force a split somewhere.
2491            for i in 0..100 {
2492                let value = i as i32;
2493                let _ = map.insert(range_for(i), value);
2494            }
2495
2496            // We don't know whether the split will occur at the critical index, but we try all the
2497            // possible indices to ensure that we test an index at which a split occurred.
2498            let critical_range = range_for(critial_index);
2499            let _ = map.remove(critical_range.clone());
2500
2501            // We now insert a range that spans the critical point. This range will be inserted to
2502            // left of the split.
2503            let value = -10 as i32;
2504            let spanning_range = (critical_range.start - 2)..(critical_range.start + 2);
2505            let _ = map.insert(spanning_range.clone(), value);
2506
2507            // Check to see if we can find the range by looking before the critical point.
2508            let key_before_split = critical_range.start - 1;
2509            assert_eq!(map.get(key_before_split), Some((&spanning_range, &value)));
2510
2511            // Check to see if we can find the range by looking after the critical point.
2512            let key_after_split = critical_range.start + 1;
2513            assert_eq!(map.get(key_after_split), Some((&spanning_range, &value)));
2514        }
2515    }
2516
2517    #[::fuchsia::test]
2518    fn test_find_gap_end_empty() {
2519        let map = RangeMap::<u32, i32>::default();
2520        assert_eq!(map.find_gap_end(10, &100), 100);
2521    }
2522
2523    #[::fuchsia::test]
2524    fn test_find_gap_end_single_range() {
2525        let mut map = RangeMap::<u32, i32>::default();
2526        let _ = map.insert(10..20, 1);
2527        assert_eq!(map.find_gap_end(10, &100), 100);
2528    }
2529
2530    #[::fuchsia::test]
2531    fn test_find_gap_end_multiple_ranges() {
2532        let mut map = RangeMap::<u32, i32>::default();
2533        let _ = map.insert(10..20, 1);
2534        let _ = map.insert(40..50, 2);
2535        let _ = map.insert(60..70, 3);
2536
2537        // Test finding gaps of various sizes
2538        assert_eq!(map.find_gap_end(5, &80), 80);
2539        assert_eq!(map.find_gap_end(10, &80), 80);
2540        assert_eq!(map.find_gap_end(11, &80), 40);
2541        assert_eq!(map.find_gap_end(20, &80), 40);
2542        assert_eq!(map.find_gap_end(21, &80), 10);
2543
2544        // Test finding gaps of various sizes with a lower bound
2545        assert_eq!(map.find_gap_end(5, &10), 10);
2546        assert_eq!(map.find_gap_end(5, &20), 10);
2547        assert_eq!(map.find_gap_end(5, &30), 30);
2548        assert_eq!(map.find_gap_end(5, &40), 40);
2549        assert_eq!(map.find_gap_end(5, &50), 40);
2550        assert_eq!(map.find_gap_end(5, &60), 60);
2551        assert_eq!(map.find_gap_end(5, &70), 60);
2552        assert_eq!(map.find_gap_end(5, &80), 80);
2553        assert_eq!(map.find_gap_end(5, &90), 90);
2554        assert_eq!(map.find_gap_end(5, &100), 100);
2555    }
2556
2557    #[::fuchsia::test]
2558    fn test_find_gap_end_rightmost() {
2559        let mut map = RangeMap::<u32, i32>::default();
2560        let _ = map.insert(10..20, 1);
2561        let _ = map.insert(30..40, 2);
2562        let _ = map.insert(50..60, 3);
2563        let _ = map.insert(70..80, 4);
2564
2565        // All gaps are size 10, should find the rightmost one
2566        assert_eq!(map.find_gap_end(10, &10), 10);
2567        assert_eq!(map.find_gap_end(10, &20), 10);
2568        assert_eq!(map.find_gap_end(10, &30), 30);
2569        assert_eq!(map.find_gap_end(10, &40), 30);
2570        assert_eq!(map.find_gap_end(10, &50), 50);
2571        assert_eq!(map.find_gap_end(10, &60), 50);
2572        assert_eq!(map.find_gap_end(10, &70), 70);
2573        assert_eq!(map.find_gap_end(10, &80), 70);
2574        assert_eq!(map.find_gap_end(10, &90), 90);
2575        assert_eq!(map.find_gap_end(10, &100), 100);
2576    }
2577
2578    #[::fuchsia::test]
2579    fn test_find_gap_end_large_map() {
2580        let mut map = RangeMap::<u32, i32>::default();
2581        let num_entries = 1000;
2582
2583        fn range_for(i: u32) -> Range<u32> {
2584            let start = i * (8000 - i) as u32;
2585            let end = start + 10;
2586            start..end
2587        }
2588
2589        // Insert ranges with decreasing gap sizes
2590        for i in 0..num_entries {
2591            let _ = map.insert(range_for(i), i as i32);
2592        }
2593
2594        let upper_bound = range_for(num_entries - 1).end;
2595
2596        for i in 0..num_entries - 1 {
2597            let current_range = range_for(i);
2598            let next_range = range_for(i + 1);
2599            let gap_size = current_range.end.measure_gap(&next_range.start);
2600            assert_eq!(map.find_gap_end(gap_size, &upper_bound), next_range.start);
2601        }
2602    }
2603
2604    #[::fuchsia::test]
2605    fn test_find_gap_end_after_removal() {
2606        let mut map = RangeMap::<u32, i32>::default();
2607        let _ = map.insert(10..20, 1);
2608        let _ = map.insert(30..40, 2);
2609        let _ = map.insert(50..60, 3);
2610
2611        assert_eq!(map.find_gap_end(12, &60), 10);
2612
2613        let _ = map.remove(30..35);
2614        assert_eq!(map.find_gap_end(12, &60), 35);
2615    }
2616
2617    #[::fuchsia::test]
2618    fn test_find_gap_end_adjacent_ranges() {
2619        let mut map = RangeMap::<u32, i32>::default();
2620        let _ = map.insert(10..20, 1);
2621        let _ = map.insert(20..30, 2);
2622        let _ = map.insert(30..40, 3);
2623
2624        // No gaps between ranges
2625        assert_eq!(map.find_gap_end(1, &100), 100);
2626    }
2627
2628    #[::fuchsia::test]
2629    fn test_find_gap_end_merging() {
2630        let mut map = RangeMap::<u32, i32>::default();
2631        let _ = map.insert(10..20, 1);
2632        let _ = map.insert(30..40, 2);
2633        let _ = map.insert(50..60, 2); // Same value as previous range
2634
2635        // Initially should find the last gap
2636        assert_eq!(map.find_gap_end(10, &100), 100);
2637
2638        // Merge the last two ranges
2639        let _ = map.insert(40..50, 1);
2640
2641        // Now should find the first gap
2642        assert_eq!(map.find_gap_end(10, &100), 100);
2643    }
2644
2645    #[::fuchsia::test]
2646    fn test_remove_empty_node() {
2647        let mut map = RangeMap::<u32, i32>::default();
2648
2649        // Fill two leaf nodes to capacity.
2650        for i in 0..(NODE_CAPACITY * 2) {
2651            let start = i as u32 * 10;
2652            let end = start + 1;
2653            let _ = map.insert(start..end, i as i32 * 100);
2654        }
2655
2656        // Insert at the right edge of the left leaf node, causing us to create a middle leaf node
2657        // with a single element.
2658        let i = NODE_CAPACITY - 1;
2659        let start = i as u32 * 10 + 2;
2660        let end = start + 1;
2661        let critical_range = start..end;
2662        let _ = map.insert(critical_range.clone(), i as i32 * 1000);
2663
2664        {
2665            // Remove the lone entry from the middle leaf node, ensuring that we pass our internal
2666            // validation checks in that scenario.
2667            let mut map = map.clone();
2668            let _ = map.remove(critical_range.clone());
2669        }
2670
2671        {
2672            let mut map = map.clone();
2673
2674            // Remove a bunch of nodes from the left side to encourage rebalancing from the right.
2675            for i in 0..(NODE_CAPACITY / 2 - 1) {
2676                let start = i as u32 * 10;
2677                let end = start + 1;
2678                let _ = map.remove(start..end);
2679            }
2680
2681            // Again, we remove the lone entry from the middle leaf node. This check is similar to
2682            // the previous check, but now the left leaf node has fewer elements, which would have
2683            // caused us to rebalance to the right in a previous version of this data structure.
2684            let _ = map.remove(critical_range);
2685        }
2686    }
2687
2688    #[::fuchsia::test]
2689    fn test_insert_overwrites_completely() {
2690        let mut map = RangeMap::<u32, i32>::default();
2691        let _ = map.insert(10..20, 1);
2692        let removed = map.insert(10..20, 10);
2693        assert_eq!(removed, vec![1]);
2694    }
2695
2696    #[::fuchsia::test]
2697    fn test_insert_overwrites_partially() {
2698        let mut map = RangeMap::<u32, i32>::default();
2699        let _ = map.insert(30..40, 2);
2700        let removed = map.insert(35..45, 20);
2701        assert_eq!(removed, vec![2]);
2702        assert_eq!(
2703            map.get(32),
2704            Some((&(30..35), &2)),
2705            "remaining part of overwritten range should exist"
2706        );
2707    }
2708
2709    #[::fuchsia::test]
2710    fn test_insert_overwrites_multiple() {
2711        let mut map = RangeMap::<u32, i32>::default();
2712        let _ = map.insert(10..20, 1);
2713        let _ = map.insert(30..40, 2);
2714        let _ = map.insert(50..60, 3);
2715
2716        let removed = map.insert(15..55, 30);
2717        let mut removed = removed;
2718        removed.sort();
2719        assert_eq!(removed, vec![1, 2, 3]);
2720    }
2721
2722    #[::fuchsia::test]
2723    fn test_insert_merge_does_not_return_values() {
2724        let mut map = RangeMap::<u32, i32>::default();
2725
2726        let _ = map.insert(10..20, 1);
2727
2728        let removed = map.insert(20..30, 1);
2729        assert!(removed.is_empty(), "merging right should not return removed values");
2730        assert_eq!(map.get(15), Some((&(10..30), &1)));
2731
2732        let removed = map.insert(0..10, 1);
2733        assert!(removed.is_empty(), "merging left should not return removed values");
2734        assert_eq!(map.get(15), Some((&(0..30), &1)));
2735    }
2736
2737    #[::fuchsia::test]
2738    fn test_update_exact() {
2739        let mut map = RangeMap::<u32, i32>::default();
2740        let _ = map.insert(10..20, 1);
2741        let _ = map.insert(30..40, 2);
2742        let _ = map.insert(50..60, 3);
2743
2744        // 1. Update non-existent range.
2745        assert!(
2746            !map.update_exact(&(10..15), |v| {
2747                *v = 10;
2748                Ok::<(), ()>(())
2749            })
2750            .unwrap()
2751        );
2752        assert!(
2753            !map.update_exact(&(10..25), |v| {
2754                *v = 10;
2755                Ok::<(), ()>(())
2756            })
2757            .unwrap()
2758        );
2759
2760        // 2. In-place update with no neighbors merging.
2761        assert!(
2762            map.update_exact(&(30..40), |v| {
2763                *v = 20;
2764                Ok::<(), ()>(())
2765            })
2766            .unwrap()
2767        );
2768        assert_eq!(map.get(35), Some((&(30..40), &20)));
2769
2770        // 3. Update triggering merge left.
2771        let _ = map.insert(20..30, 5);
2772        assert!(
2773            map.update_exact(&(20..30), |v| {
2774                *v = 1;
2775                Ok::<(), ()>(())
2776            })
2777            .unwrap()
2778        );
2779        assert_eq!(map.get(15), Some((&(10..30), &1)));
2780        assert_eq!(map.get(25), Some((&(10..30), &1)));
2781        assert_eq!(map.get(35), Some((&(30..40), &20)));
2782
2783        // 4. Update triggering merge right.
2784        assert!(
2785            map.update_exact(&(30..40), |v| {
2786                *v = 1;
2787                Ok::<(), ()>(())
2788            })
2789            .unwrap()
2790        );
2791        assert_eq!(map.get(15), Some((&(10..40), &1)));
2792        assert_eq!(map.get(25), Some((&(10..40), &1)));
2793        assert_eq!(map.get(35), Some((&(10..40), &1)));
2794
2795        // 5. Update triggering merge both left and right.
2796        let _ = map.insert(40..50, 5);
2797        assert!(
2798            map.update_exact(&(50..60), |v| {
2799                *v = 1;
2800                Ok::<(), ()>(())
2801            })
2802            .unwrap()
2803        );
2804        // Now we have 10..40 (value 1), 40..50 (value 5), 50..60 (value 1).
2805        assert_eq!(map.get(15), Some((&(10..40), &1)));
2806        assert_eq!(map.get(45), Some((&(40..50), &5)));
2807        assert_eq!(map.get(55), Some((&(50..60), &1)));
2808
2809        assert!(
2810            map.update_exact(&(40..50), |v| {
2811                *v = 1;
2812                Ok::<(), ()>(())
2813            })
2814            .unwrap()
2815        );
2816        // Now they should all be merged.
2817        assert_eq!(map.get(15), Some((&(10..60), &1)));
2818        assert_eq!(map.get(45), Some((&(10..60), &1)));
2819        assert_eq!(map.get(55), Some((&(10..60), &1)));
2820    }
2821}