Debian Codegraph @

src/impls/union.rs

raw symbols SCIP
1 use crate::Counter;
2
3 use num_traits::Zero;
4
5 use std::hash::Hash;
6 use std::ops::{BitOr, BitOrAssign};
7
8 impl<T, N> BitOr 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 union of `self` and `rhs` as a new `Counter`.
16 ///
17 /// `out = c | d;` -> `out[x] == max(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', 3), ('b', 2)].iter().cloned().collect::<HashMap<_, _>>();
28 /// assert_eq!(e.into_map(), expect);
29 /// ```
30 fn bitor(mut self, rhs: Counter<T, N>) -> Self::Output {
31 for (key, rhs_value) in rhs.map {
32 let entry = self.map.entry(key).or_insert_with(N::zero);
33 // We want to update the value of the now occupied entry in `self` with the maximum of
34 // its current value and `rhs_value`. If that max is `rhs_value`, we can just update
35 // the value of the entry. If the max is the current value, we do nothing. Note that
36 // `Ord::max()` returns the second argument (here `rhs_value`) if its two arguments are
37 // equal, justifying the use of the weak inequality below instead of a strict
38 // inequality.
39 //
40 // Doing it this way with an inequality instead of actually using `std::cmp::max()`
41 // lets us avoid trying (and failing) to move the non-copy value out of the entry in
42 // order to pass it as an argument to `std::cmp::max()`, while still holding a mutable
43 // reference to the value slot in the entry.
44 //
45 // And while using the inequality seemingly only requires the bound `N: PartialOrd`, we
46 // nevertheless prefer to require `Ord` as though we were using `std::cmp::max()`
47 // because the semantics of `BitOr` for `Counter` really do not make sense if there are
48 // possibly non-comparable values of type `N`.
49 if rhs_value >= *entry {
50 *entry = rhs_value;
51 }
52 }
53 self
54 }
55 }
56
57 impl<T, N> BitOrAssign for Counter<T, N>
58 where
59 T: Hash + Eq,
60 N: Ord + Zero,
61 {
62 /// Updates `self` with the union of `self` and `rhs`
63 ///
64 /// `c |= d;` -> `c[x] == max(c[x], d[x])`
65 ///
66 /// ```rust
67 /// # use counter::Counter;
68 /// # use std::collections::HashMap;
69 /// let mut c = "aaab".chars().collect::<Counter<_>>();
70 /// let d = "abb".chars().collect::<Counter<_>>();
71 ///
72 /// c |= d;
73 ///
74 /// let expect = [('a', 3), ('b', 2)].iter().cloned().collect::<HashMap<_, _>>();
75 /// assert_eq!(c.into_map(), expect);
76 /// ```
77 fn bitor_assign(&mut self, mut rhs: Counter<T, N>) {
78 for (key, rhs_count) in rhs.drain() {
79 if rhs_count > self[&key] {
80 self.map.insert(key, rhs_count);
81 }
82 }
83 }
84 }