1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#[cfg(test)]
#[path = "collection_arithmetics_test.rs"]
mod test;

use std::hash::Hash;
use std::ops::{Add, Sub};

use crate::ordered_hash_map::OrderedHashMap;

/// A trait for types which have a zero value.
///
/// Functions may assume the following:
/// * `x = x + zero() = zero() + x`
pub trait HasZero {
    /// Returns the zero value for the type.
    fn zero() -> Self;
}
impl HasZero for i32 {
    fn zero() -> Self {
        0
    }
}
impl HasZero for i64 {
    fn zero() -> Self {
        0
    }
}

/// Returns a map which contains the sum of the values from the given two maps, for each key.
///
/// If the key is missing from one of them, it is treated as zero.
pub fn add_maps<Key: Hash + Eq, Value: HasZero + Add<Output = Value> + Clone + Eq>(
    lhs: OrderedHashMap<Key, Value>,
    rhs: OrderedHashMap<Key, Value>,
) -> OrderedHashMap<Key, Value> {
    let mut res = lhs;
    for (key, rhs_val) in rhs {
        let lhs_val = res.get(&key).cloned().unwrap_or_else(Value::zero);
        let new_val = lhs_val + rhs_val;
        if new_val == Value::zero() {
            res.swap_remove(&key);
        } else {
            res.insert(key, new_val);
        }
    }
    res
}

/// Returns a map which contains the difference of the values from the given two maps, for each key.
///
/// If the key is missing from one of them, it is treated as zero.
pub fn sub_maps<Key: Hash + Eq, Value: HasZero + Sub<Output = Value> + Clone + Eq>(
    lhs: OrderedHashMap<Key, Value>,
    rhs: OrderedHashMap<Key, Value>,
) -> OrderedHashMap<Key, Value> {
    let mut res = lhs;
    for (key, rhs_val) in rhs {
        let lhs_val = res.get(&key).cloned().unwrap_or_else(Value::zero);
        let new_val = lhs_val - rhs_val;
        if new_val == Value::zero() {
            res.swap_remove(&key);
        } else {
            res.insert(key, new_val);
        }
    }
    res
}