| Crates.io | thread_local_scope |
| lib.rs | thread_local_scope |
| version | 0.1.0 |
| created_at | 2026-01-24 04:41:53.730057+00 |
| updated_at | 2026-01-24 04:41:53.730057+00 |
| description | Scoped access to thread local storage |
| homepage | |
| repository | |
| max_upload_size | |
| id | 2066156 |
| size | 9,640 |
Provides a token type [LocalScope] that guards access to thread local storage. Makes it easier to work with thread locals inside the scope.
You can use the scoping to gracefully handle errors.
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 LocalScopes.
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)))
}