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<'a>(&'a self, prefix: &P) -> Iter<'a, P, T> {
407 let nodes = lpm_children_iter_start(&self.table, prefix);
408 Iter {
409 table: Some(&self.table),
410 nodes,
411 }
412 }
413
414 /// Get an iterator of mutable references of the node itself and all its children. All elements
415 /// returned have a prefix that is contained within `prefix` itself (or are the same). The
416 /// iterator yields references to the keys, and mutable references to the values, i.e., type
417 /// `(&'a P, &'a mut T)`. The iterator yields elements in lexicographic order.
418 ///
419 /// **Note**: Consider using [`AsViewMut::view_mut_at`] as an alternative.
420 ///
421 /// ```
422 /// # use prefix_trie::*;
423 /// # #[cfg(feature = "ipnet")]
424 /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
425 /// let mut pm: PrefixMap<ipnet::Ipv4Net, _> = PrefixMap::new();
426 /// pm.insert("192.168.0.0/22".parse()?, 1);
427 /// pm.insert("192.168.0.0/23".parse()?, 2);
428 /// pm.insert("192.168.0.0/24".parse()?, 3);
429 /// pm.insert("192.168.2.0/23".parse()?, 4);
430 /// pm.insert("192.168.2.0/24".parse()?, 5);
431 /// pm.children_mut(&"192.168.0.0/23".parse()?).for_each(|(_, x)| *x *= 10);
432 /// assert_eq!(
433 /// pm.into_iter().collect::<Vec<_>>(),
434 /// vec![
435 /// ("192.168.0.0/22".parse()?, 1),
436 /// ("192.168.0.0/23".parse()?, 20),
437 /// ("192.168.0.0/24".parse()?, 30),
438 /// ("192.168.2.0/23".parse()?, 4),
439 /// ("192.168.2.0/24".parse()?, 5),
440 /// ]
441 /// );
442 /// # Ok(())
443 /// # }
444 /// # #[cfg(not(feature = "ipnet"))]
445 /// # fn main() {}
446 /// ```
447 pub fn children_mut<'a>(&'a mut self, prefix: &P) -> IterMut<'a, P, T> {
448 let nodes = lpm_children_iter_start(&self.table, prefix);
449 IterMut {
450 table: Some(&self.table),
451 nodes,
452 }
453 }
454
455 /// Get an iterator over the node itself and all children with a value. All elements returned
456 /// have a prefix that is contained within `prefix` itself (or are the same). This function will
457 /// consume `self`, returning an iterator over all owned children.
458 ///
459 /// ```
460 /// # use prefix_trie::*;
461 /// # #[cfg(feature = "ipnet")]
462 /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
463 /// let mut pm: PrefixMap<ipnet::Ipv4Net, _> = PrefixMap::new();
464 /// pm.insert("192.168.0.0/22".parse()?, 1);
465 /// pm.insert("192.168.0.0/23".parse()?, 2);
466 /// pm.insert("192.168.2.0/23".parse()?, 3);
467 /// pm.insert("192.168.0.0/24".parse()?, 4);
468 /// pm.insert("192.168.2.0/24".parse()?, 5);
469 /// assert_eq!(
470 /// pm.into_children(&"192.168.0.0/23".parse()?).collect::<Vec<_>>(),
471 /// vec![
472 /// ("192.168.0.0/23".parse()?, 2),
473 /// ("192.168.0.0/24".parse()?, 4),
474 /// ]
475 /// );
476 /// # Ok(())
477 /// # }
478 /// # #[cfg(not(feature = "ipnet"))]
479 /// # fn main() {}
480 /// ```
481 pub fn into_children(self, prefix: &P) -> IntoIter<P, T> {
482 let nodes = lpm_children_iter_start(&self.table, prefix);
483 IntoIter {
484 table: self.table.into_inner(),
485 nodes,
486 }
487 }
488}
489
490fn lpm_children_iter_start<P: Prefix, T>(table: &Table<P, T>, prefix: &P) -> Vec<usize> {
491 let mut idx = 0;
492 let mut cur_p = &table[idx].prefix;
493
494 loop {
495 if cur_p.eq(prefix) {
496 break vec![idx];
497 }
498 let right = to_right(cur_p, prefix);
499 match table.get_child(idx, right) {
500 Some(c) => {
501 cur_p = &table[c].prefix;
502 if cur_p.contains(prefix) {
503 // continue traversal
504 idx = c;
505 } else if prefix.contains(cur_p) {
506 break vec![c];
507 } else {
508 break vec![];
509 }
510 }
511 None => break vec![],
512 }
513 }
514}
515
516impl<P, T> FromIterator<(P, T)> for PrefixMap<P, T>
517where
518 P: Prefix,
519{
520 fn from_iter<I: IntoIterator<Item = (P, T)>>(iter: I) -> Self {
521 let mut map = Self::new();
522 iter.into_iter().for_each(|(p, v)| {
523 map.insert(p, v);
524 });
525 map
526 }
527}
528
529/// An iterator that yields all items in a `PrefixMap` that covers a given prefix (including the
530/// prefix itself if preseint). See [`PrefixMap::cover`] for how to create this iterator.
531pub struct Cover<'a, 'p, P, T> {
532 pub(super) table: &'a Table<P, T>,
533 pub(super) idx: Option<usize>,
534 pub(super) prefix: &'p P,
535}
536
537impl<'a, P, T> Iterator for Cover<'a, '_, P, T>
538where
539 P: Prefix,
540{
541 type Item = (&'a P, &'a T);
542
543 fn next(&mut self) -> Option<Self::Item> {
544 // check if self.idx is None. If so, then check if the first branch is present in the map
545 if self.idx.is_none() {
546 self.idx = Some(0);
547 let entry = &self.table[0];
548 if let Some(value) = entry.value.as_ref() {
549 return Some((&entry.prefix, value));
550 }
551 }
552
553 // if we reach here, then self.idx is not None!
554
555 loop {
556 let map::Direction::Enter { next, .. } =
557 self.table.get_direction(self.idx.unwrap(), self.prefix)
558 else {
559 return None;
560 };
561 self.idx = Some(next);
562 let entry = &self.table[next];
563 if let Some(value) = entry.value.as_ref() {
564 return Some((&entry.prefix, value));
565 }
566 }
567 }
568}
569
570/// An iterator that yields all keys (prefixes) in a `PrefixMap` that covers a given prefix
571/// (including the prefix itself if preseint). See [`PrefixMap::cover_keys`] for how to create this
572/// iterator.
573pub struct CoverKeys<'a, 'p, P, T>(pub(super) Cover<'a, 'p, P, T>);
574
575impl<'a, P, T> Iterator for CoverKeys<'a, '_, P, T>
576where
577 P: Prefix,
578{
579 type Item = &'a P;
580
581 fn next(&mut self) -> Option<Self::Item> {
582 self.0.next().map(|(p, _)| p)
583 }
584}
585
586/// An iterator that yields all values in a `PrefixMap` that covers a given prefix (including the
587/// prefix itself if preseint). See [`PrefixMap::cover_values`] for how to create this iterator.
588pub struct CoverValues<'a, 'p, P, T>(pub(super) Cover<'a, 'p, P, T>);
589
590impl<'a, P, T> Iterator for CoverValues<'a, '_, P, T>
591where
592 P: Prefix,
593{
594 type Item = &'a T;
595
596 fn next(&mut self) -> Option<Self::Item> {
597 self.0.next().map(|(_, t)| t)
598 }
599}