use std::sync::LazyLock;
use hashbrown::HashTable;
use parking_lot::{Mutex, MutexGuard};
use crate::entry::Entry;
type LockedShard = HashTable<Entry>;
type Shard = Mutex<LockedShard>;
#[derive(Debug, Default, Clone, Copy)]
pub struct MemoryUsage {
pub len: usize,
pub capacity: usize,
}
pub(crate) struct ShardedSet {
pub(crate) shift: usize,
pub(crate) hash_builder: ahash::RandomState,
pub(crate) shards: Box<[Shard]>,
}
impl ShardedSet {
fn get_shard(&self, hash: u64) -> MutexGuard<'_, LockedShard> {
let idx = ((hash << 7) >> self.shift) as usize;
self.shards[idx].lock()
}
fn get_hash_and_shard(&self, value: &[u8]) -> (u64, MutexGuard<'_, LockedShard>) {
let hash = self.hash_builder.hash_one(value);
(hash, self.get_shard(hash))
}
pub(crate) fn get_from_existing_ref(&self, value: &[u8]) -> Option<Entry> {
let (hash, shard) = self.get_hash_and_shard(value);
shard
.find(hash, |o| std::ptr::eq(o.data_ptr(), value.as_ptr()))
.map(|o| unsafe { o.acquire() })
}
pub(crate) fn get_or_insert(&self, value: &[u8]) -> Entry {
let (hash, mut shard) = self.get_hash_and_shard(value);
let entry = shard
.entry(
hash,
|o| unsafe { o.data() } == value,
|o| unsafe { o.hash() },
)
.or_insert_with(|| Entry::new(value, hash));
unsafe { entry.get().acquire() }
}
pub(crate) unsafe fn release(&self, entry: Entry) {
let hash = unsafe { entry.hash() };
if !unsafe { entry.release() } {
return;
}
let mut shard = self.get_shard(hash);
let Ok(found) = shard.find_entry(hash, |o| *o == entry) else {
return;
};
if !unsafe { found.get().is_unused() } {
return;
}
let (removed, _) = found.remove();
drop(shard);
unsafe { removed.free() };
}
pub(crate) fn is_empty(&self) -> bool {
self.len() == 0
}
pub(crate) fn len(&self) -> usize {
self.shards.iter().map(|o| o.lock().len()).sum()
}
pub(crate) fn capacity(&self) -> usize {
self.shards.iter().map(|o| o.lock().capacity()).sum()
}
pub(crate) fn get_memory_usage(&self) -> MemoryUsage {
self.shards
.iter()
.map(|o| {
let o = o.lock();
MemoryUsage {
len: o.len(),
capacity: o.capacity(),
}
})
.reduce(|acc, o| MemoryUsage {
len: acc.len + o.len,
capacity: acc.capacity + o.capacity,
})
.unwrap_or_default()
}
pub(crate) fn shrink_to_fit(&self) {
for shard in self.shards.iter() {
shard.lock().shrink_to_fit(|o| unsafe { o.hash() });
}
}
}
impl Default for ShardedSet {
fn default() -> Self {
static DEFAULT_SHARDS_COUNT: LazyLock<usize> = LazyLock::new(|| {
(std::thread::available_parallelism().map_or(1, usize::from) * 4).next_power_of_two()
});
let shift = (u64::BITS - DEFAULT_SHARDS_COUNT.trailing_zeros()) as usize;
Self {
shift,
hash_builder: Default::default(),
shards: (0..*DEFAULT_SHARDS_COUNT)
.map(|_| Default::default())
.collect(),
}
}
}
pub(crate) static POOL: LazyLock<ShardedSet> = LazyLock::new(Default::default);
pub fn is_empty() -> bool {
POOL.is_empty()
}
pub fn len() -> usize {
POOL.len()
}
pub fn capacity() -> usize {
POOL.capacity()
}
pub fn get_memory_usage() -> MemoryUsage {
POOL.get_memory_usage()
}
pub fn shrink_to_fit() {
POOL.shrink_to_fit();
}