about summary refs log tree commit diff
path: root/src/liballoc
diff options
context:
space:
mode:
authorChai T. Rex <ChaiTRex@users.noreply.github.com>2020-04-10 12:10:05 -0400
committerChai T. Rex <ChaiTRex@users.noreply.github.com>2020-04-10 12:54:09 -0400
commit921579cc3cdc57dbcfac48b275d92b7927234988 (patch)
tree51cc908210688838c34c306d2d955a0870088095 /src/liballoc
parent93dc97a85381cc52eb872d27e50e4d518926a27c (diff)
downloadrust-921579cc3cdc57dbcfac48b275d92b7927234988.tar.gz
rust-921579cc3cdc57dbcfac48b275d92b7927234988.zip
Add or_insert_with_key to Entry of HashMap/BTreeMap
Going along with or_insert_with, or_insert_with_key provides the
Entry's key to the lambda, avoiding the need to either clone the
key or the need to reimplement this body of this method from
scratch each time.

This is useful when the initial value for a map entry is derived
from the key. For example, the introductory Rust book has an
example Cacher struct that takes an expensive-to-compute lambda and
then can, given an argument to the lambda, produce either the
cached result or execute the lambda.
Diffstat (limited to 'src/liballoc')
-rw-r--r--src/liballoc/collections/btree/map.rs27
1 files changed, 27 insertions, 0 deletions
diff --git a/src/liballoc/collections/btree/map.rs b/src/liballoc/collections/btree/map.rs
index a1e59b2e6af..650582850ab 100644
--- a/src/liballoc/collections/btree/map.rs
+++ b/src/liballoc/collections/btree/map.rs
@@ -2378,6 +2378,33 @@ impl<'a, K: Ord, V> Entry<'a, K, V> {
         }
     }
 
+    #[unstable(feature = "or_insert_with_key", issue = "70996")]
+    /// 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
+    ///
+    /// ```
+    /// use std::collections::BTreeMap;
+    ///
+    /// let mut map: BTreeMap<&str, usize> = BTreeMap::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