-
Notifications
You must be signed in to change notification settings - Fork 0
/
map.go
107 lines (93 loc) · 1.82 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
package concurrent
import (
"encoding/json"
"sync"
)
func NewMap[K comparable, V any](options ...MapOption[K, V]) *Map[K, V] {
m := &Map[K, V]{
data: make(map[K]V),
}
for _, option := range options {
option(m)
}
return m
}
type Map[K comparable, V any] struct {
mux sync.RWMutex
data map[K]V
}
func (slf *Map[K, V]) Set(k K, v V) {
slf.mux.Lock()
defer slf.mux.Unlock()
slf.data[k] = v
}
func (slf *Map[K, V]) Get(k K) (V, bool) {
slf.mux.RLock()
defer slf.mux.RUnlock()
val, ok := slf.data[k]
return val, ok
}
func (slf *Map[K, V]) Delete(k K) {
slf.mux.Lock()
defer slf.mux.Unlock()
delete(slf.data, k)
}
func (slf *Map[K, V]) Exist(key K) bool {
slf.mux.RLock()
defer slf.mux.RUnlock()
_, exist := slf.data[key]
return exist
}
func (slf *Map[K, V]) Len() int {
slf.mux.RLock()
defer slf.mux.RUnlock()
return len(slf.data)
}
func (slf *Map[K, V]) ForEach(f func(K, V)) {
slf.mux.RLock()
defer slf.mux.RUnlock()
for key, val := range slf.data {
f(key, val)
}
}
func (slf *Map[K, V]) Keys() []K {
slf.mux.RLock()
defer slf.mux.RUnlock()
keys := make([]K, 0, len(slf.data))
for key := range slf.data {
keys = append(keys, key)
}
return keys
}
func (slf *Map[K, V]) Values() []V {
slf.mux.RLock()
defer slf.mux.RUnlock()
values := make([]V, 0, len(slf.data))
for _, value := range slf.data {
values = append(values, value)
}
return values
}
func (slf *Map[K, V]) Map() map[K]V {
slf.mux.RLock()
defer slf.mux.RUnlock()
m := make(map[K]V)
for k, v := range slf.data {
m[k] = v
}
return m
}
func (slf *Map[K, V]) MarshalJSON() ([]byte, error) {
m := slf.Map()
return json.Marshal(m)
}
func (slf *Map[K, V]) UnmarshalJSON(bytes []byte) error {
m := make(map[K]V)
slf.mux.Lock()
slf.mux.Unlock()
if err := json.Unmarshal(bytes, &m); err != nil {
return err
}
slf.data = m
return nil
}