essm/lib.rs
1#![doc = include_str!("../README.md")]
2#![no_std]
3
4/// Re-export `Infallible` and `Any` so users can import everything via `use essm::*;`.
5/// When using wildcard imports, allow the Clippy lint:
6///
7/// ```rust
8/// # #[allow(clippy::wildcard_imports)]
9/// use essm::*;
10/// ```
11pub use core::{any::Any, convert::Infallible};
12
13/// A type that is used as state in a state-machine must implement `State`. States are
14/// generic over the error type their methods may raise. `Error` defaults to `Infallible` to
15/// simplify creation of state machines. Context is passed as '&dyn Any' and must be
16/// downcasted for use, side effects on the context need interior mutability. Context is not
17/// optional but can be ignored and transitions without context. We use the unit value `()`
18/// in that case. Context is not an `Option` because in almost any cases where a context is
19/// used, it is required and must be of the correct type. Failing to do so is a programming
20/// error, not a runtime error.
21///
22/// In the simplest case `impl State for MyType {}` is sufficient, being infallible and has no-op methods.
23pub trait State<Error = Infallible>: Sized {
24 /// Invariants check on States. Can be used for debugging (conditionally implemented). The
25 /// blanket implementation is a no-op, when not required then don't implement it.
26 /// Its on the users decision if invariant may panic or return an error.
27 ///
28 /// # Example
29 ///
30 /// ```
31 /// # #[allow(clippy::wildcard_imports)]
32 /// # use essm::*;
33 ///
34 /// struct Positive { value: i32 }
35 ///
36 /// impl State for Positive {
37 /// // May be gated to debug mode, falls back to the blanket no-op in release mode.
38 /// #[cfg(debug_assertions)]
39 /// fn invariant(&self) -> Result<(), Infallible> {
40 /// assert!(self.value > 0, "invariant violation: value must be positive");
41 /// Ok(())
42 /// }
43 /// }
44 /// ```
45 #[inline]
46 fn invariant(&self) -> Result<(), Error> {
47 Ok(())
48 }
49
50 /// Called before leaving this state.
51 ///
52 /// This method receives `&self`, so it cannot mutate the state directly. Use interior
53 /// mutability (e.g. [`Cell`](core::cell::Cell), [`RefCell`](core::cell::RefCell)) for
54 /// side effects such as logging or reference counting.
55 ///
56 /// The blanket implementation is a no-op. You only need to define it when needed.
57 ///
58 /// # Example
59 ///
60 /// ```
61 /// # #[allow(clippy::wildcard_imports)]
62 /// # use essm::*;
63 /// use core::cell::Cell;
64 ///
65 /// struct MyState { left: Cell<bool> }
66 ///
67 /// impl State for MyState {
68 /// fn leave(&self, _ctx: &dyn Any) -> Result<(), Infallible> {
69 /// self.left.set(true);
70 /// Ok(())
71 /// }
72 /// }
73 ///
74 /// let state = MyState { left: Cell::new(false) };
75 /// assert!(state.leave(&()).is_ok());
76 /// assert!(state.left.get());
77 /// ```
78 #[inline]
79 fn leave(&self, _ctx: &dyn Any) -> Result<(), Error> {
80 Ok(())
81 }
82
83 /// Called after entering this state.
84 ///
85 /// Like [`leave`](State::leave), this receives `&self`, use interior mutability
86 /// for side effects.
87 ///
88 /// The blanket implementation is a no-op. You only need to define it when needed.
89 ///
90 /// # Example
91 ///
92 /// ```
93 /// # #[allow(clippy::wildcard_imports)]
94 /// # use essm::*;
95 /// use core::cell::Cell;
96 ///
97 /// struct MyState { entered: Cell<bool> }
98 ///
99 /// impl State for MyState {
100 /// fn enter(&self, _ctx: &dyn Any) -> Result<(), Infallible> {
101 /// self.entered.set(true);
102 /// Ok(())
103 /// }
104 /// }
105 ///
106 /// let state = MyState { entered: Cell::new(false) };
107 /// assert!(state.enter(&()).is_ok());
108 /// assert!(state.entered.get());
109 /// ```
110 #[inline]
111 fn enter(&self, _ctx: &dyn Any) -> Result<(), Error> {
112 Ok(())
113 }
114}
115
116/// The state transition trait. Users implement this to define allowed transitions.
117///
118/// A transition is generic over four parameters:
119/// * `Next`: The state to transition to, this one is mandatory
120/// * `Error`: The error the transition may raise, defaults to `Infallible`
121/// * `OriginError`: The error associated with the input state, defaults to `Error`
122/// * `NextError`: The error associated with the input state, defaults to `OriginError`
123///
124/// External context is handed as `&dyn Any` and must be downcasted on use.
125///
126/// Only the `change()` method needs to be implemented all other method have sensible/no-op
127/// blanket implementations that can be overridden when required.
128pub trait Transition<
129 Next: State<NextError>,
130 Error = Infallible,
131 OriginError: MapErr<Error> = Error,
132 NextError: MapErr<Error> = OriginError,
133>: State<OriginError>
134{
135 /// Constructs the next state from the current state. This is the only mandatory method
136 /// that must be implemented by the user. `change()` should not be called manually later,
137 /// it is called by the transition methods which sequence it with other methods for state
138 /// transition.
139 ///
140 /// This method consumes `self`, it owns the current state and can move data out of it
141 /// into the next state. If construction fails, use [`ErrorState::err`],
142 /// [`ErrorState::err_origin`], or [`ErrorState::err_next`] to return the error with
143 /// information about what state survived.
144 ///
145 /// # Example
146 ///
147 /// ```
148 /// # #[allow(clippy::wildcard_imports)]
149 /// # use essm::*;
150 ///
151 /// #[derive(Debug)]
152 /// struct Src { data: u32 }
153 /// impl State for Src {}
154 ///
155 /// #[derive(Debug)]
156 /// struct Dst { data: u32 }
157 /// impl State for Dst {}
158 ///
159 /// impl Transition<Dst> for Src {
160 /// fn change(self, _ctx: &dyn Any) -> TransitionResult<Src, Dst> {
161 /// Ok(Dst { data: self.data })
162 /// }
163 /// }
164 ///
165 /// let src = Src { data: 42 };
166 /// let dst: Dst = src.transition();
167 /// assert_eq!(dst.data, 42);
168 /// ```
169 fn change(self, ctx: &dyn Any) -> TransitionResult<Self, Next, Error>;
170
171 /// Guard condition
172 ///
173 /// This guards a transition it receives the current state and context. It may error when
174 /// the transition is (dynamically determined) not available. The blanket implementaton is
175 /// a no-op.
176 ///
177 /// Returns `Ok(())` if the transition is allowed. Like [`leave`](State::leave),
178 /// this receives `&self`. Use interior mutability for side effects.
179 ///
180 /// # Example
181 ///
182 /// ```
183 /// # #[allow(clippy::wildcard_imports)]
184 /// # use essm::*;
185 ///
186 /// #[derive(Debug, PartialEq)]
187 /// enum MyError { NotReady }
188 ///
189 /// impl StateError for MyError {}
190 ///
191 /// #[derive(Debug, Default)]
192 /// struct Idle;
193 /// impl State<MyError> for Idle {}
194 ///
195 /// #[derive(Debug, Default)]
196 /// struct Running;
197 /// impl State<MyError> for Running {}
198 ///
199 /// // example only, showing a failing guard
200 /// fn is_ready() -> bool { false }
201 ///
202 /// impl Transition<Running, MyError> for Idle {
203 /// fn change(self, _ctx: &dyn Any) -> TransitionResult<Idle, Running, MyError> {
204 /// Ok(Running)
205 /// }
206 ///
207 /// fn guard(&self, _ctx: &dyn Any) -> Result<(), MyError> {
208 /// if is_ready() { Ok(()) } else { Err(MyError::NotReady) }
209 /// }
210 /// }
211 ///
212 /// let error = Idle.try_transition().unwrap_err();
213 /// assert_eq!(error.err, MyError::NotReady);
214 /// assert!(matches!(error.at, FailedAt::Origin(Idle)));
215 /// ```
216 #[inline]
217 fn guard(&self, _ctx: &dyn Any) -> Result<(), Error> {
218 Ok(())
219 }
220
221 /// Execute the transition without context. Delegates to
222 /// [`try_transition_with`](Transition::try_transition_with)(&dyn ()).
223 ///
224 /// Keep the blanket implementation and do not override it.
225 ///
226 /// # Example
227 ///
228 /// ```
229 /// # #[allow(clippy::wildcard_imports)]
230 /// # use essm::*;
231 /// #[derive(Debug)]
232 /// struct Idle; impl State for Idle {}
233 ///
234 /// #[derive(Debug)]
235 /// struct Running; impl State for Running {}
236 ///
237 /// impl Transition<Running> for Idle {
238 /// fn change(self, _ctx: &dyn Any) -> TransitionResult<Idle, Running> {
239 /// Ok(Running)
240 /// }
241 /// }
242 ///
243 /// let idle = Idle;
244 /// let running: Running = idle.try_transition().unwrap();
245 /// ```
246 #[inline]
247 fn try_transition(self) -> TransitionResult<Self, Next, Error> {
248 self.try_transition_with(&())
249 }
250
251 /// Execute the transition with mutable context.
252 ///
253 /// Using a context allows to pass suppelemental information along the state machine that
254 /// is not part of the states themself. ESSM does not put any limitations here, its
255 /// limited by the creativity of the user. Eg handles for user notification, interfaces to
256 /// the real world, queues, counters and so on can be put in contexts.
257 ///
258 /// Keep the blanket implementation and do not override it.
259 ///
260 /// # Example
261 ///
262 /// ```
263 /// # #[allow(clippy::wildcard_imports)]
264 /// # use essm::*;
265 /// # use std::cell::Cell;
266 /// #[derive(Debug)]
267 /// struct MyCtx { counter: Cell<u32> }
268 ///
269 /// impl MyCtx {
270 /// fn inc(&self) {
271 /// self.counter.set(self.counter.get()+1);
272 /// }
273 /// }
274 ///
275 /// #[derive(Debug, Default)]
276 /// struct Idle; impl State for Idle {}
277 ///
278 /// #[derive(Debug, Default)]
279 /// struct Running; impl State for Running {}
280 ///
281 /// impl Transition<Running> for Idle {
282 /// fn change(self, ctx: &dyn Any) -> TransitionResult<Idle, Running> {
283 /// let ctx=ctx.downcast_ref::<MyCtx>().unwrap();
284 /// ctx.inc();
285 /// Ok(Running)
286 /// }
287 /// }
288 /// let idle = Idle;
289 /// let ctx = MyCtx { counter: Cell::new(0) };
290 /// let running: Running = idle.try_transition_with(&ctx).unwrap();
291 /// assert_eq!(ctx.counter.get(), 1);
292 /// ```
293 #[inline]
294 fn try_transition_with(self, ctx: &dyn Any) -> TransitionResult<Self, Next, Error> {
295 // Source phase: &self borrows, recoverable
296 if let Err(e) = self.invariant().map_err(MapErr::map_err) {
297 return ErrorState::err_origin(e, self);
298 }
299 if let Err(e) = self.leave(ctx).map_err(MapErr::map_err) {
300 return ErrorState::err_origin(e, self);
301 }
302 if let Err(e) = self.guard(ctx) {
303 return ErrorState::err_origin(e, self);
304 }
305 // Transition: self consumed
306 let next = self.change(ctx)?;
307 // Next phase: &Next borrows, recoverable
308 if let Err(e) = next.enter(ctx).map_err(MapErr::map_err) {
309 return ErrorState::err_next(e, next);
310 }
311 if let Err(e) = next.invariant().map_err(MapErr::map_err) {
312 return ErrorState::err_next(e, next);
313 }
314 Ok(next)
315 }
316}
317
318/// Extension trait providing infallible transition methods for states where `Error = Infallible`.
319///
320/// This trait is automatically implemented for any type satisfying
321/// [`Transition`]`<Next, Ctx, Infallible>`. It provides [`transition`](TransitionInfallible::transition)
322/// and [`transition_with`](TransitionInfallible::transition_with).
323///
324/// # Example
325///
326/// ```
327/// # #[allow(clippy::wildcard_imports)]
328/// # use essm::*;
329///
330/// #[derive(Debug)]
331/// struct Idle;
332/// impl State for Idle {}
333///
334/// #[derive(Debug)]
335/// struct Running;
336/// impl State for Running {}
337///
338/// impl Transition<Running> for Idle {
339/// fn change(self, _ctx: &dyn Any) -> TransitionResult<Idle, Running> {
340/// Ok(Running)
341/// }
342/// }
343///
344/// let idle = Idle;
345/// let running = idle.transition(); // no Result, no unwrap needed
346/// ```
347pub trait TransitionInfallible<Next: State>: Transition<Next, Infallible> {
348 /// Infallible transition. Returns the next state directly.
349 fn transition(self) -> Next
350 where
351 Self: core::fmt::Debug,
352 Next: core::fmt::Debug,
353 {
354 #[allow(clippy::unwrap_used)]
355 self.try_transition().unwrap()
356 }
357
358 /// Infallible transition with context. Returns the next state directly.
359 fn transition_with(self, ctx: &dyn Any) -> Next
360 where
361 Self: core::fmt::Debug,
362 Next: core::fmt::Debug,
363 {
364 #[allow(clippy::unwrap_used)]
365 self.try_transition_with(ctx).unwrap()
366 }
367}
368
369/// Blanket implementation: any type with an infallible transition gets these convenience methods.
370impl<T: Transition<Next>, Next: State> TransitionInfallible<Next> for T {}
371
372/// The state before all states. Bootstrap mechanism for the state machine.
373///
374/// [`Primordial`] implements [`State<_>`] with all hooks being no-op. It exists solely as the
375/// source for the initial transition that creates the first real state of your state
376/// machine. You never instantiate it yourself. It is used internally by [`InitialState`]
377/// constructors.
378///
379/// # Bootstrap usage
380///
381/// To use [`Primordial`] as a bootstrap, implement `Transition<YourState>` for it:
382///
383/// ```
384/// # #[allow(clippy::wildcard_imports)]
385/// # use essm::*;
386///
387/// #[derive(Debug)]
388/// struct Idle;
389/// impl State for Idle {}
390///
391/// impl Transition<Idle> for Primordial {
392/// fn change(self, _ctx: &dyn Any) -> TransitionResult<Primordial, Idle> {
393/// Ok(Idle)
394/// }
395/// }
396/// ```
397///
398/// With this in place, `InitialState*`'s blanket impl gives you convenience
399/// constructors `new()/new_with()/try_new()/try_new_with()`:
400///
401/// ```
402/// # #[allow(clippy::wildcard_imports)]
403/// # use essm::*;
404/// # #[derive(Debug)]
405/// # struct Idle;
406/// # impl State for Idle {}
407/// # impl Transition<Idle> for Primordial {
408/// # fn change(self, _ctx: &dyn Any) -> TransitionResult<Primordial, Idle> {
409/// # Ok(Idle)
410/// # }
411/// # }
412/// let idle = Idle::new();
413/// ```
414#[derive(Debug, PartialEq)]
415pub struct Primordial;
416impl<Error> State<Error> for Primordial {}
417
418/// Convenience constructors for states that can be created from [`Primordial`].
419///
420/// This provides `try_new()` and `try_new_with(ctx)` methods to create initial states.
421///
422/// # Example
423///
424/// ```
425/// # #[allow(clippy::wildcard_imports)]
426/// # use essm::*;
427///
428/// #[derive(Debug)]
429/// enum DbError { ConnectionFailed }
430///
431/// impl StateError for DbError {}
432///
433/// #[derive(Debug)]
434/// struct DbConnected { conn: u32 }
435/// impl State<DbError> for DbConnected {}
436///
437/// impl Transition<DbConnected, DbError> for Primordial {
438/// fn change(self, _ctx: &dyn Any) -> TransitionResult<Primordial, DbConnected, DbError> {
439/// // ... connect to database ...
440/// Ok(DbConnected { conn: 42 })
441/// }
442/// }
443///
444/// # fn main() -> Result<(), ErrorState<DbError, Primordial, DbConnected>> {
445/// let db = DbConnected::try_new()?;
446/// # Ok(())
447/// # }
448/// ```
449pub trait InitialState<Error: MapErr<Error>>: State<Error> + core::fmt::Debug {
450 /// Fallible creation without context.
451 ///
452 /// Returns the new state, or an [`ErrorState`] describing what went wrong.
453 /// The error type is the generic `Error` parameter, which comes from your
454 /// `Transition<Self, Error> for `[`Primordial`] implementation.
455 /// Context defaults to `&()`.
456 fn try_new() -> TransitionResult<Primordial, Self, Error>
457 where
458 Primordial: Transition<Self, Error>,
459 Error: core::fmt::Debug,
460 {
461 Primordial.try_transition()
462 }
463
464 /// Fallible creation with context.
465 ///
466 /// Like [`try_new`](InitialState::try_new) but passes a context through the transition
467 /// pipeline. Use this when construction needs access to external resources or shared
468 /// state.
469 fn try_new_with(ctx: &dyn Any) -> TransitionResult<Primordial, Self, Error>
470 where
471 Primordial: Transition<Self, Error>,
472 Error: core::fmt::Debug,
473 {
474 Primordial.try_transition_with(ctx)
475 }
476}
477
478/// Implement `InitialState` for all types that implement `Transition<T,Error> for Primordial`.
479impl<T: State<Error> + core::fmt::Debug, Error: MapErr<Error>> InitialState<Error> for T where
480 Primordial: Transition<T, Error>
481{
482}
483
484/// Convenience constructors for states that can be infallibly crated from [`Primordial`].
485///
486/// This provides `new()` and `new_with(ctx)` methods to create initial states. Unlike the
487/// `try_*` variants, infallible constructions returns the new states directly instead
488/// wrapping them into [`TransitionResult`].
489///
490/// # Example
491///
492/// ```
493/// # #[allow(clippy::wildcard_imports)]
494/// # use essm::*;
495/// #[derive(Debug)]
496/// struct Red;
497/// impl State for Red {}
498///
499/// impl Transition<Red> for Primordial {
500/// fn change(self, _ctx: &dyn Any) -> TransitionResult<Primordial, Red> {
501/// Ok(Red)
502/// }
503/// }
504///
505/// let red = Red::new();
506/// ```
507pub trait InitialStateInfallible: State {
508 /// Infallible constructor.
509 fn new() -> Self;
510
511 /// Infallible constructor with context.
512 fn new_with(ctx: &dyn Any) -> Self;
513}
514
515/// Implement `InitialStateInfallible` for all types that implement `Transition<T, Infallible> for Primordial`.
516impl<T: State + core::fmt::Debug> InitialStateInfallible for T
517where
518 Primordial: Transition<T, Infallible>,
519{
520 fn new() -> Self
521 where
522 Primordial: Transition<Self>,
523 {
524 // Infallible will never error
525 #[allow(clippy::unwrap_used)]
526 Self::try_new().unwrap()
527 }
528
529 fn new_with(ctx: &dyn Any) -> Self
530 where
531 Primordial: Transition<Self>,
532 {
533 // Infallible will never error
534 #[allow(clippy::unwrap_used)]
535 Self::try_new_with(ctx).unwrap()
536 }
537}
538
539/// The terminal state. The state a machine enters when it is done.
540///
541/// [`Terminated`] is the symmetric counterpart to [`Primordial`]: just as a state machine
542/// starts by transitioning *from* `Primordial`, it can ends by transitioning *to*
543/// `Terminated`.
544///
545/// Transitions to `Terminated` are defined via `impl Transition<Terminated> for MyState`,
546/// which triggers the blanket implementation of [`TerminalState`] and [`TerminalStateInfallible`].
547/// These in turn providing different flavors of `terminate()` calls to tear a state machine down.
548/// You never instantiate or use `Terminated` yourself outside of the `Transition` implementation.
549///
550/// # Example
551///
552/// ```
553/// # #[allow(clippy::wildcard_imports)]
554/// # use essm::*;
555///
556/// #[derive(Debug)] struct Red; impl State for Red {}
557/// #[derive(Debug)] struct Green; impl State for Green {}
558///
559/// // Primordial->Red defines the initial constructor
560/// impl Transition<Red> for Primordial {
561/// fn change(self, _: &dyn Any) -> TransitionResult<Primordial, Red> { Ok(Red) }
562/// }
563///
564/// // Red->Green is a user defined transition
565/// impl Transition<Green> for Red {
566/// fn change(self, _: &dyn Any) -> TransitionResult<Red, Green> { Ok(Green) }
567/// }
568///
569/// // Green->Terminated defines the destruction
570/// impl Transition<Terminated> for Green {
571/// fn change(self, _: &dyn Any) -> TransitionResult<Green, Terminated> { Ok(Terminated) }
572/// }
573///
574/// let red = Red::new();
575/// let green: Green = red.transition();
576/// // Finally terminate the state machine.
577/// green.terminate();
578/// ```
579///
580/// # `impl Drop` on state types
581///
582/// Rust forbids partial moves out of `Drop`-implementing types (E0509), but
583/// [`Transition::change`] consumes `self` and may move data
584/// into the next state. The most universal workaround is [`Option::take()`],
585/// wrap movable fields in [`Option`] and extract ownership through `&mut self`
586/// without destructuring.
587///
588/// [`core::mem::take()`] is an alternative for `T: Default` types. External crates like
589/// `derive_destructure2` provide proc macros for destructuring `Drop` types directly. For
590/// zero-cost repackaging, wrap in [`ManuallyDrop`](core::mem::ManuallyDrop) and
591/// [`ptr::read`](core::ptr::read) each field.
592///
593/// Prefer [`TerminalState`] for structured teardown. See the crate-level
594/// documentation for a full example.
595#[derive(Debug, PartialEq)]
596pub struct Terminated;
597impl<Error> State<Error> for Terminated {}
598
599/// Convenience destructors for states that can be transitioned to [`Terminated`].
600///
601/// This provides `try_terminate()` and `try_terminate_with(ctx)` methods to destroy states.
602///
603/// # Example
604///
605/// ```
606/// # #[allow(clippy::wildcard_imports)]
607/// # use essm::*;
608///
609/// #[derive(Debug, Default)]
610/// enum MyError { #[default] CleanupFailed }
611///
612/// impl StateError for MyError {}
613///
614/// #[derive(Debug)]
615/// struct Active;
616/// impl State<MyError> for Active {}
617/// impl Transition<Active, MyError> for Primordial {
618/// fn change(self, _: &dyn Any) -> TransitionResult<Primordial, Active, MyError> { Ok(Active) }
619/// }
620///
621/// // The teardown transition
622/// impl Transition<Terminated, MyError> for Active {
623/// fn change(self, _: &dyn Any) -> TransitionResult<Active, Terminated, MyError> {
624/// // ... cleanup that may fail ...
625/// Ok(Terminated)
626/// }
627/// }
628///
629/// # fn main() {
630/// // since we use `MyError` only the fallible constructors are available
631/// let active = Active::try_new().unwrap();
632/// // destroy the state
633/// active.try_terminate().unwrap();
634/// # }
635/// ```
636pub trait TerminalState<Error: MapErr<Error>>: State<Error> + core::fmt::Debug {
637 /// Fallible termination without context.
638 ///
639 /// Consumes the state and returns [`Terminated`], or an [`ErrorState`] describing
640 /// what went wrong. The error type is the generic `Error` parameter, which comes
641 /// from your `Transition<Terminated, Error> for Self` implementation.
642 /// When no Error happened then the `Terminated` itself can be just dropped.
643 fn try_terminate(self) -> TransitionResult<Self, Terminated, Error>
644 where
645 Self: Transition<Terminated, Error>,
646 Error: core::fmt::Debug,
647 {
648 self.try_transition()
649 }
650
651 /// Fallible termination with context.
652 ///
653 /// Like [`try_terminate`](TerminalState::try_terminate) but passes a context through the
654 /// transition pipeline. Use this when termination needs access to external resources or
655 /// shared state.
656 fn try_terminate_with(self, ctx: &dyn Any) -> TransitionResult<Self, Terminated, Error>
657 where
658 Self: Transition<Terminated, Error>,
659 Error: core::fmt::Debug,
660 {
661 self.try_transition_with(ctx)
662 }
663}
664
665/// Blanket implementation for states that can transition to [`Terminated`]
666impl<T: State<Error> + core::fmt::Debug, Error: MapErr<Error>> TerminalState<Error> for T where
667 T: Transition<Terminated, Error>
668{
669}
670
671/// Extension trait providing infallible termination methods for states where `Error = Infallible`.
672///
673/// This trait is automatically implemented for any state satisfying `Infallible` as Error.
674/// It provides [`terminate()`](TerminalStateInfallible::terminate) and
675/// [`terminate_with()`](TerminalStateInfallible::terminate_with) which do not return a
676/// `Result`.
677///
678/// # Example
679///
680/// ```
681/// # #[allow(clippy::wildcard_imports)]
682/// # use essm::*;
683///
684/// #[derive(Debug)]
685/// struct Green;
686/// impl State for Green {}
687/// impl Transition<Green> for Primordial {
688/// fn change(self, _: &dyn Any) -> TransitionResult<Primordial, Green> { Ok(Green) }
689/// }
690///
691/// impl Transition<Terminated> for Green {
692/// fn change(self, _: &dyn Any) -> TransitionResult<Green, Terminated> { Ok(Terminated) }
693/// }
694///
695/// let green = Green::new();
696/// green.terminate();
697/// ```
698pub trait TerminalStateInfallible: State<Infallible> {
699 /// Infallible termination. Consumes the state and returns [`Terminated`].
700 fn terminate(self);
701
702 /// Infallible termination with context.
703 fn terminate_with(self, ctx: &dyn Any);
704}
705
706/// Implement `TerminalStateInfallible` for all types that implement `Transition<Terminal, Infallible> for T`.
707impl<T: State<Infallible> + core::fmt::Debug> TerminalStateInfallible for T
708where
709 T: Transition<Terminated, Infallible>,
710{
711 fn terminate(self) {
712 self.transition();
713 }
714
715 fn terminate_with(self, ctx: &dyn Any) {
716 self.transition_with(ctx);
717 }
718}
719
720/// Error to Error conversion
721/// For states that are generic over different error types we need error to error conversions.
722/// * For `Infallible` into any other Error this is already implemented.
723/// * For any `E` that implements `StateError` a E->E self conversion is implemented as well
724/// (rust wont let us blanket implement this without the helper trait `StateError`).
725///
726/// Implement `StateError` for your error types, this is just a marker, no methods.
727/// Any conversion between different errors needs to be explicitly implemented by the user.
728pub trait MapErr<E>: Sized {
729 /// Takes a Self and converts it to E
730 fn map_err(self) -> E;
731}
732
733impl<E> MapErr<E> for Infallible {
734 /// This can never happen since `Infallible` errors never happen. Optimizes to a no-op.
735 #[inline]
736 fn map_err(self) -> E {
737 unreachable!()
738 }
739}
740
741/// Marker trait that enables no-op E->E conversions. Any user defined error type must either
742/// `impl StateError for UserError{}` or `impl MapErr<UserError> for UserError { fn
743/// map_err(self)->Self{self}}`. The first is more convenient to do.
744pub trait StateError {}
745
746/// Defines the no-op E->E conversion.
747impl<E: StateError> MapErr<E> for E {
748 #[inline]
749 fn map_err(self) -> Self {
750 self
751 }
752}
753
754/// Indicates at what point a transition failed and what state survived.
755#[derive(Debug, PartialEq)]
756pub enum FailedAt<Origin, Next> {
757 /// Source consumed, no state to recover.
758 None,
759 /// Holds the source state, invariant/leave/guard failed.
760 Origin(Origin),
761 /// Holds the target state, enter/invariant on next failed.
762 Next(Next),
763}
764
765/// Wraps an error with information about what state survived the failed transition.
766///
767/// `ErrorState` implements [`State`], it can be used as a state in error recovery transitions.
768///
769/// Note that we do not depend on `core::error::Error`, for all our use cases requiring only
770/// `Debug` is sufficient.
771#[derive(Debug, PartialEq)]
772pub struct ErrorState<Error, Origin, Next> {
773 /// Actual error
774 pub err: Error,
775 /// Recovered state
776 pub at: FailedAt<Origin, Next>,
777}
778
779/// `ErrorState` implements constructors that ergonomically create `Result::Err` instances.
780impl<E, Origin, Next> ErrorState<E, Origin, Next> {
781 /// Error with no state recoverable state. The `at` field is set to `None`.
782 ///
783 /// # Example
784 ///
785 /// ```
786 /// # #[allow(clippy::wildcard_imports)]
787 /// # use essm::*;
788 ///
789 /// #[derive(Debug)]
790 /// enum MyError { Bad }
791 ///
792 /// impl StateError for MyError {}
793 ///
794 /// #[derive(Debug)]
795 /// struct Src;
796 /// impl State<MyError> for Src {}
797 ///
798 /// #[derive(Debug)]
799 /// struct Dst;
800 /// impl State<MyError> for Dst {}
801 ///
802 /// impl Transition<Dst, MyError> for Src {
803 /// fn change(self, _ctx: &dyn Any) -> TransitionResult<Src, Dst, MyError> {
804 /// // Change fails, source consumed, nothing survived
805 /// ErrorState::err(MyError::Bad)
806 /// }
807 /// }
808 ///
809 /// let result = Src.try_transition();
810 /// assert!(result.is_err());
811 /// let error = result.unwrap_err();
812 /// assert!(matches!(error.at, FailedAt::None));
813 /// ```
814 #[inline]
815 pub const fn err(err: E) -> Result<Next, Self> {
816 Err(Self {
817 err,
818 at: FailedAt::None,
819 })
820 }
821
822 /// Error with origin state preserved, invariant/leave/guard failed.
823 /// The `at` field will contain `FailedAt::Origin(self)`.
824 ///
825 /// # Example
826 ///
827 /// ```
828 /// # #[allow(clippy::wildcard_imports)]
829 /// # use essm::*;
830 ///
831 /// #[derive(Debug)]
832 /// enum MyError { Bad }
833 ///
834 /// impl StateError for MyError {}
835 ///
836 /// #[derive(Debug)]
837 /// struct Src;
838 /// impl State<MyError> for Src {}
839 ///
840 /// #[derive(Debug)]
841 /// struct Dst;
842 /// impl State<MyError> for Dst {}
843 ///
844 /// impl Transition<Dst, MyError> for Src {
845 /// fn change(self, _ctx: &dyn Any) -> TransitionResult<Src, Dst, MyError> {
846 /// // Change fails, origin state preserved for recovery
847 /// ErrorState::err_origin(MyError::Bad, self)
848 /// }
849 /// }
850 ///
851 /// let result = Src.try_transition();
852 /// assert!(result.is_err());
853 /// let error = result.unwrap_err();
854 /// assert!(matches!(error.at, FailedAt::Origin(_)));
855 /// ```
856 #[inline]
857 pub const fn err_origin(err: E, origin: Origin) -> Result<Next, Self> {
858 Err(Self {
859 err,
860 at: FailedAt::Origin(origin),
861 })
862 }
863
864 /// Error with next state preserved, enter/invariant on target failed.
865 /// The `at` field will contain `FailedAt::Next(next)`.
866 ///
867 /// # Example
868 ///
869 /// ```
870 /// # #[allow(clippy::wildcard_imports)]
871 /// # use essm::*;
872 ///
873 /// #[derive(Debug)]
874 /// enum MyError { Bad }
875 ///
876 /// impl StateError for MyError {}
877 ///
878 /// #[derive(Debug)]
879 /// struct Src;
880 /// impl State<MyError> for Src {}
881 ///
882 /// #[derive(Debug)]
883 /// struct Dst;
884 /// impl State<MyError> for Dst {}
885 ///
886 /// impl Transition<Dst, MyError> for Src {
887 /// fn change(self, _ctx: &dyn Any) -> TransitionResult<Src, Dst, MyError> {
888 /// let next = Dst;
889 /// // Target constructed but invalid; return it so caller can recover
890 /// ErrorState::err_next(MyError::Bad, next)
891 /// }
892 /// }
893 ///
894 /// let result = Src.try_transition();
895 /// assert!(result.is_err());
896 /// let error = result.unwrap_err();
897 /// assert!(matches!(error.at, FailedAt::Next(_)));
898 /// ```
899 #[inline]
900 pub const fn err_next(err: E, next: Next) -> Result<Next, Self> {
901 Err(Self {
902 err,
903 at: FailedAt::Next(next),
904 })
905 }
906}
907
908/// Any `ErrorState` itself implements `State<Infallible>` thus they can be used in a
909/// statemachine to recover from errors.
910impl<Error, Origin, Next> State<Infallible> for ErrorState<Error, Origin, Next> {}
911
912/// The canonical return type of a state transition.
913///
914/// `TransitionResult<Origin, Next, Error>` is a type alias for `Result<Next,
915/// ErrorState<Error, Origin, Next>>` with `Error` defaulting to `Infallible`. It simplifies
916/// the signature of [`Transition::change`] and related methods by putting the three type
917/// parameters in a logical order: where we came from, where we're going, and what can go
918/// wrong.
919///
920/// # Example
921///
922/// ```
923/// # #[allow(clippy::wildcard_imports)]
924/// # use essm::*;
925///
926/// #[derive(Debug)]
927/// struct Idle;
928/// impl State for Idle {}
929///
930/// #[derive(Debug)]
931/// struct Running;
932/// impl State for Running {}
933///
934/// impl Transition<Running> for Idle {
935/// fn change(self, _ctx: &dyn Any) -> TransitionResult<Idle, Running> {
936/// Ok(Running)
937/// }
938/// }
939/// ```
940pub type TransitionResult<Origin, Next, Error = Infallible> =
941 Result<Next, ErrorState<Error, Origin, Next>>;
942
943#[cfg(test)]
944mod tests {
945 #![allow(clippy::unwrap_used)]
946 extern crate std;
947 use super::*;
948 use std::vec;
949 use std::vec::Vec;
950
951 #[derive(Debug, PartialEq)]
952 enum MyError {
953 ConnectFailed,
954 GuardRejected,
955 }
956
957 impl StateError for MyError {}
958
959 #[test]
960 fn smoke() {
961 #[derive(Debug, Default)]
962 struct Idle;
963 impl State for Idle {}
964
965 #[derive(Debug, Default)]
966 struct Blinking;
967 impl State for Blinking {}
968
969 #[derive(Debug, Default)]
970 struct Running;
971 impl State for Running {}
972
973 impl Transition<Blinking> for Idle {
974 fn change(self, _ctx: &dyn Any) -> TransitionResult<Idle, Blinking> {
975 Ok(Blinking)
976 }
977 }
978 impl Transition<Running> for Idle {
979 fn change(self, _ctx: &dyn Any) -> TransitionResult<Idle, Running> {
980 Ok(Running)
981 }
982 }
983 impl Transition<Idle> for Blinking {
984 fn change(self, _ctx: &dyn Any) -> TransitionResult<Blinking, Idle> {
985 Ok(Idle)
986 }
987 }
988 impl Transition<Running> for Blinking {
989 fn change(self, _ctx: &dyn Any) -> TransitionResult<Blinking, Running> {
990 Ok(Running)
991 }
992 }
993 impl Transition<Blinking> for Running {
994 fn change(self, _ctx: &dyn Any) -> TransitionResult<Running, Blinking> {
995 Ok(Blinking)
996 }
997 }
998 impl Transition<Idle> for Running {
999 fn change(self, _ctx: &dyn Any) -> TransitionResult<Running, Idle> {
1000 Ok(Idle)
1001 }
1002 }
1003
1004 let start = Idle;
1005 let blinking: Blinking = start.transition();
1006 let running: Running = blinking.transition();
1007 let _: Idle = running.transition();
1008 }
1009
1010 #[test]
1011 fn data_carrying_states() {
1012 #[derive(Debug)]
1013 struct Parsing {
1014 buf: Vec<u8>,
1015 pos: usize,
1016 }
1017 impl State for Parsing {}
1018
1019 #[derive(Debug)]
1020 struct Ready {
1021 buf: Vec<u8>,
1022 }
1023 impl State for Ready {}
1024
1025 impl Transition<Ready> for Parsing {
1026 fn change(self, _ctx: &dyn Any) -> TransitionResult<Parsing, Ready> {
1027 Ok(Ready { buf: self.buf })
1028 }
1029 }
1030 let parsing = Parsing {
1031 buf: vec![1, 2, 3],
1032 pos: 0,
1033 };
1034 assert_eq!(parsing.pos, 0);
1035 let ready: Ready = parsing.transition();
1036 assert_eq!(ready.buf, vec![1, 2, 3]);
1037 }
1038
1039 #[derive(Debug)]
1040 struct Connecting {
1041 should_fail: bool,
1042 }
1043 impl State for Connecting {}
1044
1045 #[derive(Debug)]
1046 struct Connected;
1047 impl State for Connected {}
1048
1049 impl Transition<Connected, MyError, Infallible> for Connecting {
1050 fn change(self, _ctx: &dyn Any) -> TransitionResult<Connecting, Connected, MyError> {
1051 if self.should_fail {
1052 ErrorState::err_origin(MyError::ConnectFailed, self)
1053 } else {
1054 Ok(Connected)
1055 }
1056 }
1057 }
1058
1059 #[test]
1060 fn fallible_change_success() {
1061 let connecting = Connecting { should_fail: false };
1062 let _connected: Connected = connecting.try_transition().unwrap();
1063 }
1064
1065 #[test]
1066 fn fallible_change_failure() {
1067 let connecting = Connecting { should_fail: true };
1068 let result: TransitionResult<Connecting, Connected, MyError> = connecting.try_transition();
1069 assert!(result.is_err());
1070 let enriched = result.unwrap_err();
1071 assert_eq!(enriched.err, MyError::ConnectFailed);
1072 match enriched.at {
1073 FailedAt::Origin(c) => {
1074 assert!(c.should_fail);
1075 }
1076 _ => panic!("Expected FailedAt::Origin"),
1077 }
1078 }
1079
1080 #[test]
1081 fn enter_leave_hooks_called_in_order() {
1082 use core::cell::Cell;
1083 use std::rc::Rc;
1084
1085 #[derive(Debug)]
1086 struct HookedSource {
1087 log: Rc<Cell<u32>>,
1088 left: Rc<Cell<bool>>,
1089 }
1090
1091 impl State for HookedSource {
1092 fn leave(&self, _ctx: &dyn Any) -> Result<(), Infallible> {
1093 self.left.set(true);
1094 self.log.set(self.log.get() + 1);
1095 Ok(())
1096 }
1097 }
1098
1099 #[derive(Debug)]
1100 struct HookedTarget {
1101 log: Rc<Cell<u32>>,
1102 entered: Rc<Cell<bool>>,
1103 }
1104 impl State for HookedTarget {
1105 fn enter(&self, _ctx: &dyn Any) -> Result<(), Infallible> {
1106 self.entered.set(true);
1107 self.log.set(self.log.get() + 1);
1108 Ok(())
1109 }
1110 }
1111
1112 impl Transition<HookedTarget> for HookedSource {
1113 fn change(
1114 self,
1115 _ctx: &dyn Any,
1116 ) -> TransitionResult<HookedSource, HookedTarget, Infallible> {
1117 Ok(HookedTarget {
1118 log: self.log,
1119 entered: Rc::new(Cell::new(false)),
1120 })
1121 }
1122 }
1123
1124 let log = Rc::new(Cell::new(0));
1125 let left = Rc::new(Cell::new(false));
1126 let source = HookedSource {
1127 log: Rc::clone(&log),
1128 left: Rc::clone(&left),
1129 };
1130
1131 let target: HookedTarget = source.transition();
1132
1133 assert!(left.get(), "leave() should have been called on source");
1134 assert!(
1135 target.entered.get(),
1136 "enter() should have been called on target"
1137 );
1138 // leave increments log to 1, then enter increments to 2
1139 assert_eq!(log.get(), 2, "leave should be called before enter");
1140 }
1141
1142 #[derive(Debug)]
1143 struct SourceWithGuard;
1144 impl State<MyError> for SourceWithGuard {}
1145
1146 #[derive(Debug, Default)]
1147 struct TargetDefault;
1148 impl State<MyError> for TargetDefault {}
1149
1150 impl Transition<TargetDefault, MyError> for SourceWithGuard {
1151 fn change(
1152 self,
1153 _ctx: &dyn Any,
1154 ) -> TransitionResult<SourceWithGuard, TargetDefault, MyError> {
1155 Ok(TargetDefault)
1156 }
1157
1158 fn guard(&self, _ctx: &dyn Any) -> Result<(), MyError> {
1159 Err(MyError::GuardRejected)
1160 }
1161 }
1162
1163 #[test]
1164 fn guard_rejects_transition() {
1165 let source = SourceWithGuard;
1166 let result: TransitionResult<SourceWithGuard, TargetDefault, MyError> =
1167 source.try_transition();
1168 assert!(result.is_err());
1169 let enriched = result.unwrap_err();
1170 assert_eq!(enriched.err, MyError::GuardRejected);
1171 match enriched.at {
1172 FailedAt::Origin(_) => {} // source returned intact
1173 _ => panic!("Expected FailedAt::Origin after guard failure"),
1174 }
1175 }
1176
1177 // ── Test 6: Self-transition ──────────────────────────────────────
1178
1179 #[test]
1180 fn self_transition_preserves_data() {
1181 #[derive(Debug, PartialEq)]
1182 struct Counter {
1183 value: u32,
1184 }
1185 impl State for Counter {}
1186
1187 impl Transition<Counter, Infallible> for Counter {
1188 fn change(self, _ctx: &dyn Any) -> TransitionResult<Counter, Counter, Infallible> {
1189 Ok(Counter {
1190 value: self.value + 1,
1191 })
1192 }
1193 }
1194
1195 let counter = Counter { value: 5 };
1196 let counter: Counter = counter.transition();
1197 assert_eq!(counter.value, 6);
1198 }
1199
1200 // ── Test 7: ErrorState carries the correct FailedAt variant ────
1201
1202 #[derive(Debug)]
1203 struct FailChangeNone;
1204 impl State for FailChangeNone {}
1205
1206 #[derive(Debug, Default)]
1207 struct SimpleTarget;
1208 impl State for SimpleTarget {}
1209
1210 impl Transition<SimpleTarget, MyError, Infallible> for FailChangeNone {
1211 fn change(self, _ctx: &dyn Any) -> TransitionResult<FailChangeNone, SimpleTarget, MyError> {
1212 ErrorState::err(MyError::ConnectFailed)
1213 }
1214 }
1215
1216 #[test]
1217 fn failedat_none_on_change_failure() {
1218 let source = FailChangeNone;
1219 let result: TransitionResult<FailChangeNone, SimpleTarget, MyError> =
1220 source.try_transition();
1221 assert!(result.is_err());
1222 let enriched = result.unwrap_err();
1223 match enriched.at {
1224 FailedAt::None => {}
1225 _ => panic!("Expected FailedAt::None"),
1226 }
1227 }
1228
1229 #[derive(Debug)]
1230 struct FailChangeNext;
1231 impl State for FailChangeNext {}
1232
1233 impl Transition<SimpleTarget, MyError, Infallible> for FailChangeNext {
1234 fn change(self, _ctx: &dyn Any) -> TransitionResult<FailChangeNext, SimpleTarget, MyError> {
1235 ErrorState::err_next(MyError::ConnectFailed, SimpleTarget)
1236 }
1237 }
1238
1239 #[test]
1240 fn failedat_next_on_change_failure() {
1241 let source = FailChangeNext;
1242 let result: TransitionResult<FailChangeNext, SimpleTarget, MyError> =
1243 source.try_transition();
1244 assert!(result.is_err());
1245 let enriched = result.unwrap_err();
1246 match enriched.at {
1247 FailedAt::Next(_) => {}
1248 _ => panic!("Expected FailedAt::Next"),
1249 }
1250 }
1251
1252 #[test]
1253 fn failedat_origin_on_guard_failure() {
1254 // Already tested in guard_rejects_transition; verify the enum variant
1255 let source = SourceWithGuard;
1256 let result: TransitionResult<SourceWithGuard, TargetDefault, MyError> =
1257 source.try_transition();
1258 assert!(result.is_err());
1259 let enriched = result.unwrap_err();
1260 match enriched.at {
1261 FailedAt::Origin(_) => {}
1262 _ => panic!("Expected FailedAt::Origin after guard failure"),
1263 }
1264 }
1265
1266 // ── Test 8: Invariant calls ──────────────────────────────────────
1267
1268 use std::cell::Cell;
1269 use std::rc::Rc;
1270
1271 #[derive(Debug)]
1272 struct SourceWithInvariant {
1273 invariant_called: Rc<Cell<bool>>,
1274 }
1275 impl State for SourceWithInvariant {
1276 fn invariant(&self) -> Result<(), Infallible> {
1277 self.invariant_called.set(true);
1278 Ok(())
1279 }
1280 }
1281
1282 #[derive(Debug)]
1283 struct TargetWithInvariant {
1284 invariant_called: Rc<Cell<bool>>,
1285 }
1286 impl State for TargetWithInvariant {
1287 fn invariant(&self) -> Result<(), Infallible> {
1288 self.invariant_called.set(true);
1289 Ok(())
1290 }
1291 }
1292
1293 impl Transition<TargetWithInvariant, Infallible> for SourceWithInvariant {
1294 fn change(
1295 self,
1296 _ctx: &dyn Any,
1297 ) -> Result<
1298 TargetWithInvariant,
1299 ErrorState<Infallible, SourceWithInvariant, TargetWithInvariant>,
1300 > {
1301 Ok(TargetWithInvariant {
1302 invariant_called: Rc::new(Cell::new(false)),
1303 })
1304 }
1305 }
1306
1307 #[test]
1308 fn invariant_called_on_source_before_and_target_after() {
1309 let source_flag = Rc::new(Cell::new(false));
1310 let source = SourceWithInvariant {
1311 invariant_called: Rc::clone(&source_flag),
1312 };
1313
1314 // Before transition, invariant should not have been called yet
1315 assert!(!source_flag.get());
1316
1317 let target: TargetWithInvariant = source.transition();
1318
1319 // After transition, source invariant should have been called
1320 assert!(source_flag.get());
1321 // And target invariant should have been called
1322 assert!(target.invariant_called.get());
1323 }
1324
1325 // ── Test 9: ErrorState as State: error recovery transitions ───────
1326
1327 #[derive(Debug)]
1328 #[allow(dead_code)]
1329 enum WorkError {
1330 TaskFailed,
1331 Invalid,
1332 }
1333
1334 impl StateError for WorkError {}
1335
1336 #[derive(Debug, Default)]
1337 struct IdleWork;
1338 impl State for IdleWork {}
1339
1340 #[derive(Debug)]
1341 struct Working {
1342 should_fail: bool,
1343 }
1344 impl State for Working {}
1345
1346 #[derive(Debug)]
1347 struct Done;
1348 impl State for Done {}
1349
1350 // Normal transition: IdleWork → Working
1351 impl Transition<Working, WorkError, Infallible> for IdleWork {
1352 fn change(self, _ctx: &dyn Any) -> TransitionResult<IdleWork, Working, WorkError> {
1353 Ok(Working { should_fail: false })
1354 }
1355 }
1356
1357 // Fallible transition: Working → Done (may fail)
1358 impl Transition<Done, WorkError, Infallible> for Working {
1359 fn change(self, _ctx: &dyn Any) -> TransitionResult<Working, Done, WorkError> {
1360 if self.should_fail {
1361 ErrorState::err_origin(WorkError::TaskFailed, self)
1362 } else {
1363 Ok(Done)
1364 }
1365 }
1366 }
1367
1368 // Error recovery: ErrorState<WorkError, Working, Done> → IdleWork
1369 impl Transition<IdleWork> for ErrorState<WorkError, Working, Done> {
1370 fn change(self, _ctx: &dyn Any) -> TransitionResult<Self, IdleWork> {
1371 Ok(IdleWork)
1372 }
1373 }
1374
1375 #[test]
1376 fn error_state_is_a_state() {
1377 // Verify ErrorState implements State
1378 let error: ErrorState<WorkError, Working, Done> = ErrorState {
1379 err: WorkError::TaskFailed,
1380 at: FailedAt::None,
1381 };
1382 // State methods work
1383 assert!(error.invariant().is_ok());
1384 assert!(error.leave(&()).is_ok());
1385 assert!(error.enter(&()).is_ok());
1386 }
1387
1388 #[test]
1389 fn error_recovery_happy_path() {
1390 let idle = IdleWork;
1391 let working: Working = idle.try_transition().unwrap();
1392 let done: Done = working.try_transition().unwrap();
1393 let _ = done; // Happy path succeeds
1394 }
1395
1396 #[test]
1397 fn error_recovery_from_failure() {
1398 let idle = IdleWork;
1399 let _working: Working = idle.try_transition().unwrap();
1400
1401 // Manually trigger a failure by creating a Working that should_fail
1402 let faulty = Working { should_fail: true };
1403 let result: TransitionResult<Working, Done, WorkError> = faulty.try_transition();
1404 assert!(result.is_err());
1405
1406 let error_state = result.unwrap_err();
1407 assert!(matches!(error_state.at, FailedAt::Origin(_)));
1408
1409 // Recover: transition from ErrorState back to IdleWork
1410 let recovered_idle: IdleWork = error_state.try_transition().unwrap();
1411
1412 // Now try again successfully
1413 let working2: Working = recovered_idle.try_transition().unwrap();
1414 let done: Done = working2.try_transition().unwrap();
1415 let _ = done;
1416 }
1417}