-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmemkv.go
109 lines (93 loc) · 1.73 KB
/
memkv.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package mutcask
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"io"
"sync"
)
var _ KVDB = (*memkv)(nil)
func NewMemkv() KVDB {
return &memkv{
m: make(map[string][]byte),
}
}
// apply KVDB using map for test case usage
type memkv struct {
sync.RWMutex
m map[string][]byte
}
func (mkv *memkv) Put(key string, value []byte) error {
mkv.Lock()
defer mkv.Unlock()
mkv.m[key] = clone(value)
return nil
}
func (mkv *memkv) Delete(key string) error {
mkv.Lock()
defer mkv.Unlock()
delete(mkv.m, key)
return nil
}
func (mkv *memkv) Get(key string) ([]byte, error) {
mkv.RLock()
defer mkv.RUnlock()
bs, ok := mkv.m[key]
if ok {
return clone(bs), nil
}
return nil, ErrNotFound
}
func (mkv *memkv) Read(key string, w io.Writer) (int, error) {
mkv.RLock()
defer mkv.RUnlock()
bs, ok := mkv.m[key]
if !ok {
return 0, ErrNotFound
}
wn, err := io.Copy(w, bytes.NewReader(bs))
return int(wn), err
}
func (mkv *memkv) CheckSum(key string) (string, error) {
mkv.RLock()
defer mkv.RUnlock()
bs, ok := mkv.m[key]
if ok {
sum := (sha256.Sum256(bs))
return hex.EncodeToString(sum[:]), nil
}
return "", ErrNotFound
}
func (mkv *memkv) Size(key string) (int, error) {
mkv.RLock()
defer mkv.RUnlock()
bs, ok := mkv.m[key]
if ok {
return len(bs), nil
}
return -1, ErrNotFound
}
func (mkv *memkv) AllKeysChan(ctx context.Context) (chan string, error) {
kc := make(chan string)
go func(ctx context.Context, m *memkv) {
defer close(kc)
for key := range m.m {
select {
case <-ctx.Done():
return
default:
kc <- key
}
}
}(ctx, mkv)
return kc, nil
}
func (mkv *memkv) Close() error {
return nil
}
func clone(src []byte) (cp []byte) {
cp = make([]byte, len(src))
copy(cp, src)
return
}