1use std::sync::LazyLock;
2
3use hashbrown::HashTable;
4use parking_lot::{Mutex, MutexGuard};
5
6use crate::entry::Entry;
7
8#[derive(Default)]
9pub(crate) struct LockedShard {
10 table: HashTable<Entry>,
11 bytes: usize,
13}
14
15type Shard = Mutex<LockedShard>;
16
17#[derive(Debug, Default, Clone, Copy)]
18#[non_exhaustive]
19pub struct MemoryUsage {
20 pub len: usize,
21 pub capacity: usize,
22 pub bytes: usize,
25}
26
27pub(crate) struct ShardedSet {
28 pub(crate) shift: usize,
29 pub(crate) hash_builder: ahash::RandomState,
30 pub(crate) shards: Box<[Shard]>,
31}
32
33impl ShardedSet {
34 fn get_shard(&self, hash: u64) -> MutexGuard<'_, LockedShard> {
35 let idx = ((hash << 7) >> self.shift) as usize;
37 self.shards[idx].lock()
38 }
39
40 fn get_hash_and_shard(&self, value: &[u8]) -> (u64, MutexGuard<'_, LockedShard>) {
41 let hash = self.hash_builder.hash_one(value);
43 (hash, self.get_shard(hash))
44 }
45
46 pub(crate) fn get_from_existing_ref(&self, value: &[u8]) -> Option<Entry> {
47 let (hash, shard) = self.get_hash_and_shard(value);
48 shard
49 .table
50 .find(hash, |o| std::ptr::eq(o.data_ptr(), value.as_ptr()))
51 .map(|o| unsafe { o.acquire() })
53 }
54
55 pub(crate) fn get_or_insert(&self, value: &[u8]) -> Entry {
56 let (hash, mut shard) = self.get_hash_and_shard(value);
57 let LockedShard { table, bytes } = &mut *shard;
58
59 let entry = table
61 .entry(
62 hash,
63 |o| unsafe { o.data() } == value,
64 |o| unsafe { o.hash() },
65 )
66 .or_insert_with(|| {
67 let entry = Entry::new(value, hash);
68 *bytes += Entry::allocation_size_for(value.len());
69 entry
70 });
71
72 unsafe { entry.get().acquire() }
74 }
75
76 pub(crate) unsafe fn release(&self, entry: Entry) {
82 let hash = unsafe { entry.hash() };
85
86 if !unsafe { entry.release() } {
88 return;
89 }
90
91 let mut shard = self.get_shard(hash);
93 let LockedShard { table, bytes } = &mut *shard;
94
95 let Ok(found) = table.find_entry(hash, |o| *o == entry) else {
96 return;
98 };
99
100 if !unsafe { found.get().is_unused() } {
103 return;
104 }
105
106 let (removed, _) = found.remove();
107 *bytes -= unsafe { removed.allocation_size() };
109 drop(shard);
111 unsafe { removed.free() };
113 }
114
115 pub(crate) fn is_empty(&self) -> bool {
116 self.shards.iter().all(|s| s.lock().table.is_empty())
117 }
118
119 pub(crate) fn len(&self) -> usize {
120 self.shards.iter().map(|o| o.lock().table.len()).sum()
121 }
122
123 pub(crate) fn capacity(&self) -> usize {
124 self.shards.iter().map(|o| o.lock().table.capacity()).sum()
125 }
126
127 pub(crate) fn get_memory_usage(&self) -> MemoryUsage {
128 self.shards
129 .iter()
130 .map(|o| {
131 let o = o.lock();
132 MemoryUsage {
133 len: o.table.len(),
134 capacity: o.table.capacity(),
135 bytes: o.bytes,
136 }
137 })
138 .reduce(|acc, o| MemoryUsage {
139 len: acc.len + o.len,
140 capacity: acc.capacity + o.capacity,
141 bytes: acc.bytes + o.bytes,
142 })
143 .unwrap_or_default()
144 }
145
146 pub(crate) fn shrink_to_fit(&self) {
147 for shard in self.shards.iter() {
148 shard.lock().table.shrink_to_fit(|o| unsafe { o.hash() });
150 }
151 }
152}
153
154impl Default for ShardedSet {
155 fn default() -> Self {
156 static DEFAULT_SHARDS_COUNT: LazyLock<usize> = LazyLock::new(|| {
158 (std::thread::available_parallelism().map_or(1, usize::from) * 4).next_power_of_two()
159 });
160
161 let shift = (u64::BITS - DEFAULT_SHARDS_COUNT.trailing_zeros()) as usize;
164
165 Self {
166 shift,
167 hash_builder: Default::default(),
168 shards: (0..*DEFAULT_SHARDS_COUNT)
169 .map(|_| Default::default())
170 .collect(),
171 }
172 }
173}
174
175pub(crate) static POOL: LazyLock<ShardedSet> = LazyLock::new(Default::default);
176
177pub fn is_empty() -> bool {
178 POOL.is_empty()
179}
180
181pub fn len() -> usize {
182 POOL.len()
183}
184
185pub fn capacity() -> usize {
186 POOL.capacity()
187}
188
189pub fn get_memory_usage() -> MemoryUsage {
190 POOL.get_memory_usage()
191}
192
193pub fn shrink_to_fit() {
194 POOL.shrink_to_fit();
195}