mozilla/rust — pull request #6815 by kballard (2013-05-29 22:37:01+00:00)
Title: Implement new method HashMap.insert_or_modify_with()

`std::hashmap::HashMap.insert_or_modify_with()` is basically the opposite
of `find_or_insert_with()`. It inserts a given key-value pair if the key
does not already exist, or replaces the existing value with the output
of the passed function if it does.

This is useful because replicating this with existing functionality is awkward, especially with the current borrow-checker. In my own project I have code that looks like

if match map.find_mut(&key) {
None => { true }
Some(x) => { *x += 1; false }
} {
map.insert(key, 0);
}

and it took several iterations to make it look this good. The new function turns this into

map.insert_or_modify_with(key, 0, |&x| x+1);