1use std::sync::LazyLock;
2
3use hashbrown::HashTable;
4use parking_lot::{Mutex, MutexGuard};
5
6use crate::entry::Entry;
7
8type LockedShard = HashTable<Entry>;
9type Shard = Mutex<LockedShard>;
10
11#[derive(Debug, Default, Clone, Copy)]
12pub struct MemoryUsage {
13 pub len: usize,
14 pub capacity: usize,
15}
16
17pub(crate) struct ShardedSet {
18 pub(crate) shift: usize,
19 pub(crate) hash_builder: ahash::RandomState,
20 pub(crate) shards: Box<[Shard]>,
21}
22
23impl ShardedSet {
24 fn get_shard(&self, hash: u64) -> MutexGuard<'_, LockedShard> {
25 let idx = ((hash << 7) >> self.shift) as usize;
27 self.shards[idx].lock()
28 }
29
30 fn get_hash_and_shard(&self, value: &[u8]) -> (u64, MutexGuard<'_, LockedShard>) {
31 let hash = self.hash_builder.hash_one(value);
33 (hash, self.get_shard(hash))
34 }
35
36 pub(crate) fn get_from_existing_ref(&self, value: &[u8]) -> Option<Entry> {
37 let (hash, shard) = self.get_hash_and_shard(value);
38 shard
39 .find(hash, |o| std::ptr::eq(o.data_ptr(), value.as_ptr()))
40 .map(|o| unsafe { o.acquire() })
42 }
43
44 pub(crate) fn get_or_insert(&self, value: &[u8]) -> Entry {
45 let (hash, mut shard) = self.get_hash_and_shard(value);
46
47 let entry = shard
49 .entry(
50 hash,
51 |o| unsafe { o.data() } == value,
52 |o| unsafe { o.hash() },
53 )
54 .or_insert_with(|| Entry::new(value, hash));
55
56 unsafe { entry.get().acquire() }
58 }
59
60 pub(crate) unsafe fn release(&self, entry: Entry) {
66 let hash = unsafe { entry.hash() };
69
70 if !unsafe { entry.release() } {
72 return;
73 }
74
75 let mut shard = self.get_shard(hash);
77
78 let Ok(found) = shard.find_entry(hash, |o| *o == entry) else {
79 return;
81 };
82
83 if !unsafe { found.get().is_unused() } {
86 return;
87 }
88
89 let (removed, _) = found.remove();
90 drop(shard);
92 unsafe { removed.free() };
94 }
95
96 pub(crate) fn is_empty(&self) -> bool {
97 self.len() == 0
98 }
99
100 pub(crate) fn len(&self) -> usize {
101 self.shards.iter().map(|o| o.lock().len()).sum()
102 }
103
104 pub(crate) fn capacity(&self) -> usize {
105 self.shards.iter().map(|o| o.lock().capacity()).sum()
106 }
107
108 pub(crate) fn get_memory_usage(&self) -> MemoryUsage {
109 self.shards
110 .iter()
111 .map(|o| {
112 let o = o.lock();
113 MemoryUsage {
114 len: o.len(),
115 capacity: o.capacity(),
116 }
117 })
118 .reduce(|acc, o| MemoryUsage {
119 len: acc.len + o.len,
120 capacity: acc.capacity + o.capacity,
121 })
122 .unwrap_or_default()
123 }
124
125 pub(crate) fn shrink_to_fit(&self) {
126 for shard in self.shards.iter() {
127 shard.lock().shrink_to_fit(|o| unsafe { o.hash() });
129 }
130 }
131}
132
133impl Default for ShardedSet {
134 fn default() -> Self {
135 static DEFAULT_SHARDS_COUNT: LazyLock<usize> = LazyLock::new(|| {
137 (std::thread::available_parallelism().map_or(1, usize::from) * 4).next_power_of_two()
138 });
139
140 let shift = (u64::BITS - DEFAULT_SHARDS_COUNT.trailing_zeros()) as usize;
143
144 Self {
145 shift,
146 hash_builder: Default::default(),
147 shards: (0..*DEFAULT_SHARDS_COUNT)
148 .map(|_| Default::default())
149 .collect(),
150 }
151 }
152}
153
154pub(crate) static POOL: LazyLock<ShardedSet> = LazyLock::new(Default::default);
155
156pub fn is_empty() -> bool {
157 POOL.is_empty()
158}
159
160pub fn len() -> usize {
161 POOL.len()
162}
163
164pub fn capacity() -> usize {
165 POOL.capacity()
166}
167
168pub fn get_memory_usage() -> MemoryUsage {
169 POOL.get_memory_usage()
170}
171
172pub fn shrink_to_fit() {
173 POOL.shrink_to_fit();
174}