Auto merge of #24879 - Stebalien:vec_deque, r=alexcrichton

According to rust-lang/rfcs#235, `VecDeque` should have this method (`VecDeque` was called `RingBuf` at the time) but it was never implemented.

I marked this stable since "1.0.0" because it's stable in `Vec`.
This commit is contained in:
bors 2015-05-06 03:33:42 +00:00
commit 5b04c16bd6
3 changed files with 46 additions and 0 deletions

View File

@ -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> {

View File

@ -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;

View File

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