// Array-based binary min-heap of (long key, long value) entries. // // Layout: one contiguous native buffer of 16-byte entries {key, value}, // aligned to 128 bytes. Tree position p lives at buffer index p + 1 (1-based // indexing), so the children of buffer index j are 2j and 2j + 1: a sibling // pair always occupies one aligned 32-byte block and never straddles a cache // line, and parent/child arithmetic is a single shift. using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential)] internal struct HeapEntry { public long K; public long V; } public sealed unsafe class Heap { private const int Align = 128; private const int MinCap = 64; // Subtrees with at most about this many nodes are built level by level; // larger ones are built depth-first so each subtree is cache-resident // when its root is sifted. private const int SmallShift = 14; private void* _raw; // pointer returned by the allocator private HeapEntry* _a; // aligned base; entry j (1-based) at _a[j] private int _cnt; // number of entries private int _cap; // max entries storable (indices 1.._cap) public Heap() { Allocate(MinCap); } public Heap(long[] keys, long[] values, int count) { Allocate(count > MinCap ? count : MinCap); HeapEntry* a = _a; fixed (long* pk = keys) fixed (long* pv = values) { for (int i = 0; i < count; i++) { a[i + 1].K = pk[i]; a[i + 1].V = pv[i]; } } _cnt = count; if (count > 1) Build(a, count); } ~Heap() { if (_raw != null) { NativeMemory.Free(_raw); _raw = null; } } public int Count { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return _cnt; } } // ------------------------------------------------------------ memory private void Allocate(int cap) { nuint bytes = (nuint)(cap + 1) * (nuint)sizeof(HeapEntry) + Align; _raw = NativeMemory.Alloc(bytes); _a = (HeapEntry*)(((nuint)_raw + (Align - 1)) & ~(nuint)(Align - 1)); _cap = cap; } [MethodImpl(MethodImplOptions.NoInlining)] private void Grow() { long nc = (long)_cap * 2; if (nc > int.MaxValue - 2) nc = int.MaxValue - 2; int newCap = (int)nc; nuint oldOff = (nuint)_a - (nuint)_raw; nuint bytes = (nuint)(newCap + 1) * (nuint)sizeof(HeapEntry) + Align; void* raw = NativeMemory.Realloc(_raw, bytes); HeapEntry* a = (HeapEntry*)(((nuint)raw + (Align - 1)) & ~(nuint)(Align - 1)); nuint newOff = (nuint)a - (nuint)raw; if (newOff != oldOff) { nuint used = (nuint)(_cnt + 1) * (nuint)sizeof(HeapEntry); Buffer.MemoryCopy((byte*)raw + oldOff, a, used, used); } _raw = raw; _a = a; _cap = newCap; } // ------------------------------------------------------------ order [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool Less(long ak, long av, long bk, long bv) { return (ak < bk) | ((ak == bk) & (av < bv)); } // ------------------------------------------------------------ sifting // Place x into the hole at index h, moving it up towards (but not above) // index top. [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void SiftUp(HeapEntry* a, int h, int top, long xk, long xv) { while (h > top) { int p = h >> 1; HeapEntry* pp = a + p; if (!Less(xk, xv, pp->K, pp->V)) break; a[h] = *pp; h = p; } a[h].K = xk; a[h].V = xv; } // Bottom-up sift-down (Floyd/Wegener): the hole at index h travels down // the path of smaller children to a leaf, then x is sifted up from there // (never above h). n is the last valid index. private static void SiftDownBottomUp(HeapEntry* a, int h, int n, long xk, long xv) { int top = h; int c = h << 1; while (c < n) { HeapEntry* p = a + c; c += Less(p[1].K, p[1].V, p[0].K, p[0].V) ? 1 : 0; a[h] = a[c]; h = c; c = h << 1; } if (c == n) { a[h] = a[c]; h = c; } SiftUp(a, h, top, xk, xv); } // Top-down sift-down from the root with early exit, for an arbitrary new // entry x. n is the last valid index. private static void SiftDownTopDown(HeapEntry* a, int n, long xk, long xv) { int h = 1; int c = 2; while (c < n) { HeapEntry* p = a + c; c += Less(p[1].K, p[1].V, p[0].K, p[0].V) ? 1 : 0; HeapEntry* q = a + c; if (!Less(q->K, q->V, xk, xv)) goto Done; a[h] = *q; h = c; c = h << 1; } if (c == n) { HeapEntry* q = a + c; if (Less(q->K, q->V, xk, xv)) { a[h] = *q; h = c; } } Done: a[h].K = xk; a[h].V = xv; } // ------------------------------------------------------------ build private static void Build(HeapEntry* a, int m) { BuildSubtree(a, 1, m); } // Heapify the subtree rooted at internal index i (2i <= m). private static void BuildSubtree(HeapEntry* a, int i, int m) { int half = m >> 1; if (((long)i << SmallShift) <= m) { // Large subtree: depth-first, children first. int l = i << 1; if (l <= half) BuildSubtree(a, l, m); if (l + 1 <= half) BuildSubtree(a, l + 1, m); HeapEntry* r = a + i; SiftDownBottomUp(a, i, m, r->K, r->V); return; } // Small subtree: level by level from the deepest internal level up. int d = 0; while (((long)i << (d + 1)) <= half) d++; for (; d >= 0; d--) { int lo = i << d; long hiL = ((long)(i + 1) << d) - 1; int hi = hiL < half ? (int)hiL : half; for (int k = hi; k >= lo; k--) { HeapEntry* r = a + k; SiftDownBottomUp(a, k, m, r->K, r->V); } } } // ------------------------------------------------------------ operations public void Push(long key, long value) { int j = _cnt + 1; if (j > _cap) Grow(); _cnt = j; SiftUp(_a, j, 1, key, value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool TryPeek(out long key, out long value) { if (_cnt == 0) { key = 0; value = 0; return false; } HeapEntry* a = _a; key = a[1].K; value = a[1].V; return true; } public bool TryPop(out long key, out long value) { int n = _cnt; if (n == 0) { key = 0; value = 0; return false; } HeapEntry* a = _a; key = a[1].K; value = a[1].V; n--; _cnt = n; if (n > 0) { HeapEntry* last = a + (n + 1); SiftDownBottomUp(a, 1, n, last->K, last->V); } return true; } public bool TryReplace(long key, long value, out long oldKey, out long oldValue) { int n = _cnt; if (n == 0) { Push(key, value); oldKey = 0; oldValue = 0; return false; } HeapEntry* a = _a; oldKey = a[1].K; oldValue = a[1].V; SiftDownTopDown(a, n, key, value); return true; } public void PushPop(long key, long value, out long outKey, out long outValue) { int n = _cnt; HeapEntry* a = _a; if (n == 0 || !Less(a[1].K, a[1].V, key, value)) { outKey = key; outValue = value; return; } outKey = a[1].K; outValue = a[1].V; SiftDownTopDown(a, n, key, value); } public void Slot(int i, out long key, out long value) { HeapEntry* e = _a + (i + 1); key = e->K; value = e->V; } }