| 1 | use crate::Counter; |
| 2 | |
| 3 | use num_traits::{One, Zero}; |
| 4 | |
| 5 | use std::hash::Hash; |
| 6 | use std::ops::{Sub, SubAssign}; |
| 7 | |
| 8 | impl<I, T, N> Sub<I> for Counter<T, N> |
| 9 | where |
| 10 | I: IntoIterator<Item = T>, |
| 11 | T: Hash + Eq, |
| 12 | N: PartialOrd + SubAssign + Zero + One, |
| 13 | { |
| 14 | type Output = Self; |
| 15 | /// Consume `self` producing a `Counter` like `self` with the counts of the |
| 16 | /// elements of `I` subtracted, keeping only positive values. |
| 17 | /// |
| 18 | /// ```rust |
| 19 | /// # use counter::Counter; |
| 20 | /// # use std::collections::HashMap; |
| 21 | /// let c = "aaab".chars().collect::<Counter<_>>(); |
| 22 | /// let e = c - "abb".chars(); |
| 23 | /// |
| 24 | /// let expect = [('a', 2)].iter().cloned().collect::<HashMap<_, _>>(); |
| 25 | /// assert_eq!(e.into_map(), expect); |
| 26 | /// ``` |
| 27 | fn sub(mut self, rhs: I) -> Self::Output { |
| 28 | self.subtract(rhs); |
| 29 | self |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | impl<I, T, N> SubAssign<I> for Counter<T, N> |
| 34 | where |
| 35 | I: IntoIterator<Item = T>, |
| 36 | T: Hash + Eq, |
| 37 | N: PartialOrd + SubAssign + Zero + One, |
| 38 | { |
| 39 | /// Directly subtract the counts of the elements of `I` from `self`, |
| 40 | /// keeping only items with a value greater than [`N::zero()`]. |
| 41 | /// |
| 42 | /// [`N::zero()`]: |
| 43 | /// https://docs.rs/num-traits/latest/num_traits/identities/trait.Zero.html#tymethod.zero |
| 44 | /// |
| 45 | /// ```rust |
| 46 | /// # use counter::Counter; |
| 47 | /// # use std::collections::HashMap; |
| 48 | /// let mut c = "aaab".chars().collect::<Counter<_>>(); |
| 49 | /// c -= "abb".chars(); |
| 50 | /// |
| 51 | /// let expect = [('a', 2)].iter().cloned().collect::<HashMap<_, _>>(); |
| 52 | /// assert_eq!(c.into_map(), expect); |
| 53 | /// ``` |
| 54 | fn sub_assign(&mut self, rhs: I) { |
| 55 | self.subtract(rhs); |
| 56 | } |
| 57 | } |