github.com/fibonacci-chain/fbc@v0.0.0-20231124064014-c7636198c1e9/libs/cosmos-sdk/store/firstlast.go (about)

     1  package store
     2  
     3  import (
     4  	"bytes"
     5  
     6  	tmkv "github.com/fibonacci-chain/fbc/libs/tendermint/libs/kv"
     7  
     8  	"github.com/fibonacci-chain/fbc/libs/cosmos-sdk/store/types"
     9  )
    10  
    11  // Gets the first item.
    12  func First(st KVStore, start, end []byte) (kv tmkv.Pair, ok bool) {
    13  	iter := st.Iterator(start, end)
    14  	if !iter.Valid() {
    15  		return kv, false
    16  	}
    17  	defer iter.Close()
    18  
    19  	return tmkv.Pair{Key: iter.Key(), Value: iter.Value()}, true
    20  }
    21  
    22  // Gets the last item.  `end` is exclusive.
    23  func Last(st KVStore, start, end []byte) (kv tmkv.Pair, ok bool) {
    24  	iter := st.ReverseIterator(end, start)
    25  	if !iter.Valid() {
    26  		if v := st.Get(start); v != nil {
    27  			return tmkv.Pair{Key: types.Cp(start), Value: types.Cp(v)}, true
    28  		}
    29  		return kv, false
    30  	}
    31  	defer iter.Close()
    32  
    33  	if bytes.Equal(iter.Key(), end) {
    34  		// Skip this one, end is exclusive.
    35  		iter.Next()
    36  		if !iter.Valid() {
    37  			return kv, false
    38  		}
    39  	}
    40  
    41  	return tmkv.Pair{Key: iter.Key(), Value: iter.Value()}, true
    42  }