about summary refs log tree commit diff
diff options
context:
space:
mode:
authorStein Somers <git@steinsomers.be>2020-04-05 18:56:07 +0200
committerStein Somers <git@steinsomers.be>2020-04-06 19:56:29 +0200
commit8212b9772e486ae272639fb22ee3b6e7f9047d3f (patch)
tree1316a202333b0dee627da4615d64205090ffb240
parentc23ee767d94a8ea5e0aa782731f89f4e00fbdc7e (diff)
downloadrust-8212b9772e486ae272639fb22ee3b6e7f9047d3f.tar.gz
rust-8212b9772e486ae272639fb22ee3b6e7f9047d3f.zip
BTreeMap first/last: add pop methods
-rw-r--r--src/liballoc/collections/btree/map.rs48
1 files changed, 48 insertions, 0 deletions
diff --git a/src/liballoc/collections/btree/map.rs b/src/liballoc/collections/btree/map.rs
index d550856b6ed..a1e59b2e6af 100644
--- a/src/liballoc/collections/btree/map.rs
+++ b/src/liballoc/collections/btree/map.rs
@@ -689,6 +689,30 @@ impl<K: Ord, V> BTreeMap<K, V> {
         })
     }
 
+    /// Removes and returns the first element in the map.
+    /// The key of this element is the minimum key that was in the map.
+    ///
+    /// # Examples
+    ///
+    /// Draining elements in ascending order, while keeping a usable map each iteration.
+    ///
+    /// ```
+    /// #![feature(map_first_last)]
+    /// use std::collections::BTreeMap;
+    ///
+    /// let mut map = BTreeMap::new();
+    /// map.insert(1, "a");
+    /// map.insert(2, "b");
+    /// while let Some((key, _val)) = map.pop_first() {
+    ///     assert!(map.iter().all(|(k, _v)| *k > key));
+    /// }
+    /// assert!(map.is_empty());
+    /// ```
+    #[unstable(feature = "map_first_last", issue = "62924")]
+    pub fn pop_first(&mut self) -> Option<(K, V)> {
+        self.first_entry().map(|entry| entry.remove_entry())
+    }
+
     /// Returns the last key-value pair in the map.
     /// The key in this pair is the maximum key in the map.
     ///
@@ -742,6 +766,30 @@ impl<K: Ord, V> BTreeMap<K, V> {
         })
     }
 
+    /// Removes and returns the last element in the map.
+    /// The key of this element is the maximum key that was in the map.
+    ///
+    /// # Examples
+    ///
+    /// Draining elements in descending order, while keeping a usable map each iteration.
+    ///
+    /// ```
+    /// #![feature(map_first_last)]
+    /// use std::collections::BTreeMap;
+    ///
+    /// let mut map = BTreeMap::new();
+    /// map.insert(1, "a");
+    /// map.insert(2, "b");
+    /// while let Some((key, _val)) = map.pop_last() {
+    ///     assert!(map.iter().all(|(k, _v)| *k < key));
+    /// }
+    /// assert!(map.is_empty());
+    /// ```
+    #[unstable(feature = "map_first_last", issue = "62924")]
+    pub fn pop_last(&mut self) -> Option<(K, V)> {
+        self.last_entry().map(|entry| entry.remove_entry())
+    }
+
     /// Returns `true` if the map contains a value for the specified key.
     ///
     /// The key may be any borrowed form of the map's key type, but the ordering