hashmap_ext/
lib.rs

1#![cfg_attr( features = "unstable"
2           , feature(augmented_assignments, op_assign_traits) )]
3
4//! Extensions to `std::collections::HashMap`
5use std::collections::HashMap;
6use std::collections::hash_map::Entry::{Occupied, Vacant};
7use std::hash::Hash;
8
9#[cfg(features = "unstable")]
10pub struct HashMapAddable<K: Hash + Eq, V>(HashMap<K,V>);
11#[cfg(features = "unstable")]
12impl<K,V> std::ops::AddAssign<(K, V)> for HashMapAddable<K, V>
13where K: Hash + Eq {
14    // type Rhs = (K, V);
15    fn add_assign(&mut self, (key, value): (K, V)) {
16        self.0.insert(key, value);
17    }
18}
19
20pub trait UpdateOr<K, V> {
21    fn update_or<F>(&mut self, key: &K, f: F, default: V)
22    where F: FnOnce(&mut V);
23}
24
25impl<K, V> UpdateOr<K, V> for HashMap<K, V>
26where K: Hash + Eq,
27      K: Copy {
28
29    fn update_or<F>(&mut self, key: &K, f: F, default: V)
30    where F: FnOnce(&mut V) {
31        match self.entry(*key) {
32            Vacant(entry) => { entry.insert(default); }
33          , Occupied(mut entry) => { f(entry.get_mut()); }
34        }
35    }
36
37}
38
39pub trait Update<K, V> {
40    fn update<F>(&mut self, key: &K, f: F)
41    where F: FnOnce(&mut V);
42}
43
44impl<K, V> Update<K, V> for HashMap<K, V>
45where K: Hash + Eq,
46      K: Copy {
47
48    fn update<F>(&mut self, key: &K, f: F)
49    where F: FnOnce(&mut V) {
50        match self.entry(*key) {
51            Vacant(_) => { }
52          , Occupied(mut entry) => { f(entry.get_mut()); }
53        }
54    }
55
56}
57
58
59#[cfg(test)]
60mod tests {
61    #[test]
62    fn it_works() {
63    }
64}