-
Notifications
You must be signed in to change notification settings - Fork 1
/
context_store.go
64 lines (52 loc) · 1.02 KB
/
context_store.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
package hexa
import (
"sync"
)
// Store is actually a concurrency-safe map.
type Store interface {
Get(key string) any
Set(key string, val any)
SetIfNotExist(key string, val func() any) any
}
type atomicStore struct {
lock sync.RWMutex
m map[string]any
}
func (s *atomicStore) Get(key string) any {
s.lock.RLock()
defer s.lock.RUnlock()
return s.m[key]
}
func (s *atomicStore) Set(key string, val any) {
s.lock.Lock()
defer s.lock.Unlock()
if s.m == nil {
s.m = make(map[string]any)
}
s.m[key] = val
}
func (s *atomicStore) SetIfNotExist(key string, vp func() any) any {
s.lock.RLock()
val := s.m[key]
if val != nil {
s.lock.RUnlock()
return val
}
s.lock.RUnlock()
s.lock.Lock()
defer s.lock.Unlock()
val = s.m[key] // check if exists again, maybe when we were changing the locks, someone set the value.
if val != nil {
return val
}
if s.m == nil {
s.m = make(map[string]any)
}
val = vp()
s.m[key] = val
return val
}
func newStore() Store {
return &atomicStore{}
}
var _ Store = &atomicStore{}