Struct automatons::State
source · [−]pub struct State { /* private fields */ }
Expand description
In-memory state for tasks
Steps in a task can share information with each other by putting it into a shared state. The state leverages Rust’s type system and uses type ids to index information. In combination with the newtype pattern, this creates a flexible but still strongly typed store.
Example
use automatons::State;
let mut state = State::new();
state.insert("example");
assert_eq!(Some(&"example"), state.get::<&str>());
Acknowledgements
The implementation for this type-based map is inspired by the Extensions
store in the
http
crate.
Implementations
sourceimpl State
impl State
sourcepub fn insert<T: Send + Sync + 'static>(&mut self, val: T) -> Option<T>where
T: Debug,
pub fn insert<T: Send + Sync + 'static>(&mut self, val: T) -> Option<T>where
T: Debug,
Inserts the given value into the state.
The given value is added to the state’s internal store. If the store already contains data with the same type, it will be overwritten by the new value.
Example
let mut state = State::new();
// Data is indexed by its type, in this case u32
state.insert(0u32);
assert_eq!(Some(&0u32), state.get::<u32>());
// Adding another u32 overwrites the original value
state.insert(1u32);
assert_eq!(Some(&1u32), state.get::<u32>());
sourcepub fn get<T: Send + Sync + 'static>(&self) -> Option<&T>
pub fn get<T: Send + Sync + 'static>(&self) -> Option<&T>
Returns an option with the requested data type
The state uses type ids to index data, which can be leveraged when looking up data in the store. In most cases, the compiler will be able to infer the correct data type. But the type can also by explicitly specified using the turbofish operator or a type hint.
Example
let mut state = State::new();
state.insert(2u32);
let a: u32 = 3;
let b = state.get()?;
assert_eq!(6, a * b);
sourcepub fn get_mut<T: Send + Sync + 'static>(&mut self) -> Option<&mut T>
pub fn get_mut<T: Send + Sync + 'static>(&mut self) -> Option<&mut T>
Returns an option with a mutable reference for the requested data type
The state uses type ids to index data, which can be leveraged when looking up data in the store. In most cases, the compiler will be able to infer the correct data type. But the type can also by explicitly specified using the turbofish operator or a type hint.
Example
let mut state = State::new();
state.insert(String::from("Hello"));
let mut string = state.get_mut::<String>()?;
string.push_str(", World!");
assert_eq!(&String::from("Hello, World!"), state.get::<String>()?);