-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmap.go
102 lines (83 loc) · 1.92 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
package pksafe
import (
"sync"
"golang.org/x/exp/constraints"
)
type alertMapValueFunc[K constraints.Ordered, T any] func() (key K, value T)
type safeMap[K constraints.Ordered, T any] struct {
mutex sync.RWMutex
data map[K]T
alertChan chan alertMapValueFunc[K, T]
}
type Map[K constraints.Ordered, T any] interface {
Get(key K) (value T, exist bool)
Has(key K) (exist bool)
Insert(key K, value T) Map[K, T]
Alert() <-chan alertMapValueFunc[K, T]
Size() (size int)
Delete(key K)
Value() (value map[K]T)
Clear()
}
func NewMap[K constraints.Ordered, T any]() Map[K, T] {
return &safeMap[K, T]{
data: make(map[K]T),
alertChan: make(chan alertMapValueFunc[K, T])}
}
func (m *safeMap[K, T]) Get(key K) (value T, exist bool) {
m.mutex.RLock()
defer m.mutex.RUnlock()
value, exist = m.data[key]
return
}
func (m *safeMap[K, T]) Has(key K) (exist bool) {
_, exist = m.Get(key)
return
}
func (m *safeMap[K, T]) Insert(key K, value T) Map[K, T] {
if len(m.alertChan) > 0 {
<-m.alertChan
}
m.mutex.Lock()
defer m.mutex.Unlock()
m.data[key] = value
m.alertChan <- func() (key K, value T) { return key, value }
return m
}
func (m *safeMap[K, T]) Alert() <-chan alertMapValueFunc[K, T] { return m.alertChan }
func (m *safeMap[K, T]) Size() (size int) {
m.mutex.RLock()
defer m.mutex.RUnlock()
size = len(m.data)
return
}
func (m *safeMap[K, T]) Delete(key K) {
m.mutex.Lock()
defer m.mutex.Unlock()
delete(m.data, key)
}
func (m *safeMap[K, T]) Value() (value map[K]T) {
m.mutex.RLock()
defer m.mutex.RUnlock()
value = make(map[K]T)
for k, v := range m.data {
value[k] = v
}
return
}
func (m *safeMap[K, T]) getKeys() (result []K) {
m.mutex.RLock()
defer m.mutex.RUnlock()
for key := range m.data {
result = append(result, key)
}
return
}
func (m *safeMap[K, T]) Clear() {
keys := m.getKeys()
m.mutex.Lock()
defer m.mutex.Unlock()
for _, key := range keys {
delete(m.data, key)
}
}