-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtransition.go
48 lines (41 loc) · 1.34 KB
/
transition.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
package fsm
// transition is to go from a state to an other
// It will check the current state to ensure that the transition is
// allowed execute the handler and then change the current state to
// a new state
type transition struct {
// from represent the state needed for allowing the transition
from string
// to represente the state of the fsm after the transition
to string
// handler to call if the transition is allowed
handler func()
}
// AddTransition will add to the fsm a new transition.
func (fsm *Fsm) AddTransition(name string, from string, to string, handler func()) error {
if isValideState(fsm.states, from) == false {
return ErrUnknowState
}
if isValideState(fsm.states, to) == false {
return ErrUnknowState
}
fsm.transitions[name] = transition{from, to, handler}
return nil
}
// HandleTransition will check if the transition is possible.
// Check if the current state is the state require, call the handler and
// change the current state to the new state.
func (fsm *Fsm) HandleTransition(name string) (string, error) {
transition, exist := fsm.transitions[name]
if exist == false {
return fsm.current, ErrUnknowTransition
}
fsm.mutex.Lock()
defer fsm.mutex.Unlock()
if transition.from == fsm.current {
transition.handler()
fsm.current = transition.to
return fsm.current, nil
}
return fsm.current, ErrBadState
}