pub struct Cache<K, V> {
inner: Mutex<HashMap<K, V>>,
}
Expand description
Cache that remembers the result for each key.
Fields§
§inner: Mutex<HashMap<K, V>>
Implementations§
Source§impl<K: Eq + Hash + Clone, V: Clone> Cache<K, V>
impl<K: Eq + Hash + Clone, V: Clone> Cache<K, V>
Sourcepub fn get_or_insert_with<F: FnOnce(K) -> V>(&self, key: K, f: F) -> V
pub fn get_or_insert_with<F: FnOnce(K) -> V>(&self, key: K, f: F) -> V
Retrieve the value or insert a new one created by f
.
An invocation to this function should not block another invocation with a different key. For
example, if a thread calls get_or_insert_with(key1, f1)
and another thread calls
get_or_insert_with(key2, f2)
(key1≠key2
, key1,key2∉cache
) concurrently, f1
and f2
should run concurrently.
On the other hand, since f
may consume a lot of resource (= money), it’s undesirable to
duplicate the work. That is, f
should be run only once for each key. Specifically, even
for concurrent invocations of get_or_insert_with(key, f)
, f
is called only once per key.
Hint: the Entry
API may be useful in implementing this function.
Trait Implementations§
Auto Trait Implementations§
impl<K, V> !Freeze for Cache<K, V>
impl<K, V> RefUnwindSafe for Cache<K, V>
impl<K, V> Send for Cache<K, V>
impl<K, V> Sync for Cache<K, V>
impl<K, V> Unpin for Cache<K, V>
impl<K, V> UnwindSafe for Cache<K, V>
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more