Expand description
§Token Store
This crate provides a small abstraction of a type allowing you to stroe values of arbitrary types and retrieving them using tokens values that are cheap to move around and clone.
The typical use-case is a data store shared by large portions of an application requiring sequential access to parts of this store, but while not caring nor being able to know what else is stored in it.
§How to use it
use token_store::Store;
// create a store
let mut store = Store::new();
// insert some things in it, you are given tokens
let token1 = store.insert(42);
// you can store any type as log as it is `Any + 'static`
let token2 = store.insert(String::from("I like trains"));
// the tokens keep the information of the store type,
// as such you don't need any annotation to retrieve a value:
store.get_mut(&token2).push_str(", and cars too!");
The retrieved tokens can be cloned and shared as you like between various parts of your code.
Note however that, as it is possible to store !Send
types in the token_store
,
neither the store nor its tokens can be shared accross threads.
§Value scopes and genericity
It is also possible to access simultaneously several values of the store using a scoped access:
let mut store = Store::new();
let token = store.insert(42);
store.with_value(&token, |proxy, value| {
// Here, proxy is a `StoreProxy`, it allows you to to all you want with the
// store, as long as you do not try to access again the value guarded by
// the token provided to `with_value`.
// Also, value is a mutable reference to the value guarded by this token.
// You can nest calls to `with_value` to access several values simultaneously
let token2 = proxy.insert(String::new());
proxy.with_value(&token2, |proxy, value2| {
// Here you can access value, value2, as well as a proxy tracking that
// both values are borrowed
});
});
Two implementations of the From
trait are also provided, allowing you to convert
both a &mut Store
and a &mut StoreProxy
into a StoreProxy
. This is to help
generic code like this:
fn do_stuff<'store, S: Into<StoreProxy<'store>>>(s: S) {
let proxy = s.into();
// we now have a store proxy, and can do our stuff with it
// and the caller can call us directly with a `&mut Store` or
// from within a value scope.
}
Structs§
- Store
- A token store
- Store
Proxy - A Proxy representing a
Store
with ongoing borrows - Token
- A token for accessing the store contents