/
store.go
80 lines (66 loc) · 1.51 KB
/
store.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
package types
import (
"errors"
"github.com/davebryson/menta/storage"
)
// KVStore re-exported for the sdk
type (
Snapshot = storage.TreeReader
Cache = storage.Cache
)
func PrefixedKey(service, key []byte) []byte {
res := make([]byte, len(service)+len(key))
copy(res, service)
copy(res[len(service):], key)
return res
}
type PrefixedKVStore struct {
prefix []byte
store Cache
}
func NewPrefixedKVStore(prefix string, store Cache) PrefixedKVStore {
return PrefixedKVStore{
prefix: []byte(prefix),
store: store,
}
}
func (ps PrefixedKVStore) key(k []byte) []byte {
return PrefixedKey(ps.prefix, k)
}
func (ps PrefixedKVStore) Get(key []byte) ([]byte, error) {
data, err := ps.store.Get(ps.key(key))
if err != nil {
return nil, err
}
return data, nil
}
func (ps PrefixedKVStore) Has(key []byte) bool {
_, err := ps.Get(key)
return err == nil
}
func (ps PrefixedKVStore) Put(key, value []byte) error {
if key == nil {
return errors.New("PrefixKVStore: Key is nil")
}
if value == nil {
return errors.New("PrefixKVStore: Value is nil")
}
ps.store.Put(ps.key(key), value)
return nil
}
func (ps PrefixedKVStore) Remove(key []byte) {
ps.store.Remove(ps.key(key))
}
type PrefixedSnapshot struct {
prefix []byte
store Snapshot
}
func NewPrefixedSnapshot(prefix string, snapshot Snapshot) PrefixedSnapshot {
return PrefixedSnapshot{
prefix: []byte(prefix),
store: snapshot,
}
}
func (ps PrefixedSnapshot) Get(key []byte) ([]byte, error) {
return ps.store.Get(PrefixedKey(ps.prefix, key))
}