threadscopedref

A library that is similar to a thread local storage but allows to store references / dyn Trait within a scope. It can be used to 'inject' references (if you don't own the data and Rc/Arc is not possible) into something you don't control entirely (e.g. a function you provide that gets called by a library you don't own).

+------- (set) -----------> &Data <---------- (access/read) ----------+ | | +---------+------------+ +--------------------------------------------|-------------+ | Data | | External library | | | (huge/context/no Rc) | | | | +----------------------+ | +-----------+------+ | | ---- (calls) ---> | Your function | | | +------------------+ | +----------------------------------------------------------+

More information

Usage

Cargo

toml [dependencies] thread-scoped-ref = "0"

Example

``` use threadscopedref::{threadscopedref, scoped, with}; use std::collections::HashMap;

threadscopedref!(SOMEENVVALUES, HashMap);

/// It's not possible to pass &HashMap<String, String> to this function since it's called /// by some library you don't control... fn readenvvalue() { // ... so we read from the static 'SOMEENVVALUES'. with(&SOMEENVVALUES, |maybeenvvalues| { // don't "unwrap" in reality: Since maybe_env_values will be None if not // called within a scope! let envvalues = maybeenvvalues.unwrap(); asserteq!("true", envvalues.get("deleteentire_ssd").unwrap()); }); }

/// An external library you don't control or generated code. fn externallibrary(functionptr : fn()) { function_ptr(); }

let mut envvalues = HashMap::default(); envvalues.insert("deleteentiressd".tostring(), "true".tostring()); // Create a scope. Note: We only need a reference to env_values (no move required). scoped(&SOMEENVVALUES, &envvalues, || { externallibrary(readenvvalue); }); ```

License

Licensed under either of

at your option.