// Radix tree (path-compressed byte trie) with subtree counts.
//
// Every node is one variable-sized block inside a single arena (raw memory
// grown with realloc), addressed by a 32-bit offset in 8-byte units (offset 0
// is reserved as "null"). Block layout:
//
//   0   value      Int64
//   8   count      UInt32   keys in this subtree (itself included)
//   12  nChild     UInt16   number of children (0 ... 256)
//   14  labelLen   UInt8    length of the edge label leading to this node
//   15  flags      UInt8    bit 7: holds a key; bits 0-3: capacity code
//   16  children   UInt32 x cap      child offsets, sorted by first byte
//   16+4cap keys   UInt8  x cap      first label byte of each child (sorted)
//   16+5cap label  UInt8  x labelLen
//
// Capacity is 0 or a power of two from 2 to 256. Freed blocks go to exact
// size free lists (sizes are at most 194 units).

#if canImport(Darwin)
import Darwin
#else
import Glibc
#endif

private let HASV: UInt8 = 0x80
private let MAXUNITS = 200

@inline(__always) private func capOf(_ flags: UInt8) -> Int {
    return (1 &<< Int(flags & 15)) & ~1
}

@inline(__always) private func unitsFor(_ cap: Int, _ labelLen: Int) -> Int {
    return (23 &+ 5 &* cap &+ labelLen) &>> 3
}

@inline(__always) private func hCount(_ h: UInt64) -> Int { Int(truncatingIfNeeded: UInt32(truncatingIfNeeded: h)) }
@inline(__always) private func hNC(_ h: UInt64) -> Int { Int(truncatingIfNeeded: (h &>> 32) & 0xFFFF) }
@inline(__always) private func hLen(_ h: UInt64) -> Int { Int(truncatingIfNeeded: (h &>> 48) & 0xFF) }
@inline(__always) private func hFlags(_ h: UInt64) -> UInt8 { UInt8(truncatingIfNeeded: h &>> 56) }

@inline(__always) private func nodePtr(_ b: UnsafeMutableRawPointer, _ off: UInt32) -> UnsafeMutableRawPointer {
    return b + (Int(truncatingIfNeeded: off) &<< 3)
}

// Index of the child whose first byte is `byte`, or -1. n > 0. Reads whole
// 8-byte words of the key array; the block layout keeps those reads inside it.
@inline(__always) private func findChild(_ keys: UnsafeRawPointer, _ n: Int, _ byte: UInt8) -> Int {
    let pat = UInt64(byte) &* 0x0101_0101_0101_0101
    var i = 0
    repeat {
        let w = keys.loadUnaligned(fromByteOffset: i, as: UInt64.self) ^ pat
        let t = (w &- 0x0101_0101_0101_0101) & ~w & 0x8080_8080_8080_8080
        if t != 0 {
            let j = i &+ (t.trailingZeroBitCount &>> 3)
            return j < n ? j : -1
        }
        i &+= 8
    } while i < n
    return -1
}

// Length of the common prefix of a[0..<n] and b[0..<n].
@inline(__always) private func commonPrefix(_ a: UnsafeRawPointer, _ b: UnsafeRawPointer, _ n: Int) -> Int {
    var i = 0
    while i &+ 8 <= n {
        let x = a.loadUnaligned(fromByteOffset: i, as: UInt64.self) ^ b.loadUnaligned(fromByteOffset: i, as: UInt64.self)
        if x != 0 { return i &+ (x.trailingZeroBitCount &>> 3) }
        i &+= 8
    }
    while i < n {
        if a.load(fromByteOffset: i, as: UInt8.self) != b.load(fromByteOffset: i, as: UInt8.self) { return i }
        i &+= 1
    }
    return n
}

// a[0..<n] == b[0..<n]
@inline(__always) private func bytesEqual(_ a: UnsafeRawPointer, _ b: UnsafeRawPointer, _ n: Int) -> Bool {
    if n >= 8 {
        var i = 0
        let last = n &- 8
        while i < last {
            if a.loadUnaligned(fromByteOffset: i, as: UInt64.self) != b.loadUnaligned(fromByteOffset: i, as: UInt64.self) {
                return false
            }
            i &+= 8
        }
        return a.loadUnaligned(fromByteOffset: last, as: UInt64.self) == b.loadUnaligned(fromByteOffset: last, as: UInt64.self)
    }
    if n >= 4 {
        let last = n &- 4
        return (a.loadUnaligned(as: UInt32.self) == b.loadUnaligned(as: UInt32.self))
            && (a.loadUnaligned(fromByteOffset: last, as: UInt32.self) == b.loadUnaligned(fromByteOffset: last, as: UInt32.self))
    }
    if n >= 2 {
        let last = n &- 2
        return (a.loadUnaligned(as: UInt16.self) == b.loadUnaligned(as: UInt16.self))
            && (a.loadUnaligned(fromByteOffset: last, as: UInt16.self) == b.loadUnaligned(fromByteOffset: last, as: UInt16.self))
    }
    if n == 1 {
        return a.load(as: UInt8.self) == b.load(as: UInt8.self)
    }
    return true
}

// Write every value of the subtree at `off` in key order.
private func walkAll(_ b: UnsafeMutableRawPointer, _ off: UInt32, _ out: UnsafeMutablePointer<Int64>, _ w: inout Int) {
    let p = nodePtr(b, off)
    let h = p.load(fromByteOffset: 8, as: UInt64.self)
    if hFlags(h) & HASV != 0 {
        out[w] = p.load(as: Int64.self)
        w &+= 1
    }
    let nc = hNC(h)
    var i = 0
    while i < nc {
        let c = p.load(fromByteOffset: 16 &+ 4 &* i, as: UInt32.self)
        let cp = nodePtr(b, c)
        let ch = cp.load(fromByteOffset: 8, as: UInt64.self)
        if hNC(ch) == 0 {
            // A leaf always holds a key.
            out[w] = cp.load(as: Int64.self)
            w &+= 1
        } else {
            walkAll(b, c, out, &w)
        }
        i &+= 1
    }
}

// Like walkAll but stops at `limit`; returns true when the output is full.
private func walkLimited(_ b: UnsafeMutableRawPointer, _ off: UInt32, _ out: UnsafeMutablePointer<Int64>,
                         _ limit: Int, _ w: inout Int) -> Bool {
    let p = nodePtr(b, off)
    let h = p.load(fromByteOffset: 8, as: UInt64.self)
    if limit &- w >= hCount(h) {
        walkAll(b, off, out, &w)
        return w == limit
    }
    if hFlags(h) & HASV != 0 {
        out[w] = p.load(as: Int64.self)
        w &+= 1
        if w == limit { return true }
    }
    let nc = hNC(h)
    var i = 0
    while i < nc {
        let c = p.load(fromByteOffset: 16 &+ 4 &* i, as: UInt32.self)
        if walkLimited(b, c, out, limit, &w) { return true }
        i &+= 1
    }
    return false
}

private func countNodes(_ b: UnsafeMutableRawPointer, _ off: UInt32) -> Int {
    let p = nodePtr(b, off)
    let nc = hNC(p.load(fromByteOffset: 8, as: UInt64.self))
    var total = 1
    for i in 0..<nc {
        total += countNodes(b, p.load(fromByteOffset: 16 + 4 * i, as: UInt32.self))
    }
    return total
}

private func subtreeHeight(_ b: UnsafeMutableRawPointer, _ off: UInt32) -> Int {
    let p = nodePtr(b, off)
    let nc = hNC(p.load(fromByteOffset: 8, as: UInt64.self))
    var best = 0
    for i in 0..<nc {
        let hh = 1 + subtreeHeight(b, p.load(fromByteOffset: 16 + 4 * i, as: UInt32.self))
        if hh > best { best = hh }
    }
    return best
}

struct RadixCore {
    var base: UnsafeMutableRawPointer
    var capUnits: Int
    var top: Int
    var root: UInt32
    var size: Int
    let freeHeads: UnsafeMutablePointer<UInt32>
    let path: UnsafeMutablePointer<UInt32>  // node offsets from the root down
    let slots: UnsafeMutablePointer<Int>    // slots[d]: index of path[d] among path[d-1]'s children

    init() {
        capUnits = 1 << 12
        base = malloc(capUnits * 8)!
        top = 1  // unit 0 is the null offset
        root = 0
        size = 0
        freeHeads = UnsafeMutablePointer<UInt32>.allocate(capacity: MAXUNITS)
        freeHeads.initialize(repeating: 0, count: MAXUNITS)
        path = UnsafeMutablePointer<UInt32>.allocate(capacity: 264)
        path.initialize(repeating: 0, count: 264)
        slots = UnsafeMutablePointer<Int>.allocate(capacity: 264)
        slots.initialize(repeating: 0, count: 264)
        let r = alloc(unitsFor(0, 0))
        let p = nodePtr(base, r)
        p.storeBytes(of: 0, as: Int64.self)
        p.storeBytes(of: 0, toByteOffset: 8, as: UInt64.self)
        root = r
    }

    func destroy() {
        free(base)
        freeHeads.deallocate()
        path.deallocate()
        slots.deallocate()
    }

    // ------------------------------------------------------------ memory

    @inline(__always) mutating func alloc(_ units: Int) -> UInt32 {
        let h = freeHeads[units]
        if h != 0 {
            freeHeads[units] = nodePtr(base, h).load(as: UInt32.self)
            return h
        }
        let r = top
        if r &+ units > capUnits { grow(r + units) }
        top = r &+ units
        return UInt32(truncatingIfNeeded: r)
    }

    @inline(never) mutating func grow(_ need: Int) {
        var nc = capUnits * 2
        while nc < need { nc *= 2 }
        precondition(nc <= (1 << 32), "radix tree arena too large")
        base = realloc(base, nc * 8)!
        capUnits = nc
    }

    @inline(__always) mutating func release(_ off: UInt32, _ units: Int) {
        nodePtr(base, off).storeBytes(of: freeHeads[units], as: UInt32.self)
        freeHeads[units] = off
    }

    @inline(__always) mutating func newLeaf(_ src: UnsafeRawPointer, _ len: Int, _ value: Int64) -> UInt32 {
        let off = alloc(unitsFor(0, len))
        let p = nodePtr(base, off)
        p.storeBytes(of: value, as: Int64.self)
        p.storeBytes(of: 1 | (UInt64(len) &<< 48) | (UInt64(HASV) &<< 56), toByteOffset: 8, as: UInt64.self)
        memcpy(p + 16, src, len)
        return off
    }

    @inline(__always) func bumpPath(_ depth: Int, _ delta: UInt32) {
        let b = base
        var i = 0
        while i < depth {
            let p = nodePtr(b, path[i])
            p.storeBytes(of: p.load(fromByteOffset: 8, as: UInt32.self) &+ delta, toByteOffset: 8, as: UInt32.self)
            i &+= 1
        }
    }

    // Point the parent of path[d] (or the root) at `off`.
    @inline(__always) mutating func relink(_ d: Int, _ off: UInt32) {
        path[d] = off
        if d == 0 {
            root = off
        } else {
            nodePtr(base, path[d - 1]).storeBytes(of: off, toByteOffset: 16 + 4 * slots[d], as: UInt32.self)
        }
    }

    // Add `child` with first byte `byte` to node path[d], growing it if full.
    mutating func addChild(_ d: Int, _ byte: UInt8, _ child: UInt32) {
        let off = path[d]
        var p = nodePtr(base, off)
        let h = p.load(fromByteOffset: 8, as: UInt64.self)
        let nc = hNC(h)
        let len = hLen(h)
        let fl = hFlags(h)
        var cap = capOf(fl)
        if nc == cap {
            let code = Int(fl & 15)
            let ncode = code == 0 ? 1 : code + 1
            let ncap = 1 << ncode
            let noff = alloc(unitsFor(ncap, len))
            p = nodePtr(base, off)
            let np = nodePtr(base, noff)
            memcpy(np, p, 16 + 4 * nc)
            memcpy(np + 16 + 4 * ncap, p + 16 + 4 * cap, nc)
            memcpy(np + 16 + 5 * ncap, p + 16 + 5 * cap, len)
            np.storeBytes(of: (fl & 0xF0) | UInt8(ncode), toByteOffset: 15, as: UInt8.self)
            release(off, unitsFor(cap, len))
            relink(d, noff)
            p = np
            cap = ncap
        }
        let keys = p + 16 + 4 * cap
        var i = 0
        while i < nc && keys.load(fromByteOffset: i, as: UInt8.self) < byte { i += 1 }
        if i < nc {
            memmove(p + 16 + 4 * (i + 1), p + 16 + 4 * i, 4 * (nc - i))
            memmove(keys + i + 1, keys + i, nc - i)
        }
        p.storeBytes(of: child, toByteOffset: 16 + 4 * i, as: UInt32.self)
        keys.storeBytes(of: byte, toByteOffset: i, as: UInt8.self)
        p.storeBytes(of: UInt16(nc + 1), toByteOffset: 12, as: UInt16.self)
    }

    // Split the edge to child `c` (slot j of `cur`) after m label bytes and
    // add the key kp[0..<n] (which matches up to pos + m).
    mutating func split(_ cur: UInt32, _ j: Int, _ c: UInt32, _ m: Int,
                        _ kp: UnsafeRawPointer, _ pos: Int, _ n: Int, _ value: Int64) {
        let ch = nodePtr(base, c).load(fromByteOffset: 8, as: UInt64.self)
        let len = hLen(ch)
        let cnc = hNC(ch)
        let ccap = capOf(hFlags(ch))
        let low = alloc(unitsFor(ccap, len - m))
        let endsHere = pos + m == n
        let leaf: UInt32 = endsHere ? 0 : newLeaf(kp + pos + m, n - pos - m, value)
        let mid = alloc(unitsFor(2, m))
        let b = base
        let cp = nodePtr(b, c)
        let lp = nodePtr(b, low)
        memcpy(lp, cp, 16 + 4 * cnc)
        memcpy(lp + 16 + 4 * ccap, cp + 16 + 4 * ccap, cnc)
        let clab = cp + 16 + 5 * ccap
        memcpy(lp + 16 + 5 * ccap, clab + m, len - m)
        lp.storeBytes(of: UInt8(len - m), toByteOffset: 14, as: UInt8.self)
        let lowByte = clab.load(fromByteOffset: m, as: UInt8.self)
        release(c, unitsFor(ccap, len))
        let mp = nodePtr(b, mid)
        let cnt = UInt64(hCount(ch) + 1)
        // mid has capacity 2: children at 16, keys at 24, label at 26.
        if endsHere {
            mp.storeBytes(of: value, as: Int64.self)
            mp.storeBytes(of: cnt | (1 << 32) | (UInt64(m) << 48) | (UInt64(HASV | 1) << 56),
                          toByteOffset: 8, as: UInt64.self)
            mp.storeBytes(of: low, toByteOffset: 16, as: UInt32.self)
            mp.storeBytes(of: lowByte, toByteOffset: 24, as: UInt8.self)
        } else {
            mp.storeBytes(of: 0, as: Int64.self)
            mp.storeBytes(of: cnt | (2 << 32) | (UInt64(m) << 48) | (UInt64(1) << 56),
                          toByteOffset: 8, as: UInt64.self)
            let leafByte = kp.load(fromByteOffset: pos + m, as: UInt8.self)
            if leafByte < lowByte {
                mp.storeBytes(of: leaf, toByteOffset: 16, as: UInt32.self)
                mp.storeBytes(of: low, toByteOffset: 20, as: UInt32.self)
                mp.storeBytes(of: leafByte, toByteOffset: 24, as: UInt8.self)
                mp.storeBytes(of: lowByte, toByteOffset: 25, as: UInt8.self)
            } else {
                mp.storeBytes(of: low, toByteOffset: 16, as: UInt32.self)
                mp.storeBytes(of: leaf, toByteOffset: 20, as: UInt32.self)
                mp.storeBytes(of: lowByte, toByteOffset: 24, as: UInt8.self)
                mp.storeBytes(of: leafByte, toByteOffset: 25, as: UInt8.self)
            }
        }
        memcpy(mp + 26, kp + pos, m)
        nodePtr(b, cur).storeBytes(of: mid, toByteOffset: 16 + 4 * j, as: UInt32.self)
    }

    // Merge path[d] (no key, exactly one child) with its child.
    mutating func merge(_ d: Int) {
        let y = path[d]
        let yh = nodePtr(base, y).load(fromByteOffset: 8, as: UInt64.self)
        let ylen = hLen(yh)
        let ycap = capOf(hFlags(yh))
        let c = nodePtr(base, y).load(fromByteOffset: 16, as: UInt32.self)
        let ch = nodePtr(base, c).load(fromByteOffset: 8, as: UInt64.self)
        let clen = hLen(ch)
        let ccap = capOf(hFlags(ch))
        let cnc = hNC(ch)
        let total = ylen + clen
        let noff = alloc(unitsFor(ccap, total))
        let b = base
        let yp = nodePtr(b, y)
        let cp = nodePtr(b, c)
        let np = nodePtr(b, noff)
        memcpy(np, cp, 16 + 4 * cnc)
        memcpy(np + 16 + 4 * ccap, cp + 16 + 4 * ccap, cnc)
        let nlab = np + 16 + 5 * ccap
        memcpy(nlab, yp + 16 + 5 * ycap, ylen)
        memcpy(nlab + ylen, cp + 16 + 5 * ccap, clen)
        np.storeBytes(of: UInt8(total), toByteOffset: 14, as: UInt8.self)
        release(y, unitsFor(ycap, ylen))
        release(c, unitsFor(ccap, clen))
        relink(d, noff)
    }

    // ------------------------------------------------------------ operations

    mutating func insert(_ kp: UnsafeRawPointer, _ n: Int, _ value: Int64) -> Bool {
        var cur = root
        path[0] = cur
        var depth = 1
        var pos = 0
        while true {
            let p = nodePtr(base, cur)
            let h = p.load(fromByteOffset: 8, as: UInt64.self)
            if pos == n {
                p.storeBytes(of: value, as: Int64.self)
                let fl = hFlags(h)
                if fl & HASV != 0 { return false }
                p.storeBytes(of: fl | HASV, toByteOffset: 15, as: UInt8.self)
                bumpPath(depth, 1)
                size += 1
                return true
            }
            let nc = hNC(h)
            let cap = capOf(hFlags(h))
            let byte = kp.load(fromByteOffset: pos, as: UInt8.self)
            let j = nc == 0 ? -1 : findChild(p + (16 &+ 4 &* cap), nc, byte)
            if j < 0 {
                let leaf = newLeaf(kp + pos, n &- pos, value)
                addChild(depth - 1, byte, leaf)
                bumpPath(depth, 1)
                size += 1
                return true
            }
            let c = p.load(fromByteOffset: 16 &+ 4 &* j, as: UInt32.self)
            let cp = nodePtr(base, c)
            let ch = cp.load(fromByteOffset: 8, as: UInt64.self)
            let len = hLen(ch)
            let lab = cp + (16 &+ 5 &* capOf(hFlags(ch)))
            let rem = n &- pos
            let lim = len < rem ? len : rem
            let m = 1 &+ commonPrefix(lab + 1, kp + (pos &+ 1), lim &- 1)
            if m == len {
                path[depth] = c
                slots[depth] = j
                depth &+= 1
                cur = c
                pos &+= len
                continue
            }
            split(cur, j, c, m, kp, pos, n, value)
            bumpPath(depth, 1)
            size += 1
            return true
        }
    }

    mutating func remove(_ kp: UnsafeRawPointer, _ n: Int) -> Bool {
        let b0 = base
        var cur = root
        path[0] = cur
        var depth = 1
        var pos = 0
        while pos < n {
            let p = nodePtr(b0, cur)
            let h = p.load(fromByteOffset: 8, as: UInt64.self)
            let nc = hNC(h)
            if nc == 0 { return false }
            let byte = kp.load(fromByteOffset: pos, as: UInt8.self)
            let j = findChild(p + (16 &+ 4 &* capOf(hFlags(h))), nc, byte)
            if j < 0 { return false }
            let c = p.load(fromByteOffset: 16 &+ 4 &* j, as: UInt32.self)
            let cp = nodePtr(b0, c)
            let ch = cp.load(fromByteOffset: 8, as: UInt64.self)
            let len = hLen(ch)
            if len > n &- pos { return false }
            let lab = cp + (16 &+ 5 &* capOf(hFlags(ch)))
            if !bytesEqual(lab + 1, kp + (pos &+ 1), len &- 1) { return false }
            path[depth] = c
            slots[depth] = j
            depth &+= 1
            cur = c
            pos &+= len
        }
        let p = nodePtr(b0, cur)
        let h = p.load(fromByteOffset: 8, as: UInt64.self)
        let fl = hFlags(h)
        if fl & HASV == 0 { return false }
        p.storeBytes(of: fl & ~HASV, toByteOffset: 15, as: UInt8.self)
        bumpPath(depth, 0xFFFF_FFFF)
        size -= 1
        if depth == 1 { return true }  // the root is never removed or merged
        let nc = hNC(h)
        if nc >= 2 { return true }
        if nc == 1 {
            merge(depth - 1)
            return true
        }
        // A leaf: unlink it from its parent.
        let pd = depth - 2
        let pp = nodePtr(b0, path[pd])
        let ph = pp.load(fromByteOffset: 8, as: UInt64.self)
        let pnc = hNC(ph)
        let pcap = capOf(hFlags(ph))
        let slot = slots[depth - 1]
        let tail = pnc - slot - 1
        if tail > 0 {
            memmove(pp + 16 + 4 * slot, pp + 16 + 4 * (slot + 1), 4 * tail)
            let keys = pp + 16 + 4 * pcap
            memmove(keys + slot, keys + slot + 1, tail)
        }
        pp.storeBytes(of: UInt16(pnc - 1), toByteOffset: 12, as: UInt16.self)
        release(cur, unitsFor(capOf(fl), hLen(h)))
        if pd > 0 && pnc - 1 == 1 && hFlags(ph) & HASV == 0 {
            merge(pd)
        }
        return true
    }

    func get(_ kp: UnsafeRawPointer, _ n: Int) -> Int64? {
        let b = base
        var cur = root
        var pos = 0
        while true {
            let p = nodePtr(b, cur)
            let h = p.load(fromByteOffset: 8, as: UInt64.self)
            if pos == n {
                return hFlags(h) & HASV != 0 ? p.load(as: Int64.self) : nil
            }
            let nc = hNC(h)
            if nc == 0 { return nil }
            let byte = kp.load(fromByteOffset: pos, as: UInt8.self)
            let j = findChild(p + (16 &+ 4 &* capOf(hFlags(h))), nc, byte)
            if j < 0 { return nil }
            let c = p.load(fromByteOffset: 16 &+ 4 &* j, as: UInt32.self)
            let cp = nodePtr(b, c)
            let ch = cp.load(fromByteOffset: 8, as: UInt64.self)
            let len = hLen(ch)
            if len > n &- pos { return nil }
            let lab = cp + (16 &+ 5 &* capOf(hFlags(ch)))
            if !bytesEqual(lab + 1, kp + (pos &+ 1), len &- 1) { return nil }
            cur = c
            pos &+= len
        }
    }

    func longestPrefix(_ kp: UnsafeRawPointer, _ n: Int) -> (length: Int, value: Int64)? {
        let b = base
        var cur = root
        var pos = 0
        var found = false
        var bestLen = 0
        var bestVal: Int64 = 0
        while true {
            let p = nodePtr(b, cur)
            let h = p.load(fromByteOffset: 8, as: UInt64.self)
            if hFlags(h) & HASV != 0 {
                found = true
                bestLen = pos
                bestVal = p.load(as: Int64.self)
            }
            if pos == n { break }
            let nc = hNC(h)
            if nc == 0 { break }
            let byte = kp.load(fromByteOffset: pos, as: UInt8.self)
            let j = findChild(p + (16 &+ 4 &* capOf(hFlags(h))), nc, byte)
            if j < 0 { break }
            let c = p.load(fromByteOffset: 16 &+ 4 &* j, as: UInt32.self)
            let cp = nodePtr(b, c)
            let ch = cp.load(fromByteOffset: 8, as: UInt64.self)
            let len = hLen(ch)
            if len > n &- pos { break }
            let lab = cp + (16 &+ 5 &* capOf(hFlags(ch)))
            if !bytesEqual(lab + 1, kp + (pos &+ 1), len &- 1) { break }
            cur = c
            pos &+= len
        }
        return found ? (bestLen, bestVal) : nil
    }

    // The node whose subtree holds exactly the keys starting with kp[0..<n], or 0.
    func locate(_ kp: UnsafeRawPointer, _ n: Int) -> UInt32 {
        let b = base
        var cur = root
        var pos = 0
        while pos < n {
            let p = nodePtr(b, cur)
            let h = p.load(fromByteOffset: 8, as: UInt64.self)
            let nc = hNC(h)
            if nc == 0 { return 0 }
            let byte = kp.load(fromByteOffset: pos, as: UInt8.self)
            let j = findChild(p + (16 &+ 4 &* capOf(hFlags(h))), nc, byte)
            if j < 0 { return 0 }
            let c = p.load(fromByteOffset: 16 &+ 4 &* j, as: UInt32.self)
            let cp = nodePtr(b, c)
            let ch = cp.load(fromByteOffset: 8, as: UInt64.self)
            let len = hLen(ch)
            let lab = cp + (16 &+ 5 &* capOf(hFlags(ch)))
            let rem = n &- pos
            if len >= rem {
                return bytesEqual(lab + 1, kp + (pos &+ 1), rem &- 1) ? c : 0
            }
            if !bytesEqual(lab + 1, kp + (pos &+ 1), len &- 1) { return 0 }
            cur = c
            pos &+= len
        }
        return cur
    }

    func prefixCount(_ kp: UnsafeRawPointer, _ n: Int) -> Int {
        let node = locate(kp, n)
        if node == 0 { return 0 }
        return hCount(nodePtr(base, node).load(fromByteOffset: 8, as: UInt64.self))
    }

    func prefixValues(_ kp: UnsafeRawPointer, _ n: Int, _ out: UnsafeMutablePointer<Int64>, _ limit: Int) -> Int {
        if limit <= 0 { return 0 }
        let node = locate(kp, n)
        if node == 0 { return 0 }
        var w = 0
        _ = walkLimited(base, node, out, limit, &w)
        return w
    }

    func nodeCount() -> Int { countNodes(base, root) }
    func height() -> Int { subtreeHeight(base, root) }
}

final class RadixTree {
    private let core: UnsafeMutablePointer<RadixCore>

    init() {
        core = UnsafeMutablePointer<RadixCore>.allocate(capacity: 1)
        core.initialize(to: RadixCore())
    }

    deinit {
        core.pointee.destroy()
        core.deinitialize(count: 1)
        core.deallocate()
    }

    @inline(__always) private static func raw(_ k: UnsafeBufferPointer<UInt8>) -> UnsafeRawPointer {
        if let b = k.baseAddress { return UnsafeRawPointer(b) }
        return UnsafeRawPointer(bitPattern: 16)!  // never dereferenced: count is 0
    }

    func insert(_ key: UnsafeBufferPointer<UInt8>, _ value: Int64) -> Bool {
        return core.pointee.insert(RadixTree.raw(key), key.count, value)
    }

    func get(_ key: UnsafeBufferPointer<UInt8>) -> Int64? {
        return core.pointee.get(RadixTree.raw(key), key.count)
    }

    func remove(_ key: UnsafeBufferPointer<UInt8>) -> Bool {
        return core.pointee.remove(RadixTree.raw(key), key.count)
    }

    func longestPrefix(_ key: UnsafeBufferPointer<UInt8>) -> (length: Int, value: Int64)? {
        return core.pointee.longestPrefix(RadixTree.raw(key), key.count)
    }

    func prefixCount(_ prefix: UnsafeBufferPointer<UInt8>) -> Int {
        return core.pointee.prefixCount(RadixTree.raw(prefix), prefix.count)
    }

    func prefixValues(_ prefix: UnsafeBufferPointer<UInt8>,
                      _ outValues: UnsafeMutablePointer<Int64>, _ limit: Int) -> Int {
        return core.pointee.prefixValues(RadixTree.raw(prefix), prefix.count, outValues, limit)
    }

    var count: Int { core.pointee.size }

    func nodeCount() -> Int { core.pointee.nodeCount() }

    func height() -> Int { core.pointee.height() }
}
