using System; using System.Numerics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; public sealed unsafe class BTree { private const int T = 16; private const int MinKeys = T - 1; // 15 private const int MaxKeys = 2 * T - 1; // 31 private const int MaxChildren = 2 * T; // 32 private const int SplitLeft = T; // 16 private const int SplitRight = T - 1; // 15 private const int MaxHeight = 16; // 512 bytes = exactly 4 Apple M3 cache lines (128 bytes each), 128-byte aligned. // Line 0 (0..127): Count (4B) + pad (4B) + Keys[0..14] (120B) // Line 1 (128..255): Keys[15..30] (128B) // Line 2 (256..383): Values[0..15] (128B) // Line 3 (384..511): Values[16..30] (120B) + pad (8B) [StructLayout(LayoutKind.Explicit, Size = 512)] private struct LeafNode { [FieldOffset(0)] public int Count; [FieldOffset(8)] public fixed long Keys[MaxKeys]; [FieldOffset(256)] public fixed long Values[MaxKeys]; } // 640 bytes = exactly 5 Apple M3 cache lines (128 bytes each), 128-byte aligned. // Line 0 (0..127): Count (4B) + pad (4B) + Keys[0..14] (120B) // Line 1 (128..255): Keys[15..30] (128B) // Line 2 (256..383): Children[0..31] (128B) -- all 32 child handles in 1 cache line! // Line 3 (384..511): Values[0..15] (128B) // Line 4 (512..639): Values[16..30] (120B) + pad (8B) // Hot traversal footprint (Keys + Children) = 384 bytes (3 cache lines). [StructLayout(LayoutKind.Explicit, Size = 640)] private struct InternalNode { [FieldOffset(0)] public int Count; [FieldOffset(8)] public fixed long Keys[MaxKeys]; [FieldOffset(256)] public fixed int Children[MaxChildren]; [FieldOffset(384)] public fixed long Values[MaxKeys]; } private struct RangeFrame { public int NodeId; public int Idx; public int Level; } private LeafNode* _leaves; private InternalNode* _internals; private int _root; private int _height; private int _count; private int _leafCap; private int _leafCount; private int _leafFree; private int _internalCap; private int _internalCount; private int _internalFree; public BTree() { _leaves = null; _internals = null; _leafCap = 0; _leafCount = 0; _leafFree = -1; _internalCap = 0; _internalCount = 0; _internalFree = -1; _root = -1; _height = 0; _count = 0; } ~BTree() { if (_leaves != null) { NativeMemory.AlignedFree(_leaves); _leaves = null; } if (_internals != null) { NativeMemory.AlignedFree(_internals); _internals = null; } } public int Count => _count; public int Height() => _height; // ------------------------------------------------------------ Pool management [MethodImpl(MethodImplOptions.AggressiveInlining)] private int AllocLeaf() { int free = _leafFree; if (free >= 0) { _leafFree = *(int*)(_leaves + (nuint)(uint)free); return free; } int id = _leafCount; if (id == _leafCap) { GrowLeaves(); } _leafCount = id + 1; return id; } [MethodImpl(MethodImplOptions.NoInlining)] private void GrowLeaves() { int newCap = _leafCap == 0 ? 16 : _leafCap * 2; nuint newBytes = (nuint)(uint)newCap * (nuint)sizeof(LeafNode); LeafNode* newBuf = (LeafNode*)NativeMemory.AlignedAlloc(newBytes, 128); if (_leaves != null) { nuint usedBytes = (nuint)(uint)_leafCount * (nuint)sizeof(LeafNode); Buffer.MemoryCopy(_leaves, newBuf, newBytes, usedBytes); NativeMemory.AlignedFree(_leaves); } _leaves = newBuf; _leafCap = newCap; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void FreeLeaf(int id) { *(int*)(_leaves + (nuint)(uint)id) = _leafFree; _leafFree = id; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private int AllocInternal() { int free = _internalFree; if (free >= 0) { _internalFree = *(int*)(_internals + (nuint)(uint)free); return free; } int id = _internalCount; if (id == _internalCap) { GrowInternals(); } _internalCount = id + 1; return id; } [MethodImpl(MethodImplOptions.NoInlining)] private void GrowInternals() { int newCap = _internalCap == 0 ? 8 : _internalCap * 2; nuint newBytes = (nuint)(uint)newCap * (nuint)sizeof(InternalNode); InternalNode* newBuf = (InternalNode*)NativeMemory.AlignedAlloc(newBytes, 128); if (_internals != null) { nuint usedBytes = (nuint)(uint)_internalCount * (nuint)sizeof(InternalNode); Buffer.MemoryCopy(_internals, newBuf, newBytes, usedBytes); NativeMemory.AlignedFree(_internals); } _internals = newBuf; _internalCap = newCap; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void FreeInternal(int id) { *(int*)(_internals + (nuint)(uint)id) = _internalFree; _internalFree = id; } // ------------------------------------------------------------ In-node search & copy helpers // Completely branchless lower bound for non-root nodes (15 <= count <= 31). // Returns smallest idx in [0, count] with idx == count || keys[idx] >= key. [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int LowerBoundNonRoot(long* keys, int count, long key) { int r = count - 15; int p = r > 0 ? r - 1 : 0; int lo = keys[p] < key ? r : 0; int c1 = lo + 8; lo = keys[lo + 7] < key ? c1 : lo; int c2 = lo + 4; lo = keys[lo + 3] < key ? c2 : lo; int c3 = lo + 2; lo = keys[lo + 1] < key ? c3 : lo; int c4 = lo + 1; lo = keys[lo] < key ? c4 : lo; return lo; } // Lower bound for any node (1 <= count <= 31). [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int LowerBoundAny(long* keys, int count, long key) { if (count >= 15) { return LowerBoundNonRoot(keys, count, key); } int lo = 0; int len = count; while (len > 1) { int half = len >> 1; int next = lo + (len - half); lo = keys[lo + half] < key ? next : lo; len = half; } int last = lo + 1; return keys[lo] < key ? last : lo; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void CopyLongs(long* dst, long* src, int count) { int i = 0; if (Vector.IsHardwareAccelerated) { int vCount = Vector.Count; int v2 = vCount * 2; while (i <= count - v2) { Unsafe.WriteUnaligned(dst + i, Unsafe.ReadUnaligned>(src + i)); Unsafe.WriteUnaligned(dst + i + vCount, Unsafe.ReadUnaligned>(src + i + vCount)); i += v2; } while (i <= count - vCount) { Unsafe.WriteUnaligned(dst + i, Unsafe.ReadUnaligned>(src + i)); i += vCount; } } for (; i < count; i++) { dst[i] = src[i]; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void CopyInts(int* dst, int* src, int count) { int i = 0; if (Vector.IsHardwareAccelerated) { int vCount = Vector.Count; int v2 = vCount * 2; while (i <= count - v2) { Unsafe.WriteUnaligned(dst + i, Unsafe.ReadUnaligned>(src + i)); Unsafe.WriteUnaligned(dst + i + vCount, Unsafe.ReadUnaligned>(src + i + vCount)); i += v2; } while (i <= count - vCount) { Unsafe.WriteUnaligned(dst + i, Unsafe.ReadUnaligned>(src + i)); i += vCount; } } for (; i < count; i++) { dst[i] = src[i]; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void ShiftRight1(long* arr, int idx, int count) { int i = count; if (Vector.IsHardwareAccelerated) { int vCount = Vector.Count; while (i >= idx + vCount) { i -= vCount; Unsafe.WriteUnaligned(arr + i + 1, Unsafe.ReadUnaligned>(arr + i)); } } while (i > idx) { arr[i] = arr[i - 1]; i--; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void ShiftRight1(int* arr, int idx, int count) { int i = count; if (Vector.IsHardwareAccelerated) { int vCount = Vector.Count; while (i >= idx + vCount) { i -= vCount; Unsafe.WriteUnaligned(arr + i + 1, Unsafe.ReadUnaligned>(arr + i)); } } while (i > idx) { arr[i] = arr[i - 1]; i--; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void ShiftLeft1(long* arr, int idx, int count) { int last = count - 1; int i = idx; if (Vector.IsHardwareAccelerated) { int vCount = Vector.Count; while (i <= last - vCount) { Unsafe.WriteUnaligned(arr + i, Unsafe.ReadUnaligned>(arr + i + 1)); i += vCount; } } for (; i < last; i++) { arr[i] = arr[i + 1]; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void ShiftLeft1(int* arr, int idx, int count) { int last = count - 1; int i = idx; if (Vector.IsHardwareAccelerated) { int vCount = Vector.Count; while (i <= last - vCount) { Unsafe.WriteUnaligned(arr + i, Unsafe.ReadUnaligned>(arr + i + 1)); i += vCount; } } for (; i < last; i++) { arr[i] = arr[i + 1]; } } // ------------------------------------------------------------ TryGet public bool TryGet(long key, out long value) { int h = _height; if (h == 0) { value = 0; return false; } int nodeId = _root; if (h == 1) { LeafNode* rootLeaf = _leaves + (nuint)(uint)nodeId; int c = rootLeaf->Count; long* k = rootLeaf->Keys; int idx = LowerBoundAny(k, c, key); if (idx < c && k[idx] == key) { value = rootLeaf->Values[idx]; return true; } value = 0; return false; } InternalNode* internals = _internals; // Root (level == h, count can be 1..31) { InternalNode* rootNode = internals + (nuint)(uint)nodeId; int c = rootNode->Count; long* k = rootNode->Keys; int idx = LowerBoundAny(k, c, key); if (idx < c && k[idx] == key) { value = rootNode->Values[idx]; return true; } nodeId = rootNode->Children[idx]; } // Non-root internal nodes (levels h-1 .. 2, count is 15..31) for (int level = h - 1; level > 1; level--) { InternalNode* node = internals + (nuint)(uint)nodeId; int c = node->Count; long* k = node->Keys; int idx = LowerBoundNonRoot(k, c, key); if (idx < c && k[idx] == key) { value = node->Values[idx]; return true; } nodeId = node->Children[idx]; } // Non-root leaf (level == 1, count is 15..31) { LeafNode* leaf = _leaves + (nuint)(uint)nodeId; int c = leaf->Count; long* k = leaf->Keys; int idx = LowerBoundNonRoot(k, c, key); if (idx < c && k[idx] == key) { value = leaf->Values[idx]; return true; } } value = 0; return false; } // ------------------------------------------------------------ Insert public bool Insert(long key, long value) { int h = _height; if (h == 0) { int rootId = AllocLeaf(); LeafNode* rootLeaf = _leaves + (nuint)(uint)rootId; rootLeaf->Count = 1; rootLeaf->Keys[0] = key; rootLeaf->Values[0] = value; _root = rootId; _height = 1; _count = 1; return true; } int* pathNodes = stackalloc int[MaxHeight]; int* pathIdx = stackalloc int[MaxHeight]; int depth = 0; int nodeId = _root; if (h > 1) { InternalNode* internals = _internals; // Root internal node { InternalNode* node = internals + (nuint)(uint)nodeId; int c = node->Count; long* k = node->Keys; int idx = LowerBoundAny(k, c, key); if (idx < c && k[idx] == key) { node->Values[idx] = value; return false; } pathNodes[0] = nodeId; pathIdx[0] = idx; depth = 1; nodeId = node->Children[idx]; } // Non-root internal nodes for (int level = h - 1; level > 1; level--) { InternalNode* node = internals + (nuint)(uint)nodeId; int c = node->Count; long* k = node->Keys; int idx = LowerBoundNonRoot(k, c, key); if (idx < c && k[idx] == key) { node->Values[idx] = value; return false; } pathNodes[depth] = nodeId; pathIdx[depth] = idx; depth++; nodeId = node->Children[idx]; } } // Leaf node LeafNode* leaf = _leaves + (nuint)(uint)nodeId; int leafCount = leaf->Count; long* leafKeys = leaf->Keys; int leafIdx = h == 1 ? LowerBoundAny(leafKeys, leafCount, key) : LowerBoundNonRoot(leafKeys, leafCount, key); if (leafIdx < leafCount && leafKeys[leafIdx] == key) { leaf->Values[leafIdx] = value; return false; } _count++; // Fast path: leaf has room if (leafCount < MaxKeys) { ShiftRight1(leafKeys, leafIdx, leafCount); ShiftRight1(leaf->Values, leafIdx, leafCount); leafKeys[leafIdx] = key; leaf->Values[leafIdx] = value; leaf->Count = leafCount + 1; return true; } // Slow path: split leaf and propagate upward InsertSplit(nodeId, leafIdx, key, value, pathNodes, pathIdx, depth); return true; } [MethodImpl(MethodImplOptions.NoInlining)] private void InsertSplit(int leafId, int leafIdx, long key, long value, int* pathNodes, int* pathIdx, int depth) { // Allocate right leaf first (may reallocate _leaves, so fetch pointers after!) int rightId = AllocLeaf(); LeafNode* left = _leaves + (nuint)(uint)leafId; LeafNode* right = _leaves + (nuint)(uint)rightId; long pKey, pVal; if (leafIdx < SplitLeft) { pKey = left->Keys[SplitLeft - 1]; pVal = left->Values[SplitLeft - 1]; CopyLongs(right->Keys, left->Keys + SplitLeft, SplitRight); CopyLongs(right->Values, left->Values + SplitLeft, SplitRight); ShiftRight1(left->Keys, leafIdx, SplitLeft - 1); ShiftRight1(left->Values, leafIdx, SplitLeft - 1); left->Keys[leafIdx] = key; left->Values[leafIdx] = value; } else if (leafIdx == SplitLeft) { pKey = key; pVal = value; CopyLongs(right->Keys, left->Keys + SplitLeft, SplitRight); CopyLongs(right->Values, left->Values + SplitLeft, SplitRight); } else { pKey = left->Keys[SplitLeft]; pVal = left->Values[SplitLeft]; int before = leafIdx - (SplitLeft + 1); if (before > 0) { CopyLongs(right->Keys, left->Keys + SplitLeft + 1, before); CopyLongs(right->Values, left->Values + SplitLeft + 1, before); } right->Keys[before] = key; right->Values[before] = value; int after = MaxKeys - leafIdx; if (after > 0) { CopyLongs(right->Keys + before + 1, left->Keys + leafIdx, after); CopyLongs(right->Values + before + 1, left->Values + leafIdx, after); } } left->Count = SplitLeft; right->Count = SplitRight; int pChild = rightId; int leftChild = leafId; // Propagate splits up through internal ancestors while (depth > 0) { depth--; int parentId = pathNodes[depth]; int idx = pathIdx[depth]; InternalNode* parent = _internals + (nuint)(uint)parentId; int count = parent->Count; if (count < MaxKeys) { ShiftRight1(parent->Keys, idx, count); ShiftRight1(parent->Values, idx, count); ShiftRight1(parent->Children, idx + 1, count + 1); parent->Keys[idx] = pKey; parent->Values[idx] = pVal; parent->Children[idx + 1] = pChild; parent->Count = count + 1; return; } // Parent is full: split internal node int rightIntId = AllocInternal(); parent = _internals + (nuint)(uint)parentId; InternalNode* rightInt = _internals + (nuint)(uint)rightIntId; long nextKey, nextVal; if (idx < SplitLeft) { nextKey = parent->Keys[SplitLeft - 1]; nextVal = parent->Values[SplitLeft - 1]; CopyLongs(rightInt->Keys, parent->Keys + SplitLeft, SplitRight); CopyLongs(rightInt->Values, parent->Values + SplitLeft, SplitRight); CopyInts(rightInt->Children, parent->Children + SplitLeft, SplitRight + 1); ShiftRight1(parent->Keys, idx, SplitLeft - 1); ShiftRight1(parent->Values, idx, SplitLeft - 1); ShiftRight1(parent->Children, idx + 1, SplitLeft); parent->Keys[idx] = pKey; parent->Values[idx] = pVal; parent->Children[idx + 1] = pChild; } else if (idx == SplitLeft) { nextKey = pKey; nextVal = pVal; CopyLongs(rightInt->Keys, parent->Keys + SplitLeft, SplitRight); CopyLongs(rightInt->Values, parent->Values + SplitLeft, SplitRight); rightInt->Children[0] = pChild; CopyInts(rightInt->Children + 1, parent->Children + SplitLeft + 1, SplitRight); } else { nextKey = parent->Keys[SplitLeft]; nextVal = parent->Values[SplitLeft]; int before = idx - (SplitLeft + 1); if (before > 0) { CopyLongs(rightInt->Keys, parent->Keys + SplitLeft + 1, before); CopyLongs(rightInt->Values, parent->Values + SplitLeft + 1, before); } rightInt->Keys[before] = pKey; rightInt->Values[before] = pVal; int after = MaxKeys - idx; if (after > 0) { CopyLongs(rightInt->Keys + before + 1, parent->Keys + idx, after); CopyLongs(rightInt->Values + before + 1, parent->Values + idx, after); } int childBefore = idx - SplitLeft; CopyInts(rightInt->Children, parent->Children + SplitLeft + 1, childBefore); rightInt->Children[childBefore] = pChild; if (after > 0) { CopyInts(rightInt->Children + childBefore + 1, parent->Children + idx + 1, after); } } parent->Count = SplitLeft; rightInt->Count = SplitRight; pKey = nextKey; pVal = nextVal; leftChild = parentId; pChild = rightIntId; } // Root split: create a new root internal node int newRootId = AllocInternal(); InternalNode* newRoot = _internals + (nuint)(uint)newRootId; newRoot->Count = 1; newRoot->Keys[0] = pKey; newRoot->Values[0] = pVal; newRoot->Children[0] = leftChild; newRoot->Children[1] = pChild; _root = newRootId; _height++; } // ------------------------------------------------------------ Remove public bool Remove(long key) { int h = _height; if (h == 0) { return false; } if (h == 1) { LeafNode* rootLeaf = _leaves + (nuint)(uint)_root; int c = rootLeaf->Count; long* k = rootLeaf->Keys; int idx = LowerBoundAny(k, c, key); if (idx >= c || k[idx] != key) { return false; } _count--; if (c == 1) { FreeLeaf(_root); _root = -1; _height = 0; return true; } ShiftLeft1(k, idx, c); ShiftLeft1(rootLeaf->Values, idx, c); rootLeaf->Count = c - 1; return true; } int* pathNodes = stackalloc int[MaxHeight]; int* pathIdx = stackalloc int[MaxHeight]; int depth = 0; int nodeId = _root; InternalNode* internals = _internals; // Descend through internal nodes for (int level = h; level > 1; level--) { InternalNode* node = internals + (nuint)(uint)nodeId; int c = node->Count; long* k = node->Keys; int idx = level == h ? LowerBoundAny(k, c, key) : LowerBoundNonRoot(k, c, key); if (idx < c && k[idx] == key) { // Key found in internal node: replace with in-order predecessor pathNodes[depth] = nodeId; pathIdx[depth] = idx; depth++; int currId = node->Children[idx]; for (int subLevel = level - 1; subLevel > 1; subLevel--) { InternalNode* sub = internals + (nuint)(uint)currId; int sc = sub->Count; pathNodes[depth] = currId; pathIdx[depth] = sc; depth++; currId = sub->Children[sc]; } LeafNode* predLeaf = _leaves + (nuint)(uint)currId; int plc = predLeaf->Count - 1; node->Keys[idx] = predLeaf->Keys[plc]; node->Values[idx] = predLeaf->Values[plc]; predLeaf->Count = plc; _count--; if (plc < MinKeys) { RebalanceFromLeaf(currId, pathNodes, pathIdx, depth); } return true; } pathNodes[depth] = nodeId; pathIdx[depth] = idx; depth++; nodeId = node->Children[idx]; } // Leaf node (non-root, since h > 1) LeafNode* leaf = _leaves + (nuint)(uint)nodeId; int leafCount = leaf->Count; long* leafKeys = leaf->Keys; int leafIdx = LowerBoundNonRoot(leafKeys, leafCount, key); if (leafIdx >= leafCount || leafKeys[leafIdx] != key) { return false; } _count--; ShiftLeft1(leafKeys, leafIdx, leafCount); ShiftLeft1(leaf->Values, leafIdx, leafCount); int newCount = leafCount - 1; leaf->Count = newCount; if (newCount < MinKeys) { RebalanceFromLeaf(nodeId, pathNodes, pathIdx, depth); } return true; } [MethodImpl(MethodImplOptions.NoInlining)] private void RebalanceFromLeaf(int leafId, int* pathNodes, int* pathIdx, int depth) { depth--; int parentId = pathNodes[depth]; int childIdx = pathIdx[depth]; InternalNode* parent = _internals + (nuint)(uint)parentId; LeafNode* curr = _leaves + (nuint)(uint)leafId; // Try borrowing from left sibling (equalize surplus) if (childIdx > 0) { int leftId = parent->Children[childIdx - 1]; LeafNode* left = _leaves + (nuint)(uint)leftId; int leftCount = left->Count; if (leftCount > MinKeys) { int move = (leftCount - (MinKeys - 1)) >> 1; // >= 1 int pIdx = childIdx - 1; // Shift curr right by move for (int i = MinKeys - 2; i >= 0; i--) { curr->Keys[i + move] = curr->Keys[i]; curr->Values[i + move] = curr->Values[i]; } curr->Keys[move - 1] = parent->Keys[pIdx]; curr->Values[move - 1] = parent->Values[pIdx]; int newLeftCount = leftCount - move; if (move > 1) { CopyLongs(curr->Keys, left->Keys + newLeftCount + 1, move - 1); CopyLongs(curr->Values, left->Values + newLeftCount + 1, move - 1); } parent->Keys[pIdx] = left->Keys[newLeftCount]; parent->Values[pIdx] = left->Values[newLeftCount]; left->Count = newLeftCount; curr->Count = (MinKeys - 1) + move; return; } } // Try borrowing from right sibling (equalize surplus), or merge with right sibling int parentCount = parent->Count; if (childIdx < parentCount) { int rightId = parent->Children[childIdx + 1]; LeafNode* right = _leaves + (nuint)(uint)rightId; int rightCount = right->Count; if (rightCount > MinKeys) { int move = (rightCount - (MinKeys - 1)) >> 1; // >= 1 curr->Keys[MinKeys - 1] = parent->Keys[childIdx]; curr->Values[MinKeys - 1] = parent->Values[childIdx]; if (move > 1) { CopyLongs(curr->Keys + MinKeys, right->Keys, move - 1); CopyLongs(curr->Values + MinKeys, right->Values, move - 1); } parent->Keys[childIdx] = right->Keys[move - 1]; parent->Values[childIdx] = right->Values[move - 1]; int remRight = rightCount - move; for (int i = 0; i < remRight; i++) { right->Keys[i] = right->Keys[i + move]; right->Values[i] = right->Values[i + move]; } curr->Count = (MinKeys - 1) + move; right->Count = remRight; return; } // Merge curr (14) + parent[childIdx] (1) + right (15) = 30 into curr curr->Keys[MinKeys - 1] = parent->Keys[childIdx]; curr->Values[MinKeys - 1] = parent->Values[childIdx]; CopyLongs(curr->Keys + MinKeys, right->Keys, rightCount); CopyLongs(curr->Values + MinKeys, right->Values, rightCount); curr->Count = MinKeys + rightCount; FreeLeaf(rightId); ShiftLeft1(parent->Keys, childIdx, parentCount); ShiftLeft1(parent->Values, childIdx, parentCount); ShiftLeft1(parent->Children, childIdx + 1, parentCount + 1); parent->Count = parentCount - 1; } else { // Merge left (15) + parent[childIdx - 1] (1) + curr (14) = 30 into left int pIdx = childIdx - 1; int leftId = parent->Children[pIdx]; LeafNode* left = _leaves + (nuint)(uint)leftId; int leftCount = left->Count; left->Keys[leftCount] = parent->Keys[pIdx]; left->Values[leftCount] = parent->Values[pIdx]; CopyLongs(left->Keys + leftCount + 1, curr->Keys, MinKeys - 1); CopyLongs(left->Values + leftCount + 1, curr->Values, MinKeys - 1); left->Count = leftCount + MinKeys; FreeLeaf(leafId); // childIdx == parentCount, so pIdx == parentCount - 1 (last key & child!) parent->Count = parentCount - 1; leafId = leftId; // survivor if root shrinks } // Check if parent underflowed (or if root became empty) if (depth == 0) { if (parent->Count == 0) { FreeInternal(parentId); _root = leafId; _height--; } return; } if (parent->Count < MinKeys) { RebalanceInternal(parentId, pathNodes, pathIdx, depth); } } private void RebalanceInternal(int nodeId, int* pathNodes, int* pathIdx, int depth) { InternalNode* internals = _internals; while (depth > 0) { depth--; int parentId = pathNodes[depth]; int childIdx = pathIdx[depth]; InternalNode* parent = internals + (nuint)(uint)parentId; InternalNode* curr = internals + (nuint)(uint)nodeId; // Try borrowing from left internal sibling if (childIdx > 0) { int leftId = parent->Children[childIdx - 1]; InternalNode* left = internals + (nuint)(uint)leftId; int leftCount = left->Count; if (leftCount > MinKeys) { int move = (leftCount - (MinKeys - 1)) >> 1; int pIdx = childIdx - 1; for (int i = MinKeys - 2; i >= 0; i--) { curr->Keys[i + move] = curr->Keys[i]; curr->Values[i + move] = curr->Values[i]; } for (int i = MinKeys - 1; i >= 0; i--) { curr->Children[i + move] = curr->Children[i]; } curr->Keys[move - 1] = parent->Keys[pIdx]; curr->Values[move - 1] = parent->Values[pIdx]; int newLeftCount = leftCount - move; if (move > 1) { CopyLongs(curr->Keys, left->Keys + newLeftCount + 1, move - 1); CopyLongs(curr->Values, left->Values + newLeftCount + 1, move - 1); } CopyInts(curr->Children, left->Children + newLeftCount + 1, move); parent->Keys[pIdx] = left->Keys[newLeftCount]; parent->Values[pIdx] = left->Values[newLeftCount]; left->Count = newLeftCount; curr->Count = (MinKeys - 1) + move; return; } } // Try borrowing from right internal sibling, or merge int parentCount = parent->Count; if (childIdx < parentCount) { int rightId = parent->Children[childIdx + 1]; InternalNode* right = internals + (nuint)(uint)rightId; int rightCount = right->Count; if (rightCount > MinKeys) { int move = (rightCount - (MinKeys - 1)) >> 1; curr->Keys[MinKeys - 1] = parent->Keys[childIdx]; curr->Values[MinKeys - 1] = parent->Values[childIdx]; if (move > 1) { CopyLongs(curr->Keys + MinKeys, right->Keys, move - 1); CopyLongs(curr->Values + MinKeys, right->Values, move - 1); } CopyInts(curr->Children + MinKeys, right->Children, move); parent->Keys[childIdx] = right->Keys[move - 1]; parent->Values[childIdx] = right->Values[move - 1]; int remRight = rightCount - move; for (int i = 0; i < remRight; i++) { right->Keys[i] = right->Keys[i + move]; right->Values[i] = right->Values[i + move]; } for (int i = 0; i <= remRight; i++) { right->Children[i] = right->Children[i + move]; } curr->Count = (MinKeys - 1) + move; right->Count = remRight; return; } // Merge curr (14) + parent[childIdx] (1) + right (15) into curr curr->Keys[MinKeys - 1] = parent->Keys[childIdx]; curr->Values[MinKeys - 1] = parent->Values[childIdx]; CopyLongs(curr->Keys + MinKeys, right->Keys, rightCount); CopyLongs(curr->Values + MinKeys, right->Values, rightCount); CopyInts(curr->Children + MinKeys, right->Children, rightCount + 1); curr->Count = MinKeys + rightCount; FreeInternal(rightId); ShiftLeft1(parent->Keys, childIdx, parentCount); ShiftLeft1(parent->Values, childIdx, parentCount); ShiftLeft1(parent->Children, childIdx + 1, parentCount + 1); parent->Count = parentCount - 1; } else { // Merge left (15) + parent[childIdx - 1] (1) + curr (14) into left int pIdx = childIdx - 1; int leftId = parent->Children[pIdx]; InternalNode* left = internals + (nuint)(uint)leftId; int leftCount = left->Count; left->Keys[leftCount] = parent->Keys[pIdx]; left->Values[leftCount] = parent->Values[pIdx]; CopyLongs(left->Keys + leftCount + 1, curr->Keys, MinKeys - 1); CopyLongs(left->Values + leftCount + 1, curr->Values, MinKeys - 1); CopyInts(left->Children + leftCount + 1, curr->Children, MinKeys); left->Count = leftCount + MinKeys; FreeInternal(nodeId); parent->Count = parentCount - 1; nodeId = leftId; } if (depth == 0) { if (parent->Count == 0) { FreeInternal(parentId); _root = nodeId; _height--; } return; } if (parent->Count >= MinKeys) { return; } nodeId = parentId; } } // ------------------------------------------------------------ Range public int Range(long lo, long hi, long[] outKeys, long[] outVals, int limit) { int h = _height; if (limit <= 0 || lo > hi || h == 0) { return 0; } fixed (long* dstKeys = outKeys) fixed (long* dstVals = outVals) { if (h == 1) { LeafNode* rootLeaf = _leaves + (nuint)(uint)_root; int c = rootLeaf->Count; long* k = rootLeaf->Keys; int start = LowerBoundAny(k, c, lo); int avail = c - start; if (avail <= 0) return 0; if (avail <= limit && k[c - 1] <= hi) { CopyLongs(dstKeys, k + start, avail); CopyLongs(dstVals, rootLeaf->Values + start, avail); return avail; } int written1 = 0; int end = start + (avail < limit ? avail : limit); long* v = rootLeaf->Values; for (int i = start; i < end; i++) { long key = k[i]; if (key > hi) break; dstKeys[written1] = key; dstVals[written1] = v[i]; written1++; } return written1; } RangeFrame* stack = stackalloc RangeFrame[MaxHeight]; int sp = 0; int nodeId = _root; InternalNode* internals = _internals; bool exactLoInInternal = false; // Descend to lo for (int level = h; level > 1; level--) { InternalNode* node = internals + (nuint)(uint)nodeId; int c = node->Count; long* k = node->Keys; int idx = level == h ? LowerBoundAny(k, c, lo) : LowerBoundNonRoot(k, c, lo); if (idx < c) { stack[sp].NodeId = nodeId; stack[sp].Idx = idx; stack[sp].Level = level; sp++; if (k[idx] == lo) { exactLoInInternal = true; break; } } nodeId = node->Children[idx]; } int written = 0; LeafNode* leaves = _leaves; // Process first leaf (unless lo matched an internal key exactly) if (!exactLoInInternal) { LeafNode* leaf = leaves + (nuint)(uint)nodeId; int c = leaf->Count; long* k = leaf->Keys; int start = LowerBoundNonRoot(k, c, lo); int avail = c - start; if (avail > 0) { long lastKey = k[c - 1]; if (avail <= limit && lastKey <= hi) { CopyLongs(dstKeys, k + start, avail); CopyLongs(dstVals, leaf->Values + start, avail); written = avail; if (written == limit || lastKey == hi) { return written; } } else { int end = start + (avail < limit ? avail : limit); long* v = leaf->Values; for (int i = start; i < end; i++) { long key = k[i]; if (key > hi) return written; dstKeys[written] = key; dstVals[written] = v[i]; written++; } return written; } } } // Unwind ancestor stack, emitting separator keys and right subtrees while (sp > 0) { sp--; InternalNode* node = internals + (nuint)(uint)stack[sp].NodeId; int idx = stack[sp].Idx; int level = stack[sp].Level; int c = node->Count; long* nk = node->Keys; long* nv = node->Values; int* nc = node->Children; if (level == 2) { // Children are leaves: inline bulk copy for (; idx < c; idx++) { long sepKey = nk[idx]; if (sepKey > hi) return written; dstKeys[written] = sepKey; dstVals[written] = nv[idx]; written++; if (written == limit || sepKey == hi) return written; LeafNode* leaf = leaves + (nuint)(uint)nc[idx + 1]; int lc = leaf->Count; long* lk = leaf->Keys; int rem = limit - written; long lastKey = lk[lc - 1]; if (lc <= rem && lastKey <= hi) { CopyLongs(dstKeys + written, lk, lc); CopyLongs(dstVals + written, leaf->Values, lc); written += lc; if (written == limit || lastKey == hi) return written; } else { int end = lc < rem ? lc : rem; long* lv = leaf->Values; for (int j = 0; j < end; j++) { long key = lk[j]; if (key > hi) return written; dstKeys[written] = key; dstVals[written] = lv[j]; written++; } return written; } } } else { for (; idx < c; idx++) { long sepKey = nk[idx]; if (sepKey > hi) return written; dstKeys[written] = sepKey; dstVals[written] = nv[idx]; written++; if (written == limit || sepKey == hi) return written; if (RangeSubtree(nc[idx + 1], level - 1, hi, dstKeys, dstVals, ref written, limit)) { return written; } } } } return written; } } // Emit entries from an entire subtree whose keys are all > lo, stopping at hi or limit. // Returns true if hi or limit was reached (caller should stop immediately). private bool RangeSubtree(int nodeId, int level, long hi, long* dstKeys, long* dstVals, ref int written, int limit) { InternalNode* node = _internals + (nuint)(uint)nodeId; int c = node->Count; long* nk = node->Keys; long* nv = node->Values; int* nc = node->Children; if (level == 2) { LeafNode* leaves = _leaves; int w = written; for (int i = 0; ; i++) { LeafNode* leaf = leaves + (nuint)(uint)nc[i]; int lc = leaf->Count; long* lk = leaf->Keys; int rem = limit - w; long lastKey = lk[lc - 1]; if (lc <= rem && lastKey <= hi) { CopyLongs(dstKeys + w, lk, lc); CopyLongs(dstVals + w, leaf->Values, lc); w += lc; if (w == limit || lastKey == hi) { written = w; return true; } } else { int end = lc < rem ? lc : rem; long* lv = leaf->Values; for (int j = 0; j < end; j++) { long key = lk[j]; if (key > hi) { written = w; return true; } dstKeys[w] = key; dstVals[w] = lv[j]; w++; } written = w; return true; } if (i == c) { written = w; return false; } long sepKey = nk[i]; if (sepKey > hi) { written = w; return true; } dstKeys[w] = sepKey; dstVals[w] = nv[i]; w++; if (w == limit || sepKey == hi) { written = w; return true; } } } for (int i = 0; ; i++) { if (RangeSubtree(nc[i], level - 1, hi, dstKeys, dstVals, ref written, limit)) { return true; } if (i == c) { return false; } long sepKey = nk[i]; if (sepKey > hi) { return true; } int w = written; dstKeys[w] = sepKey; dstVals[w] = nv[i]; w++; written = w; if (w == limit || sepKey == hi) { return true; } } } }