-
Notifications
You must be signed in to change notification settings - Fork 175
/
protected_map.go
66 lines (57 loc) · 1.5 KB
/
protected_map.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
package unittest
import "sync"
// ProtectedMap is a thread-safe map.
type ProtectedMap[K comparable, V any] struct {
mu sync.RWMutex
m map[K]V
}
// NewProtectedMap returns a new ProtectedMap with the given types
func NewProtectedMap[K comparable, V any]() *ProtectedMap[K, V] {
return &ProtectedMap[K, V]{
m: make(map[K]V),
}
}
// Add adds a key-value pair to the map
func (p *ProtectedMap[K, V]) Add(key K, value V) {
p.mu.Lock()
defer p.mu.Unlock()
p.m[key] = value
}
// Remove removes a key-value pair from the map
func (p *ProtectedMap[K, V]) Remove(key K) {
p.mu.Lock()
defer p.mu.Unlock()
delete(p.m, key)
}
// Has returns true if the map contains the given key
func (p *ProtectedMap[K, V]) Has(key K) bool {
p.mu.RLock()
defer p.mu.RUnlock()
_, ok := p.m[key]
return ok
}
// Get returns the value for the given key and a boolean indicating if the key was found
func (p *ProtectedMap[K, V]) Get(key K) (V, bool) {
p.mu.RLock()
defer p.mu.RUnlock()
value, ok := p.m[key]
return value, ok
}
// ForEach iterates over the map and calls the given function for each key-value pair.
// If the function returns an error, the iteration is stopped and the error is returned.
func (p *ProtectedMap[K, V]) ForEach(fn func(k K, v V) error) error {
p.mu.RLock()
defer p.mu.RUnlock()
for k, v := range p.m {
if err := fn(k, v); err != nil {
return err
}
}
return nil
}
// Size returns the size of the map.
func (p *ProtectedMap[K, V]) Size() int {
p.mu.RLock()
defer p.mu.RUnlock()
return len(p.m)
}