-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmap.go
127 lines (97 loc) · 2.3 KB
/
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
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
package threadsafe
import "sync"
// Map represents a generic map[comparable]any that locks itself on each operation. The underlying map Data is left
// exposed to not block any potential operations that might be needed, but should generally not be touched directly.
type Map[K comparable, V any] struct {
Data map[K]V
lock sync.Mutex
}
func NewMap[K comparable, V any]() *Map[K, V] {
return &Map[K, V]{
Data: make(map[K]V),
}
}
// Get returns the value V at key K. Also returns a boolean representing if the value was found or not.
func (m *Map[K, V]) Get(key K) (V, bool) {
m.lock.Lock()
defer m.lock.Unlock()
v, ok := m.Data[key]
return v, ok
}
// Pull behaves like Get but will also delete the key from the map before returning and unlocking the map. This can be
// useful for singleton operations.
func (m *Map[K, V]) Pull(key K) (V, bool) {
m.lock.Lock()
defer m.lock.Unlock()
v, ok := m.Data[key]
if !ok {
return v, ok
}
m.Delete(key)
return v, ok
}
// Set writes the value V at key K.
func (m *Map[K, V]) Set(key K, value V) {
m.lock.Lock()
defer m.lock.Unlock()
m.Data[key] = value
}
// Delete deletes the key K, if it exists.
func (m *Map[K, V]) Delete(key K) {
m.lock.Lock()
defer m.lock.Unlock()
if _, ok := m.Data[key]; ok {
delete(m.Data, key)
}
}
// Keys returns a slice of K keys.
func (m *Map[K, V]) Keys() []K {
m.lock.Lock()
defer m.lock.Unlock()
keys := make([]K, len(m.Data))
index := 0
for k := range m.Data {
keys[index] = k
index++
}
return keys
}
// Values returns a slice V values.
func (m *Map[K, V]) Values() []V {
m.lock.Lock()
defer m.lock.Unlock()
values := make([]V, len(m.Data))
index := 0
for _, v := range m.Data {
values[index] = v
index++
}
return values
}
// Items returns both the slice of keys and values.
func (m *Map[K, V]) Items() ([]K, []V) {
m.lock.Lock()
defer m.lock.Unlock()
keys := make([]K, len(m.Data))
values := make([]V, len(m.Data))
index := 0
for k, v := range m.Data {
keys[index] = k
values[index] = v
index++
}
return keys, values
}
// Empty deletes all keys in the map.
func (m *Map[K, V]) Empty() {
m.lock.Lock()
defer m.lock.Unlock()
m.Data = nil
m.Data = make(map[K]V)
}
// Len returns the length of the map.
func (m *Map[K, V]) Len() int {
m.lock.Lock()
defer m.lock.Unlock()
return len(m.Data)
}