thread_local_scope

Crates.iothread_local_scope
lib.rsthread_local_scope
version0.1.0
created_at2026-01-24 04:41:53.730057+00
updated_at2026-01-24 04:41:53.730057+00
descriptionScoped access to thread local storage
homepage
repository
max_upload_size
id2066156
size9,640
KyleDavidE (KyleDavidE)

documentation

README

thread_local_scope

Provides a token type [LocalScope] that guards access to thread local storage. Makes it easier to work with thread locals inside the scope.

Examples

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)))
}
Commit count: 0

cargo fmt