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

Add Vec::retain_mut #34265

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
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
38 changes: 38 additions & 0 deletions src/libcollections/vec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -684,6 +684,44 @@ impl<T> Vec<T> {
}
}

/// Retains only the elements specified by the predicate.
///
/// In other words, remove all elements `e` such that `f(&e)` returns false.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should probably be f(&mut e).

/// This method operates in place and preserves the order of the retained
/// elements.
///
/// # Examples
///
/// ```
/// let mut vec = vec![1, 2, 3, 4];
/// vec.retain_mut(|x| {
/// *x -= 1;
/// *x % 2 == 0
/// });
/// assert_eq!(vec, [0, 2]);
/// ```
#[unstable(feature = "retain_mut", reason = "recently added", issue = "00000")]
pub fn retain_mut<F>(&mut self, mut f: F)
where F: FnMut(&mut T) -> bool
{
let len = self.len();
let mut del = 0;
{
let v = &mut **self;

for i in 0..len {
if !f(&mut v[i]) {
del += 1;
} else if del > 0 {
v.swap(i - del, i);
}
}
}
if del > 0 {
self.truncate(len - del);
}
}

/// Appends an element to the back of a collection.
///
/// # Panics
Expand Down
10 changes: 10 additions & 0 deletions src/libcollectionstest/vec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,16 @@ fn test_retain() {
assert_eq!(vec, [2, 4]);
}

#[test]
fn test_retain_mut() {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't believe this test is necessary since as far as I known the examples in doc comments are already executed as if they were tests.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This was following existing convention; I'm not sure of the exact benefits of having the test in both places though.

let mut vec = vec![1, 2, 3, 4];
vec.retain_mut(|x| {
*x -= 1;
*x % 2 == 0
});
assert_eq!(vec, [0, 2]);
}

#[test]
fn zero_sized_values() {
let mut v = Vec::new();
Expand Down