using System; using System.Numerics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [SkipLocalsInit] public sealed unsafe class RadixTree { // Handle encoding (32-bit): // bits 0..12 (13 bits): 32-byte slot offset within chunk (0..8191, max 256 KB per chunk) // bits 13..31 (19 bits): chunk index into _chunks private const uint NONE = 0xFFFF_FFFFu; private const int OFFSET_BITS = 13; private const uint OFFSET_MASK = (1u << OFFSET_BITS) - 1u; private const nuint MAX_CHUNK_BYTES = 1u << (OFFSET_BITS + 5); // 262,144 bytes (256 KB) // Node kinds stored in Meta bits 0..2: private const byte KIND_LEAF = 0; // 32 B (stride32 = 1), inline label <= 16 B, 0 children private const byte KIND_NODE8 = 1; // 64 B (stride32 = 2), inline label <= 8 B, 1..8 children private const byte KIND_NODE16 = 2; // 128 B (stride32 = 4), inline label <= 32 B, 1..16 children private const byte KIND_NODE48 = 3; // 512 B (stride32 = 16), inline label <= 8 B, 1..48 children private const byte KIND_NODE256 = 4; // 1152B (stride32 = 36), inline label <= 80 B, 1..256 children private const byte KIND_MASK = 0x07; // Meta flags: private const byte EXT_LABEL = 0x40; private const byte HAS_VALUE = 0x80; // Node layouts (all start with 16-byte NodeHeader, inline label / ext ptr at offset 16): // Leaf (32B): [0..15 Header] [16..31 Label(16)] // Node8 (64B): [0..15 Header] [16..23 Label(8)] [24..31 Keys(8)] [32..63 Children(8*4)] // Node16 (128B): [0..15 Header] [16..47 Label(32)] [48..63 Keys(16)] [64..127 Children(16*4)] // Node48 (512B): [0..15 Header] [16..23 Label(8)] [24..31 UsedMask(8)] [32..63 Bitmap(32)] [64..255 Children(48*4)] [256..511 Index(256)] // Node256 (1152B): [0..15 Header] [16..95 Label(80)] [96..127 Bitmap(32)] [128..1151 Children(256*4)] private const int NODE8_KEYS_OFF = 24; private const int NODE8_CHILDREN_OFF = 32; private const int NODE16_KEYS_OFF = 48; private const int NODE16_CHILDREN_OFF = 64; private const int NODE48_USEDMASK_OFF = 24; private const int NODE48_BITMAP_OFF = 32; private const int NODE48_CHILDREN_OFF = 64; private const int NODE48_INDEX_OFF = 256; private const int NODE256_BITMAP_OFF = 96; private const int NODE256_CHILDREN_OFF = 128; private const ulong SWAR_LO = 0x0101_0101_0101_0101UL; private const ulong SWAR_HI = 0x8080_8080_8080_8080UL; private const ulong ALL_FF = 0xFFFF_FFFF_FFFF_FFFFUL; [StructLayout(LayoutKind.Explicit, Size = 16)] private struct NodeHeader { [FieldOffset(0)] public int SubtreeCount; [FieldOffset(4)] public ushort ChildCount; [FieldOffset(6)] public byte LabelLen; [FieldOffset(7)] public byte Meta; [FieldOffset(8)] public long Value; } private struct NodePool { public uint FreeHead; public uint BumpChunkId; public uint BumpOff32; public uint BumpLimit32; public nuint NextChunkBytes; } private struct ExtPool { public byte* FreeHead; public byte* BumpPtr; public byte* BumpEnd; public nuint NextChunkBytes; } // Hot read-path fields packed first: private byte** _chunks; private uint _rootHandle; private int _chunkCount; private int _chunkCap; // 5 node size-class pools (inline structs, zero managed sub-allocations): private NodePool _pool0; // Leaf (32B) private NodePool _pool1; // Node8 (64B) private NodePool _pool2; // Node16 (128B) private NodePool _pool3; // Node48 (512B) private NodePool _pool4; // Node256 (1152B) // 4 external label pools (32B, 64B, 128B, 256B): private byte** _extChunks; private int _extChunkCount; private int _extChunkCap; private ExtPool _ext0; // 32B private ExtPool _ext1; // 64B private ExtPool _ext2; // 128B private ExtPool _ext3; // 256B public RadixTree() { _chunkCap = 16; _chunkCount = 0; _chunks = (byte**)NativeMemory.Alloc((nuint)_chunkCap * (nuint)sizeof(byte*)); _pool0.FreeHead = NONE; _pool0.NextChunkBytes = 4096; _pool1.FreeHead = NONE; _pool1.NextChunkBytes = 4096; _pool2.FreeHead = NONE; _pool2.NextChunkBytes = 4096; _pool3.FreeHead = NONE; _pool3.NextChunkBytes = 4096; _pool4.FreeHead = NONE; _pool4.NextChunkBytes = 4 * 1152; // 4608 (multiple of 128) _extChunks = null; _extChunkCount = 0; _extChunkCap = 0; _ext0.NextChunkBytes = 4096; _ext1.NextChunkBytes = 4096; _ext2.NextChunkBytes = 4096; _ext3.NextChunkBytes = 4096; // Allocate root node as an empty Leaf (SubtreeCount = 0, ChildCount = 0, LabelLen = 0, HasValue = false). _rootHandle = AllocNode(KIND_LEAF, out NodeHeader* root); root->SubtreeCount = 0; root->ChildCount = 0; root->LabelLen = 0; root->Meta = KIND_LEAF; root->Value = 0; } ~RadixTree() { byte** chunks = _chunks; if (chunks != null) { int count = _chunkCount; for (int i = 0; i < count; i++) { NativeMemory.AlignedFree(chunks[i]); } NativeMemory.Free(chunks); _chunks = null; _chunkCount = 0; } byte** extChunks = _extChunks; if (extChunks != null) { int count = _extChunkCount; for (int i = 0; i < count; i++) { NativeMemory.Free(extChunks[i]); } NativeMemory.Free(extChunks); _extChunks = null; _extChunkCount = 0; } } public int Count => GetPtr(_chunks, _rootHandle)->SubtreeCount; // ------------------------------------------------------------ memory helpers [MethodImpl(MethodImplOptions.AggressiveInlining)] private static NodeHeader* GetPtr(byte** chunks, uint handle) { return (NodeHeader*)(chunks[handle >> OFFSET_BITS] + ((nuint)(handle & OFFSET_MASK) << 5)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static byte* GetLabelPtr(NodeHeader* node, byte meta) { byte* inlinePtr = (byte*)node + 16; return (meta & EXT_LABEL) == 0 ? inlinePtr : *(byte**)inlinePtr; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int InlineCap(int kind) { return kind switch { KIND_LEAF => 16, KIND_NODE8 => 8, KIND_NODE16 => 32, KIND_NODE48 => 8, _ => 80 }; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static uint Stride32(int kind) { return kind switch { KIND_LEAF => 1u, KIND_NODE8 => 2u, KIND_NODE16 => 4u, KIND_NODE48 => 16u, _ => 36u }; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private ref NodePool GetNodePool(int kind) { switch (kind) { case KIND_LEAF: return ref _pool0; case KIND_NODE8: return ref _pool1; case KIND_NODE16: return ref _pool2; case KIND_NODE48: return ref _pool3; default: return ref _pool4; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private uint AllocNode(int kind, out NodeHeader* ptr) { ref NodePool pool = ref GetNodePool(kind); uint free = pool.FreeHead; if (free != NONE) { NodeHeader* p = GetPtr(_chunks, free); pool.FreeHead = *(uint*)p; ptr = p; return free; } uint off = pool.BumpOff32; if (off < pool.BumpLimit32) { uint h = (pool.BumpChunkId << OFFSET_BITS) | off; pool.BumpOff32 = off + Stride32(kind); ptr = (NodeHeader*)(_chunks[pool.BumpChunkId] + ((nuint)off << 5)); return h; } return AllocNodeSlow(kind, ref pool, out ptr); } [MethodImpl(MethodImplOptions.NoInlining)] private uint AllocNodeSlow(int kind, ref NodePool pool, out NodeHeader* ptr) { if (_chunkCount == _chunkCap) { int newCap = _chunkCap * 2; byte** newChunks = (byte**)NativeMemory.Alloc((nuint)newCap * (nuint)sizeof(byte*)); Buffer.MemoryCopy(_chunks, newChunks, (nuint)newCap * (nuint)sizeof(byte*), (nuint)_chunkCount * (nuint)sizeof(byte*)); NativeMemory.Free(_chunks); _chunks = newChunks; _chunkCap = newCap; } nuint chunkBytes = pool.NextChunkBytes; byte* mem = (byte*)NativeMemory.AlignedAlloc(chunkBytes, 128); uint chunkId = (uint)_chunkCount++; _chunks[chunkId] = mem; uint stride32 = Stride32(kind); uint total32 = (uint)(chunkBytes >> 5); pool.BumpChunkId = chunkId; pool.BumpOff32 = stride32; pool.BumpLimit32 = total32; // Grow next chunk size up to 256 KB (or 224 * 1152 for Node256 so offset32 < 8192). nuint maxBytes = kind == KIND_NODE256 ? (nuint)(224 * 1152) : MAX_CHUNK_BYTES; nuint next = chunkBytes * 2; pool.NextChunkBytes = next <= maxBytes ? next : maxBytes; ptr = (NodeHeader*)mem; return chunkId << OFFSET_BITS; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void FreeNodeStructOnly(int kind, uint handle, NodeHeader* ptr) { ref NodePool pool = ref GetNodePool(kind); *(uint*)ptr = pool.FreeHead; pool.FreeHead = handle; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void FreeNodeFull(uint handle, NodeHeader* ptr) { byte meta = ptr->Meta; if ((meta & EXT_LABEL) != 0) { FreeExtLabel(*(byte**)((byte*)ptr + 16), ptr->LabelLen); } FreeNodeStructOnly(meta & KIND_MASK, handle, ptr); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int ExtClass(int len) { if (len <= 32) return 0; if (len <= 64) return 1; if (len <= 128) return 2; return 3; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private ref ExtPool GetExtPool(int cls) { switch (cls) { case 0: return ref _ext0; case 1: return ref _ext1; case 2: return ref _ext2; default: return ref _ext3; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private byte* AllocExtLabel(int len) { int cls = ExtClass(len); ref ExtPool pool = ref GetExtPool(cls); byte* free = pool.FreeHead; if (free != null) { pool.FreeHead = *(byte**)free; return free; } byte* bump = pool.BumpPtr; if (bump < pool.BumpEnd) { pool.BumpPtr = bump + (32 << cls); return bump; } return AllocExtLabelSlow(cls, ref pool); } [MethodImpl(MethodImplOptions.NoInlining)] private byte* AllocExtLabelSlow(int cls, ref ExtPool pool) { if (_extChunkCount == _extChunkCap) { int newCap = _extChunkCap == 0 ? 8 : _extChunkCap * 2; byte** newArr = (byte**)NativeMemory.Alloc((nuint)newCap * (nuint)sizeof(byte*)); if (_extChunks != null) { Buffer.MemoryCopy(_extChunks, newArr, (nuint)newCap * (nuint)sizeof(byte*), (nuint)_extChunkCount * (nuint)sizeof(byte*)); NativeMemory.Free(_extChunks); } _extChunks = newArr; _extChunkCap = newCap; } nuint chunkBytes = pool.NextChunkBytes; byte* mem = (byte*)NativeMemory.Alloc(chunkBytes); _extChunks[_extChunkCount++] = mem; nuint slotBytes = (nuint)(32 << cls); pool.BumpPtr = mem + slotBytes; pool.BumpEnd = mem + chunkBytes; nuint next = chunkBytes * 2; pool.NextChunkBytes = next <= MAX_CHUNK_BYTES ? next : MAX_CHUNK_BYTES; return mem; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void FreeExtLabel(byte* buf, int len) { int cls = ExtClass(len); ref ExtPool pool = ref GetExtPool(cls); *(byte**)buf = pool.FreeHead; pool.FreeHead = buf; } // ------------------------------------------------------------ label helpers // Assumes len >= 1. [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void CopyBytes(byte* src, byte* dst, int len) { if (len == 1) { *dst = *src; return; } if (len <= 3) { *(ushort*)dst = *(ushort*)src; dst[len - 1] = src[len - 1]; return; } if (len <= 7) { *(uint*)dst = *(uint*)src; *(uint*)(dst + len - 4) = *(uint*)(src + len - 4); return; } int i = 0; int end = len - 8; while (i < end) { *(ulong*)(dst + i) = *(ulong*)(src + i); i += 8; } *(ulong*)(dst + end) = *(ulong*)(src + end); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void InitLabel(NodeHeader* node, int kind, byte* src, int len) { node->LabelLen = (byte)len; if (len == 0) return; byte* inlinePtr = (byte*)node + 16; if (len <= InlineCap(kind)) { CopyBytes(src, inlinePtr, len); } else { byte* ext = AllocExtLabel(len); CopyBytes(src, ext, len); *(byte**)inlinePtr = ext; node->Meta |= EXT_LABEL; } } // Transfers ownership of src's label to dst (which has kind dstKind, and Meta initialized without EXT_LABEL). [MethodImpl(MethodImplOptions.AggressiveInlining)] private void MoveLabel(NodeHeader* src, NodeHeader* dst, int dstKind) { int len = src->LabelLen; dst->LabelLen = (byte)len; if (len == 0) return; byte* srcInline = (byte*)src + 16; byte* dstInline = (byte*)dst + 16; int dstCap = InlineCap(dstKind); if ((src->Meta & EXT_LABEL) == 0) { if (len <= dstCap) { CopyBytes(srcInline, dstInline, len); } else { byte* ext = AllocExtLabel(len); CopyBytes(srcInline, ext, len); *(byte**)dstInline = ext; dst->Meta |= EXT_LABEL; } } else { byte* ext = *(byte**)srcInline; if (len <= dstCap) { CopyBytes(ext, dstInline, len); FreeExtLabel(ext, len); } else { *(byte**)dstInline = ext; dst->Meta |= EXT_LABEL; } } } // Drops the first `shift` bytes (1 <= shift < node->LabelLen) from node's label. private void ShrinkLabel(NodeHeader* node, int shift) { int oldLen = node->LabelLen; int newLen = oldLen - shift; byte* inlinePtr = (byte*)node + 16; if ((node->Meta & EXT_LABEL) == 0) { Buffer.MemoryCopy(inlinePtr + shift, inlinePtr, newLen, newLen); } else { byte* oldBuf = *(byte**)inlinePtr; int cap = InlineCap(node->Meta & KIND_MASK); if (newLen <= cap) { CopyBytes(oldBuf + shift, inlinePtr, newLen); FreeExtLabel(oldBuf, oldLen); node->Meta &= unchecked((byte)~EXT_LABEL); } else if (ExtClass(newLen) == ExtClass(oldLen)) { Buffer.MemoryCopy(oldBuf + shift, oldBuf, newLen, newLen); } else { byte* newBuf = AllocExtLabel(newLen); CopyBytes(oldBuf + shift, newBuf, newLen); FreeExtLabel(oldBuf, oldLen); *(byte**)inlinePtr = newBuf; } } node->LabelLen = (byte)newLen; } // Prepends pPtr[0..pLen-1] to child's existing label. private void PrependLabel(NodeHeader* child, byte* pPtr, int pLen) { int cLen = child->LabelLen; int total = pLen + cLen; byte* inlinePtr = (byte*)child + 16; if ((child->Meta & EXT_LABEL) == 0) { int cap = InlineCap(child->Meta & KIND_MASK); if (total <= cap) { Buffer.MemoryCopy(inlinePtr, inlinePtr + pLen, cLen, cLen); CopyBytes(pPtr, inlinePtr, pLen); } else { byte* newBuf = AllocExtLabel(total); CopyBytes(pPtr, newBuf, pLen); CopyBytes(inlinePtr, newBuf + pLen, cLen); *(byte**)inlinePtr = newBuf; child->Meta |= EXT_LABEL; } } else { byte* oldBuf = *(byte**)inlinePtr; if (ExtClass(total) == ExtClass(cLen)) { Buffer.MemoryCopy(oldBuf, oldBuf + pLen, cLen, cLen); CopyBytes(pPtr, oldBuf, pLen); } else { byte* newBuf = AllocExtLabel(total); CopyBytes(pPtr, newBuf, pLen); CopyBytes(oldBuf, newBuf + pLen, cLen); FreeExtLabel(oldBuf, cLen); *(byte**)inlinePtr = newBuf; } } child->LabelLen = (byte)total; } // Assumes len >= 1. [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool BytesEqual(byte* a, byte* b, int len) { if (len == 1) return *a == *b; if (len <= 3) return *(ushort*)a == *(ushort*)b && a[len - 1] == b[len - 1]; if (len <= 7) return *(uint*)a == *(uint*)b && *(uint*)(a + len - 4) == *(uint*)(b + len - 4); int i = 0; int end = len - 8; while (i < end) { if (*(ulong*)(a + i) != *(ulong*)(b + i)) return false; i += 8; } return *(ulong*)(a + end) == *(ulong*)(b + end); } // Assumes a[0] == b[0] and maxLen >= 1. [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int CommonPrefixLenFrom1(byte* a, byte* b, int maxLen) { int i = 1; while (i + 8 <= maxLen) { ulong diff = *(ulong*)(a + i) ^ *(ulong*)(b + i); if (diff != 0) return i + (BitOperations.TrailingZeroCount(diff) >> 3); i += 8; } if (i + 4 <= maxLen) { uint diff = *(uint*)(a + i) ^ *(uint*)(b + i); if (diff != 0) return i + (BitOperations.TrailingZeroCount(diff) >> 3); i += 4; } while (i < maxLen && a[i] == b[i]) i++; return i; } // ------------------------------------------------------------ child lookup & mutation [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int FindIndexNode8(NodeHeader* node, byte b) { ulong dup = SWAR_LO * b; ulong m = *(ulong*)((byte*)node + NODE8_KEYS_OFF) ^ dup; ulong eq = (m - SWAR_LO) & ~m & SWAR_HI; return BitOperations.TrailingZeroCount(eq) >> 3; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int FindIndexNode16(NodeHeader* node, byte b) { ulong dup = SWAR_LO * b; ulong m0 = *(ulong*)((byte*)node + NODE16_KEYS_OFF) ^ dup; ulong e0 = (m0 - SWAR_LO) & ~m0 & SWAR_HI; ulong m1 = *(ulong*)((byte*)node + NODE16_KEYS_OFF + 8) ^ dup; ulong e1 = (m1 - SWAR_LO) & ~m1 & SWAR_HI; int i0 = BitOperations.TrailingZeroCount(e0) >> 3; int i1 = 8 + (BitOperations.TrailingZeroCount(e1) >> 3); return e0 != 0 ? i0 : i1; } // Assumes kind != KIND_LEAF. [MethodImpl(MethodImplOptions.AggressiveInlining)] private static uint FindChild(NodeHeader* node, int kind, byte b) { if (kind == KIND_NODE8) { int idx = FindIndexNode8(node, b); return idx < node->ChildCount ? ((uint*)((byte*)node + NODE8_CHILDREN_OFF))[idx] : NONE; } if (kind == KIND_NODE16) { int idx = FindIndexNode16(node, b); return idx < node->ChildCount ? ((uint*)((byte*)node + NODE16_CHILDREN_OFF))[idx] : NONE; } if (kind == KIND_NODE48) { byte slot = ((byte*)node + NODE48_INDEX_OFF)[b]; return slot != 0xFF ? ((uint*)((byte*)node + NODE48_CHILDREN_OFF))[slot] : NONE; } return ((uint*)((byte*)node + NODE256_CHILDREN_OFF))[b]; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void ReplaceChild(NodeHeader* parent, byte b, uint newChildHandle) { int kind = parent->Meta & KIND_MASK; if (kind == KIND_NODE8) { int idx = FindIndexNode8(parent, b); ((uint*)((byte*)parent + NODE8_CHILDREN_OFF))[idx] = newChildHandle; return; } if (kind == KIND_NODE16) { int idx = FindIndexNode16(parent, b); ((uint*)((byte*)parent + NODE16_CHILDREN_OFF))[idx] = newChildHandle; return; } if (kind == KIND_NODE48) { byte slot = ((byte*)parent + NODE48_INDEX_OFF)[b]; ((uint*)((byte*)parent + NODE48_CHILDREN_OFF))[slot] = newChildHandle; return; } ((uint*)((byte*)parent + NODE256_CHILDREN_OFF))[b] = newChildHandle; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void InsertIntoNode8(NodeHeader* node, byte b, uint childHandle) { int cnt = node->ChildCount; byte* keys = (byte*)node + NODE8_KEYS_OFF; uint* children = (uint*)((byte*)node + NODE8_CHILDREN_OFF); int i = cnt; while (i > 0 && keys[i - 1] > b) { keys[i] = keys[i - 1]; children[i] = children[i - 1]; i--; } keys[i] = b; children[i] = childHandle; node->ChildCount = (ushort)(cnt + 1); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void InsertIntoNode16(NodeHeader* node, byte b, uint childHandle) { int cnt = node->ChildCount; byte* keys = (byte*)node + NODE16_KEYS_OFF; uint* children = (uint*)((byte*)node + NODE16_CHILDREN_OFF); int i = cnt; while (i > 0 && keys[i - 1] > b) { keys[i] = keys[i - 1]; children[i] = children[i - 1]; i--; } keys[i] = b; children[i] = childHandle; node->ChildCount = (ushort)(cnt + 1); } // Adds child (b, childHandle) to node, promoting if full. // Returns the resulting handle and pointer of the node (may differ if promoted). private uint AddChild(uint nodeHandle, NodeHeader* node, byte b, uint childHandle, out NodeHeader* outNode) { int kind = node->Meta & KIND_MASK; if (kind == KIND_LEAF) { uint newHandle = AllocNode(KIND_NODE8, out NodeHeader* n8); n8->SubtreeCount = node->SubtreeCount; n8->ChildCount = 1; n8->Meta = (byte)(KIND_NODE8 | (node->Meta & HAS_VALUE)); n8->Value = node->Value; MoveLabel(node, n8, KIND_NODE8); *(ulong*)((byte*)n8 + NODE8_KEYS_OFF) = ALL_FF; ((byte*)n8 + NODE8_KEYS_OFF)[0] = b; ((uint*)((byte*)n8 + NODE8_CHILDREN_OFF))[0] = childHandle; FreeNodeStructOnly(KIND_LEAF, nodeHandle, node); outNode = n8; return newHandle; } if (kind == KIND_NODE8) { if (node->ChildCount < 8) { InsertIntoNode8(node, b, childHandle); outNode = node; return nodeHandle; } // Promote Node8 -> Node16 uint newHandle = AllocNode(KIND_NODE16, out NodeHeader* n16); n16->SubtreeCount = node->SubtreeCount; n16->ChildCount = 8; n16->Meta = (byte)(KIND_NODE16 | (node->Meta & HAS_VALUE)); n16->Value = node->Value; MoveLabel(node, n16, KIND_NODE16); *(ulong*)((byte*)n16 + NODE16_KEYS_OFF) = *(ulong*)((byte*)node + NODE8_KEYS_OFF); *(ulong*)((byte*)n16 + NODE16_KEYS_OFF + 8) = ALL_FF; Buffer.MemoryCopy((byte*)node + NODE8_CHILDREN_OFF, (byte*)n16 + NODE16_CHILDREN_OFF, 32, 32); InsertIntoNode16(n16, b, childHandle); FreeNodeStructOnly(KIND_NODE8, nodeHandle, node); outNode = n16; return newHandle; } if (kind == KIND_NODE16) { if (node->ChildCount < 16) { InsertIntoNode16(node, b, childHandle); outNode = node; return nodeHandle; } // Promote Node16 -> Node48 uint newHandle = AllocNode(KIND_NODE48, out NodeHeader* n48); n48->SubtreeCount = node->SubtreeCount; n48->ChildCount = 17; n48->Meta = (byte)(KIND_NODE48 | (node->Meta & HAS_VALUE)); n48->Value = node->Value; MoveLabel(node, n48, KIND_NODE48); ulong* bm = (ulong*)((byte*)n48 + NODE48_BITMAP_OFF); bm[0] = 0; bm[1] = 0; bm[2] = 0; bm[3] = 0; byte* idxTbl = (byte*)n48 + NODE48_INDEX_OFF; new Span(idxTbl, 256).Fill(0xFF); byte* oldKeys = (byte*)node + NODE16_KEYS_OFF; uint* oldChildren = (uint*)((byte*)node + NODE16_CHILDREN_OFF); uint* newChildren = (uint*)((byte*)n48 + NODE48_CHILDREN_OFF); for (int i = 0; i < 16; i++) { byte k = oldKeys[i]; idxTbl[k] = (byte)i; newChildren[i] = oldChildren[i]; bm[k >> 6] |= 1UL << (k & 63); } idxTbl[b] = 16; newChildren[16] = childHandle; bm[b >> 6] |= 1UL << (b & 63); *(ulong*)((byte*)n48 + NODE48_USEDMASK_OFF) = (1UL << 17) - 1UL; FreeNodeStructOnly(KIND_NODE16, nodeHandle, node); outNode = n48; return newHandle; } if (kind == KIND_NODE48) { if (node->ChildCount < 48) { ulong* usedMaskPtr = (ulong*)((byte*)node + NODE48_USEDMASK_OFF); int slot = BitOperations.TrailingZeroCount(~(*usedMaskPtr)); *usedMaskPtr |= 1UL << slot; ((byte*)node + NODE48_INDEX_OFF)[b] = (byte)slot; ((uint*)((byte*)node + NODE48_CHILDREN_OFF))[slot] = childHandle; ((ulong*)((byte*)node + NODE48_BITMAP_OFF))[b >> 6] |= 1UL << (b & 63); node->ChildCount++; outNode = node; return nodeHandle; } // Promote Node48 -> Node256 uint newHandle = AllocNode(KIND_NODE256, out NodeHeader* n256); n256->SubtreeCount = node->SubtreeCount; n256->ChildCount = 49; n256->Meta = (byte)(KIND_NODE256 | (node->Meta & HAS_VALUE)); n256->Value = node->Value; MoveLabel(node, n256, KIND_NODE256); ulong* oldBm = (ulong*)((byte*)node + NODE48_BITMAP_OFF); ulong* newBm = (ulong*)((byte*)n256 + NODE256_BITMAP_OFF); newBm[0] = oldBm[0]; newBm[1] = oldBm[1]; newBm[2] = oldBm[2]; newBm[3] = oldBm[3]; uint* newChildren = (uint*)((byte*)n256 + NODE256_CHILDREN_OFF); new Span(newChildren, 256).Fill(NONE); byte* oldIdx = (byte*)node + NODE48_INDEX_OFF; uint* oldChildren = (uint*)((byte*)node + NODE48_CHILDREN_OFF); for (int w = 0; w < 4; w++) { ulong bits = oldBm[w]; int baseKey = w << 6; while (bits != 0) { int k = baseKey + BitOperations.TrailingZeroCount(bits); bits &= bits - 1; newChildren[k] = oldChildren[oldIdx[k]]; } } newChildren[b] = childHandle; newBm[b >> 6] |= 1UL << (b & 63); FreeNodeStructOnly(KIND_NODE48, nodeHandle, node); outNode = n256; return newHandle; } // Node256 ((uint*)((byte*)node + NODE256_CHILDREN_OFF))[b] = childHandle; ((ulong*)((byte*)node + NODE256_BITMAP_OFF))[b >> 6] |= 1UL << (b & 63); node->ChildCount++; outNode = node; return nodeHandle; } // Removes child byte `b` from node, demoting with hysteresis if appropriate. // Returns the resulting handle and pointer of the node (may differ if demoted). private uint RemoveChild(uint nodeHandle, NodeHeader* node, byte b, out NodeHeader* outNode) { int kind = node->Meta & KIND_MASK; if (kind == KIND_NODE8) { int idx = FindIndexNode8(node, b); int last = node->ChildCount - 1; if (last == 0) { // Demote Node8 -> Leaf uint newHandle = AllocNode(KIND_LEAF, out NodeHeader* leaf); leaf->SubtreeCount = node->SubtreeCount; leaf->ChildCount = 0; leaf->Meta = (byte)(KIND_LEAF | (node->Meta & HAS_VALUE)); leaf->Value = node->Value; MoveLabel(node, leaf, KIND_LEAF); FreeNodeStructOnly(KIND_NODE8, nodeHandle, node); outNode = leaf; return newHandle; } byte* keys = (byte*)node + NODE8_KEYS_OFF; uint* children = (uint*)((byte*)node + NODE8_CHILDREN_OFF); for (int i = idx; i < last; i++) { keys[i] = keys[i + 1]; children[i] = children[i + 1]; } keys[last] = 0xFF; node->ChildCount = (ushort)last; outNode = node; return nodeHandle; } if (kind == KIND_NODE16) { int idx = FindIndexNode16(node, b); int last = node->ChildCount - 1; byte* keys = (byte*)node + NODE16_KEYS_OFF; uint* children = (uint*)((byte*)node + NODE16_CHILDREN_OFF); for (int i = idx; i < last; i++) { keys[i] = keys[i + 1]; children[i] = children[i + 1]; } keys[last] = 0xFF; node->ChildCount = (ushort)last; if (last <= 6) { // Demote Node16 -> Node8 uint newHandle = AllocNode(KIND_NODE8, out NodeHeader* n8); n8->SubtreeCount = node->SubtreeCount; n8->ChildCount = (ushort)last; n8->Meta = (byte)(KIND_NODE8 | (node->Meta & HAS_VALUE)); n8->Value = node->Value; MoveLabel(node, n8, KIND_NODE8); *(ulong*)((byte*)n8 + NODE8_KEYS_OFF) = *(ulong*)keys; // keys[last..7] are already 0xFF Buffer.MemoryCopy(children, (byte*)n8 + NODE8_CHILDREN_OFF, (nuint)last * 4u, (nuint)last * 4u); FreeNodeStructOnly(KIND_NODE16, nodeHandle, node); outNode = n8; return newHandle; } outNode = node; return nodeHandle; } if (kind == KIND_NODE48) { byte* idxTbl = (byte*)node + NODE48_INDEX_OFF; int slot = idxTbl[b]; idxTbl[b] = 0xFF; *(ulong*)((byte*)node + NODE48_USEDMASK_OFF) &= ~(1UL << slot); ulong* bm = (ulong*)((byte*)node + NODE48_BITMAP_OFF); bm[b >> 6] &= ~(1UL << (b & 63)); int newCount = --node->ChildCount; if (newCount <= 12) { // Demote Node48 -> Node16 uint newHandle = AllocNode(KIND_NODE16, out NodeHeader* n16); n16->SubtreeCount = node->SubtreeCount; n16->ChildCount = (ushort)newCount; n16->Meta = (byte)(KIND_NODE16 | (node->Meta & HAS_VALUE)); n16->Value = node->Value; MoveLabel(node, n16, KIND_NODE16); byte* n16Keys = (byte*)n16 + NODE16_KEYS_OFF; *(ulong*)n16Keys = ALL_FF; *(ulong*)(n16Keys + 8) = ALL_FF; uint* n16Children = (uint*)((byte*)n16 + NODE16_CHILDREN_OFF); uint* oldChildren = (uint*)((byte*)node + NODE48_CHILDREN_OFF); int dst = 0; for (int w = 0; w < 4; w++) { ulong bits = bm[w]; int baseKey = w << 6; while (bits != 0) { int k = baseKey + BitOperations.TrailingZeroCount(bits); bits &= bits - 1; n16Keys[dst] = (byte)k; n16Children[dst] = oldChildren[idxTbl[k]]; dst++; } } FreeNodeStructOnly(KIND_NODE48, nodeHandle, node); outNode = n16; return newHandle; } outNode = node; return nodeHandle; } // Node256 uint* c256 = (uint*)((byte*)node + NODE256_CHILDREN_OFF); c256[b] = NONE; ulong* bm256 = (ulong*)((byte*)node + NODE256_BITMAP_OFF); bm256[b >> 6] &= ~(1UL << (b & 63)); int cnt256 = --node->ChildCount; if (cnt256 <= 36) { // Demote Node256 -> Node48 uint newHandle = AllocNode(KIND_NODE48, out NodeHeader* n48); n48->SubtreeCount = node->SubtreeCount; n48->ChildCount = (ushort)cnt256; n48->Meta = (byte)(KIND_NODE48 | (node->Meta & HAS_VALUE)); n48->Value = node->Value; MoveLabel(node, n48, KIND_NODE48); ulong* newBm = (ulong*)((byte*)n48 + NODE48_BITMAP_OFF); newBm[0] = bm256[0]; newBm[1] = bm256[1]; newBm[2] = bm256[2]; newBm[3] = bm256[3]; byte* newIdx = (byte*)n48 + NODE48_INDEX_OFF; new Span(newIdx, 256).Fill(0xFF); uint* newChildren = (uint*)((byte*)n48 + NODE48_CHILDREN_OFF); int slot = 0; for (int w = 0; w < 4; w++) { ulong bits = bm256[w]; int baseKey = w << 6; while (bits != 0) { int k = baseKey + BitOperations.TrailingZeroCount(bits); bits &= bits - 1; newIdx[k] = (byte)slot; newChildren[slot] = c256[k]; slot++; } } *(ulong*)((byte*)n48 + NODE48_USEDMASK_OFF) = (1UL << slot) - 1UL; FreeNodeStructOnly(KIND_NODE256, nodeHandle, node); outNode = n48; return newHandle; } outNode = node; return nodeHandle; } // ------------------------------------------------------------ public operations public bool TryGet(ReadOnlySpan key, out long value) { byte** chunks = _chunks; NodeHeader* node = GetPtr(chunks, _rootHandle); int keyLen = key.Length; byte meta = node->Meta; if (keyLen == 0) { if ((meta & HAS_VALUE) != 0) { value = node->Value; return true; } value = 0; return false; } int kind = meta & KIND_MASK; if (kind == KIND_LEAF) { value = 0; return false; } fixed (byte* keyPtr = key) { uint h = FindChild(node, kind, keyPtr[0]); if (h == NONE) { value = 0; return false; } node = GetPtr(chunks, h); int pos = 0; while (true) { int labelLen = node->LabelLen; int nextPos = pos + labelLen; meta = node->Meta; kind = meta & KIND_MASK; if (kind == KIND_LEAF) { if (nextPos != keyLen) { value = 0; return false; } if (labelLen > 1 && !BytesEqual(GetLabelPtr(node, meta) + 1, keyPtr + pos + 1, labelLen - 1)) { value = 0; return false; } value = node->Value; return true; } if (nextPos > keyLen) { value = 0; return false; } if (labelLen > 1 && !BytesEqual(GetLabelPtr(node, meta) + 1, keyPtr + pos + 1, labelLen - 1)) { value = 0; return false; } if (nextPos == keyLen) { if ((meta & HAS_VALUE) != 0) { value = node->Value; return true; } value = 0; return false; } pos = nextPos; h = FindChild(node, kind, keyPtr[pos]); if (h == NONE) { value = 0; return false; } node = GetPtr(chunks, h); } } } public bool TryLongestPrefix(ReadOnlySpan key, out int length, out long value) { byte** chunks = _chunks; NodeHeader* node = GetPtr(chunks, _rootHandle); bool found = false; int bestLen = 0; long bestVal = 0; byte meta = node->Meta; if ((meta & HAS_VALUE) != 0) { found = true; bestVal = node->Value; } int keyLen = key.Length; int kind = meta & KIND_MASK; if (keyLen == 0 || kind == KIND_LEAF) { length = bestLen; value = bestVal; return found; } fixed (byte* keyPtr = key) { uint h = FindChild(node, kind, keyPtr[0]); if (h == NONE) { length = bestLen; value = bestVal; return found; } node = GetPtr(chunks, h); int pos = 0; while (true) { int labelLen = node->LabelLen; int nextPos = pos + labelLen; if (nextPos > keyLen) break; meta = node->Meta; if (labelLen > 1 && !BytesEqual(GetLabelPtr(node, meta) + 1, keyPtr + pos + 1, labelLen - 1)) break; pos = nextPos; kind = meta & KIND_MASK; if (kind == KIND_LEAF) { length = pos; value = node->Value; return true; } if ((meta & HAS_VALUE) != 0) { found = true; bestLen = pos; bestVal = node->Value; } if (pos == keyLen) break; h = FindChild(node, kind, keyPtr[pos]); if (h == NONE) break; node = GetPtr(chunks, h); } } length = bestLen; value = bestVal; return found; } public int PrefixCount(ReadOnlySpan prefix) { byte** chunks = _chunks; NodeHeader* node = GetPtr(chunks, _rootHandle); int prefixLen = prefix.Length; if (prefixLen == 0) { return node->SubtreeCount; } int kind = node->Meta & KIND_MASK; if (kind == KIND_LEAF) return 0; fixed (byte* prefixPtr = prefix) { uint h = FindChild(node, kind, prefixPtr[0]); if (h == NONE) return 0; node = GetPtr(chunks, h); int pos = 0; while (true) { int labelLen = node->LabelLen; int rem = prefixLen - pos; byte meta = node->Meta; if (rem <= labelLen) { if (rem > 1 && !BytesEqual(GetLabelPtr(node, meta) + 1, prefixPtr + pos + 1, rem - 1)) return 0; return node->SubtreeCount; } if (labelLen > 1 && !BytesEqual(GetLabelPtr(node, meta) + 1, prefixPtr + pos + 1, labelLen - 1)) return 0; pos += labelLen; kind = meta & KIND_MASK; if (kind == KIND_LEAF) return 0; h = FindChild(node, kind, prefixPtr[pos]); if (h == NONE) return 0; node = GetPtr(chunks, h); } } } public int PrefixValues(ReadOnlySpan prefix, long[] outValues, int limit) { if (limit <= 0) return 0; byte** chunks = _chunks; NodeHeader* node = GetPtr(chunks, _rootHandle); int prefixLen = prefix.Length; if (prefixLen > 0) { int kind = node->Meta & KIND_MASK; if (kind == KIND_LEAF) return 0; fixed (byte* prefixPtr = prefix) { uint h = FindChild(node, kind, prefixPtr[0]); if (h == NONE) return 0; node = GetPtr(chunks, h); int pos = 0; while (true) { int labelLen = node->LabelLen; int rem = prefixLen - pos; byte meta = node->Meta; if (rem <= labelLen) { if (rem > 1 && !BytesEqual(GetLabelPtr(node, meta) + 1, prefixPtr + pos + 1, rem - 1)) return 0; break; } if (labelLen > 1 && !BytesEqual(GetLabelPtr(node, meta) + 1, prefixPtr + pos + 1, labelLen - 1)) return 0; pos += labelLen; kind = meta & KIND_MASK; if (kind == KIND_LEAF) return 0; h = FindChild(node, kind, prefixPtr[pos]); if (h == NONE) return 0; node = GetPtr(chunks, h); } } } int subCount = node->SubtreeCount; if (subCount == 0) return 0; if ((node->Meta & KIND_MASK) == KIND_LEAF) { outValues[0] = node->Value; return 1; } fixed (long* outBase = outValues) { long* endPtr = subCount <= limit ? CollectAll(chunks, node, outBase) : CollectLimited(chunks, node, outBase, outBase + limit); return (int)(endPtr - outBase); } } // Walks entire subtree rooted at an internal node `node` (no limit check needed). private static long* CollectAll(byte** chunks, NodeHeader* node, long* outPtr) { byte meta = node->Meta; if ((meta & HAS_VALUE) != 0) { *outPtr++ = node->Value; } int kind = meta & KIND_MASK; if (kind <= KIND_NODE16) { uint* children = (uint*)((byte*)node + (kind == KIND_NODE8 ? NODE8_CHILDREN_OFF : NODE16_CHILDREN_OFF)); int cnt = node->ChildCount; for (int i = 0; i < cnt; i++) { NodeHeader* ch = GetPtr(chunks, children[i]); if ((ch->Meta & KIND_MASK) == KIND_LEAF) { *outPtr++ = ch->Value; } else { outPtr = CollectAll(chunks, ch, outPtr); } } return outPtr; } if (kind == KIND_NODE48) { ulong* bm = (ulong*)((byte*)node + NODE48_BITMAP_OFF); byte* idxTbl = (byte*)node + NODE48_INDEX_OFF; uint* children = (uint*)((byte*)node + NODE48_CHILDREN_OFF); for (int w = 0; w < 4; w++) { ulong bits = bm[w]; int baseKey = w << 6; while (bits != 0) { int k = baseKey + BitOperations.TrailingZeroCount(bits); bits &= bits - 1; NodeHeader* ch = GetPtr(chunks, children[idxTbl[k]]); if ((ch->Meta & KIND_MASK) == KIND_LEAF) { *outPtr++ = ch->Value; } else { outPtr = CollectAll(chunks, ch, outPtr); } } } return outPtr; } // Node256 { ulong* bm = (ulong*)((byte*)node + NODE256_BITMAP_OFF); uint* children = (uint*)((byte*)node + NODE256_CHILDREN_OFF); for (int w = 0; w < 4; w++) { ulong bits = bm[w]; int baseKey = w << 6; while (bits != 0) { int k = baseKey + BitOperations.TrailingZeroCount(bits); bits &= bits - 1; NodeHeader* ch = GetPtr(chunks, children[k]); if ((ch->Meta & KIND_MASK) == KIND_LEAF) { *outPtr++ = ch->Value; } else { outPtr = CollectAll(chunks, ch, outPtr); } } } return outPtr; } } // Walks subtree rooted at an internal node `node`, stopping once outPtr == outEnd. private static long* CollectLimited(byte** chunks, NodeHeader* node, long* outPtr, long* outEnd) { byte meta = node->Meta; if ((meta & HAS_VALUE) != 0) { *outPtr++ = node->Value; if (outPtr == outEnd) return outPtr; } int kind = meta & KIND_MASK; if (kind <= KIND_NODE16) { uint* children = (uint*)((byte*)node + (kind == KIND_NODE8 ? NODE8_CHILDREN_OFF : NODE16_CHILDREN_OFF)); int cnt = node->ChildCount; for (int i = 0; i < cnt; i++) { NodeHeader* ch = GetPtr(chunks, children[i]); if ((ch->Meta & KIND_MASK) == KIND_LEAF) { *outPtr++ = ch->Value; if (outPtr == outEnd) return outPtr; } else { outPtr = CollectLimited(chunks, ch, outPtr, outEnd); if (outPtr == outEnd) return outPtr; } } return outPtr; } if (kind == KIND_NODE48) { ulong* bm = (ulong*)((byte*)node + NODE48_BITMAP_OFF); byte* idxTbl = (byte*)node + NODE48_INDEX_OFF; uint* children = (uint*)((byte*)node + NODE48_CHILDREN_OFF); for (int w = 0; w < 4; w++) { ulong bits = bm[w]; int baseKey = w << 6; while (bits != 0) { int k = baseKey + BitOperations.TrailingZeroCount(bits); bits &= bits - 1; NodeHeader* ch = GetPtr(chunks, children[idxTbl[k]]); if ((ch->Meta & KIND_MASK) == KIND_LEAF) { *outPtr++ = ch->Value; if (outPtr == outEnd) return outPtr; } else { outPtr = CollectLimited(chunks, ch, outPtr, outEnd); if (outPtr == outEnd) return outPtr; } } } return outPtr; } // Node256 { ulong* bm = (ulong*)((byte*)node + NODE256_BITMAP_OFF); uint* children = (uint*)((byte*)node + NODE256_CHILDREN_OFF); for (int w = 0; w < 4; w++) { ulong bits = bm[w]; int baseKey = w << 6; while (bits != 0) { int k = baseKey + BitOperations.TrailingZeroCount(bits); bits &= bits - 1; NodeHeader* ch = GetPtr(chunks, children[k]); if ((ch->Meta & KIND_MASK) == KIND_LEAF) { *outPtr++ = ch->Value; if (outPtr == outEnd) return outPtr; } else { outPtr = CollectLimited(chunks, ch, outPtr, outEnd); if (outPtr == outEnd) return outPtr; } } } return outPtr; } } public bool Insert(ReadOnlySpan key, long value) { int keyLen = key.Length; byte** chunks = _chunks; NodeHeader* root = GetPtr(chunks, _rootHandle); if (keyLen == 0) { if ((root->Meta & HAS_VALUE) != 0) { root->Value = value; return false; } root->Meta |= HAS_VALUE; root->Value = value; root->SubtreeCount++; return true; } fixed (byte* keyPtr = key) { byte firstByte = keyPtr[0]; int rootKind = root->Meta & KIND_MASK; uint curHandle = rootKind == KIND_LEAF ? NONE : FindChild(root, rootKind, firstByte); if (curHandle == NONE) { uint leafHandle = AllocNode(KIND_LEAF, out NodeHeader* leaf); leaf->SubtreeCount = 1; leaf->ChildCount = 0; leaf->Meta = (byte)(KIND_LEAF | HAS_VALUE); leaf->Value = value; InitLabel(leaf, KIND_LEAF, keyPtr, keyLen); _rootHandle = AddChild(_rootHandle, root, firstByte, leafHandle, out NodeHeader* newRoot); newRoot->SubtreeCount++; return true; } NodeHeader** pathPtrs = stackalloc NodeHeader*[256]; byte* pathBytes = stackalloc byte[256]; pathPtrs[0] = root; pathBytes[0] = firstByte; int depth = 1; NodeHeader* cur = GetPtr(chunks, curHandle); pathPtrs[1] = cur; int pos = 0; while (true) { int labelLen = cur->LabelLen; int rem = keyLen - pos; int maxCmp = labelLen < rem ? labelLen : rem; byte curMeta = cur->Meta; byte* curLabel = GetLabelPtr(cur, curMeta); int match = maxCmp > 1 ? CommonPrefixLenFrom1(curLabel, keyPtr + pos, maxCmp) : 1; if (match < labelLen) { // Split cur's edge at `match`. uint splitHandle = AllocNode(KIND_NODE8, out NodeHeader* split); byte bOld = curLabel[match]; split->SubtreeCount = cur->SubtreeCount + 1; *(ulong*)((byte*)split + NODE8_KEYS_OFF) = ALL_FF; if (match == rem) { // New key ends inside cur's label. split->Meta = (byte)(KIND_NODE8 | HAS_VALUE); split->Value = value; split->ChildCount = 1; InitLabel(split, KIND_NODE8, curLabel, match); ((byte*)split + NODE8_KEYS_OFF)[0] = bOld; ((uint*)((byte*)split + NODE8_CHILDREN_OFF))[0] = curHandle; } else { // Branch into cur and a new leaf. uint leafHandle = AllocNode(KIND_LEAF, out NodeHeader* leaf); leaf->SubtreeCount = 1; leaf->ChildCount = 0; leaf->Meta = (byte)(KIND_LEAF | HAS_VALUE); leaf->Value = value; InitLabel(leaf, KIND_LEAF, keyPtr + pos + match, rem - match); split->Meta = KIND_NODE8; split->Value = 0; split->ChildCount = 2; InitLabel(split, KIND_NODE8, curLabel, match); byte bNew = keyPtr[pos + match]; byte* sKeys = (byte*)split + NODE8_KEYS_OFF; uint* sChildren = (uint*)((byte*)split + NODE8_CHILDREN_OFF); if (bOld < bNew) { sKeys[0] = bOld; sChildren[0] = curHandle; sKeys[1] = bNew; sChildren[1] = leafHandle; } else { sKeys[0] = bNew; sChildren[0] = leafHandle; sKeys[1] = bOld; sChildren[1] = curHandle; } } ShrinkLabel(cur, match); ReplaceChild(pathPtrs[depth - 1], pathBytes[depth - 1], splitHandle); for (int i = 0; i < depth; i++) { pathPtrs[i]->SubtreeCount++; } return true; } // Full label matched. pos += labelLen; if (pos == keyLen) { if ((curMeta & HAS_VALUE) != 0) { cur->Value = value; return false; } cur->Meta = (byte)(curMeta | HAS_VALUE); cur->Value = value; for (int i = 0; i <= depth; i++) { pathPtrs[i]->SubtreeCount++; } return true; } byte nextB = keyPtr[pos]; int curKind = curMeta & KIND_MASK; uint nextHandle = curKind == KIND_LEAF ? NONE : FindChild(cur, curKind, nextB); if (nextHandle == NONE) { uint leafHandle = AllocNode(KIND_LEAF, out NodeHeader* leaf); leaf->SubtreeCount = 1; leaf->ChildCount = 0; leaf->Meta = (byte)(KIND_LEAF | HAS_VALUE); leaf->Value = value; InitLabel(leaf, KIND_LEAF, keyPtr + pos, keyLen - pos); uint newCurHandle = AddChild(curHandle, cur, nextB, leafHandle, out NodeHeader* newCur); if (newCurHandle != curHandle) { ReplaceChild(pathPtrs[depth - 1], pathBytes[depth - 1], newCurHandle); pathPtrs[depth] = newCur; } for (int i = 0; i <= depth; i++) { pathPtrs[i]->SubtreeCount++; } return true; } pathBytes[depth] = nextB; depth++; curHandle = nextHandle; cur = GetPtr(chunks, curHandle); pathPtrs[depth] = cur; } } } public bool Remove(ReadOnlySpan key) { byte** chunks = _chunks; NodeHeader* root = GetPtr(chunks, _rootHandle); int keyLen = key.Length; if (keyLen == 0) { if ((root->Meta & HAS_VALUE) == 0) return false; root->Meta &= unchecked((byte)~HAS_VALUE); root->SubtreeCount--; return true; } int rootKind = root->Meta & KIND_MASK; if (rootKind == KIND_LEAF) return false; fixed (byte* keyPtr = key) { byte firstByte = keyPtr[0]; uint parentHandle = _rootHandle; uint curHandle = FindChild(root, rootKind, firstByte); if (curHandle == NONE) return false; NodeHeader** pathPtrs = stackalloc NodeHeader*[256]; byte* pathBytes = stackalloc byte[256]; pathPtrs[0] = root; pathBytes[0] = firstByte; int depth = 1; NodeHeader* cur = GetPtr(chunks, curHandle); pathPtrs[1] = cur; int pos = 0; while (true) { int labelLen = cur->LabelLen; int nextPos = pos + labelLen; if (nextPos > keyLen) return false; byte curMeta = cur->Meta; if (labelLen > 1 && !BytesEqual(GetLabelPtr(cur, curMeta) + 1, keyPtr + pos + 1, labelLen - 1)) return false; pos = nextPos; if (pos == keyLen) break; int curKind = curMeta & KIND_MASK; if (curKind == KIND_LEAF) return false; byte nextB = keyPtr[pos]; uint nextHandle = FindChild(cur, curKind, nextB); if (nextHandle == NONE) return false; pathBytes[depth] = nextB; depth++; parentHandle = curHandle; curHandle = nextHandle; cur = GetPtr(chunks, curHandle); pathPtrs[depth] = cur; } byte targetMeta = cur->Meta; if ((targetMeta & HAS_VALUE) == 0) return false; int childCount = cur->ChildCount; if (childCount >= 2) { // Keep branching node; just clear its key. cur->Meta = (byte)(targetMeta & ~HAS_VALUE); cur->SubtreeCount--; for (int i = 0; i < depth; i++) { pathPtrs[i]->SubtreeCount--; } return true; } if (childCount == 1) { // Node8 with 1 child and no remaining key: merge cur into its sole child. uint soleChildHandle = ((uint*)((byte*)cur + NODE8_CHILDREN_OFF))[0]; NodeHeader* soleChild = GetPtr(chunks, soleChildHandle); PrependLabel(soleChild, GetLabelPtr(cur, targetMeta), cur->LabelLen); FreeNodeFull(curHandle, cur); ReplaceChild(pathPtrs[depth - 1], pathBytes[depth - 1], soleChildHandle); for (int i = 0; i < depth; i++) { pathPtrs[i]->SubtreeCount--; } return true; } // childCount == 0 (cur is a Leaf): delete cur and remove from parent. FreeNodeFull(curHandle, cur); int parentDepth = depth - 1; NodeHeader* parentPtr = pathPtrs[parentDepth]; byte parentEdgeByte = pathBytes[parentDepth]; uint newParentHandle = RemoveChild(parentHandle, parentPtr, parentEdgeByte, out NodeHeader* newParentPtr); if (newParentHandle != parentHandle) { if (parentDepth == 0) { _rootHandle = newParentHandle; } else { ReplaceChild(pathPtrs[parentDepth - 1], pathBytes[parentDepth - 1], newParentHandle); } pathPtrs[parentDepth] = newParentPtr; parentHandle = newParentHandle; parentPtr = newParentPtr; } for (int i = 0; i <= parentDepth; i++) { pathPtrs[i]->SubtreeCount--; } // If parent is non-root, has no key, and now has exactly 1 child, merge parent into its sole child. if (parentDepth > 0) { byte pMeta = parentPtr->Meta; if ((pMeta & HAS_VALUE) == 0 && parentPtr->ChildCount == 1) { uint soleChildHandle = ((uint*)((byte*)parentPtr + NODE8_CHILDREN_OFF))[0]; NodeHeader* soleChild = GetPtr(_chunks, soleChildHandle); PrependLabel(soleChild, GetLabelPtr(parentPtr, pMeta), parentPtr->LabelLen); FreeNodeFull(parentHandle, parentPtr); ReplaceChild(pathPtrs[parentDepth - 1], pathBytes[parentDepth - 1], soleChildHandle); } } return true; } } // ------------------------------------------------------------ structural inspection (untimed) public int NodeCount() { return CountNodes(_chunks, GetPtr(_chunks, _rootHandle)); } private static int CountNodes(byte** chunks, NodeHeader* node) { int kind = node->Meta & KIND_MASK; if (kind == KIND_LEAF) return 1; int total = 1; if (kind <= KIND_NODE16) { uint* children = (uint*)((byte*)node + (kind == KIND_NODE8 ? NODE8_CHILDREN_OFF : NODE16_CHILDREN_OFF)); int cnt = node->ChildCount; for (int i = 0; i < cnt; i++) { total += CountNodes(chunks, GetPtr(chunks, children[i])); } return total; } if (kind == KIND_NODE48) { ulong* bm = (ulong*)((byte*)node + NODE48_BITMAP_OFF); byte* idxTbl = (byte*)node + NODE48_INDEX_OFF; uint* children = (uint*)((byte*)node + NODE48_CHILDREN_OFF); for (int w = 0; w < 4; w++) { ulong bits = bm[w]; int baseKey = w << 6; while (bits != 0) { int k = baseKey + BitOperations.TrailingZeroCount(bits); bits &= bits - 1; total += CountNodes(chunks, GetPtr(chunks, children[idxTbl[k]])); } } return total; } { ulong* bm = (ulong*)((byte*)node + NODE256_BITMAP_OFF); uint* children = (uint*)((byte*)node + NODE256_CHILDREN_OFF); for (int w = 0; w < 4; w++) { ulong bits = bm[w]; int baseKey = w << 6; while (bits != 0) { int k = baseKey + BitOperations.TrailingZeroCount(bits); bits &= bits - 1; total += CountNodes(chunks, GetPtr(chunks, children[k])); } } return total; } } public int Height() { return ComputeHeight(_chunks, GetPtr(_chunks, _rootHandle)); } private static int ComputeHeight(byte** chunks, NodeHeader* node) { int kind = node->Meta & KIND_MASK; if (kind == KIND_LEAF) return 0; int best = 0; if (kind <= KIND_NODE16) { uint* children = (uint*)((byte*)node + (kind == KIND_NODE8 ? NODE8_CHILDREN_OFF : NODE16_CHILDREN_OFF)); int cnt = node->ChildCount; for (int i = 0; i < cnt; i++) { int h = 1 + ComputeHeight(chunks, GetPtr(chunks, children[i])); if (h > best) best = h; } return best; } if (kind == KIND_NODE48) { ulong* bm = (ulong*)((byte*)node + NODE48_BITMAP_OFF); byte* idxTbl = (byte*)node + NODE48_INDEX_OFF; uint* children = (uint*)((byte*)node + NODE48_CHILDREN_OFF); for (int w = 0; w < 4; w++) { ulong bits = bm[w]; int baseKey = w << 6; while (bits != 0) { int k = baseKey + BitOperations.TrailingZeroCount(bits); bits &= bits - 1; int h = 1 + ComputeHeight(chunks, GetPtr(chunks, children[idxTbl[k]])); if (h > best) best = h; } } return best; } { ulong* bm = (ulong*)((byte*)node + NODE256_BITMAP_OFF); uint* children = (uint*)((byte*)node + NODE256_CHILDREN_OFF); for (int w = 0; w < 4; w++) { ulong bits = bm[w]; int baseKey = w << 6; while (bits != 0) { int k = baseKey + BitOperations.TrailingZeroCount(bits); bits &= bits - 1; int h = 1 + ComputeHeight(chunks, GetPtr(chunks, children[k])); if (h > best) best = h; } } return best; } } }