pub struct SharedState { /* private fields */ }Expand description
Shared state: a heterogeneous container accessed by type.
Type is the key: a second insert of the same
type overwrites; retrieval takes a type parameter (compile-time type
safety). Unlike Box<dyn Any>’s “store anything”, this container holds
multiple values side by side, distinguished by type.
An internal RwLock (read-heavy) provides cross-thread safety;
Clone is cheap (Arc), so tools and agents — several agents — share
the same instance.
§Example
use molo::SharedState;
#[derive(Debug, Clone, PartialEq)]
struct Session { user: String }
let state = SharedState::new();
state.insert(Session { user: "alice".into() });
state.with::<Session>(|s| assert_eq!(s.user, "alice"));
state.with_mut::<Session>(|s| s.user = "bob".into());
assert_eq!(state.get::<Session>(), Some(Session { user: "bob".into() }));Implementations§
Sourcepub fn new() -> SharedState
pub fn new() -> SharedState
An empty shared state.
Sourcepub fn insert<T>(&self, value: T)
pub fn insert<T>(&self, value: T)
Store a custom value; storing the same type again overwrites.
Sourcepub fn get<T>(&self) -> Option<T>
pub fn get<T>(&self) -> Option<T>
Retrieve (clone) a custom value; returns None when the type is
absent (the type must implement Clone; a clone is returned and the
original value in the container is unchanged).
Sourcepub fn with<T>(&self, f: impl FnOnce(&T))where
T: Any,
pub fn with<T>(&self, f: impl FnOnce(&T))where
T: Any,
Read an existing value under the lock; the closure does not run when the type is absent.
§Panics
A panic inside the closure propagates outward; the lock gets
poisoned as a result, but the container recovers from poisoning and
later access works as usual (the closure returns nothing; for an
in-place read use get).
§Deadlock red line
The underlying RwLock is not reentrant, and the closure runs
while the lock is held: the closure must not access the same
SharedState again (e.g. with(|a| ... state.get::<B>() ...)), or
it hangs with no error. To access several values at once, call
get sequentially / combine them into one struct, or move reads
and writes outside the closure.
Sourcepub fn with_mut<T>(&self, f: impl FnOnce(&mut T))where
T: Any,
pub fn with_mut<T>(&self, f: impl FnOnce(&mut T))where
T: Any,
Update an existing value in place under the lock; the closure does not run when the type is absent.
§Panics
A panic inside the closure propagates outward; the lock gets poisoned as a result, but the container recovers from poisoning and later access works as usual.
§Deadlock red line
Same as with: the underlying lock is not
reentrant, and the closure must not access the same SharedState
again.
Trait Implementations§
Source§fn clone(&self) -> SharedState
fn clone(&self) -> SharedState
1.0.0 (const: unstable) · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source. Read more