I've found myself coming back to this article several times when working on some hardware controller logic. Turns out Rust has some incredibly natural constructs for encoding state machines.
TL:DR Have a generically typed state machine struct. Encode the states in structs. Encode the allowed transitions between states using the From
trait. For example,
// machine
struct Machine<S> {
state: S
}
// states
struct State1
struct State2
struct State3
// transitions
//
// state 1 -> state 2 -> state 3
// ^ |
// |_____________________|
// transition from state 1 to state 2.
impl From<Machine<State1>> for Machine<State2> {}
// transition from state 2 to state 3.
impl From<Machine<State2>> for Machine<State3> {}
// transition from state 3 to state 1.
impl From<Machine<State3>> for Machine<State1> {}