-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathkvstore_mock.go
86 lines (75 loc) · 1.56 KB
/
kvstore_mock.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
// +build mock
package terago
import (
"errors"
"fmt"
"sort"
"sync"
)
type KvStore struct {
Name string
Data map[string]string
Mu sync.Mutex
}
func (p KvStore) Close() {
fmt.Println("close mock table: " + p.Name)
}
// discard ttl in mock table
func (p KvStore) Put(key, value string, ttl int) (err error) {
p.Mu.Lock()
p.Data[key] = value
p.Mu.Unlock()
return nil
}
func (p KvStore) PutAsync(key, value string, ttl int) (err error) {
p.Data[key] = value
return nil
}
func (p KvStore) Get(key string) (value string, err error) {
var found bool
value, found = p.Data[key]
if !found {
err = errors.New("NotExist")
}
return
}
func (p KvStore) BatchPut(kvs []KeyValue) (err error) {
for _, kv := range kvs {
p.Data[kv.Key] = kv.Value
}
return nil
}
func (p KvStore) BatchGet(keys []string) (result []KeyValue, err error) {
for _, key := range keys {
value, ok := p.Data[key]
if ok {
result = append(result, KeyValue{Key: key, Value: value})
} else {
result = append(result, KeyValue{Key: key, Err: errors.New("NotFound")})
err = errors.New("NotFound")
}
}
return
}
func (p KvStore) RangeGet(start, end string, maxNum int) (result []KeyValue, err error) {
var keysSort []string
for k, _ := range p.Data {
keysSort = append(keysSort, k)
}
sort.Strings(keysSort)
cnt := 0
for _, k := range keysSort {
if k >= start && k < end {
result = append(result, KeyValue{Key: k, Value: p.Data[k]})
cnt++
if cnt >= maxNum {
break
}
}
}
return
}
func (p KvStore) Delete(key string) (err error) {
delete(p.Data, key)
return nil
}