This repository has been archived by the owner on Oct 6, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathiterator.go
62 lines (54 loc) · 1.49 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
package db
import (
"github.com/dgraph-io/badger/v3"
"github.com/pkg/errors"
)
var (
ErrIteratorFinished = errors.New("iterator finished")
ReverseKeyIteratorOpts = badger.IteratorOptions{
PrefetchValues: false,
Reverse: true,
}
ReversePrefetchIteratorOpts = badger.IteratorOptions{
Reverse: true,
PrefetchSize: 100,
PrefetchValues: true,
}
PrefetchIteratorOpts = badger.IteratorOptions{
PrefetchSize: 100,
PrefetchValues: true,
}
KeyIteratorOpts = badger.IteratorOptions{
PrefetchValues: false,
Reverse: false,
}
Continue = false
)
type IteratorFilter func(item *badger.Item) (finish bool, err error)
// Iterator calls filter function for every element matching the prefix.
// First return value of the filter function is the finish flag.
func (d *Database) Iterator(prefix []byte, opts badger.IteratorOptions, filter IteratorFilter) error {
return d.View(func(txn *badger.Txn) error {
it := txn.NewIterator(opts)
defer it.Close()
seekPrefix := newSeekPrefix(prefix, opts)
for it.Seek(seekPrefix); it.ValidForPrefix(prefix); it.Next() {
finish, err := filter(it.Item())
if err != nil {
return err
}
if finish {
return nil
}
}
return ErrIteratorFinished
})
}
func newSeekPrefix(prefix []byte, opts badger.IteratorOptions) []byte {
if opts.Reverse {
newPrefix := make([]byte, 0, len(prefix)+1)
newPrefix = append(newPrefix, prefix...)
return append(newPrefix, 0xFF) // Required to loop backwards
}
return prefix
}