Skip to main content

cranelift_bforest/
map.rs

1//! Forest of maps.
2
3use super::{Comparator, Forest, INNER_SIZE, Node, NodeData, NodePool, Path};
4use crate::packed_option::PackedOption;
5#[cfg(test)]
6use alloc::string::String;
7#[cfg(test)]
8use core::fmt;
9use core::{
10    marker::PhantomData,
11    mem,
12    ops::{Bound, RangeBounds},
13};
14use wasmtime_core::{alloc::PanicOnOom as _, error::OutOfMemory};
15
16/// Tag type defining forest types for a map.
17struct MapTypes<K, V>(PhantomData<(K, V)>);
18
19impl<K, V> Forest for MapTypes<K, V>
20where
21    K: Copy,
22    V: Copy,
23{
24    type Key = K;
25    type Value = V;
26    type LeafKeys = [K; INNER_SIZE - 1];
27    type LeafValues = [V; INNER_SIZE - 1];
28
29    fn splat_key(key: Self::Key) -> Self::LeafKeys {
30        [key; INNER_SIZE - 1]
31    }
32
33    fn splat_value(value: Self::Value) -> Self::LeafValues {
34        [value; INNER_SIZE - 1]
35    }
36}
37
38/// Memory pool for a forest of `Map` instances.
39pub struct MapForest<K, V>
40where
41    K: Copy,
42    V: Copy,
43{
44    nodes: NodePool<MapTypes<K, V>>,
45}
46
47impl<K, V> MapForest<K, V>
48where
49    K: Copy,
50    V: Copy,
51{
52    /// Create a new empty forest.
53    pub fn new() -> Self {
54        Self {
55            nodes: NodePool::new(),
56        }
57    }
58
59    /// Clear all maps in the forest.
60    ///
61    /// All `Map` instances belong to this forest are invalidated and should no longer be used.
62    pub fn clear(&mut self) {
63        self.nodes.clear();
64    }
65}
66
67/// B-tree mapping from `K` to `V`.
68///
69/// This is not a general-purpose replacement for `BTreeMap`. See the [module
70/// documentation](index.html) for more information about design tradeoffs.
71///
72/// Maps can be cloned, but that operation should only be used as part of cloning the whole forest
73/// they belong to. *Cloning a map does not allocate new memory for the clone*. It creates an alias
74/// of the same memory.
75#[derive(Clone)]
76pub struct Map<K, V>
77where
78    K: Copy,
79    V: Copy,
80{
81    root: PackedOption<Node>,
82    unused: PhantomData<(K, V)>,
83}
84
85impl<K, V> Map<K, V>
86where
87    K: Copy,
88    V: Copy,
89{
90    /// Make an empty map.
91    pub fn new() -> Self {
92        Self {
93            root: None.into(),
94            unused: PhantomData,
95        }
96    }
97
98    /// Is this an empty map?
99    pub fn is_empty(&self) -> bool {
100        self.root.is_none()
101    }
102
103    /// Get the value stored for `key`.
104    pub fn get<C: Comparator<K>>(&self, key: K, forest: &MapForest<K, V>, comp: &C) -> Option<V> {
105        self.root
106            .expand()
107            .and_then(|root| Path::default().find(key, root, &forest.nodes, comp))
108    }
109
110    /// Look up the value stored for `key`.
111    ///
112    /// If it exists, return the stored key-value pair.
113    ///
114    /// Otherwise, return the last key-value pair with a key that is less than or equal to `key`.
115    ///
116    /// If no stored keys are less than or equal to `key`, return `None`.
117    pub fn get_or_less<C: Comparator<K>>(
118        &self,
119        key: K,
120        forest: &MapForest<K, V>,
121        comp: &C,
122    ) -> Option<(K, V)> {
123        self.root.expand().and_then(|root| {
124            let mut path = Path::default();
125            match path.find(key, root, &forest.nodes, comp) {
126                Some(v) => Some((key, v)),
127                None => path.prev(root, &forest.nodes),
128            }
129        })
130    }
131
132    /// Insert `key, value` into the map and return the old value stored for `key`, if any.
133    pub fn insert<C: Comparator<K>>(
134        &mut self,
135        key: K,
136        value: V,
137        forest: &mut MapForest<K, V>,
138        comp: &C,
139    ) -> Option<V> {
140        self.cursor_mut(forest, comp).insert(key, value)
141    }
142
143    /// Like `insert` but returns an error on allocation failure.
144    pub fn try_insert<C: Comparator<K>>(
145        &mut self,
146        key: K,
147        value: V,
148        forest: &mut MapForest<K, V>,
149        comp: &C,
150    ) -> Result<Option<V>, OutOfMemory> {
151        self.cursor_mut(forest, comp).try_insert(key, value)
152    }
153
154    /// Remove `key` from the map and return the removed value for `key`, if any.
155    pub fn remove<C: Comparator<K>>(
156        &mut self,
157        key: K,
158        forest: &mut MapForest<K, V>,
159        comp: &C,
160    ) -> Option<V> {
161        let mut c = self.cursor_mut(forest, comp);
162        if c.goto(key).is_some() {
163            c.remove()
164        } else {
165            None
166        }
167    }
168
169    /// Remove all entries.
170    pub fn clear(&mut self, forest: &mut MapForest<K, V>) {
171        if let Some(root) = self.root.take() {
172            forest.nodes.free_tree(root);
173        }
174    }
175
176    /// Retains only the elements specified by the predicate.
177    ///
178    /// Remove all key-value pairs where the predicate returns false.
179    ///
180    /// The predicate is allowed to update the values stored in the map.
181    pub fn retain<F>(&mut self, forest: &mut MapForest<K, V>, mut predicate: F)
182    where
183        F: FnMut(K, &mut V) -> bool,
184    {
185        let mut path = Path::default();
186        if let Some(root) = self.root.expand() {
187            path.first(root, &forest.nodes);
188        }
189        while let Some((node, entry)) = path.leaf_pos() {
190            let keep = {
191                let (ks, vs) = forest.nodes[node].unwrap_leaf_mut();
192                predicate(ks[entry], &mut vs[entry])
193            };
194            if keep {
195                path.next(&forest.nodes);
196            } else {
197                self.root = path.remove(&mut forest.nodes).into();
198            }
199        }
200    }
201
202    /// Create an immutable cursor for navigating this map.
203    ///
204    /// The cursor is initially positioned off the end of the map.
205    pub fn cursor<'a, C: Comparator<K>>(
206        &'a self,
207        forest: &'a MapForest<K, V>,
208        comp: &'a C,
209    ) -> MapCursor<'a, K, V, C> {
210        MapCursor::new(self, forest, comp)
211    }
212
213    /// Create a mutable cursor for navigating this map.
214    ///
215    /// The cursor is initially positioned off the end of the map.
216    pub fn cursor_mut<'a, C: Comparator<K>>(
217        &'a mut self,
218        forest: &'a mut MapForest<K, V>,
219        comp: &'a C,
220    ) -> MapCursorMut<'a, K, V, C> {
221        MapCursorMut::new(self, forest, comp)
222    }
223
224    /// Create an iterator traversing this map. The iterator type is `(K, V)`.
225    pub fn iter<'a>(&'a self, forest: &'a MapForest<K, V>) -> MapIter<'a, K, V> {
226        MapIter {
227            root: self.root,
228            pool: &forest.nodes,
229            path: Path::default(),
230        }
231    }
232
233    /// Consume this map and its forest, yielding `(K, V)` pairs from the map.
234    pub fn into_iter(self, forest: MapForest<K, V>) -> MapIntoIter<K, V> {
235        MapIntoIter {
236            root: self.root,
237            pool: forest.nodes,
238            path: Path::default(),
239        }
240    }
241
242    /// Iterate over the enties within the given range.
243    pub fn range<'a, R, C>(
244        &'a self,
245        range: R,
246        forest: &'a MapForest<K, V>,
247        comp: &'a C,
248    ) -> MapRange<'a, K, V, R, C>
249    where
250        R: RangeBounds<K>,
251        C: Comparator<K>,
252    {
253        MapRange {
254            cursor: self.cursor(forest, comp),
255            range,
256            started: false,
257        }
258    }
259}
260
261impl<K, V> Default for Map<K, V>
262where
263    K: Copy,
264    V: Copy,
265{
266    fn default() -> Self {
267        Self::new()
268    }
269}
270
271#[cfg(test)]
272impl<K, V> Map<K, V>
273where
274    K: Copy + fmt::Display,
275    V: Copy,
276{
277    /// Verify consistency.
278    fn verify<C: Comparator<K>>(&self, forest: &MapForest<K, V>, comp: &C)
279    where
280        NodeData<MapTypes<K, V>>: fmt::Display,
281    {
282        if let Some(root) = self.root.expand() {
283            forest.nodes.verify_tree(root, comp);
284        }
285    }
286
287    /// Get a text version of the path to `key`.
288    fn tpath<C: Comparator<K>>(&self, key: K, forest: &MapForest<K, V>, comp: &C) -> String {
289        use alloc::string::ToString;
290        match self.root.expand() {
291            None => "map(empty)".to_string(),
292            Some(root) => {
293                let mut path = Path::default();
294                path.find(key, root, &forest.nodes, comp);
295                path.to_string()
296            }
297        }
298    }
299}
300
301struct MapCursorRaw<K, V>
302where
303    K: Copy,
304    V: Copy,
305{
306    path: Path<MapTypes<K, V>>,
307}
308
309impl<K, V> MapCursorRaw<K, V>
310where
311    K: Copy,
312    V: Copy,
313{
314    fn new() -> Self {
315        Self {
316            path: Path::default(),
317        }
318    }
319
320    fn is_empty(&self, root: &PackedOption<Node>) -> bool {
321        root.is_none()
322    }
323
324    fn next(&mut self, pool: &NodePool<MapTypes<K, V>>) -> Option<(K, V)> {
325        self.path.next(pool)
326    }
327
328    fn prev(
329        &mut self,
330        root: &PackedOption<Node>,
331        pool: &NodePool<MapTypes<K, V>>,
332    ) -> Option<(K, V)> {
333        root.expand().and_then(|root| self.path.prev(root, pool))
334    }
335
336    fn key(&self, pool: &NodePool<MapTypes<K, V>>) -> Option<K> {
337        self.path
338            .leaf_pos()
339            .and_then(|(node, entry)| pool[node].unwrap_leaf().0.get(entry).cloned())
340    }
341
342    fn value(&self, pool: &NodePool<MapTypes<K, V>>) -> Option<V> {
343        self.path
344            .leaf_pos()
345            .and_then(|(node, entry)| pool[node].unwrap_leaf().1.get(entry).cloned())
346    }
347
348    fn value_mut<'a>(&self, pool: &'a mut NodePool<MapTypes<K, V>>) -> Option<&'a mut V> {
349        self.path
350            .leaf_pos()
351            .and_then(move |(node, entry)| pool[node].unwrap_leaf_mut().1.get_mut(entry))
352    }
353
354    fn goto(
355        &mut self,
356        root: &PackedOption<Node>,
357        pool: &NodePool<MapTypes<K, V>>,
358        elem: K,
359        comp: &impl Comparator<K>,
360    ) -> Option<V> {
361        root.expand().and_then(|root| {
362            let v = self.path.find(elem, root, pool, comp);
363            if v.is_none() {
364                self.path.normalize(pool);
365            }
366            v
367        })
368    }
369
370    fn goto_first(
371        &mut self,
372        root: &PackedOption<Node>,
373        pool: &NodePool<MapTypes<K, V>>,
374    ) -> Option<V> {
375        root.map(|root| self.path.first(root, pool).1)
376    }
377
378    fn goto_end(&mut self) {
379        self.path = Path::default();
380    }
381
382    fn insert(
383        &mut self,
384        root: &mut PackedOption<Node>,
385        pool: &mut NodePool<MapTypes<K, V>>,
386        key: K,
387        value: V,
388        comp: &impl Comparator<K>,
389    ) -> Option<V> {
390        self.try_insert(root, pool, key, value, comp).panic_on_oom()
391    }
392
393    fn try_insert(
394        &mut self,
395        root: &mut PackedOption<Node>,
396        pool: &mut NodePool<MapTypes<K, V>>,
397        key: K,
398        value: V,
399        comp: &impl Comparator<K>,
400    ) -> Result<Option<V>, OutOfMemory> {
401        match root.expand() {
402            None => {
403                let node = pool.alloc_node(NodeData::leaf(key, value))?;
404                *root = node.into();
405                self.path.set_root_node(node);
406                Ok(None)
407            }
408            Some(r) => {
409                // TODO: Optimize the case where `self.path` is already at the correct insert pos.
410                let old = self.path.find(key, r, pool, comp);
411                if old.is_some() {
412                    *self.path.value_mut(pool) = value;
413                } else {
414                    *root = self.path.insert(key, value, pool)?.into();
415                }
416                Ok(old)
417            }
418        }
419    }
420
421    fn remove(
422        &mut self,
423        root: &mut PackedOption<Node>,
424        pool: &mut NodePool<MapTypes<K, V>>,
425    ) -> Option<V> {
426        let value = self.value(pool);
427        if value.is_some() {
428            *root = self.path.remove(pool).into();
429        }
430        value
431    }
432}
433
434/// A position in a `Map` used to navigate and modify the ordered map.
435///
436/// A cursor always points at a key-value pair in the map, or "off the end" which is a position
437/// after the last entry in the map.
438pub struct MapCursor<'a, K, V, C>
439where
440    K: 'a + Copy,
441    V: 'a + Copy,
442    C: 'a + Comparator<K>,
443{
444    root: &'a PackedOption<Node>,
445    pool: &'a NodePool<MapTypes<K, V>>,
446    comp: &'a C,
447    raw: MapCursorRaw<K, V>,
448}
449
450impl<'a, K, V, C> MapCursor<'a, K, V, C>
451where
452    K: Copy,
453    V: Copy,
454    C: Comparator<K>,
455{
456    /// Create a cursor with a default (off-the-end) location.
457    fn new(container: &'a Map<K, V>, forest: &'a MapForest<K, V>, comp: &'a C) -> Self {
458        Self {
459            root: &container.root,
460            pool: &forest.nodes,
461            comp,
462            raw: MapCursorRaw::new(),
463        }
464    }
465
466    /// Is this cursor pointing to an empty map?
467    pub fn is_empty(&self) -> bool {
468        self.raw.is_empty(self.root)
469    }
470
471    /// Move cursor to the next key-value pair and return it.
472    ///
473    /// If the cursor reaches the end, return `None` and leave the cursor at the off-the-end
474    /// position.
475    pub fn next(&mut self) -> Option<(K, V)> {
476        self.raw.next(self.pool)
477    }
478
479    /// Move cursor to the previous key-value pair and return it.
480    ///
481    /// If the cursor is already pointing at the first entry, leave it there and return `None`.
482    pub fn prev(&mut self) -> Option<(K, V)> {
483        self.raw.prev(self.root, self.pool)
484    }
485
486    /// Get the current key, or `None` if the cursor is at the end.
487    pub fn key(&self) -> Option<K> {
488        self.raw.key(self.pool)
489    }
490
491    /// Get the current value, or `None` if the cursor is at the end.
492    pub fn value(&self) -> Option<V> {
493        self.raw.value(self.pool)
494    }
495
496    /// Move this cursor to `key`.
497    ///
498    /// If `key` is in the map, place the cursor at `key` and return the corresponding value.
499    ///
500    /// If `key` is not in the set, place the cursor at the next larger element (or the end) and
501    /// return `None`.
502    pub fn goto(&mut self, elem: K) -> Option<V> {
503        self.raw.goto(self.root, self.pool, elem, self.comp)
504    }
505
506    /// Move this cursor to the first element.
507    pub fn goto_first(&mut self) -> Option<V> {
508        self.raw.goto_first(self.root, self.pool)
509    }
510
511    /// Move the cursor to the off-the-end location.
512    pub fn goto_end(&mut self) {
513        self.raw.goto_end();
514    }
515}
516
517/// A position in a `Map` used to navigate and modify the ordered map.
518///
519/// A cursor always points at a key-value pair in the map, or "off the end" which is a position
520/// after the last entry in the map.
521pub struct MapCursorMut<'a, K, V, C>
522where
523    K: 'a + Copy,
524    V: 'a + Copy,
525    C: 'a + Comparator<K>,
526{
527    root: &'a mut PackedOption<Node>,
528    pool: &'a mut NodePool<MapTypes<K, V>>,
529    comp: &'a C,
530    raw: MapCursorRaw<K, V>,
531}
532
533impl<'a, K, V, C> MapCursorMut<'a, K, V, C>
534where
535    K: Copy,
536    V: Copy,
537    C: Comparator<K>,
538{
539    /// Create a cursor with a default (off-the-end) location.
540    fn new(container: &'a mut Map<K, V>, forest: &'a mut MapForest<K, V>, comp: &'a C) -> Self {
541        Self {
542            root: &mut container.root,
543            pool: &mut forest.nodes,
544            comp,
545            raw: MapCursorRaw::new(),
546        }
547    }
548
549    /// Is this cursor pointing to an empty map?
550    pub fn is_empty(&self) -> bool {
551        self.raw.is_empty(self.root)
552    }
553
554    /// Move cursor to the next key-value pair and return it.
555    ///
556    /// If the cursor reaches the end, return `None` and leave the cursor at the off-the-end
557    /// position.
558    pub fn next(&mut self) -> Option<(K, V)> {
559        self.raw.next(self.pool)
560    }
561
562    /// Move cursor to the previous key-value pair and return it.
563    ///
564    /// If the cursor is already pointing at the first entry, leave it there and return `None`.
565    pub fn prev(&mut self) -> Option<(K, V)> {
566        self.raw.prev(self.root, self.pool)
567    }
568
569    /// Get the current key, or `None` if the cursor is at the end.
570    pub fn key(&self) -> Option<K> {
571        self.raw.key(self.pool)
572    }
573
574    /// Get the current value, or `None` if the cursor is at the end.
575    pub fn value(&self) -> Option<V> {
576        self.raw.value(self.pool)
577    }
578
579    /// Get a mutable reference to the current value, or `None` if the cursor is at the end.
580    pub fn value_mut(&mut self) -> Option<&mut V> {
581        self.raw.value_mut(self.pool)
582    }
583
584    /// Move this cursor to `key`.
585    ///
586    /// If `key` is in the map, place the cursor at `key` and return the corresponding value.
587    ///
588    /// If `key` is not in the set, place the cursor at the next larger element (or the end) and
589    /// return `None`.
590    pub fn goto(&mut self, elem: K) -> Option<V> {
591        self.raw.goto(self.root, self.pool, elem, self.comp)
592    }
593
594    /// Move this cursor to the first element.
595    pub fn goto_first(&mut self) -> Option<V> {
596        self.raw.goto_first(self.root, self.pool)
597    }
598
599    /// Insert `(key, value))` into the map and leave the cursor at the inserted pair.
600    ///
601    /// If the map did not contain `key`, return `None`.
602    ///
603    /// If `key` is already present, replace the existing with `value` and return the old value.
604    pub fn insert(&mut self, key: K, value: V) -> Option<V> {
605        self.raw.insert(self.root, self.pool, key, value, self.comp)
606    }
607
608    /// Like `insert` but returns an error on allocation failure.
609    pub fn try_insert(&mut self, key: K, value: V) -> Result<Option<V>, OutOfMemory> {
610        self.raw
611            .try_insert(self.root, self.pool, key, value, self.comp)
612    }
613
614    /// Remove the current entry (if any) and return the mapped value.
615    /// This advances the cursor to the next entry after the removed one.
616    pub fn remove(&mut self) -> Option<V> {
617        self.raw.remove(self.root, self.pool)
618    }
619}
620
621/// An iterator visiting the key-value pairs of a `Map`.
622pub struct MapIter<'a, K, V>
623where
624    K: 'a + Copy,
625    V: 'a + Copy,
626{
627    root: PackedOption<Node>,
628    pool: &'a NodePool<MapTypes<K, V>>,
629    path: Path<MapTypes<K, V>>,
630}
631
632impl<'a, K, V> Iterator for MapIter<'a, K, V>
633where
634    K: 'a + Copy,
635    V: 'a + Copy,
636{
637    type Item = (K, V);
638
639    fn next(&mut self) -> Option<Self::Item> {
640        // We use `self.root` to indicate if we need to go to the first element. Reset to `None`
641        // once we've returned the first element. This also works for an empty tree since the
642        // `path.next()` call returns `None` when the path is empty. This also fuses the iterator.
643        match self.root.take() {
644            Some(root) => Some(self.path.first(root, self.pool)),
645            None => self.path.next(self.pool),
646        }
647    }
648}
649
650/// A consuming iterator of a `Map`, yielding its key-value pairs.
651pub struct MapIntoIter<K, V>
652where
653    K: Copy,
654    V: Copy,
655{
656    root: PackedOption<Node>,
657    pool: NodePool<MapTypes<K, V>>,
658    path: Path<MapTypes<K, V>>,
659}
660
661impl<K, V> Iterator for MapIntoIter<K, V>
662where
663    K: Copy,
664    V: Copy,
665{
666    type Item = (K, V);
667
668    fn next(&mut self) -> Option<Self::Item> {
669        // We use `self.root` to indicate if we need to go to the first element. Reset to `None`
670        // once we've returned the first element. This also works for an empty tree since the
671        // `path.next()` call returns `None` when the path is empty. This also fuses the iterator.
672        match self.root.take() {
673            Some(root) => Some(self.path.first(root, &self.pool)),
674            None => self.path.next(&self.pool),
675        }
676    }
677}
678
679/// An immutable iterator over a range of values, returned by `Map::range`.
680pub struct MapRange<'a, K, V, R, C>
681where
682    K: Copy,
683    V: Copy,
684    R: RangeBounds<K>,
685    C: Comparator<K>,
686{
687    cursor: MapCursor<'a, K, V, C>,
688    range: R,
689    started: bool,
690}
691
692impl<'a, K, V, R, C> Iterator for MapRange<'a, K, V, R, C>
693where
694    K: Copy,
695    V: Copy,
696    R: RangeBounds<K>,
697    C: Comparator<K>,
698{
699    type Item = (K, V);
700
701    fn next(&mut self) -> Option<Self::Item> {
702        let started = mem::replace(&mut self.started, true);
703
704        let key_val = (|| {
705            if started {
706                self.cursor.next()
707            } else {
708                match self.range.start_bound() {
709                    Bound::Included(k) => {
710                        self.cursor.goto(*k);
711                        Some((self.cursor.key()?, self.cursor.value()?))
712                    }
713                    Bound::Excluded(k) => {
714                        self.cursor.goto(*k);
715                        if self
716                            .cursor
717                            .key()
718                            .is_some_and(|key| self.cursor.comp.cmp(*k, key).is_eq())
719                        {
720                            self.cursor.next()
721                        } else {
722                            Some((self.cursor.key()?, self.cursor.value()?))
723                        }
724                    }
725                    Bound::Unbounded => {
726                        let val = self.cursor.goto_first()?;
727                        Some((self.cursor.key()?, val))
728                    }
729                }
730            }
731        })();
732
733        match key_val {
734            Some((key, val)) if self.is_in_bounds(key) => Some((key, val)),
735            _ => {
736                self.cursor.goto_end();
737                None
738            }
739        }
740    }
741}
742
743impl<'a, K, V, R, C> MapRange<'a, K, V, R, C>
744where
745    K: Copy,
746    V: Copy,
747    R: RangeBounds<K>,
748    C: Comparator<K>,
749{
750    fn is_in_bounds(&self, key: K) -> bool {
751        debug_assert!(self.is_in_start_bound(key));
752        self.is_in_end_bound(key)
753    }
754
755    fn is_in_start_bound(&self, key: K) -> bool {
756        match self.range.start_bound() {
757            Bound::Included(k) => self.cursor.comp.cmp(key, *k).is_ge(),
758            Bound::Excluded(k) => self.cursor.comp.cmp(key, *k).is_gt(),
759            Bound::Unbounded => true,
760        }
761    }
762
763    fn is_in_end_bound(&self, key: K) -> bool {
764        match self.range.end_bound() {
765            Bound::Included(k) => self.cursor.comp.cmp(*k, key).is_ge(),
766            Bound::Excluded(k) => self.cursor.comp.cmp(*k, key).is_gt(),
767            Bound::Unbounded => true,
768        }
769    }
770}
771
772#[cfg(test)]
773impl<'a, K, V, C> MapCursorMut<'a, K, V, C>
774where
775    K: Copy + fmt::Display,
776    V: Copy + fmt::Display,
777    C: Comparator<K>,
778{
779    fn verify(&self) {
780        self.raw.path.verify(self.pool);
781        self.root.map(|root| self.pool.verify_tree(root, self.comp));
782    }
783
784    /// Get a text version of the path to the current position.
785    fn tpath(&self) -> String {
786        use alloc::string::ToString;
787        self.raw.path.to_string()
788    }
789}
790
791#[cfg(test)]
792mod tests {
793    use super::*;
794    use alloc::{vec, vec::Vec};
795    use core::mem;
796
797    #[test]
798    fn node_size() {
799        // check that nodes are cache line sized when keys and values are 32 bits.
800        type F = MapTypes<u32, u32>;
801        assert_eq!(mem::size_of::<NodeData<F>>(), 64);
802    }
803
804    #[test]
805    fn empty() {
806        let mut f = MapForest::<u32, f32>::new();
807        f.clear();
808
809        let mut m = Map::<u32, f32>::new();
810        assert!(m.is_empty());
811        m.clear(&mut f);
812
813        assert_eq!(m.get(7, &f, &()), None);
814        assert_eq!(m.iter(&f).next(), None);
815        assert_eq!(m.get_or_less(7, &f, &()), None);
816        m.retain(&mut f, |_, _| unreachable!());
817
818        let mut c = m.cursor_mut(&mut f, &());
819        assert!(c.is_empty());
820        assert_eq!(c.key(), None);
821        assert_eq!(c.value(), None);
822        assert_eq!(c.next(), None);
823        assert_eq!(c.prev(), None);
824        c.verify();
825        assert_eq!(c.tpath(), "<empty path>");
826        assert_eq!(c.goto_first(), None);
827        assert_eq!(c.tpath(), "<empty path>");
828    }
829
830    #[test]
831    fn inserting() {
832        let f = &mut MapForest::<u32, f32>::new();
833        let mut m = Map::<u32, f32>::new();
834
835        // The first seven values stay in a single leaf node.
836        assert_eq!(m.insert(50, 5.0, f, &()), None);
837        assert_eq!(m.insert(50, 5.5, f, &()), Some(5.0));
838        assert_eq!(m.insert(20, 2.0, f, &()), None);
839        assert_eq!(m.insert(80, 8.0, f, &()), None);
840        assert_eq!(m.insert(40, 4.0, f, &()), None);
841        assert_eq!(m.insert(60, 6.0, f, &()), None);
842        assert_eq!(m.insert(90, 9.0, f, &()), None);
843        assert_eq!(m.insert(200, 20.0, f, &()), None);
844
845        m.verify(f, &());
846
847        assert_eq!(
848            m.iter(f).collect::<Vec<_>>(),
849            [
850                (20, 2.0),
851                (40, 4.0),
852                (50, 5.5),
853                (60, 6.0),
854                (80, 8.0),
855                (90, 9.0),
856                (200, 20.0),
857            ]
858        );
859
860        assert_eq!(m.get(0, f, &()), None);
861        assert_eq!(m.get(20, f, &()), Some(2.0));
862        assert_eq!(m.get(30, f, &()), None);
863        assert_eq!(m.get(40, f, &()), Some(4.0));
864        assert_eq!(m.get(50, f, &()), Some(5.5));
865        assert_eq!(m.get(60, f, &()), Some(6.0));
866        assert_eq!(m.get(70, f, &()), None);
867        assert_eq!(m.get(80, f, &()), Some(8.0));
868        assert_eq!(m.get(100, f, &()), None);
869
870        assert_eq!(m.get_or_less(0, f, &()), None);
871        assert_eq!(m.get_or_less(20, f, &()), Some((20, 2.0)));
872        assert_eq!(m.get_or_less(30, f, &()), Some((20, 2.0)));
873        assert_eq!(m.get_or_less(40, f, &()), Some((40, 4.0)));
874        assert_eq!(m.get_or_less(200, f, &()), Some((200, 20.0)));
875        assert_eq!(m.get_or_less(201, f, &()), Some((200, 20.0)));
876
877        {
878            let mut c = m.cursor_mut(f, &());
879            assert_eq!(c.prev(), Some((200, 20.0)));
880            assert_eq!(c.prev(), Some((90, 9.0)));
881            assert_eq!(c.prev(), Some((80, 8.0)));
882            assert_eq!(c.prev(), Some((60, 6.0)));
883            assert_eq!(c.prev(), Some((50, 5.5)));
884            assert_eq!(c.prev(), Some((40, 4.0)));
885            assert_eq!(c.prev(), Some((20, 2.0)));
886            assert_eq!(c.prev(), None);
887        }
888
889        // Test some removals where the node stays healthy.
890        assert_eq!(m.tpath(50, f, &()), "node0[2]");
891        assert_eq!(m.tpath(80, f, &()), "node0[4]");
892        assert_eq!(m.tpath(200, f, &()), "node0[6]");
893
894        assert_eq!(m.remove(80, f, &()), Some(8.0));
895        assert_eq!(m.tpath(50, f, &()), "node0[2]");
896        assert_eq!(m.tpath(80, f, &()), "node0[4]");
897        assert_eq!(m.tpath(200, f, &()), "node0[5]");
898        assert_eq!(m.remove(80, f, &()), None);
899        m.verify(f, &());
900
901        assert_eq!(m.remove(20, f, &()), Some(2.0));
902        assert_eq!(m.tpath(50, f, &()), "node0[1]");
903        assert_eq!(m.tpath(80, f, &()), "node0[3]");
904        assert_eq!(m.tpath(200, f, &()), "node0[4]");
905        assert_eq!(m.remove(20, f, &()), None);
906        m.verify(f, &());
907
908        // [ 40 50 60 90 200 ]
909
910        {
911            let mut c = m.cursor_mut(f, &());
912            assert_eq!(c.goto_first(), Some(4.0));
913            assert_eq!(c.key(), Some(40));
914            assert_eq!(c.value(), Some(4.0));
915            assert_eq!(c.next(), Some((50, 5.5)));
916            assert_eq!(c.next(), Some((60, 6.0)));
917            assert_eq!(c.next(), Some((90, 9.0)));
918            assert_eq!(c.next(), Some((200, 20.0)));
919            c.verify();
920            assert_eq!(c.next(), None);
921            c.verify();
922        }
923
924        // Removals from the root leaf node beyond underflow.
925        assert_eq!(m.remove(200, f, &()), Some(20.0));
926        assert_eq!(m.remove(40, f, &()), Some(4.0));
927        assert_eq!(m.remove(60, f, &()), Some(6.0));
928        m.verify(f, &());
929        assert_eq!(m.remove(50, f, &()), Some(5.5));
930        m.verify(f, &());
931        assert_eq!(m.remove(90, f, &()), Some(9.0));
932        m.verify(f, &());
933        assert!(m.is_empty());
934    }
935
936    #[test]
937    fn split_level0_leaf() {
938        // Various ways of splitting a full leaf node at level 0.
939        let f = &mut MapForest::<u32, f32>::new();
940
941        fn full_leaf(f: &mut MapForest<u32, f32>) -> Map<u32, f32> {
942            let mut m = Map::new();
943            for n in 1..8 {
944                m.insert(n * 10, n as f32 * 1.1, f, &());
945            }
946            m
947        }
948
949        // Insert at front of leaf.
950        let mut m = full_leaf(f);
951        m.insert(5, 4.2, f, &());
952        m.verify(f, &());
953        assert_eq!(m.get(5, f, &()), Some(4.2));
954
955        // Retain even entries, with altered values.
956        m.retain(f, |k, v| {
957            *v = (k / 10) as f32;
958            (k % 20) == 0
959        });
960        assert_eq!(
961            m.iter(f).collect::<Vec<_>>(),
962            [(20, 2.0), (40, 4.0), (60, 6.0)]
963        );
964
965        // Insert at back of leaf.
966        let mut m = full_leaf(f);
967        m.insert(80, 4.2, f, &());
968        m.verify(f, &());
969        assert_eq!(m.get(80, f, &()), Some(4.2));
970
971        // Insert before middle (40).
972        let mut m = full_leaf(f);
973        m.insert(35, 4.2, f, &());
974        m.verify(f, &());
975        assert_eq!(m.get(35, f, &()), Some(4.2));
976
977        // Insert after middle (40).
978        let mut m = full_leaf(f);
979        m.insert(45, 4.2, f, &());
980        m.verify(f, &());
981        assert_eq!(m.get(45, f, &()), Some(4.2));
982
983        m.clear(f);
984        assert!(m.is_empty());
985    }
986
987    #[test]
988    fn split_level1_leaf() {
989        // Various ways of splitting a full leaf node at level 1.
990        let f = &mut MapForest::<u32, f32>::new();
991
992        // Return a map whose root node is a full inner node, and the leaf nodes are all full
993        // containing:
994        //
995        // 110, 120, ..., 170
996        // 210, 220, ..., 270
997        // ...
998        // 810, 820, ..., 870
999        fn full(f: &mut MapForest<u32, f32>) -> Map<u32, f32> {
1000            let mut m = Map::new();
1001
1002            // Start by inserting elements in order.
1003            // This should leave 8 leaf nodes with 4 elements in each.
1004            for row in 1..9 {
1005                for col in 1..5 {
1006                    m.insert(row * 100 + col * 10, row as f32 + col as f32 * 0.1, f, &());
1007                }
1008            }
1009
1010            // Then top up the leaf nodes without splitting them.
1011            for row in 1..9 {
1012                for col in 5..8 {
1013                    m.insert(row * 100 + col * 10, row as f32 + col as f32 * 0.1, f, &());
1014                }
1015            }
1016
1017            m
1018        }
1019
1020        let mut m = full(f);
1021        // Verify geometry. Get get node2 as the root and leaves node0, 1, 3, ...
1022        m.verify(f, &());
1023        assert_eq!(m.tpath(110, f, &()), "node2[0]--node0[0]");
1024        assert_eq!(m.tpath(140, f, &()), "node2[0]--node0[3]");
1025        assert_eq!(m.tpath(210, f, &()), "node2[1]--node1[0]");
1026        assert_eq!(m.tpath(270, f, &()), "node2[1]--node1[6]");
1027        assert_eq!(m.tpath(310, f, &()), "node2[2]--node3[0]");
1028        assert_eq!(m.tpath(810, f, &()), "node2[7]--node8[0]");
1029        assert_eq!(m.tpath(870, f, &()), "node2[7]--node8[6]");
1030
1031        {
1032            let mut c = m.cursor_mut(f, &());
1033            assert_eq!(c.goto_first(), Some(1.1));
1034            assert_eq!(c.key(), Some(110));
1035        }
1036
1037        // Front of first leaf.
1038        m.insert(0, 4.2, f, &());
1039        m.verify(f, &());
1040        assert_eq!(m.get(0, f, &()), Some(4.2));
1041
1042        // First leaf split 4-4 after appending to LHS.
1043        f.clear();
1044        m = full(f);
1045        m.insert(135, 4.2, f, &());
1046        m.verify(f, &());
1047        assert_eq!(m.get(135, f, &()), Some(4.2));
1048
1049        // First leaf split 4-4 after prepending to RHS.
1050        f.clear();
1051        m = full(f);
1052        m.insert(145, 4.2, f, &());
1053        m.verify(f, &());
1054        assert_eq!(m.get(145, f, &()), Some(4.2));
1055
1056        // First leaf split 4-4 after appending to RHS.
1057        f.clear();
1058        m = full(f);
1059        m.insert(175, 4.2, f, &());
1060        m.verify(f, &());
1061        assert_eq!(m.get(175, f, &()), Some(4.2));
1062
1063        // Left-middle leaf split, ins LHS.
1064        f.clear();
1065        m = full(f);
1066        m.insert(435, 4.2, f, &());
1067        m.verify(f, &());
1068        assert_eq!(m.get(435, f, &()), Some(4.2));
1069
1070        // Left-middle leaf split, ins RHS.
1071        f.clear();
1072        m = full(f);
1073        m.insert(445, 4.2, f, &());
1074        m.verify(f, &());
1075        assert_eq!(m.get(445, f, &()), Some(4.2));
1076
1077        // Right-middle leaf split, ins LHS.
1078        f.clear();
1079        m = full(f);
1080        m.insert(535, 4.2, f, &());
1081        m.verify(f, &());
1082        assert_eq!(m.get(535, f, &()), Some(4.2));
1083
1084        // Right-middle leaf split, ins RHS.
1085        f.clear();
1086        m = full(f);
1087        m.insert(545, 4.2, f, &());
1088        m.verify(f, &());
1089        assert_eq!(m.get(545, f, &()), Some(4.2));
1090
1091        // Last leaf split, ins LHS.
1092        f.clear();
1093        m = full(f);
1094        m.insert(835, 4.2, f, &());
1095        m.verify(f, &());
1096        assert_eq!(m.get(835, f, &()), Some(4.2));
1097
1098        // Last leaf split, ins RHS.
1099        f.clear();
1100        m = full(f);
1101        m.insert(845, 4.2, f, &());
1102        m.verify(f, &());
1103        assert_eq!(m.get(845, f, &()), Some(4.2));
1104
1105        // Front of last leaf.
1106        f.clear();
1107        m = full(f);
1108        m.insert(805, 4.2, f, &());
1109        m.verify(f, &());
1110        assert_eq!(m.get(805, f, &()), Some(4.2));
1111
1112        m.clear(f);
1113        m.verify(f, &());
1114    }
1115
1116    // Make a tree with two barely healthy leaf nodes:
1117    // [ 10 20 30 40 ] [ 50 60 70 80 ]
1118    fn two_leaf(f: &mut MapForest<u32, f32>) -> Map<u32, f32> {
1119        f.clear();
1120        let mut m = Map::new();
1121        for n in 1..9 {
1122            m.insert(n * 10, n as f32, f, &());
1123        }
1124        m
1125    }
1126
1127    #[test]
1128    fn remove_level1() {
1129        let f = &mut MapForest::<u32, f32>::new();
1130        let mut m = two_leaf(f);
1131
1132        // Verify geometry.
1133        m.verify(f, &());
1134        assert_eq!(m.tpath(10, f, &()), "node2[0]--node0[0]");
1135        assert_eq!(m.tpath(40, f, &()), "node2[0]--node0[3]");
1136        assert_eq!(m.tpath(49, f, &()), "node2[0]--node0[4]");
1137        assert_eq!(m.tpath(50, f, &()), "node2[1]--node1[0]");
1138        assert_eq!(m.tpath(80, f, &()), "node2[1]--node1[3]");
1139
1140        // Remove the front entry from a node that stays healthy.
1141        assert_eq!(m.insert(55, 5.5, f, &()), None);
1142        assert_eq!(m.remove(50, f, &()), Some(5.0));
1143        m.verify(f, &());
1144        assert_eq!(m.tpath(49, f, &()), "node2[0]--node0[4]");
1145        assert_eq!(m.tpath(50, f, &()), "node2[0]--node0[4]");
1146        assert_eq!(m.tpath(55, f, &()), "node2[1]--node1[0]");
1147
1148        // Remove the front entry from the first leaf node: No critical key to update.
1149        assert_eq!(m.insert(15, 1.5, f, &()), None);
1150        assert_eq!(m.remove(10, f, &()), Some(1.0));
1151        m.verify(f, &());
1152
1153        // [ 15 20 30 40 ] [ 55 60 70 80 ]
1154
1155        // Remove the front entry from a right-most node that underflows.
1156        // No rebalancing for the right-most node. Still need critical key update.
1157        assert_eq!(m.remove(55, f, &()), Some(5.5));
1158        m.verify(f, &());
1159        assert_eq!(m.tpath(55, f, &()), "node2[0]--node0[4]");
1160        assert_eq!(m.tpath(60, f, &()), "node2[1]--node1[0]");
1161
1162        // [ 15 20 30 40 ] [ 60 70 80 ]
1163
1164        // Replenish the right leaf.
1165        assert_eq!(m.insert(90, 9.0, f, &()), None);
1166        assert_eq!(m.insert(100, 10.0, f, &()), None);
1167        m.verify(f, &());
1168        assert_eq!(m.tpath(55, f, &()), "node2[0]--node0[4]");
1169        assert_eq!(m.tpath(60, f, &()), "node2[1]--node1[0]");
1170
1171        // [ 15 20 30 40 ] [ 60 70 80 90 100 ]
1172
1173        // Removing one entry from the left leaf should trigger a rebalancing from the right
1174        // sibling.
1175        assert_eq!(m.remove(20, f, &()), Some(2.0));
1176        m.verify(f, &());
1177
1178        // [ 15 30 40 60 ] [ 70 80 90 100 ]
1179        // Check that the critical key was updated correctly.
1180        assert_eq!(m.tpath(50, f, &()), "node2[0]--node0[3]");
1181        assert_eq!(m.tpath(60, f, &()), "node2[0]--node0[3]");
1182        assert_eq!(m.tpath(70, f, &()), "node2[1]--node1[0]");
1183
1184        // Remove front entry from the left-most leaf node, underflowing.
1185        // This should cause two leaf nodes to be merged and the root node to go away.
1186        assert_eq!(m.remove(15, f, &()), Some(1.5));
1187        m.verify(f, &());
1188    }
1189
1190    #[test]
1191    fn remove_level1_rightmost() {
1192        let f = &mut MapForest::<u32, f32>::new();
1193        let mut m = two_leaf(f);
1194
1195        // [ 10 20 30 40 ] [ 50 60 70 80 ]
1196
1197        // Remove entries from the right leaf. This doesn't trigger a rebalancing.
1198        assert_eq!(m.remove(60, f, &()), Some(6.0));
1199        assert_eq!(m.remove(80, f, &()), Some(8.0));
1200        assert_eq!(m.remove(50, f, &()), Some(5.0));
1201        m.verify(f, &());
1202
1203        // [ 10 20 30 40 ] [ 70 ]
1204        assert_eq!(m.tpath(50, f, &()), "node2[0]--node0[4]");
1205        assert_eq!(m.tpath(70, f, &()), "node2[1]--node1[0]");
1206
1207        // Removing the last entry from the right leaf should cause a collapse.
1208        assert_eq!(m.remove(70, f, &()), Some(7.0));
1209        m.verify(f, &());
1210    }
1211
1212    // Make a 3-level tree with barely healthy nodes.
1213    // 1 root, 8 inner nodes, 7*4+5=33 leaf nodes, 4 entries each.
1214    fn level3_sparse(f: &mut MapForest<u32, f32>) -> Map<u32, f32> {
1215        f.clear();
1216        let mut m = Map::new();
1217        for n in 1..133 {
1218            m.insert(n * 10, n as f32, f, &());
1219        }
1220        m
1221    }
1222
1223    #[test]
1224    fn level3_removes() {
1225        let f = &mut MapForest::<u32, f32>::new();
1226        let mut m = level3_sparse(f);
1227        m.verify(f, &());
1228
1229        // Check geometry.
1230        // Root: node11
1231        // [ node2 170 node10 330 node16 490 node21 650 node26 810 node31 970 node36 1130 node41 ]
1232        // L1: node11
1233        assert_eq!(m.tpath(0, f, &()), "node11[0]--node2[0]--node0[0]");
1234        assert_eq!(m.tpath(10000, f, &()), "node11[7]--node41[4]--node40[4]");
1235
1236        // 650 is a critical key in the middle of the root.
1237        assert_eq!(m.tpath(640, f, &()), "node11[3]--node21[3]--node19[3]");
1238        assert_eq!(m.tpath(650, f, &()), "node11[4]--node26[0]--node20[0]");
1239
1240        // Deleting 640 triggers a rebalance from node19 to node 20, cascading to n21 -> n26.
1241        assert_eq!(m.remove(640, f, &()), Some(64.0));
1242        m.verify(f, &());
1243        assert_eq!(m.tpath(650, f, &()), "node11[3]--node26[3]--node20[3]");
1244
1245        // 1130 is in the first leaf of the last L1 node. Deleting it triggers a rebalance node35
1246        // -> node37, but no rebalance above where there is no right sibling.
1247        assert_eq!(m.tpath(1130, f, &()), "node11[6]--node41[0]--node35[0]");
1248        assert_eq!(m.tpath(1140, f, &()), "node11[6]--node41[0]--node35[1]");
1249        assert_eq!(m.remove(1130, f, &()), Some(113.0));
1250        m.verify(f, &());
1251        assert_eq!(m.tpath(1140, f, &()), "node11[6]--node41[0]--node37[0]");
1252    }
1253
1254    #[test]
1255    fn insert_many() {
1256        let f = &mut MapForest::<u32, f32>::new();
1257        let mut m = Map::<u32, f32>::new();
1258
1259        let mm = 4096;
1260        let mut x = 0;
1261
1262        for n in 0..mm {
1263            assert_eq!(m.insert(x, n as f32, f, &()), None);
1264            m.verify(f, &());
1265
1266            x = (x + n + 1) % mm;
1267        }
1268
1269        x = 0;
1270        for n in 0..mm {
1271            assert_eq!(m.get(x, f, &()), Some(n as f32));
1272            x = (x + n + 1) % mm;
1273        }
1274
1275        x = 0;
1276        for n in 0..mm {
1277            assert_eq!(m.remove(x, f, &()), Some(n as f32));
1278            m.verify(f, &());
1279
1280            x = (x + n + 1) % mm;
1281        }
1282
1283        assert!(m.is_empty());
1284    }
1285
1286    #[test]
1287    fn immutable_cursor() {
1288        let f = &mut MapForest::<u32, f32>::new();
1289        let mut m = Map::<u32, f32>::new();
1290
1291        for i in 100..200 {
1292            m.insert(i, i as f32, f, &());
1293        }
1294
1295        let mut c = m.cursor(f, &());
1296
1297        let v = c.goto_first().unwrap();
1298        assert_eq!(v, 100.0);
1299        assert_eq!(c.key(), Some(100));
1300        assert_eq!(c.value(), Some(100.0));
1301
1302        let (k, v) = c.next().unwrap();
1303        assert_eq!(k, 101);
1304        assert_eq!(v, 101.0);
1305        assert_eq!(c.key(), Some(101));
1306        assert_eq!(c.value(), Some(101.0));
1307
1308        let (k, v) = c.next().unwrap();
1309        assert_eq!(k, 102);
1310        assert_eq!(v, 102.0);
1311        assert_eq!(c.key(), Some(102));
1312        assert_eq!(c.value(), Some(102.0));
1313
1314        let (k, v) = c.prev().unwrap();
1315        assert_eq!(k, 101);
1316        assert_eq!(v, 101.0);
1317        assert_eq!(c.key(), Some(101));
1318        assert_eq!(c.value(), Some(101.0));
1319
1320        let v = c.goto(175).unwrap();
1321        assert_eq!(v, 175.0);
1322        assert_eq!(c.key(), Some(175));
1323        assert_eq!(c.value(), Some(175.0));
1324
1325        let (k, v) = c.next().unwrap();
1326        assert_eq!(k, 176);
1327        assert_eq!(v, 176.0);
1328        assert_eq!(c.key(), Some(176));
1329        assert_eq!(c.value(), Some(176.0));
1330
1331        let (k, v) = c.prev().unwrap();
1332        assert_eq!(k, 175);
1333        assert_eq!(v, 175.0);
1334        assert_eq!(c.key(), Some(175));
1335        assert_eq!(c.value(), Some(175.0));
1336
1337        let v = c.goto(200);
1338        assert!(v.is_none());
1339        assert!(c.key().is_none());
1340        assert!(c.value().is_none());
1341
1342        for i in (100..200).rev() {
1343            let (k, v) = c.prev().unwrap();
1344            assert_eq!(k, i);
1345            assert_eq!(v, i as f32);
1346            assert_eq!(c.key(), Some(i));
1347            assert_eq!(c.value(), Some(i as f32));
1348        }
1349        assert!(c.prev().is_none());
1350
1351        assert_eq!(c.key(), Some(100));
1352        assert_eq!(c.value(), Some(100.0));
1353        for i in 101..200 {
1354            let (k, v) = c.next().unwrap();
1355            assert_eq!(k, i);
1356            assert_eq!(v, i as f32);
1357            assert_eq!(c.key(), Some(i));
1358            assert_eq!(c.value(), Some(i as f32));
1359        }
1360        assert!(c.next().is_none());
1361        assert!(c.key().is_none());
1362        assert!(c.value().is_none());
1363    }
1364
1365    #[test]
1366    fn into_iter() {
1367        let mut f = MapForest::<u32, f32>::new();
1368        let mut m = Map::<u32, f32>::new();
1369
1370        for i in 10..20 {
1371            m.insert(i, i as f32, &mut f, &());
1372        }
1373
1374        assert_eq!(
1375            m.into_iter(f).collect::<Vec<_>>(),
1376            vec![
1377                (10, 10.0),
1378                (11, 11.0),
1379                (12, 12.0),
1380                (13, 13.0),
1381                (14, 14.0),
1382                (15, 15.0),
1383                (16, 16.0),
1384                (17, 17.0),
1385                (18, 18.0),
1386                (19, 19.0),
1387            ],
1388        );
1389    }
1390
1391    #[test]
1392    fn range() {
1393        let mut f = MapForest::<u32, f32>::new();
1394        let mut m = Map::<u32, f32>::new();
1395
1396        for i in 10..20 {
1397            m.insert(i, i as f32, &mut f, &());
1398        }
1399
1400        assert_eq!(
1401            m.range(.., &f, &()).collect::<Vec<_>>(),
1402            vec![
1403                (10, 10.0),
1404                (11, 11.0),
1405                (12, 12.0),
1406                (13, 13.0),
1407                (14, 14.0),
1408                (15, 15.0),
1409                (16, 16.0),
1410                (17, 17.0),
1411                (18, 18.0),
1412                (19, 19.0),
1413            ],
1414        );
1415
1416        assert_eq!(
1417            m.range(5..12, &f, &()).collect::<Vec<_>>(),
1418            vec![(10, 10.0), (11, 11.0)],
1419        );
1420
1421        assert_eq!(
1422            m.range(18..30, &f, &()).collect::<Vec<_>>(),
1423            vec![(18, 18.0), (19, 19.0)],
1424        );
1425
1426        assert_eq!(
1427            m.range(..13, &f, &()).collect::<Vec<_>>(),
1428            vec![(10, 10.0), (11, 11.0), (12, 12.0)],
1429        );
1430
1431        assert_eq!(
1432            m.range(18.., &f, &()).collect::<Vec<_>>(),
1433            vec![(18, 18.0), (19, 19.0)],
1434        );
1435
1436        assert_eq!(
1437            m.range(12..=15, &f, &()).collect::<Vec<_>>(),
1438            vec![(12, 12.0), (13, 13.0), (14, 14.0), (15, 15.0)],
1439        );
1440
1441        // Check when the query range is outside the entry range.
1442        assert_eq!(m.range(0..5, &f, &()).collect::<Vec<_>>(), vec![]);
1443        assert_eq!(m.range(30..40, &f, &()).collect::<Vec<_>>(), vec![]);
1444
1445        // Check when the query range's start and end land in between entries.
1446        for i in 30..40 {
1447            if i % 2 == 0 {
1448                m.insert(i, i as f32, &mut f, &());
1449            }
1450        }
1451        assert_eq!(
1452            m.range(31..35, &f, &()).collect::<Vec<_>>(),
1453            vec![(32, 32.0), (34, 34.0)],
1454        );
1455        assert_eq!(
1456            m.range(29..33, &f, &()).collect::<Vec<_>>(),
1457            vec![(30, 30.0), (32, 32.0)],
1458        );
1459        assert_eq!(
1460            m.range(35..40, &f, &()).collect::<Vec<_>>(),
1461            vec![(36, 36.0), (38, 38.0)],
1462        );
1463    }
1464}