Crate small_fsm

Crate small_fsm 

Source
Expand description

§FSM for Rust

Build Status Latest Version Rust Documentation License Badge

Finite State Machine for Rust.

The full version of the README can be found on GitHub.

§Including Fsm in Your Project

[dependencies]
small-fsm = "0.1"

# optional, you can also use `strum` to work with enums and strings easier in Rust.
# strum = { version = "0.26", features = ["derive"] }

§Example

use small_fsm::{Closure, EventDesc, FSMState, HookType, FSM};
use std::collections::HashMap;
use strum::AsRefStr;
use strum::Display;

#[derive(Display, AsRefStr, Debug, Clone, Hash, PartialEq, Eq)]
enum StateTag {
    #[strum(serialize = "opened")]
    Opened,
    #[strum(serialize = "closed")]
    Closed,
}
impl FSMState for StateTag {}
impl AsRef<Self> for StateTag {
    fn as_ref(&self) -> &Self {
        &self
    }
}

#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
pub enum MyError {
    Unknown,
}

impl std::fmt::Display for MyError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
        match self {
            MyError::Unknown => write!(f, "unknown error"),
        }
    }
}

impl std::error::Error for MyError {
    fn description(&self) -> &str {
        match self {
            MyError::Unknown => "unknown error.",
        }
    }
}

let mut fsm: FSM<_, Vec<u32>, _> = FSM::new(
    StateTag::Closed,
    vec![
        EventDesc {
            name: "open",
            src: vec![StateTag::Closed],
            dst: StateTag::Opened,
        },
        EventDesc {
            name: "close",
            src: vec![StateTag::Opened],
            dst: StateTag::Closed,
        },
    ],
    HashMap::from([
        (
            HookType::BeforeEvent,
            Closure::new(|_e| -> Result<(), MyError> { Ok(()) }),
        ),
        (
            HookType::AfterEvent,
            Closure::new(|_e| -> Result<(), MyError> { Ok(()) }),
        ),
    ]),
);

assert_eq!(StateTag::Closed, fsm.get_current());

assert!(fsm.on_event("open", None).is_ok());
assert_eq!(StateTag::Opened, fsm.get_current());

assert!(fsm.on_event("close", None).is_ok());
assert_eq!(StateTag::Closed, fsm.get_current());

Structs§

Closure
Closure is a wrapper around a closure that implements the Action trait. unsupport thread-safe
EventDesc
EventDesc represents an event when initializing the FSM.
FSM
FSM represents a finite state machine.

Enums§

CallbackType
CallbackType represents the type of callback.
FSMError
FSMError is the error type for the FSM.
HookType
HookType represents the type of event.

Traits§

Action
Action is the trait for callbacks.
FSMState
FSMState represents the state of the FSM.