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
use std::collections::HashMap;

macro_rules! run_machine {
    ($machine:expr, $state:expr) => {
        $machine.on_enter(&mut $state) &&
        $machine.update(&mut $state)   &&
        $machine.on_exit(&mut $state)
    };
}

pub enum MachineError {
    NotFoundNextState,
    NotFoundStartState
}

type MachineResult = Result<(), MachineError>;

type MachineVal<State> = Box<Machine<State>>;

pub struct StateMachine<State>
    where State : PartialEq + Eq + std::hash::Hash
{
    map: HashMap<State, MachineVal<State>>,
    state: State
}

pub trait Machine<State> {
    fn on_enter(&self, _: &mut State) -> bool {
        true
    }

    fn update(&self, state: &mut State) -> bool;

    fn on_exit(&self, _: &mut State) -> bool {
        true
    }
}

impl <State> StateMachine<State>
    where State : PartialEq + Eq + std::hash::Hash
{
    /// Create new StateMachine and init start state
    /// # Examples
    ///
    /// ```
    /// use StateMachine;
    ///
    /// let mut machine = StateMachine::new(States::Empty)
    /// ```
    #[inline]
    pub fn new(start_state: State) -> Self {
        StateMachine {
            map: HashMap::new(),
            state: start_state
        }
    }

    /// Run state machine loop.
    /// if on_enter, update, or on_exit return false
    /// loop will be stopped
    #[inline]
    pub fn run(&mut self) -> MachineResult {
        match self.map.get(&self.state) {
            Some(ref mut machine) => {
                while run_machine!(machine, self.state) {
                    match self.map.get(&self.state) {
                        Some(ref next_machine) => *machine = next_machine,
                        None => return Err(MachineError::NotFoundNextState)
                    }
                }
            },
            None => return Err(MachineError::NotFoundStartState)
        }
        Ok(())
    }

    /// Run current state, if state can run
    ///
    /// # Examples
    ///
    /// ```
    /// use Machine;
    /// use StateMachine;
    ///
    /// let mut machine = StateMachine::new(States::Empty);
    /// machine.add(States::Empty, Box::new(EmptyImpl));
    /// machine.add(States::Fire, Box::new(FireImpl));
    /// machine.add(States::Stop, Box::new(StopImpl));
    ///
    /// // Run empty state, and switch to next state
    /// machine.next();
    /// ```
    #[inline]
    pub fn next(&mut self) -> bool {
        match self.map.get(&self.state) {
            Some(ref mut machine) => run_machine!(machine, self.state),
            None => false
        }
    }

    /// Add new state implementation to machine
    ///
    /// If the machine did not have this state present, [`None`] is returned.
    ///
    /// If the machine did have this key present, the value is updated, and the old
    /// value is returned. The key is not updated, though; this matters for
    /// types that can be `==` without being identical. See the [module-level
    /// documentation] for more.
    ///
    /// [`None`]: ../../std/option/enum.Option.html#variant.None
    /// [module-level documentation]: index.html#insert-and-complex-keys
    ///
    /// # Examples
    ///
    /// ```
    /// use Machine;
    /// use StateMachine;
    ///
    /// let mut machine = StateMachine::new(States::Empty);
    /// machine.add(States::Fire, Box::new(FireStateImpl));
    ///
    /// assert_eq!(machine.add(States::Fire, Box::new(StopStateImpl)), Some(Box<Machine<States>>));
    /// assert_eq!(machine.add(&States::Block), None);
    /// ```
    #[inline]
    pub fn add(&mut self, state: State, machine: MachineVal<State>) -> Option<MachineVal<State>> {
        self.map.insert(state, machine)
    }

    /// Add new machine
    ///
    /// # Example
    /// ```
    /// let mut mach = StateMachine::new(1);
    ///
    ///    mach
    ///        .add_builder(2, State2)
    ///        .add_builder(3, State3);
    /// ```
    #[inline]
    pub fn add_builder(&mut self, state: State, machine: MachineVal<State>) -> &Self {
        self.add(state, machine);
        self
    }

    /// Remove state from machine, return the machine if the state was
    /// previously in machine
    ///
    /// # Examples
    ///
    /// ```
    /// use Machine;
    /// use StateMachine;
    ///
    /// let mut machine = StateMachine::new(States::Empty);
    /// machine.add(States::Fire, Box::new(FireStateImpl));
    ///
    /// assert_eq!(machine.remove(&States::Fire), Some(Box<Machine<States>>));
    /// assert_eq!(machine.remove(&States::Stop), None);
    /// ```
    #[inline]
    pub fn remove(&mut self, state: &State) -> Option<MachineVal<State>> {
        self.map.remove(state)
    }

    /// Returns true if the machine contains state.
    ///
    /// # Examples
    ///
    /// ```
    /// use Machine;
    /// use StateMachine;
    ///
    /// let mut machine = StateMachine::new(States::Empty);
    /// machine.add(States::Fire, Box::new(FireStateImpl));
    ///
    /// assert_eq!(machine.contain(&States::Fire), true);
    /// assert_eq!(machine.contain(&States::Stop), false);
    /// ```
    #[inline]
    pub fn contain(&self, state: &State) -> bool {
        self.map.contains_key(state)
    }

    /// Returns a reference to the value corresponding to the state.
    ///
    /// # Examples
    ///
    /// ```
    /// use Machine;
    /// use StateMachine;
    ///
    /// let mut machine = StateMachine::new(States::Empty);
    /// machine.add(States::Fire, Box::new(FireStateImpl));
    ///
    /// assert_eq!(machine.contain(&States::Fire), true);
    /// assert_eq!(machine.contain(&States::Stop), false);
    ///
    /// assert_eq!(machine.get(&States::Fire), Some(&Box<Machine<States>>));
    /// assert_eq!(machine.get(&States::Empty), None);
    /// ```
    #[inline]
    pub fn get_machine(&self, state: &State) -> Option<&MachineVal<State>> {
        self.map.get(state)
    }

    /// Return actual state machine state
    /// See full example in test. method 'get'
    ///
    /// # Examples
    ///
    /// ```
    /// use Machine;
    /// use StateMachine;
    ///
    /// let mut machine = StateMachine::new(States::Empty)
    /// machine.add(States::Music, Box::new(MusicImpl));
    /// machine.add(States::Empty, Box::new(EmptyImpl));
    ///
    /// assert_eq!(*machine.get_state(), States::Empty);
    ///
    /// machine.next();
    /// assert_eq!(*machine.get_state(), States::Music);
    /// ```
    #[inline]
    pub fn get_state(&self) -> &State {
        &self.state
    }
}

#[cfg(test)]
mod test {
    use Machine;
    use StateMachine;

    #[derive(Eq, PartialEq, Hash, Debug)]
    enum States {
        Empty,
        Move,
        Music,
        Last
    }

    #[derive(Eq, PartialEq, Debug)] struct Empty;
    #[derive(Eq, PartialEq, Debug)] struct Move;
    #[derive(Eq, PartialEq, Debug)] struct Music;

    impl Machine<States> for Empty {
        fn update(&self, state: &mut States) -> bool {
            println!("Empty state");
            *state = States::Music;
            true
        }
    }

    impl Machine<States> for Music {
        fn on_enter(&self, _: &mut States) -> bool {
            println!("\nOn enter music state");
            true
        }

        fn update(&self, state: &mut States) -> bool {
            println!("Music state");
            *state = States::Move;
            true
        }
    }

    impl Machine<States> for Move {
        fn update(&self, _: &mut States) -> bool {
            println!("\nStop state");
            true
        }

        fn on_exit(&self, _: &mut States) -> bool {
            println!("On exit move state");
            false
        }
    }

    fn create_machine() -> StateMachine<States> {
        let mut state = StateMachine::new(States::Empty);
        state.add(States::Music, Box::new(Music));
        state.add(States::Empty, Box::new(Empty));
        state.add(States::Move, Box::new(Move));
        state
    }

    #[test]
    fn contain() {
        assert_eq!(create_machine().contain(&States::Move), true);

        assert_ne!(create_machine().contain(&States::Last), true);
    }

    #[test]
    fn get() {
        let mut machine = create_machine();
        assert_eq!(*machine.get_state(), States::Empty);

        machine.next();
        assert_eq!(*machine.get_state(), States::Music);

        assert_eq!(create_machine().get_machine(&States::Move).is_some(), true);

        assert_eq!(create_machine().get_machine(&States::Last).is_some(), false);
    }

    #[allow(dead_code)]
    fn example() {
        let mut state = create_machine();


        // Empty state
        state.next();

        // On enter music state
        // Music state
        //
        // Stop state
        // On exit move state
        let _ = state.run();
    }
}