Skip to main content

Crate nanomachine

Crate nanomachine 

Source
Expand description

A generic finite state machine implementation.

This module provides a Machine struct that represents a finite state machine (FSM) with generic state (S) and event (E) types.

You can define transitions between states based on events, register callbacks for entering specific states or for any transition, and trigger events with optional payloads.

§Examples

use nanomachine::Machine;

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
enum State {
  Locked,
  Unlocked,
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
enum Event {
    InsertCoin,
    TurnKnob,
}

let mut nano = Machine::new(State::Locked);

// Define transitions.
nano.when(Event::InsertCoin, State::Locked, State::Unlocked);
nano.when(Event::TurnKnob, State::Unlocked, State::Locked);

// Register a callback when entering Unlocked.
nano.on_enter(State::Unlocked, |event| {
    println!("Unlocked by event: {:?}", event);
});

assert!(nano.trigger(&Event::InsertCoin).is_ok());
assert_eq!(*nano.state(), State::Unlocked);

assert!(nano.trigger(&Event::TurnKnob).is_ok());
assert_eq!(*nano.state(), State::Locked);

// You can attach data to transitions.
nano.on_enter_with(State::Unlocked, |event, amount: &u32| {
    println!("Unlocked after {} cents by {:?}", amount, event);
});

// Pass a payload when triggering.
nano.trigger_with(&Event::InsertCoin, &50u32);

Structs§

Machine
A generic finite state machine.

Enums§

MachineError
Errors that can occur when triggering events on a [Machine].

Type Aliases§

MachineResult
A specialized Result type for operations on a Machine.