game_tree_search/table/
shared.rs1use alloc::vec::Vec;
4use std::sync::{Mutex, MutexGuard, PoisonError};
5
6use super::{Entry, SlotTable, Table, TableKey};
7
8#[derive(Debug)]
19pub struct SharedTable<K, M, S> {
20 shards: Vec<Mutex<SlotTable<K, M, S>>>,
22}
23
24impl<K: TableKey, M: Clone, S: Clone> SharedTable<K, M, S> {
25 #[must_use]
32 pub fn new(capacity: usize, shards: usize) -> Self {
33 let shards = shards
34 .max(1)
35 .checked_next_power_of_two()
36 .expect("the shard count fits in usize when rounded up");
37 let per_shard = capacity.div_ceil(shards);
38
39 Self {
40 shards: (0..shards)
41 .map(|_| Mutex::new(SlotTable::new(per_shard)))
42 .collect(),
43 }
44 }
45
46 #[must_use]
48 pub fn capacity(&self) -> usize {
49 self.shards.len() * lock(&self.shards[0]).capacity()
50 }
51
52 pub fn clear(&self) {
54 for shard in &self.shards {
55 lock(shard).clear();
56 }
57 }
58
59 fn shard(&self, key: &K) -> MutexGuard<'_, SlotTable<K, M, S>> {
63 lock(&self.shards[self.index(key)])
64 }
65
66 fn index(&self, key: &K) -> usize {
68 let bits = self.shards.len().trailing_zeros();
69 let mixed = key.slot().wrapping_mul(0x9e37_79b9_7f4a_7c15);
70 if bits == 0 {
71 return 0;
72 }
73
74 usize::try_from(mixed >> (64 - bits)).expect("a shard index is below the shard count")
75 }
76}
77
78fn lock<T>(shard: &Mutex<T>) -> MutexGuard<'_, T> {
81 shard.lock().unwrap_or_else(PoisonError::into_inner)
82}
83
84impl<K: TableKey, M: Clone, S: Clone> Table<K, M, S> for &SharedTable<K, M, S> {
85 fn probe(&mut self, key: &K) -> Option<Entry<M, S>> {
86 self.shard(key).probe(key)
87 }
88
89 fn store(&mut self, key: K, entry: Entry<M, S>) {
90 self.shard(&key).store(key, entry);
91 }
92}
93
94#[cfg(test)]
96mod tests {
97 use alloc::collections::BTreeSet;
98
99 use super::SharedTable;
100
101 #[test]
103 fn small_keys_spread_over_the_shards() {
104 let table = SharedTable::<u64, u8, i32>::new(1024, 8);
105 let shards: BTreeSet<usize> = (0..64_u64).map(|key| table.index(&key)).collect();
106 assert!(shards.len() >= 6, "{shards:?}");
107 assert_eq!(SharedTable::<u64, u8, i32>::new(16, 1).index(&5), 0);
108 }
109}