github.com/gnolang/gno@v0.0.0-20240520182011-228e9d0192ce/tm2/pkg/store/firstlast.go (about) 1 package store 2 3 import ( 4 "bytes" 5 6 "github.com/gnolang/gno/tm2/pkg/std" 7 "github.com/gnolang/gno/tm2/pkg/store/types" 8 ) 9 10 // Gets the first item. 11 func First(st Store, start, end []byte) (kv std.KVPair, ok bool) { 12 iter := st.Iterator(start, end) 13 if !iter.Valid() { 14 return kv, false 15 } 16 defer iter.Close() 17 18 return std.KVPair{Key: iter.Key(), Value: iter.Value()}, true 19 } 20 21 // Gets the last item. `end` is exclusive. 22 func Last(st Store, start, end []byte) (kv std.KVPair, ok bool) { 23 iter := st.ReverseIterator(end, start) 24 if !iter.Valid() { 25 if v := st.Get(start); v != nil { 26 return std.KVPair{Key: types.Cp(start), Value: types.Cp(v)}, true 27 } 28 return kv, false 29 } 30 defer iter.Close() 31 32 if bytes.Equal(iter.Key(), end) { 33 // Skip this one, end is exclusive. 34 iter.Next() 35 if !iter.Valid() { 36 return kv, false 37 } 38 } 39 40 return std.KVPair{Key: iter.Key(), Value: iter.Value()}, true 41 }