| 1 |
use dashmap::DashMap; |
| 2 |
use std::ops::Deref; |
| 3 |
use std::sync::Arc; |
| 4 |
use std::{collections::hash_map::RandomState, hash::Hash}; |
| 5 |
use std::{hash::BuildHasher, marker::PhantomData}; |
| 6 |
|
| 7 |
/// An insert-only map for caching the result of functions |
| 8 |
pub struct CacheMap<K: Hash + Eq, V: ?Sized, S = RandomState> { |
| 9 |
inner: DashMap<K, Arc<V>, S>, |
| 10 |
} |
| 11 |
|
| 12 |
/// A handle that can be converted to a &T or an Arc<T> |
| 13 |
pub struct ArcRef<'a, T: ?Sized> { |
| 14 |
// this pointer never gets dereferenced, but it has to be T, so that Ref is the right size for wide pointers |
| 15 |
#[allow(dead_code)] |
| 16 |
fake_ptr: *const T, |
| 17 |
phantom: PhantomData<&'a T>, |
| 18 |
} |
| 19 |
|
| 20 |
impl<'a, T: ?Sized> Clone for ArcRef<'a, T> { |
| 21 |
fn clone(&self) -> Self { |
| 22 |
*self |
| 23 |
} |
| 24 |
} |
| 25 |
impl<'a, T: ?Sized> Copy for ArcRef<'a, T> {} |
| 26 |
|
| 27 |
impl<T: ?Sized> Deref for ArcRef<'_, T> { |
| 28 |
type Target = Arc<T>; |
| 29 |
fn deref(&self) -> &Self::Target { |
| 30 |
unsafe { std::mem::transmute(self) } |
| 31 |
} |
| 32 |
} |
| 33 |
|
| 34 |
impl<'a, T: ?Sized> ArcRef<'a, T> { |
| 35 |
/// Converts the ArcRef into an Arc<T> |
| 36 |
pub fn to_arc(self) -> Arc<T> { |
| 37 |
self.deref().clone() |
| 38 |
} |
| 39 |
|
| 40 |
/// Converts the ArcRef into a &T |
| 41 |
pub fn as_ref(self) -> &'a T { |
| 42 |
let ptr = &**self as *const T; |
| 43 |
unsafe { &*ptr } |
| 44 |
} |
| 45 |
} |
| 46 |
|
| 47 |
impl<K: Hash + Eq, V: ?Sized, S: BuildHasher + Default + Clone> Default for CacheMap<K, V, S> { |
| 48 |
fn default() -> Self { |
| 49 |
CacheMap { |
| 50 |
inner: Default::default(), |
| 51 |
} |
| 52 |
} |
| 53 |
} |
| 54 |
|
| 55 |
impl<K: Hash + Eq, V, S: BuildHasher + Default + Clone> std::iter::FromIterator<(K, V)> |
| 56 |
for CacheMap<K, V, S> |
| 57 |
{ |
| 58 |
fn from_iter<T>(iter: T) -> Self |
| 59 |
where |
| 60 |
T: IntoIterator<Item = (K, V)>, |
| 61 |
{ |
| 62 |
CacheMap { |
| 63 |
inner: iter.into_iter().map(|(k, v)| (k, Arc::new(v))).collect(), |
| 64 |
} |
| 65 |
} |
| 66 |
} |
| 67 |
|
| 68 |
pub struct IntoIter<K, V, S>(dashmap::iter::OwningIter<K, Arc<V>, S>); |
| 69 |
|
| 70 |
impl<K: Eq + Hash, V, S: BuildHasher + Clone> Iterator for IntoIter<K, V, S> { |
| 71 |
type Item = (K, Arc<V>); |
| 72 |
|
| 73 |
fn next(&mut self) -> Option<Self::Item> { |
| 74 |
self.0.next() |
| 75 |
} |
| 76 |
} |
| 77 |
|
| 78 |
impl<K: Hash + Eq, V, S: BuildHasher + Clone> IntoIterator for CacheMap<K, V, S> { |
| 79 |
type Item = (K, Arc<V>); |
| 80 |
type IntoIter = IntoIter<K, V, S>; |
| 81 |
|
| 82 |
fn into_iter(self) -> Self::IntoIter { |
| 83 |
IntoIter(self.inner.into_iter()) |
| 84 |
} |
| 85 |
} |
| 86 |
|
| 87 |
impl<K: Hash + Eq, V, S: BuildHasher + Clone> CacheMap<K, V, S> { |
| 88 |
/// Fetch the value associated with the key, or run the provided function to insert one. |
| 89 |
/// |
| 90 |
/// # Example |
| 91 |
/// |
| 92 |
/// ``` |
| 93 |
/// use cachemap2::CacheMap; |
| 94 |
/// |
| 95 |
/// let m = CacheMap::new(); |
| 96 |
/// |
| 97 |
/// let fst = m.cache("key", || 5u32).as_ref(); |
| 98 |
/// let snd = m.cache("key", || 7u32).as_ref(); |
| 99 |
/// |
| 100 |
/// assert_eq!(*fst, *snd); |
| 101 |
/// assert_eq!(*fst, 5u32); |
| 102 |
/// ``` |
| 103 |
pub fn cache<F: FnOnce() -> V>(&self, key: K, f: F) -> ArcRef<'_, V> { |
| 104 |
self.cache_arc(key, || Arc::new(f())) |
| 105 |
} |
| 106 |
|
| 107 |
/// Fetch the value associated with the key, or insert a default value. |
| 108 |
pub fn cache_default(&self, key: K) -> ArcRef<'_, V> |
| 109 |
where |
| 110 |
V: Default, |
| 111 |
{ |
| 112 |
self.cache(key, || Default::default()) |
| 113 |
} |
| 114 |
|
| 115 |
/// Return whether the map contains the given key. |
| 116 |
pub fn contains_key<Q: ?Sized>(&self, key: &Q) -> bool |
| 117 |
where |
| 118 |
K: std::borrow::Borrow<Q>, |
| 119 |
Q: Hash + Eq, |
| 120 |
{ |
| 121 |
self.inner.contains_key(key) |
| 122 |
} |
| 123 |
} |
| 124 |
|
| 125 |
impl<K: Hash + Eq, V: ?Sized> CacheMap<K, V, RandomState> { |
| 126 |
/// Creates a new CacheMap |
| 127 |
pub fn new() -> Self { |
| 128 |
CacheMap { |
| 129 |
inner: DashMap::new(), |
| 130 |
} |
| 131 |
} |
| 132 |
} |
| 133 |
|
| 134 |
impl<K: Hash + Eq, V: ?Sized, S: BuildHasher + Clone> CacheMap<K, V, S> { |
| 135 |
/// Creates a new CacheMap with the provided hasher |
| 136 |
pub fn with_hasher(hash_builder: S) -> Self { |
| 137 |
Self { |
| 138 |
inner: DashMap::with_hasher(hash_builder), |
| 139 |
} |
| 140 |
} |
| 141 |
|
| 142 |
/// Fetch the value associated with the key, or run the provided function to insert one. |
| 143 |
/// With this version, the function returns an Arc<V>, whch allows caching unsized types. |
| 144 |
/// |
| 145 |
/// # Example |
| 146 |
/// |
| 147 |
/// ``` |
| 148 |
/// use cachemap2::CacheMap; |
| 149 |
/// |
| 150 |
/// let m: CacheMap<_, [usize]> = CacheMap::new(); |
| 151 |
/// |
| 152 |
/// let a = m.cache_arc("a", || { |
| 153 |
/// let a = &[1,2,3][..]; |
| 154 |
/// a.into() |
| 155 |
/// }).as_ref(); |
| 156 |
/// |
| 157 |
/// let b = m.cache_arc("b", || { |
| 158 |
/// let b = &[9,9][..]; |
| 159 |
/// b.into() |
| 160 |
/// }).as_ref(); |
| 161 |
/// |
| 162 |
/// assert_eq!(a, &[1,2,3]); |
| 163 |
/// assert_eq!(b, &[9,9]); |
| 164 |
/// ``` |
| 165 |
pub fn cache_arc<F: FnOnce() -> Arc<V>>(&self, key: K, f: F) -> ArcRef<'_, V> { |
| 166 |
let val = self.inner.entry(key).or_insert_with(f); |
| 167 |
let arc: &Arc<V> = &*val; |
| 168 |
let arc_ref: &ArcRef<'_, V> = unsafe { std::mem::transmute(arc) }; |
| 169 |
*arc_ref |
| 170 |
} |
| 171 |
} |
| 172 |
|
| 173 |
#[cfg(test)] |
| 174 |
mod tests { |
| 175 |
use super::*; |
| 176 |
|
| 177 |
#[test] |
| 178 |
fn single_insert() { |
| 179 |
let m = CacheMap::new(); |
| 180 |
|
| 181 |
let a = m.cache("key", || 21u32).as_ref(); |
| 182 |
assert_eq!(21, *a); |
| 183 |
} |
| 184 |
|
| 185 |
#[test] |
| 186 |
fn contains_key() { |
| 187 |
let m = CacheMap::new(); |
| 188 |
|
| 189 |
m.cache("key", || 21u32); |
| 190 |
assert!(m.contains_key("key")); |
| 191 |
assert!(!m.contains_key("other")); |
| 192 |
} |
| 193 |
|
| 194 |
#[test] |
| 195 |
fn double_insert() { |
| 196 |
let m = CacheMap::new(); |
| 197 |
|
| 198 |
let a = m.cache("key", || 5u32).as_ref(); |
| 199 |
let b = m.cache("key", || 7u32).as_ref(); |
| 200 |
|
| 201 |
assert_eq!(*a, *b); |
| 202 |
assert_eq!(5, *a); |
| 203 |
} |
| 204 |
|
| 205 |
#[test] |
| 206 |
fn insert_two() { |
| 207 |
let m = CacheMap::new(); |
| 208 |
|
| 209 |
let a = m.cache("a", || 5u32).as_ref(); |
| 210 |
let b = m.cache("b", || 7u32).as_ref(); |
| 211 |
|
| 212 |
assert_eq!(5, *a); |
| 213 |
assert_eq!(7, *b); |
| 214 |
|
| 215 |
let c = m.cache("a", || 9u32).as_ref(); |
| 216 |
let d = m.cache("b", || 11u32).as_ref(); |
| 217 |
|
| 218 |
assert_eq!(*a, *c); |
| 219 |
assert_eq!(*b, *d); |
| 220 |
|
| 221 |
assert_eq!(5, *a); |
| 222 |
assert_eq!(7, *b); |
| 223 |
} |
| 224 |
|
| 225 |
#[test] |
| 226 |
fn use_after_drop() { |
| 227 |
#[derive(Clone)] |
| 228 |
struct Foo(usize); |
| 229 |
impl Drop for Foo { |
| 230 |
fn drop(&mut self) { |
| 231 |
assert_eq!(33, self.0); |
| 232 |
} |
| 233 |
} |
| 234 |
|
| 235 |
{ |
| 236 |
let mut arc = { |
| 237 |
let m = CacheMap::new(); |
| 238 |
let a = m.cache("key", || Foo(99)).to_arc(); |
| 239 |
assert_eq!(99, (*a).0); |
| 240 |
a |
| 241 |
}; |
| 242 |
|
| 243 |
Arc::make_mut(&mut arc).0 = 33; |
| 244 |
} |
| 245 |
|
| 246 |
assert!(true); |
| 247 |
} |
| 248 |
} |