-
Notifications
You must be signed in to change notification settings - Fork 0
/
cmap.go
69 lines (55 loc) · 1.27 KB
/
cmap.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 cmap
import (
"hash/fnv"
"sync"
)
type ConcurrentMap struct {
buckets []map[string]interface{}
locks []sync.RWMutex
}
func NewConcurrentMap(bucketSize int) *ConcurrentMap {
if bucketSize <= 0 {
panic("illegal param bucketSize<=0")
}
m := &ConcurrentMap{
buckets: make([]map[string]interface{}, bucketSize),
locks: make([]sync.RWMutex, bucketSize),
}
for i := range m.buckets {
m.buckets[i] = make(map[string]interface{})
}
return m
}
func (m *ConcurrentMap) Len() int {
length := 0
for i := range m.locks {
m.locks[i].RLock()
length += len(m.buckets[i])
m.locks[i].RUnlock()
}
return length
}
func (m *ConcurrentMap) Get(key string) interface{} {
slot := m.hash(key) % len(m.buckets)
m.locks[slot].RLock()
value := m.buckets[slot][key]
m.locks[slot].RUnlock()
return value
}
func (m *ConcurrentMap) Set(key string, value interface{}) {
slot := m.hash(key) % len(m.buckets)
m.locks[slot].Lock()
m.buckets[slot][key] = value
m.locks[slot].Unlock()
}
func (m *ConcurrentMap) Delete(key string) {
slot := m.hash(key) % len(m.buckets)
m.locks[slot].Lock()
delete(m.buckets[slot], key)
m.locks[slot].Unlock()
}
func (m *ConcurrentMap) hash(key string) int {
hasher := fnv.New32()
hasher.Write([]byte(key))
return int(hasher.Sum32())
}