Debian Codegraph @

src/lib.rs

raw symbols SCIP
1 //! A concurrent insert only hash map.
2 //!
3 //! This crate implements a "memo map" which is in many ways similar to a
4 //! [`HashMap`] with some crucial differences:
5 //!
6 //! * Unlike a regular hash map, a memo map is thread safe and synchronized.
7 //! * Adding or retrieving keys works through a shared reference, removing only
8 //! through a mutable reference.
9 //! * Retrieving a value from a memo map returns a plain old reference.
10 //!
11 //! Together these purposes allow one to use this type of structure to
12 //! implement something similar to lazy loading in places where the API
13 //! has been constrained to references before.
14 //!
15 //! The values in the map are individually boxed up so that resizing of the
16 //! map retains the previously issued references.
17 //!
18 //! ```
19 //! use memo_map::MemoMap;
20 //!
21 //! let memo = MemoMap::new();
22 //! let one = memo.get_or_insert(&1, || "one".to_string());
23 //! let one2 = memo.get_or_insert(&1, || "not one".to_string());
24 //! assert_eq!(one, "one");
25 //! assert_eq!(one2, "one");
26 //! ```
27 //!
28 //! # Notes on Iteration
29 //!
30 //! Because the memo map internally uses a mutex it needs to be held during
31 //! iteration. This is potentially dangerous as it means you can easily
32 //! deadlock yourself when trying to use the memo map while iterating. The
33 //! iteration functionality thus has to be used with great care.
34 //!
35 //! # Notes on Removal
36 //!
37 //! Items can be removed from a memo map but this operation requires a mutable
38 //! reference to the memo map. This is so that it can ensure that there are no
39 //! borrows outstanding that would be invalidated through the removal of the item.
40 use std::borrow::Borrow;
41 use std::collections::hash_map::{Entry, RandomState};
42 use std::collections::HashMap;
43 use std::convert::Infallible;
44 use std::hash::{BuildHasher, Hash};
45 use std::mem::{transmute, ManuallyDrop};
46 use std::sync::{Mutex, MutexGuard};
47
48 macro_rules! lock {
49 ($mutex:expr) => {
50 match $mutex.lock() {
51 Ok(guard) => guard,
52 Err(poisoned) => poisoned.into_inner(),
53 }
54 };
55 }
56
57 /// An insert only, thread safe hash map to memoize values.
58 #[derive(Debug)]
59 pub struct MemoMap<K, V, S = RandomState> {
60 inner: Mutex<HashMap<K, Box<V>, S>>,
61 }
62
63 impl<K: Clone, V: Clone, S: Clone> Clone for MemoMap<K, V, S> {
64 fn clone(&self) -> Self {
65 Self {
66 inner: Mutex::new(lock!(self.inner).clone()),
67 }
68 }
69 }
70
71 impl<K, V, S: Default> Default for MemoMap<K, V, S> {
72 fn default() -> Self {
73 MemoMap {
74 inner: Mutex::new(HashMap::default()),
75 }
76 }
77 }
78
79 impl<K, V> MemoMap<K, V, RandomState> {
80 /// Creates an empty `MemoMap`.
81 pub fn new() -> MemoMap<K, V, RandomState> {
82 MemoMap {
83 inner: Mutex::default(),
84 }
85 }
86 }
87
88 impl<K, V, S> MemoMap<K, V, S> {
89 /// Creates an empty `MemoMap` which will use the given hash builder to hash
90 /// keys.
91 pub fn with_hasher(hash_builder: S) -> MemoMap<K, V, S> {
92 MemoMap {
93 inner: Mutex::new(HashMap::with_hasher(hash_builder)),
94 }
95 }
96 }
97
98 impl<K, V, S> MemoMap<K, V, S>
99 where
100 K: Eq + Hash,
101 S: BuildHasher,
102 {
103 /// Inserts a value into the memo map.
104 ///
105 /// This inserts a value for a specific key into the memo map. If the
106 /// key already exists, this method does nothing and instead returns `false`.
107 /// Otherwise the value is inserted and `true` is returned. It's generally
108 /// recommended to instead use [`get_or_insert`](Self::get_or_insert) or
109 /// it's sibling [`get_or_try_insert`](Self::get_or_try_insert).
110 pub fn insert(&self, key: K, value: V) -> bool {
111 let mut inner = lock!(self.inner);
112 match inner.entry(key) {
113 Entry::Occupied(_) => false,
114 Entry::Vacant(vacant) => {
115 vacant.insert(Box::new(value));
116 true
117 }
118 }
119 }
120
121 /// Inserts a value into the memo map replacing the old value.
122 ///
123 /// This has the same restrictions as [`remove`](Self::remove) and
124 /// [`clear`](Self::clear) in that it requires a mutable reference to
125 /// the map.
126 pub fn replace(&mut self, key: K, value: V) {
127 lock!(self.inner).insert(key, Box::new(value));
128 }
129
130 /// Returns true if the map contains a value for the specified key.
131 ///
132 /// The key may be any borrowed form of the map's key type, but [`Hash`] and
133 /// [`Eq`] on the borrowed form must match those for the key type.
134 pub fn contains_key<Q>(&self, key: &Q) -> bool
135 where
136 Q: Hash + Eq + ?Sized,
137 K: Borrow<Q>,
138 {
139 lock!(self.inner).contains_key(key)
140 }
141
142 /// Returns a reference to the value corresponding to the key.
143 ///
144 /// The key may be any borrowed form of the map's key type, but [`Hash`] and
145 /// [`Eq`] on the borrowed form must match those for the key type.
146 pub fn get<Q>(&self, key: &Q) -> Option<&V>
147 where
148 Q: Hash + Eq + ?Sized,
149 K: Borrow<Q>,
150 {
151 let inner = lock!(self.inner);
152 let value = inner.get(key)?;
153 Some(unsafe { transmute::<_, _>(&**value) })
154 }
155
156 /// Returns a reference to the value corresponding to the key or inserts.
157 ///
158 /// This is the preferred way to work with a memo map: if the value has not
159 /// been in the map yet the creator function is invoked to create the value,
160 /// otherwise the already stored value is returned. The creator function itself
161 /// can be falliable and the error is passed through.
162 ///
163 /// If the creator is infallible, [`get_or_insert`](Self::get_or_insert) can be used.
164 pub fn get_or_try_insert<Q, F, E>(&self, key: &Q, creator: F) -> Result<&V, E>
165 where
166 Q: Hash + Eq + ToOwned<Owned = K> + ?Sized,
167 K: Borrow<Q>,
168 F: FnOnce() -> Result<V, E>,
169 {
170 let mut inner = lock!(self.inner);
171 let value = if let Some(value) = inner.get(key) {
172 value
173 } else {
174 inner.insert(key.to_owned(), Box::new(creator()?));
175 inner.get(key).unwrap()
176 };
177 Ok(unsafe { transmute::<_, _>(&**value) })
178 }
179
180 /// Returns a reference to the value corresponding to the key or inserts.
181 ///
182 /// This is the preferred way to work with a memo map: if the value has not
183 /// been in the map yet the creator function is invoked to create the value,
184 /// otherwise the already stored value is returned.
185 ///
186 /// If the creator is fallible, [`get_or_try_insert`](Self::get_or_try_insert) can be used.
187 ///
188 /// # Example
189 ///
190 /// ```
191 /// # use memo_map::MemoMap;
192 /// let memo = MemoMap::new();
193 ///
194 /// // first time inserts
195 /// let value = memo.get_or_insert("key", || "23");
196 /// assert_eq!(*value, "23");
197 ///
198 /// // second time returns old value
199 /// let value = memo.get_or_insert("key", || "24");
200 /// assert_eq!(*value, "23");
201 /// ```
202 pub fn get_or_insert<Q, F>(&self, key: &Q, creator: F) -> &V
203 where
204 Q: Hash + Eq + ToOwned<Owned = K> + ?Sized,
205 K: Borrow<Q>,
206 F: FnOnce() -> V,
207 {
208 self.get_or_try_insert::<_, _, Infallible>(key, || Ok(creator()))
209 .unwrap()
210 }
211
212 /// Removes a key from the memo map, returning the value at the key if the key
213 /// was previously in the map.
214 ///
215 /// A key can only be removed if a mutable reference to the memo map exists.
216 /// In other words a key can not be removed if there can be borrows to the item.
217 pub fn remove<Q>(&mut self, key: &Q) -> Option<V>
218 where
219 Q: Hash + Eq + ?Sized,
220 K: Borrow<Q>,
221 {
222 lock!(self.inner).remove(key).map(|x| *x)
223 }
224
225 /// Clears the map, removing all elements.
226 pub fn clear(&mut self) {
227 lock!(self.inner).clear();
228 }
229
230 /// Returns the number of items in the map.
231 ///
232 /// # Example
233 ///
234 /// ```
235 /// # use memo_map::MemoMap;
236 /// let memo = MemoMap::new();
237 ///
238 /// assert_eq!(memo.len(), 0);
239 /// memo.insert(1, "a");
240 /// memo.insert(2, "b");
241 /// memo.insert(2, "not b");
242 /// assert_eq!(memo.len(), 2);
243 /// ```
244 pub fn len(&self) -> usize {
245 lock!(self.inner).len()
246 }
247
248 /// Returns `true` if the memo map contains no items.
249 pub fn is_empty(&self) -> bool {
250 lock!(self.inner).is_empty()
251 }
252
253 /// An iterator visiting all key-value pairs in arbitrary order. The
254 /// iterator element type is `(&'a K, &'a V)`.
255 ///
256 /// Important note: during iteration the map is locked! This means that you
257 /// must not perform modifications to the map or you will run into deadlocks.
258 pub fn iter(&self) -> Iter<'_, K, V, S> {
259 let guard = lock!(self.inner);
260 let iter = guard.iter();
261 Iter {
262 iter: unsafe { transmute::<_, _>(iter) },
263 guard: ManuallyDrop::new(guard),
264 }
265 }
266
267 /// An iterator visiting all keys in arbitrary order. The iterator element
268 /// type is `&'a K`.
269 pub fn keys(&self) -> Keys<'_, K, V, S> {
270 Keys { iter: self.iter() }
271 }
272 }
273
274 /// An iterator over the items of a [`MemoMap`].
275 ///
276 /// This struct is created by the [`iter`](MemoMap::iter) method on [`MemoMap`].
277 /// See its documentation for more information.
278 pub struct Iter<'a, K, V, S> {
279 guard: ManuallyDrop<MutexGuard<'a, HashMap<K, Box<V>, S>>>,
280 iter: std::collections::hash_map::Iter<'a, K, Box<V>>,
281 }
282
283 impl<'a, K, V, S> Drop for Iter<'a, K, V, S> {
284 fn drop(&mut self) {
285 unsafe {
286 ManuallyDrop::drop(&mut self.guard);
287 }
288 }
289 }
290
291 impl<'a, K, V, S> Iterator for Iter<'a, K, V, S> {
292 type Item = (&'a K, &'a V);
293
294 fn next(&mut self) -> Option<Self::Item> {
295 self.iter.next().map(|(k, v)| (k, &**v))
296 }
297 }
298
299 /// An iterator over the keys of a [`MemoMap`].
300 ///
301 /// This struct is created by the [`keys`](MemoMap::keys) method on [`MemoMap`].
302 /// See its documentation for more information.
303 pub struct Keys<'a, K, V, S> {
304 iter: Iter<'a, K, V, S>,
305 }
306
307 impl<'a, K, V, S> Iterator for Keys<'a, K, V, S> {
308 type Item = &'a K;
309
310 fn next(&mut self) -> Option<Self::Item> {
311 self.iter.next().map(|(k, _)| k)
312 }
313 }
314
315 #[test]
316 fn test_insert() {
317 let memo = MemoMap::new();
318 assert!(memo.insert(23u32, Box::new(1u32)));
319 assert!(!memo.insert(23u32, Box::new(2u32)));
320 assert_eq!(memo.get(&23u32).cloned(), Some(Box::new(1)));
321 }
322
323 #[test]
324 fn test_iter() {
325 let memo = MemoMap::new();
326 memo.insert(1, "one");
327 memo.insert(2, "two");
328 memo.insert(3, "three");
329 let mut values = memo.iter().map(|(k, v)| (*k, *v)).collect::<Vec<_>>();
330 values.sort();
331 assert_eq!(values, vec![(1, "one"), (2, "two"), (3, "three")]);
332 }
333
334 #[test]
335 fn test_keys() {
336 let memo = MemoMap::new();
337 memo.insert(1, "one");
338 memo.insert(2, "two");
339 memo.insert(3, "three");
340 let mut values = memo.keys().map(|k| *k).collect::<Vec<_>>();
341 values.sort();
342 assert_eq!(values, vec![1, 2, 3]);
343 }
344
345 #[test]
346 fn test_contains() {
347 let memo = MemoMap::new();
348 memo.insert(1, "one");
349 assert!(memo.contains_key(&1));
350 assert!(!memo.contains_key(&2));
351 }
352
353 #[test]
354 fn test_remove() {
355 let mut memo = MemoMap::new();
356 memo.insert(1, "one");
357 let value = memo.get(&1);
358 assert!(value.is_some());
359 drop(value);
360 let old_value = memo.remove(&1);
361 assert_eq!(old_value, Some("one"));
362 let value = memo.get(&1);
363 assert!(value.is_none());
364 drop(value);
365 }
366
367 #[test]
368 fn test_clear() {
369 let mut memo = MemoMap::new();
370 memo.insert(1, "one");
371 memo.insert(2, "two");
372 assert_eq!(memo.len(), 2);
373 assert!(!memo.is_empty());
374 memo.clear();
375 assert_eq!(memo.len(), 0);
376 assert!(memo.is_empty());
377 }
378
379 #[test]
380 fn test_ref_after_resize() {
381 let memo = MemoMap::new();
382 let mut refs = Vec::new();
383
384 let iterations = if cfg!(miri) { 100 } else { 10000 };
385
386 for key in 0..iterations {
387 refs.push((key, memo.get_or_insert(&key, || Box::new(key))));
388 }
389 for (key, val) in refs {
390 dbg!(key, val);
391 assert_eq!(memo.get(&key), Some(val));
392 }
393 }
394
395 #[test]
396 fn test_replace() {
397 let mut memo = MemoMap::new();
398 memo.insert("foo", "bar");
399 memo.replace("foo", "bar2");
400 assert_eq!(memo.get("foo"), Some(&"bar2"));
401 }