about summary refs log tree commit diff
path: root/src/libstd
diff options
context:
space:
mode:
authorbors <bors@rust-lang.org>2020-04-11 21:19:28 +0000
committerbors <bors@rust-lang.org>2020-04-11 21:19:28 +0000
commit378901d988cd59d29b3643ab6e9cba8a31421271 (patch)
tree1ef481a1cc168d2430993446995091d970917210 /src/libstd
parente82734e56b2a50d38e0937d08f559d15dbe8e46b (diff)
parentd8dcdec2b8603cdb8059488a090b3b81223dcb22 (diff)
downloadrust-378901d988cd59d29b3643ab6e9cba8a31421271.tar.gz
rust-378901d988cd59d29b3643ab6e9cba8a31421271.zip
Auto merge of #71031 - Dylan-DPC:rollup-zr8hh86, r=Dylan-DPC
Rollup of 5 pull requests

Successful merges:

 - #70644 (Clean up `ModuleConfig` initialization)
 - #70937 (Fix staticlib name for *-pc-windows-gnu targets)
 - #70996 (Add or_insert_with_key to Entry of HashMap/BTreeMap)
 - #71020 (Store UNICODE_VERSION as a tuple)
 - #71021 (Use write!-style syntax for MIR assert terminator)

Failed merges:

r? @ghost
Diffstat (limited to 'src/libstd')
-rw-r--r--src/libstd/collections/hash/map.rs28
1 files changed, 28 insertions, 0 deletions
diff --git a/src/libstd/collections/hash/map.rs b/src/libstd/collections/hash/map.rs
index d1cb8e92d56..706b388f783 100644
--- a/src/libstd/collections/hash/map.rs
+++ b/src/libstd/collections/hash/map.rs
@@ -1943,6 +1943,34 @@ impl<'a, K, V> Entry<'a, K, V> {
         }
     }
 
+    #[unstable(feature = "or_insert_with_key", issue = "71024")]
+    /// Ensures a value is in the entry by inserting, if empty, the result of the default function,
+    /// which takes the key as its argument, and returns a mutable reference to the value in the
+    /// entry.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// #![feature(or_insert_with_key)]
+    /// use std::collections::HashMap;
+    ///
+    /// let mut map: HashMap<&str, usize> = HashMap::new();
+    ///
+    /// map.entry("poneyland").or_insert_with_key(|key| key.chars().count());
+    ///
+    /// assert_eq!(map["poneyland"], 9);
+    /// ```
+    #[inline]
+    pub fn or_insert_with_key<F: FnOnce(&K) -> V>(self, default: F) -> &'a mut V {
+        match self {
+            Occupied(entry) => entry.into_mut(),
+            Vacant(entry) => {
+                let value = default(entry.key());
+                entry.insert(value)
+            }
+        }
+    }
+
     /// Returns a reference to this entry's key.
     ///
     /// # Examples