/
table.go
81 lines (61 loc) · 1.23 KB
/
table.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
// SPDX-FileCopyrightText: 2023 Steffen Vogel <post@steffenvogel.de>
// SPDX-License-Identifier: Apache-2.0
package table
import "sync"
type Table[K comparable, V any] struct {
kvs map[K]V
mu sync.RWMutex
}
func New[K comparable, V any]() Table[K, V] {
return Table[K, V]{
kvs: map[K]V{},
}
}
func (t *Table[K, V]) Lookup(k K) (V, bool) {
t.mu.RLock()
defer t.mu.RUnlock()
v, ok := t.kvs[k]
return v, ok
}
func (t *Table[K, V]) Insert(k K, v V) {
t.mu.Lock()
defer t.mu.Unlock()
t.kvs[k] = v
}
func (t *Table[K, V]) Remove(k K) {
t.mu.Lock()
defer t.mu.Unlock()
delete(t.kvs, k)
}
// ForEach runs the provided callback for each entry
// of the table while keeping the lock
func (t *Table[K, V]) ForEach(cb func(k K, v V) error) error {
t.mu.Lock()
defer t.mu.Unlock()
for k, v := range t.kvs {
if err := cb(k, v); err != nil {
return err
}
}
return nil
}
func (t *Table[K, V]) Clear() {
t.mu.Lock()
defer t.mu.Unlock()
t.kvs = map[K]V{}
}
func (t *Table[K, V]) Len() int {
t.mu.Lock()
defer t.mu.Unlock()
return len(t.kvs)
}
func (t *Table[K, V]) Empty() bool {
return t.Len() == 0
}
func (t *Table[K, V]) Update(m map[K]V) {
t.mu.Lock()
defer t.mu.Unlock()
for k, v := range m {
t.kvs[k] = v
}
}