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 May 5, 2015
1 parent 9b481f8 commit decf395
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 0 deletions.
36 changes: 36 additions & 0 deletions src/libcollections/vec_deque.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1395,6 +1395,42 @@ 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
///
/// ```
/// # #![feature(vec_deque_retain)]
/// 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]);
/// ```
#[unstable(feature = "vec_deque_retain",
reason = "new API, waiting for dust to settle")]
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
1 change: 1 addition & 0 deletions src/libcollectionstest/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
#![feature(into_cow)]
#![feature(step_by)]
#![cfg_attr(test, feature(str_char))]
#![cfg_attr(test, feature(vec_deque_retain))]

#[macro_use] extern crate log;

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 decf395

Please sign in to comment.