2019-02-01 17:03:09 -08:00
|
|
|
package cachekv
|
2017-12-11 23:30:44 -08:00
|
|
|
|
2017-12-12 22:17:20 -08:00
|
|
|
import (
|
2021-12-12 15:12:37 -08:00
|
|
|
"bytes"
|
|
|
|
|
2019-08-02 06:20:39 -07:00
|
|
|
dbm "github.com/tendermint/tm-db"
|
2020-08-03 12:47:25 -07:00
|
|
|
|
2021-09-10 12:42:56 -07:00
|
|
|
"github.com/cosmos/cosmos-sdk/store/types"
|
2017-12-12 22:17:20 -08:00
|
|
|
)
|
|
|
|
|
2017-12-11 23:30:44 -08:00
|
|
|
// Iterates over iterKVCache items.
|
|
|
|
// if key is nil, means it was deleted.
|
|
|
|
// Implements Iterator.
|
|
|
|
type memIterator struct {
|
2021-09-10 12:42:56 -07:00
|
|
|
types.Iterator
|
2019-05-15 07:42:06 -07:00
|
|
|
|
2021-12-12 15:12:37 -08:00
|
|
|
lastKey []byte
|
2021-09-10 12:42:56 -07:00
|
|
|
deleted map[string]struct{}
|
2017-12-11 23:30:44 -08:00
|
|
|
}
|
|
|
|
|
2021-09-10 12:42:56 -07:00
|
|
|
func newMemIterator(start, end []byte, items *dbm.MemDB, deleted map[string]struct{}, ascending bool) *memIterator {
|
|
|
|
var iter types.Iterator
|
|
|
|
var err error
|
2017-12-11 23:30:44 -08:00
|
|
|
|
2021-09-10 12:42:56 -07:00
|
|
|
if ascending {
|
|
|
|
iter, err = items.Iterator(start, end)
|
|
|
|
} else {
|
|
|
|
iter, err = items.ReverseIterator(start, end)
|
|
|
|
}
|
2017-12-11 23:30:44 -08:00
|
|
|
|
2021-09-10 12:42:56 -07:00
|
|
|
if err != nil {
|
2020-01-16 13:46:51 -08:00
|
|
|
panic(err)
|
2017-12-11 23:30:44 -08:00
|
|
|
}
|
|
|
|
|
2021-09-10 12:42:56 -07:00
|
|
|
return &memIterator{
|
|
|
|
Iterator: iter,
|
2020-04-29 19:36:34 -07:00
|
|
|
|
2021-12-12 15:12:37 -08:00
|
|
|
lastKey: nil,
|
|
|
|
deleted: deleted,
|
2019-05-15 07:42:06 -07:00
|
|
|
}
|
2017-12-11 23:30:44 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
func (mi *memIterator) Value() []byte {
|
2021-09-10 12:42:56 -07:00
|
|
|
key := mi.Iterator.Key()
|
2021-12-12 15:12:37 -08:00
|
|
|
// We need to handle the case where deleted is modified and includes our current key
|
|
|
|
// We handle this by maintaining a lastKey object in the iterator.
|
|
|
|
// If the current key is the same as the last key (and last key is not nil / the start)
|
|
|
|
// then we are calling value on the same thing as last time.
|
|
|
|
// Therefore we don't check the mi.deleted to see if this key is included in there.
|
|
|
|
reCallingOnOldLastKey := (mi.lastKey != nil) && bytes.Equal(key, mi.lastKey)
|
|
|
|
if _, ok := mi.deleted[string(key)]; ok && !reCallingOnOldLastKey {
|
2021-09-10 12:42:56 -07:00
|
|
|
return nil
|
2020-01-16 13:46:51 -08:00
|
|
|
}
|
2021-12-12 15:12:37 -08:00
|
|
|
mi.lastKey = key
|
2021-09-10 12:42:56 -07:00
|
|
|
return mi.Iterator.Value()
|
2020-01-16 13:46:51 -08:00
|
|
|
}
|