Finite state machine

Create finite state machines in rust with macros. The macro generates a struct, event enums and traits and also a decider trait. The decider trait is used to decide which state to transition to. Each state has a function which is called automatically when the state is entered. An invalid state and an end state are automatically added. You also need to implement a function for each transition. The macro automatically generates traits for everything you need to implement so the validity is checked on compile time.

Usage

```rust use finitestatemachine::state_machine; // Debug is only needed if the verbose feature is enabled

[derive(Debug, Default)]

struct Data { ... } state_machine!( // The name of the state machine and the type of the data, you can also use livetimes here CircuitBreaker(Data); // the first state will automatically become the start state, no matter the name Closed { Ok => Closed, // on Ok event go to Closed state AmperageTooHigh => Open // on AmperageTooHigh event go to open state }, Open { AttemptReset => HalfOpen, Wait => Open }, HalfOpen { Success => Closed, AmperageTooHigh => Open, MaxAttemps => End } );

use circuit_breaker::*;

// now you need to implement the decider trait which emits events which decide which state to transition to impl Deciders for CircuitBreaker { fn closed(&self) -> circuitbreaker::ClosedEvents { if self.data.currentamperage > self.data.maxamperage { circuitbreaker::ClosedEvents::AmperageTooHigh } else { circuit_breaker::ClosedEvents::Ok } } ... }

// now we need to implement the transition trait for each state impl ClosedTransitions for CircuitBreaker { fn amperagetoohigh(&mut self) -> Result<(), &'static str> { self.data.trippedat = Some(SystemTime::now()); Ok(()) } fn ok(&mut self) -> Result<(), &'static str> { self.data.currentamperage += 1; std::thread::sleep(Duration::from_millis(500)); Ok(()) } fn illegal(&mut self) {} } ```

For more details, check the examples folder.

How it works

Debugging

You can enable the feature verbose to get more information about the state machine. This will print the current state, the transition and the current data.