Skip to content

Commit fa0a4db

Browse files
committed
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.
1 parent f7bb664 commit fa0a4db

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

src/map.rs

+30
Original file line numberDiff line numberDiff line change
@@ -2301,6 +2301,36 @@ impl<'a, K, V, S> Entry<'a, K, V, S> {
23012301
}
23022302
}
23032303

2304+
/// Ensures a value is in the entry by inserting, if empty, the result of the default function,
2305+
/// which takes the key as its argument, and returns a mutable reference to the value in the
2306+
/// entry.
2307+
///
2308+
/// # Examples
2309+
///
2310+
/// ```
2311+
/// use hashbrown::HashMap;
2312+
///
2313+
/// let mut map: HashMap<&str, usize> = HashMap::new();
2314+
///
2315+
/// map.entry("poneyland").or_insert_with_key(|key| key.chars().count());
2316+
///
2317+
/// assert_eq!(map["poneyland"], 9);
2318+
/// ```
2319+
#[cfg_attr(feature = "inline-more", inline)]
2320+
pub fn or_insert_with_key<F: FnOnce(&K) -> V>(self, default: F) -> &'a mut V
2321+
where
2322+
K: Hash,
2323+
S: BuildHasher,
2324+
{
2325+
match self {
2326+
Entry::Occupied(entry) => entry.into_mut(),
2327+
Entry::Vacant(entry) => {
2328+
let value = default(entry.key());
2329+
entry.insert(value)
2330+
}
2331+
}
2332+
}
2333+
23042334
/// Returns a reference to this entry's key.
23052335
///
23062336
/// # Examples

0 commit comments

Comments
 (0)