-
Notifications
You must be signed in to change notification settings - Fork 174
Expand file tree
/
Copy pathsyncmap.go
More file actions
60 lines (51 loc) · 1.41 KB
/
syncmap.go
File metadata and controls
60 lines (51 loc) · 1.41 KB
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
package maputil
import "github.com/stackrox/rox/pkg/sync"
// SyncMap interface provides methods to access a map container.
type SyncMap[K comparable, V any] interface {
Store(K, V)
Load(K) (V, bool)
Contains(k K) bool
Access(fn func(m *map[K]V))
RAccess(fn func(m map[K]V))
}
type syncMapImpl[K comparable, V any] struct {
data map[K]V
mux sync.RWMutex
}
// NewSyncMap returns a new synchronized map.
func NewSyncMap[K comparable, V any]() SyncMap[K, V] {
return &syncMapImpl[K, V]{data: make(map[K]V)}
}
// Load returns the stored value by key.
func (m *syncMapImpl[K, V]) Load(k K) (V, bool) {
m.mux.RLock()
defer m.mux.RUnlock()
v, ok := m.data[k]
return v, ok
}
// Contains returns true if the map contains the key, false otherwise.
func (m *syncMapImpl[K, V]) Contains(k K) bool {
m.mux.RLock()
defer m.mux.RUnlock()
_, ok := m.data[k]
return ok
}
// Store inserts the value v to the map at the key k, or updates the value if the
// comparison predicate returns true.
func (m *syncMapImpl[K, V]) Store(k K, v V) {
m.mux.Lock()
defer m.mux.Unlock()
m.data[k] = v
}
// Access gives protected read and write access to the internal map.
func (m *syncMapImpl[K, V]) Access(fn func(m *map[K]V)) {
m.mux.Lock()
defer m.mux.Unlock()
fn(&m.data)
}
// RAccess gives protected read access to the internal map.
func (m *syncMapImpl[K, V]) RAccess(fn func(m map[K]V)) {
m.mux.RLock()
defer m.mux.RUnlock()
fn(m.data)
}