pubfn mutex_into_inner_impl<T>(m: MutexImpl<T>) -> T {
m.into_inner()
}
}
#[cfg(feature = "abi_stable")] use abi_stable_impl::*;
/// An insert-only map for caching the result of functions #[cfg_attr(feature = "abi_stable", derive(abi_stable::StableAbi))] #[cfg_attr(feature = "abi_stable", repr(C))] pubstruct CacheMap<K, V, S = RandomState> {
inner: MutexImpl<HashMapImpl<K, BoxImpl<V>, S>>,
}
impl<'a, K, V, S> IntoIterator for &'a CacheMap<K, V, S> { type Item = (&'a K, &'a V); type IntoIter = Iter<'a, K, V, S>;
fn into_iter(self) -> Self::IntoIter { let guard = mutex_lock_impl(&self.inner); let iter = unsafe {
std::mem::transmute::<IterImpl<K, BoxImpl<V>>, IterImpl<K, BoxImpl<V>>>(guard.iter())
};
Iter {
iter,
_guard: guard,
}
}
}
impl<K: Eq + Hash, V, S: BuildHasher> CacheMap<K, V, S> { /// Fetch the value associated with the key, or run the provided function to insert one. /// /// # Example /// /// ``` /// use cachemap2::CacheMap; /// /// let m = CacheMap::new(); /// /// let fst = m.cache("key", || 5u32); /// let snd = m.cache("key", || 7u32); /// /// assert_eq!(*fst, *snd); /// assert_eq!(*fst, 5u32); /// ``` pubfn cache<F: FnOnce() -> V>(&self, key: K, f: F) -> &V { let v = std::ptr::NonNull::from(
mutex_lock_impl(&self.inner)
.entry(key)
.or_insert_with(|| BoxImpl::new(f()))
.as_ref(),
); // Safety: We only support adding entries to the hashmap, and as long as a reference is // maintained the value will be present. unsafe { v.as_ref() }
}
/// Fetch the value associated with the key, or insert a default value. pubfn cache_default(&self, key: K) -> &V where
V: Default,
{ self.cache(key, || Default::default())
}
/// Return whether the map contains the given key. pubfn contains_key<Q: ?Sized>(&self, key: &Q) -> bool where
K: std::borrow::Borrow<Q>,
Q: Hash + Eq,
{
mutex_lock_impl(&self.inner).contains_key(key)
}
/// Return an iterator over the map. /// /// This iterator will lock the underlying map until it is dropped. pubfn iter(&self) -> Iter<K, V, S> { self.into_iter()
}
}
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.