using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [SkipLocalsInit] public sealed unsafe class RBTree { private const int InitialChunkNodes = 64; private const int MaxChunkNodes = 262_144; // 8 MiB per chunk (262144 * 32 bytes) [StructLayout(LayoutKind.Sequential)] private struct Node { public long Key; // offset 0 public nuint Left; // offset 8: bit 0 = isRed (1 = red, 0 = black), upper bits = Node* public Node* Right; // offset 16 public long Value; // offset 24 } private Node* _root; private Node* _freeHead; private Node* _bumpCur; private Node* _bumpEnd; private int _count; // Cold chunk tracking fields (only touched on chunk allocation and finalization) private void** _chunks; private int _chunkCount; private int _chunkCap; private int _nextChunkNodes; public RBTree() { _nextChunkNodes = InitialChunkNodes; } ~RBTree() { void** 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; } } public int Count { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => _count; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private Node* AllocNode() { Node* node = _freeHead; if (node != null) { _freeHead = node->Right; return node; } node = _bumpCur; if (node != _bumpEnd) { _bumpCur = node + 1; return node; } return AllocFromNewChunk(); } [MethodImpl(MethodImplOptions.NoInlining)] private Node* AllocFromNewChunk() { if (_chunkCount == _chunkCap) { int newCap = _chunkCap == 0 ? 32 : _chunkCap * 2; void** newChunks = (void**)NativeMemory.Alloc((nuint)newCap * (nuint)sizeof(void*)); void** oldChunks = _chunks; if (oldChunks != null) { int oldCount = _chunkCount; for (int i = 0; i < oldCount; i++) { newChunks[i] = oldChunks[i]; } NativeMemory.Free(oldChunks); } _chunks = newChunks; _chunkCap = newCap; } int n = _nextChunkNodes; Node* chunk = (Node*)NativeMemory.AlignedAlloc((nuint)n * (nuint)sizeof(Node), 128); _chunks[_chunkCount++] = chunk; if (n < MaxChunkNodes) { _nextChunkNodes = n << 1; } _bumpCur = chunk + 1; _bumpEnd = chunk + n; return chunk; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool TryGet(long key, out long value) { Node* cur = _root; while (cur != null) { long k = cur->Key; nuint left = cur->Left & ~(nuint)1; nuint right = (nuint)cur->Right; if (key == k) { value = cur->Value; return true; } cur = (Node*)(key < k ? left : right); } value = 0; return false; } public bool Insert(long key, long value) { Node* cur = _root; if (cur == null) { Node* n = AllocNode(); n->Key = key; n->Value = value; n->Left = 0; // black, null left n->Right = null; _root = n; _count = 1; return true; } Node** path = stackalloc Node*[68]; int depth = 0; ulong dirs = 0; while (true) { long k = cur->Key; if (key == k) { cur->Value = value; return false; } path[depth++] = cur; nuint left = cur->Left & ~(nuint)1; nuint right = (nuint)cur->Right; bool goRight = key > k; dirs = (dirs << 1) | (goRight ? 1UL : 0UL); Node* next = (Node*)(goRight ? right : left); if (next == null) { break; } cur = next; } Node* node = AllocNode(); node->Key = key; node->Value = value; node->Left = 1; // red, null left node->Right = null; _count++; // cur == path[depth - 1] is parent if ((dirs & 1) != 0) { cur->Right = node; } else { // cur's left pointer was null (cur->Left is 0 or 1), so OR preserves color cur->Left |= (nuint)node; } // Fast exit: parent is black if ((cur->Left & 1) == 0) { return true; } // Rebalance upward: `node` is red, `parent` (cur) is red, so `gp` exists and is black. Node* parent = cur; while (true) { Node* gp = path[depth - 2]; if ((dirs & 2) == 0) { // parent is left child of gp Node* uncle = gp->Right; if (uncle != null && (uncle->Left & 1) != 0) { // Case 1: uncle is red -> recolor and move up 2 levels parent->Left &= ~(nuint)1; uncle->Left &= ~(nuint)1; gp->Left |= 1; depth -= 2; if (depth == 0) { gp->Left &= ~(nuint)1; // root is always black return true; } dirs >>= 2; parent = path[depth - 1]; if ((parent->Left & 1) == 0) { return true; } node = gp; } else { Node* newSub; if ((dirs & 1) != 0) { // Case 2 (LR): fused left-right double rotation Node* b = (Node*)(node->Left & ~(nuint)1); Node* c = node->Right; parent->Right = b; gp->Left = (nuint)c | 1; // gp becomes red node->Left = (nuint)parent; // node becomes black node->Right = gp; newSub = node; } else { // Case 3 (LL): single right rotation at gp Node* b = parent->Right; gp->Left = (nuint)b | 1; // gp becomes red parent->Left &= ~(nuint)1; // parent becomes black parent->Right = gp; newSub = parent; } if (depth == 2) { _root = newSub; } else { Node* ggp = path[depth - 3]; if ((dirs & 4) != 0) { ggp->Right = newSub; } else { ggp->Left = (ggp->Left & 1) | (nuint)newSub; } } return true; } } else { // parent is right child of gp Node* uncle = (Node*)(gp->Left & ~(nuint)1); if (uncle != null && (uncle->Left & 1) != 0) { // Case 1: uncle is red -> recolor and move up 2 levels parent->Left &= ~(nuint)1; uncle->Left &= ~(nuint)1; gp->Left |= 1; depth -= 2; if (depth == 0) { gp->Left &= ~(nuint)1; // root is always black return true; } dirs >>= 2; parent = path[depth - 1]; if ((parent->Left & 1) == 0) { return true; } node = gp; } else { Node* newSub; if ((dirs & 1) == 0) { // Case 2 (RL): fused right-left double rotation Node* a = (Node*)(node->Left & ~(nuint)1); Node* b = node->Right; gp->Right = a; gp->Left |= 1; // gp becomes red parent->Left = (nuint)b | 1; // parent stays red node->Left = (nuint)gp; // node becomes black node->Right = parent; newSub = node; } else { // Case 3 (RR): single left rotation at gp Node* b = (Node*)(parent->Left & ~(nuint)1); gp->Right = b; gp->Left |= 1; // gp becomes red parent->Left = (nuint)gp; // parent becomes black newSub = parent; } if (depth == 2) { _root = newSub; } else { Node* ggp = path[depth - 3]; if ((dirs & 4) != 0) { ggp->Right = newSub; } else { ggp->Left = (ggp->Left & 1) | (nuint)newSub; } } return true; } } } } public bool Remove(long key) { Node* cur = _root; if (cur == null) { return false; } Node** path = stackalloc Node*[68]; int depth = 0; ulong dirs = 0; while (true) { long k = cur->Key; if (key == k) { break; } path[depth++] = cur; nuint left = cur->Left & ~(nuint)1; nuint right = (nuint)cur->Right; bool goRight = key > k; dirs = (dirs << 1) | (goRight ? 1UL : 0UL); cur = (Node*)(goRight ? right : left); if (cur == null) { return false; } } Node* leftChild = (Node*)(cur->Left & ~(nuint)1); Node* rightChild = cur->Right; Node* x; if (leftChild != null && rightChild != null) { Node* target = cur; path[depth++] = cur; dirs = (dirs << 1) | 1UL; cur = rightChild; while (true) { Node* l = (Node*)(cur->Left & ~(nuint)1); if (l == null) { break; } path[depth++] = cur; dirs <<= 1; cur = l; } target->Key = cur->Key; target->Value = cur->Value; x = cur->Right; } else { x = leftChild != null ? leftChild : rightChild; } bool removedRed = (cur->Left & 1) != 0; cur->Right = _freeHead; _freeHead = cur; _count--; if (depth == 0) { _root = x; if (x != null) { x->Left &= ~(nuint)1; } return true; } Node* parent = path[depth - 1]; if ((dirs & 1) != 0) { parent->Right = x; } else { parent->Left = (parent->Left & 1) | (nuint)x; } if (removedRed) { return true; } if (x != null && (x->Left & 1) != 0) { x->Left &= ~(nuint)1; return true; } // Double-black fixup while (true) { parent = path[depth - 1]; if ((dirs & 1) == 0) { // Double-black is parent's left child Node* w = parent->Right; if ((w->Left & 1) != 0) { // Case 1: sibling w is red Node* wLeft = (Node*)(w->Left & ~(nuint)1); parent->Right = wLeft; parent->Left |= 1; // parent becomes red w->Left = (nuint)parent; // w becomes black if (depth == 1) { _root = w; } else { Node* gp = path[depth - 2]; if ((dirs & 2) != 0) { gp->Right = w; } else { gp->Left = (gp->Left & 1) | (nuint)w; } } path[depth - 1] = w; path[depth] = parent; depth++; dirs <<= 1; w = wLeft; } Node* wr = w->Right; if (wr != null && (wr->Left & 1) != 0) { // Case 4: w's right child is red -> left rotate at parent (no need to dereference wl) nuint parentColor = parent->Left & 1; Node* wl = (Node*)(w->Left & ~(nuint)1); parent->Right = wl; parent->Left &= ~(nuint)1; // parent becomes black w->Left = (nuint)parent | parentColor; wr->Left &= ~(nuint)1; // wr becomes black if (depth == 1) { _root = w; } else { Node* gp = path[depth - 2]; if ((dirs & 2) != 0) { gp->Right = w; } else { gp->Left = (gp->Left & 1) | (nuint)w; } } return true; } Node* wLeftNode = (Node*)(w->Left & ~(nuint)1); if (wLeftNode != null && (wLeftNode->Left & 1) != 0) { // Case 3+4: fused right-left double rotation nuint parentColor = parent->Left & 1; Node* a = (Node*)(wLeftNode->Left & ~(nuint)1); Node* b = wLeftNode->Right; parent->Right = a; parent->Left &= ~(nuint)1; // parent becomes black w->Left = (nuint)b; // w stays black wLeftNode->Left = (nuint)parent | parentColor; wLeftNode->Right = w; if (depth == 1) { _root = wLeftNode; } else { Node* gp = path[depth - 2]; if ((dirs & 2) != 0) { gp->Right = wLeftNode; } else { gp->Left = (gp->Left & 1) | (nuint)wLeftNode; } } return true; } // Case 2: both of w's children are black w->Left |= 1; // w becomes red if ((parent->Left & 1) != 0) { parent->Left &= ~(nuint)1; return true; } depth--; if (depth == 0) { return true; } dirs >>= 1; } else { // Double-black is parent's right child Node* w = (Node*)(parent->Left & ~(nuint)1); if ((w->Left & 1) != 0) { // Case 1: sibling w is red Node* wRight = w->Right; parent->Left = (nuint)wRight | 1; // parent becomes red w->Left &= ~(nuint)1; // w becomes black w->Right = parent; if (depth == 1) { _root = w; } else { Node* gp = path[depth - 2]; if ((dirs & 2) != 0) { gp->Right = w; } else { gp->Left = (gp->Left & 1) | (nuint)w; } } path[depth - 1] = w; path[depth] = parent; depth++; dirs = (dirs << 1) | 1UL; w = wRight; } Node* wl = (Node*)(w->Left & ~(nuint)1); if (wl != null && (wl->Left & 1) != 0) { // Case 4: w's left child is red -> right rotate at parent (no need to dereference wr) nuint parentColor = parent->Left & 1; Node* wr = w->Right; parent->Left = (nuint)wr; // parent becomes black w->Left = (nuint)wl | parentColor; w->Right = parent; wl->Left &= ~(nuint)1; // wl becomes black if (depth == 1) { _root = w; } else { Node* gp = path[depth - 2]; if ((dirs & 2) != 0) { gp->Right = w; } else { gp->Left = (gp->Left & 1) | (nuint)w; } } return true; } Node* wRightNode = w->Right; if (wRightNode != null && (wRightNode->Left & 1) != 0) { // Case 3+4: fused left-right double rotation nuint parentColor = parent->Left & 1; Node* a = (Node*)(wRightNode->Left & ~(nuint)1); Node* b = wRightNode->Right; parent->Left = (nuint)b; // parent becomes black w->Right = a; // w stays black wRightNode->Left = (nuint)w | parentColor; wRightNode->Right = parent; if (depth == 1) { _root = wRightNode; } else { Node* gp = path[depth - 2]; if ((dirs & 2) != 0) { gp->Right = wRightNode; } else { gp->Left = (gp->Left & 1) | (nuint)wRightNode; } } return true; } // Case 2: both of w's children are black w->Left |= 1; // w becomes red if ((parent->Left & 1) != 0) { parent->Left &= ~(nuint)1; return true; } depth--; if (depth == 0) { return true; } dirs >>= 1; } } } public int Range(long lo, long hi, long[] outKeys, long[] outVals, int limit) { Node* cur = _root; if (cur == null || limit <= 0 || lo > hi) { return 0; } if ((uint)limit > (uint)outKeys.Length || (uint)limit > (uint)outVals.Length) { throw new ArgumentOutOfRangeException(nameof(limit)); } Node** stack = stackalloc Node*[68]; int sp = 0; ulong span = unchecked((ulong)(hi - lo)); while (cur != null) { long k = cur->Key; nuint left = cur->Left & ~(nuint)1; nuint right = (nuint)cur->Right; if (unchecked((ulong)(k - lo)) <= span) { stack[sp++] = cur; if (k == lo) { break; } } cur = (Node*)(k < lo ? right : left); } if (sp == 0) { return 0; } int count = 0; ref long keysRef = ref MemoryMarshal.GetArrayDataReference(outKeys); ref long valsRef = ref MemoryMarshal.GetArrayDataReference(outVals); cur = stack[--sp]; while (true) { long k = cur->Key; if (k > hi) { break; } Unsafe.Add(ref keysRef, count) = k; Unsafe.Add(ref valsRef, count) = cur->Value; if (++count == limit) { break; } Node* r = cur->Right; if (r != null) { cur = r; while (true) { Node* l = (Node*)(cur->Left & ~(nuint)1); if (l == null) { break; } stack[sp++] = cur; cur = l; } } else { if (sp == 0) { break; } cur = stack[--sp]; } } return count; } public int Height() { return HeightOf(_root); } private static int HeightOf(Node* n) { if (n == null) { return 0; } int lh = HeightOf((Node*)(n->Left & ~(nuint)1)); int rh = HeightOf(n->Right); return (lh > rh ? lh : rh) + 1; } }