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
use std::borrow::Borrow;
pub enum NextState<S,I>{
ChangeState(Executor<S,I>, S),
Continue(S),
End(S)
}
pub type Executor<S,I> = fn(S, I) -> NextState<S,I>;
pub struct StateMachine<S, I> {
next_executor:Option<Executor<S,I>>,
current_state:Option<S>
}
impl<S,I> StateMachine<S,I>{
pub fn process(&mut self, input_val:I){
if let Some(executor) = self.next_executor.take() {
let old_state = self.current_state.take().unwrap();
let next_state = executor(old_state, input_val);
match next_state {
NextState::ChangeState(exec, state) => {
self.next_executor = Some(exec);
self.current_state = Some(state);
}
NextState::Continue(state) => {
self.current_state = Some(state);
}
NextState::End(state) => {
self.next_executor = None;
self.current_state = Some(state);
}
}
}
}
pub fn is_complete(&self) -> bool{
self.next_executor.is_none()
}
pub fn extract_state(self) -> S {
self.current_state.unwrap()
}
pub fn new(exec:Executor<S,I>, state:S) -> StateMachine<S,I>{
StateMachine{next_executor:Some(exec), current_state:Some(state)}
}
}
impl<S,I> Borrow<S> for StateMachine<S, I> {
fn borrow(&self) -> &S {
self.current_state.as_ref().unwrap()
}
}
impl<S:Clone, I> StateMachine<S,I>{
pub fn clone_state(&self) -> S {
self.current_state.clone().unwrap()
}
}
#[test]
fn simple_storage(){
let storer:Executor<Option<isize>, isize> = simple_storage_statefn;
let mut state_machine:StateMachine<Option<isize>, isize> = StateMachine::new(storer, None);
assert!(state_machine.clone_state() == None);
state_machine.process(2);
assert!(state_machine.clone_state() == Some(2));
state_machine.process(0);
assert!(state_machine.is_complete());
state_machine.process(10);
assert!(state_machine.is_complete());
assert!(state_machine.extract_state() == Some(2));
}
#[cfg(test)]
fn simple_storage_statefn(state:Option<isize>, input:isize) -> NextState<Option<isize>, isize> {
if input == 0 {
NextState::End(state)
}else if input < 0 {
NextState::Continue(None)
}else{
NextState::Continue(Some(input))
}
}