-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcursor.go
98 lines (73 loc) · 1.76 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package tempdb
import (
"cmp"
"errors"
"slices"
)
type pair struct {
key []byte
value []byte
}
type Cursor struct {
bucket *Bucket
keys []string
index int
}
func (c *Cursor) get(index int) ([]byte, []byte) {
if index < 0 || index >= len(c.keys) {
return nil, nil
}
k := c.keys[index]
v := c.bucket.Value[k]
return []byte(k), v
}
func (c *Cursor) First() ([]byte, []byte) {
Logger.Debug("cursor first", "bucket ID", c.bucket.ID)
return c.get(0)
}
func (c *Cursor) Last() ([]byte, []byte) {
Logger.Debug("cursor last", "bucket ID", c.bucket.ID, "index", len(c.keys)-1)
return c.get(len(c.keys) - 1)
}
func (c *Cursor) Next() ([]byte, []byte) {
Logger.Debug("cursor next", "bucket ID", c.bucket.ID, "index", c.index+1)
c.index++
return c.get(c.index)
}
func (c *Cursor) Prev() ([]byte, []byte) {
Logger.Debug("cursor prev", "bucket ID", c.bucket.ID, "index", c.index-1)
return c.get(c.index - 1)
}
func (c *Cursor) Seek(seek []byte) ([]byte, []byte) {
Logger.Debug("cursor seek", "bucket ID", c.bucket.ID, "seek", seek)
for i, k := range c.keys {
// check if the key is >= to seek.
if cmp.Compare(k, string(seek)) >= 0 {
// move to the index.
c.index = i
break
}
}
return c.get(c.index)
}
func (c *Cursor) Delete() error {
Logger.Debug("cursor delete", "bucket ID", c.bucket.ID, "index", c.index)
k, _ := c.get(c.index)
if k == nil {
return errors.New("current index out of range")
}
return c.bucket.Delete(k)
}
func newCursor(bkt *Bucket) *Cursor {
Logger.Debug("new cursor", "bucket ID", bkt.ID, "transaction ID", bkt.tx.ID)
c := &Cursor{
bucket: bkt,
}
// add every key to a slice.
for k, _ := range c.bucket.Value {
c.keys = append(c.keys, k)
}
// sort the keys lexicographically.
slices.Sort(c.keys)
return c
}