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
#![cfg_attr( features = "unstable"
, feature(augmented_assignments, op_assign_traits) )]
use std::collections::HashMap;
use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::hash::Hash;
#[cfg(features = "unstable")]
pub struct HashMapAddable<K: Hash + Eq, V>(HashMap<K,V>);
#[cfg(features = "unstable")]
impl<K,V> std::ops::AddAssign<(K, V)> for HashMapAddable<K, V>
where K: Hash + Eq {
fn add_assign(&mut self, (key, value): (K, V)) {
self.0.insert(key, value);
}
}
pub trait UpdateOr<K, V> {
fn update_or<F>(&mut self, key: &K, f: F, default: V)
where F: FnOnce(&mut V);
}
impl<K, V> UpdateOr<K, V> for HashMap<K, V>
where K: Hash + Eq,
K: Copy {
fn update_or<F>(&mut self, key: &K, f: F, default: V)
where F: FnOnce(&mut V) {
match self.entry(*key) {
Vacant(entry) => { entry.insert(default); }
, Occupied(mut entry) => { f(entry.get_mut()); }
}
}
}
pub trait Update<K, V> {
fn update<F>(&mut self, key: &K, f: F)
where F: FnOnce(&mut V);
}
impl<K, V> Update<K, V> for HashMap<K, V>
where K: Hash + Eq,
K: Copy {
fn update<F>(&mut self, key: &K, f: F)
where F: FnOnce(&mut V) {
match self.entry(*key) {
Vacant(_) => { }
, Occupied(mut entry) => { f(entry.get_mut()); }
}
}
}
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
}
}