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