Skip to content

Commit

Permalink
Merge pull request #35 from camsteffen/retain
Browse files Browse the repository at this point in the history
add retain method
  • Loading branch information
pczarn authored Jun 16, 2017
2 parents adfde1d + c0d7eee commit 550b8f0
Showing 1 changed file with 50 additions and 0 deletions.
50 changes: 50 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -583,6 +583,34 @@ impl<V> VecMap<V> {
})
}
}

/// Retains only the elements specified by the predicate.
///
/// In other words, remove all pairs `(k, v)` such that `f(&k, &mut v)` returns `false`.
///
/// # Examples
///
/// ```
/// use vec_map::VecMap;
///
/// let mut map: VecMap<usize> = (0..8).map(|x|(x, x*10)).collect();
/// map.retain(|k, _| k % 2 == 0);
/// assert_eq!(map.len(), 4);
/// ```
pub fn retain<F>(&mut self, mut f: F)
where F: FnMut(usize, &mut V) -> bool
{
for (i, e) in self.v.iter_mut().enumerate() {
let remove = match *e {
Some(ref mut value) => !f(i, value),
None => false,
};
if remove {
*e = None;
self.n -= 1;
}
}
}
}

impl<'a, V> Entry<'a, V> {
Expand Down Expand Up @@ -1542,4 +1570,26 @@ mod test {

impls_serde_traits::<VecMap<u32>>();
}

#[test]
fn test_retain() {
let mut map = VecMap::new();
map.insert(1, "one");
map.insert(2, "two");
map.insert(3, "three");
map.retain(|k, v| match k {
1 => false,
2 => {
*v = "two changed";
true
},
3 => false,
_ => panic!(),
});

assert_eq!(map.len(), 1);
assert_eq!(map.get(1), None);
assert_eq!(map[2], "two changed");
assert_eq!(map.get(3), None);
}
}

0 comments on commit 550b8f0

Please sign in to comment.