-
Notifications
You must be signed in to change notification settings - Fork 2
/
state.go
69 lines (58 loc) · 1.06 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
package falcon
import (
"encoding/json"
"sync"
)
type State[K comparable, V any] struct {
mu sync.RWMutex
data map[K]V
}
func NewState[K comparable, V any]() *State[K, V] {
return &State[K, V]{
data: make(map[K]V),
}
}
func (s *State[K, V]) Set(k K, v V) {
s.mu.Lock()
defer s.mu.Unlock()
s.data[k] = v
}
func (s *State[K, V]) Get(k K) (V, bool) {
s.mu.RLock()
defer s.mu.RUnlock()
val, ok := s.data[k]
return val, ok
}
func (s *State[K, V]) Delete(k K) {
s.mu.Lock()
defer s.mu.Unlock()
delete(s.data, k)
}
func (s *State[K, V]) Len() int {
s.mu.RLock()
defer s.mu.RUnlock()
return len(s.data)
}
func (s *State[K, V]) ForEach(f func(K, V)) {
s.mu.RLock()
defer s.mu.RUnlock()
for key, val := range s.data {
f(key, val)
}
}
func (s *State[K, V]) Reset() {
s.mu.Lock()
defer s.mu.Unlock()
for k := range s.data {
delete(s.data, k)
}
}
func (s *State[K, V]) MarshalJSON() ([]byte, error) {
s.mu.RLock()
defer s.mu.RUnlock()
return json.Marshal(s.data)
}
func (s *State[K, V]) String() string {
b, _ := s.MarshalJSON()
return string(b)
}