Skip to content

Commit 75f1b7f

Browse files
committed
Add new function hashmap.insert_or_update_with()
fn insert_or_update_with<'a>(&'a mut self, k: K, f: &fn(&K, &mut V)) -> &'a V
1 parent 7bc950c commit 75f1b7f

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed

src/libstd/hashmap.rs

+15
Original file line numberDiff line numberDiff line change
@@ -467,6 +467,14 @@ impl<K: Hash + Eq, V> HashMap<K, V> {
467467
self.mangle(k, (), |k,_a| f(k), |_k,_v,_a| ())
468468
}
469469

470+
/// Insert a key-value pair into the map if the key is not already present.
471+
/// Otherwise, modify the existing value for the key.
472+
/// Returns the new or modified value for the key.
473+
pub fn insert_or_update_with<'a>(&'a mut self, k: K, v: V,
474+
f: &fn(&K, &mut V)) -> &'a mut V {
475+
self.mangle(k, v, |_k,a| a, |k,v,_a| f(k,v))
476+
}
477+
470478
/// Calls a function on each element of a hash map, destroying the hash
471479
/// map in the process.
472480
pub fn consume(&mut self, f: &fn(K, V)) {
@@ -758,6 +766,13 @@ mod test_map {
758766
assert_eq!(*m.find_or_insert_with(1, |_| 3), 2);
759767
}
760768

769+
#[test]
770+
fn test_insert_or_update_with() {
771+
let mut m = HashMap::new::<int, int>();
772+
assert_eq!(*m.insert_or_update_with(1, 2, |_,x| *x+=1), 2);
773+
assert_eq!(*m.insert_or_update_with(1, 2, |_,x| *x+=1), 3);
774+
}
775+
761776
#[test]
762777
fn test_consume() {
763778
let mut m = HashMap::new();

0 commit comments

Comments
 (0)