1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
// TODO: Implement .iter_mut()

use crate::{IndexTreeMap, Key, Value};

// IntoIterator
pub struct IndexTreeIntoIterator<K, V> {
    pub tree: IndexTreeMap<K, V>,
}

impl<K: Key, V: Value> IntoIterator for IndexTreeMap<K, V> {
    type Item = (Option<K>, Option<V>);
    type IntoIter = IndexTreeIntoIterator<K, V>;

    /// Creates a consuming iterator visiting all the keys, in sorted order. The map cannot be used after calling this.
    ///
    /// # Example
    ///
    /// Basic usage:
    /// ```rust
    /// use std::collections::BTreeMap;
    ///
    /// let mut map = BTreeMap::new();
    /// map.insert(2, "b");
    /// map.insert(1, "a");
    ///
    /// let items: Vec<(i32, &str)> = map.into_iter().collect();
    /// assert_eq!(items, [(1, "a"), (2, "b")]);
    /// ```
    fn into_iter(self) -> Self::IntoIter {
        IndexTreeIntoIterator { tree: self }
    }
}

impl<K: Key, V: Value> Iterator for IndexTreeIntoIterator<K, V> {
    type Item = (Option<K>, Option<V>);

    fn next(&mut self) -> Option<Self::Item> {
        if self.tree.size == 0 {
            return None;
        }
        Some(self.tree.remove_from_index(0))
    }
}

//Iterator
pub struct IndexTreeIterator<'a, K, V> {
    tree: &'a IndexTreeMap<K, V>,
    index: usize,
}

impl<'a, K: Key, V: Value> Iterator for IndexTreeIterator<'a, K, V> {
    type Item = (Option<&'a K>, Option<&'a V>);

    fn next(&mut self) -> Option<Self::Item> {
        if self.index < self.tree.size {
            self.index += 1;
            return Some(self.tree.get_key_value_from_index(self.index - 1));
        }
        None
    }
}

impl<K: Key, V: Value> IndexTreeMap<K, V> {
    /// Gets an iterator over the entries of the map, sorted by key.
    ///
    /// # Example
    ///
    /// Basic usage:
    /// ```rust
    /// use std::collections::BTreeMap;
    ///
    /// let mut map = BTreeMap::new();
    /// map.insert(3, "c");
    /// map.insert(2, "b");
    /// map.insert(1, "a");
    ///
    /// for (key, value) in map.iter() {
    ///     println!("{key}: {value}");
    /// }
    ///
    /// let (first_key, first_value) = map.iter().next().unwrap();
    /// assert_eq!((*first_key, *first_value), (1, "a"));
    /// ```
    pub fn iter(&self) -> IndexTreeIterator<K, V> {
        IndexTreeIterator {
            tree: self,
            index: 0,
        }
    }
}