erigon-pulse/common/etl/heap.go

58 lines
1.1 KiB
Go
Raw Normal View History

package etl
2020-05-26 13:37:25 +00:00
import (
"bytes"
"github.com/ledgerwatch/turbo-geth/common/dbutils"
)
2020-05-26 13:37:25 +00:00
type HeapElem struct {
Key []byte
TimeIdx int
Value []byte
2020-05-26 13:37:25 +00:00
}
type Heap struct {
comparator dbutils.CmpFunc
elems []HeapElem
}
func (h Heap) SetComparator(cmp dbutils.CmpFunc) {
h.comparator = cmp
}
2020-05-26 13:37:25 +00:00
func (h Heap) Len() int {
return len(h.elems)
2020-05-26 13:37:25 +00:00
}
func (h Heap) Less(i, j int) bool {
if h.comparator != nil {
if c := h.comparator(h.elems[i].Key, h.elems[j].Key, h.elems[i].Value, h.elems[j].Value); c != 0 {
return c < 0
}
return h.elems[i].TimeIdx < h.elems[j].TimeIdx
}
if c := bytes.Compare(h.elems[i].Key, h.elems[j].Key); c != 0 {
2020-05-26 13:37:25 +00:00
return c < 0
}
return h.elems[i].TimeIdx < h.elems[j].TimeIdx
2020-05-26 13:37:25 +00:00
}
func (h Heap) Swap(i, j int) {
h.elems[i], h.elems[j] = h.elems[j], h.elems[i]
2020-05-26 13:37:25 +00:00
}
func (h *Heap) Push(x interface{}) {
// Push and Pop use pointer receivers because they modify the slice's length,
// not just its contents.
h.elems = append(h.elems, x.(HeapElem))
2020-05-26 13:37:25 +00:00
}
func (h *Heap) Pop() interface{} {
old := h.elems
2020-05-26 13:37:25 +00:00
n := len(old)
x := old[n-1]
h.elems = old[0 : n-1]
2020-05-26 13:37:25 +00:00
return x
}