Debian Codegraph @

src/impls/intersection.rs

raw symbols SCIP
1 use crate::Counter;
2
3 use num_traits::Zero;
4
5 use std::hash::Hash;
6 use std::ops::{BitAnd, BitAndAssign};
7
8 impl<T, N> BitAnd for Counter<T, N>
9 where
10 T: Hash + Eq,
11 N: Ord + Zero,
12 {
13 type Output = Counter<T, N>;
14
15 /// Returns the intersection of `self` and `rhs` as a new `Counter`.
16 ///
17 /// `out = c & d;` -> `out[x] == min(c[x], d[x])`
18 ///
19 /// ```rust
20 /// # use counter::Counter;
21 /// # use std::collections::HashMap;
22 /// let c = "aaab".chars().collect::<Counter<_>>();
23 /// let d = "abb".chars().collect::<Counter<_>>();
24 ///
25 /// let e = c & d;
26 ///
27 /// let expect = [('a', 1), ('b', 1)].iter().cloned().collect::<HashMap<_, _>>();
28 /// assert_eq!(e.into_map(), expect);
29 /// ```
30 fn bitand(self, mut rhs: Counter<T, N>) -> Self::Output {
31 use std::cmp::min;
32
33 let mut counter = Counter::new();
34 for (key, lhs_count) in self.map {
35 if let Some(rhs_count) = rhs.remove(&key) {
36 let count = min(lhs_count, rhs_count);
37 counter.map.insert(key, count);
38 }
39 }
40 counter
41 }
42 }
43
44 impl<T, N> BitAndAssign for Counter<T, N>
45 where
46 T: Hash + Eq,
47 N: Ord + Zero,
48 {
49 /// Updates `self` with the intersection of `self` and `rhs`
50 ///
51 /// `c &= d;` -> `c[x] == min(c[x], d[x])`
52 ///
53 /// ```rust
54 /// # use counter::Counter;
55 /// # use std::collections::HashMap;
56 /// let mut c = "aaab".chars().collect::<Counter<_>>();
57 /// let d = "abb".chars().collect::<Counter<_>>();
58 ///
59 /// c &= d;
60 ///
61 /// let expect = [('a', 1), ('b', 1)].iter().cloned().collect::<HashMap<_, _>>();
62 /// assert_eq!(c.into_map(), expect);
63 /// ```
64 fn bitand_assign(&mut self, mut rhs: Counter<T, N>) {
65 for (key, rhs_count) in rhs.drain() {
66 if rhs_count < self[&key] {
67 self.map.insert(key, rhs_count);
68 }
69 }
70 }
71 }