github.com/fibonacci-chain/fbc@v0.0.0-20231124064014-c7636198c1e9/libs/cosmos-sdk/store/queue/queue.go (about) 1 package store 2 3 // TODO: make it independent from list 4 /* 5 import ( 6 "github.com/fibonacci-chain/fbc/libs/cosmos-sdk/codec" 7 sdk "github.com/fibonacci-chain/fbc/libs/cosmos-sdk/types" 8 9 "github.com/fibonacci-chain/fbc/libs/cosmos-sdk/store/list" 10 ) 11 12 // Key for the top element position in the queue 13 func TopKey() []byte { 14 return []byte{0x02} 15 } 16 17 // Queue is a List wrapper that provides queue-like functions 18 // It panics when the element type cannot be (un/)marshalled by the codec 19 type Queue struct { 20 List list.List 21 } 22 23 // NewQueue constructs new Queue 24 func NewQueue(cdc *codec.Codec, store sdk.KVStore) Queue { 25 return Queue{NewList(cdc, store)} 26 } 27 28 func (m Queue) getTop() (res uint64) { 29 bz := m.List.store.Get(TopKey()) 30 if bz == nil { 31 return 0 32 } 33 34 m.List.cdc.MustUnmarshalBinaryLengthPrefixed(bz, &res) 35 return 36 } 37 38 func (m Queue) setTop(top uint64) { 39 bz := m.List.cdc.MustMarshalBinaryLengthPrefixed(top) 40 m.List.store.Set(TopKey(), bz) 41 } 42 43 // Push() inserts the elements to the rear of the queue 44 func (m Queue) Push(value interface{}) { 45 m.List.Push(value) 46 } 47 48 // Popping/Peeking on an empty queue will cause panic 49 // The user should check IsEmpty() before doing any actions 50 // Peek() returns the element at the front of the queue without removing it 51 func (m Queue) Peek(ptr interface{}) error { 52 top := m.getTop() 53 return m.List.Get(top, ptr) 54 } 55 56 // Pop() returns the element at the front of the queue and removes it 57 func (m Queue) Pop() { 58 top := m.getTop() 59 m.List.Delete(top) 60 m.setTop(top + 1) 61 } 62 63 // IsEmpty() checks if the queue is empty 64 func (m Queue) IsEmpty() bool { 65 top := m.getTop() 66 length := m.List.Len() 67 return top >= length 68 } 69 70 // Flush() removes elements it processed 71 // Return true in the continuation to break 72 // The interface{} is unmarshalled before the continuation is called 73 // Starts from the top(head) of the queue 74 // CONTRACT: Pop() or Push() should not be performed while flushing 75 func (m Queue) Flush(ptr interface{}, fn func() bool) { 76 top := m.getTop() 77 length := m.List.Len() 78 79 var i uint64 80 for i = top; i < length; i++ { 81 err := m.List.Get(i, ptr) 82 if err != nil { 83 // TODO: Handle with #870 84 panic(err) 85 } 86 m.List.Delete(i) 87 if fn() { 88 break 89 } 90 } 91 m.setTop(i) 92 } 93 */