rstm_state/types/
halter.rs

1/*
2    Appellation: halting <module>
3    Contrib: FL03 <jo3mccain@icloud.com>
4*/
5use crate::state::State;
6use crate::traits::{Halt, RawState};
7
8/// [`Halter`] extends the [State] by allowing for an 'imaginary' state that is not actually
9/// part of the machine's state space.
10#[derive(
11    Clone,
12    Copy,
13    Debug,
14    Eq,
15    Hash,
16    Ord,
17    PartialEq,
18    PartialOrd,
19    strum::EnumDiscriminants,
20    strum::EnumIs,
21)]
22#[cfg_attr(
23    feature = "serde",
24    derive(serde::Deserialize, serde::Serialize),
25    serde(rename_all = "camelCase"),
26    strum_discriminants(derive(serde::Deserialize, serde::Serialize))
27)]
28#[strum_discriminants(name(HaltTag), derive(Hash, Ord, PartialOrd))]
29pub enum Halter<Q = usize> {
30    Halt(Q),
31    State(Q),
32}
33
34impl<Q> Halter<Q>
35where
36    Q: RawState,
37{
38    /// Creates a new instance of a [HaltState] with a halted state.
39    pub fn halt(State(state): State<Q>) -> Self {
40        Self::Halt(state)
41    }
42    /// Creates a new instance of a [HaltState] with a continuing state.
43    pub fn state(State(state): State<Q>) -> Self {
44        Self::State(state)
45    }
46
47    pub fn into_state(self) -> State<Q> {
48        match self {
49            Self::State(state) => State(state),
50            Self::Halt(halt) => State(halt),
51        }
52    }
53
54    pub fn as_state(&self) -> State<&Q> {
55        State(self.get())
56    }
57
58    pub fn as_mut_state(&mut self) -> State<&mut Q> {
59        State(self.get_mut())
60    }
61
62    pub fn get(&self) -> &Q {
63        match self {
64            Self::State(inner) => inner,
65            Self::Halt(inner) => inner,
66        }
67    }
68
69    pub fn get_mut(&mut self) -> &mut Q {
70        match self {
71            Self::State(inner) => inner,
72            Self::Halt(inner) => inner,
73        }
74    }
75
76    pub fn set(&mut self, state: Q) -> &mut Self {
77        match self {
78            Self::State(inner) => {
79                *inner = state;
80            }
81            Self::Halt(inner) => {
82                *inner = state;
83            }
84        }
85        self
86    }
87}
88
89impl<Q> Default for Halter<Q>
90where
91    Q: Default,
92{
93    fn default() -> Self {
94        Self::State(Default::default())
95    }
96}
97
98impl<Q> From<State<Q>> for Halter<Q> {
99    fn from(State(state): State<Q>) -> Self {
100        Self::State(state)
101    }
102}
103
104impl<Q> RawState for Halter<Q>
105where
106    Q: RawState,
107{
108    seal!();
109}
110
111impl<Q> Halt for Halter<Q>
112where
113    Q: RawState,
114{
115    seal!();
116
117    fn is_halted(&self) -> bool {
118        matches!(self, Self::Halt(_))
119    }
120}