essm 0.2.0

extremely simple state machine
Documentation
  • Coverage
  • 100%
    40 out of 40 items documented19 out of 33 items with examples
  • Size
  • Source code size: 89.8 kB This is the summed size of all the files inside the crates.io package for this release.
  • Documentation size: 936.0 kB This is the summed size of all files generated by rustdoc for all configured targets
  • Ø build duration
  • this release: 3s Average build duration of successful builds.
  • all releases: 4s Average build duration of successful builds in releases after 2024-10-23.
  • Links
  • Repository
  • crates.io
  • Dependencies
  • Versions
  • Owners
  • cehteh

ESSM: Extremely Simple State Machines

A compile-time typestate state machine library for Rust. States are distinct types, transitions are trait implementations.

Design philosophy

ESSM provides safe state transitions via the typestate pattern. It does NOT provide a runtime state machine wrapper, event dispatch, or async drivers; those are the user's domain. ESSM handles one thing: making sure you can only transition between states that have a defined path, and that the transition hooks (invariants, guards, entry/exit checks) execute in the correct order.

Being extremely simple applies to being the usage which is intended to be very ergonomic and safe (wrong use is a compile error). As well as its implementation which may be surprisingly minimal.

Intended scope

ESSM is designed for small-to-medium sized state machines. Each transition pair requires a separate trait implementation, this is the cost of compile-time type safety.

Getting started

Add essm to your Cargo.toml, then import everything:

#[allow(clippy::wildcard_imports)]
use essm::*;

This brings in [State], [Transition], [TransitionResult], [TransitionInfallible], [ErrorState], [FailedAt], [Primordial], [Terminated], [Infallible], [InitialState], [InitialStateInfallible], [TerminalState], [TerminalStateInfallible], and all other public types in one line.

Quick example

#[allow(clippy::wildcard_imports)]
use essm::*;

#[derive(Debug, Default)]
struct Idle;
impl State for Idle {}

#[derive(Debug, Default)]
struct Running;
impl State for Running {}

// Define allowed transitions
impl Transition<Running> for Idle {
    fn change(self, _ctx: &mut ()) -> TransitionResult<Idle, Running, Infallible> {
        Ok(Running)
    }
}

impl Transition<Idle> for Running {
    fn change(self, _ctx: &mut ()) -> TransitionResult<Running, Idle, Infallible> {
        Ok(Idle)
    }
}

let idle = Idle;
let running: Running = idle.transition();
let idle: Idle = running.transition();

Bootstrap and termination

ESSM provides an optional bootstrap pattern via predefined [Primordial] and [Terminated] pseudo states. These make creation and destruction symmetric with state transitions. Every lifecycle event uses the same [Transition] pipeline.

Creating initial states

Implement Transition<YourState> for [Primordial] to define how your first state is created, the [InitialState]/[InitialStateInfallible] traits are automatically implemented for any transition from Primordial. They define convenient constructors:

# #[allow(clippy::wildcard_imports)]
# use essm::*;

#[derive(Debug)]
struct Red;
impl State for Red {}

impl Transition<Red> for Primordial {
    fn change(self, _: &mut ()) -> TransitionResult<Primordial, Red, Infallible> {
        Ok(Red)
    }
}

/// This is calling InitialStateInfallible::new()
let red = Red::new();

For fallible construction, use a custom error type and impl InitialState<MyError> for MyState {}.

Terminating the machine

Implement Transition<Terminated> for the final state, then call .terminate():

# #[allow(clippy::wildcard_imports)]
# use essm::*;
# #[derive(Debug)]
# struct Red;
# impl State for Red {}
# impl Transition<Red> for Primordial {
#     fn change(self, _: &mut ()) -> TransitionResult<Primordial, Red, Infallible> { Ok(Red) }
# }
# let red = Red::new();

impl Transition<Terminated> for Red {
    fn change(self, _: &mut ()) -> TransitionResult<Red, Terminated, Infallible> {
        Ok(Terminated)
    }
}

// this is calling TerminalStateInfallible::terminate()
red.terminate();

Primordial and Terminated are optional

You are not required to use [Primordial] or [Terminated]. States can be constructed directly (e.g., let idle = Idle;) and destroyed by simply letting them go out of scope. This is perfectly valid and often simpler for small state machines or ZST states.

However, when bypassing [Primordial] and [Terminated], you are responsible for calling the lifecycle hooks manually:

  • state.enter(&ctx) — after constructing a state
  • state.invariant() — for validating a state
  • state.leave(&ctx) — before destroying a state

The [InitialState] and [TerminalState] traits automate this for you.

impl Drop on state types

Rust forbids partial moves out of Drop-implementing types (E0509), but Transition::change must consume self and move data into the next state. The most universal workaround is Option::take():

# use essm::{State, Transition, ErrorState};
# use core::convert::Infallible;
#
#[derive(Debug)]
struct Parsing {
    buf: Option<Vec<u8>>,
    pos: usize,
}
impl State for Parsing {}

impl Drop for Parsing {
    fn drop(&mut self) {
        // Called after change() — buf is None if transition succeeded
    }
}

#[derive(Debug)]
struct Ready { buf: Vec<u8> }
impl State for Ready {}

impl Transition<Ready, Infallible> for Parsing {
    fn change(mut self, _ctx: &mut ()) -> Result<Ready, ErrorState<Infallible, Parsing, Ready>> {
        let buf = self.buf.take().unwrap_or_default();
        Ok(Ready { buf })
    }
}
#
# fn main() {
#     let parsing = Parsing { buf: Some(vec![1, 2, 3]), pos: 0 };
#     let ready: Ready = parsing.try_transition().unwrap();
#     assert_eq!(ready.buf, vec![1, 2, 3]);
#     // Drop ran on parsing (with buf: None) — no UB, no double-free
# }

core::mem::take() is an alternative for T: Default types (no Option wrapper needed).

External crates: The derive_destructure2 crate provides proc macros (#[derive(destructure)], #[derive(remove_trait_impls)]) that let you destructure Drop types directly. The drop-with-owned-fields crate offers a safe ManuallyDrop wrapper.

Unsafe escape hatch: For zero-cost repackaging, wrap the struct in ManuallyDrop, ptr::read each field, and never drop the wrapper.

Prefer [TerminalState] for structured teardown — or rely on Rust's automatic drop for Drop-implementing fields (Vec, String, Box).

Caveats: Your Drop impl must handle fields that may have been taken. All patterns above are panic-safe: if change() panics, remaining fields hold valid defaults and Drop can still run without UB.

Data-carrying states

When a state carries data, move that data to the next state in change():

# #[allow(clippy::wildcard_imports)]
# use essm::*;
struct Parsing { buf: Vec<u8>, pos: usize }
impl State for Parsing {}

struct Ready { buf: Vec<u8> }
impl State for Ready {}

impl Transition<Ready> for Parsing {
    fn change(self, _ctx: &mut ()) -> TransitionResult<Parsing, Ready, Infallible> {
        Ok(Ready { buf: self.buf })
    }
}

Transition pipeline

Each transition() executes hooks in a fixed order:

1. self.invariant()                 : invariant check on source state integrity (no context)
2. self.leave(&ctx)                 : on-exit check, immutable context (&Ctx)
3. self.guard(&ctx)                 : pure predicate, immutable context (&Ctx)
4. let next = self.change(&mut ctx) : produce next state, mutable context (&mut Ctx)
5. next.enter(&ctx)                 : on-entry check, immutable context (&Ctx)
6. next.invariant()                 : invariant check on target state integrity (no context)

Call try_transition() for the zero-argument convenience path (context is ()). Use try_transition_with() to pass a mutable context that threads through the entire pipeline; hooks can read from it, and change() can mutate it.

# #[allow(clippy::wildcard_imports)]
# use essm::*;
# #[derive(Debug, Default)] struct Idle; impl State for Idle {}
# #[derive(Debug, Default)] struct Running; impl State for Running {}
# impl Transition<Running> for Idle {
#     fn change(self, _ctx: &mut ()) -> TransitionResult<Idle, Running, Infallible> {
#         Ok(Running)
#     }
# }
let idle = Idle;
let running: Running = idle.transition();

With a user-defined context — set the Transition's Ctx type:

# #[allow(clippy::wildcard_imports)]
# use essm::*;
# #[derive(Debug, Default)] struct Idle; impl State for Idle {}
# #[derive(Debug, Default)] struct Running; impl State for Running {}
struct MyCtx { counter: u32 }
# impl Transition<Running, Infallible, MyCtx> for Idle {
#     fn change(self, _: &mut MyCtx) -> TransitionResult<Idle, Running, Infallible> {
#         Ok(Running)
#     }
# }
let idle = Idle;
let mut ctx = MyCtx { counter: 0 };
let running: Running = idle.transition_with(&mut ctx);

Error recovery

In ESSM, errors are states. When a transition fails, it returns an [ErrorState] which implements [State]. This means you can transition FROM an error back to a valid state:

# #[allow(clippy::wildcard_imports)]
# use essm::*;
# #[derive(Debug)] enum MyError { Bad }
# #[derive(Debug, Default)] struct Idle; impl State for Idle {}
# #[derive(Debug)] struct Working { should_fail: bool }
# impl State for Working {}
# #[derive(Debug)] struct Done; impl State for Done {}
# impl Transition<Working, MyError> for Idle {
#     fn change(self, _ctx: &mut ()) -> TransitionResult<Idle, Working, MyError> {
#         Ok(Working { should_fail: false })
#     }
# }
# impl Transition<Done, MyError> for Working {
#     fn change(self, _ctx: &mut ()) -> TransitionResult<Working, Done, MyError> {
#         ErrorState::err_origin(MyError::Bad, self)
#     }
# }

// Recover: from any error back to Idle
impl<E, S, T> Transition<Idle, E> for ErrorState<E, S, T> {
    fn change(self, _ctx: &mut ()) -> TransitionResult<Self, Idle, E> {
        Ok(Idle)
    }
}

let idle = Idle;
let working: Working = idle.try_transition().unwrap();

// Transition fails -- but the error IS a state
match working.try_transition() {
    Ok(done) => { /* success */ }
    Err(error_state) => {
        // Recover: transition from the error back to Idle
        let idle: Idle = error_state.try_transition().unwrap();
    }
}

On failure, try_transition() returns an [ErrorState] that carries both the original error and a [FailedAt] wrapping the state that survived. Use [ErrorState::err_origin], [ErrorState::err_next], or [ErrorState::err] to construct errors from your change() implementation.

Custom error types

You can define your own error types instead of using [Infallible]. For example, the vending machine example defines a VendError enum to signal insufficient credit:

# #[allow(clippy::wildcard_imports)]
# use essm::*;
#[derive(Debug)]
enum VendError { NotEnoughCredit }

The HasCredit → Dispensing transition checks the credit balance and returns VendError::NotEnoughCredit via [ErrorState::err_origin] if the balance is too low. Because the origin state (HasCredit) is preserved in the [ErrorState], the caller can recover by extracting it and continuing.

Recovery pattern

Since [ErrorState] implements [State], you can implement [Transition] from an [ErrorState] back to a valid state. Recovery can restore the original state via the [FailedAt::Origin] variant:

# #[allow(clippy::wildcard_imports)]
# use essm::*;
# #[derive(Debug)] enum VendError { NotEnoughCredit }
# #[derive(Debug)] struct HasCredit { amount: u32 }; impl State for HasCredit {}
# #[derive(Debug)] struct Dispensing { item: &'static str, change: u32 }; impl State for Dispensing {}
// Recovery: ErrorState → HasCredit, restoring the original state
impl Transition<HasCredit, VendError> for ErrorState<VendError, HasCredit, Dispensing> {
    fn change(self, _ctx: &mut ()) -> TransitionResult<Self, HasCredit, VendError> {
        match self.at {
            FailedAt::Origin(state) => Ok(state),  // restore original HasCredit
            _ => panic!("expected origin in recovery"),
        }
    }
}

This pattern lets you attempt a fallible transition, recover from failure by restoring the original state, and retry with different inputs.

Customizing transitions

The pipeline is defined by [Transition]'s default methods. Override the hooks, not the pipeline:

Hook Trait Purpose
invariant() State invariant check on state integrity
leave() State On-exit check, immutable context
guard() Transition Pure predicate: is the transition allowed?
change() Transition Produce the next state from the current one
enter() State On-entry check, immutable context

no_std

ESSM is #![no_std] by default. It uses only core::convert::Infallible. Tests use std behind #[cfg(test)].

LLM usage

  • Design and planning: Completely human. Architecture decisions, API design, trait boundaries, and the transition pipeline are human-authored.
  • Implementation: Hybrid. Core traits and library code are human-authored with LLM assistance for boilerplate. All LLM-generated code undergoes close human review before merging.
  • Documentation and examples: Partially LLM-generated, human-reviewed. README, doctests, and example programs are drafted with LLM assistance and verified by human review.