about summary refs log tree commit diff
path: root/src/libstd/collections
diff options
context:
space:
mode:
authorJeroen Bollen <contact@jeroenbollen.eu>2017-09-02 23:44:21 +0200
committerJeroen Bollen <contact@jeroenbollen.eu>2017-09-03 00:19:56 +0200
commite9f01bcf68b7f01c4b05422068adb3872f68cbaf (patch)
treeb9d291f9eae978484f4550430339fc8297c51a4f /src/libstd/collections
parent204c0a47e7b7e371cf1cdc159404d405b86386ba (diff)
downloadrust-e9f01bcf68b7f01c4b05422068adb3872f68cbaf.tar.gz
rust-e9f01bcf68b7f01c4b05422068adb3872f68cbaf.zip
Added a way to retrieve the key out of a HashMap when it's being 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 16b0c709986..6eb6f892f80 100644
--- a/src/libstd/collections/hash/map.rs
+++ b/src/libstd/collections/hash/map.rs
@@ -2161,6 +2161,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
+    ///
+    /// ```
+    /// use std::collections::HashMap;
+    /// use std::collections::hash_map::Entry;
+    ///
+    /// let mut map: HashMap<String, u32> = HashMap::new();
+    /// map.insert(String::from("poneyland"), 15);
+    ///
+    /// if let Entry::Occupied(entry) = map.entry(String::from("poneyland")) {
+    ///     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));
+    ///
+    /// ```
+    #[stable(feature = "rust1", since = "1.20.0")]
+    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> {