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
use crate::{FsmBackend, lib::*};

use crate::FsmResult;

/// The implementation should hold all of the FSM's states as fields.
pub trait FsmStates<TFsm>: FsmStateFactory<TFsm> where TFsm: FsmBackend {
    /// The enum type for all states that's used as the "current state" field in the FSM's backend.
    type StateKind: Clone + Copy + Debug + PartialEq + 'static;
    /// An array of current states for the machine, one for each region.
    type CurrentState: Clone + Copy + Debug + Default + AsRef<[FsmCurrentState<Self::StateKind>]> + AsMut<[FsmCurrentState<Self::StateKind>]> + 'static;
}

/// The current state of the FSM.
#[derive(Copy, Clone, PartialEq)]
pub enum FsmCurrentState<S> where S: Clone + Copy {
    /// The FSM is halted and has to be started using the `start()` method.
    Stopped,
    /// The FSM is in this state.
    State(S)
}

impl<S> FsmCurrentState<S> where S: Clone + Copy {
    pub fn all_stopped(current_states: &[Self]) -> bool {
        current_states.iter().all(|s| match s {
            FsmCurrentState::Stopped => true,
            _ => false
        })
    }
}

impl<S> Debug for FsmCurrentState<S> where S: Debug + Copy {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            FsmCurrentState::Stopped => f.write_str("Fsm::Stopped"),
            FsmCurrentState::State(s) => s.fmt(f)
        }
    }
}

impl<S> Default for FsmCurrentState<S> where S: Clone + Copy {
    fn default() -> Self {
        Self::Stopped
    }
}

/// Create a new state from the shared global context.
pub trait FsmStateFactory<TFsm> where Self: Sized, TFsm: FsmBackend {
    /// Constructor for building this state from the shared global context.
    fn new_state(context: &<TFsm as FsmBackend>::Context) -> FsmResult<Self>;
}

/// The implementation of a simple state factory, where the state supports Default.
impl<TState, TFsm> FsmStateFactory<TFsm> for TState where TState: Default, TFsm: FsmBackend {
    fn new_state(_context: &<TFsm as FsmBackend>::Context) -> FsmResult<Self> {
        Ok(Default::default())
    }
}

/// Retrieve a pair of states as immutable references. Used in state transitions.
pub trait FsmStateTransitionAsRef<T1, T2> {
    fn as_state_transition_ref(&self) -> (&T1, &T2);
}

/// Retrieve a pair of states as mutable references. Used in state transitions.
pub trait FsmStateTransitionAsMut<T1, T2> {
    fn as_state_transition_mut(&mut self) -> (&mut T1, &mut T2);
}