Skip to main content

fixed_map/set/
intersection.rs

1//! Module that defines the [`Intersection`] for [`Set`].
2
3use core::fmt;
4
5use super::{Iter, Key, Set};
6
7/// A lazy iterator producing elements in the intersection of `Set`s.
8///
9/// This `struct` is created by the [`intersection`] method on [`Set`]. See its
10/// documentation for more.
11///
12/// [`intersection`]: Set::intersection
13///
14/// # Examples
15///
16/// ```
17/// use fixed_map::{Key, Set};
18///
19/// #[derive(Clone, Copy, Key, Debug)]
20/// enum K {
21///     One,
22///     Two,
23///     Three,
24/// }
25///
26/// let a = Set::from([K::One]);
27/// let b = Set::from([K::One, K::Two, K::Two]);
28///
29/// let intersection = a.intersection(&b).collect::<Set<_>>();
30/// assert_eq!(intersection, Set::from([K::One]));
31/// ```
32#[must_use = "this returns the intersection as an iterator, \
33              without modifying either input set"]
34pub struct Intersection<'a, T: 'a + Key> {
35    // iterator of the first set
36    pub(super) iter: Iter<'a, T>,
37    // the second set
38    pub(super) other: &'a Set<T>,
39}
40
41impl<T: Key> Clone for Intersection<'_, T> {
42    #[inline]
43    fn clone(&self) -> Self {
44        Intersection {
45            iter: self.iter.clone(),
46            ..*self
47        }
48    }
49}
50
51impl<T> Iterator for Intersection<'_, T>
52where
53    T: Key,
54{
55    type Item = T;
56
57    #[inline]
58    fn next(&mut self) -> Option<T> {
59        loop {
60            let elt = self.iter.next()?;
61
62            if self.other.contains(elt) {
63                return Some(elt);
64            }
65        }
66    }
67
68    #[inline]
69    fn size_hint(&self) -> (usize, Option<usize>) {
70        let (_, upper) = self.iter.size_hint();
71        (0, upper)
72    }
73
74    #[inline]
75    fn fold<B, F>(self, init: B, mut f: F) -> B
76    where
77        Self: Sized,
78        F: FnMut(B, Self::Item) -> B,
79    {
80        self.iter.fold(init, |acc, elt| {
81            if self.other.contains(elt) {
82                f(acc, elt)
83            } else {
84                acc
85            }
86        })
87    }
88}
89
90impl<T> fmt::Debug for Intersection<'_, T>
91where
92    T: fmt::Debug + Key,
93{
94    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
95        f.debug_list().entries(self.clone()).finish()
96    }
97}