/
synced_map.go
88 lines (77 loc) · 1.78 KB
/
synced_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
package mapdb
import (
"strings"
"sync"
"github.com/loveandpeople-DAG/goHive/byteutils"
)
type syncedKVMap struct {
sync.RWMutex
m map[string][]byte
}
func (s *syncedKVMap) has(key []byte) bool {
s.RLock()
defer s.RUnlock()
_, ok := s.m[string(key)]
return ok
}
func (s *syncedKVMap) get(key []byte) ([]byte, bool) {
s.RLock()
defer s.RUnlock()
value, ok := s.m[string(key)]
if !ok {
return nil, false
}
// always copy the value
return byteutils.ConcatBytes(value), true
}
func (s *syncedKVMap) set(key, value []byte) {
s.Lock()
defer s.Unlock()
// always copy the value
s.m[string(key)] = byteutils.ConcatBytes(value)
}
func (s *syncedKVMap) delete(key []byte) {
s.Lock()
defer s.Unlock()
delete(s.m, string(key))
}
func (s *syncedKVMap) deletePrefix(keyPrefix []byte) {
s.Lock()
defer s.Unlock()
prefix := string(keyPrefix)
for key := range s.m {
if strings.HasPrefix(key, prefix) {
delete(s.m, key)
}
}
}
func (s *syncedKVMap) iterate(realm []byte, keyPrefix []byte, consume func(key, value []byte) bool) {
// take a snapshot of the current elements
s.RLock()
copiedElements := make(map[string][]byte)
prefix := byteutils.ConcatBytesToString(realm, keyPrefix)
for key, value := range s.m {
if strings.HasPrefix(key, prefix) {
copiedElements[key] = byteutils.ConcatBytes(value)
}
}
s.RUnlock()
// iterate through found elements
for key, value := range copiedElements {
if !consume([]byte(key)[len(realm):], value) {
break
}
}
}
func (s *syncedKVMap) iterateKeys(realm []byte, keyPrefix []byte, consume func(key []byte) bool) {
s.RLock()
defer s.RUnlock()
prefix := byteutils.ConcatBytesToString(realm, keyPrefix)
for key := range s.m {
if strings.HasPrefix(key, prefix) {
if !consume([]byte(key)[len(realm):]) {
break
}
}
}
}