1// TODO: Remove this when drain_filter comes to stable rust
2
3pub(crate) trait VecRetainMut<T> {
4 fn retain_mut<F>(&mut self, f: F)
5 where
6 F: FnMut(&mut T) -> bool;
7}
8
9impl<T> VecRetainMut<T> for Vec<T> {
10 // Adapted from libcollections/vec.rs in Rust
11 // Primary author in Rust: Michael Darakananda
12 fn retain_mut<F>(&mut self, mut f: F)
13 where
14 F: FnMut(&mut T) -> bool,
15 {
16 let len = self.len();
17 let mut del = 0;
18 {
19 let v = &mut **self;
20
21 for i in 0..len {
22 if !f(&mut v[i]) {
23 del += 1;
24 } else if del > 0 {
25 v.swap(i - del, i);
26 }
27 }
28 }
29 if del > 0 {
30 self.truncate(len - del);
31 }
32 }
33}
34