#state-machine #finite-state-machine #state #transition #events #enums #behavior

fsm

一个简单的有限状态机库,提供状态和事件类型,然后创建一个具有初始状态的状态机,给它一些转换行为,你就有了你的状态机!

5 个版本

使用旧的 Rust 2015

0.2.2 2015 年 8 月 29 日
0.2.1 2015 年 8 月 28 日
0.2.0 2015 年 8 月 28 日
0.1.1 2015 年 8 月 24 日
0.1.0 2015 年 8 月 24 日

#2476算法

38 每月下载量

MIT 许可证

7KB
111

Rust 中简单的有限状态机库。提供状态和事件类型(通常是枚举),然后生成一个具有初始状态的状态机,给它一些转换行为,你就有了你的状态机!

使用方法

使用来自 FSM 维基百科条目的简单投币式旋转门示例

定义你的状态和事件

// 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 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")
);

按需触发事件,然后出发

// 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)

此示例也是库的测试用例,尽管这里省略了测试相关的细节。

待办事项

  • 公开谓词接口并为其编写单元测试

替代方案

基于宏的解决方案

其他

无运行时依赖