-
Notifications
You must be signed in to change notification settings - Fork 93
/
Copy pathiterator.go
75 lines (65 loc) · 1.75 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
package pogreb
import (
"errors"
"sync"
)
// ErrIterationDone is returned by ItemIterator.Next calls when there are no more items to return.
var ErrIterationDone = errors.New("no more items in iterator")
type item struct {
key []byte
value []byte
}
// ItemIterator is an iterator over DB key-value pairs. It iterates the items in an unspecified order.
type ItemIterator struct {
db *DB
nextBucketIdx uint32
queue []item
mu sync.Mutex
}
// fetchItems adds items to the iterator queue from a bucket located at nextBucketIdx.
func (it *ItemIterator) fetchItems(nextBucketIdx uint32) error {
bit := it.db.index.newBucketIterator(nextBucketIdx)
for {
b, err := bit.next()
if err == ErrIterationDone {
return nil
}
if err != nil {
return err
}
for i := 0; i < slotsPerBucket; i++ {
sl := b.slots[i]
if sl.offset == 0 {
// No more items in the bucket.
break
}
key, value, err := it.db.datalog.readKeyValue(sl)
if err != nil {
return err
}
key = cloneBytes(key)
value = cloneBytes(value)
it.queue = append(it.queue, item{key: key, value: value})
}
}
}
// Next returns the next key-value pair if available, otherwise it returns ErrIterationDone error.
func (it *ItemIterator) Next() ([]byte, []byte, error) {
it.mu.Lock()
defer it.mu.Unlock()
it.db.mu.RLock()
defer it.db.mu.RUnlock()
// The iterator queue is empty and we have more buckets to check.
for len(it.queue) == 0 && it.nextBucketIdx < it.db.index.numBuckets {
if err := it.fetchItems(it.nextBucketIdx); err != nil {
return nil, nil, err
}
it.nextBucketIdx++
}
if len(it.queue) > 0 {
item := it.queue[0]
it.queue = it.queue[1:]
return item.key, item.value, nil
}
return nil, nil, ErrIterationDone
}