pub struct OnceMap<K, V, S = RandomState> { /* private fields */ }Expand description
Run tasks only once and store the results in a parallel hash map.
We often have jobs Fn(K) -> V that we only want to run once and memoize, e.g. network
requests for metadata. When multiple tasks start the same query in parallel, e.g. through source
dist builds, we want to wait until the other task is done and get a reference to the same
result.
Note that this always clones the value out of the underlying map. Because
of this, it’s common to wrap the V in an Arc<V> to make cloning cheap.
Implementations§
Source§impl<K: Eq + Hash + Clone, V: Clone, H: BuildHasher + Clone> OnceMap<K, V, H>
impl<K: Eq + Hash + Clone, V: Clone, H: BuildHasher + Clone> OnceMap<K, V, H>
Sourcepub async fn register_or_wait(&self, key: &K) -> Option<V>
pub async fn register_or_wait(&self, key: &K) -> Option<V>
Register that you want to start a job, unless it was already started, then wait for its result.
Use this method for once-only operations.
Returns None if the job needs to be started, otherwise returns the result of the job.
§Example
ⓘ
if let Some(response) = cache.register_or_wait(&id).await {
response
} else {
let response = fetch(&id).await;
cache.done(id, response.clone());
response
}Trait Implementations§
Auto Trait Implementations§
impl<K, V, S = RandomState> !Freeze for OnceMap<K, V, S>
impl<K, V, S> RefUnwindSafe for OnceMap<K, V, S>where
HashMap<K, Value<V>, S>: RefUnwindSafe,
impl<K, V, S> Send for OnceMap<K, V, S>
impl<K, V, S> Sync for OnceMap<K, V, S>
impl<K, V, S> Unpin for OnceMap<K, V, S>
impl<K, V, S> UnsafeUnpin for OnceMap<K, V, S>where
HashMap<K, Value<V>, S>: UnsafeUnpin,
impl<K, V, S> UnwindSafe for OnceMap<K, V, S>where
HashMap<K, Value<V>, S>: UnwindSafe,
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