Skip to content

Commit

Permalink
Implement retain for vec_deque
Browse files Browse the repository at this point in the history
  • Loading branch information
Stebalien committed Apr 28, 2015
1 parent d8b64c7 commit 850e6a7
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
34 changes: 34 additions & 0 deletions src/libcollections/vec_deque.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1396,6 +1396,40 @@ impl<T> VecDeque<T> {
// 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<F>(&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<T: Clone> VecDeque<T> {
Expand Down
9 changes: 9 additions & 0 deletions src/libcollectionstest/vec_deque.rs
Original file line number Diff line number Diff line change
Expand Up @@ -885,3 +885,12 @@ fn test_append() {
assert_eq!(b.iter().cloned().collect::<Vec<_>>(), [1, 2, 3, 4, 5, 6]);
assert_eq!(a.iter().cloned().collect::<Vec<_>>(), []);
}

#[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]);
}

0 comments on commit 850e6a7

Please sign in to comment.