| 1 | use crate::Counter; |
| 2 | |
| 3 | use num_traits::Zero; |
| 4 | |
| 5 | use std::hash::Hash; |
| 6 | use std::ops::{Sub, SubAssign}; |
| 7 | |
| 8 | impl<T, N> Sub for Counter<T, N> |
| 9 | where |
| 10 | T: Hash + Eq, |
| 11 | N: PartialOrd + PartialEq + SubAssign + Zero, |
| 12 | { |
| 13 | type Output = Counter<T, N>; |
| 14 | |
| 15 | /// Subtract (keeping only positive values). |
| 16 | /// |
| 17 | /// `out = c - d;` -> `out[x] == c[x] - d[x]` for all `x`, |
| 18 | /// keeping only items with a value greater than [`N::zero()`]. |
| 19 | /// |
| 20 | /// [`N::zero()`]: |
| 21 | /// https://docs.rs/num-traits/latest/num_traits/identities/trait.Zero.html#tymethod.zero |
| 22 | /// |
| 23 | /// ```rust |
| 24 | /// # use counter::Counter; |
| 25 | /// # use std::collections::HashMap; |
| 26 | /// let c = "aaab".chars().collect::<Counter<_>>(); |
| 27 | /// let d = "abb".chars().collect::<Counter<_>>(); |
| 28 | /// |
| 29 | /// let e = c - d; |
| 30 | /// |
| 31 | /// let expect = [('a', 2)].iter().cloned().collect::<HashMap<_, _>>(); |
| 32 | /// assert_eq!(e.into_map(), expect); |
| 33 | /// ``` |
| 34 | fn sub(mut self, rhs: Counter<T, N>) -> Self::Output { |
| 35 | self -= rhs; |
| 36 | self |
| 37 | } |
| 38 | } |
| 39 | |
| 40 | impl<T, N> SubAssign for Counter<T, N> |
| 41 | where |
| 42 | T: Hash + Eq, |
| 43 | N: PartialOrd + PartialEq + SubAssign + Zero, |
| 44 | { |
| 45 | /// Subtract (keeping only positive values). |
| 46 | /// |
| 47 | /// `c -= d;` -> `c[x] -= d[x]` for all `x`, |
| 48 | /// keeping only items with a value greater than [`N::zero()`]. |
| 49 | /// |
| 50 | /// [`N::zero()`]: |
| 51 | /// https://docs.rs/num-traits/latest/num_traits/identities/trait.Zero.html#tymethod.zero |
| 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', 2)].iter().cloned().collect::<HashMap<_, _>>(); |
| 62 | /// assert_eq!(c.into_map(), expect); |
| 63 | /// ``` |
| 64 | fn sub_assign(&mut self, rhs: Self) { |
| 65 | for (key, value) in rhs.map { |
| 66 | let mut remove = false; |
| 67 | if let Some(entry) = self.map.get_mut(&key) { |
| 68 | if *entry >= value { |
| 69 | *entry -= value; |
| 70 | } else { |
| 71 | remove = true; |
| 72 | } |
| 73 | if *entry == N::zero() { |
| 74 | remove = true; |
| 75 | } |
| 76 | } |
| 77 | if remove { |
| 78 | self.map.remove(&key); |
| 79 | } |
| 80 | } |
| 81 | } |
| 82 | } |