Skip to content

Commit 1f1e049

Browse files
authored
Merge pull request rust-lang#175 from cuviper/or_insert_with_key
add Entry::or_insert_with_key like Rust 1.50
2 parents ddc2088 + eebb54c commit 1f1e049

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

src/map/core.rs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -470,6 +470,24 @@ impl<'a, K, V> Entry<'a, K, V> {
470470
}
471471
}
472472

473+
/// Inserts the result of the `call` function with a reference to the entry's key if it is
474+
/// vacant, and returns a mutable reference to the new value. Otherwise a mutable reference to
475+
/// an already existent value is returned.
476+
///
477+
/// Computes in **O(1)** time (amortized average).
478+
pub fn or_insert_with_key<F>(self, call: F) -> &'a mut V
479+
where
480+
F: FnOnce(&K) -> V,
481+
{
482+
match self {
483+
Entry::Occupied(entry) => entry.into_mut(),
484+
Entry::Vacant(entry) => {
485+
let value = call(&entry.key);
486+
entry.insert(value)
487+
}
488+
}
489+
}
490+
473491
/// Gets a reference to the entry's key, either within the map if occupied,
474492
/// or else the new key that was used to find the entry.
475493
pub fn key(&self) -> &K {

0 commit comments

Comments
 (0)