about summary refs log tree commit diff
diff options
context:
space:
mode:
authorGuillaume Gomez <guillaume.gomez@huawei.com>2021-11-25 11:48:31 +0100
committerGuillaume Gomez <guillaume.gomez@huawei.com>2021-11-25 13:28:31 +0100
commit0466a1256f46fac36cbdfcabe08153c8d0763cbd (patch)
treecd5b54a74f41bb5d723eee4415fa2c871e881a06
parentc6a7ca196a707acd65e6cce1d337cd11786c59a5 (diff)
downloadrust-0466a1256f46fac36cbdfcabe08153c8d0763cbd.tar.gz
rust-0466a1256f46fac36cbdfcabe08153c8d0763cbd.zip
Implement VecDeque::retain_mut
-rw-r--r--library/alloc/src/collections/vec_deque/mod.rs37
1 files changed, 34 insertions, 3 deletions
diff --git a/library/alloc/src/collections/vec_deque/mod.rs b/library/alloc/src/collections/vec_deque/mod.rs
index de607c8fdab..18c945e1c06 100644
--- a/library/alloc/src/collections/vec_deque/mod.rs
+++ b/library/alloc/src/collections/vec_deque/mod.rs
@@ -2149,13 +2149,44 @@ impl<T, A: Allocator> VecDeque<T, A> {
     where
         F: FnMut(&T) -> bool,
     {
+        self.retain_mut(|elem| f(elem));
+    }
+
+    /// Retains only the elements specified by the predicate.
+    ///
+    /// In other words, remove all elements `e` such that `f(&e)` returns false.
+    /// This method operates in place, visiting each element exactly once in the
+    /// original order, and preserves the order of the retained elements.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// #![feature(vec_retain_mut)]
+    ///
+    /// use std::collections::VecDeque;
+    ///
+    /// let mut buf = VecDeque::new();
+    /// buf.extend(1..5);
+    /// buf.retain_mut(|x| if *x % 2 == 0 {
+    ///     *x += 1;
+    ///     true
+    /// } else {
+    ///     false
+    /// });
+    /// assert_eq!(buf, [3, 5]);
+    /// ```
+    #[unstable(feature = "vec_retain_mut", issue = "90829")]
+    pub fn retain_mut<F>(&mut self, mut f: F)
+    where
+        F: FnMut(&mut T) -> bool,
+    {
         let len = self.len();
         let mut idx = 0;
         let mut cur = 0;
 
         // Stage 1: All values are retained.
         while cur < len {
-            if !f(&self[cur]) {
+            if !f(&mut self[cur]) {
                 cur += 1;
                 break;
             }
@@ -2164,7 +2195,7 @@ impl<T, A: Allocator> VecDeque<T, A> {
         }
         // Stage 2: Swap retained value into current idx.
         while cur < len {
-            if !f(&self[cur]) {
+            if !f(&mut self[cur]) {
                 cur += 1;
                 continue;
             }
@@ -2173,7 +2204,7 @@ impl<T, A: Allocator> VecDeque<T, A> {
             cur += 1;
             idx += 1;
         }
-        // Stage 3: Trancate all values after idx.
+        // Stage 3: Truncate all values after idx.
         if cur != idx {
             self.truncate(idx);
         }