Skip to main content

fast_cache/storage/embedded_store_sharded/
thread_local.rs

1use super::*;
2
3impl WorkerLocalEmbeddedStore {
4    /// Install this store into the current thread's local worker slot.
5    ///
6    /// Only one worker-local store can be installed per thread. Use
7    /// [`crate::storage::take_local_embedded_store`] to remove it again.
8    pub fn install_local(self) -> Result<(), LocalStoreInstallError> {
9        THREAD_LOCAL_EMBEDDED_STORE.with(|slot| {
10            let mut slot = slot.borrow_mut();
11            if slot.is_some() {
12                return Err(LocalStoreInstallError::AlreadyInstalled);
13            }
14            *slot = Some(self);
15            Ok(())
16        })
17    }
18}
19
20/// Run a closure against the worker-local embedded store installed on this thread.
21pub fn with_thread_local_embedded_store<R>(
22    f: impl FnOnce(&mut WorkerLocalEmbeddedStore) -> R,
23) -> Result<R, LocalStoreAccessError> {
24    THREAD_LOCAL_EMBEDDED_STORE.with(|slot| {
25        let mut slot = slot.borrow_mut();
26        let store = slot.as_mut().ok_or(LocalStoreAccessError::NotInstalled)?;
27        Ok(f(store))
28    })
29}
30
31/// Remove and return the worker-local embedded store installed on this thread.
32pub fn take_thread_local_embedded_store() -> Option<WorkerLocalEmbeddedStore> {
33    THREAD_LOCAL_EMBEDDED_STORE.with(|slot| slot.borrow_mut().take())
34}