diff options
| author | bors <bors@rust-lang.org> | 2017-10-06 12:51:11 +0000 |
|---|---|---|
| committer | bors <bors@rust-lang.org> | 2017-10-06 12:51:11 +0000 |
| commit | a8feaee5b6b54c03f49481fe04a9ad9e8f659f7c (patch) | |
| tree | 4918f2dbd5a71e6157e0e50c1fd71278e5161225 /src/liballoc | |
| parent | 3ed8b698421291f5057059da885cd670d76a47e9 (diff) | |
| parent | 9e36111fc60ff448bb8c2977dc51ccf0d3e3a3e9 (diff) | |
| download | rust-a8feaee5b6b54c03f49481fe04a9ad9e8f659f7c.tar.gz rust-a8feaee5b6b54c03f49481fe04a9ad9e8f659f7c.zip | |
Auto merge of #44734 - mchlrhw:wip/hashmap-entry-and-then, r=BurntSushi
Implement `and_modify` on `Entry` ## Motivation `Entry`s are useful for allowing access to existing values in a map while also allowing default values to be inserted for absent keys. The existing API is similar to that of `Option`, where `or` and `or_with` can be used if the option variant is `None`. The `Entry` API is, however, missing an equivalent of `Option`'s `and_then` method. If it were present it would be possible to modify an existing entry before calling `or_insert` without resorting to matching on the entry variant. Tracking issue: https://github.com/rust-lang/rust/issues/44733.
Diffstat (limited to 'src/liballoc')
| -rw-r--r-- | src/liballoc/btree/map.rs | 34 |
1 files changed, 34 insertions, 0 deletions
diff --git a/src/liballoc/btree/map.rs b/src/liballoc/btree/map.rs index 4c93fead172..b114dc640fb 100644 --- a/src/liballoc/btree/map.rs +++ b/src/liballoc/btree/map.rs @@ -2102,6 +2102,40 @@ impl<'a, K: Ord, V> Entry<'a, K, V> { Vacant(ref entry) => entry.key(), } } + + /// Provides in-place mutable access to an occupied entry before any + /// potential inserts into the map. + /// + /// # Examples + /// + /// ``` + /// #![feature(entry_and_modify)] + /// use std::collections::BTreeMap; + /// + /// let mut map: BTreeMap<&str, usize> = BTreeMap::new(); + /// + /// map.entry("poneyland") + /// .and_modify(|e| { *e += 1 }) + /// .or_insert(42); + /// assert_eq!(map["poneyland"], 42); + /// + /// map.entry("poneyland") + /// .and_modify(|e| { *e += 1 }) + /// .or_insert(42); + /// assert_eq!(map["poneyland"], 43); + /// ``` + #[unstable(feature = "entry_and_modify", issue = "44733")] + pub fn and_modify<F>(self, mut f: F) -> Self + where F: FnMut(&mut V) + { + match self { + Occupied(mut entry) => { + f(entry.get_mut()); + Occupied(entry) + }, + Vacant(entry) => Vacant(entry), + } + } } impl<'a, K: Ord, V: Default> Entry<'a, K, V> { |
