/
iterator.go
78 lines (64 loc) · 1.52 KB
/
iterator.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
package engine
import (
"bytes"
"github.com/ByteStorage/FlyDB/config"
"github.com/ByteStorage/FlyDB/engine/index"
)
// Iterator iterator
type Iterator struct {
indexIter index.Iterator
db *DB
options config.IteratorOptions
}
// NewIterator Initializes the iterator
func (db *DB) NewIterator(opt config.IteratorOptions) *Iterator {
indexIter := db.index.Iterator(opt.Reverse)
return &Iterator{
indexIter: indexIter,
db: db,
options: opt,
}
}
func (it *Iterator) Rewind() {
it.indexIter.Rewind()
it.skipToNext()
}
func (it *Iterator) Seek(key []byte) {
it.indexIter.Seek(key)
it.skipToNext()
}
func (it *Iterator) Next() {
it.indexIter.Next()
it.skipToNext()
}
func (it *Iterator) Valid() bool {
return it.indexIter.Valid()
}
func (it *Iterator) Key() []byte {
return it.indexIter.Key()
}
func (it *Iterator) Value() ([]byte, error) {
logRecordPst := it.indexIter.Value()
it.db.lock.RLock()
defer it.db.lock.RUnlock()
return it.db.getValueByPosition(logRecordPst)
}
func (it *Iterator) Close() {
it.indexIter.Close()
}
// According to the key passed by Prefix,
// the key is equal to the key prefix in the iterator.
// If it is not equal, the next iteration is performed
func (it *Iterator) skipToNext() {
prefixLen := len(it.options.Prefix)
if prefixLen == 0 {
return
}
for ; it.indexIter.Valid(); it.indexIter.Next() {
key := it.indexIter.Key()
// Check if the key has the desired prefix
if prefixLen <= len(key) && bytes.Equal(it.options.Prefix, key[:prefixLen]) {
break
}
}
}