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
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        // copied from https://github.com/xacrimon/dashmap/blob/366ce7e7872866a06de66eb95002fa6cf2c117a7/src/lib.rs#L419
26        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        // hash before locking
32        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            // Safety: the shard is locked
41            .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        // Safety: entries are only accessed while the shard is locked
48        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        // Safety: the shard is locked
57        unsafe { entry.get().acquire() }
58    }
59
60    /// Gives up a handle, removing `entry` from the pool if it was the last one
61    ///
62    /// # Safety
63    ///
64    /// The caller must own the handle being given up, and must not use it after this call
65    pub(crate) unsafe fn release(&self, entry: Entry) {
66        // read before releasing, since another thread may free the entry right after
67        // Safety: the handle being given up keeps the entry alive until then
68        let hash = unsafe { entry.hash() };
69
70        // Safety: guaranteed by the caller
71        if !unsafe { entry.release() } {
72            return;
73        }
74
75        // `entry` may be dangling from here on, so it's only compared by address
76        let mut shard = self.get_shard(hash);
77
78        let Ok(found) = shard.find_entry(hash, |o| *o == entry) else {
79            // another thread already removed it
80            return;
81        };
82
83        // check again in case a new handle was acquired before the shard was locked
84        // Safety: the shard is locked
85        if !unsafe { found.get().is_unused() } {
86            return;
87        }
88
89        let (removed, _) = found.remove();
90        // free outside of the lock
91        drop(shard);
92        // Safety: the entry was removed with no handles left, so nothing can reach it anymore
93        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            // Safety: the shard is locked
128            shard.lock().shrink_to_fit(|o| unsafe { o.hash() });
129        }
130    }
131}
132
133impl Default for ShardedSet {
134    fn default() -> Self {
135        // copied from https://github.com/xacrimon/dashmap/blob/366ce7e7872866a06de66eb95002fa6cf2c117a7/src/lib.rs#L63
136        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        // based on https://github.com/xacrimon/dashmap/blob/366ce7e7872866a06de66eb95002fa6cf2c117a7/src/lib.rs#L269
141        // using the width of the u64 hash rather than usize, which is narrower on 32-bit targets
142        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}