-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
Copy pathmemiterator.go
108 lines (83 loc) · 1.8 KB
/
memiterator.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
package cachekv
import (
"container/list"
"errors"
dbm "github.com/tendermint/tm-db"
"github.com/cosmos/cosmos-sdk/types/kv"
)
// Iterates over iterKVCache items.
// if key is nil, means it was deleted.
// Implements Iterator.
type memIterator struct {
start, end []byte
items []*kv.Pair
ascending bool
}
func newMemIterator(start, end []byte, items *list.List, ascending bool) *memIterator {
itemsInDomain := make([]*kv.Pair, 0, items.Len())
var entered bool
for e := items.Front(); e != nil; e = e.Next() {
item := e.Value.(*kv.Pair)
if !dbm.IsKeyInDomain(item.Key, start, end) {
if entered {
break
}
continue
}
itemsInDomain = append(itemsInDomain, item)
entered = true
}
return &memIterator{
start: start,
end: end,
items: itemsInDomain,
ascending: ascending,
}
}
func (mi *memIterator) Domain() ([]byte, []byte) {
return mi.start, mi.end
}
func (mi *memIterator) Valid() bool {
return len(mi.items) > 0
}
func (mi *memIterator) assertValid() {
if err := mi.Error(); err != nil {
panic(err)
}
}
func (mi *memIterator) Next() {
mi.assertValid()
if mi.ascending {
mi.items = mi.items[1:]
} else {
mi.items = mi.items[:len(mi.items)-1]
}
}
func (mi *memIterator) Key() []byte {
mi.assertValid()
if mi.ascending {
return mi.items[0].Key
}
return mi.items[len(mi.items)-1].Key
}
func (mi *memIterator) Value() []byte {
mi.assertValid()
if mi.ascending {
return mi.items[0].Value
}
return mi.items[len(mi.items)-1].Value
}
func (mi *memIterator) Close() error {
mi.start = nil
mi.end = nil
mi.items = nil
return nil
}
// Error returns an error if the memIterator is invalid defined by the Valid
// method.
func (mi *memIterator) Error() error {
if !mi.Valid() {
return errors.New("invalid memIterator")
}
return nil
}