Skip to content

Commit

Permalink
Auto merge of #152 - ChaiTRex:master, r=Amanieu
Browse files Browse the repository at this point in the history
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 rust-lang/rust#70996 and intended to sync the APIs of `std` and `hashbrown`.
  • Loading branch information
bors committed Apr 11, 2020
2 parents f7bb664 + fa0a4db commit d2414e4
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions src/map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<F: FnOnce(&K) -> 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
Expand Down

0 comments on commit d2414e4

Please sign in to comment.