-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfsm.go
51 lines (41 loc) · 963 Bytes
/
fsm.go
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
package fsm
import "errors"
type StateMachine interface {
Start()
Transit(Action) error
Current() State
Accepted() bool
}
type stateMachine struct {
StateMachine stateMachineComprehension
CurrentState State
}
func (machine *stateMachine) Start() {
machine.CurrentState = machine.StateMachine.start
}
func (machine *stateMachine) Transit(a Action) error {
s := machine.CurrentState
next, exists := machine.StateMachine.transitions[StateActionTuple{s, a}]
if !exists {
return errors.New("No transition")
}
machine.CurrentState = next
return nil
}
func (machine stateMachine) Current() State {
return machine.CurrentState
}
func (machine stateMachine) Accepted() bool {
for _, accept := range machine.StateMachine.accepts {
if machine.CurrentState == accept {
return true
}
}
return false
}
func New(builder StateMachineBuilder) StateMachine {
return &stateMachine{
StateMachine: builder.Build(),
CurrentState: State{},
}
}