#![deny(
// The following are allowed by default lints according to
// https://doc.rust-lang.org/rustc/lints/listing/allowed-by-default.html
anonymous_parameters,
bare_trait_objects,
// box_pointers, // futures involve boxed pointers
elided_lifetimes_in_paths, // allow anonymous lifetime in generated code
missing_copy_implementations,
missing_debug_implementations,
// missing_docs, // TODO: add documents
single_use_lifetimes, // TODO: fix lifetime names only used once
trivial_casts, // TODO: remove trivial casts in code
trivial_numeric_casts,
// unreachable_pub, use clippy::redundant_pub_crate instead
// unsafe_code, unsafe codes are inevitable here
unstable_features,
unused_extern_crates,
unused_import_braces,
unused_qualifications,
// unused_results, // TODO: fix unused results
variant_size_differences,
// Treat warnings as errors
warnings,
clippy::all,
clippy::restriction,
clippy::pedantic,
clippy::nursery,
clippy::cargo
)]
#![allow(
// Some explicitly allowed Clippy lints, must have clear reason to allow
clippy::blanket_clippy_restriction_lints, // allow clippy::restriction
clippy::panic, // allow debug_assert, panic in production code
clippy::implicit_return, // actually omitting the return keyword is idiomatic Rust code
clippy::separated_literal_suffix, // conflicts with clippy::unseparated_literal_suffix
)]
#![allow(
clippy::undocumented_unsafe_blocks, // FIXME
clippy::missing_panics_doc, // FIXME
clippy::single_char_lifetime_names, // FIXME
)]
mod pointer;
mod map_inner;
use pointer::{AtomicPtr, SharedPtr};
use std::borrow::Borrow;
use std::collections::hash_map::RandomState;
use std::hash::Hash;
use std::sync::atomic::Ordering;
pub use crossbeam_epoch::{pin, Guard};
pub struct LockFreeCuckooHash<K, V>
where
K: Eq + Hash,
{
map: AtomicPtr<map_inner::MapInner<K, V>>,
}
impl<K, V> std::fmt::Debug for LockFreeCuckooHash<K, V>
where
K: std::fmt::Debug + Eq + Hash,
V: std::fmt::Debug,
{
#[inline]
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let guard = pin();
self.load_inner(&guard).fmt(f)
}
}
impl<K, V> Default for LockFreeCuckooHash<K, V>
where
K: Eq + Hash,
{
#[inline]
fn default() -> Self {
Self::new()
}
}
impl<K, V> Drop for LockFreeCuckooHash<K, V>
where
K: Eq + Hash,
{
#[inline]
fn drop(&mut self) {
let guard = pin();
self.load_inner(&guard).drop_entries(&guard);
unsafe {
drop(self.map.load(Ordering::SeqCst, &guard).into_box());
}
}
}
impl<'guard, K, V> LockFreeCuckooHash<K, V>
where
K: 'guard + Eq + Hash,
{
pub const DEFAULT_CAPACITY: usize = 16;
#[must_use]
#[inline]
pub fn new() -> Self {
Self::with_capacity(Self::DEFAULT_CAPACITY)
}
#[must_use]
#[inline]
pub fn with_capacity(capacity: usize) -> Self {
Self {
map: AtomicPtr::new(map_inner::MapInner::with_capacity(
capacity,
[RandomState::new(), RandomState::new()],
)),
}
}
#[inline]
pub fn capacity(&self) -> usize {
let guard = pin();
self.load_inner(&guard).capacity()
}
#[inline]
pub fn size(&self) -> usize {
let guard = pin();
self.load_inner(&guard).size()
}
#[inline]
pub unsafe fn clear(&self) {
let cap = self.capacity();
self.clear_with_capacity(cap);
}
#[inline]
pub unsafe fn clear_with_capacity(&self, capacity: usize) {
let guard = pin();
let new_map = SharedPtr::from_box(Box::new(map_inner::MapInner::<K, V>::with_capacity(
capacity,
[RandomState::new(), RandomState::new()],
)));
loop {
let current_map = self.map.load(Ordering::SeqCst, &guard);
match self
.map
.compare_and_set(current_map, new_map, Ordering::SeqCst, &guard)
{
Ok(old_map) => {
guard.defer_unchecked(move || {
drop(old_map.into_box());
});
break;
}
Err(_) => {
continue;
}
}
}
}
#[inline]
pub fn get<Q: ?Sized>(&self, key: &Q, guard: &'guard Guard) -> Option<&'guard V>
where
K: Borrow<Q>,
Q: Hash + Eq,
{
self.load_inner(guard)
.search(key, guard)
.map(|pair| &pair.value)
}
#[inline]
pub fn get_key_value<Q: ?Sized>(
&self,
key: &Q,
guard: &'guard Guard,
) -> Option<(&'guard K, &'guard V)>
where
K: Borrow<Q>,
Q: Hash + Eq,
{
self.load_inner(guard)
.search(key, guard)
.map(|pair| (&pair.key, &pair.value))
}
#[inline]
pub fn contains_key<Q: ?Sized>(&self, key: &Q) -> bool
where
K: Borrow<Q>,
Q: Hash + Eq,
{
let guard = pin();
self.get_key_value(key, &guard).is_some()
}
#[inline]
pub fn insert(&self, key: K, value: V) -> bool {
let guard = pin();
self.insert_with_guard(key, value, &guard).is_some()
}
#[inline]
pub fn insert_with_guard(&self, key: K, value: V, guard: &'guard Guard) -> Option<&'guard V> {
let kvpair = SharedPtr::from_box(Box::new(map_inner::KVPair { key, value }));
loop {
match self.load_inner(guard).insert(
kvpair,
map_inner::InsertType::InsertOrReplace,
&self.map,
guard,
) {
map_inner::InsertResult::Retry | map_inner::InsertResult::Fail(_) => continue,
map_inner::InsertResult::Succ(result) => return result.map(|pair| &pair.value),
}
}
}
#[inline]
#[allow(clippy::unwrap_used)]
pub fn get_or_insert(&self, key: K, value: V, guard: &'guard Guard) -> &'guard V {
let kvpair = SharedPtr::from_box(Box::new(map_inner::KVPair { key, value }));
loop {
match self.load_inner(guard).insert(
kvpair,
map_inner::InsertType::GetOrInsert,
&self.map,
guard,
) {
map_inner::InsertResult::Retry => continue,
map_inner::InsertResult::Fail(result) => return &result.unwrap().value,
map_inner::InsertResult::Succ(_) => {
return unsafe { &(*kvpair.as_raw()).value };
}
}
}
}
#[inline]
pub fn insert_if_not_exists(&self, key: K, value: V) -> bool {
let guard = &pin();
let kvpair = SharedPtr::from_box(Box::new(map_inner::KVPair { key, value }));
loop {
match self.load_inner(guard).insert(
kvpair,
map_inner::InsertType::GetOrInsert,
&self.map,
guard,
) {
map_inner::InsertResult::Retry => continue,
map_inner::InsertResult::Fail(_) => return false,
map_inner::InsertResult::Succ(_) => return true,
}
}
}
#[inline]
pub fn compare_and_update(&self, key: K, new_value: V, old_value: &V) -> bool
where
V: PartialEq,
{
let guard = &pin();
let kvpair = SharedPtr::from_box(Box::new(map_inner::KVPair {
key,
value: new_value,
}));
let compare_fn: fn(&V, &V) -> bool = V::eq;
loop {
match self.load_inner(guard).insert(
kvpair,
map_inner::InsertType::CompareAndUpdate(old_value, compare_fn),
&self.map,
guard,
) {
map_inner::InsertResult::Retry => continue,
map_inner::InsertResult::Fail(_) => return false,
map_inner::InsertResult::Succ(_) => return true,
}
}
}
fn update_on_helper(
&self,
key: K,
new_value: V,
compare_fn: fn(&V, &V) -> bool,
force_insert: bool,
guard: &'guard Guard,
) -> (bool, Option<&'guard V>) {
let kvpair = SharedPtr::from_box(Box::new(map_inner::KVPair {
key,
value: new_value,
}));
loop {
match self.load_inner(guard).insert(
kvpair,
map_inner::InsertType::UpdateOn(compare_fn, force_insert),
&self.map,
guard,
) {
map_inner::InsertResult::Retry => continue,
map_inner::InsertResult::Fail(result) => {
return (false, result.map(|kv| &kv.value));
}
map_inner::InsertResult::Succ(result) => {
return (true, result.map(|kv| &kv.value));
}
}
}
}
#[inline]
pub fn update_on(
&self,
key: K,
new_value: V,
compare_fn: fn(&V, &V) -> bool,
guard: &'guard Guard,
) -> (bool, Option<&'guard V>) {
self.update_on_helper(key, new_value, compare_fn, false, guard)
}
#[inline]
pub fn insert_or_update_on(
&self,
key: K,
new_value: V,
compare_fn: fn(&V, &V) -> bool,
guard: &'guard Guard,
) -> (bool, Option<&'guard V>) {
self.update_on_helper(key, new_value, compare_fn, true, guard)
}
#[inline]
pub fn remove<Q: ?Sized>(&self, key: &Q) -> bool
where
K: Borrow<Q>,
Q: Hash + Eq,
{
let guard = pin();
self.remove_with_guard(key, &guard).is_some()
}
#[inline]
pub fn remove_with_guard<Q: ?Sized>(&self, key: &Q, guard: &'guard Guard) -> Option<&'guard V>
where
K: Borrow<Q>,
Q: Hash + Eq,
{
loop {
match self.load_inner(guard).remove(key, &self.map, guard) {
map_inner::RemoveResult::Retry => continue,
map_inner::RemoveResult::Succ(old) => return old.map(|pair| &pair.value),
}
}
}
fn load_inner(&self, guard: &'guard Guard) -> &'guard map_inner::MapInner<K, V> {
let raw = self.map.load(Ordering::SeqCst, guard).as_raw();
unsafe { &*raw }
}
}
#[cfg(test)]
#[allow(clippy::all, clippy::restriction)]
mod tests {
use super::{pin, LockFreeCuckooHash};
#[test]
fn test_insert() {
let hashtable = LockFreeCuckooHash::new();
let key: u32 = 1;
let value: u32 = 2;
hashtable.insert(key, value);
let guard = pin();
let ret = hashtable.get(&key, &guard);
assert!(ret.is_some());
assert_eq!(*(ret.unwrap()), value);
}
#[test]
fn test_replace() {
let hashtable = LockFreeCuckooHash::new();
let key: u32 = 1;
let value0: u32 = 2;
hashtable.insert(key, value0);
let guard = pin();
let ret0 = hashtable.get(&key, &guard);
assert!(ret0.is_some());
assert_eq!(*(ret0.unwrap()), value0);
assert_eq!(hashtable.size(), 1);
let value1: u32 = 3;
hashtable.insert(key, value1);
let ret1 = hashtable.get(&key, &guard);
assert!(ret1.is_some());
assert_eq!(*(ret1.unwrap()), value1);
assert_eq!(hashtable.size(), 1);
}
#[test]
fn test_get_or_insert() {
let hashtable = LockFreeCuckooHash::new();
let guard = &pin();
hashtable.insert(1, 1);
assert_eq!(hashtable.get_or_insert(1, 2, guard), &1);
assert_eq!(hashtable.get_or_insert(2, 3, guard), &3);
assert_eq!(hashtable.get_or_insert(2, 4, guard), &3);
}
#[test]
fn test_remove() {
let hashtable = LockFreeCuckooHash::new();
let key = 1;
let value = 2;
let fake_key = 3;
hashtable.insert(key, value);
assert_eq!(hashtable.size(), 1);
assert!(!hashtable.remove(&fake_key));
assert!(hashtable.remove(&key));
assert_eq!(hashtable.size(), 0);
}
#[test]
fn test_clear() {
let hashtable = LockFreeCuckooHash::new();
let key = 1;
let value = 2;
hashtable.insert(key, value);
let guard = pin();
let ret = hashtable.get(&key, &guard);
assert!(ret.is_some());
assert_eq!(*(ret.unwrap()), value);
unsafe { hashtable.clear() };
let ret = hashtable.get(&key, &guard);
assert!(ret.is_none());
}
#[test]
fn test_compare_and_update() {
let hashtable = LockFreeCuckooHash::new();
let guard = &pin();
hashtable.insert(1, 10);
assert_eq!(hashtable.compare_and_update(1, 20, &30), false);
assert_eq!(hashtable.get(&1, guard), Some(&10));
assert_eq!(hashtable.compare_and_update(1, 20, &10), true);
assert_eq!(hashtable.get(&1, guard), Some(&20));
}
#[test]
fn test_update_on() {
let hashtable = LockFreeCuckooHash::new();
let guard = &pin();
assert_eq!(
hashtable.update_on(1, 5, |v1, v2| { v1 < v2 }, guard),
(false, None)
);
hashtable.insert(1, 10);
assert_eq!(
hashtable.update_on(1, 5, |v1, v2| { v1 < v2 }, guard),
(false, Some(&10))
);
assert_eq!(hashtable.get(&1, guard), Some(&10));
assert_eq!(
hashtable.update_on(1, 20, |v1, v2| { v1 < v2 }, guard),
(true, Some(&10))
);
assert_eq!(hashtable.get(&1, guard), Some(&20));
}
#[test]
fn test_insert_or_update_on() {
let hashtable = LockFreeCuckooHash::new();
let guard = &pin();
assert_eq!(
hashtable.insert_or_update_on(1, 10, |v1, v2| { v1 < v2 }, guard),
(true, None)
);
assert_eq!(
hashtable.insert_or_update_on(1, 5, |v1, v2| { v1 < v2 }, guard),
(false, Some(&10))
);
assert_eq!(
hashtable.insert_or_update_on(1, 20, |v1, v2| { v1 < v2 }, guard),
(true, Some(&10))
);
assert_eq!(hashtable.get(&1, guard), Some(&20));
}
}