Advertisement
Guest User

Untitled

a guest
Oct 15th, 2019
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.87 KB | None | 0 0
  1. use std::collections::HashMap;
  2. use std::hash::Hash;
  3.  
  4. // you can also change the default hashing algo
  5.  
  6. struct KVStore<K, V>(HashMap<K, V>);
  7.  
  8. impl<K, V> KVStore<K, V>
  9. where
  10. K: Eq + Hash,
  11. {
  12. fn new(vals: Vec<(K, V)>) -> Self {
  13. let mut inner = HashMap::new();
  14. for (k, v) in vals {
  15. inner.insert(k, v);
  16. }
  17. KVStore(inner)
  18. }
  19. fn get(&self, key: &K) -> Option<&V> {
  20. self.0.get(key)
  21. }
  22.  
  23. fn update<F: Fn(&mut V)>(&mut self, key: &K, f: &F) {
  24. // just to update or you could use entries api
  25. if let Some(mut val) = self.0.get_mut(key) {
  26. f(&mut val)
  27. }
  28. }
  29. }
  30.  
  31. fn main() {
  32. // or make new load key value pairs from some restricted source.
  33. let mut kv_store = KVStore::new(vec![(1, 1), (2, 2), (3, 3)]);
  34. kv_store.update(&2, &|v| *v += 1);
  35. println!("{:?}", kv_store.get(&2));
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement