Struct StateMachine

pub struct StateMachine<S>
where S: Ord + Clone,
{ /* private fields */ }
Expand description

A bounded directed transition graph with one deferred request at a time.

Requesting, inspecting, replacing, and cancelling never change Self::current. Only a successful commit changes it, and each queued transition is consumed once. Tracing is disabled initially; enabling it retains at most the configured number of records, evicting the oldest on overflow.

Implementations§

§

impl<S> StateMachine<S>
where S: Ord + Clone,

pub fn new(initial: S) -> StateMachine<S>

Start at initial with no permitted edges, pending transition, or tracing.

pub fn set_trace_capacity( &mut self, capacity: usize, ) -> Result<(), TryReserveError>

Enable or resize the commit trace, retaining the newest capacity records.

Zero disables tracing, discards history and releases its backing buffer. Other sizes reserve the full record capacity up front, so recording never grows the ring. Shrinking to a nonzero size reuses the existing allocation. State clones can allocate; the bound is on record count, not state bytes. Disabled tracing does not clone states beyond the normal commit clone.

Allocation failure or an unrepresentable capacity returns an error without changing the trace or its limit. Configuration never changes the current state, pending request/cause, or Self::commit_sequence. Enabling tracing does not recover earlier commits.

use ferravex_engine::state::{StateMachine, Transition, TransitionRecord};
let mut states = StateMachine::new("menu");
states.allow("menu", "playing");
states.allow("playing", "menu");
states.set_trace_capacity(2)?;
states.request_with_cause("playing", "start button")?;
states.commit_with(|_| {});
assert_eq!(states.trace().next(), Some(&TransitionRecord {
    sequence: 1,
    cause: Some("start button"),
    transition: Transition { from: "menu", to: "playing" },
}));
states.request("menu")?;
states.commit();
states.set_trace_capacity(1)?;
assert_eq!(states.trace_capacity(), 1);
assert_eq!(states.trace().len(), 1);
assert_eq!(states.trace().next().unwrap().sequence, 2);
assert_eq!(states.trace().next().unwrap().cause, None);
states.clear_trace();
assert_eq!(states.trace().len(), 0);
assert_eq!(states.commit_sequence(), 2);
states.set_trace_capacity(0)?;
assert_eq!(states.trace_capacity(), 0);

pub fn trace_capacity(&self) -> usize

Maximum retained records; zero means tracing is disabled.

pub fn trace(&self) -> Iter<'_, TransitionRecord<S>>

Borrow records oldest to newest without allocating, cloning or consuming.

Records are appended before lifecycle hooks run. A record means the state committed, not that host exit/enter work completed successfully.

pub fn clear_trace(&mut self)

Discard history, retaining capacity, pending context and commit sequence.

pub fn commit_sequence(&self) -> u64

Successful commits since construction, even while tracing is disabled.

Starts at zero and saturates at u64::MAX; at saturation, records share that sequence and iterator order still reflects commit order. Rejected or cancelled requests, rejected guards and empty commits never advance it.

pub fn allow(&mut self, from: S, to: S) -> bool

Allow a directed edge. Returns false when 256 distinct edges already exist.

Duplicate edge registration is idempotent. A registered self-edge still cannot be requested: same-state requests never trigger exit/enter handling.

pub fn check_request(&self, next: &S) -> Result<(), TransitionError>

Check whether Self::request would accept next, without queuing it.

An existing pending transition takes precedence over other errors, exactly as in request. Use Self::replace_pending to explicitly supersede it.

pub fn request(&mut self, next: S) -> Result<(), TransitionError>

Queue next without changing the current state or running lifecycle work.

Any error preserves both the current state and an existing pending request. The accepted request has no cause label; see Self::request_with_cause.

pub fn request_with_cause( &mut self, next: S, cause: &'static str, ) -> Result<(), TransitionError>

Queue next with a diagnostic cause using the same checks as Self::request.

The label is retained with the pending request, including across guard rejection, even while tracing is disabled. Errors preserve the previous request and cause. Static labels require no allocation or string copying; they do not affect validation. See Self::set_trace_capacity for usage.

pub fn replace_pending(&mut self, next: S) -> Result<Option<S>, TransitionError>

Atomically queue next, returning the previous pending target, if any.

Validation uses the current state, not the old pending target. On an invalid or same-state target, the previous request is retained. With no pending request this behaves like Self::request. Replacing a request with the same pending target is allowed and does not cause extra lifecycle work; only a subsequent commit does. Successful replacement clears the old cause label; use Self::replace_pending_with_cause to supply a new one.

use ferravex_engine::state::{StateMachine, TransitionError};
let mut states = StateMachine::new("menu");
states.allow("menu", "playing");
states.allow("menu", "quit");
states.request("playing")?;
assert_eq!(states.replace_pending("quit")?, Some("playing"));
assert_eq!(states.replace_pending("menu"), Err(TransitionError::SameState));
assert_eq!(states.pending(), Some(&"quit"));
assert_eq!(states.current(), &"menu");

pub fn replace_pending_with_cause( &mut self, next: S, cause: &'static str, ) -> Result<Option<S>, TransitionError>

Atomically replace the queued target and its diagnostic cause.

Uses Self::replace_pending validation; errors preserve both the old target and cause. Replacing with the same pending target updates the label. With no pending target, queues a labeled request. Neither path records a transition until commit.

use ferravex_engine::state::{StateMachine, TransitionError};
let mut states = StateMachine::new("menu");
states.allow("menu", "playing");
states.allow("menu", "quit");
states.request_with_cause("playing", "start button")?;
assert_eq!(states.replace_pending_with_cause("quit", "window closed")?,
    Some("playing"));
assert_eq!(states.pending_cause(), Some("window closed"));
assert_eq!(states.replace_pending_with_cause("menu", "invalid"),
    Err(TransitionError::SameState));
assert_eq!(states.pending_cause(), Some("window closed"));
states.cancel();
assert_eq!(states.pending_cause(), None);

pub fn current(&self) -> &S

The live state, unchanged until a transition is committed.

pub fn pending(&self) -> Option<&S>

The queued target, if any.

pub fn pending_cause(&self) -> Option<&'static str>

Cause of the pending request; None if unlabeled or no request is queued.

pub fn pending_transition(&self) -> Option<Transition<&S>>

Borrow both endpoints without consuming the request or cloning states.

pub fn cancel(&mut self) -> Option<S>

Discard the pending cause and return the queued target without changing the live state, commit sequence or history.

pub fn commit(&mut self) -> Option<Transition<S>>

Consume a request and return its endpoints exactly once, without callbacks.

The current state has changed and the pending slot is empty before this returns. Calling again without another request returns None. A successful commit advances Self::commit_sequence and appends one record if tracing is enabled, evicting the oldest record when full.

State clones are prepared before mutation; if cloning panics, the current state, pending request/cause, sequence and trace remain unchanged.

pub fn commit_with( &mut self, apply: impl FnOnce(&Transition<S>), ) -> Option<Transition<S>>

Commit, then call apply once with the old and new states.

Put exit handling followed by enter handling in this single closure so both can borrow the same host context. Nothing runs without a pending request. apply runs after the state changes and the request is consumed; if it panics, the transition remains committed and will not be applied again. Its trace record (when enabled) is retained even if apply panics. Use Self::try_commit_with for fallible checks before lifecycle effects.

pub fn try_commit_with<E>( &mut self, guard: impl FnOnce(Transition<&S>) -> Result<(), E>, apply: impl FnOnce(&Transition<S>), ) -> Result<Option<Transition<S>>, E>

Check a pending transition, then commit and run lifecycle work once.

guard borrows the endpoints before any state change. On Err, the current state and pending target are retained, and apply is not called. The caller can retry, cancel, or replace that request. With no request, neither closure runs and this returns Ok(None). Errors are returned unchanged. Rejection also retains the pending cause and leaves sequence/history intact.

As with Self::commit_with, apply runs after commit. Keep exit/enter effects there: changes to external data made by guard cannot be rolled back.

use ferravex_engine::state::StateMachine;
let mut states = StateMachine::new("loading");
states.allow("loading", "running");
states.request("running").unwrap();
let assets_ready = false;
let result = states.try_commit_with(
    |_| if assets_ready { Ok(()) } else { Err("load the level assets first") },
    |_| unreachable!("a rejected transition has no lifecycle effects"),
);
assert_eq!(result, Err("load the level assets first"));
assert_eq!(states.current(), &"loading");
assert_eq!(states.pending(), Some(&"running"));

let mut lifecycle = Vec::new();
states.try_commit_with(
    |_| Ok::<(), &str>(()),
    |transition| {
        lifecycle.push(("exit", transition.from));
        lifecycle.push(("enter", transition.to));
    },
).unwrap();
assert_eq!(lifecycle, [("exit", "loading"), ("enter", "running")]);

Auto Trait Implementations§

§

impl<S> Freeze for StateMachine<S>
where S: Freeze,

§

impl<S> RefUnwindSafe for StateMachine<S>
where S: RefUnwindSafe,

§

impl<S> Send for StateMachine<S>
where S: Send,

§

impl<S> Sync for StateMachine<S>
where S: Sync,

§

impl<S> Unpin for StateMachine<S>
where S: Unpin,

§

impl<S> UnwindSafe for StateMachine<S>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.