use super::ebr::{Arc, AtomicArc, Barrier};
use super::hash_table::bucket::{Bucket, EntryPtr, Locker};
use super::hash_table::bucket_array::BucketArray;
use super::hash_table::HashTable;
use super::wait_queue::{AsyncWait, DeriveAsyncWait};
use std::borrow::Borrow;
use std::collections::hash_map::RandomState;
use std::fmt::{self, Debug};
use std::hash::{BuildHasher, Hash};
use std::iter::FusedIterator;
use std::pin::Pin;
use std::ptr;
use std::sync::atomic::AtomicU8;
use std::sync::atomic::Ordering::Acquire;
pub struct HashIndex<K, V, H = RandomState>
where
K: 'static + Clone + Eq + Hash + Sync,
V: 'static + Clone + Sync,
H: BuildHasher,
{
array: AtomicArc<BucketArray<K, V, true>>,
minimum_capacity: usize,
resize_mutex: AtomicU8,
build_hasher: H,
}
impl<K, V, H> HashIndex<K, V, H>
where
K: 'static + Clone + Eq + Hash + Sync,
V: 'static + Clone + Sync,
H: BuildHasher,
{
#[inline]
pub fn with_hasher(build_hasher: H) -> HashIndex<K, V, H> {
HashIndex {
array: AtomicArc::from(Arc::new(BucketArray::<K, V, true>::new(
Self::DEFAULT_CAPACITY,
AtomicArc::null(),
))),
minimum_capacity: Self::DEFAULT_CAPACITY,
resize_mutex: AtomicU8::new(0),
build_hasher,
}
}
#[inline]
pub fn with_capacity_and_hasher(capacity: usize, build_hasher: H) -> HashIndex<K, V, H> {
let initial_capacity = capacity.max(Self::DEFAULT_CAPACITY);
HashIndex {
array: AtomicArc::from(Arc::new(BucketArray::<K, V, true>::new(
initial_capacity,
AtomicArc::null(),
))),
minimum_capacity: initial_capacity,
resize_mutex: AtomicU8::new(0),
build_hasher,
}
}
#[inline]
pub fn insert(&self, key: K, val: V) -> Result<(), (K, V)> {
let barrier = Barrier::new();
let hash = self.hash(key.borrow());
if let Ok(Some((k, v))) = self.insert_entry(key, val, hash, &mut (), &barrier) {
Err((k, v))
} else {
Ok(())
}
}
#[inline]
pub async fn insert_async(&self, mut key: K, mut val: V) -> Result<(), (K, V)> {
let hash = self.hash(key.borrow());
loop {
let mut async_wait = AsyncWait::default();
let mut async_wait_pinned = Pin::new(&mut async_wait);
match self.insert_entry(key, val, hash, &mut async_wait_pinned, &Barrier::new()) {
Ok(Some(returned)) => return Err(returned),
Ok(None) => return Ok(()),
Err(returned) => {
key = returned.0;
val = returned.1;
}
}
async_wait_pinned.await;
}
}
#[inline]
pub unsafe fn update<Q, F, R>(&self, key: &Q, updater: F) -> Option<R>
where
K: Borrow<Q>,
Q: Eq + Hash + ?Sized,
F: FnOnce(&K, &mut V) -> R,
{
let barrier = Barrier::new();
let (mut locker, data_block, mut entry_ptr) = self
.acquire_entry(key, self.hash(key), &mut (), &barrier)
.ok()?;
if entry_ptr.is_valid() {
let (k, v) = entry_ptr.get_mut(data_block, &mut locker);
return Some(updater(k, v));
}
None
}
#[inline]
pub async unsafe fn update_async<Q, F, R>(&self, key: &Q, updater: F) -> Option<R>
where
K: Borrow<Q>,
Q: Eq + Hash + ?Sized,
F: FnOnce(&K, &mut V) -> R,
{
let hash = self.hash(key);
loop {
let mut async_wait = AsyncWait::default();
let mut async_wait_pinned = Pin::new(&mut async_wait);
if let Ok((mut locker, data_block, mut entry_ptr)) =
self.acquire_entry(key, hash, &mut async_wait_pinned, &Barrier::new())
{
if entry_ptr.is_valid() {
let (k, v) = entry_ptr.get_mut(data_block, &mut locker);
return Some(updater(k, v));
}
return None;
}
async_wait_pinned.await;
}
}
#[inline]
pub fn remove<Q>(&self, key: &Q) -> bool
where
K: Borrow<Q>,
Q: Eq + Hash + ?Sized,
{
self.remove_if(key, |_| true)
}
#[inline]
pub async fn remove_async<Q>(&self, key: &Q) -> bool
where
K: Borrow<Q>,
Q: Eq + Hash + ?Sized,
{
self.remove_if_async(key, |_| true).await
}
#[inline]
pub fn remove_if<Q, F: FnOnce(&V) -> bool>(&self, key: &Q, condition: F) -> bool
where
K: Borrow<Q>,
Q: Eq + Hash + ?Sized,
{
self.remove_entry(
key,
self.hash(key),
condition,
|r| r.is_some(),
&mut (),
&Barrier::new(),
)
.ok()
.map_or(false, |r| r)
}
#[inline]
pub async fn remove_if_async<Q, F: FnOnce(&V) -> bool>(&self, key: &Q, mut condition: F) -> bool
where
K: Borrow<Q>,
Q: Eq + Hash + ?Sized,
{
let hash = self.hash(key);
loop {
let mut async_wait = AsyncWait::default();
let mut async_wait_pinned = Pin::new(&mut async_wait);
match self.remove_entry(
key,
hash,
condition,
|r| r.is_some(),
&mut async_wait_pinned,
&Barrier::new(),
) {
Ok(r) => return r,
Err(c) => condition = c,
};
async_wait_pinned.await;
}
}
#[inline]
pub fn read<Q, R, F: FnOnce(&K, &V) -> R>(&self, key: &Q, reader: F) -> Option<R>
where
K: Borrow<Q>,
Q: Eq + Hash + ?Sized,
{
let barrier = Barrier::new();
self.read_entry(key, self.hash(key), &mut (), &barrier)
.ok()
.flatten()
.map(|(k, v)| reader(k, v))
}
#[inline]
pub fn read_with<'b, Q, R, F: FnOnce(&'b K, &'b V) -> R>(
&self,
key: &Q,
reader: F,
barrier: &'b Barrier,
) -> Option<R>
where
K: Borrow<Q>,
Q: Eq + Hash + ?Sized,
{
self.read_entry(key, self.hash(key), &mut (), barrier)
.ok()
.flatten()
.map(|(k, v)| reader(k, v))
}
#[inline]
pub fn contains<Q>(&self, key: &Q) -> bool
where
K: Borrow<Q>,
Q: Eq + Hash + ?Sized,
{
self.read(key, |_, _| ()).is_some()
}
pub fn clear(&self) -> usize {
let mut num_removed: usize = 0;
let barrier = Barrier::new();
let mut current_array_ptr = self.array.load(Acquire, &barrier);
while let Some(current_array) = current_array_ptr.as_ref() {
while !current_array.old_array(&barrier).is_null() {
if self.partial_rehash::<_, _, false>(current_array, &mut (), &barrier) == Ok(true)
{
break;
}
}
for index in 0..current_array.num_buckets() {
let bucket = current_array.bucket_mut(index);
if let Some(mut locker) = Locker::lock(bucket, &barrier) {
let data_block = current_array.data_block(index);
let mut entry_ptr = EntryPtr::new(&barrier);
while entry_ptr.next(locker.bucket(), &barrier) {
locker.erase(data_block, &mut entry_ptr);
num_removed = num_removed.saturating_add(1);
}
}
}
let new_current_array_ptr = self.array.load(Acquire, &barrier);
if current_array_ptr == new_current_array_ptr {
self.resize(&barrier);
break;
}
current_array_ptr = new_current_array_ptr;
}
num_removed
}
pub async fn clear_async(&self) -> usize {
let mut num_removed: usize = 0;
let mut current_array_holder = self.array.get_arc(Acquire, &Barrier::new());
while let Some(current_array) = current_array_holder.take() {
while !current_array.old_array(&Barrier::new()).is_null() {
let mut async_wait = AsyncWait::default();
let mut async_wait_pinned = Pin::new(&mut async_wait);
if self.partial_rehash::<_, _, false>(
¤t_array,
&mut async_wait_pinned,
&Barrier::new(),
) == Ok(true)
{
break;
}
async_wait_pinned.await;
}
for index in 0..current_array.num_buckets() {
let killed = loop {
let mut async_wait = AsyncWait::default();
let mut async_wait_pinned = Pin::new(&mut async_wait);
{
let barrier = Barrier::new();
let bucket = current_array.bucket_mut(index);
if let Ok(locker) = Locker::try_lock_or_wait(
bucket,
unsafe { async_wait_pinned.derive().unwrap_unchecked() },
&barrier,
) {
if let Some(mut locker) = locker {
let data_block = current_array.data_block(index);
let mut entry_ptr = EntryPtr::new(&barrier);
while entry_ptr.next(locker.bucket(), &barrier) {
locker.erase(data_block, &mut entry_ptr);
num_removed = num_removed.saturating_add(1);
}
break false;
}
break true;
};
}
async_wait_pinned.await;
};
if killed {
break;
}
}
if let Some(new_current_array) = self.array.get_arc(Acquire, &Barrier::new()) {
if new_current_array.as_ptr() == current_array.as_ptr() {
break;
}
current_array_holder.replace(new_current_array);
continue;
}
break;
}
if num_removed != 0 {
self.resize(&Barrier::new());
}
num_removed
}
#[inline]
pub fn len(&self) -> usize {
self.num_entries(&Barrier::new())
}
#[inline]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
#[inline]
pub fn capacity(&self) -> usize {
self.num_slots(&Barrier::new())
}
#[inline]
pub fn iter<'h, 'b>(&'h self, barrier: &'b Barrier) -> Visitor<'h, 'b, K, V, H> {
Visitor {
hashindex: self,
current_array: None,
current_index: 0,
current_bucket: None,
current_entry_ptr: EntryPtr::new(barrier),
barrier,
}
}
}
impl<K, V, H> Clone for HashIndex<K, V, H>
where
K: 'static + Clone + Eq + Hash + Sync,
V: 'static + Clone + Sync,
H: 'static + BuildHasher + Clone,
{
#[inline]
fn clone(&self) -> Self {
let cloned = Self::with_capacity_and_hasher(self.capacity(), self.hasher().clone());
for (k, v) in self.iter(&Barrier::new()) {
let _reuslt = cloned.insert(k.clone(), v.clone());
}
cloned
}
}
impl<K, V, H> Debug for HashIndex<K, V, H>
where
K: 'static + Clone + Debug + Eq + Hash + Sync,
V: 'static + Clone + Debug + Sync,
H: 'static + BuildHasher,
{
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let barrier = Barrier::new();
f.debug_map().entries(self.iter(&barrier)).finish()
}
}
impl<K, V> HashIndex<K, V, RandomState>
where
K: 'static + Clone + Eq + Hash + Sync,
V: 'static + Clone + Sync,
{
#[inline]
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[inline]
#[must_use]
pub fn with_capacity(capacity: usize) -> HashIndex<K, V, RandomState> {
let initial_capacity = capacity.max(Self::DEFAULT_CAPACITY);
HashIndex {
array: AtomicArc::from(Arc::new(BucketArray::<K, V, true>::new(
initial_capacity,
AtomicArc::null(),
))),
minimum_capacity: initial_capacity,
resize_mutex: AtomicU8::new(0),
build_hasher: RandomState::new(),
}
}
}
impl<K, V> Default for HashIndex<K, V, RandomState>
where
K: 'static + Clone + Eq + Hash + Sync,
V: 'static + Clone + Sync,
{
#[inline]
fn default() -> Self {
HashIndex {
array: AtomicArc::from(Arc::new(BucketArray::<K, V, true>::new(
Self::DEFAULT_CAPACITY,
AtomicArc::null(),
))),
minimum_capacity: Self::DEFAULT_CAPACITY,
resize_mutex: AtomicU8::new(0),
build_hasher: RandomState::new(),
}
}
}
impl<K, V, H> HashTable<K, V, H, true> for HashIndex<K, V, H>
where
K: 'static + Clone + Eq + Hash + Sync,
V: 'static + Clone + Sync,
H: BuildHasher,
{
#[inline]
fn hasher(&self) -> &H {
&self.build_hasher
}
#[inline]
fn cloner(entry: &(K, V)) -> Option<(K, V)> {
Some((entry.0.clone(), entry.1.clone()))
}
#[inline]
fn bucket_array(&self) -> &AtomicArc<BucketArray<K, V, true>> {
&self.array
}
#[inline]
fn minimum_capacity(&self) -> usize {
self.minimum_capacity
}
#[inline]
fn resize_mutex(&self) -> &AtomicU8 {
&self.resize_mutex
}
}
impl<K, V, H> PartialEq for HashIndex<K, V, H>
where
K: 'static + Clone + Eq + Hash + Sync,
V: 'static + Clone + PartialEq + Sync,
H: 'static + BuildHasher,
{
#[inline]
fn eq(&self, other: &Self) -> bool {
let barrier = Barrier::new();
if !self
.iter(&barrier)
.any(|(k, v)| other.read(k, |_, ov| v == ov) != Some(true))
{
return !other
.iter(&barrier)
.any(|(k, v)| self.read(k, |_, sv| v == sv) != Some(true));
}
false
}
}
pub struct Visitor<'h, 'b, K, V, H>
where
K: 'static + Clone + Eq + Hash + Sync,
V: 'static + Clone + Sync,
H: BuildHasher,
{
hashindex: &'h HashIndex<K, V, H>,
current_array: Option<&'b BucketArray<K, V, true>>,
current_index: usize,
current_bucket: Option<&'b Bucket<K, V, true>>,
current_entry_ptr: EntryPtr<'b, K, V, true>,
barrier: &'b Barrier,
}
impl<'h, 'b, K, V, H> Iterator for Visitor<'h, 'b, K, V, H>
where
K: 'static + Clone + Eq + Hash + Sync,
V: 'static + Clone + Sync,
H: 'static + BuildHasher,
{
type Item = (&'b K, &'b V);
#[inline]
fn next(&mut self) -> Option<Self::Item> {
let mut array = if let Some(array) = self.current_array.as_ref().copied() {
array
} else {
let current_array = self.hashindex.current_array_unchecked(self.barrier);
let old_array_ptr = current_array.old_array(self.barrier);
let array = if let Some(old_array) = old_array_ptr.as_ref() {
old_array
} else {
current_array
};
self.current_array.replace(array);
self.current_bucket.replace(array.bucket(0));
self.current_entry_ptr = EntryPtr::new(self.barrier);
array
};
loop {
if let Some(bucket) = self.current_bucket.take() {
if self.current_entry_ptr.next(bucket, self.barrier) {
let (k, v) = self
.current_entry_ptr
.get(array.data_block(self.current_index));
self.current_bucket.replace(bucket);
return Some((k, v));
}
}
self.current_index += 1;
if self.current_index == array.num_buckets() {
let current_array = self.hashindex.current_array_unchecked(self.barrier);
if self
.current_array
.as_ref()
.copied()
.map_or(false, |a| ptr::eq(a, current_array))
{
break;
}
let old_array_ptr = current_array.old_array(self.barrier);
if self
.current_array
.as_ref()
.copied()
.map_or(false, |a| ptr::eq(a, old_array_ptr.as_raw()))
{
array = current_array;
self.current_array.replace(array);
self.current_index = 0;
self.current_bucket.replace(array.bucket(0));
self.current_entry_ptr = EntryPtr::new(self.barrier);
continue;
}
array = if let Some(old_array) = old_array_ptr.as_ref() {
old_array
} else {
current_array
};
self.current_array.replace(array);
self.current_index = 0;
self.current_bucket.replace(array.bucket(0));
self.current_entry_ptr = EntryPtr::new(self.barrier);
continue;
}
self.current_bucket
.replace(array.bucket(self.current_index));
self.current_entry_ptr = EntryPtr::new(self.barrier);
}
None
}
}
impl<'h, 'b, K, V, H> FusedIterator for Visitor<'h, 'b, K, V, H>
where
K: 'static + Clone + Eq + Hash + Sync,
V: 'static + Clone + Sync,
H: 'static + BuildHasher,
{
}