about summary refs log tree commit diff
path: root/src/libstd
diff options
context:
space:
mode:
authorbors <bors@rust-lang.org>2017-10-06 12:51:11 +0000
committerbors <bors@rust-lang.org>2017-10-06 12:51:11 +0000
commita8feaee5b6b54c03f49481fe04a9ad9e8f659f7c (patch)
tree4918f2dbd5a71e6157e0e50c1fd71278e5161225 /src/libstd
parent3ed8b698421291f5057059da885cd670d76a47e9 (diff)
parent9e36111fc60ff448bb8c2977dc51ccf0d3e3a3e9 (diff)
downloadrust-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/libstd')
-rw-r--r--src/libstd/collections/hash/map.rs35
1 files changed, 35 insertions, 0 deletions
diff --git a/src/libstd/collections/hash/map.rs b/src/libstd/collections/hash/map.rs
index 406acde1f1c..3c0fa0860d3 100644
--- a/src/libstd/collections/hash/map.rs
+++ b/src/libstd/collections/hash/map.rs
@@ -2013,6 +2013,41 @@ impl<'a, K, 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::HashMap;
+    ///
+    /// let mut map: HashMap<&str, u32> = HashMap::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, V: Default> Entry<'a, K, V> {