-
Notifications
You must be signed in to change notification settings - Fork 0
/
map.go
69 lines (55 loc) · 987 Bytes
/
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
package safe
import "sync"
type Map[T any] struct {
mu sync.Mutex
data map[string]T
sample T
}
func (sm *Map[T]) init() {
if sm.data == nil {
sm.data = make(map[string]T)
}
}
func (sm *Map[T]) Set(key string, value T) {
sm.mu.Lock()
defer sm.mu.Unlock()
sm.init()
sm.data[key] = value
sm.sample = value
}
func (sm *Map[T]) Get(key string) (T, bool) {
sm.mu.Lock()
defer sm.mu.Unlock()
sm.init()
value, ok := sm.data[key]
return value, ok
}
func (sm *Map[T]) Sample() T {
return sm.sample
}
func (sm *Map[T]) Count() int {
return len(sm.data)
}
func (sm *Map[T]) Data() map[string]T {
data := map[string]T{}
for k, v := range sm.data {
data[k] = v
}
return data
}
func (sm *Map[T]) Keys() []string {
keys := []string{}
if sm.data != nil {
for key := range sm.data {
keys = append(keys, key)
}
}
return keys
}
func (sm *Map[T]) Merge(values map[string]T) {
if len(values) > 0 {
for k, v := range values {
sm.Set(k, v)
}
}
}