Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add HashSet::drain_filter method #179

Merged
merged 1 commit into from
Jul 11, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
- Added methods that allow re-using a `RawIter` for `RawDrain`,
`RawIntoIter`, and `RawParIter`. (#175)
- Added `reflect_remove` and `reflect_insert` to `RawIter`. (#175)
- Added a `drain_filter` function to `HashSet`. (#179)

### Changed
- Deprecated `RawTable::erase_no_drop` in favor of `erase` and `remove`. (#176)
Expand Down
54 changes: 36 additions & 18 deletions src/map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -603,14 +603,17 @@ impl<K, V, S> HashMap<K, V, S> {
/// assert_eq!(drained.count(), 4);
/// assert_eq!(map.len(), 4);
/// ```
#[cfg_attr(feature = "inline-more", inline)]
pub fn drain_filter<F>(&mut self, f: F) -> DrainFilter<'_, K, V, F>
where
F: FnMut(&K, &mut V) -> bool,
{
DrainFilter {
f,
iter: unsafe { self.table.iter() },
table: &mut self.table,
inner: DrainFilterInner {
iter: unsafe { self.table.iter() },
table: &mut self.table,
},
}
}

Expand Down Expand Up @@ -1331,45 +1334,60 @@ where
F: FnMut(&K, &mut V) -> bool,
{
f: F,
iter: RawIter<(K, V)>,
table: &'a mut RawTable<(K, V)>,
inner: DrainFilterInner<'a, K, V>,
}

impl<'a, K, V, F> Drop for DrainFilter<'a, K, V, F>
where
F: FnMut(&K, &mut V) -> bool,
{
#[cfg_attr(feature = "inline-more", inline)]
fn drop(&mut self) {
struct DropGuard<'r, 'a, K, V, F>(&'r mut DrainFilter<'a, K, V, F>)
where
F: FnMut(&K, &mut V) -> bool;

impl<'r, 'a, K, V, F> Drop for DropGuard<'r, 'a, K, V, F>
where
F: FnMut(&K, &mut V) -> bool,
{
fn drop(&mut self) {
while let Some(_) = self.0.next() {}
}
}
while let Some(item) = self.next() {
let guard = DropGuard(self);
let guard = ConsumeAllOnDrop(self);
drop(item);
mem::forget(guard);
}
}
}

pub(super) struct ConsumeAllOnDrop<'a, T: Iterator>(pub &'a mut T);

impl<T: Iterator> Drop for ConsumeAllOnDrop<'_, T> {
#[cfg_attr(feature = "inline-more", inline)]
fn drop(&mut self) {
self.0.for_each(drop)
}
}

impl<K, V, F> Iterator for DrainFilter<'_, K, V, F>
where
F: FnMut(&K, &mut V) -> bool,
{
type Item = (K, V);

#[cfg_attr(feature = "inline-more", inline)]
fn next(&mut self) -> Option<Self::Item> {
self.inner.next(&mut self.f)
}
}

/// Portions of `DrainFilter` shared with `set::DrainFilter`
pub(super) struct DrainFilterInner<'a, K, V> {
pub iter: RawIter<(K, V)>,
pub table: &'a mut RawTable<(K, V)>,
}

impl<K, V> DrainFilterInner<'_, K, V> {
#[cfg_attr(feature = "inline-more", inline)]
pub(super) fn next<F>(&mut self, f: &mut F) -> Option<(K, V)>
where
F: FnMut(&K, &mut V) -> bool,
{
unsafe {
while let Some(item) = self.iter.next() {
let &mut (ref key, ref mut value) = item.as_mut();
if !(self.f)(key, value) {
if !f(key, value) {
return Some(self.table.remove(item));
}
}
Expand Down
96 changes: 95 additions & 1 deletion src/set.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,10 @@ use core::borrow::Borrow;
use core::fmt;
use core::hash::{BuildHasher, Hash};
use core::iter::{Chain, FromIterator, FusedIterator};
use core::mem;
use core::ops::{BitAnd, BitOr, BitXor, Sub};

use super::map::{self, DefaultHashBuilder, HashMap, Keys};
use super::map::{self, ConsumeAllOnDrop, DefaultHashBuilder, DrainFilterInner, HashMap, Keys};

// Future Optimization (FIXME!)
// =============================
Expand Down Expand Up @@ -285,6 +286,39 @@ impl<T, S> HashSet<T, S> {
self.map.retain(|k, _| f(k));
}

/// Drains elements which are false under the given predicate,
/// and returns an iterator over the removed items.
///
/// In other words, move all elements `e` such that `f(&e)` returns `false` out
/// into another iterator.
///
/// When the returned DrainedFilter is dropped, the elements that don't satisfy
/// the predicate are dropped from the set.
///
/// # Examples
///
/// ```
/// use hashbrown::HashSet;
///
/// let mut set: HashSet<i32> = (0..8).collect();
/// let drained = set.drain_filter(|&k| k % 2 == 0);
/// assert_eq!(drained.count(), 4);
/// assert_eq!(set.len(), 4);
/// ```
#[cfg_attr(feature = "inline-more", inline)]
pub fn drain_filter<F>(&mut self, f: F) -> DrainFilter<'_, T, F>
where
F: FnMut(&T) -> bool,
{
DrainFilter {
f,
inner: DrainFilterInner {
iter: unsafe { self.map.table.iter() },
table: &mut self.map.table,
},
}
}

/// Clears the set, removing all values.
///
/// # Examples
Expand Down Expand Up @@ -1185,6 +1219,21 @@ pub struct Drain<'a, K> {
iter: map::Drain<'a, K, ()>,
}

/// A draining iterator over entries of a `HashSet` which don't satisfy the predicate `f`.
///
/// This `struct` is created by the [`drain_filter`] method on [`HashSet`]. See its
/// documentation for more.
///
/// [`drain_filter`]: struct.HashSet.html#method.drain_filter
/// [`HashSet`]: struct.HashSet.html
pub struct DrainFilter<'a, K, F>
where
F: FnMut(&K) -> bool,
{
f: F,
inner: DrainFilterInner<'a, K, ()>,
}

/// A lazy iterator producing elements in the intersection of `HashSet`s.
///
/// This `struct` is created by the [`intersection`] method on [`HashSet`].
Expand Down Expand Up @@ -1365,6 +1414,34 @@ impl<K: fmt::Debug> fmt::Debug for Drain<'_, K> {
}
}

impl<'a, K, F> Drop for DrainFilter<'a, K, F>
where
F: FnMut(&K) -> bool,
{
#[cfg_attr(feature = "inline-more", inline)]
fn drop(&mut self) {
while let Some(item) = self.next() {
let guard = ConsumeAllOnDrop(self);
drop(item);
mem::forget(guard);
}
}
}

impl<K, F> Iterator for DrainFilter<'_, K, F>
where
F: FnMut(&K) -> bool,
{
type Item = K;

#[cfg_attr(feature = "inline-more", inline)]
fn next(&mut self) -> Option<Self::Item> {
let f = &mut self.f;
let (k, _) = self.inner.next(&mut |k, _| f(k))?;
Some(k)
}
}

impl<T, S> Clone for Intersection<'_, T, S> {
#[cfg_attr(feature = "inline-more", inline)]
fn clone(&self) -> Self {
Expand Down Expand Up @@ -1973,4 +2050,21 @@ mod test_set {
assert!(set.contains(&4));
assert!(set.contains(&6));
}

#[test]
fn test_drain_filter() {
{
let mut set: HashSet<i32> = (0..8).collect();
let drained = set.drain_filter(|&k| k % 2 == 0);
let mut out = drained.collect::<Vec<_>>();
out.sort_unstable();
assert_eq!(vec![1, 3, 5, 7], out);
assert_eq!(set.len(), 4);
}
{
let mut set: HashSet<i32> = (0..8).collect();
drop(set.drain_filter(|&k| k % 2 == 0));
assert_eq!(set.len(), 4, "Removes non-matching items on drop");
}
}
}