From fa0a4dbf1bbd9465a973de699da68fdb826fa9e9 Mon Sep 17 00:00:00 2001 From: "Chai T. Rex" Date: Sat, 11 Apr 2020 08:35:22 -0400 Subject: [PATCH] Add or_insert_with_key to Entry of HashMap 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. This is modified from https://github.com/rust-lang/rust/pull/70996. --- src/map.rs | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/src/map.rs b/src/map.rs index edb9401507..2689332e03 100644 --- a/src/map.rs +++ b/src/map.rs @@ -2301,6 +2301,36 @@ impl<'a, K, V, S> Entry<'a, K, V, S> { } } + /// 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 hashbrown::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); + /// ``` + #[cfg_attr(feature = "inline-more", inline)] + pub fn or_insert_with_key V>(self, default: F) -> &'a mut V + where + K: Hash, + S: BuildHasher, + { + match self { + Entry::Occupied(entry) => entry.into_mut(), + Entry::Vacant(entry) => { + let value = default(entry.key()); + entry.insert(value) + } + } + } + /// Returns a reference to this entry's key. /// /// # Examples