Re: [PATCH 5/5] rust: alloc: add Vec::retain
From: Benno Lossin
Date: Thu Mar 20 2025 - 18:22:27 EST
On Thu Mar 20, 2025 at 2:53 PM CET, Alice Ryhl wrote:
> diff --git a/rust/kernel/alloc/kvec.rs b/rust/kernel/alloc/kvec.rs
> index 303198509885f5e24b74da5a92382b518de3e1c0..00dabea8ea6c8a742a7fc95954d8de58be124493 100644
> --- a/rust/kernel/alloc/kvec.rs
> +++ b/rust/kernel/alloc/kvec.rs
> @@ -588,6 +588,20 @@ pub fn drain_all(&mut self) -> DrainAll<'_, T> {
> elements: self.spare_capacity_mut()[..len].iter_mut(),
> }
> }
> +
> + /// Removes all elements that don't match the provided closure.
Can you also add an example here? Otherwise the code looks good.
---
Cheers,
Benno
> + pub fn retain(&mut self, mut f: impl FnMut(&mut T) -> bool) {
> + let mut num_kept = 0;
> + let mut next_to_check = 0;
> + while let Some(to_check) = self.get_mut(next_to_check) {
> + if f(to_check) {
> + self.swap(num_kept, next_to_check);
> + num_kept += 1;
> + }
> + next_to_check += 1;
> + }
> + self.truncate(num_kept);
> + }
> }
>
> impl<T: Clone, A: Allocator> Vec<T, A> {