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