about summary refs log tree commit diff
path: root/src/libstd/collections
diff options
context:
space:
mode:
authorbors <bors@rust-lang.org>2017-09-28 18:52:49 +0000
committerbors <bors@rust-lang.org>2017-09-28 18:52:49 +0000
commit3c96d40d326b64f6a50f4a902051fe71c4acdc92 (patch)
tree5ff7baf61d9aa339663351e92aec01b3c9d21015 /src/libstd/collections
parent688a8583912a305f14ebc8bc21a2dd3cd3c912b0 (diff)
parentd3de465dc85638a6a77298638ebbbfab04b1844d (diff)
downloadrust-3c96d40d326b64f6a50f4a902051fe71c4acdc92.tar.gz
rust-3c96d40d326b64f6a50f4a902051fe71c4acdc92.zip
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.
Diffstat (limited to 'src/libstd/collections')
-rw-r--r--src/libstd/collections/hash/map.rs30
1 files changed, 30 insertions, 0 deletions
diff --git a/src/libstd/collections/hash/map.rs b/src/libstd/collections/hash/map.rs
index 96af2272578..026b863b963 100644
--- a/src/libstd/collections/hash/map.rs
+++ b/src/libstd/collections/hash/map.rs
@@ -2191,6 +2191,36 @@ impl<'a, K, V> OccupiedEntry<'a, K, V> {
     fn take_key(&mut self) -> Option<K> {
         self.key.take()
     }
+
+    /// Replaces the entry, returning the old key and value.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// #![feature(map_entry_replace)]
+    /// use std::collections::HashMap;
+    /// use std::collections::hash_map::Entry;
+    ///
+    /// let mut map: HashMap<String, u32> = HashMap::new();
+    /// map.insert("poneyland".to_string(), 15);
+    ///
+    /// if let Entry::Occupied(entry) = map.entry("poneyland".to_string()) {
+    ///     let (old_key, old_value): (String, u32) = entry.replace(16);
+    ///     assert_eq!(old_key, "poneyland");
+    ///     assert_eq!(old_value, 15);
+    /// }
+    ///
+    /// assert_eq!(map.get("poneyland"), Some(&16));
+    /// ```
+    #[unstable(feature = "map_entry_replace", issue = "44286")]
+    pub fn replace(mut self, value: V) -> (K, V) {
+        let (old_key, old_value) = self.elem.read_mut();
+
+        let old_key = mem::replace(old_key, self.key.unwrap());
+        let old_value = mem::replace(old_value, value);
+
+        (old_key, old_value)
+    }
 }
 
 impl<'a, K: 'a, V: 'a> VacantEntry<'a, K, V> {