#fsm #state

fsm

A simple Finite State Machine library, provide State and Event types, then create a machine with an initial state, give it some transition behaviours and you have your state machine!

5 releases

Uses old Rust 2015

0.2.2 Aug 29, 2015
0.2.1 Aug 28, 2015
0.2.0 Aug 28, 2015
0.1.1 Aug 24, 2015
0.1.0 Aug 24, 2015

#870 in Algorithms

Download history 6/week @ 2022-01-24 3/week @ 2022-01-31 1/week @ 2022-02-07 9/week @ 2022-02-14 7/week @ 2022-02-21 3/week @ 2022-02-28 2/week @ 2022-03-07 22/week @ 2022-03-14 16/week @ 2022-03-21 4/week @ 2022-03-28 2/week @ 2022-04-04 4/week @ 2022-04-11 3/week @ 2022-04-18 13/week @ 2022-04-25 62/week @ 2022-05-02 7/week @ 2022-05-09

86 downloads per month

MIT license

7KB
111 lines

A simple Finite State Machine library in Rust. Provide State and Event types (usually enums), then generate a machine with an initial state, give it some transition behaviours and you have your state machine!

Usage

Using the simple coin-operated turnstyle example from the FSM wikipedia entry:

Define your states and events:

// states and events must be C-like enums (copyable and easily converted to primitives)
#[derive(Copy, Clone)]
enum TurnStyleState {
	Locked,
	Unlocked,
}

#[derive(Copy, Clone)]
enum TurnStyleEvent {
	Push,
	InsertCoin,
}

// implement the EnumTag trait for states and events
impl EnumTag for TurnStyleState {
	fn tag_number(&self) -> usize {
		*self as usize
	}
	fn max_tag_number() -> usize {
		TurnStyleState::Unlocked as usize
	}
}

impl EnumTag for TurnStyleEvent {
	fn tag_number(&self) -> usize {
		*self as usize
	}
	fn max_tag_number() -> usize {
		TurnStyleEvent::InsertCoin as usize
	}
}

Create your machine and define your transitions:

// create the machine initially in the Locked state
let mut machine = Machine::new(TurnStyleState::Locked);
// create the transition from Locked -> Unlocked upon inserting a coin
machine.add_transition(
	TurnStyleState::Locked, TurnStyleEvent::InsertCoin,
	TurnStyleState::Unlocked, |_,_| println!("unlocked")
);
// create the transition from Unlocked -> Locked upon pushing the turnstyle
machine.add_transition(
	TurnStyleState::Unlocked, TurnStyleEvent::Push,
	TurnStyleState::Locked, |_,_| println!("locked")
);

Trigger events as needed and huzzah, off you go:

// initially we're in the Locked state
machine.on_event(TurnStyleEvent::InsertCoin);
// now we're Unlocked, ("unlocked" was just printed)
machine.on_event(TurnStyleEvent::Push);
// now we're Locked again, ("locked" was just printed)

This example is also the test case for the library, although here I've ommitted the test-related details.

To Do

  • Expose predicate interface and write unit tests for it

Alternatives

Macro based solutions

Other

No runtime deps