Playground
gnomod.toml
module = "gno.land/p/nym-moultest123/x/daily/heap/v0" gno = "0.9" [addpkg] creator = "g1ml9grtwnpzqn3hre5ve5vjdlmv2srrmpmc0dsv" height = 186405 max_deposit = "5000000ugnot"
heap.gno
// Package heap is a binary min-heap / priority queue over string items with
// integer priorities, as a pure, reusable package.
//
// Go's container/heap makes the caller implement five methods and hands back an
// interface; that indirection buys generality this chain does not need and
// costs gas it does. This is the concrete data structure instead: an implicit
// binary heap in a slice, Push/Pop in O(log n), Peek in O(1).
//
// Ordering is TOTAL and deterministic. Equal priorities are broken by insertion
// sequence, so two heaps fed the same items in the same order always pop the
// same sequence — a heap that reordered ties by allocation address would make a
// Render vary between nodes, which is a consensus bug rather than a cosmetic
// one.
//
// A live demo of this package is at
// [r/moul/x/daily/heapdemo](/r/nym-moultest123/x/daily/heapdemo/v0).
package heap
// MaxItems bounds the heap so gas stays predictable.
const MaxItems = 4096
type item struct {
value string
priority int
seq int // insertion sequence, breaks priority ties
}
// Heap is a binary min-heap: the lowest priority pops first.
type Heap struct {
items []item
next int // monotonic insertion counter
max bool
}
// New returns an empty min-heap (lowest priority pops first).
func New() *Heap { return &Heap{} }
// NewMax returns an empty max-heap (highest priority pops first). Ties are
// still broken by insertion order, oldest first.
func NewMax() *Heap { return &Heap{max: true} }
// Len returns the number of items.
func (h *Heap) Len() int { return len(h.items) }
// IsEmpty reports whether the heap holds nothing.
func (h *Heap) IsEmpty() bool { return len(h.items) == 0 }
// IsMax reports whether this is a max-heap.
func (h *Heap) IsMax() bool { return h.max }
// less reports whether a should pop before b.
func (h *Heap) less(a, b item) bool {
if a.priority != b.priority {
if h.max {
return a.priority > b.priority
}
return a.priority < b.priority
}
// Total order: equal priorities pop oldest-first, in BOTH heap kinds.
return a.seq < b.seq
}
// Push adds value with the given priority. Returns false when the heap is full.
func (h *Heap) Push(value string, priority int) bool {
if len(h.items) >= MaxItems {
return false
}
h.items = append(h.items, item{value: value, priority: priority, seq: h.next})
h.next++
h.up(len(h.items) - 1)
return true
}
// Peek returns the item that would pop next, without removing it.
func (h *Heap) Peek() (value string, priority int, ok bool) {
if len(h.items) == 0 {
return "", 0, false
}
return h.items[0].value, h.items[0].priority, true
}
// Pop removes and returns the next item.
func (h *Heap) Pop() (value string, priority int, ok bool) {
if len(h.items) == 0 {
return "", 0, false
}
top := h.items[0]
last := len(h.items) - 1
h.items[0] = h.items[last]
h.items = h.items[:last]
if len(h.items) > 0 {
h.down(0)
}
return top.value, top.priority, true
}
// Drain pops everything, returning values in pop order. The heap ends empty.
func (h *Heap) Drain() []string {
out := make([]string, 0, len(h.items))
for {
v, _, ok := h.Pop()
if !ok {
return out
}
out = append(out, v)
}
}
// Clone returns an independent copy.
func (h *Heap) Clone() *Heap {
cp := &Heap{items: make([]item, len(h.items)), next: h.next, max: h.max}
copy(cp.items, h.items)
return cp
}
func (h *Heap) up(i int) {
for i > 0 {
parent := (i - 1) / 2
if !h.less(h.items[i], h.items[parent]) {
return
}
h.items[i], h.items[parent] = h.items[parent], h.items[i]
i = parent
}
}
func (h *Heap) down(i int) {
n := len(h.items)
for {
left := 2*i + 1
if left >= n {
return
}
best := left
if right := left + 1; right < n && h.less(h.items[right], h.items[left]) {
best = right
}
if !h.less(h.items[best], h.items[i]) {
return
}
h.items[i], h.items[best] = h.items[best], h.items[i]
i = best
}
}
heap_test.gno
package heap
import (
"strconv"
"testing"
"gno.land/p/nt/uassert/v0"
)
func TestEmpty(t *testing.T) {
h := New()
uassert.Equal(t, 0, h.Len())
uassert.True(t, h.IsEmpty(), "a new heap is empty")
_, _, ok := h.Peek()
uassert.False(t, ok, "peek on empty returns not-ok")
_, _, ok = h.Pop()
uassert.False(t, ok, "pop on empty returns not-ok")
}
func TestMinOrder(t *testing.T) {
h := New()
for _, c := range []struct {
v string
p int
}{{"c", 3}, {"a", 1}, {"d", 4}, {"b", 2}} {
uassert.True(t, h.Push(c.v, c.p), "push should succeed")
}
uassert.Equal(t, 4, h.Len())
v, p, ok := h.Peek()
uassert.True(t, ok)
uassert.Equal(t, "a", v)
uassert.Equal(t, 1, p)
uassert.Equal(t, 4, h.Len(), "peek must not remove")
uassert.Equal(t, "a,b,c,d", join(h.Drain()))
uassert.True(t, h.IsEmpty(), "drain empties the heap")
}
func TestMaxOrder(t *testing.T) {
h := NewMax()
uassert.True(t, h.IsMax(), "NewMax builds a max-heap")
for _, c := range []struct {
v string
p int
}{{"c", 3}, {"a", 1}, {"d", 4}, {"b", 2}} {
h.Push(c.v, c.p)
}
uassert.Equal(t, "d,c,b,a", join(h.Drain()))
}
// TestTiesBreakByInsertionOrder is the determinism guarantee: equal priorities
// pop oldest-first, so the same input always yields the same output.
func TestTiesBreakByInsertionOrder(t *testing.T) {
h := New()
h.Push("first", 5)
h.Push("second", 5)
h.Push("third", 5)
uassert.Equal(t, "first,second,third", join(h.Drain()))
}
// TestTiesBreakOldestFirstInMaxHeap pins that the tiebreak does NOT invert with
// the heap kind — only the priority comparison does.
func TestTiesBreakOldestFirstInMaxHeap(t *testing.T) {
h := NewMax()
h.Push("first", 5)
h.Push("second", 5)
h.Push("third", 5)
uassert.Equal(t, "first,second,third", join(h.Drain()))
}
// TestDeterministicAcrossEqualInput feeds two heaps identically and requires
// identical output — the property a Render depends on.
func TestDeterministicAcrossEqualInput(t *testing.T) {
build := func() *Heap {
h := New()
for i := 0; i < 50; i++ {
h.Push("v"+strconv.Itoa(i), i%7)
}
return h
}
uassert.Equal(t, join(build().Drain()), join(build().Drain()))
}
func TestInterleavedPushPop(t *testing.T) {
h := New()
h.Push("b", 2)
h.Push("d", 4)
v, _, _ := h.Pop()
uassert.Equal(t, "b", v)
h.Push("a", 1)
h.Push("c", 3)
uassert.Equal(t, "a,c,d", join(h.Drain()))
}
func TestNegativeAndZeroPriorities(t *testing.T) {
h := New()
h.Push("zero", 0)
h.Push("neg", -10)
h.Push("pos", 10)
uassert.Equal(t, "neg,zero,pos", join(h.Drain()))
}
func TestDuplicateValues(t *testing.T) {
h := New()
h.Push("same", 2)
h.Push("same", 1)
// Duplicate values are independent entries, ordered by priority.
uassert.Equal(t, 2, h.Len())
uassert.Equal(t, "same,same", join(h.Drain()))
}
func TestClone(t *testing.T) {
h := New()
h.Push("a", 1)
h.Push("b", 2)
cp := h.Clone()
cp.Pop()
uassert.Equal(t, 2, h.Len(), "clone must not share storage")
uassert.Equal(t, 1, cp.Len())
uassert.Equal(t, "a,b", join(h.Drain()))
}
func TestCloneKeepsKind(t *testing.T) {
uassert.True(t, NewMax().Clone().IsMax(), "clone of a max-heap is a max-heap")
uassert.False(t, New().Clone().IsMax(), "clone of a min-heap is a min-heap")
}
func TestMaxItems(t *testing.T) {
h := New()
for i := 0; i < MaxItems; i++ {
uassert.True(t, h.Push("v", i), "should accept up to MaxItems")
}
uassert.Equal(t, MaxItems, h.Len())
uassert.False(t, h.Push("overflow", 0), "a full heap refuses new items")
uassert.Equal(t, MaxItems, h.Len(), "a refused push must not grow the heap")
}
// TestHeapPropertyHolds drains a pseudo-random load and checks the sequence is
// non-decreasing — the invariant, independent of the insertion pattern.
func TestHeapPropertyHolds(t *testing.T) {
h := New()
x := 7
for i := 0; i < 200; i++ {
x = (x*31 + 17) % 101 // deterministic spread, no rand
h.Push("v"+strconv.Itoa(i), x)
}
prev := -1
for {
_, p, ok := h.Pop()
if !ok {
break
}
uassert.True(t, p >= prev, "pop order must be non-decreasing")
prev = p
}
}
func join(ss []string) string {
out := ""
for i, s := range ss {
if i > 0 {
out += ","
}
out += s
}
return out
}