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
39impl<S, E> Display for StateMachineError<S, E>
40where
41 S: Debug,
42 E: Debug,
43{
44 /// Formats the transition failure with enough context for diagnostics.
45 fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
46 match self {
47 Self::UnknownState { state } => {
48 write!(formatter, "unknown state: {state:?}")
49 }
50 Self::UnknownTransition { source, event } => {
51 write!(formatter, "unknown transition: {source:?} --{event:?}--> ?")
52 }
53 Self::CasConflict { attempts } => {
54 write!(
55 formatter,
56 "CAS transition failed after {attempts} attempt(s)"
57 )
58 }
59 }
60 }
61}
62
63impl<S, E> Error for StateMachineError<S, E>
64where
65 S: Debug,
66 E: Debug,
67{
68}