Skip to content

Commit

Permalink
Rollup merge of #90772 - GuillaumeGomez:vec-retain-mut, r=joshtriplett
Browse files Browse the repository at this point in the history
Add Vec::retain_mut

This is to continue the discussion started in #83218.

Original comment was:

> Take 2 of #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``````
  • Loading branch information
matthiaskrgr authored Nov 17, 2021
2 parents ec84633 + c15b55a commit 904dba5
Showing 1 changed file with 29 additions and 1 deletion.
30 changes: 29 additions & 1 deletion library/alloc/src/vec/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1444,6 +1444,34 @@ impl<T, A: Allocator> Vec<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, passing a mutable reference to it.
///
/// In other words, remove all elements `e` such that `f(&mut 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)]
///
/// let mut vec = vec![1, 2, 3, 4];
/// vec.retain_mut(|x| if *x > 3 {
/// false
/// } else {
/// *x += 1;
/// true
/// });
/// assert_eq!(vec, [2, 3, 4]);
/// ```
#[unstable(feature = "vec_retain_mut", issue = "90829")]
pub fn retain_mut<F>(&mut self, mut f: F)
where
F: FnMut(&mut T) -> bool,
{
let original_len = self.len();
// Avoid double drop if the drop guard is not executed,
Expand Down Expand Up @@ -1496,7 +1524,7 @@ impl<T, A: Allocator> Vec<T, A> {
g: &mut BackshiftOnDrop<'_, T, A>,
) -> bool
where
F: FnMut(&T) -> bool,
F: FnMut(&mut T) -> bool,
{
// SAFETY: Unchecked element must be valid.
let cur = unsafe { &mut *g.v.as_mut_ptr().add(g.processed_len) };
Expand Down

0 comments on commit 904dba5

Please sign in to comment.