-
Notifications
You must be signed in to change notification settings - Fork 5
/
iterator.go
45 lines (37 loc) · 1021 Bytes
/
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
package bptree
// Iterator returns a stateful Iterator for traversing the tree
// in ascending key order.
type Iterator struct {
next *node
i int
}
// Iterator returns a stateful iterator that traverses the tree
// in ascending key order.
func (t *BPTree) Iterator() *Iterator {
return &Iterator{t.leftmost, 0}
}
// HasNext returns true if there is a next element to retrive.
func (it *Iterator) HasNext() bool {
return it.next != nil && it.i < it.next.keyNum
}
// Next returns a key and a value at the current position of the iteration
// and advances the iterator.
// Caution! Next panics if called on the nil element.
func (it *Iterator) Next() ([]byte, []byte) {
if !it.HasNext() {
// to sleep well
panic("there is no next node")
}
key, value := it.next.keys[it.i], it.next.pointers[it.i].asValue()
it.i++
if it.i == it.next.keyNum {
nextPointer := it.next.next()
if nextPointer != nil {
it.next = nextPointer.asNode()
} else {
it.next = nil
}
it.i = 0
}
return key, value
}