Crates.io | finny |
lib.rs | finny |
version | 0.2.0 |
source | src |
created_at | 2021-01-05 18:15:38.17971 |
updated_at | 2022-01-24 20:57:00.402527 |
description | Finite State Machines with a procedural builder-style API and compile time transition checks. |
homepage | |
repository | https://github.com/hashmismatch/finny.rs |
max_upload_size | |
id | 332323 |
size | 82,053 |
no_std
support[dependencies]
finny = "0.2"
use finny::{finny_fsm, FsmFactory, FsmResult, decl::{BuiltFsm, FsmBuilder}};
// The context is shared between all guards, actions and transitions. Generics are supported here!
#[derive(Default)]
pub struct MyContext { val: u32 }
// The states are plain structs.
#[derive(Default)]
pub struct MyStateA { n: usize }
#[derive(Default)]
pub struct MyStateB;
// The events are also plain structs. They can have fields.
#[derive(Clone)]
pub struct MyEvent;
// The FSM is generated by a procedural macro
#[finny_fsm]
fn my_fsm(mut fsm: FsmBuilder<MyFsm, MyContext>) -> BuiltFsm {
// The FSM is described using a builder-style API
fsm.state::<MyStateA>()
.on_entry(|state, ctx| {
state.n += 1;
ctx.context.val += 1;
})
.on_event::<MyEvent>()
.transition_to::<MyStateB>()
.guard(|_ev, ctx, _states| { ctx.context.val > 0 })
.action(|_ev, ctx, state_a, state_b| { ctx.context.val += 1; });
fsm.state::<MyStateB>();
fsm.initial_state::<MyStateA>();
fsm.build()
}
// The FSM is built and tested.
fn main() -> FsmResult<()> {
let mut fsm = MyFsm::new(MyContext::default())?;
assert_eq!(0, fsm.val);
fsm.start()?;
let state_a: &MyStateA = fsm.get_state();
assert_eq!(1, state_a.n);
assert_eq!(1, fsm.val);
fsm.dispatch(MyEvent)?;
assert_eq!(2, fsm.val);
Ok(())
}
License: MIT OR Apache-2.0