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).
It's also very similar to https://github.com/alexcrichton/scoped-tls, with those differences:
thread_scoped_ref
works with traits / unsized types.thread_scoped_ref
does not panic when calling ScopedKey::with
, instead calls the closure with None
.According to scoped-tls
there once was something similar in the old rust standard library (quote from scoped-tls
):
A Rust library providing the old standard library's
scoped_thread_local!
macro as a library implementation on crates.io.
Example use case:
```
+----- (set) ---------> &Data <------- (access/read) ----------+
| |
+---------+------------+ +--------------------------------------------|-------------+ | Data | | External library | | | (huge/context/no Rc) | | | | +----------------------+ | +-----------+------+ | | ---- (calls) ---> | Your function | | | +------------------+ | +----------------------------------------------------------+ ```
toml
[dependencies]
thread-scoped-ref = "0"
```rust 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);
});
```
Licensed under either of
at your option.