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
use core::cmp::Ordering;

use crate::Response;
use crate::StateMachine;
use crate::StateOrSuperstate;

/// An enum that represents the superstates of the state machine.
pub trait Superstate<M>
where
    M: StateMachine,
{
    /// Call the handler for the current superstate.
    fn call_handler(
        &mut self,
        context: &mut <M as StateMachine>::Context,
        event: &<M as StateMachine>::Event,
    ) -> Response<<M as StateMachine>::State>;

    /// Call the entry action for the current superstate.
    fn call_entry_action(&mut self, _object: &mut <M as StateMachine>::Context) {}

    /// Call the exit action for the current superstate.
    fn call_exit_action(&mut self, _object: &mut <M as StateMachine>::Context) {}

    /// Return the superstate of the current superstate, if there is one.
    fn superstate(&mut self) -> Option<<M as StateMachine>::Superstate<'_>>
    where
        Self: Sized,
    {
        None
    }
}

/// Extensions for `Superstate` trait.
pub trait SuperstateExt<M>: Superstate<M>
where
    M: StateMachine,
    Self: Sized,
{
    fn same_state(
        lhs: &<M as StateMachine>::Superstate<'_>,
        rhs: &<M as StateMachine>::Superstate<'_>,
    ) -> bool {
        use core::mem::{discriminant, transmute_copy, Discriminant};

        // Generic associated types are invariant over any lifetime arguments, so the
        // compiler won't allow us to compare them directly. Instead we need to coerce them
        // to have the same lifetime by transmuting them to the same type.

        let lhs: Discriminant<<M as StateMachine>::Superstate<'_>> =
            unsafe { transmute_copy(&discriminant(lhs)) };
        let rhs: Discriminant<<M as StateMachine>::Superstate<'_>> =
            unsafe { transmute_copy(&discriminant(rhs)) };

        lhs == rhs
    }

    /// Get the depth of the current superstate.
    fn depth(&mut self) -> usize {
        match self.superstate() {
            Some(mut superstate) => superstate.depth() + 1,
            None => 1,
        }
    }

    /// Get the depth of the common ancestor of two states.
    fn common_ancestor_depth(
        mut source: <M as StateMachine>::Superstate<'_>,
        mut target: <M as StateMachine>::Superstate<'_>,
    ) -> usize {
        match source.depth().cmp(&target.depth()) {
            Ordering::Equal => match Self::same_state(&source, &target) {
                true => source.depth(),
                false => match (source.superstate(), target.superstate()) {
                    (Some(source), Some(target)) => Self::common_ancestor_depth(source, target),
                    _ => 0,
                },
            },
            Ordering::Greater => match source.superstate() {
                Some(superstate) => Self::common_ancestor_depth(superstate, target),
                None => 0,
            },
            Ordering::Less => match target.superstate() {
                Some(superstate) => Self::common_ancestor_depth(source, superstate),
                None => 0,
            },
        }
    }

    /// Handle the given event in the current superstate.
    fn handle(
        &mut self,
        context: &mut <M as StateMachine>::Context,
        event: &<M as StateMachine>::Event,
    ) -> Response<<M as StateMachine>::State>
    where
        Self: Sized,
    {
        let response = self.call_handler(context, event);

        match response {
            Response::Handled => Response::Handled,
            Response::Super => match self.superstate() {
                Some(mut superstate) => {
                    M::on_dispatch(context, StateOrSuperstate::Superstate(&superstate), event);

                    superstate.handle(context, event)
                }
                None => Response::Super,
            },
            Response::Transition(state) => Response::Transition(state),
        }
    }

    /// Starting from the current superstate, climb a given amount of levels and execute all the
    /// entry actions while going back down to the current superstate.
    fn enter(&mut self, context: &mut <M as StateMachine>::Context, mut levels: usize) {
        match levels {
            0 => (),
            1 => self.call_entry_action(context),
            _ => {
                if let Some(mut superstate) = self.superstate() {
                    levels -= 1;
                    superstate.enter(context, levels);
                }
                self.call_entry_action(context);
            }
        }
    }

    /// Starting from the current superstate, climb a given amount of levels and execute all the
    /// the exit actions while going up to a certain superstate.
    fn exit(&mut self, context: &mut <M as StateMachine>::Context, mut levels: usize) {
        match levels {
            0 => (),
            1 => self.call_exit_action(context),
            _ => {
                self.call_exit_action(context);
                if let Some(mut superstate) = self.superstate() {
                    levels -= 1;
                    superstate.exit(context, levels);
                }
            }
        }
    }
}

/// When no superstates are required, the user can pass the [`()`](unit) type.
impl<M> Superstate<M> for ()
where
    M: StateMachine,
{
    fn call_handler(
        &mut self,
        _context: &mut <M as StateMachine>::Context,
        _event: &<M as StateMachine>::Event,
    ) -> Response<<M as StateMachine>::State> {
        Response::Handled
    }

    fn call_entry_action(&mut self, _object: &mut <M as StateMachine>::Context) {}

    fn call_exit_action(&mut self, _object: &mut <M as StateMachine>::Context) {}

    fn superstate(&mut self) -> Option<<M as StateMachine>::Superstate<'_>>
    where
        Self: Sized,
    {
        None
    }
}

impl<T, M> SuperstateExt<M> for T
where
    T: Superstate<M>,
    M: StateMachine,
{
}