Crates.io | apparat |
lib.rs | apparat |
version | 0.5.5 |
source | src |
created_at | 2021-04-17 13:59:57.861986 |
updated_at | 2021-05-21 16:20:51.408516 |
description | A lightweight event-driven behavioral state machine |
homepage | https://gitlab.com/vkahl/apparat |
repository | https://gitlab.com/vkahl/apparat |
max_upload_size | |
id | 385755 |
size | 43,583 |
A lightweight, event-driven behavioral state machine
Notable features:
Note: I am still experimenting with this a bit so while it's below version 1.0, there might be breaking API changes in point releases. If you want to be sure, specify an exact version number in your Cargo.toml. In point-point-releases there won't be breaking changes ever.
This feature flag facilitates more compiler optimizations in some cases (verified using cargo asm). This is achieved by using core::hint::unreachable_unchecked()
in one place, where the author is certain enough that it's sound. Nevertheless, use this at your own risk. If you're curious, have a look at the code - I've written a safety-comment about my assumptions there. If you think I missed something, please file an issue.
* The data within the state types is exclusively accessible in the respective state. It's getting dropped on transitions and moved when events are handled. These moves might get optimized out in some cases, but generally, if you want the best possible performance, the state types should be rather small and cheap to move.
If it's impossible to keep them small and you are handling a lot of events without transitioning, consider putting the bigger data in a Box
within the state type. Alternatively you could make that bigger data a part of the context type which won't get moved or dropped at all. But if you do the latter, the data will of course also be accessible from other states.
Note: All provided types must implement Debug
.
ApparatWrapper
trait for the wrapper enumApparatState
trait for the wrapper enum. The enum delegates all method-calls of that trait to the inner state objects.Wrap
trait for all provided states (for convenience)ApparatState<StateWrapper>
This trait must be implemented for all state types. The only required method is handle
, which takes an event and returns a Handled<StateWrapper>
. That's just the next state wrapped in a StateWrapper
alongside an output value. To construct this return type, we can first call .wrap()
on our state and then .with_output(...)
on the wrapper. If our output type implements Default
, we can also use .default_output()
instead.
There are two other methods in the ApparatState
trait: init
and is_init
. These form an initialization mechanism: After constructing an Apparat
and after handling any event, init
is called on the current state, until is_init
returns true
. This way, a single event can potentially trigger multiple, context dependent transitions. This happens in a while loop without any recursion. If a state doesn't need that, these methods can just be ignored.
TransitionFrom<OtherState, ContextData>
The TransitionFrom
trait can be used to define specific transitions between states. The TransitionTo
trait is then automatically implemented, so we can call .transition
using the turbofish syntax. This design is similar to From
and Into
in the standard library, but TransitionFrom
and TransitionInto
can also mutate the provided context as a side effect. TransitionInto
is recommended for trait bounds.
If you have to define a lot of transitions using the same state constructor methods, you can use the transitions
macro. Within the macro call, a single transition can be defined like this: StateA -> StateB::new
. In this case, the type StateB
would have to implement a method new
with this signature: fn new(prev: StateA, ctx: &mut ContextData) -> Self
. If transitions from multiple different states to StateA
shall use the same transition method, the first argument has to be generic. All of this is demonstrated in the example called "counter_transitions_macro".
Wrap<StateWrapper>
The Wrap<StateWrapper>
trait provides a wrap
method to turn individual state objects into a StateWrapper
. This is preferred over using into
because it's more concise and enables type inference in more cases. Wrap
is automatically implemented for all state types by the macro.
For a slightly more complete example, have a look at counter.rs in the examples directory.
//! This state machine switches from `StateA` to `StateB` on a single event but
//! then needs three events to switch back to `StateA`. Additionally it keeps
//! track of how often it got toggled back from `StateB` to `StateA`.
use apparat::prelude::*;
// Define the necessary types
// --------------------------
// States
#[derive(Debug, Default)]
pub struct StateA;
#[derive(Debug, Default)]
pub struct StateB {
ignored_events: usize,
}
// Context
// Data that survives state transitions and can be accessed in all states
#[derive(Debug, Default)]
pub struct ContextData {
toggled: usize,
}
// Auto-generate the state wrapper and auto-implement traits
// ---------------------------------------------------------
// In this example we are just using the unit type for `event` and `output`
// because we are only handling one kind of event and we don't care about values
// being returned when events are handled.
build_wrapper! {
states: [StateA, StateB],
wrapper: MyStateWrapper, // This is just an identifier we can pick
context: ContextData,
event: (),
output: (),
}
// Define transitions
// ------------------
impl TransitionFrom<StateB> for StateA {
fn transition_from(_prev: StateB, ctx: &mut ContextData) -> Self {
// Increase toggled value
ctx.toggled += 1;
println!("B -> A | toggled: {}", ctx.toggled);
StateA::default()
}
}
impl TransitionFrom<StateA> for StateB {
fn transition_from(_prev: StateA, ctx: &mut ContextData) -> Self {
println!("A -> B | toggled: {}", ctx.toggled);
StateB::default()
}
}
// Implement the `ApparatState` trait for all states
// -------------------------------------------------
impl ApparatState for StateA {
type Wrapper = MyStateWrapper;
fn handle(self, _event: (), ctx: &mut ContextData) -> Handled<MyStateWrapper> {
println!("A handles event | toggled: {}", ctx.toggled);
// Transition to `StateB`
let state_b = self.transition::<StateB>(ctx);
// Now we need to wrap that `state_b` in a `MyStateWrapper`...
let state_b_wrapped = state_b.wrap();
// ... and add an output value to turn it into a `Handled<...>`.
state_b_wrapped.default_output()
// If we would need a different output value or our output type wouldn't
// implement `Default` we would have to use `.with_output(...)` instead.
}
}
impl ApparatState for StateB {
type Wrapper = MyStateWrapper;
fn handle(mut self, _event: (), ctx: &mut ContextData) -> Handled<MyStateWrapper> {
println!("B handles event | toggled: {}", ctx.toggled);
if self.ignored_events == 2 {
self.transition::<StateA>(ctx).wrap().default_output()
} else {
self.ignored_events += 1;
self.wrap().default_output()
}
}
}
// Run the machine
// ---------------
fn main() {
let mut apparat = Apparat::new(StateA::default().wrap(), ContextData::default());
// Handle some events
for _ in 0..10 {
apparat.handle(());
}
}