rustate 0.3.0

A Rust library for creating and managing state machines, inspired by XState.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
use crate::action::Action;
use crate::transition::Transition;
use crate::{Context, Event, EventTrait};
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;
use std::fmt::{Debug, Display};
use std::hash::Hash;
use uuid::Uuid;

/// Trait defining requirements for a state identifier
pub trait StateTrait:
    Serialize + DeserializeOwned + Clone + Debug + Display + Hash + Eq + Send + Sync + 'static
{
    /// Returns the unique identifier of the state.
    fn id(&self) -> &Self;
}

// Implement StateTrait for String, a common use case for state IDs
impl StateTrait for String {
    fn id(&self) -> &Self {
        self
    }
}

// Implement StateTrait for simple static strings if needed
// impl StateTrait for &'static str {} // Requires DeserializeOwned, tricky for &'static str

/// Represents a type of state
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Hash)]
pub enum StateType {
    /// A normal state
    Normal,
    /// A state with children (compound state)
    Compound,
    /// A parallel state that can be in multiple child states simultaneously
    Parallel,
    /// A final state
    Final,
    /// A history state that remembers the last active state
    History,
    /// A deep history state that remembers the last active substate
    DeepHistory,
}

/// Represents the history mechanism for history states
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Hash)]
pub enum HistoryType {
    /// A shallow history state
    Shallow,
    /// A deep history state
    Deep,
}

/// Represents a state node within the state machine.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(bound(
    serialize = "S: Serialize",
    deserialize = "S: StateTrait + DeserializeOwned + Eq + Hash"
))]
pub struct State<S = String, C = Context, E = Event>
where
    S: StateTrait
        + Serialize
        + DeserializeOwned
        + Clone
        + Debug
        + Display
        + Hash
        + Eq
        + Send
        + Sync
        + 'static,
    C: Send + Sync + 'static + Default + Clone + Debug + Serialize + DeserializeOwned,
    E: EventTrait + Send + Sync + 'static + Eq + Clone + Debug + Serialize + DeserializeOwned,
{
    /// Unique identifier for the state
    pub id: S,
    /// Type of state
    #[serde(rename = "type")]
    pub state_type: StateType,
    /// Optional parent state id
    pub parent: Option<S>,
    /// Child states (for compound and parallel states)
    // Key should be String derived from child state's S::Display
    #[serde(bound(deserialize = "S: StateTrait + Eq + Hash + DeserializeOwned"))]
    pub children: HashMap<String, State<S, C, E>>,
    /// Initial state (for compound states)
    pub initial: Option<S>,
    /// Data associated with this state
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub data: Option<Value>,
    /// Internal unique identifier
    #[serde(default = "Uuid::new_v4")]
    pub(crate) uuid: Uuid,
    /// Optional meta information for the state
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub meta: Option<Value>,
    /// History type for History states
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub history: Option<HistoryType>,
    /// Entry actions - Skip during deserialization
    #[serde(skip, default, skip_serializing_if = "Vec::is_empty")]
    pub entry: Vec<Action<C, E>>,
    /// Exit actions - Skip during deserialization
    #[serde(skip, default, skip_serializing_if = "Vec::is_empty")]
    pub exit: Vec<Action<C, E>>,
    /// Transitions originating from this state - Skip during deserialization
    #[serde(skip, default, skip_serializing_if = "HashMap::is_empty")]
    pub on: HashMap<String, Vec<Transition<S, C, E>>>,
}

impl<S, C, E> State<S, C, E>
where
    S: StateTrait
        + Serialize
        + DeserializeOwned
        + Clone
        + Debug
        + Display
        + Hash
        + Eq
        + Send
        + Sync
        + 'static,
    C: Clone + Default + Send + Sync + Debug + 'static + Serialize + DeserializeOwned,
    E: EventTrait + Send + Sync + 'static + Eq + Clone + Debug + Serialize + DeserializeOwned,
{
    /// Create a new normal state
    pub fn new(id: S) -> Self {
        Self {
            id,
            state_type: StateType::Normal,
            parent: None,
            children: HashMap::new(),
            initial: None,
            data: None,
            uuid: Uuid::new_v4(),
            meta: None,
            history: None,
            entry: Vec::new(),
            exit: Vec::new(),
            on: HashMap::new(),
        }
    }

    /// Create a new compound state
    pub fn new_compound(id: S, initial: S) -> Self {
        Self {
            id,
            state_type: StateType::Compound,
            parent: None,
            children: HashMap::new(),
            initial: Some(initial),
            data: None,
            uuid: Uuid::new_v4(),
            meta: None,
            history: None,
            entry: Vec::new(),
            exit: Vec::new(),
            on: HashMap::new(),
        }
    }

    /// Create a new parallel state
    pub fn new_parallel(id: S) -> Self {
        Self {
            id,
            state_type: StateType::Parallel,
            parent: None,
            children: HashMap::new(),
            initial: None,
            data: None,
            uuid: Uuid::new_v4(),
            meta: None,
            history: None,
            entry: Vec::new(),
            exit: Vec::new(),
            on: HashMap::new(),
        }
    }

    /// Create a new final state
    pub fn new_final(id: S) -> Self {
        Self {
            id,
            state_type: StateType::Final,
            parent: None,
            children: HashMap::new(),
            initial: None,
            data: None,
            uuid: Uuid::new_v4(),
            meta: None,
            history: None,
            entry: Vec::new(),
            exit: Vec::new(),
            on: HashMap::new(),
        }
    }

    /// Create a new history state
    pub fn new_history(id: S, history_type: HistoryType) -> Self {
        Self {
            id,
            state_type: StateType::History,
            parent: None,
            children: HashMap::new(),
            initial: None,
            data: None,
            uuid: Uuid::new_v4(),
            meta: None,
            history: Some(history_type),
            entry: Vec::new(),
            exit: Vec::new(),
            on: HashMap::new(),
        }
    }

    /// Add a child state to this state
    pub fn add_child(&mut self, mut child_state: State<S, C, E>) -> &mut Self {
        child_state.parent = Some(self.id.clone());
        self.children
            .insert(child_state.id.to_string(), child_state);
        self
    }

    /// Add an entry action
    pub fn add_entry(&mut self, action: impl Into<Action<C, E>>) -> &mut Self {
        self.entry.push(action.into());
        self
    }

    /// Add an exit action
    pub fn add_exit(&mut self, action: impl Into<Action<C, E>>) -> &mut Self {
        self.exit.push(action.into());
        self
    }

    /// Add a transition for a specific event
    pub fn add_transition(
        &mut self,
        event: impl Into<String>,
        transition: impl Into<Transition<S, C, E>>,
    ) -> &mut Self {
        self.on
            .entry(event.into())
            .or_default()
            .push(transition.into());
        self
    }

    /// Set the data associated with this state
    pub fn with_data(mut self, data: Value) -> Self {
        self.data = Some(data);
        self
    }

    /// Set the parent state ID
    pub fn with_parent(mut self, parent_id: S) -> Self {
        self.parent = Some(parent_id);
        self
    }

    /// Set the initial child state ID
    pub fn with_initial(mut self, initial_id: S) -> Self {
        self.initial = Some(initial_id);
        self
    }

    /// Set the state meta information
    pub fn with_meta(mut self, meta: Value) -> Self {
        self.meta = Some(meta);
        self
    }

    pub fn id(&self) -> &S {
        &self.id
    }

    pub fn state_type(&self) -> StateType {
        self.state_type.clone()
    }

    pub fn parent(&self) -> Option<&S> {
        self.parent.as_ref()
    }

    pub fn children(&self) -> &HashMap<String, State<S, C, E>> {
        &self.children
    }

    pub fn initial(&self) -> Option<&S> {
        self.initial.as_ref()
    }

    pub fn data(&self) -> Option<&Value> {
        self.data.as_ref()
    }

    pub fn meta(&self) -> Option<&Value> {
        self.meta.as_ref()
    }

    pub fn history(&self) -> Option<HistoryType> {
        self.history.clone()
    }

    pub fn entry_actions(&self) -> &Vec<Action<C, E>> {
        &self.entry
    }

    pub fn exit_actions(&self) -> &Vec<Action<C, E>> {
        &self.exit
    }

    pub fn transitions(&self) -> &HashMap<String, Vec<Transition<S, C, E>>> {
        &self.on
    }

    /// Checks if the state is a final state
    pub fn is_final(&self) -> bool {
        self.state_type == StateType::Final
    }

    /// Checks if the state is an atomic state (no children)
    pub fn is_atomic(&self) -> bool {
        self.state_type == StateType::Normal && self.children.is_empty()
    }

    /// Checks if the state is a compound state
    pub fn is_compound(&self) -> bool {
        self.state_type == StateType::Compound
    }

    /// Checks if the state is a parallel state
    pub fn is_parallel(&self) -> bool {
        self.state_type == StateType::Parallel
    }

    /// Checks if the state is a history state
    pub fn is_history(&self) -> bool {
        matches!(self.state_type, StateType::History | StateType::DeepHistory)
    }
}

/// A collection of states
#[derive(Debug, Default, Clone, Serialize)]
#[serde(bound(serialize = "S: Serialize"))]
pub struct StateCollection<S, C = Context, E = Event>
where
    S: StateTrait
        + Eq
        + Hash
        + Serialize
        + DeserializeOwned
        + Clone
        + Debug
        + Display
        + Send
        + Sync
        + 'static
        + From<String>,
    C: Clone + Default + Send + Sync + Debug + 'static + Serialize + DeserializeOwned,
    E: EventTrait + Send + Sync + 'static + Eq + Clone + Debug + Serialize + DeserializeOwned,
{
    #[serde(bound(deserialize = "S: StateTrait + Eq + Hash + DeserializeOwned"))]
    states: HashMap<String, State<S, C, E>>,
}

impl<S, C, E> StateCollection<S, C, E>
where
    S: StateTrait
        + Eq
        + Hash
        + Serialize
        + DeserializeOwned
        + Clone
        + Debug
        + Display
        + Send
        + Sync
        + 'static
        + From<String>,
    C: Clone + Default + Send + Sync + Debug + 'static + Serialize + DeserializeOwned,
    E: EventTrait + Send + Sync + 'static + Eq + Clone + Debug + Serialize + DeserializeOwned,
{
    /// Creates a new, empty `StateCollection`.
    pub fn new() -> Self {
        Self {
            states: HashMap::new(),
        }
    }

    /// Add a state to the collection
    pub fn add(&mut self, state: State<S, C, E>) -> &mut Self {
        self.states.insert(state.id.to_string(), state);
        self
    }

    /// Get a state by id
    pub fn get(&self, id: &S) -> Option<&State<S, C, E>> {
        self.states.get(&id.to_string())
    }

    /// Get a mutable reference to a state by id
    pub fn get_mut(&mut self, id: &S) -> Option<&mut State<S, C, E>> {
        self.states.get_mut(&id.to_string())
    }

    /// Check if a state exists
    pub fn contains(&self, id: &S) -> bool {
        self.states.contains_key(&id.to_string())
    }

    /// Get all states
    pub fn all(&self) -> impl Iterator<Item = &State<S, C, E>> {
        self.states.values()
    }

    pub fn is_empty(&self) -> bool {
        self.states.is_empty()
    }
}