-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmap.go
93 lines (78 loc) · 1.58 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
package concurrency_map
import (
"hash/fnv"
"sync"
)
const SharedCount = 1024
type ConcurrentMapShared struct {
items map[string]any
sync.RWMutex
}
type ConcurrentMap []*ConcurrentMapShared
func New() ConcurrentMap {
m := make(ConcurrentMap, SharedCount)
for i := 0; i < SharedCount; i++ {
m[i] = &ConcurrentMapShared{
items: map[string]any{},
}
}
return m
}
func (m ConcurrentMap) getShared(key string) *ConcurrentMapShared {
h := fnv.New64a()
h.Write([]byte(key))
return m[h.Sum64()&(SharedCount-1)]
}
func (m ConcurrentMap) Set(key string, v any) {
shared := m.getShared(key)
shared.Lock()
shared.items[key] = v
shared.Unlock()
}
func (m ConcurrentMap) Get(key string) (any, bool) {
shared := m.getShared(key)
shared.RLock()
v, ok := shared.items[key]
shared.RUnlock()
return v, ok
}
func (m ConcurrentMap) Count() int {
count := 0
for i := 0; i < SharedCount; i++ {
shared := m[i]
shared.RLock()
count += len(shared.items)
shared.RUnlock()
}
return count
}
func (m ConcurrentMap) Delete(key string) {
shared := m.getShared(key)
shared.Lock()
delete(shared.items, key)
shared.Unlock()
}
func (m ConcurrentMap) Keys() []string {
count := m.Count()
ch := make(chan string, count)
go func() {
var wg sync.WaitGroup
wg.Add(SharedCount)
for _, shared := range m {
go func(shared *ConcurrentMapShared) {
shared.RLock()
for key := range shared.items {
ch <- key
}
shared.RUnlock()
wg.Done()
}(shared)
}
close(ch)
}()
keys := make([]string, 0, count)
for k := range ch {
keys = append(keys, k)
}
return keys
}