ic_stable_structures/btreemap/
iter.rs

1use super::{
2    node::{Node, NodeType},
3    BTreeMap,
4};
5use crate::{types::NULL, Address, Memory, Storable};
6use std::borrow::Cow;
7use std::ops::{Bound, RangeBounds};
8
9/// An indicator of the current position in the map.
10pub(crate) enum Cursor<K: Storable + Ord + Clone> {
11    Address(Address),
12    Node { node: Node<K>, next: Index },
13}
14
15/// An index into a node's child or entry.
16pub(crate) enum Index {
17    Child(usize),
18    Entry(usize),
19}
20
21/// An iterator over the entries of a [`BTreeMap`].
22#[must_use = "iterators are lazy and do nothing unless consumed"]
23pub(crate) struct IterInternal<'a, K, V, M>
24where
25    K: Storable + Ord + Clone,
26    V: Storable,
27    M: Memory,
28{
29    // A reference to the map being iterated on.
30    map: &'a BTreeMap<K, V, M>,
31
32    // Flags indicating if the cursors have been initialized yet. These are needed to distinguish
33    // between the case where the iteration hasn't started yet and the case where the iteration has
34    // finished (in both cases the cursors will be empty).
35    forward_cursors_initialized: bool,
36    backward_cursors_initialized: bool,
37
38    // Stacks of cursors indicating the current iteration positions in the tree.
39    forward_cursors: Vec<Cursor<K>>,
40    backward_cursors: Vec<Cursor<K>>,
41
42    // The range of keys we want to traverse.
43    range: (Bound<K>, Bound<K>),
44}
45
46impl<'a, K, V, M> IterInternal<'a, K, V, M>
47where
48    K: Storable + Ord + Clone,
49    V: Storable,
50    M: Memory,
51{
52    pub(crate) fn new(map: &'a BTreeMap<K, V, M>) -> Self {
53        Self {
54            map,
55            forward_cursors_initialized: false,
56            backward_cursors_initialized: false,
57            forward_cursors: vec![],
58            backward_cursors: vec![],
59            range: (Bound::Unbounded, Bound::Unbounded),
60        }
61    }
62
63    /// Returns an empty iterator.
64    pub(crate) fn null(map: &'a BTreeMap<K, V, M>) -> Self {
65        Self {
66            map,
67            forward_cursors_initialized: true,
68            backward_cursors_initialized: true,
69            forward_cursors: vec![],
70            backward_cursors: vec![],
71            range: (Bound::Unbounded, Bound::Unbounded),
72        }
73    }
74
75    pub(crate) fn new_in_range(map: &'a BTreeMap<K, V, M>, range: (Bound<K>, Bound<K>)) -> Self {
76        Self {
77            map,
78            forward_cursors_initialized: false,
79            backward_cursors_initialized: false,
80            forward_cursors: vec![],
81            backward_cursors: vec![],
82            range,
83        }
84    }
85
86    fn initialize_forward_cursors(&mut self) {
87        debug_assert!(!self.forward_cursors_initialized);
88
89        match self.range.start_bound() {
90            Bound::Unbounded => {
91                self.forward_cursors
92                    .push(Cursor::Address(self.map.root_addr));
93            }
94            Bound::Included(key) | Bound::Excluded(key) => {
95                let mut node = self.map.load_node(self.map.root_addr);
96                loop {
97                    match node.search(key, self.map.memory()) {
98                        Ok(idx) => {
99                            if let Bound::Included(_) = self.range.start_bound() {
100                                // We found the key exactly matching the left bound.
101                                // Here is where we'll start the iteration.
102                                self.forward_cursors.push(Cursor::Node {
103                                    node,
104                                    next: Index::Entry(idx),
105                                });
106                                break;
107                            } else {
108                                // We found the key that we must
109                                // exclude.  We add its right neighbor
110                                // to the stack and start iterating
111                                // from its right child.
112                                let right_child = match node.node_type() {
113                                    NodeType::Internal => Some(node.child(idx + 1)),
114                                    NodeType::Leaf => None,
115                                };
116
117                                if idx + 1 < node.entries_len()
118                                    && self.range.contains(node.key(idx + 1, self.map.memory()))
119                                {
120                                    self.forward_cursors.push(Cursor::Node {
121                                        node,
122                                        next: Index::Entry(idx + 1),
123                                    });
124                                }
125                                if let Some(right_child) = right_child {
126                                    self.forward_cursors.push(Cursor::Address(right_child));
127                                }
128                                break;
129                            }
130                        }
131                        Err(idx) => {
132                            // The `idx` variable points to the first
133                            // key that is greater than the left
134                            // bound.
135                            //
136                            // If the index points to a valid node, we
137                            // will visit its left subtree and then
138                            // return to this key.
139                            //
140                            // If the index points at the end of
141                            // array, we'll continue with the right
142                            // child of the last key.
143
144                            // Load the left child of the node to visit if it exists.
145                            // This is done first to avoid cloning the node.
146                            let child = match node.node_type() {
147                                NodeType::Internal => {
148                                    // Note that loading a child node cannot fail since
149                                    // len(children) = len(entries) + 1
150                                    Some(self.map.load_node(node.child(idx)))
151                                }
152                                NodeType::Leaf => None,
153                            };
154
155                            if idx < node.entries_len()
156                                && self.range.contains(node.key(idx, self.map.memory()))
157                            {
158                                self.forward_cursors.push(Cursor::Node {
159                                    node,
160                                    next: Index::Entry(idx),
161                                });
162                            }
163
164                            match child {
165                                None => {
166                                    // Leaf node. Return an iterator with the found cursors.
167                                    break;
168                                }
169                                Some(child) => {
170                                    // Iterate over the child node.
171                                    node = child;
172                                }
173                            }
174                        }
175                    }
176                }
177            }
178        }
179        self.forward_cursors_initialized = true;
180    }
181
182    fn initialize_backward_cursors(&mut self) {
183        debug_assert!(!self.backward_cursors_initialized);
184
185        match self.range.end_bound() {
186            Bound::Unbounded => {
187                self.backward_cursors
188                    .push(Cursor::Address(self.map.root_addr));
189            }
190            Bound::Included(key) | Bound::Excluded(key) => {
191                let mut node = self.map.load_node(self.map.root_addr);
192                loop {
193                    match node.search(key, self.map.memory()) {
194                        Ok(idx) => {
195                            if let Bound::Included(_) = self.range.end_bound() {
196                                // We found the key exactly matching the right bound.
197                                // Here is where we'll start the iteration.
198                                self.backward_cursors.push(Cursor::Node {
199                                    node,
200                                    next: Index::Entry(idx),
201                                });
202                                break;
203                            } else {
204                                // We found the key that we must
205                                // exclude. We add its left neighbor
206                                // to the stack and start iterating
207                                // from its left child.
208                                let left_child = match node.node_type() {
209                                    NodeType::Internal => Some(node.child(idx)),
210                                    NodeType::Leaf => None,
211                                };
212
213                                if idx > 0
214                                    && self.range.contains(node.key(idx - 1, self.map.memory()))
215                                {
216                                    self.backward_cursors.push(Cursor::Node {
217                                        node,
218                                        next: Index::Entry(idx - 1),
219                                    });
220                                }
221                                if let Some(left_child) = left_child {
222                                    self.backward_cursors.push(Cursor::Address(left_child));
223                                }
224                                break;
225                            }
226                        }
227                        Err(idx) => {
228                            // The `idx` variable points to the first
229                            // key that is greater than the right
230                            // bound.
231                            //
232                            // If the index points to a valid node, we
233                            // will visit its left subtree.
234                            //
235                            // If the index points at the end of
236                            // array, we'll continue with the right
237                            // child of the last key.
238
239                            // Load the left child of the node to visit if it exists.
240                            // This is done first to avoid cloning the node.
241                            let child = match node.node_type() {
242                                NodeType::Internal => {
243                                    // Note that loading a child node cannot fail since
244                                    // len(children) = len(entries) + 1
245                                    Some(self.map.load_node(node.child(idx)))
246                                }
247                                NodeType::Leaf => None,
248                            };
249
250                            if idx > 0 && self.range.contains(node.key(idx - 1, self.map.memory()))
251                            {
252                                self.backward_cursors.push(Cursor::Node {
253                                    node,
254                                    next: Index::Entry(idx - 1),
255                                });
256                            }
257
258                            match child {
259                                None => {
260                                    // Leaf node. Return an iterator with the found cursors.
261                                    break;
262                                }
263                                Some(child) => {
264                                    // Iterate over the child node.
265                                    node = child;
266                                }
267                            }
268                        }
269                    }
270                }
271            }
272        }
273        self.backward_cursors_initialized = true;
274    }
275
276    // Iterates to find the next element in the requested range.
277    // If it exists, `map` is applied to that element and the result is returned.
278    fn next_map<T, F: Fn(&Node<K>, usize) -> T>(&mut self, map: F) -> Option<T> {
279        if !self.forward_cursors_initialized {
280            self.initialize_forward_cursors();
281        }
282
283        // If the cursors are empty. Iteration is complete.
284        match self.forward_cursors.pop()? {
285            Cursor::Address(address) => {
286                if address != NULL {
287                    // Load the node at the given address, and add it to the cursors.
288                    let node = self.map.load_node(address);
289                    self.forward_cursors.push(Cursor::Node {
290                        next: match node.node_type() {
291                            // Iterate on internal nodes starting from the first child.
292                            NodeType::Internal => Index::Child(0),
293                            // Iterate on leaf nodes starting from the first entry.
294                            NodeType::Leaf => Index::Entry(0),
295                        },
296                        node,
297                    });
298                }
299                self.next_map(map)
300            }
301
302            Cursor::Node {
303                node,
304                next: Index::Child(child_idx),
305            } => {
306                let child_address = node.child(child_idx);
307
308                if child_idx < node.entries_len() {
309                    // After iterating on the child, iterate on the next _entry_ in this node.
310                    // The entry immediately after the child has the same index as the child's.
311                    self.forward_cursors.push(Cursor::Node {
312                        node,
313                        next: Index::Entry(child_idx),
314                    });
315                }
316
317                // Add the child to the top of the cursors to be iterated on first.
318                self.forward_cursors.push(Cursor::Address(child_address));
319
320                self.next_map(map)
321            }
322
323            Cursor::Node {
324                node,
325                next: Index::Entry(entry_idx),
326            } => {
327                // If the key does not belong to the range, iteration stops.
328                if !self.range.contains(node.key(entry_idx, self.map.memory())) {
329                    // Clear all cursors to avoid needless work in subsequent calls.
330                    self.forward_cursors = vec![];
331                    self.backward_cursors = vec![];
332                    return None;
333                }
334
335                let res = map(&node, entry_idx);
336                self.range.0 = Bound::Excluded(node.key(entry_idx, self.map.memory()).clone());
337
338                let next = match node.node_type() {
339                    // If this is an internal node, add the next child to the cursors.
340                    NodeType::Internal => Index::Child(entry_idx + 1),
341                    // If this is a leaf node, and it contains another entry, add the
342                    // next entry to the cursors.
343                    NodeType::Leaf if entry_idx + 1 < node.entries_len() => {
344                        Index::Entry(entry_idx + 1)
345                    }
346                    _ => return Some(res),
347                };
348
349                // Add to the cursors the next element to be traversed.
350                self.forward_cursors.push(Cursor::Node { next, node });
351                Some(res)
352            }
353        }
354    }
355
356    // Iterates to find the next back element in the requested range.
357    // If it exists, `map` is applied to that element and the result is returned.
358    fn next_back_map<T, F: Fn(&Node<K>, usize) -> T>(&mut self, map: F) -> Option<T> {
359        if !self.backward_cursors_initialized {
360            self.initialize_backward_cursors();
361        }
362
363        // If the cursors are empty. Iteration is complete.
364        match self.backward_cursors.pop()? {
365            Cursor::Address(address) => {
366                if address != NULL {
367                    // Load the node at the given address, and add it to the cursors.
368                    let node = self.map.load_node(address);
369                    if let Some(next) = match node.node_type() {
370                        // Iterate on internal nodes starting from the last child.
371                        NodeType::Internal if node.children_len() > 0 => {
372                            Some(Index::Child(node.children_len() - 1))
373                        }
374                        // Iterate on leaf nodes starting from the last entry.
375                        NodeType::Leaf if node.entries_len() > 0 => {
376                            Some(Index::Entry(node.entries_len() - 1))
377                        }
378                        _ => None,
379                    } {
380                        self.backward_cursors.push(Cursor::Node { next, node });
381                    }
382                }
383                self.next_back_map(map)
384            }
385
386            Cursor::Node {
387                node,
388                next: Index::Child(child_idx),
389            } => {
390                let child_address = node.child(child_idx);
391
392                if 0 < child_idx {
393                    // After iterating on the child, iterate on the previous _entry_ in this node.
394                    self.backward_cursors.push(Cursor::Node {
395                        node,
396                        next: Index::Entry(child_idx - 1),
397                    });
398                }
399
400                // Add the child to the top of the cursors to be iterated on first.
401                self.backward_cursors.push(Cursor::Address(child_address));
402
403                self.next_back_map(map)
404            }
405
406            Cursor::Node {
407                node,
408                next: Index::Entry(entry_idx),
409            } => {
410                // If the key does not belong to the range, iteration stops.
411                if !self.range.contains(node.key(entry_idx, self.map.memory())) {
412                    // Clear all cursors to avoid needless work in subsequent calls.
413                    self.forward_cursors = vec![];
414                    self.backward_cursors = vec![];
415                    return None;
416                }
417
418                let res = map(&node, entry_idx);
419                self.range.1 = Bound::Excluded(node.key(entry_idx, self.map.memory()).clone());
420
421                if let Some(next) = match node.node_type() {
422                    // If this is an internal node, add the previous child to the cursors.
423                    NodeType::Internal => Some(Index::Child(entry_idx)),
424                    // If this is a leaf node, add the previous entry to the cursors.
425                    NodeType::Leaf if entry_idx > 0 => Some(Index::Entry(entry_idx - 1)),
426                    _ => None,
427                } {
428                    // Add to the cursors the next element to be traversed.
429                    self.backward_cursors.push(Cursor::Node { next, node });
430                }
431
432                Some(res)
433            }
434        }
435    }
436
437    fn count(&mut self) -> usize {
438        let mut cnt = 0;
439        while self.next_map(|_, _| ()).is_some() {
440            cnt += 1;
441        }
442        cnt
443    }
444}
445
446pub struct Iter<'a, K, V, M>(IterInternal<'a, K, V, M>)
447where
448    K: Storable + Ord + Clone,
449    V: Storable,
450    M: Memory;
451
452impl<K, V, M> Iterator for Iter<'_, K, V, M>
453where
454    K: Storable + Ord + Clone,
455    V: Storable,
456    M: Memory,
457{
458    type Item = (K, V);
459
460    fn next(&mut self) -> Option<Self::Item> {
461        self.0.next_map(|node, entry_idx| {
462            let (key, encoded_value) = node.entry(entry_idx, self.0.map.memory());
463            (key.clone(), V::from_bytes(Cow::Borrowed(encoded_value)))
464        })
465    }
466
467    fn count(mut self) -> usize
468    where
469        Self: Sized,
470    {
471        self.0.count()
472    }
473}
474
475impl<K, V, M> DoubleEndedIterator for Iter<'_, K, V, M>
476where
477    K: Storable + Ord + Clone,
478    V: Storable,
479    M: Memory,
480{
481    fn next_back(&mut self) -> Option<Self::Item> {
482        self.0.next_back_map(|node, entry_idx| {
483            let (key, encoded_value) = node.entry(entry_idx, self.0.map.memory());
484            (key.clone(), V::from_bytes(Cow::Borrowed(encoded_value)))
485        })
486    }
487}
488
489pub struct KeysIter<'a, K, V, M>(IterInternal<'a, K, V, M>)
490where
491    K: Storable + Ord + Clone,
492    V: Storable,
493    M: Memory;
494
495impl<K, V, M> Iterator for KeysIter<'_, K, V, M>
496where
497    K: Storable + Ord + Clone,
498    V: Storable,
499    M: Memory,
500{
501    type Item = K;
502
503    fn next(&mut self) -> Option<Self::Item> {
504        self.0
505            .next_map(|node, entry_idx| node.key(entry_idx, self.0.map.memory()).clone())
506    }
507
508    fn count(mut self) -> usize
509    where
510        Self: Sized,
511    {
512        self.0.count()
513    }
514}
515
516impl<K, V, M> DoubleEndedIterator for KeysIter<'_, K, V, M>
517where
518    K: Storable + Ord + Clone,
519    V: Storable,
520    M: Memory,
521{
522    fn next_back(&mut self) -> Option<Self::Item> {
523        self.0
524            .next_back_map(|node, entry_idx| node.key(entry_idx, self.0.map.memory()).clone())
525    }
526}
527
528pub struct ValuesIter<'a, K, V, M>(IterInternal<'a, K, V, M>)
529where
530    K: Storable + Ord + Clone,
531    V: Storable,
532    M: Memory;
533
534impl<K, V, M> Iterator for ValuesIter<'_, K, V, M>
535where
536    K: Storable + Ord + Clone,
537    V: Storable,
538    M: Memory,
539{
540    type Item = V;
541
542    fn next(&mut self) -> Option<Self::Item> {
543        self.0.next_map(|node, entry_idx| {
544            let encoded_value = node.value(entry_idx, self.0.map.memory());
545            V::from_bytes(Cow::Borrowed(encoded_value))
546        })
547    }
548
549    fn count(mut self) -> usize
550    where
551        Self: Sized,
552    {
553        self.0.count()
554    }
555}
556
557impl<K, V, M> DoubleEndedIterator for ValuesIter<'_, K, V, M>
558where
559    K: Storable + Ord + Clone,
560    V: Storable,
561    M: Memory,
562{
563    fn next_back(&mut self) -> Option<Self::Item> {
564        self.0.next_back_map(|node, entry_idx| {
565            let encoded_value = node.value(entry_idx, self.0.map.memory());
566            V::from_bytes(Cow::Borrowed(encoded_value))
567        })
568    }
569}
570
571impl<'a, K, V, M> From<IterInternal<'a, K, V, M>> for Iter<'a, K, V, M>
572where
573    K: Storable + Ord + Clone,
574    V: Storable,
575    M: Memory,
576{
577    fn from(value: IterInternal<'a, K, V, M>) -> Self {
578        Iter(value)
579    }
580}
581
582impl<'a, K, V, M> From<IterInternal<'a, K, V, M>> for KeysIter<'a, K, V, M>
583where
584    K: Storable + Ord + Clone,
585    V: Storable,
586    M: Memory,
587{
588    fn from(value: IterInternal<'a, K, V, M>) -> Self {
589        KeysIter(value)
590    }
591}
592
593impl<'a, K, V, M> From<IterInternal<'a, K, V, M>> for ValuesIter<'a, K, V, M>
594where
595    K: Storable + Ord + Clone,
596    V: Storable,
597    M: Memory,
598{
599    fn from(value: IterInternal<'a, K, V, M>) -> Self {
600        ValuesIter(value)
601    }
602}
603
604#[cfg(test)]
605mod test {
606    use super::*;
607    use std::cell::RefCell;
608    use std::rc::Rc;
609
610    fn make_memory() -> Rc<RefCell<Vec<u8>>> {
611        Rc::new(RefCell::new(Vec::new()))
612    }
613
614    #[test]
615    fn iterate_leaf() {
616        let mem = make_memory();
617        let mut btree = BTreeMap::new(mem);
618
619        for i in 0..10u8 {
620            btree.insert(i, i + 1);
621        }
622
623        let mut i = 0;
624        for (key, value) in btree.iter() {
625            assert_eq!(key, i);
626            assert_eq!(value, i + 1);
627            i += 1;
628        }
629
630        assert_eq!(i, 10u8);
631    }
632
633    #[test]
634    fn iterate_children() {
635        let mem = make_memory();
636        let mut btree = BTreeMap::new(mem);
637
638        // Insert the elements in reverse order.
639        for i in (0..100u64).rev() {
640            btree.insert(i, i + 1);
641        }
642
643        // Iteration should be in ascending order.
644        let mut i = 0;
645        for (key, value) in btree.iter() {
646            assert_eq!(key, i);
647            assert_eq!(value, i + 1);
648            i += 1;
649        }
650
651        assert_eq!(i, 100);
652    }
653
654    #[test]
655    fn iterate_range() {
656        let mem = make_memory();
657        let mut btree = BTreeMap::new(mem);
658
659        // Insert the elements in reverse order.
660        for i in (0..100u64).rev() {
661            btree.insert(i, i + 1);
662        }
663
664        // Iteration should be in ascending order.
665        let mut i = 10;
666        for (key, value) in btree.range(10..90) {
667            assert_eq!(key, i);
668            assert_eq!(value, i + 1);
669            i += 1;
670        }
671
672        assert_eq!(i, 90);
673    }
674
675    #[test]
676    fn iterate_reverse() {
677        let mem = make_memory();
678        let mut btree = BTreeMap::new(mem);
679
680        // Insert the elements in reverse order.
681        for i in (0..100u64).rev() {
682            btree.insert(i, i + 1);
683        }
684
685        // Iteration should be in descending order.
686        let mut i = 100;
687        for (key, value) in btree.iter().rev() {
688            i -= 1;
689            assert_eq!(key, i);
690            assert_eq!(value, i + 1);
691        }
692
693        assert_eq!(i, 0);
694    }
695
696    #[test]
697    fn iterate_range_reverse() {
698        let mem = make_memory();
699        let mut btree = BTreeMap::new(mem);
700
701        // Insert the elements in reverse order.
702        for i in (0..100u64).rev() {
703            btree.insert(i, i + 1);
704        }
705
706        // Iteration should be in descending order.
707        let mut i = 80;
708        for (key, value) in btree.range(20..80).rev() {
709            i -= 1;
710            assert_eq!(key, i);
711            assert_eq!(value, i + 1);
712        }
713
714        assert_eq!(i, 20);
715    }
716
717    #[test]
718    fn iterate_from_both_ends() {
719        let mem = make_memory();
720        let mut btree = BTreeMap::new(mem);
721
722        // Insert the elements in reverse order.
723        for i in (0..100u64).rev() {
724            btree.insert(i, i + 1);
725        }
726
727        let mut iter = btree.iter();
728
729        for i in 0..50 {
730            let (key, value) = iter.next().unwrap();
731            assert_eq!(key, i);
732            assert_eq!(value, i + 1);
733
734            let (key, value) = iter.next_back().unwrap();
735            assert_eq!(key, 99 - i);
736            assert_eq!(value, 100 - i);
737        }
738
739        assert!(iter.next().is_none());
740        assert!(iter.next_back().is_none());
741    }
742
743    #[test]
744    fn iterate_range_from_both_ends() {
745        let mem = make_memory();
746        let mut btree = BTreeMap::new(mem);
747
748        // Insert the elements in reverse order.
749        for i in (0..100u64).rev() {
750            btree.insert(i, i + 1);
751        }
752
753        let mut iter = btree.range(30..70);
754
755        for i in 0..20 {
756            let (key, value) = iter.next().unwrap();
757            assert_eq!(key, 30 + i);
758            assert_eq!(value, 31 + i);
759
760            let (key, value) = iter.next_back().unwrap();
761            assert_eq!(key, 69 - i);
762            assert_eq!(value, 70 - i);
763        }
764
765        assert!(iter.next().is_none());
766        assert!(iter.next_back().is_none());
767    }
768
769    #[test]
770    fn keys_from_both_ends() {
771        let mem = make_memory();
772        let mut btree = BTreeMap::new(mem);
773
774        // Insert the elements in reverse order.
775        for i in (0..100u64).rev() {
776            btree.insert(i, i + 1);
777        }
778
779        let mut iter = btree.keys();
780
781        for i in 0..50 {
782            let key = iter.next().unwrap();
783            assert_eq!(key, i);
784
785            let key = iter.next_back().unwrap();
786            assert_eq!(key, 99 - i);
787        }
788
789        assert!(iter.next().is_none());
790        assert!(iter.next_back().is_none());
791    }
792
793    #[test]
794    fn keys_range_from_both_ends() {
795        let mem = make_memory();
796        let mut btree = BTreeMap::new(mem);
797
798        // Insert the elements in reverse order.
799        for i in (0..100u64).rev() {
800            btree.insert(i, i + 1);
801        }
802
803        let mut iter = btree.keys_range(30..70);
804
805        for i in 0..20 {
806            let key = iter.next().unwrap();
807            assert_eq!(key, 30 + i);
808
809            let key = iter.next_back().unwrap();
810            assert_eq!(key, 69 - i);
811        }
812
813        assert!(iter.next().is_none());
814        assert!(iter.next_back().is_none());
815    }
816
817    #[test]
818    fn values_from_both_ends() {
819        let mem = make_memory();
820        let mut btree = BTreeMap::new(mem);
821
822        // Insert the elements in reverse order.
823        for i in (0..100u64).rev() {
824            btree.insert(i, i + 1);
825        }
826
827        let mut iter = btree.values();
828
829        for i in 0..50 {
830            let value = iter.next().unwrap();
831            assert_eq!(value, i + 1);
832
833            let value = iter.next_back().unwrap();
834            assert_eq!(value, 100 - i);
835        }
836
837        assert!(iter.next().is_none());
838        assert!(iter.next_back().is_none());
839    }
840
841    #[test]
842    fn values_range_from_both_ends() {
843        let mem = make_memory();
844        let mut btree = BTreeMap::new(mem);
845
846        // Insert the elements in reverse order.
847        for i in (0..100u64).rev() {
848            btree.insert(i, i + 1);
849        }
850
851        let mut iter = btree.values_range(30..70);
852
853        for i in 0..20 {
854            let value = iter.next().unwrap();
855            assert_eq!(value, 31 + i);
856
857            let value = iter.next_back().unwrap();
858            assert_eq!(value, 70 - i);
859        }
860
861        assert!(iter.next().is_none());
862        assert!(iter.next_back().is_none());
863    }
864}