Skip to main content

intern_mint/
pool.rs

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    /// Sum of the allocation sizes of the entries in `table`
12    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    /// Bytes allocated for the entries themselves, each a small header followed by the data, as
23    /// requested from the allocator
24    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        // copied from https://github.com/xacrimon/dashmap/blob/366ce7e7872866a06de66eb95002fa6cf2c117a7/src/lib.rs#L419
36        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        // hash before locking
42        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            // Safety: the shard is locked
52            .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        // Safety: entries are only accessed while the shard is locked
60        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        // Safety: the shard is locked
73        unsafe { entry.get().acquire() }
74    }
75
76    /// Gives up a handle, removing `entry` from the pool if it was the last one
77    ///
78    /// # Safety
79    ///
80    /// The caller must own the handle being given up, and must not use it after this call
81    pub(crate) unsafe fn release(&self, entry: Entry) {
82        // read before releasing, since another thread may free the entry right after
83        // Safety: the handle being given up keeps the entry alive until then
84        let hash = unsafe { entry.hash() };
85
86        // Safety: guaranteed by the caller
87        if !unsafe { entry.release() } {
88            return;
89        }
90
91        // `entry` may be dangling from here on, so it's only compared by address
92        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            // another thread already removed it
97            return;
98        };
99
100        // check again in case a new handle was acquired before the shard was locked
101        // Safety: the shard is locked
102        if !unsafe { found.get().is_unused() } {
103            return;
104        }
105
106        let (removed, _) = found.remove();
107        // Safety: the shard is still locked, so the entry hasn't been freed
108        *bytes -= unsafe { removed.allocation_size() };
109        // free outside of the lock
110        drop(shard);
111        // Safety: the entry was removed with no handles left, so nothing can reach it anymore
112        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            // Safety: the shard is locked
149            shard.lock().table.shrink_to_fit(|o| unsafe { o.hash() });
150        }
151    }
152}
153
154impl Default for ShardedSet {
155    fn default() -> Self {
156        // copied from https://github.com/xacrimon/dashmap/blob/366ce7e7872866a06de66eb95002fa6cf2c117a7/src/lib.rs#L63
157        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        // based on https://github.com/xacrimon/dashmap/blob/366ce7e7872866a06de66eb95002fa6cf2c117a7/src/lib.rs#L269
162        // using the width of the u64 hash rather than usize, which is narrower on 32-bit targets
163        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}