Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement VecDeque::retain_mut #91215

Merged
merged 1 commit into from
Dec 5, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 34 additions & 3 deletions library/alloc/src/collections/vec_deque/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2148,14 +2148,45 @@ impl<T, A: Allocator> VecDeque<T, A> {
pub fn retain<F>(&mut self, mut f: F)
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;
}
Expand All @@ -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;
}
Expand All @@ -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);
}
Expand Down