Skip to content

Commit ca12838

Browse files
mkjsgued
authored andcommitted
linear_map: Add LinearMap::retain()
1 parent cf0bad5 commit ca12838

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
3030
- Add missing `Debug` derive to `vec::IntoIter`.
3131
- Removed generic from `spsc::Consumer`, `spsc::Producer` and `spsc::Iter`.
3232
- Added `LinearMap::entry()` API.
33+
- Added `LinearMap::retain()`.
3334

3435
### Fixed
3536

src/linear_map.rs

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -509,6 +509,16 @@ where
509509
}),
510510
}
511511
}
512+
513+
/// Retains only the elements specified by the predicate.
514+
///
515+
/// In other words, remove all pairs `(k, v)` for which `f(&k, &mut v)` returns `false`.
516+
pub fn retain<F>(&mut self, mut f: F)
517+
where
518+
F: FnMut(&K, &mut V) -> bool,
519+
{
520+
self.buffer.retain_mut(|(k, v)| f(k, v));
521+
}
512522
}
513523

514524
impl<K, V, Q, S: LinearMapStorage<K, V> + ?Sized> ops::Index<&'_ Q> for LinearMapInner<K, V, S>
@@ -960,6 +970,30 @@ mod test {
960970
assert_eq!(*v, 500);
961971
}
962972

973+
#[test]
974+
fn retain() {
975+
let mut src = almost_filled_map();
976+
src.retain(|k, _v| k % 2 == 0);
977+
src.retain(|k, _v| k % 3 == 0);
978+
979+
for (k, v) in src.iter() {
980+
assert_eq!(k, v);
981+
assert_eq!(k % 2, 0);
982+
assert_eq!(k % 3, 0);
983+
}
984+
985+
let mut src = almost_filled_map();
986+
src.retain(|_k, _v| false);
987+
assert!(src.is_empty());
988+
989+
let mut src = almost_filled_map();
990+
src.retain(|_k, _v| true);
991+
assert_eq!(src.len(), MAP_SLOTS - 1);
992+
src.insert(0, 0).unwrap();
993+
src.retain(|_k, _v| true);
994+
assert_eq!(src.len(), MAP_SLOTS);
995+
}
996+
963997
#[test]
964998
fn entry_find() {
965999
let key = 0;

0 commit comments

Comments
 (0)