forked from ByteStorage/FlyDB
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathiterator.go
73 lines (60 loc) · 1.37 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
package flydb
import (
"bytes"
"github.com/qishenonly/flydb/index"
)
// Iterator 迭代器
type Iterator struct {
indexIter index.Iterator
db *DB
options IteratorOptions
}
// NewIterator 初始化迭代器
func (db *DB) NewIterator(opt 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()
}
// 根据Prefix 传进来的 key 判断是与迭代器里面的 key 的前缀相等,不相等往后迭代
func (it *Iterator) skipToNext() {
prefixLen := len(it.options.Prefix)
if prefixLen == 0 {
return
}
for ; it.indexIter.Valid(); it.indexIter.Next() {
key := it.indexIter.Key()
if prefixLen <= len(key) && bytes.Compare(it.options.Prefix, key[:prefixLen]) == 0 {
break
}
}
}