Skip to content

Commit 3c96d40

Browse files
committedSep 28, 2017
Auto merge of #44278 - Binero:master, r=BurntSushi
Allow replacing HashMap entries This is an obvious API hole. At the moment the only way to retrieve an entry from a `HashMap` is to get an entry to it, remove it, and then insert a new entry. This PR allows entries to be replaced.
2 parents 688a858 + d3de465 commit 3c96d40

File tree

1 file changed

+30
-0
lines changed
  • src/libstd/collections/hash

1 file changed

+30
-0
lines changed
 

‎src/libstd/collections/hash/map.rs

+30
Original file line numberDiff line numberDiff line change
@@ -2191,6 +2191,36 @@ impl<'a, K, V> OccupiedEntry<'a, K, V> {
21912191
fn take_key(&mut self) -> Option<K> {
21922192
self.key.take()
21932193
}
2194+
2195+
/// Replaces the entry, returning the old key and value.
2196+
///
2197+
/// # Examples
2198+
///
2199+
/// ```
2200+
/// #![feature(map_entry_replace)]
2201+
/// use std::collections::HashMap;
2202+
/// use std::collections::hash_map::Entry;
2203+
///
2204+
/// let mut map: HashMap<String, u32> = HashMap::new();
2205+
/// map.insert("poneyland".to_string(), 15);
2206+
///
2207+
/// if let Entry::Occupied(entry) = map.entry("poneyland".to_string()) {
2208+
/// let (old_key, old_value): (String, u32) = entry.replace(16);
2209+
/// assert_eq!(old_key, "poneyland");
2210+
/// assert_eq!(old_value, 15);
2211+
/// }
2212+
///
2213+
/// assert_eq!(map.get("poneyland"), Some(&16));
2214+
/// ```
2215+
#[unstable(feature = "map_entry_replace", issue = "44286")]
2216+
pub fn replace(mut self, value: V) -> (K, V) {
2217+
let (old_key, old_value) = self.elem.read_mut();
2218+
2219+
let old_key = mem::replace(old_key, self.key.unwrap());
2220+
let old_value = mem::replace(old_value, value);
2221+
2222+
(old_key, old_value)
2223+
}
21942224
}
21952225

21962226
impl<'a, K: 'a, V: 'a> VacantEntry<'a, K, V> {

0 commit comments

Comments
 (0)
Please sign in to comment.