Skip to content

Commit 00c2961

Browse files
authored
Rollup merge of rust-lang#90772 - GuillaumeGomez:vec-retain-mut, r=joshtriplett
Add Vec::retain_mut This is to continue the discussion started in rust-lang#83218. Original comment was: > Take 2 of rust-lang#34265, since I needed this today. The reason I think why we should add `retain_mut` is for coherency and for discoverability. For example we have `chunks` and `chunks_mut` or `get` and `get_mut` or `iter` and `iter_mut`, etc. When looking for mutable `retain`, I would expect `retain_mut` to exist. It took me a while to find out about `drain_filter`. So even if it provides an API close to `drain_filter`, just for the discoverability, I think it's worth it. cc ````@m-ou-se```` ````@jonas-schievink```` ````@Mark-Simulacrum````
2 parents 359fef7 + c15b55a commit 00c2961

File tree

1 file changed

+29
-1
lines changed

1 file changed

+29
-1
lines changed

library/alloc/src/vec/mod.rs

+29-1
Original file line numberDiff line numberDiff line change
@@ -1444,6 +1444,34 @@ impl<T, A: Allocator> Vec<T, A> {
14441444
pub fn retain<F>(&mut self, mut f: F)
14451445
where
14461446
F: FnMut(&T) -> bool,
1447+
{
1448+
self.retain_mut(|elem| f(elem));
1449+
}
1450+
1451+
/// Retains only the elements specified by the predicate, passing a mutable reference to it.
1452+
///
1453+
/// In other words, remove all elements `e` such that `f(&mut e)` returns `false`.
1454+
/// This method operates in place, visiting each element exactly once in the
1455+
/// original order, and preserves the order of the retained elements.
1456+
///
1457+
/// # Examples
1458+
///
1459+
/// ```
1460+
/// #![feature(vec_retain_mut)]
1461+
///
1462+
/// let mut vec = vec![1, 2, 3, 4];
1463+
/// vec.retain_mut(|x| if *x > 3 {
1464+
/// false
1465+
/// } else {
1466+
/// *x += 1;
1467+
/// true
1468+
/// });
1469+
/// assert_eq!(vec, [2, 3, 4]);
1470+
/// ```
1471+
#[unstable(feature = "vec_retain_mut", issue = "90829")]
1472+
pub fn retain_mut<F>(&mut self, mut f: F)
1473+
where
1474+
F: FnMut(&mut T) -> bool,
14471475
{
14481476
let original_len = self.len();
14491477
// Avoid double drop if the drop guard is not executed,
@@ -1496,7 +1524,7 @@ impl<T, A: Allocator> Vec<T, A> {
14961524
g: &mut BackshiftOnDrop<'_, T, A>,
14971525
) -> bool
14981526
where
1499-
F: FnMut(&T) -> bool,
1527+
F: FnMut(&mut T) -> bool,
15001528
{
15011529
// SAFETY: Unchecked element must be valid.
15021530
let cur = unsafe { &mut *g.v.as_mut_ptr().add(g.processed_len) };

0 commit comments

Comments
 (0)