Back to all projects

smallsm

A lightweight, fast, header-only state machine framework in C++17.

State diagram generated by smallsm, showing idle, connecting, connected and failed states and the events between them.
4 B
Machine size, no hooks
0
Heap allocations

You write states and events as structs and list the transitions in a type, and the compiler checks the table.

The library is about 1,900 lines of headers and depends only on the standard library. smallsm generated the diagram above from the transition table.

Fire events at the network machine from the transition table. An event with no transition from the current state returns no_transition, and clearing the host makes the guard reject connect_t. This is a JavaScript model of how dispatch behaves in the C++ library.

Current state

Log

    Why not a switch

    What goes wrong with a hand-written enum and switch as a machine grows.

    The transition table

    A machine is declared as one C++ type, and the compiler rejects invalid tables.

    Benchmarks

    On random events, smallsm takes 1.8 times as long as a hand-written switch, or 1.76 ns more per event.

    784 bytes down to 4

    v0.1 reserved a slot for every hook. v0.2 reserves one only when you declare it.

    Testing

    CI on GCC, Clang and MSVC, a compile-fail suite, and a zero-allocation test.