/
safemap.go
83 lines (71 loc) · 1.43 KB
/
safemap.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
package safemap
import (
"sync"
"github.com/cagnosolutions/safemap/util"
)
var SHARD_COUNT int
type SafeMap []*Shard
type Shard struct {
items map[string]interface{}
sync.RWMutex
}
func NewSafeMap(shardCount int) *SafeMap {
if shardCount == 0 || shardCount%2 != 0 {
shardCount = 16
}
SHARD_COUNT = shardCount
sm := make(SafeMap, SHARD_COUNT)
for i := 0; i < SHARD_COUNT; i++ {
sm[i] = &Shard{
items: make(map[string]interface{}),
}
}
return &sm
}
func (sm *SafeMap) GetShard(key string) *Shard {
bucket := util.Sum32([]byte(key)) % uint32(SHARD_COUNT)
return (*sm)[bucket]
}
func (sm *SafeMap) Set(key string, val interface{}) bool {
shard := sm.GetShard(key)
shard.Lock()
shard.items[key] = val
_, ok := shard.items[key]
shard.Unlock()
return ok
}
func (sm *SafeMap) Get(key string) (interface{}, bool) {
shard := sm.GetShard(key)
shard.RLock()
val, ok := shard.items[key]
shard.RUnlock()
return val, ok
}
func (sm *SafeMap) Del(key string) bool {
var ok bool
if shard := sm.GetShard(key); shard != nil {
shard.Lock()
delete(shard.items, key)
_, ok = shard.items[key]
shard.Unlock()
}
return !ok
}
type EntrySet struct {
Key string
Val interface{}
}
func (sm *SafeMap) Iter() <-chan EntrySet {
ch := make(chan EntrySet)
go func() {
for _, shard := range *sm {
shard.RLock()
for key, val := range shard.items {
ch <- EntrySet{key, val}
}
shard.RUnlock()
}
close(ch)
}()
return ch
}