/
state.go
76 lines (64 loc) · 1.23 KB
/
state.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
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
package state
import (
"fmt"
"strings"
"sync"
)
type State struct {
State map[string]string
RWMutex sync.RWMutex
}
func NewState() *State {
return &State{
State: map[string]string{},
}
}
func (s *State) InitializeSequences(incomingState map[string]string) {
s.RWMutex.Lock()
for stateKey := range incomingState {
if strings.Contains(stateKey, "sequence:") {
s.State[stateKey] = "1"
}
}
s.RWMutex.Unlock()
}
func (s *State) GetState(key string) (string, bool) {
s.RWMutex.RLock()
val, ok := s.State[key]
s.RWMutex.RUnlock()
return val, ok
}
func (s *State) SetState(state map[string]string) {
s.RWMutex.Lock()
s.State = state
s.RWMutex.Unlock()
}
func (s *State) PatchState(toPatch map[string]string) {
s.RWMutex.Lock()
for k, v := range toPatch {
s.State[k] = v
}
s.RWMutex.Unlock()
}
func (s *State) RemoveState(toRemove []string) {
s.RWMutex.Lock()
for _, key := range toRemove {
delete(s.State, key)
}
s.RWMutex.Unlock()
}
func (s *State) GetNewSequenceKey() string {
returnKey := ""
i := 1
s.RWMutex.RLock()
for returnKey == "" {
tempKey := fmt.Sprintf("sequence:%v", i)
if s.State[tempKey] == "" {
returnKey = tempKey
} else {
i = i + 1
}
}
s.RWMutex.RUnlock()
return returnKey
}