@@ -467,6 +467,14 @@ impl<K: Hash + Eq, V> HashMap<K, V> {
467
467
self . mangle ( k, ( ) , |k, _a| f ( k) , |_k, _v, _a| ( ) )
468
468
}
469
469
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
+
470
478
/// Calls a function on each element of a hash map, destroying the hash
471
479
/// map in the process.
472
480
pub fn consume ( & mut self , f : & fn ( K , V ) ) {
@@ -758,6 +766,13 @@ mod test_map {
758
766
assert_eq ! ( * m. find_or_insert_with( 1 , |_| 3 ) , 2 ) ;
759
767
}
760
768
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
+
761
776
#[ test]
762
777
fn test_consume( ) {
763
778
let mut m = HashMap :: new ( ) ;
0 commit comments