use alloc::vec::Vec;
use std::sync::{Mutex, MutexGuard, PoisonError};
use super::{Entry, SlotTable, Table, TableKey};
#[derive(Debug)]
pub struct SharedTable<K, M, S> {
shards: Vec<Mutex<SlotTable<K, M, S>>>,
}
impl<K: TableKey, M: Clone, S: Clone> SharedTable<K, M, S> {
#[must_use]
pub fn new(capacity: usize, shards: usize) -> Self {
let shards = shards
.max(1)
.checked_next_power_of_two()
.expect("the shard count fits in usize when rounded up");
let per_shard = capacity.div_ceil(shards);
Self {
shards: (0..shards)
.map(|_| Mutex::new(SlotTable::new(per_shard)))
.collect(),
}
}
#[must_use]
pub fn capacity(&self) -> usize {
self.shards.len() * lock(&self.shards[0]).capacity()
}
pub fn clear(&self) {
for shard in &self.shards {
lock(shard).clear();
}
}
fn shard(&self, key: &K) -> MutexGuard<'_, SlotTable<K, M, S>> {
lock(&self.shards[self.index(key)])
}
fn index(&self, key: &K) -> usize {
let bits = self.shards.len().trailing_zeros();
let mixed = key.slot().wrapping_mul(0x9e37_79b9_7f4a_7c15);
if bits == 0 {
return 0;
}
usize::try_from(mixed >> (64 - bits)).expect("a shard index is below the shard count")
}
}
fn lock<T>(shard: &Mutex<T>) -> MutexGuard<'_, T> {
shard.lock().unwrap_or_else(PoisonError::into_inner)
}
impl<K: TableKey, M: Clone, S: Clone> Table<K, M, S> for &SharedTable<K, M, S> {
fn probe(&mut self, key: &K) -> Option<Entry<M, S>> {
self.shard(key).probe(key)
}
fn store(&mut self, key: K, entry: Entry<M, S>) {
self.shard(&key).store(key, entry);
}
}
#[cfg(test)]
mod tests {
use alloc::collections::BTreeSet;
use super::SharedTable;
#[test]
fn small_keys_spread_over_the_shards() {
let table = SharedTable::<u64, u8, i32>::new(1024, 8);
let shards: BTreeSet<usize> = (0..64_u64).map(|key| table.index(&key)).collect();
assert!(shards.len() >= 6, "{shards:?}");
assert_eq!(SharedTable::<u64, u8, i32>::new(16, 1).index(&5), 0);
}
}