using System; using System.Numerics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Radix tree (path-compressed byte trie) stored in one native arena. // // Every node is one variable-sized block in the arena, addressed by a uint // offset counted in 8-byte words. Block layout: // [0..8) long value // [8..12) int number of keys in the subtree (node included) // [12] byte label length (0 only for the root) // [13] byte block size in words // [14..16) ushort bits 0..8: child count, bit 15: node holds a key // [16..) label bytes, then the sorted first bytes of the children // ... (free space) // end-4*(j+1) uint offset of child j (child offsets grow backwards // from the end of the block) // The arena only grows (by realloc) at the start of Insert/Remove, which // reserve enough room for the whole operation, so raw pointers stay valid // for the duration of one operation. Freed blocks go to exact-size free lists. [SkipLocalsInit] public sealed unsafe class RadixTree { const int HDR = 16; const int PAD_WORDS = 64; const ulong RESERVE_WORDS = 1024; const int HASVAL = 0x8000; const int NCH_MASK = 0x1FF; const int MAX_DEPTH = 260; byte* _base; ulong _capWords; ulong _top; uint* _free; uint _root; int _count; public RadixTree() { _capWords = 1UL << 15; _base = (byte*)NativeMemory.Alloc((nuint)((_capWords + PAD_WORDS) * 8)); _free = (uint*)NativeMemory.AllocZeroed(256, sizeof(uint)); _top = 1; // offset 0 is reserved as null int w = (HDR + 256 * 5 + 7) >> 3; // the root has room for all 256 children _root = Alloc(w); byte* r = _base + (ulong)_root * 8; *(long*)r = 0; *(int*)(r + 8) = 0; r[12] = 0; r[13] = (byte)w; *(ushort*)(r + 14) = 0; } ~RadixTree() { if (_base != null) { NativeMemory.Free(_base); _base = null; } if (_free != null) { NativeMemory.Free(_free); _free = null; } } public int Count => _count; // ------------------------------------------------------------ memory [MethodImpl(MethodImplOptions.AggressiveInlining)] void Reserve() { if (_top + RESERVE_WORDS > _capWords) Grow(); } [MethodImpl(MethodImplOptions.NoInlining)] void Grow() { ulong nc = _capWords * 2; while (_top + RESERVE_WORDS > nc) nc *= 2; _base = (byte*)NativeMemory.Realloc(_base, (nuint)((nc + PAD_WORDS) * 8)); _capWords = nc; } [MethodImpl(MethodImplOptions.AggressiveInlining)] uint Alloc(int w) { uint h = _free[w]; if (h != 0) { _free[w] = *(uint*)(_base + (ulong)h * 8); return h; } uint o = (uint)_top; _top += (ulong)w; return o; } [MethodImpl(MethodImplOptions.AggressiveInlining)] void Free(byte* n) { uint off = (uint)((ulong)(n - _base) >> 3); int w = n[13]; *(uint*)n = _free[w]; _free[w] = off; } // ------------------------------------------------------------ helpers // Index of byte c among the n child first bytes, or -1. May read up to // 7 bytes past the keys; those bytes are inside the arena (padded). [MethodImpl(MethodImplOptions.AggressiveInlining)] static int Find(byte* keys, int n, byte c) { ulong pat = c * 0x0101010101010101UL; for (int j = 0; j < n; j += 8) { ulong x = *(ulong*)(keys + j) ^ pat; ulong t = (x - 0x0101010101010101UL) & ~x & 0x8080808080808080UL; if (t != 0) { int idx = j + (BitOperations.TrailingZeroCount(t) >> 3); return idx < n ? idx : -1; } } return -1; } [MethodImpl(MethodImplOptions.AggressiveInlining)] static bool Eq(byte* a, byte* b, int n) { if (n >= 8) { for (; n > 8; n -= 8, a += 8, b += 8) { if (*(ulong*)a != *(ulong*)b) return false; } return *(ulong*)(a + n - 8) == *(ulong*)(b + n - 8); } if (n >= 4) return *(uint*)a == *(uint*)b && *(uint*)(a + n - 4) == *(uint*)(b + n - 4); if (n >= 2) return *(ushort*)a == *(ushort*)b && *(ushort*)(a + n - 2) == *(ushort*)(b + n - 2); if (n == 1) return *a == *b; return true; } // First index < n where a and b differ, or n. [MethodImpl(MethodImplOptions.AggressiveInlining)] static int Mismatch(byte* a, byte* b, int n) { int i = 0; for (; i + 8 <= n; i += 8) { ulong x = *(ulong*)(a + i) ^ *(ulong*)(b + i); if (x != 0) return i + (BitOperations.TrailingZeroCount(x) >> 3); } for (; i < n; i++) { if (a[i] != b[i]) return i; } return n; } [MethodImpl(MethodImplOptions.AggressiveInlining)] static uint* EndOf(byte* n) => (uint*)(n + ((uint)n[13] << 3)); uint NewLeaf(byte* src, int l, long value) { int w = (HDR + l + 7) >> 3; uint o = Alloc(w); byte* n = _base + (ulong)o * 8; *(long*)n = value; *(int*)(n + 8) = 1; n[12] = (byte)l; n[13] = (byte)w; *(ushort*)(n + 14) = HASVAL; Unsafe.CopyBlockUnaligned(n + HDR, src, (uint)l); return o; } // Add child `child` with first byte c (absent) to node n, whose offset // is stored at *slot (slot is null only for the root, which never grows). void AddChild(byte* n, uint* slot, byte c, uint child) { int ll = n[12]; int f = *(ushort*)(n + 14); int nc = f & NCH_MASK; int sz = n[13] << 3; byte* keys = n + HDR + ll; int pos = 0; while (pos < nc && keys[pos] < c) pos++; uint* e = (uint*)(n + sz); if (HDR + ll + (nc + 1) * 5 <= sz) { for (int j = nc; j > pos; j--) keys[j] = keys[j - 1]; for (int j = nc - 1; j >= pos; j--) e[-2 - j] = e[-1 - j]; keys[pos] = c; e[-1 - pos] = child; *(ushort*)(n + 14) = (ushort)(f + 1); return; } int cap = nc + (nc >> 1) + 1; if (cap < 2) cap = 2; if (cap > 256) cap = 256; int w = (HDR + ll + cap * 5 + 7) >> 3; uint no = Alloc(w); byte* nn = _base + (ulong)no * 8; Unsafe.CopyBlockUnaligned(nn, n, (uint)(HDR + ll)); nn[13] = (byte)w; *(ushort*)(nn + 14) = (ushort)(f + 1); byte* nk = nn + HDR + ll; uint* ne = (uint*)(nn + (w << 3)); for (int j = 0; j < pos; j++) { nk[j] = keys[j]; ne[-1 - j] = e[-1 - j]; } nk[pos] = c; ne[-1 - pos] = child; for (int j = pos; j < nc; j++) { nk[j + 1] = keys[j]; ne[-2 - j] = e[-1 - j]; } Free(n); *slot = no; } // Node x (not the root) holds no key and has exactly one child: merge it // into that child. *slotX is where x's offset is stored in its parent. void Merge(byte* x, uint* slotX) { byte* b = _base; uint cOff = *(EndOf(x) - 1); byte* c = b + (ulong)cOff * 8; int xl = x[12], cl = c[12]; int nl = xl + cl; int cn = *(ushort*)(c + 14) & NCH_MASK; int need = HDR + nl + cn; if (need + cn * 4 <= (c[13] << 3)) { // room in place: shift label and keys right, prepend x's label byte* p = c + HDR; for (int j = cl + cn - 1; j >= 0; j--) p[j + xl] = p[j]; Unsafe.CopyBlockUnaligned(p, x + HDR, (uint)xl); c[12] = (byte)nl; *slotX = cOff; } else { int w = (need + cn * 4 + 7) >> 3; uint no = Alloc(w); byte* nn = b + (ulong)no * 8; Unsafe.CopyBlockUnaligned(nn, c, HDR); nn[12] = (byte)nl; nn[13] = (byte)w; Unsafe.CopyBlockUnaligned(nn + HDR, x + HDR, (uint)xl); Unsafe.CopyBlockUnaligned(nn + HDR + xl, c + HDR, (uint)(cl + cn)); uint* ce = EndOf(c); uint* ne = (uint*)(nn + (w << 3)); Unsafe.CopyBlockUnaligned(ne - cn, ce - cn, (uint)(cn * 4)); Free(c); *slotX = no; } Free(x); } // ------------------------------------------------------------ operations public bool Insert(ReadOnlySpan key, long value) { Reserve(); byte* b = _base; int len = key.Length; byte** path = stackalloc byte*[MAX_DEPTH]; fixed (byte* k = key) { byte* n = b + (ulong)_root * 8; uint* slot = null; int d = 0; int i = 0; while (true) { path[d++] = n; int f = *(ushort*)(n + 14); if (i == len) { *(long*)n = value; if ((f & HASVAL) != 0) return false; *(ushort*)(n + 14) = (ushort)(f | HASVAL); for (int j = 0; j < d; j++) (*(int*)(path[j] + 8))++; _count++; return true; } byte c = k[i]; int idx = Find(n + HDR + n[12], f & NCH_MASK, c); if (idx < 0) { for (int j = 0; j < d; j++) (*(int*)(path[j] + 8))++; _count++; uint leaf = NewLeaf(k + i, len - i, value); AddChild(n, slot, c, leaf); return true; } uint* cs = EndOf(n) - 1 - idx; uint cOff = *cs; byte* ch = b + (ulong)cOff * 8; int cl = ch[12]; int rem = len - i; int m = cl <= rem ? cl : rem; int mm = 1 + Mismatch(ch + HDR + 1, k + i + 1, m - 1); if (mm == cl) { i += cl; slot = cs; n = ch; continue; } // split the edge to ch after mm bytes for (int j = 0; j < d; j++) (*(int*)(path[j] + 8))++; _count++; int mw = (HDR + mm + 10 + 7) >> 3; uint mo = Alloc(mw); byte* M = b + (ulong)mo * 8; Unsafe.CopyBlockUnaligned(M + HDR, ch + HDR, (uint)mm); *(int*)(M + 8) = *(int*)(ch + 8) + 1; M[12] = (byte)mm; M[13] = (byte)mw; int cn = *(ushort*)(ch + 14) & NCH_MASK; byte* lp = ch + HDR; int mv = cl - mm + cn; for (int j = 0; j < mv; j++) lp[j] = lp[j + mm]; ch[12] = (byte)(cl - mm); byte cFirst = lp[0]; byte* mk = M + HDR + mm; uint* me = (uint*)(M + (mw << 3)); if (i + mm == len) { *(long*)M = value; *(ushort*)(M + 14) = (ushort)(HASVAL | 1); mk[0] = cFirst; me[-1] = cOff; } else { *(long*)M = 0; *(ushort*)(M + 14) = 2; uint lo = NewLeaf(k + i + mm, len - i - mm, value); byte lf = k[i + mm]; if (lf < cFirst) { mk[0] = lf; mk[1] = cFirst; me[-1] = lo; me[-2] = cOff; } else { mk[0] = cFirst; mk[1] = lf; me[-1] = cOff; me[-2] = lo; } } *cs = mo; return true; } } } public bool TryGet(ReadOnlySpan key, out long value) { byte* b = _base; byte* n = b + (ulong)_root * 8; int len = key.Length; fixed (byte* k = key) { int i = 0; while (i < len) { int idx = Find(n + HDR + n[12], *(ushort*)(n + 14) & NCH_MASK, k[i]); if (idx < 0) goto miss; uint off = *(EndOf(n) - 1 - idx); n = b + (ulong)off * 8; int cl = n[12]; if (cl > len - i || !Eq(n + HDR + 1, k + i + 1, cl - 1)) goto miss; i += cl; } if ((*(ushort*)(n + 14) & HASVAL) != 0) { value = *(long*)n; return true; } } miss: value = 0; return false; } public bool Remove(ReadOnlySpan key) { Reserve(); byte* b = _base; int len = key.Length; byte** nodes = stackalloc byte*[MAX_DEPTH]; uint** slots = stackalloc uint*[MAX_DEPTH]; int* idxs = stackalloc int[MAX_DEPTH]; byte* n = b + (ulong)_root * 8; int d = 0; nodes[d] = n; slots[d] = null; idxs[d] = 0; d++; fixed (byte* k = key) { int i = 0; while (i < len) { int idx = Find(n + HDR + n[12], *(ushort*)(n + 14) & NCH_MASK, k[i]); if (idx < 0) return false; uint* cs = EndOf(n) - 1 - idx; byte* ch = b + (ulong)*cs * 8; int cl = ch[12]; if (cl > len - i || !Eq(ch + HDR + 1, k + i + 1, cl - 1)) return false; i += cl; n = ch; nodes[d] = n; slots[d] = cs; idxs[d] = idx; d++; } } int f = *(ushort*)(n + 14); if ((f & HASVAL) == 0) return false; for (int j = 0; j < d; j++) (*(int*)(nodes[j] + 8))--; _count--; f &= ~HASVAL; *(ushort*)(n + 14) = (ushort)f; if (d == 1) return true; // the root int nc = f & NCH_MASK; if (nc >= 2) return true; if (nc == 1) { Merge(n, slots[d - 1]); return true; } // leaf: unlink from the parent byte* p = nodes[d - 2]; int pf = *(ushort*)(p + 14); int pn = pf & NCH_MASK; int x = idxs[d - 1]; byte* pk = p + HDR + p[12]; uint* pe = EndOf(p); for (int j = x; j < pn - 1; j++) { pk[j] = pk[j + 1]; pe[-1 - j] = pe[-2 - j]; } pf--; *(ushort*)(p + 14) = (ushort)pf; Free(n); if (d - 2 > 0 && pf == 1) Merge(p, slots[d - 2]); // pf == 1: no key, one child return true; } public bool TryLongestPrefix(ReadOnlySpan key, out int length, out long value) { byte* b = _base; byte* n = b + (ulong)_root * 8; int len = key.Length; bool found = false; int bl = 0; long bv = 0; fixed (byte* k = key) { int i = 0; while (true) { int f = *(ushort*)(n + 14); if ((f & HASVAL) != 0) { found = true; bl = i; bv = *(long*)n; } if (i == len) break; int idx = Find(n + HDR + n[12], f & NCH_MASK, k[i]); if (idx < 0) break; uint off = *(EndOf(n) - 1 - idx); byte* ch = b + (ulong)off * 8; int cl = ch[12]; if (cl > len - i || !Eq(ch + HDR + 1, k + i + 1, cl - 1)) break; i += cl; n = ch; } } length = bl; value = bv; return found; } // The node whose subtree holds exactly the keys starting with the prefix, // or null. [MethodImpl(MethodImplOptions.AggressiveInlining)] byte* Locate(byte* k, int len) { byte* b = _base; byte* n = b + (ulong)_root * 8; int i = 0; while (i < len) { int idx = Find(n + HDR + n[12], *(ushort*)(n + 14) & NCH_MASK, k[i]); if (idx < 0) return null; uint off = *(EndOf(n) - 1 - idx); byte* ch = b + (ulong)off * 8; int cl = ch[12]; int rem = len - i; if (cl >= rem) return Eq(ch + HDR + 1, k + i + 1, rem - 1) ? ch : null; if (!Eq(ch + HDR + 1, k + i + 1, cl - 1)) return null; i += cl; n = ch; } return n; } public int PrefixCount(ReadOnlySpan prefix) { fixed (byte* k = prefix) { byte* n = Locate(k, prefix.Length); return n == null ? 0 : *(int*)(n + 8); } } public int PrefixValues(ReadOnlySpan prefix, long[] outValues, int limit) { if (limit > outValues.Length) limit = outValues.Length; if (limit <= 0) return 0; byte* s; fixed (byte* k = prefix) { s = Locate(k, prefix.Length); } if (s == null) return 0; byte* b = _base; int w = 0; fixed (long* o = outValues) { int f = *(ushort*)(s + 14); if ((f & HASVAL) != 0) { o[w++] = *(long*)s; if (w == limit) return w; } int nc = f & NCH_MASK; if (nc == 0) return w; uint** stP = stackalloc uint*[MAX_DEPTH]; int* stR = stackalloc int[MAX_DEPTH]; int sp = 0; stP[0] = EndOf(s) - 1; stR[0] = nc; while (sp >= 0) { if (stR[sp] == 0) { sp--; continue; } stR[sp]--; uint off = *stP[sp]; stP[sp]--; byte* c = b + (ulong)off * 8; int cf = *(ushort*)(c + 14); if ((cf & HASVAL) != 0) { o[w++] = *(long*)c; if (w == limit) return w; } int cn = cf & NCH_MASK; if (cn != 0) { sp++; stP[sp] = EndOf(c) - 1; stR[sp] = cn; } } } return w; } public int NodeCount() { return CountNodes(_base + (ulong)_root * 8); } int CountNodes(byte* n) { int c = 1; int nc = *(ushort*)(n + 14) & NCH_MASK; uint* e = EndOf(n); for (int j = 0; j < nc; j++) c += CountNodes(_base + (ulong)e[-1 - j] * 8); return c; } public int Height() { return HeightOf(_base + (ulong)_root * 8); } int HeightOf(byte* n) { int h = 0; int nc = *(ushort*)(n + 14) & NCH_MASK; uint* e = EndOf(n); for (int j = 0; j < nc; j++) { int ch = 1 + HeightOf(_base + (ulong)e[-1 - j] * 8); if (ch > h) h = ch; } return h; } }