thread_scoped_ref
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 callingScopedKey::with
, instead calls the closure withNone
.
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.
... and another library that seems to do the same (and a bit more, like mutable references) https://crates.io/crates/scoped-tls-hkt - it seems that we both worked on this at almost the same time (the author of scoped-tls-hkt
released it last week; 2020-04-18). You should definitely check that out too.
Example use case:
.
+----- (set) ---------> &Data <------- (access/read) ----------+
| |
+---------+------------+ +--------------------------------------------|-------------+
| Data | | External library | |
| (huge/context/no Rc) | | | |
+----------------------+ | +-----------+------+ |
| ---- (calls) ---> | Your function | |
| +------------------+ |
+----------------------------------------------------------+
More information
- crates.io
- Documentation
- Tests
Usage
Cargo
[]
= "0"
Example
use ;
use HashMap;
thread_scoped_ref!;
/// It's not possible to pass `&HashMap<String, String>` to this function since it's called
/// by some library you don't control...
/// An external library you don't control or generated code.
let mut env_values = default;
env_values.insert;
// Create a scope. Note: We only need a reference to `env_values` (no move required).
scoped;
License
Licensed under either of
- Apache License, Version 2.0, (http://www.apache.org/licenses/LICENSE-2.0)
- MIT license (http://opensource.org/licenses/MIT)
at your option.