-
Notifications
You must be signed in to change notification settings - Fork 2
/
shard.go
62 lines (52 loc) · 1009 Bytes
/
shard.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
package icache
import "sync"
type shards[T any] [shardsCount]*shard[T]
func (s *shards[T]) Purge() {
for i := 0; i < shardsCount; i++ {
s[i] = &shard[T]{
entries: entries[T]{},
}
}
}
func (s shards[T]) EntriesLen() (l int) {
for _, shard := range s {
l += shard.Len()
}
return
}
type shard[T any] struct {
entries entries[T]
rw sync.RWMutex
}
func (s *shard[T]) Len() (l int) {
s.rw.RLock()
l = len(s.entries)
s.rw.RUnlock()
return
}
func (s *shard[T]) EntryExists(key uint64) (ok bool) {
s.rw.RLock()
_, ok = s.entries[key]
s.rw.RUnlock()
return
}
func (s *shard[T]) GetEntry(key uint64) (ent *entry[T], ok bool) {
s.rw.RLock()
ent, ok = s.entries[key]
s.rw.RUnlock()
return
}
func (s *shard[T]) SetEntry(key uint64, ent *entry[T]) {
if _, ok := s.GetEntry(key); ok {
s.DropEntry(key)
}
s.rw.Lock()
s.entries[key] = ent
s.rw.Unlock()
}
func (s *shard[T]) DropEntry(keys uint64) {
s.rw.Lock()
s.entries[keys] = nil
delete(s.entries, keys)
s.rw.Unlock()
}