-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfsm.go
46 lines (41 loc) · 1.24 KB
/
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
// Package fsm is a library tool for finite state nachine
package fsm
import "sync"
// Fsm is a finitate state machine
// Fsm define the possible transitions, actions, the states possible and the current state
type Fsm struct {
// mutex for handle goroutines access
mutex *sync.RWMutex
// current state of the fsm
current string
// states possible for the fsm
states []string
// transitions possible for the fsm
transitions map[string]transition
// action possible for the fsm
actions map[string]action
}
// isValideState is used to know if a state is part of the fsm possible states
func isValideState(states []string, state string) bool {
for _, val := range states {
if val == state {
return true
}
}
return false
}
// New will initialize all the properties of the fsm.
// Check if the current state is part of the possible states
func New(states []string, current string) (*Fsm, error) {
if isValideState(states, current) == false {
return nil, ErrUnknowState
}
mutex := &sync.RWMutex{}
transitions := make(map[string]transition)
actions := make(map[string]action)
return &Fsm{mutex, current, states, transitions, actions}, nil
}
// GetState return the current state of the fsm
func (Fsm *Fsm) GetState() string {
return Fsm.current
}