#![doc = include_str!("../README.md")]
#![no_std]
pub use core::convert::Infallible;
pub trait State: Sized {
#[inline]
fn invariant<Error>(&self) -> Result<(), Error> {
Ok(())
}
#[inline]
fn leave<Ctx, Error>(&self, _ctx: &Ctx) -> Result<(), Error> {
Ok(())
}
#[inline]
fn enter<Ctx, Error>(&self, _ctx: &Ctx) -> Result<(), Error> {
Ok(())
}
}
#[derive(Debug, PartialEq)]
pub struct Primordial;
impl State for Primordial {}
#[derive(Debug, PartialEq)]
pub struct Terminated;
impl State for Terminated {}
pub trait InitialState<Error = Infallible>: State + core::fmt::Debug {
fn try_new() -> TransitionResult<Primordial, Self, Error>
where
Primordial: Transition<Self, Error>,
Error: core::fmt::Debug,
{
Primordial.try_transition()
}
fn try_new_with<Ctx>(ctx: &mut Ctx) -> TransitionResult<Primordial, Self, Error>
where
Primordial: Transition<Self, Error, Ctx>,
Error: core::fmt::Debug,
{
Primordial.try_transition_with(ctx)
}
}
impl<T: State + core::fmt::Debug> InitialState for T where Primordial: Transition<T> {}
pub trait InitialStateInfallible: State {
fn new() -> Self;
fn new_with<Ctx>(ctx: &mut Ctx) -> Self
where
Primordial: Transition<Self, Infallible, Ctx>;
}
impl<T: State + core::fmt::Debug> InitialStateInfallible for T
where
Primordial: Transition<T>,
{
fn new() -> Self
where
Primordial: Transition<Self, Infallible>,
{
#[allow(clippy::unwrap_used)]
Self::try_new().unwrap()
}
fn new_with<Ctx>(ctx: &mut Ctx) -> Self
where
Primordial: Transition<Self, Infallible, Ctx>,
{
#[allow(clippy::unwrap_used)]
Self::try_new_with(ctx).unwrap()
}
}
pub trait TerminalState<Error = Infallible>: State + core::fmt::Debug {
fn try_terminate(self) -> TransitionResult<Self, Terminated, Error>
where
Self: Transition<Terminated, Error>,
Error: core::fmt::Debug,
{
self.try_transition()
}
fn try_terminate_with<Ctx>(self, ctx: &mut Ctx) -> TransitionResult<Self, Terminated, Error>
where
Self: Transition<Terminated, Error, Ctx>,
Error: core::fmt::Debug,
{
self.try_transition_with(ctx)
}
}
impl<T: State + core::fmt::Debug> TerminalState for T where T: Transition<Terminated> {}
pub trait TerminalStateInfallible: State {
fn terminate(self) -> Terminated;
fn terminate_with<Ctx>(self, ctx: &mut Ctx) -> Terminated
where
Self: Transition<Terminated, Infallible, Ctx>;
}
impl<T: State + core::fmt::Debug> TerminalStateInfallible for T
where
T: Transition<Terminated>,
{
fn terminate(self) -> Terminated
where
Self: Transition<Terminated, Infallible>,
{
#[allow(clippy::unwrap_used)]
<Self as TerminalState>::try_terminate(self).unwrap()
}
fn terminate_with<Ctx>(self, ctx: &mut Ctx) -> Terminated
where
Self: Transition<Terminated, Infallible, Ctx>,
{
#[allow(clippy::unwrap_used)]
<Self as TerminalState>::try_terminate_with(self, ctx).unwrap()
}
}
#[derive(Debug, PartialEq)]
pub enum FailedAt<Origin, Next> {
None,
Origin(Origin),
Next(Next),
}
#[derive(Debug, PartialEq)]
pub struct ErrorState<E, Origin, Next> {
pub err: E,
pub at: FailedAt<Origin, Next>,
}
impl<E, Origin, Next> State for ErrorState<E, Origin, Next> {}
pub type TransitionResult<Origin, Next, Error> = Result<Next, ErrorState<Error, Origin, Next>>;
impl<E, Origin, Next> ErrorState<E, Origin, Next> {
#[inline]
pub const fn err(err: E) -> Result<Next, Self> {
Err(Self {
err,
at: FailedAt::None,
})
}
#[inline]
pub const fn err_origin(err: E, origin: Origin) -> Result<Next, Self> {
Err(Self {
err,
at: FailedAt::Origin(origin),
})
}
#[inline]
pub const fn err_next(err: E, next: Next) -> Result<Next, Self> {
Err(Self {
err,
at: FailedAt::Next(next),
})
}
}
pub trait Transition<Next: State, Error = Infallible, Ctx = ()>: State {
fn change(self, ctx: &mut Ctx) -> TransitionResult<Self, Next, Error>;
#[inline]
fn guard(&self, _ctx: &Ctx) -> Result<(), Error> {
Ok(())
}
#[inline]
fn try_transition(self) -> TransitionResult<Self, Next, Error>
where
Ctx: Default,
{
let mut ctx = Ctx::default();
self.try_transition_with(&mut ctx)
}
#[inline]
fn try_transition_with(self, ctx: &mut Ctx) -> TransitionResult<Self, Next, Error> {
if let Err(e) = self.invariant() {
return ErrorState::err_origin(e, self);
}
if let Err(e) = self.leave(&*ctx) {
return ErrorState::err_origin(e, self);
}
if let Err(e) = self.guard(&*ctx) {
return ErrorState::err_origin(e, self);
}
let next = self.change(ctx)?;
if let Err(e) = next.enter(&*ctx) {
return ErrorState::err_next(e, next);
}
if let Err(e) = next.invariant() {
return ErrorState::err_next(e, next);
}
Ok(next)
}
}
pub trait TransitionInfallible<Next: State, Ctx = ()>: Transition<Next, Infallible, Ctx> {
fn transition(self) -> Next
where
Ctx: Default,
Self: core::fmt::Debug,
Next: core::fmt::Debug,
{
#[allow(clippy::unwrap_used)]
self.try_transition().unwrap()
}
fn transition_with(self, ctx: &mut Ctx) -> Next
where
Self: core::fmt::Debug,
Next: core::fmt::Debug,
{
#[allow(clippy::unwrap_used)]
self.try_transition_with(ctx).unwrap()
}
}
impl<N: State, C, T: Transition<N, Infallible, C>> TransitionInfallible<N, C> for T {}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used)]
extern crate std;
use super::*;
use core::cell::Cell;
use std::rc::Rc;
use std::vec;
use std::vec::Vec;
#[derive(Debug, Default)]
struct Idle;
impl State for Idle {}
#[derive(Debug, Default)]
struct Blinking;
impl State for Blinking {}
#[derive(Debug, Default)]
struct Running;
impl State for Running {}
impl Transition<Blinking> for Idle {
fn change(self, _ctx: &mut ()) -> TransitionResult<Idle, Blinking, Infallible> {
Ok(Blinking)
}
}
impl Transition<Running> for Idle {
fn change(self, _ctx: &mut ()) -> TransitionResult<Idle, Running, Infallible> {
Ok(Running)
}
}
impl Transition<Idle> for Blinking {
fn change(self, _ctx: &mut ()) -> TransitionResult<Blinking, Idle, Infallible> {
Ok(Idle)
}
}
impl Transition<Running> for Blinking {
fn change(self, _ctx: &mut ()) -> TransitionResult<Blinking, Running, Infallible> {
Ok(Running)
}
}
impl Transition<Blinking> for Running {
fn change(self, _ctx: &mut ()) -> TransitionResult<Running, Blinking, Infallible> {
Ok(Blinking)
}
}
impl Transition<Idle> for Running {
fn change(self, _ctx: &mut ()) -> TransitionResult<Running, Idle, Infallible> {
Ok(Idle)
}
}
#[test]
fn smoke() {
let start = Idle;
let blinking: Blinking = start.transition();
let running: Running = blinking.transition();
let _: Idle = running.transition();
}
#[derive(Debug)]
struct Parsing {
buf: Vec<u8>,
pos: usize,
}
impl State for Parsing {}
#[derive(Debug)]
struct Ready {
buf: Vec<u8>,
}
impl State for Ready {}
impl Transition<Ready, Infallible> for Parsing {
fn change(self, _ctx: &mut ()) -> TransitionResult<Parsing, Ready, Infallible> {
Ok(Ready { buf: self.buf })
}
}
#[test]
fn data_carrying_states() {
let parsing = Parsing {
buf: vec![1, 2, 3],
pos: 0,
};
assert_eq!(parsing.pos, 0);
let ready: Ready = parsing.transition();
assert_eq!(ready.buf, vec![1, 2, 3]);
}
#[derive(Debug, PartialEq)]
enum MyError {
ConnectFailed,
GuardRejected,
}
#[derive(Debug)]
struct Connecting {
should_fail: bool,
}
impl State for Connecting {}
#[derive(Debug)]
struct Connected;
impl State for Connected {}
impl Transition<Connected, MyError> for Connecting {
fn change(self, _ctx: &mut ()) -> TransitionResult<Connecting, Connected, MyError> {
if self.should_fail {
ErrorState::err_origin(MyError::ConnectFailed, self)
} else {
Ok(Connected)
}
}
}
#[test]
fn fallible_change_success() {
let connecting = Connecting { should_fail: false };
let _connected: Connected = connecting.try_transition().unwrap();
}
#[test]
fn fallible_change_failure() {
let connecting = Connecting { should_fail: true };
let result: TransitionResult<Connecting, Connected, MyError> = connecting.try_transition();
assert!(result.is_err());
let enriched = result.unwrap_err();
assert_eq!(enriched.err, MyError::ConnectFailed);
match enriched.at {
FailedAt::Origin(c) => {
assert!(c.should_fail);
}
_ => panic!("Expected FailedAt::Origin"),
}
}
#[derive(Debug)]
struct HookedSource {
log: Rc<Cell<u32>>,
left: Rc<Cell<bool>>,
}
impl State for HookedSource {
fn leave<Ctx, Error>(&self, _ctx: &Ctx) -> Result<(), Error> {
self.left.set(true);
self.log.set(self.log.get() + 1);
Ok(())
}
}
#[derive(Debug)]
struct HookedTarget {
log: Rc<Cell<u32>>,
entered: Rc<Cell<bool>>,
}
impl State for HookedTarget {
fn enter<Ctx, Error>(&self, _ctx: &Ctx) -> Result<(), Error> {
self.entered.set(true);
self.log.set(self.log.get() + 1);
Ok(())
}
}
impl Transition<HookedTarget, Infallible> for HookedSource {
fn change(self, _ctx: &mut ()) -> TransitionResult<HookedSource, HookedTarget, Infallible> {
Ok(HookedTarget {
log: self.log,
entered: Rc::new(Cell::new(false)),
})
}
}
#[test]
fn enter_leave_hooks_called_in_order() {
let log = Rc::new(Cell::new(0));
let left = Rc::new(Cell::new(false));
let source = HookedSource {
log: Rc::clone(&log),
left: Rc::clone(&left),
};
let target: HookedTarget = source.transition();
assert!(left.get(), "leave() should have been called on source");
assert!(
target.entered.get(),
"enter() should have been called on target"
);
assert_eq!(log.get(), 2, "leave should be called before enter");
}
#[derive(Debug)]
struct SourceWithGuard;
impl State for SourceWithGuard {}
#[derive(Debug, Default)]
struct TargetDefault;
impl State for TargetDefault {}
impl Transition<TargetDefault, MyError> for SourceWithGuard {
fn change(
self,
_ctx: &mut (),
) -> TransitionResult<SourceWithGuard, TargetDefault, MyError> {
Ok(TargetDefault)
}
fn guard(&self, _ctx: &()) -> Result<(), MyError> {
Err(MyError::GuardRejected)
}
}
#[test]
fn guard_rejects_transition() {
let source = SourceWithGuard;
let result: TransitionResult<SourceWithGuard, TargetDefault, MyError> =
source.try_transition();
assert!(result.is_err());
let enriched = result.unwrap_err();
assert_eq!(enriched.err, MyError::GuardRejected);
match enriched.at {
FailedAt::Origin(_) => {} _ => panic!("Expected FailedAt::Origin after guard failure"),
}
}
#[derive(Debug, PartialEq)]
struct Counter {
value: u32,
}
impl State for Counter {}
impl Transition<Counter, Infallible> for Counter {
fn change(self, _ctx: &mut ()) -> TransitionResult<Counter, Counter, Infallible> {
Ok(Counter {
value: self.value + 1,
})
}
}
#[test]
fn self_transition_preserves_data() {
let counter = Counter { value: 5 };
let counter: Counter = counter.transition();
assert_eq!(counter.value, 6);
}
#[derive(Debug)]
struct FailChangeNone;
impl State for FailChangeNone {}
#[derive(Debug, Default)]
struct SimpleTarget;
impl State for SimpleTarget {}
impl Transition<SimpleTarget, MyError> for FailChangeNone {
fn change(self, _ctx: &mut ()) -> TransitionResult<FailChangeNone, SimpleTarget, MyError> {
ErrorState::err(MyError::ConnectFailed)
}
}
#[test]
fn failedat_none_on_change_failure() {
let source = FailChangeNone;
let result: TransitionResult<FailChangeNone, SimpleTarget, MyError> =
source.try_transition();
assert!(result.is_err());
let enriched = result.unwrap_err();
match enriched.at {
FailedAt::None => {}
_ => panic!("Expected FailedAt::None"),
}
}
#[derive(Debug)]
struct FailChangeNext;
impl State for FailChangeNext {}
impl Transition<SimpleTarget, MyError> for FailChangeNext {
fn change(self, _ctx: &mut ()) -> TransitionResult<FailChangeNext, SimpleTarget, MyError> {
ErrorState::err_next(MyError::ConnectFailed, SimpleTarget)
}
}
#[test]
fn failedat_next_on_change_failure() {
let source = FailChangeNext;
let result: TransitionResult<FailChangeNext, SimpleTarget, MyError> =
source.try_transition();
assert!(result.is_err());
let enriched = result.unwrap_err();
match enriched.at {
FailedAt::Next(_) => {}
_ => panic!("Expected FailedAt::Next"),
}
}
#[test]
fn failedat_origin_on_guard_failure() {
let source = SourceWithGuard;
let result: TransitionResult<SourceWithGuard, TargetDefault, MyError> =
source.try_transition();
assert!(result.is_err());
let enriched = result.unwrap_err();
match enriched.at {
FailedAt::Origin(_) => {}
_ => panic!("Expected FailedAt::Origin after guard failure"),
}
}
#[derive(Debug)]
struct SourceWithInvariant {
invariant_called: Rc<Cell<bool>>,
}
impl State for SourceWithInvariant {
fn invariant<Error>(&self) -> Result<(), Error> {
self.invariant_called.set(true);
Ok(())
}
}
#[derive(Debug)]
struct TargetWithInvariant {
invariant_called: Rc<Cell<bool>>,
}
impl State for TargetWithInvariant {
fn invariant<Error>(&self) -> Result<(), Error> {
self.invariant_called.set(true);
Ok(())
}
}
impl Transition<TargetWithInvariant, Infallible> for SourceWithInvariant {
fn change(
self,
_ctx: &mut (),
) -> Result<
TargetWithInvariant,
ErrorState<Infallible, SourceWithInvariant, TargetWithInvariant>,
> {
Ok(TargetWithInvariant {
invariant_called: Rc::new(Cell::new(false)),
})
}
}
#[test]
fn invariant_called_on_source_before_and_target_after() {
let source_flag = Rc::new(Cell::new(false));
let source = SourceWithInvariant {
invariant_called: Rc::clone(&source_flag),
};
assert!(!source_flag.get());
let target: TargetWithInvariant = source.transition();
assert!(source_flag.get());
assert!(target.invariant_called.get());
}
#[derive(Debug)]
#[allow(dead_code)]
enum WorkError {
TaskFailed,
Invalid,
}
#[derive(Debug, Default)]
struct IdleWork;
impl State for IdleWork {}
#[derive(Debug)]
struct Working {
should_fail: bool,
}
impl State for Working {}
#[derive(Debug)]
struct Done;
impl State for Done {}
impl Transition<Working, WorkError> for IdleWork {
fn change(self, _ctx: &mut ()) -> TransitionResult<IdleWork, Working, WorkError> {
Ok(Working { should_fail: false })
}
}
impl Transition<Done, WorkError> for Working {
fn change(self, _ctx: &mut ()) -> TransitionResult<Working, Done, WorkError> {
if self.should_fail {
ErrorState::err_origin(WorkError::TaskFailed, self)
} else {
Ok(Done)
}
}
}
impl Transition<IdleWork, WorkError> for ErrorState<WorkError, Working, Done> {
fn change(self, _ctx: &mut ()) -> TransitionResult<Self, IdleWork, WorkError> {
Ok(IdleWork)
}
}
#[test]
fn error_state_is_a_state() {
let error: ErrorState<WorkError, Working, Done> = ErrorState {
err: WorkError::TaskFailed,
at: FailedAt::None,
};
assert!(error.invariant::<WorkError>().is_ok());
assert!(error.leave::<(), WorkError>(&()).is_ok());
assert!(error.enter::<(), WorkError>(&()).is_ok());
}
#[test]
fn error_recovery_happy_path() {
let idle = IdleWork;
let working: Working = idle.try_transition().unwrap();
let done: Done = working.try_transition().unwrap();
let _ = done; }
#[test]
fn error_recovery_from_failure() {
let idle = IdleWork;
let _working: Working = idle.try_transition().unwrap();
let faulty = Working { should_fail: true };
let result: TransitionResult<Working, Done, WorkError> = faulty.try_transition();
assert!(result.is_err());
let error_state = result.unwrap_err();
assert!(matches!(error_state.at, FailedAt::Origin(_)));
let recovered_idle: IdleWork = error_state.try_transition().unwrap();
let working2: Working = recovered_idle.try_transition().unwrap();
let done: Done = working2.try_transition().unwrap();
let _ = done;
}
}