forked from influxdata/kapacitor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
storage.go
64 lines (56 loc) · 1.27 KB
/
storage.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
package storage
import "errors"
// Common errors that can be returned
var (
ErrNoKeyExists = errors.New("no key exists")
)
// Common interface for interacting with a simple Key/Value storage
type Interface interface {
// Store a value.
Put(key string, value []byte) error
// Retrieve a value.
Get(key string) (*KeyValue, error)
// Delete a key.
// Deleting a non-existent key is not an error.
Delete(key string) error
// Check if a key exists>
Exists(key string) (bool, error)
// List all values with given prefix.
List(prefix string) ([]*KeyValue, error)
}
type KeyValue struct {
Key string
Value []byte
}
// Return a list of values from a list of KeyValues using an offset/limit bound and a match function.
func DoListFunc(list []*KeyValue, match func(value []byte) bool, offset, limit int) [][]byte {
l := len(list)
upper := offset + limit
if upper > l {
upper = l
}
size := upper - offset
if size <= 0 {
// No more results
return nil
}
matches := make([][]byte, 0, size)
i := 0
for _, kv := range list {
if !match(kv.Value) {
continue
}
// Count matched
i++
// Skip till offset
if i <= offset {
continue
}
matches = append(matches, kv.Value)
// Stop once limit reached
if len(matches) == size {
break
}
}
return matches
}