Skip to content

Commit

Permalink
Add SmallMap::retain
Browse files Browse the repository at this point in the history
Summary: Useful to have.

Reviewed By: stepancheg

Differential Revision: D62106988

fbshipit-source-id: 7bbbe100ccaa8108d6801a30495f42d59333e347
  • Loading branch information
ndmitchell authored and facebook-github-bot committed Sep 2, 2024
1 parent 239bd61 commit 7764d72
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
30 changes: 30 additions & 0 deletions starlark-rust/starlark_map/src/small_map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -724,6 +724,20 @@ impl<K, V> SmallMap<K, V> {
}
}
}

/// Retains only the elements specified by the predicate.
pub fn retain<F>(&mut self, mut f: F)
where
F: FnMut(&K, &mut V) -> bool,
{
let mut res = SmallMap::new();
for (k, mut v) in mem::take(self).into_iter_hashed() {
if f(&*k, &mut v) {
res.insert_hashed_unique_unchecked(k, v);
}
}
*self = res;
}
}

/// Reference to the actual entry in the map.
Expand Down Expand Up @@ -1386,4 +1400,20 @@ mod tests {
.collect::<Vec<_>>()
);
}

#[test]
fn test_retain() {
let mut map = SmallMap::new();
for i in 0..100 {
map.insert(i.to_string(), i);
}
map.retain(|_, v| {
let res = *v % 2 == 0;
*v += 3;
res
});
assert_eq!(map.len(), 50);
assert_eq!(map.get("7"), None);
assert_eq!(map.get("8"), Some(&11));
}
}
8 changes: 8 additions & 0 deletions starlark-rust/starlark_map/src/small_set.rs
Original file line number Diff line number Diff line change
Expand Up @@ -405,6 +405,14 @@ impl<T> SmallSet<T> {
pub fn reverse(&mut self) {
self.0.reverse();
}

/// Retains only the elements specified by the predicate.
pub fn retain<F>(&mut self, mut f: F)
where
F: FnMut(&T) -> bool,
{
self.0.retain(|k, _| f(k))
}
}

impl<'a, T> IntoIterator for &'a SmallSet<T> {
Expand Down

0 comments on commit 7764d72

Please sign in to comment.