github.com/MetalBlockchain/metalgo@v1.11.9/vms/platformvm/txs/txheap/heap.go (about)

     1  // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved.
     2  // See the file LICENSE for licensing terms.
     3  
     4  package txheap
     5  
     6  import (
     7  	"github.com/MetalBlockchain/metalgo/ids"
     8  	"github.com/MetalBlockchain/metalgo/utils/heap"
     9  	"github.com/MetalBlockchain/metalgo/vms/platformvm/txs"
    10  )
    11  
    12  type Heap interface {
    13  	Add(tx *txs.Tx)
    14  	Get(txID ids.ID) *txs.Tx
    15  	List() []*txs.Tx
    16  	Remove(txID ids.ID) *txs.Tx
    17  	Peek() *txs.Tx
    18  	RemoveTop() *txs.Tx
    19  	Len() int
    20  }
    21  
    22  type heapTx struct {
    23  	tx  *txs.Tx
    24  	age int
    25  }
    26  
    27  type txHeap struct {
    28  	heap       heap.Map[ids.ID, heapTx]
    29  	currentAge int
    30  }
    31  
    32  func (h *txHeap) Add(tx *txs.Tx) {
    33  	txID := tx.ID()
    34  	if h.heap.Contains(txID) {
    35  		return
    36  	}
    37  	htx := heapTx{
    38  		tx:  tx,
    39  		age: h.currentAge,
    40  	}
    41  	h.currentAge++
    42  	h.heap.Push(txID, htx)
    43  }
    44  
    45  func (h *txHeap) Get(txID ids.ID) *txs.Tx {
    46  	got, _ := h.heap.Get(txID)
    47  	return got.tx
    48  }
    49  
    50  func (h *txHeap) List() []*txs.Tx {
    51  	heapTxs := heap.MapValues(h.heap)
    52  	res := make([]*txs.Tx, 0, len(heapTxs))
    53  	for _, tx := range heapTxs {
    54  		res = append(res, tx.tx)
    55  	}
    56  	return res
    57  }
    58  
    59  func (h *txHeap) Remove(txID ids.ID) *txs.Tx {
    60  	removed, _ := h.heap.Remove(txID)
    61  	return removed.tx
    62  }
    63  
    64  func (h *txHeap) Peek() *txs.Tx {
    65  	_, peeked, _ := h.heap.Peek()
    66  	return peeked.tx
    67  }
    68  
    69  func (h *txHeap) RemoveTop() *txs.Tx {
    70  	_, popped, _ := h.heap.Pop()
    71  	return popped.tx
    72  }
    73  
    74  func (h *txHeap) Len() int {
    75  	return h.heap.Len()
    76  }