From eebb54cefe4d0062d08d0c7430f5b04894bd0704 Mon Sep 17 00:00:00 2001 From: Josh Stone Date: Mon, 22 Feb 2021 17:37:51 -0800 Subject: [PATCH] add Entry::or_insert_with_key like Rust 1.50 --- src/map/core.rs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/src/map/core.rs b/src/map/core.rs index 1c261a51..aaa3768a 100644 --- a/src/map/core.rs +++ b/src/map/core.rs @@ -470,6 +470,24 @@ impl<'a, K, V> Entry<'a, K, V> { } } + /// Inserts the result of the `call` function with a reference to the entry's key if it is + /// vacant, and returns a mutable reference to the new value. Otherwise a mutable reference to + /// an already existent value is returned. + /// + /// Computes in **O(1)** time (amortized average). + pub fn or_insert_with_key(self, call: F) -> &'a mut V + where + F: FnOnce(&K) -> V, + { + match self { + Entry::Occupied(entry) => entry.into_mut(), + Entry::Vacant(entry) => { + let value = call(&entry.key); + entry.insert(value) + } + } + } + /// Gets a reference to the entry's key, either within the map if occupied, /// or else the new key that was used to find the entry. pub fn key(&self) -> &K {