Skip to main content

qubit_state_machine/
state_machine_error.rs

1/*******************************************************************************
2 *
3 *    Copyright (c) 2026.
4 *    Haixing Hu, Qubit Co. Ltd.
5 *
6 *    All rights reserved.
7 *
8 ******************************************************************************/
9//! Runtime errors returned by state transitions.
10
11use std::error::Error;
12use std::fmt::{self, Debug, Display, Formatter};
13
14/// Error returned when an event cannot be applied to the current state.
15///
16/// `S` is the state type and `E` is the event type.
17#[derive(Debug, Clone, Copy, Eq, PartialEq)]
18pub enum StateMachineError<S, E> {
19    /// The current state is not registered in the state machine.
20    UnknownState {
21        /// The unregistered current state.
22        state: S,
23    },
24    /// There is no transition for the current state and event pair.
25    UnknownTransition {
26        /// The current source state.
27        source: S,
28        /// The event that was triggered.
29        event: E,
30    },
31    /// CAS retry limits were exhausted before a transition could be installed.
32    CasConflict {
33        /// Number of attempts executed by the CAS executor.
34        attempts: u32,
35    },
36}
37
38impl<S, E> Display for StateMachineError<S, E>
39where
40    S: Debug,
41    E: Debug,
42{
43    /// Formats the transition failure with enough context for diagnostics.
44    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
45        match self {
46            Self::UnknownState { state } => {
47                write!(formatter, "unknown state: {state:?}")
48            }
49            Self::UnknownTransition { source, event } => {
50                write!(formatter, "unknown transition: {source:?} --{event:?}--> ?")
51            }
52            Self::CasConflict { attempts } => {
53                write!(
54                    formatter,
55                    "CAS transition failed after {attempts} attempt(s)"
56                )
57            }
58        }
59    }
60}
61
62impl<S, E> Error for StateMachineError<S, E>
63where
64    S: Debug,
65    E: Debug,
66{
67}