StateBehavior

Trait StateBehavior 

Source
pub trait StateBehavior {
    type State: Clone + Copy + PartialEq + Default;
    type Event<'a>
       where Self: 'a;
    type Context;

    // Required method
    fn handle_event(
        &self,
        event: &Self::Event<'_>,
        _context: &mut Self::Context,
    ) -> Option<Self::State>;

    // Provided methods
    fn enter(&self, _context: &mut Self::Context) { ... }
    fn exit(&self, _context: &mut Self::Context) { ... }
}
Expand description

§Trait for the state behavior.

This trait should be implemented for an enum representing a set of states.

§Example

/// List of protocol states.
#[derive(Clone, Copy, Default, PartialEq)]
enum States {
    #[default]
    Init,
    Opened,
    Closed,
    Locked,
}

/// List of protocol events.
enum Events {
    Create,
    Open,
    Close,
    Lock,
    Unlock,
}

/// Protocol state machine context (data shared between states).
#[derive(Default)]
struct Context {
    lock_counter: u16,
}

impl StateBehavior for States {
    type State = Self;
    type Event<'a> = Events;
    type Context = Context;

    fn enter(&self, _context: &mut Self::Context) {
        if self == &States::Locked {
            _context.lock_counter += 1
        }
    }

    fn handle_event(
        &self,
        event: &Self::Event<'_>,
        _context: &mut Self::Context,
    ) -> Option<Self::State> {
        match (self, event) {
            (&States::Init, &Events::Create) => Some(States::Opened),
            (&States::Opened, &Events::Close) => Some(States::Closed),
            (&States::Closed, &Events::Open) => Some(States::Opened),
            (&States::Closed, &Events::Lock) => Some(States::Locked),
            (&States::Locked, &Events::Unlock) => Some(States::Closed),
            _ => None,
        }
    }
}

Required Associated Types§

Source

type State: Clone + Copy + PartialEq + Default

Source

type Event<'a> where Self: 'a

Source

type Context

Required Methods§

Source

fn handle_event( &self, event: &Self::Event<'_>, _context: &mut Self::Context, ) -> Option<Self::State>

Handle an event and return the next state (if a transition occurs).

Provided Methods§

Source

fn enter(&self, _context: &mut Self::Context)

State entry.

Source

fn exit(&self, _context: &mut Self::Context)

State exit.

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementors§