djs_cache/
dashmap_store.rs1use core::{fmt, hash::Hash};
4use std::sync::Arc;
5
6use dashmap::DashMap;
7
8use crate::{Backend, Limit, Resource, Store};
9
10pub(crate) type Hasher = foldhash::fast::RandomState;
14
15#[derive(Clone, Copy, Debug, Default)]
29#[non_exhaustive]
30pub struct DashMapBackend;
31
32impl DashMapBackend {
33 #[must_use]
37 pub const fn new() -> Self {
38 Self
39 }
40}
41
42impl Backend for DashMapBackend {
43 type Store<K, V>
44 = DashMapStore<K, V>
45 where
46 K: Eq + Hash + Copy + Send + Sync + 'static,
47 V: Send + Sync + 'static;
48
49 fn store<K, V>(&self, _resource: Resource, _limit: Limit) -> DashMapStore<K, V>
50 where
51 K: Eq + Hash + Copy + Send + Sync + 'static,
52 V: Send + Sync + 'static,
53 {
54 DashMapStore::new()
55 }
56}
57
58pub struct DashMapStore<K, V> {
80 map: DashMap<K, Arc<V>, Hasher>,
81}
82
83impl<K: Eq + Hash, V> DashMapStore<K, V> {
84 #[must_use]
88 pub fn new() -> Self {
89 Self {
90 map: DashMap::with_hasher(Hasher::default()),
91 }
92 }
93}
94
95impl<K: Eq + Hash, V> Default for DashMapStore<K, V> {
96 fn default() -> Self {
97 Self::new()
98 }
99}
100
101impl<K: Eq + Hash, V> fmt::Debug for DashMapStore<K, V> {
102 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
103 f.debug_struct("DashMapStore")
104 .field("len", &self.map.len())
105 .finish_non_exhaustive()
106 }
107}
108
109impl<K, V> Store<K, V> for DashMapStore<K, V>
110where
111 K: Eq + Hash + Copy + Send + Sync,
112 V: Send + Sync,
113{
114 fn get(&self, key: &K) -> Option<Arc<V>> {
115 self.map.get(key).map(|entry| Arc::clone(entry.value()))
116 }
117
118 fn insert(&self, key: K, value: Arc<V>) -> Option<Arc<V>> {
119 self.map.insert(key, value)
120 }
121
122 fn remove(&self, key: &K) -> Option<Arc<V>> {
123 self.map.remove(key).map(|(_, value)| value)
124 }
125
126 fn len(&self) -> usize {
127 self.map.len()
128 }
129
130 fn is_empty(&self) -> bool {
131 self.map.is_empty()
132 }
133
134 fn contains_key(&self, key: &K) -> bool {
135 self.map.contains_key(key)
136 }
137
138 fn retain(&self, keep: &mut dyn FnMut(&K, &V) -> bool) {
139 self.map.retain(|key, value| keep(key, value));
140 }
141
142 fn values(&self) -> Vec<Arc<V>> {
143 self.map
144 .iter()
145 .map(|entry| Arc::clone(entry.value()))
146 .collect()
147 }
148
149 fn keys(&self) -> Vec<K> {
150 self.map.iter().map(|entry| *entry.key()).collect()
151 }
152}
153
154#[cfg(test)]
155mod tests {
156 use std::{sync::Arc, thread};
157
158 use super::{DashMapBackend, DashMapStore};
159 use crate::{Backend, Limit, Resource, Store};
160
161 #[test]
162 fn insert_get_remove() {
163 let store = DashMapBackend::new().store::<u64, String>(Resource::Guild, Limit::Unlimited);
164 assert!(store.is_empty());
165 assert!(store.insert(1, Arc::new("a".to_owned())).is_none());
166 assert_eq!(
167 store
168 .insert(1, Arc::new("b".to_owned()))
169 .as_deref()
170 .map(String::as_str),
171 Some("a")
172 );
173 assert!(store.contains_key(&1));
174 assert_eq!(store.get(&1).as_deref().map(String::as_str), Some("b"));
175 assert_eq!(store.len(), 1);
176 assert_eq!(store.remove(&1).as_deref().map(String::as_str), Some("b"));
177 assert!(store.remove(&1).is_none());
178 assert!(!store.contains_key(&1));
179 }
180
181 #[test]
182 fn retain_and_values() {
183 let store = DashMapStore::new();
184 for key in 0..100_u64 {
185 store.insert(key, Arc::new(key * 10));
186 }
187 store.retain(&mut |key, _| key % 2 == 0);
188 assert_eq!(store.len(), 50);
189 let mut keys = store.keys();
190 keys.sort_unstable();
191 assert_eq!(keys, (0..100).step_by(2).collect::<Vec<_>>());
192 let mut values: Vec<u64> = store.values().iter().map(|value| **value).collect();
193 values.sort_unstable();
194 assert_eq!(
195 values,
196 (0..100).step_by(2).map(|key| key * 10).collect::<Vec<_>>()
197 );
198 }
199
200 #[test]
201 fn concurrent_writers_do_not_lose_entries() {
202 let store = Arc::new(DashMapStore::new());
203 let threads: Vec<_> = (0..8_u64)
204 .map(|thread| {
205 let store = Arc::clone(&store);
206 thread::spawn(move || {
207 for key in 0..10_000 {
208 store.insert(thread * 10_000 + key, Arc::new(key));
209 }
210 })
211 })
212 .collect();
213 for thread in threads {
214 thread.join().unwrap();
215 }
216 assert_eq!(store.len(), 80_000);
217 }
218
219 #[test]
220 fn debug_shows_the_length() {
221 let store = DashMapStore::new();
222 store.insert(1_u64, Arc::new(()));
223 assert_eq!(format!("{store:?}"), "DashMapStore { len: 1, .. }");
224 }
225}