-
Notifications
You must be signed in to change notification settings - Fork 3
/
syncmap.go
73 lines (56 loc) · 1.19 KB
/
syncmap.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
package syncmap
import (
"encoding/json"
"sync"
)
func New[A any]() *SyncMap[A] {
return &SyncMap[A]{data: make(map[string]A)}
}
type SyncMap[A any] struct {
data map[string]A
lock sync.RWMutex
}
func (s *SyncMap[A]) Put(key string, value A) {
s.lock.Lock()
defer s.lock.Unlock()
s.data[key] = value
}
func (s *SyncMap[A]) Get(key string) (A, bool) {
s.lock.RLock()
defer s.lock.RUnlock()
val, ok := s.data[key]
return val, ok
}
func (s *SyncMap[A]) Delete(key string) {
s.lock.Lock()
defer s.lock.Unlock()
delete(s.data, key)
}
func (s *SyncMap[A]) MarshalJSON() ([]byte, error) {
s.lock.RLock()
defer s.lock.RUnlock()
return json.Marshal(s.data)
}
func (s *SyncMap[A]) UnmarshalJSON(data []byte) error {
s.lock.Lock()
defer s.lock.Unlock()
return json.Unmarshal(data, &s.data)
}
func (s *SyncMap[A]) Keys() []string {
s.lock.RLock()
defer s.lock.RUnlock()
result := make([]string, 0, len(s.data))
for key := range s.data {
result = append(result, key)
}
return result
}
func (s *SyncMap[A]) Values() []A {
s.lock.RLock()
defer s.lock.RUnlock()
result := make([]A, 0, len(s.data))
for _, value := range s.data {
result = append(result, value)
}
return result
}