Skip to content

Commit 4af985a

Browse files
authored
Rollup merge of #91215 - GuillaumeGomez:vec-deque-retain-mut, r=m-ou-se
Implement VecDeque::retain_mut Part of #90829. In #90772, someone suggested that `retain_mut` should also be implemented on `VecDeque`. I think that it follows the same logic (coherency). So first: is it ok? Second: should I create a new feature for it or can we put it into the same one? r? `@joshtriplett`
2 parents 1f2a26e + 0466a12 commit 4af985a

File tree

1 file changed

+34
-3
lines changed
  • library/alloc/src/collections/vec_deque

1 file changed

+34
-3
lines changed

library/alloc/src/collections/vec_deque/mod.rs

+34-3
Original file line numberDiff line numberDiff line change
@@ -2148,14 +2148,45 @@ impl<T, A: Allocator> VecDeque<T, A> {
21482148
pub fn retain<F>(&mut self, mut f: F)
21492149
where
21502150
F: FnMut(&T) -> bool,
2151+
{
2152+
self.retain_mut(|elem| f(elem));
2153+
}
2154+
2155+
/// Retains only the elements specified by the predicate.
2156+
///
2157+
/// In other words, remove all elements `e` such that `f(&e)` returns false.
2158+
/// This method operates in place, visiting each element exactly once in the
2159+
/// original order, and preserves the order of the retained elements.
2160+
///
2161+
/// # Examples
2162+
///
2163+
/// ```
2164+
/// #![feature(vec_retain_mut)]
2165+
///
2166+
/// use std::collections::VecDeque;
2167+
///
2168+
/// let mut buf = VecDeque::new();
2169+
/// buf.extend(1..5);
2170+
/// buf.retain_mut(|x| if *x % 2 == 0 {
2171+
/// *x += 1;
2172+
/// true
2173+
/// } else {
2174+
/// false
2175+
/// });
2176+
/// assert_eq!(buf, [3, 5]);
2177+
/// ```
2178+
#[unstable(feature = "vec_retain_mut", issue = "90829")]
2179+
pub fn retain_mut<F>(&mut self, mut f: F)
2180+
where
2181+
F: FnMut(&mut T) -> bool,
21512182
{
21522183
let len = self.len();
21532184
let mut idx = 0;
21542185
let mut cur = 0;
21552186

21562187
// Stage 1: All values are retained.
21572188
while cur < len {
2158-
if !f(&self[cur]) {
2189+
if !f(&mut self[cur]) {
21592190
cur += 1;
21602191
break;
21612192
}
@@ -2164,7 +2195,7 @@ impl<T, A: Allocator> VecDeque<T, A> {
21642195
}
21652196
// Stage 2: Swap retained value into current idx.
21662197
while cur < len {
2167-
if !f(&self[cur]) {
2198+
if !f(&mut self[cur]) {
21682199
cur += 1;
21692200
continue;
21702201
}
@@ -2173,7 +2204,7 @@ impl<T, A: Allocator> VecDeque<T, A> {
21732204
cur += 1;
21742205
idx += 1;
21752206
}
2176-
// Stage 3: Trancate all values after idx.
2207+
// Stage 3: Truncate all values after idx.
21772208
if cur != idx {
21782209
self.truncate(idx);
21792210
}

0 commit comments

Comments
 (0)