-
Notifications
You must be signed in to change notification settings - Fork 0
/
shard_lock_map.go
69 lines (58 loc) · 1.12 KB
/
shard_lock_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
/**
* User: [email protected]
* Date: 2023/8/31
* Time: 11:52
*/
package vaedb
import "sync"
const (
maxShardSize = 1024
)
type ShardMap struct {
shards []*Shard
hash IHash
}
type Shard struct {
val map[string]interface{}
mux sync.RWMutex
}
func DefaultShardMap() *ShardMap {
return NewShardMap(&Fnv32Hash{})
}
func NewShardMap(hash IHash) *ShardMap {
s := &ShardMap{
shards: make([]*Shard, maxShardSize),
hash: hash,
}
for i := 0; i < maxShardSize; i++ {
s.shards[i] = &Shard{
val: make(map[string]interface{}),
}
}
return s
}
func (s *ShardMap) get(key string) interface{} {
shard := s.getShard(key)
shard.mux.RLock()
defer shard.mux.RUnlock()
v, ok := shard.val[key]
if ok {
return v
}
return nil
}
func (s *ShardMap) set(key string, value interface{}) {
shard := s.getShard(key)
shard.mux.Lock()
defer shard.mux.Unlock()
shard.val[key] = value
}
func (s *ShardMap) del(key string) {
shard := s.getShard(key)
shard.mux.Lock()
defer shard.mux.Unlock()
delete(shard.val, key)
}
func (s *ShardMap) getShard(key string) *Shard {
return s.shards[s.hash.Hash(key)%uint32(maxShardSize)]
}