thread_local_scope 0.1.0

Scoped access to thread local storage
Documentation
  • Coverage
  • 100%
    6 out of 6 items documented2 out of 6 items with examples
  • Size
  • Source code size: 9.64 kB This is the summed size of all the files inside the crates.io package for this release.
  • Documentation size: 1.5 MB This is the summed size of all files generated by rustdoc for all configured targets
  • Ø build duration
  • this release: 12s Average build duration of successful builds.
  • all releases: 12s Average build duration of successful builds in releases after 2024-10-23.
  • Links
  • crates.io
  • Dependencies
  • Versions
  • Owners
  • KyleDavidE

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)))
}