forked from influxdata/influxdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cursor.go
80 lines (65 loc) · 1.7 KB
/
cursor.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 kv
import (
"bytes"
"sort"
)
// staticCursor implements the Cursor interface for a slice of
// static key value pairs.
type staticCursor struct {
idx int
pairs []Pair
}
// Pair is a struct for key value pairs.
type Pair struct {
Key []byte
Value []byte
}
// NewStaticCursor returns an instance of a StaticCursor. It
// destructively sorts the provided pairs to be in key ascending order.
func NewStaticCursor(pairs []Pair) Cursor {
sort.Slice(pairs, func(i, j int) bool {
return bytes.Compare(pairs[i].Key, pairs[j].Key) < 0
})
return &staticCursor{
pairs: pairs,
}
}
// Seek searches the slice for the first key with the provided prefix.
func (c *staticCursor) Seek(prefix []byte) ([]byte, []byte) {
// TODO: do binary search for prefix since pairs are ordered.
for i, pair := range c.pairs {
if bytes.HasPrefix(pair.Key, prefix) {
c.idx = i
return pair.Key, pair.Value
}
}
return nil, nil
}
func (c *staticCursor) getValueAtIndex(delta int) ([]byte, []byte) {
idx := c.idx + delta
if idx < 0 {
return nil, nil
}
if idx >= len(c.pairs) {
return nil, nil
}
c.idx = idx
pair := c.pairs[c.idx]
return pair.Key, pair.Value
}
// First retrieves the first element in the cursor.
func (c *staticCursor) First() ([]byte, []byte) {
return c.getValueAtIndex(-c.idx)
}
// Last retrieves the last element in the cursor.
func (c *staticCursor) Last() ([]byte, []byte) {
return c.getValueAtIndex(len(c.pairs) - 1 - c.idx)
}
// Next retrieves the next entry in the cursor.
func (c *staticCursor) Next() ([]byte, []byte) {
return c.getValueAtIndex(1)
}
// Prev retrieves the previous entry in the cursor.
func (c *staticCursor) Prev() ([]byte, []byte) {
return c.getValueAtIndex(-1)
}