From 850e6a714a4fbff8a11b6992fac0a07d5d1aec1f Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Mon, 27 Apr 2015 13:47:19 -0400 Subject: [PATCH] Implement retain for vec_deque --- src/libcollections/vec_deque.rs | 34 +++++++++++++++++++++++++++++ src/libcollectionstest/vec_deque.rs | 9 ++++++++ 2 files changed, 43 insertions(+) diff --git a/src/libcollections/vec_deque.rs b/src/libcollections/vec_deque.rs index 61369b30dea17..dcb9e398240a3 100644 --- a/src/libcollections/vec_deque.rs +++ b/src/libcollections/vec_deque.rs @@ -1396,6 +1396,40 @@ impl VecDeque { // naive impl self.extend(other.drain()); } + + /// 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 and preserves the order of the retained + /// elements. + /// + /// # Examples + /// + /// ``` + /// use std::collections::VecDeque; + /// + /// let mut buf = VecDeque::new(); + /// buf.extend(1..5); + /// buf.retain(|&x| x%2 == 0); + /// + /// let v: Vec<_> = buf.into_iter().collect(); + /// assert_eq!(&v[..], &[2, 4]); + /// ``` + #[stable(feature = "vec_deque_retain", since = "1.1.0")] + pub fn retain(&mut self, mut f: F) where F: FnMut(&T) -> bool { + let len = self.len(); + let mut del = 0; + for i in 0..len { + if !f(&self[i]) { + del += 1; + } else if del > 0 { + self.swap(i-del, i); + } + } + if del > 0 { + self.truncate(len - del); + } + } } impl VecDeque { diff --git a/src/libcollectionstest/vec_deque.rs b/src/libcollectionstest/vec_deque.rs index 12323286f6b4b..7870447281bc1 100644 --- a/src/libcollectionstest/vec_deque.rs +++ b/src/libcollectionstest/vec_deque.rs @@ -885,3 +885,12 @@ fn test_append() { assert_eq!(b.iter().cloned().collect::>(), [1, 2, 3, 4, 5, 6]); assert_eq!(a.iter().cloned().collect::>(), []); } + +#[test] +fn test_retain() { + let mut buf = VecDeque::new(); + buf.extend(1..5); + buf.retain(|&x| x % 2 == 0); + let v: Vec<_> = buf.into_iter().collect(); + assert_eq!(&v[..], &[2, 4]); +}