#event #event-driven #state #machine #statemachine

no-std apparat

A lightweight event-driven behavioral state machine

7 releases

0.5.5 May 21, 2021
0.5.4 May 14, 2021
0.5.3 Apr 18, 2021
0.4.0 Apr 17, 2021

#505 in Rust patterns

44 downloads per month

MIT license

241 lines


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
  • 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 file an issue.

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 Debug.

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 method-calls of that trait to the inner state objects.
  • Implementations of the Wrap trait for all provided states (for convenience)



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".


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);

impl TransitionFrom<StateA> for StateB {
    fn transition_from(_prev: StateA, ctx: &mut ContextData) -> Self {
        println!("A -> B          | toggled: {}", ctx.toggled);

// 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<...>`.
        // 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 {
        } else {
            self.ignored_events += 1;

// Run the machine
// ---------------

fn main() {
    let mut apparat = Apparat::new(StateA::default().wrap(), ContextData::default());

    // Handle some events
    for _ in 0..10 {

No runtime deps


  • unsafe