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
#[derive(Debug, Clone)]
pub struct TranstionNotAllowed;
pub trait State {
fn transition_allowed(self, new_state: &Self) -> bool;
}
pub trait Feature<T: State> {
fn allowed(self, state: &T) -> bool;
}
#[derive(Clone, Copy)]
pub struct StateMachine<T> {
state: T
}
impl<T: State + Copy> StateMachine<T> {
pub fn new(state: T) -> StateMachine<T> {
StateMachine {
state: state
}
}
pub fn feature_allowed<U: Feature<T> + Copy>(self, feature: &U) -> bool {
feature.allowed(&self.state)
}
pub fn set(&mut self, new_state: &T) -> Result<(), TranstionNotAllowed> {
if self.state.transition_allowed(&new_state) {
self.state = *new_state;
Ok(())
} else {
Err(TranstionNotAllowed {})
}
}
}