forked from crypto-org-chain/go-block-stm
-
Notifications
You must be signed in to change notification settings - Fork 1
/
btreeiterator.go
121 lines (101 loc) · 1.99 KB
/
btreeiterator.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
package block_stm
import (
"bytes"
"errors"
"github.com/tidwall/btree"
)
// BTreeIteratorG iterates over btree.
// Implements Iterator.
type BTreeIteratorG[T KeyItem] struct {
iter btree.IterG[T]
start []byte
end []byte
ascending bool
valid bool
}
func NewBTreeIteratorG[T KeyItem](
startItem, endItem T,
iter btree.IterG[T],
ascending bool,
) *BTreeIteratorG[T] {
start := startItem.GetKey()
end := endItem.GetKey()
var valid bool
if ascending {
if start != nil {
valid = iter.Seek(startItem)
} else {
valid = iter.First()
}
} else {
if end != nil {
valid = iter.Seek(endItem)
if !valid {
valid = iter.Last()
} else {
// end is exclusive
valid = iter.Prev()
}
} else {
valid = iter.Last()
}
}
mi := &BTreeIteratorG[T]{
iter: iter,
start: start,
end: end,
ascending: ascending,
valid: valid,
}
if mi.valid {
mi.valid = mi.keyInRange(mi.Key())
}
return mi
}
func (mi *BTreeIteratorG[T]) Domain() (start []byte, end []byte) {
return mi.start, mi.end
}
func (mi *BTreeIteratorG[T]) Close() error {
mi.iter.Release()
return nil
}
func (mi *BTreeIteratorG[T]) Error() error {
if !mi.Valid() {
return errors.New("invalid memIterator")
}
return nil
}
func (mi *BTreeIteratorG[T]) Valid() bool {
return mi.valid
}
func (mi *BTreeIteratorG[T]) Next() {
mi.assertValid()
if mi.ascending {
mi.valid = mi.iter.Next()
} else {
mi.valid = mi.iter.Prev()
}
if mi.valid {
mi.valid = mi.keyInRange(mi.Key())
}
}
func (mi *BTreeIteratorG[T]) keyInRange(key []byte) bool {
if mi.ascending && mi.end != nil && bytes.Compare(key, mi.end) >= 0 {
return false
}
if !mi.ascending && mi.start != nil && bytes.Compare(key, mi.start) < 0 {
return false
}
return true
}
func (mi *BTreeIteratorG[T]) Item() T {
return mi.iter.Item()
}
func (mi *BTreeIteratorG[T]) Key() []byte {
return mi.Item().GetKey()
}
func (mi *BTreeIteratorG[T]) assertValid() {
if err := mi.Error(); err != nil {
panic(err)
}
}