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) into functions you don't control (e.g. functions from an external library).
toml
[dependencies]
thread-scoped-ref = "0"
See crates.io, the documentation and the tests.
```rust use threadscopedref::{threadscopedref, scoped, with};
/// Declare the REF_TO_A_STRING
.
threadscopedref!(REFTOA_STRING, str);
/// This function reads the value and prints the value. This function is usually called by an external
/// library you don't control.
fn valueconsumer() {
with(&REFTOASTRING, |maybestring| {
// maybe_string
is Some
if this is called within a scope, or None
if not called
// within a scope.
if let Some(string) = maybestring {
println!("String is: '{}'", string);
} else {
println!("There's no string.");
}
});
}
// Example #1: prints There's no string
(since not called within a scope).
value_consumer();
// Example #2: With a scope.
let mystring = "The String!".tostring();
// note: We use the reference and not the actual string. It's not static!
let mystringref = &mystring;
scoped(&REFTOASTRING, mystringref, || {
// prints String is: 'The String!'
value_consumer();
});
// Example #3: Nested scopes.
let anotherstring = "Another string".tostring();
scoped(&REFTOASTRING, &anotherstring, || {
// prints String is: 'Another string'
valueconsumer();
// a nested scope.
scoped(&REFTOASTRING, mystringref, || {
// prints String is: 'The String!'
valueconsumer();
});
// prints String is: 'Another string'
valueconsumer();
});
// Example #4: No scope (like example 1). prints There's no string
.
value_consumer();
```
MIT OR Apache-2.0