state-store
A generic, type-safe state management library with change detection and blocking iteration.
Overview
state-store provides a simple, synchronous API for managing typed property state across multiple entities. It handles:
- Type-erased storage with type-safe access
- Automatic change detection (only emits events when values actually change)
- Watch pattern for selective property monitoring
- Blocking iteration over change events
This crate is the generic foundation used by sonos-state but can be used independently for any stateful application.
Features
- Generic Entity IDs: Use any hashable type as entity identifiers (strings, custom IDs, etc.)
- Type-safe Properties: Store and retrieve strongly-typed values via the
Propertytrait - Change Detection: Only emit events when values actually differ (via
PartialEq) - Watch Pattern: Register interest in specific properties to filter change events
- Sync API: All operations are synchronous - no async runtime required
Quick Start
use ;
// Define a property type
;
API Overview
Property Trait
StateStore
let store = new;
// Get/set properties
store.set;
let value = store.;
// Watch management
store.watch;
store.unwatch;
store.is_watched;
// Entity management
store.entity_count;
store.entity_ids;
store.remove_entity;
Change Iteration
// Blocking iteration
for event in store.iter
// Non-blocking
for event in store.iter.try_iter
// With timeout
for event in store.iter.timeout_iter
// Single event with timeout
if let Some = store.iter.recv_timeout
Architecture
StateStore<Id>
|
+-- entities: HashMap<Id, PropertyBag>
| |
| +-- PropertyBag: HashMap<TypeId, Box<dyn Any>>
|
+-- watched: HashSet<(Id, property_key)>
|
+-- event_channel: mpsc::channel<ChangeEvent<Id>>
|
+-- ChangeIterator<Id>
Thread Safety
StateStoreisCloneand shares state across clones viaArc- All operations are internally synchronized with
RwLockandMutex - Safe to use from multiple threads
License
MIT License