forked from colinmarc/cdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
iterator.go
65 lines (55 loc) · 1.38 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
package cdb
// Iterator represents a sequential iterator over a CDB database.
type Iterator struct {
db *CDB
pos uint32
endPos uint32
err error
key []byte
value []byte
}
// Iter creates an Iterator that can be used to iterate the database.
func (cdb *CDB) Iter() *Iterator {
return &Iterator{
db: cdb,
pos: uint32(indexSize),
endPos: cdb.index[0].offset,
}
}
// Next reads the next key/value pair and advances the iterator one record.
// It returns false when the scan stops, either by reaching the end of the
// database or an error. After Next returns false, the Err method will return
// any error that occurred while iterating.
func (iter *Iterator) Next() bool {
if iter.pos >= iter.endPos {
return false
}
keyLength, valueLength, err := iter.db.readTuple(iter.pos)
if err != nil {
iter.err = err
return false
}
var buf []byte
buf, err = iter.db.readAt(iter.pos+8, keyLength+valueLength)
if err != nil {
iter.err = err
return false
}
// Update iterator state
iter.key = buf[:keyLength]
iter.value = buf[keyLength:]
iter.pos += 8 + keyLength + valueLength
return true
}
// Key returns the current key.
func (iter *Iterator) Key() []byte {
return iter.key
}
// Value returns the current value.
func (iter *Iterator) Value() []byte {
return iter.value
}
// Err returns the current error.
func (iter *Iterator) Err() error {
return iter.err
}