about summary refs log tree commit diff
path: root/src/libstd/hashmap.rs
diff options
context:
space:
mode:
authorKevin Ballard <kevin@sb.org>2013-05-31 18:50:20 -0700
committerKevin Ballard <kevin@sb.org>2013-06-01 17:38:24 -0700
commit75f1b7f96fa4e91244a96ba92f615f3213d97519 (patch)
tree72693fb1f25d3d5c8465365e2a7646d4b6c03cd2 /src/libstd/hashmap.rs
parent7bc950c43c820b0a0cfeede7dcf2d719625dbd90 (diff)
downloadrust-75f1b7f96fa4e91244a96ba92f615f3213d97519.tar.gz
rust-75f1b7f96fa4e91244a96ba92f615f3213d97519.zip
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
Diffstat (limited to 'src/libstd/hashmap.rs')
-rw-r--r--src/libstd/hashmap.rs15
1 files changed, 15 insertions, 0 deletions
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<K: Hash + Eq, V> HashMap<K, V> {
         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)) {
@@ -759,6 +767,13 @@ mod test_map {
     }
 
     #[test]
+    fn test_insert_or_update_with() {
+        let mut m = HashMap::new::<int, int>();
+        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();
         assert!(m.insert(1, 2));