smallsm
A lightweight, fast, header-only state machine framework in C++17.
- 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.
State machine demo
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
Breakdown
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.
Guards, builders and hooks
Callbacks stored in fixed inline buffers, and the order dispatch runs them in.
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.
Generated diagrams
Graphviz and Mermaid output generated from the transition table.
Testing
CI on GCC, Clang and MSVC, a compile-fail suite, and a zero-allocation test.