cosmos-sdk/store/firstlast.go

41 lines
812 B
Go
Raw Normal View History

2017-12-11 23:30:44 -08:00
package store
2017-12-17 18:09:39 -08:00
import (
"bytes"
2018-04-18 21:49:24 -07:00
2017-12-17 18:09:39 -08:00
cmn "github.com/tendermint/tmlibs/common"
)
2017-12-11 23:30:44 -08:00
// Gets the first item.
2017-12-17 18:09:39 -08:00
func First(st KVStore, start, end []byte) (kv cmn.KVPair, ok bool) {
2017-12-11 23:30:44 -08:00
iter := st.Iterator(start, end)
if !iter.Valid() {
return kv, false
}
defer iter.Close()
2017-12-17 18:09:39 -08:00
return cmn.KVPair{iter.Key(), iter.Value()}, true
2017-12-11 23:30:44 -08:00
}
// Gets the last item. `end` is exclusive.
2017-12-17 18:09:39 -08:00
func Last(st KVStore, start, end []byte) (kv cmn.KVPair, ok bool) {
2017-12-11 23:30:44 -08:00
iter := st.ReverseIterator(end, start)
if !iter.Valid() {
if v := st.Get(start); v != nil {
2017-12-17 18:09:39 -08:00
return cmn.KVPair{cp(start), cp(v)}, true
2017-12-11 23:30:44 -08:00
}
2018-04-18 21:49:24 -07:00
return kv, false
2017-12-11 23:30:44 -08:00
}
defer iter.Close()
2017-12-11 23:30:44 -08:00
if bytes.Equal(iter.Key(), end) {
// Skip this one, end is exclusive.
iter.Next()
if !iter.Valid() {
return kv, false
}
}
2017-12-17 18:09:39 -08:00
return cmn.KVPair{iter.Key(), iter.Value()}, true
2017-12-11 23:30:44 -08:00
}