prefix_trie/map/
iter.rs

1//! Module that contains the implementation for the iterators
2
3use map::Table;
4
5use crate::*;
6
7use super::Node;
8
9/// An iterator over all entries of a [`PrefixMap`] in lexicographic order.
10#[derive(Clone)]
11pub struct Iter<'a, P, T> {
12    table: Option<&'a Table<P, T>>,
13    nodes: Vec<usize>,
14}
15
16impl<P, T> Default for Iter<'_, P, T> {
17    fn default() -> Self {
18        Self {
19            table: None,
20            nodes: Vec::new(),
21        }
22    }
23}
24
25impl<'a, P, T> Iter<'a, P, T> {
26    pub(crate) fn new(table: &'a Table<P, T>, nodes: Vec<usize>) -> Self {
27        Self {
28            table: Some(table),
29            nodes,
30        }
31    }
32}
33
34impl<'a, P, T> Iterator for Iter<'a, P, T> {
35    type Item = (&'a P, &'a T);
36
37    fn next(&mut self) -> Option<(&'a P, &'a T)> {
38        while let Some(cur) = self.nodes.pop() {
39            let node = &self.table.as_ref()?[cur];
40            if let Some(right) = node.right {
41                self.nodes.push(right);
42            }
43            if let Some(left) = node.left {
44                self.nodes.push(left);
45            }
46            if let Some(v) = &node.value {
47                return Some((&node.prefix, v));
48            }
49        }
50        None
51    }
52}
53
54/// An iterator over all prefixes of a [`PrefixMap`] in lexicographic order.
55#[derive(Clone, Default)]
56pub struct Keys<'a, P, T> {
57    pub(crate) inner: Iter<'a, P, T>,
58}
59
60impl<'a, P, T> Iterator for Keys<'a, P, T> {
61    type Item = &'a P;
62
63    fn next(&mut self) -> Option<&'a P> {
64        self.inner.next().map(|(k, _)| k)
65    }
66}
67
68/// An iterator over all values of a [`PrefixMap`] in lexicographic order of their associated
69/// prefixes.
70#[derive(Clone, Default)]
71pub struct Values<'a, P, T> {
72    pub(crate) inner: Iter<'a, P, T>,
73}
74
75impl<'a, P, T> Iterator for Values<'a, P, T> {
76    type Item = &'a T;
77
78    fn next(&mut self) -> Option<&'a T> {
79        self.inner.next().map(|(_, v)| v)
80    }
81}
82
83/// An iterator over all owned entries of a [`PrefixMap`] in lexicographic order.
84#[derive(Clone)]
85pub struct IntoIter<P, T> {
86    table: Vec<Node<P, T>>,
87    nodes: Vec<usize>,
88}
89
90impl<P: Prefix, T> Iterator for IntoIter<P, T> {
91    type Item = (P, T);
92
93    fn next(&mut self) -> Option<(P, T)> {
94        while let Some(cur) = self.nodes.pop() {
95            let node = &mut self.table[cur];
96            if let Some(right) = node.right {
97                self.nodes.push(right);
98            }
99            if let Some(left) = node.left {
100                self.nodes.push(left);
101            }
102            if let Some(v) = node.value.take() {
103                return Some((std::mem::replace(&mut node.prefix, P::zero()), v));
104            }
105        }
106        None
107    }
108}
109
110/// An iterator over all prefixes of a [`PrefixMap`] in lexicographic order.
111#[derive(Clone)]
112pub struct IntoKeys<P, T> {
113    inner: IntoIter<P, T>,
114}
115
116impl<P: Prefix, T> Iterator for IntoKeys<P, T> {
117    type Item = P;
118
119    fn next(&mut self) -> Option<P> {
120        self.inner.next().map(|(k, _)| k)
121    }
122}
123
124/// An iterator over all values of a [`PrefixMap`] in lexicographic order of their associated
125/// prefix.
126#[derive(Clone)]
127pub struct IntoValues<P, T> {
128    inner: IntoIter<P, T>,
129}
130
131impl<P: Prefix, T> Iterator for IntoValues<P, T> {
132    type Item = T;
133
134    fn next(&mut self) -> Option<T> {
135        self.inner.next().map(|(_, v)| v)
136    }
137}
138
139impl<P: Prefix, T> IntoIterator for PrefixMap<P, T> {
140    type Item = (P, T);
141
142    type IntoIter = IntoIter<P, T>;
143
144    fn into_iter(self) -> Self::IntoIter {
145        IntoIter {
146            table: self.table.into_inner(),
147            nodes: vec![0],
148        }
149    }
150}
151
152impl<'a, P, T> IntoIterator for &'a PrefixMap<P, T> {
153    type Item = (&'a P, &'a T);
154
155    type IntoIter = Iter<'a, P, T>;
156
157    fn into_iter(self) -> Self::IntoIter {
158        // Safety: we own an immutable reference, and `Iter` will only ever read the table.
159        Iter::new(&self.table, vec![0])
160    }
161}
162
163/// A mutable iterator over a [`PrefixMap`]. This iterator yields elements in lexicographic order of
164/// their associated prefix.
165pub struct IterMut<'a, P, T> {
166    table: Option<&'a Table<P, T>>,
167    nodes: Vec<usize>,
168}
169
170impl<P, T> Default for IterMut<'_, P, T> {
171    fn default() -> Self {
172        Self {
173            table: None,
174            nodes: Vec::new(),
175        }
176    }
177}
178
179impl<'a, P, T> IterMut<'a, P, T> {
180    /// # Safety
181    /// - First, you must ensure that 'a is tied to a mutable reference of the original table.
182    /// - Second, you are allowed to create mutiple such `IterMut`s, as long as none of the root
183    ///   nodes is the parent of another root node (of any of the iterators). This also applies if
184    ///   you only create a single iterator with multiple root nodes.
185    ///
186    /// The iterator will only ever access its roots or its children.
187    pub(crate) unsafe fn new(table: &'a Table<P, T>, nodes: Vec<usize>) -> Self {
188        Self {
189            table: Some(table),
190            nodes,
191        }
192    }
193}
194
195impl<'a, P, T> Iterator for IterMut<'a, P, T> {
196    type Item = (&'a P, &'a mut T);
197
198    fn next(&mut self) -> Option<Self::Item> {
199        while let Some(cur) = self.nodes.pop() {
200            // Safety:
201            // In the following, we assume that there are no two iterators that may reach the same
202            // sub-tree (see the safety comment above).
203            //
204            // The iterator borrows from &'a mut PrefixMap, see `PrefixMap::iter_mut` where 'a is
205            // linked to a mutable reference. Then, we must ensure that we only ever construct a
206            // mutable reference to each element exactly once. We ensure this by the fact that we
207            // iterate over a tree. Thus, each node is visited exactly once.
208            let node: &'a mut Node<P, T> = unsafe { self.table.as_ref()?.get_mut(cur) };
209
210            if let Some(right) = node.right {
211                self.nodes.push(right);
212            }
213            if let Some(left) = node.left {
214                self.nodes.push(left);
215            }
216            if node.value.is_some() {
217                let v = node.value.as_mut().unwrap();
218                return Some((&node.prefix, v));
219            }
220        }
221        None
222    }
223}
224
225/// A mutable iterator over values of [`PrefixMap`]. This iterator yields elements in lexicographic
226/// order.
227#[derive(Default)]
228pub struct ValuesMut<'a, P, T> {
229    // # Safety
230    // You must ensure that there only ever exists one such iterator for each tree. You may create
231    // multiple such iterators for the same tree if you start with distinct starting nodes! This
232    // ensures that any one iteration will never yield elements of the other iterator.
233    pub(crate) inner: IterMut<'a, P, T>,
234}
235
236impl<'a, P, T> Iterator for ValuesMut<'a, P, T> {
237    type Item = &'a mut T;
238
239    fn next(&mut self) -> Option<Self::Item> {
240        self.inner.next().map(|(_, v)| v)
241    }
242}
243
244impl<P, T> PrefixMap<P, T> {
245    /// An iterator visiting all key-value pairs in lexicographic order. The iterator element type
246    /// is `(&P, &T)`.
247    ///
248    /// ```
249    /// # use prefix_trie::*;
250    /// # #[cfg(feature = "ipnet")]
251    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
252    /// let mut pm: PrefixMap<ipnet::Ipv4Net, _> = PrefixMap::new();
253    /// pm.insert("192.168.0.0/22".parse()?, 1);
254    /// pm.insert("192.168.0.0/23".parse()?, 2);
255    /// pm.insert("192.168.2.0/23".parse()?, 3);
256    /// pm.insert("192.168.0.0/24".parse()?, 4);
257    /// pm.insert("192.168.2.0/24".parse()?, 5);
258    /// assert_eq!(
259    ///     pm.iter().collect::<Vec<_>>(),
260    ///     vec![
261    ///         (&"192.168.0.0/22".parse()?, &1),
262    ///         (&"192.168.0.0/23".parse()?, &2),
263    ///         (&"192.168.0.0/24".parse()?, &4),
264    ///         (&"192.168.2.0/23".parse()?, &3),
265    ///         (&"192.168.2.0/24".parse()?, &5),
266    ///     ]
267    /// );
268    /// # Ok(())
269    /// # }
270    /// # #[cfg(not(feature = "ipnet"))]
271    /// # fn main() {}
272    /// ```
273    #[inline(always)]
274    pub fn iter(&self) -> Iter<'_, P, T> {
275        self.into_iter()
276    }
277
278    /// Get a mutable iterator over all key-value pairs. The order of this iterator is lexicographic.
279    pub fn iter_mut(&mut self) -> IterMut<'_, P, T> {
280        // Safety: We get the pointer to the table by and construct the `IterMut`. Its lifetime is
281        // now tied to the mutable borrow of `self`, so we are allowed to access elements of that
282        // table mutably.
283        unsafe { IterMut::new(&self.table, vec![0]) }
284    }
285
286    /// An iterator visiting all keys in lexicographic order. The iterator element type is `&P`.
287    ///
288    /// ```
289    /// # use prefix_trie::*;
290    /// # #[cfg(feature = "ipnet")]
291    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
292    /// let mut pm: PrefixMap<ipnet::Ipv4Net, _> = PrefixMap::new();
293    /// pm.insert("192.168.0.0/22".parse()?, 1);
294    /// pm.insert("192.168.0.0/23".parse()?, 2);
295    /// pm.insert("192.168.2.0/23".parse()?, 3);
296    /// pm.insert("192.168.0.0/24".parse()?, 4);
297    /// pm.insert("192.168.2.0/24".parse()?, 5);
298    /// assert_eq!(
299    ///     pm.keys().collect::<Vec<_>>(),
300    ///     vec![
301    ///         &"192.168.0.0/22".parse()?,
302    ///         &"192.168.0.0/23".parse()?,
303    ///         &"192.168.0.0/24".parse()?,
304    ///         &"192.168.2.0/23".parse()?,
305    ///         &"192.168.2.0/24".parse()?,
306    ///     ]
307    /// );
308    /// # Ok(())
309    /// # }
310    /// # #[cfg(not(feature = "ipnet"))]
311    /// # fn main() {}
312    /// ```
313    #[inline(always)]
314    pub fn keys(&self) -> Keys<'_, P, T> {
315        Keys { inner: self.iter() }
316    }
317
318    /// Creates a consuming iterator visiting all keys in lexicographic order. The iterator element
319    /// type is `P`.
320    #[inline(always)]
321    pub fn into_keys(self) -> IntoKeys<P, T> {
322        IntoKeys {
323            inner: IntoIter {
324                table: self.table.into_inner(),
325                nodes: vec![0],
326            },
327        }
328    }
329
330    /// An iterator visiting all values in lexicographic order. The iterator element type is `&P`.
331    ///
332    /// ```
333    /// # use prefix_trie::*;
334    /// # #[cfg(feature = "ipnet")]
335    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
336    /// let mut pm: PrefixMap<ipnet::Ipv4Net, _> = PrefixMap::new();
337    /// pm.insert("192.168.0.0/22".parse()?, 1);
338    /// pm.insert("192.168.0.0/23".parse()?, 2);
339    /// pm.insert("192.168.2.0/23".parse()?, 3);
340    /// pm.insert("192.168.0.0/24".parse()?, 4);
341    /// pm.insert("192.168.2.0/24".parse()?, 5);
342    /// assert_eq!(pm.values().collect::<Vec<_>>(), vec![&1, &2, &4, &3, &5]);
343    /// # Ok(())
344    /// # }
345    /// # #[cfg(not(feature = "ipnet"))]
346    /// # fn main() {}
347    /// ```
348    #[inline(always)]
349    pub fn values(&self) -> Values<'_, P, T> {
350        Values { inner: self.iter() }
351    }
352
353    /// Creates a consuming iterator visiting all values in lexicographic order. The iterator
354    /// element type is `P`.
355    #[inline(always)]
356    pub fn into_values(self) -> IntoValues<P, T> {
357        IntoValues {
358            inner: IntoIter {
359                table: self.table.into_inner(),
360                nodes: vec![0],
361            },
362        }
363    }
364
365    /// Get a mutable iterator over all values. The order of this iterator is lexicographic.
366    pub fn values_mut(&mut self) -> ValuesMut<'_, P, T> {
367        ValuesMut {
368            inner: self.iter_mut(),
369        }
370    }
371}
372
373impl<P, T> PrefixMap<P, T>
374where
375    P: Prefix,
376{
377    /// Get an iterator over the node itself and all children. All elements returned have a prefix
378    /// that is contained within `prefix` itself (or are the same). The iterator yields references
379    /// to both keys and values, i.e., type `(&'a P, &'a T)`. The iterator yields elements in
380    /// lexicographic order.
381    ///
382    /// **Note**: Consider using [`AsView::view_at`] as an alternative.
383    ///
384    /// ```
385    /// # use prefix_trie::*;
386    /// # #[cfg(feature = "ipnet")]
387    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
388    /// let mut pm: PrefixMap<ipnet::Ipv4Net, _> = PrefixMap::new();
389    /// pm.insert("192.168.0.0/22".parse()?, 1);
390    /// pm.insert("192.168.0.0/23".parse()?, 2);
391    /// pm.insert("192.168.2.0/23".parse()?, 3);
392    /// pm.insert("192.168.0.0/24".parse()?, 4);
393    /// pm.insert("192.168.2.0/24".parse()?, 5);
394    /// assert_eq!(
395    ///     pm.children("192.168.0.0/23".parse()?).collect::<Vec<_>>(),
396    ///     vec![
397    ///         (&"192.168.0.0/23".parse()?, &2),
398    ///         (&"192.168.0.0/24".parse()?, &4),
399    ///     ]
400    /// );
401    /// # Ok(())
402    /// # }
403    /// # #[cfg(not(feature = "ipnet"))]
404    /// # fn main() {}
405    /// ```
406    pub fn children(&self, prefix: P) -> Iter<'_, P, T> {
407        self.view_at(prefix)
408            .map(|x| x.into_iter())
409            .unwrap_or_default()
410    }
411
412    /// Get an iterator of mutable references of the node itself and all its children. All elements
413    /// returned have a prefix that is contained within `prefix` itself (or are the same). The
414    /// iterator yields references to the keys, and mutable references to the values, i.e., type
415    /// `(&'a P, &'a mut T)`. The iterator yields elements in lexicographic order.
416    ///
417    /// **Note**: Consider using [`AsViewMut::view_mut_at`] as an alternative.
418    ///
419    /// ```
420    /// # use prefix_trie::*;
421    /// # #[cfg(feature = "ipnet")]
422    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
423    /// let mut pm: PrefixMap<ipnet::Ipv4Net, _> = PrefixMap::new();
424    /// pm.insert("192.168.0.0/22".parse()?, 1);
425    /// pm.insert("192.168.0.0/23".parse()?, 2);
426    /// pm.insert("192.168.0.0/24".parse()?, 3);
427    /// pm.insert("192.168.2.0/23".parse()?, 4);
428    /// pm.insert("192.168.2.0/24".parse()?, 5);
429    /// pm.children_mut("192.168.0.0/23".parse()?).for_each(|(_, x)| *x *= 10);
430    /// assert_eq!(
431    ///     pm.into_iter().collect::<Vec<_>>(),
432    ///     vec![
433    ///         ("192.168.0.0/22".parse()?, 1),
434    ///         ("192.168.0.0/23".parse()?, 20),
435    ///         ("192.168.0.0/24".parse()?, 30),
436    ///         ("192.168.2.0/23".parse()?, 4),
437    ///         ("192.168.2.0/24".parse()?, 5),
438    ///     ]
439    /// );
440    /// # Ok(())
441    /// # }
442    /// # #[cfg(not(feature = "ipnet"))]
443    /// # fn main() {}
444    /// ```
445    pub fn children_mut(&mut self, prefix: P) -> IterMut<'_, P, T> {
446        self.view_mut_at(prefix)
447            .map(|x| x.into_iter())
448            .unwrap_or_default()
449    }
450
451    /// Get an iterator over the node itself and all children with a value. All elements returned
452    /// have a prefix that is contained within `prefix` itself (or are the same). This function will
453    /// consume `self`, returning an iterator over all owned children.
454    ///
455    /// ```
456    /// # use prefix_trie::*;
457    /// # #[cfg(feature = "ipnet")]
458    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
459    /// let mut pm: PrefixMap<ipnet::Ipv4Net, _> = PrefixMap::new();
460    /// pm.insert("192.168.0.0/22".parse()?, 1);
461    /// pm.insert("192.168.0.0/23".parse()?, 2);
462    /// pm.insert("192.168.2.0/23".parse()?, 3);
463    /// pm.insert("192.168.0.0/24".parse()?, 4);
464    /// pm.insert("192.168.2.0/24".parse()?, 5);
465    /// assert_eq!(
466    ///     pm.into_children(&"192.168.0.0/23".parse()?).collect::<Vec<_>>(),
467    ///     vec![
468    ///         ("192.168.0.0/23".parse()?, 2),
469    ///         ("192.168.0.0/24".parse()?, 4),
470    ///     ]
471    /// );
472    /// # Ok(())
473    /// # }
474    /// # #[cfg(not(feature = "ipnet"))]
475    /// # fn main() {}
476    /// ```
477    pub fn into_children(self, prefix: &P) -> IntoIter<P, T> {
478        let nodes = lpm_children_iter_start(&self.table, prefix);
479        IntoIter {
480            table: self.table.into_inner(),
481            nodes,
482        }
483    }
484}
485
486fn lpm_children_iter_start<P: Prefix, T>(table: &Table<P, T>, prefix: &P) -> Vec<usize> {
487    let mut idx = 0;
488    let mut cur_p = &table[idx].prefix;
489
490    loop {
491        if cur_p.eq(prefix) {
492            break vec![idx];
493        }
494        let right = to_right(cur_p, prefix);
495        match table.get_child(idx, right) {
496            Some(c) => {
497                cur_p = &table[c].prefix;
498                if cur_p.contains(prefix) {
499                    // continue traversal
500                    idx = c;
501                } else if prefix.contains(cur_p) {
502                    break vec![c];
503                } else {
504                    break vec![];
505                }
506            }
507            None => break vec![],
508        }
509    }
510}
511
512impl<P, T> FromIterator<(P, T)> for PrefixMap<P, T>
513where
514    P: Prefix,
515{
516    fn from_iter<I: IntoIterator<Item = (P, T)>>(iter: I) -> Self {
517        let mut map = Self::new();
518        iter.into_iter().for_each(|(p, v)| {
519            map.insert(p, v);
520        });
521        map
522    }
523}
524
525/// An iterator that yields all items in a `PrefixMap` that covers a given prefix (including the
526/// prefix itself if preseint). See [`PrefixMap::cover`] for how to create this iterator.
527pub struct Cover<'a, P, T> {
528    pub(super) table: &'a Table<P, T>,
529    pub(super) idx: Option<usize>,
530    pub(super) prefix: &'a P,
531}
532
533impl<'a, P, T> Iterator for Cover<'a, P, T>
534where
535    P: Prefix,
536{
537    type Item = (&'a P, &'a T);
538
539    fn next(&mut self) -> Option<Self::Item> {
540        // check if self.idx is None. If so, then check if the first branch is present in the map
541        if self.idx.is_none() {
542            self.idx = Some(0);
543            let entry = &self.table[0];
544            if let Some(value) = entry.value.as_ref() {
545                return Some((&entry.prefix, value));
546            }
547        }
548
549        // if we reach here, then self.idx is not None!
550
551        loop {
552            let map::Direction::Enter { next, .. } =
553                self.table.get_direction(self.idx.unwrap(), self.prefix)
554            else {
555                return None;
556            };
557            self.idx = Some(next);
558            let entry = &self.table[next];
559            if let Some(value) = entry.value.as_ref() {
560                return Some((&entry.prefix, value));
561            }
562        }
563    }
564}
565
566/// An iterator that yields all keys (prefixes) in a `PrefixMap` that covers a given prefix
567/// (including the prefix itself if preseint). See [`PrefixMap::cover_keys`] for how to create this
568/// iterator.
569pub struct CoverKeys<'a, P, T>(pub(super) Cover<'a, P, T>);
570
571impl<'a, P, T> Iterator for CoverKeys<'a, P, T>
572where
573    P: Prefix,
574{
575    type Item = &'a P;
576
577    fn next(&mut self) -> Option<Self::Item> {
578        self.0.next().map(|(p, _)| p)
579    }
580}
581
582/// An iterator that yields all values in a `PrefixMap` that covers a given prefix (including the
583/// prefix itself if preseint). See [`PrefixMap::cover_values`] for how to create this iterator.
584pub struct CoverValues<'a, P, T>(pub(super) Cover<'a, P, T>);
585
586impl<'a, P, T> Iterator for CoverValues<'a, P, T>
587where
588    P: Prefix,
589{
590    type Item = &'a T;
591
592    fn next(&mut self) -> Option<Self::Item> {
593        self.0.next().map(|(_, t)| t)
594    }
595}