Skip to content

Commit

Permalink
Implement FlurryHashSet insert() and contains()
Browse files Browse the repository at this point in the history
  • Loading branch information
twe4ked committed Jan 24, 2020
1 parent 8c014c3 commit 20b8218
Show file tree
Hide file tree
Showing 3 changed files with 68 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,8 @@
mod node;
use node::*;

pub mod set;

use crossbeam::epoch::{Atomic, Guard, Owned, Shared};
use std::collections::hash_map::RandomState;
use std::hash::{BuildHasher, Hash};
Expand Down
41 changes: 41 additions & 0 deletions src/set/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
//! A concurrent hash set backed by FlurryHashMap.

use crossbeam::epoch;
use std::collections::hash_map::RandomState;
use std::hash::Hash;

use crate::FlurryHashMap;

/// A concurrent hash set.
#[derive(Debug)]
pub struct FlurryHashSet<T, S = RandomState> {
map: FlurryHashMap<T, (), S>,
}

impl<T> FlurryHashSet<T, RandomState>
where
T: Sync + Send + Clone + Hash + Eq,
{
/// Creates a new, empty set with the default initial table size (16).
pub fn new() -> Self {
Self {
map: FlurryHashMap::<T, ()>::new(),
}
}

/// Adds a value to the set.
///
/// If the set did not have this value present, true is returned.
///
/// If the set did have this value present, false is returned.
pub fn insert(&self, value: T) -> bool {
let guard = epoch::pin();
let old = self.map.insert(value, (), &guard);
old.is_none()
}

/// Returns true if the set contains a value.
pub fn contains(&self, value: &T) -> bool {
self.map.contains_key(value)
}
}
25 changes: 25 additions & 0 deletions tests/set.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
use flurry::set::FlurryHashSet;

#[test]
fn new() {
let _set = FlurryHashSet::<usize>::new();
}

#[test]
fn insert() {
let set = FlurryHashSet::<usize>::new();
let did_set = set.insert(42);
assert!(did_set);

let did_set = set.insert(42);
assert!(!did_set);
}

#[test]
fn insert_contains() {
let set = FlurryHashSet::<usize>::new();
set.insert(42);

assert!(set.contains(&42));
assert!(!set.contains(&43));
}

0 comments on commit 20b8218

Please sign in to comment.