Crate apparat[−][src]
Apparat
A lightweight, event-driven behavioral state machine
Notable features:
- No unsafe, unless you actively enable it (see “Feature flags” below)
- No-std compatible
- Small and fast to compile
- Fewer than 250 lines of code
- No dependencies
- No procedural macros (just a declarative one)
- Very ergonomic despite the manageable amount of macro magic
- Highly flexible, suitable for many use cases
- No dynamic dispatch, enables lots of compiler optimizations
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.
Feature flags
“unsafe” (disabled by default)
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 drop me an email.
Architecture and usage
Types you provide
- An arbitrary number of types that represent the different states*
- A context type that is mutably accessible while events are handled and during transitions.
- An event type for the state machine to handle
- An output type that is returned whenever an event is handled. If this is not needed, the unit type can be used.
* 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 the standard Debug
trait.
Entities that are generated
- A wrapper enum with variants for all provided state types
- An implementation of the
ApparatWrapper
trait for the wrapper enum - An implementation of the
ApparatState
trait for the wrapper enum. The enum delegates all calls to methods of that trait to the current state object. - Implementations of the
Wrap
trait for all provided states (for convenience)
Traits
ApparatState<StateWrapper>
This trait must be implemented for all state types. The handle
method is the only one that must be implemented manually.
There are two other methods in the trait that form an initialization mechanism: After constructing an Apparat
using the new
method and after handling any event, init
is called on the current state, until is_init
returns true
. This way multiple transitions can be triggered by a single event. This happens in a while loop without any recursion. If a state doesn’t need that initialization, the methods can be ignored so their default implementation is being used.
The handle
method returns a Handled<StateWrapper>
struct where StateWrapper
is the wrapper enum that apparat generated for us. Handled<StateWrapper>
just combines this enum with the provided output type. If this output type implements the standard Default
trait, the StateWrapper
can be turned into a Handled<StateWrapper>
with the default output value using into()
. This is demonstrated and commented in the example below.
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 also recommended for usage in trait bounds.
These two traits are optional but recommended since they provide nice ergonomics.
Wrap<StateWrapperType>
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.
Example
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 // of `.default_output()`. } } impl ApparatState for StateB { type Wrapper = MyStateWrapper; fn handle(mut self, _event: (), ctx: &mut ContextData) -> Handled<MyStateWrapper> { println!("B handles event | toggled: {}", ctx.toggled); self.ignored_events += 1; if self.ignored_events > 2 { self.transition::<StateA>(ctx).wrap().default_output() } else { 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(()); } }
Modules
prelude |
Macros
build_wrapper | Generate an enum that wraps all provided state types. Additionally all
necessary traits are implemented for it, so the wrapper can be used within
an |
Structs
Apparat | The actual state machine that handles your events and manages their initialization and transitions |
Handled | This type is being returned whenever an event is handled by a state type. It
contains the new state alongside an output value that will be returned to
the caller of the |
Traits
ApparatState | A trait that must be implemented by all provided state types. Have a look at the readme or the examples for details. |
ApparatTrait | |
ApparatWrapper | This trait is used to associate all the types used together in an |
ApparatWrapperDefaultOutput | |
TransitionFrom | Define transitions between states. These transition functions can access the shared context/data mutably. |
TransitionTo | Similar to |
Wrap | An alternative to |