-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmaps.go
96 lines (83 loc) · 1.65 KB
/
maps.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package x
import (
"cmp"
"slices"
"sync"
)
// Has returns whether k is present in the map m.
func Has[M ~map[K]V, K comparable, V any](m M, k K) bool {
_, ok := m[k]
return ok
}
func Set[M ~map[K]V, K comparable, V any](m M, k K, v V) bool {
if _, ok := m[k]; ok {
return true
}
m[k] = v
return false
}
func Sort[S ~[]E, E cmp.Ordered](x S) S {
slices.Sort(x)
return x
}
// Keys returns the keys of the map m.
// The keys will be in an indeterminate order.
func Keys[M ~map[K]V, K comparable, V any](m M) []K {
r := make([]K, 0, len(m))
for k := range m {
r = append(r, k)
}
return r
}
// One returns a key and value from a map, which must not be empty.
func One[M ~map[K]V, K comparable, V any](m M) (K, V) {
for k, v := range m {
return k, v
}
panic("empty map")
}
// Values returns the values of the map m.
// The values will be in an indeterminate order.
func Values[M ~map[K]V, K comparable, V any](m M) []V {
if len(m) == 0 {
return nil
}
r := make([]V, 0, len(m))
for _, v := range m {
r = append(r, v)
}
return r
}
type Protected[K comparable, V any] struct {
M map[K]V
Lock sync.RWMutex
o sync.Once
}
func (p *Protected[K, V]) Get(k K) (v V, ok bool) {
p.Lock.RLock()
v, ok = p.M[k]
p.Lock.RUnlock()
return
}
func (p *Protected[K, _]) Has(k K) bool {
p.Lock.RLock()
_, ok := p.M[k]
p.Lock.RUnlock()
return ok
}
func (p *Protected[K, V]) Set(k K, v V) {
p.Lock.Lock()
p.o.Do(func() { p.M = map[K]V{} })
p.M[k] = v
p.Lock.Unlock()
}
func (p *Protected[K, _]) Delete(k K) {
p.Lock.Lock()
delete(p.M, k)
p.Lock.Unlock()
}
func (p *Protected[K, V]) Do(fn func(map[K]V)) {
p.Lock.Lock()
fn(p.M)
p.Lock.Unlock()
}