-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconcurrentmap.go
More file actions
51 lines (43 loc) · 872 Bytes
/
concurrentmap.go
File metadata and controls
51 lines (43 loc) · 872 Bytes
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
package concurrentmap
import (
"sync"
)
type ConcurrentMap[M ~map[K]V, K comparable, V any] struct {
m M
l sync.RWMutex
}
func Wrap[M ~map[K]V, K comparable, V any](m M) *ConcurrentMap[M, K, V] {
return &ConcurrentMap[M, K, V]{m: m, l: sync.RWMutex{}}
}
func (c *ConcurrentMap[M, K, V]) WithRLock(f func(M) any) any {
c.l.RLock()
defer c.l.RUnlock()
return f(c.m)
}
func (c *ConcurrentMap[M, K, V]) WithLock(f func(f M) any) any {
c.l.Lock()
defer c.l.Unlock()
return f(c.m)
}
func (c *ConcurrentMap[M, K, V]) Get(key K) (V, bool) {
c.l.RLock()
defer c.l.RUnlock()
val, has := c.m[key]
return val, has
}
func (c *ConcurrentMap[M, K, V]) Put(key K, val V) {
c.WithLock(
func(m M) any {
m[key] = val
return nil
},
)
}
func (c *ConcurrentMap[M, K, V]) Delete(key K) {
c.WithLock(
func(m M) any {
delete(m, key)
return nil
},
)
}