Skip to content

Commit

Permalink
add Vec::retain_mut
Browse files Browse the repository at this point in the history
  • Loading branch information
kristopherbullinger authored and Luthaf committed Oct 11, 2023
1 parent 9fcb44b commit 5f49f49
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
23 changes: 23 additions & 0 deletions soa-derive-internal/src/vec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ pub fn derive(input: &Input) -> TokenStream {
let slice_name = names::slice_name(name);
let slice_mut_name = names::slice_mut_name(&input.name);
let ref_name = names::ref_name(&input.name);
let ref_mut_name = names::ref_mut_name(&input.name);
let ptr_name = names::ptr_name(&input.name);
let ptr_mut_name = names::ptr_mut_name(&input.name);

Expand Down Expand Up @@ -314,6 +315,28 @@ pub fn derive(input: &Input) -> TokenStream {
}
}

/// Similar to [`
#[doc = #vec_name_str]
/// ::retain_mut()`](https://doc.rust-lang.org/std/vec/struct.Vec.html#method.retain_mut).
pub fn retain_mut<F>(&mut self, mut f: F) where F: FnMut(#ref_mut_name) -> bool {
let len = self.len();
let mut del = 0;

{
let mut slice = self.as_mut_slice();
for i in 0..len {
if !f(slice.get_mut(i).unwrap()) {
del += 1;
} else if del > 0 {
slice.swap(i - del, i);
}
}
}
if del > 0 {
self.truncate(len - del);
}
}

/// Similar to [`
#[doc = #vec_name_str]
/// ::get<I>()`](https://doc.rust-lang.org/std/vec/struct.Vec.html#method.get).
Expand Down
16 changes: 16 additions & 0 deletions tests/vec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,22 @@ fn retain() {
assert_eq!(particles.index(1).name, "C");
}

#[test]
fn retain_mut() {
let mut particles = ParticleVec::new();
particles.push(Particle::new(String::from("Cl"), 1.0));
particles.push(Particle::new(String::from("Na"), 1.0));
particles.push(Particle::new(String::from("Zn"), 0.0));
particles.push(Particle::new(String::from("C"), 1.0));

particles.retain_mut(|particle| {
particle.name.make_ascii_uppercase();
*particle.mass > 0.5
});
assert_eq!(particles.len(), 3);
assert!(["CL", "NA", "C"].iter().copied().eq(particles.name.iter()));
}

#[derive(StructOfArray)]
struct IncrOnDrop {
cell: Rc<Cell<usize>>,
Expand Down

0 comments on commit 5f49f49

Please sign in to comment.