Expand description
Provides a token type LocalScope that guards access to thread local storage, avoiding the need for a closure on every access.
§Examples
You can use the scoping to gracefully handle errors.
use thread_local_scope::local_scope;
thread_local! {
static WHATEVER: Whatever = Whatever::new();
}
fn with_whatever<R>(f: impl FnOnce(&Whatever) -> R) -> R {
local_scope(|scope| {
if let Ok(x) = scope.try_access(&WHATEVER) {
f(x)
} else {
let stack_local_fallback = Whatever::new();
f(&stack_local_fallback)
}
})
}
// The equivalent without this requires .unwrap()
fn with_whatever_std<R>(f: impl FnOnce(&Whatever) -> R) -> R {
let mut f = Some(f);
WHATEVER
.try_with(|x| f.take().unwrap()(x))
.unwrap_or_else(|_| {
let stack_local_fallback = Whatever::new();
f.unwrap()(&stack_local_fallback)
})
}This allows avoiding nested closures if working with multiple LocalKeys.
fn swap_local_cells<T>(a: &'static LocalKey<Cell<T>>, b: &'static LocalKey<Cell<T>>) {
local_scope(|s| {
s.access(a).swap(s.access(b))
})
}
fn swap_local_cells_std<T>(a: &'static LocalKey<Cell<T>>, b: &'static LocalKey<Cell<T>>) {
a.with(|a| b.with(|b| a.swap(b)))
}Structs§
- Local
Scope - ZST token that guarantees consistent access to thread local storage values for the duration of
'a.
Functions§
- local_
scope - Crates a new
LocalScopebound to the current call stack.