From 75f1b7f96fa4e91244a96ba92f615f3213d97519 Mon Sep 17 00:00:00 2001 From: Kevin Ballard Date: Fri, 31 May 2013 18:50:20 -0700 Subject: [PATCH] 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 --- src/libstd/hashmap.rs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/src/libstd/hashmap.rs b/src/libstd/hashmap.rs index 3221ff4730d..fb4cab72126 100644 --- a/src/libstd/hashmap.rs +++ b/src/libstd/hashmap.rs @@ -467,6 +467,14 @@ impl HashMap { self.mangle(k, (), |k,_a| f(k), |_k,_v,_a| ()) } + /// Insert a key-value pair into the map if the key is not already present. + /// Otherwise, modify the existing value for the key. + /// Returns the new or modified value for the key. + pub fn insert_or_update_with<'a>(&'a mut self, k: K, v: V, + f: &fn(&K, &mut V)) -> &'a mut V { + self.mangle(k, v, |_k,a| a, |k,v,_a| f(k,v)) + } + /// Calls a function on each element of a hash map, destroying the hash /// map in the process. pub fn consume(&mut self, f: &fn(K, V)) { @@ -758,6 +766,13 @@ mod test_map { assert_eq!(*m.find_or_insert_with(1, |_| 3), 2); } + #[test] + fn test_insert_or_update_with() { + let mut m = HashMap::new::(); + assert_eq!(*m.insert_or_update_with(1, 2, |_,x| *x+=1), 2); + assert_eq!(*m.insert_or_update_with(1, 2, |_,x| *x+=1), 3); + } + #[test] fn test_consume() { let mut m = HashMap::new();