using System; using System.Numerics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; public sealed unsafe class SkipList { private const int MAX_LEVEL = 32; private const int NUM_POOLS = 12; // Offset 0 in _arena is both HEAD (no forward link ever points to HEAD) and NIL. // First 256 bytes (32 units of 8 bytes) are reserved for HEAD: // [0..15] unused // [16..143] HEAD.Next[0..31] (levels 0..27 fit in cache line 0) private const uint HEAD_UNITS = 32u; private const uint INITIAL_CAP_UNITS = 64u; // 512 bytes // Each node in _arena is addressed by a 32-bit offset in 8-byte units (up to 32 GB), // always 8-byte aligned and packed inside 128-byte cache lines without straddling: // [0..7] long Key // [8..15] long Value // [16..16+4*h-1] uint Next[0..h-1] // Height is not stored in nodes; Remove determines it while unlinking. private struct PoolState { public uint FreeHead; public uint LineCur; public uint LineEnd; public uint BlockCur; public uint BlockEnd; public uint BlockLines; } [InlineArray(NUM_POOLS)] private struct PoolArray { private PoolState _e0; } private byte* _arena; private ulong _rngState; private int _height; private int _count; private uint _arenaUsed; private uint _arenaCap; private PoolArray _pools; public SkipList() { _arena = (byte*)NativeMemory.AlignedAlloc((nuint)INITIAL_CAP_UNITS << 3, 128); NativeMemory.Clear(_arena, (nuint)HEAD_UNITS << 3); _arenaUsed = HEAD_UNITS; _arenaCap = INITIAL_CAP_UNITS; _rngState = 0x243F6A8885A308D3UL; _height = 0; _count = 0; } ~SkipList() { byte* a = _arena; if (a != null) { _arena = null; NativeMemory.AlignedFree(a); } } public int Count => _count; public int Height() => _height; public int LevelCount(int level) { if ((uint)level >= (uint)_height) return 0; byte* arena = _arena; nuint lvlOff = (nuint)(16 + (level << 2)); uint node = *(uint*)(arena + lvlOff); int count = 0; while (node != 0) { count++; node = *(uint*)(arena + ((nuint)node << 3) + lvlOff); } return count; } public bool TryGet(long key, out long value) { int lvl = _height - 1; if (lvl < 0) { value = 0; return false; } byte* arena = _arena; byte* currPtr = arena; // HEAD at offset 0 uint stop = 0; // NIL = 0 nuint lvlOff = (nuint)(16 + (lvl << 2)); do { uint next = *(uint*)(currPtr + lvlOff); while (next != stop) { byte* nextPtr = arena + ((nuint)next << 3); long nk = *(long*)nextPtr; if (nk < key) { currPtr = nextPtr; next = *(uint*)(nextPtr + lvlOff); continue; } if (nk == key) { value = *(long*)(nextPtr + 8); return true; } stop = next; break; } lvlOff -= 4; } while (lvlOff >= 16); value = 0; return false; } [SkipLocalsInit] public bool Insert(long key, long value) { uint* update = stackalloc uint[MAX_LEVEL]; byte* arena = _arena; int height = _height; uint curr = 0; // HEAD if (height > 0) { byte* currPtr = arena; uint stop = 0; // NIL int lvl = height - 1; nuint lvlOff = (nuint)(16 + (lvl << 2)); do { uint next = *(uint*)(currPtr + lvlOff); while (next != stop) { byte* nextPtr = arena + ((nuint)next << 3); long nk = *(long*)nextPtr; if (nk < key) { curr = next; currPtr = nextPtr; next = *(uint*)(nextPtr + lvlOff); continue; } if (nk == key) { *(long*)(nextPtr + 8) = value; return false; } stop = next; break; } update[lvl] = curr; lvl--; lvlOff -= 4; } while (lvl >= 0); } int newHeight = RandomHeight(); if (newHeight > height) { for (int i = height; i < newHeight; i++) { update[i] = 0; // HEAD } _height = newHeight; } uint newNode = AllocNode(newHeight); arena = _arena; // reload in case AllocNode grew _arena byte* newPtr = arena + ((nuint)newNode << 3); *(long*)newPtr = key; *(long*)(newPtr + 8) = value; uint* newNext = (uint*)(newPtr + 16); uint* p0 = (uint*)(arena + ((nuint)update[0] << 3) + 16); newNext[0] = *p0; *p0 = newNode; if (newHeight > 1) { for (int i = 1; i < newHeight; i++) { uint* prevNext = (uint*)(arena + ((nuint)update[i] << 3) + 16 + ((nuint)i << 2)); newNext[i] = *prevNext; *prevNext = newNode; } } _count++; return true; } [SkipLocalsInit] public bool Remove(long key) { int height = _height; if (height == 0) return false; uint* update = stackalloc uint[MAX_LEVEL]; byte* arena = _arena; uint curr = 0; // HEAD byte* currPtr = arena; uint stop = 0; // NIL int lvl = height - 1; nuint lvlOff = (nuint)(16 + (lvl << 2)); do { uint next = *(uint*)(currPtr + lvlOff); while (next != stop) { byte* nextPtr = arena + ((nuint)next << 3); long nk = *(long*)nextPtr; if (nk < key) { curr = next; currPtr = nextPtr; next = *(uint*)(nextPtr + lvlOff); continue; } stop = next; break; } update[lvl] = curr; lvl--; lvlOff -= 4; } while (lvl >= 0); if (stop == 0) return false; byte* targetPtr = arena + ((nuint)stop << 3); if (*(long*)targetPtr != key) return false; uint* targetNext = (uint*)(targetPtr + 16); *(uint*)(arena + ((nuint)update[0] << 3) + 16) = targetNext[0]; int nodeHeight = 1; while (nodeHeight < height) { nuint off = (nuint)(16 + (nodeHeight << 2)); uint* prevNext = (uint*)(arena + ((nuint)update[nodeHeight] << 3) + off); if (*prevNext != stop) break; *prevNext = targetNext[nodeHeight]; nodeHeight++; } if (nodeHeight == height) { uint* headNext = (uint*)(arena + 16); while (height > 0 && headNext[height - 1] == 0) { height--; } _height = height; } FreeNode(stop, nodeHeight); _count--; return true; } public int Range(long lo, long hi, long[] outKeys, long[] outVals, int limit) { if (limit <= 0 || lo > hi) return 0; int height = _height; if (height == 0) return 0; byte* arena = _arena; byte* currPtr = arena; // HEAD uint stop = 0; // NIL nuint lvlOff = (nuint)(16 + ((height - 1) << 2)); do { uint next = *(uint*)(currPtr + lvlOff); while (next != stop) { byte* nextPtr = arena + ((nuint)next << 3); long nk = *(long*)nextPtr; if (nk < lo) { currPtr = nextPtr; next = *(uint*)(nextPtr + lvlOff); continue; } if (nk == lo) { stop = next; goto Scan; } stop = next; break; } lvlOff -= 4; } while (lvlOff >= 16); Scan: if (stop == 0) return 0; if ((uint)limit > (uint)outKeys.Length || (uint)limit > (uint)outVals.Length) { ThrowOutOfRange(); } ref long kBase = ref MemoryMarshal.GetArrayDataReference(outKeys); ref long vBase = ref MemoryMarshal.GetArrayDataReference(outVals); int written = 0; uint node = stop; do { byte* nodePtr = arena + ((nuint)node << 3); long k = *(long*)nodePtr; if (k > hi) break; uint nextNode = *(uint*)(nodePtr + 16); long v = *(long*)(nodePtr + 8); Unsafe.Add(ref kBase, written) = k; Unsafe.Add(ref vBase, written) = v; written++; node = nextNode; } while (node != 0 && written < limit); return written; } // Wyrand PRNG -> geometric(p = 1/2) height in [1, MAX_LEVEL]. [MethodImpl(MethodImplOptions.AggressiveInlining)] private int RandomHeight() { unchecked { ulong s = (_rngState += 0xA0761D6478BD642FUL); ulong hi = Math.BigMul(s, s ^ 0xE7037ED1A0B428DBUL, out ulong lo); ulong r = lo ^ hi; return BitOperations.LeadingZeroCount(r | (1UL << (64 - MAX_LEVEL))) + 1; } } // Separate height pools isolate hot upper-level towers from cold height-1 nodes // at both 128-byte cache-line and 16 KB page granularity: // pool 0: h = 1 (24B, 5/line) // pool 1: h = 2 (24B, 5/line) // pool 2: h = 3 (32B, 4/line) // pool 3: h = 4 (32B, 4/line) // pool 4: h = 5 (40B, 3/line) // pool 5: h = 6 (40B, 3/line) // pool 6: h = 7 (64B, 2/line) // pool 7: h = 8 (64B, 2/line) // pool 8: h = 9..10 (64B, 2/line) // pool 9: h = 11..12 (64B, 2/line) // pool 10: h = 13..28 (128B, 1/line) // pool 11: h = 29..32 (256B, 2 lines) [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int HeightToPool(int h) { if (h <= 8) return h - 1; if (h <= 10) return 8; if (h <= 12) return 9; if (h <= 28) return 10; return 11; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static uint PoolSlotUnits(int pool) { if (pool < 6) return (uint)((pool >> 1) + 3); if (pool < 10) return 8u; return pool == 10 ? 16u : 32u; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private uint AllocNode(int height) { int pool = HeightToPool(height); ref PoolState p = ref Unsafe.Add(ref Unsafe.As(ref _pools), pool); uint idx = p.FreeHead; if (idx != 0) { p.FreeHead = *(uint*)(_arena + ((nuint)idx << 3)); return idx; } idx = p.LineCur; if (idx < p.LineEnd) { p.LineCur = idx + PoolSlotUnits(pool); return idx; } return AllocSlow(pool); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void FreeNode(uint idx, int height) { int pool = HeightToPool(height); ref PoolState p = ref Unsafe.Add(ref Unsafe.As(ref _pools), pool); *(uint*)(_arena + ((nuint)idx << 3)) = p.FreeHead; p.FreeHead = idx; } [MethodImpl(MethodImplOptions.NoInlining)] private uint AllocSlow(int pool) { ref PoolState p = ref Unsafe.Add(ref Unsafe.As(ref _pools), pool); uint slotUnits = PoolSlotUnits(pool); uint lineStart = p.BlockCur; if (lineStart >= p.BlockEnd) { uint lines = p.BlockLines; if (lines == 0) { lines = pool == 11 ? 2u : 1u; } uint nextLines = lines << 2; p.BlockLines = nextLines <= 128u ? nextLines : 128u; uint blockUnits = lines << 4; // 128B line = 16 units of 8B uint start = _arenaUsed; uint needed = start + blockUnits; if (needed > _arenaCap) { GrowArena(needed); } _arenaUsed = needed; lineStart = start; p.BlockEnd = needed; if (slotUnits != 3u && slotUnits != 5u) { p.BlockCur = needed; p.LineCur = start + slotUnits; p.LineEnd = needed; return start; } } // 24B (3 units) and 40B (5 units): 15 usable units per 16-unit (128B) cache line. p.BlockCur = lineStart + 16u; p.LineCur = lineStart + slotUnits; p.LineEnd = lineStart + 15u; return lineStart; } [MethodImpl(MethodImplOptions.NoInlining)] private void GrowArena(uint minUnits) { uint newCap = _arenaCap; while (newCap < minUnits) { uint doubled = newCap << 1; newCap = doubled > newCap ? doubled : minUnits; } _arena = (byte*)NativeMemory.AlignedRealloc(_arena, (nuint)newCap << 3, 128); _arenaCap = newCap; } [MethodImpl(MethodImplOptions.NoInlining)] private static void ThrowOutOfRange() { throw new ArgumentOutOfRangeException("limit"); } }