#include "radix.h"

#include <stdalign.h>
#include <stdlib.h>
#include <string.h>

/*
 * High-performance path-compressed radix tree (C17).
 *
 * Design overview:
 * - 32-bit tagged node handles (Ref): low 3 bits = node kind tag, upper 29 bits = pool index.
 *   REF_NONE == 0 (tag 0). Supports up to 536M nodes per size class.
 * - Root is embedded directly in `struct radix` with a 256-entry child table and 256-bit
 *   presence bitmap, making step 0 an O(1) lookup with zero tag dispatch.
 * - Adaptive cache-line-aligned node size classes (tailored for 128B M3 cache lines):
 *     TAG_LEAF1   (  8 B): leaf with 1-byte edge label (stored in parent), just int64_t value.
 *     TAG_LEAFS   ( 16 B): leaf with 2..255-byte edge label (up to 7 rem bytes inline, else slab).
 *     TAG_NODE2   ( 32 B): 1..2 children, up to 8 rem bytes inline, branchless 2-key check.
 *     TAG_NODE8   ( 64 B): up to 8 sorted children, SWAR 64-bit parallel key search.
 *     TAG_NODE16  (128 B): up to 16 sorted children, branchless dual-SWAR key search.
 *     TAG_NODE48  (512 B): up to 48 children, O(1) byte->slot table + 256-bit bitmap.
 *     TAG_NODE256 (1152B): up to 256 children, O(1) direct table + 256-bit bitmap.
 * - All node pools and external label slabs (16/32/64/256 B) are 128-byte aligned contiguous
 *   arrays with O(1) intrusive LIFO free-lists for immediate slot reuse under churn.
 */

typedef uint32_t Ref;

enum {
    TAG_NONE    = 0,
    TAG_LEAF1   = 1,
    TAG_LEAFS   = 2,
    TAG_NODE2   = 3,
    TAG_NODE8   = 4,
    TAG_NODE16  = 5,
    TAG_NODE48  = 6,
    TAG_NODE256 = 7,
};

#define REF_NONE        ((Ref)0)
#define REF_TAG(r)      ((r) & 7u)
#define REF_IDX(r)      ((r) >> 3)
#define MAKE_REF(t, i)  (((Ref)(i) << 3) | (Ref)(t))
#define FREE_NONE       0xFFFFFFFFu

#define LIKELY(x)   __builtin_expect(!!(x), 1)
#define UNLIKELY(x) __builtin_expect(!!(x), 0)

/* Inline / external label storage for internal nodes (8 bytes). */
typedef union {
    uint8_t in[8];
    struct {
        uint32_t _pad;
        uint32_t ref;
    } ext;
} Label8;

/* TAG_LEAF1: 8 bytes (16 per 128B cache line). Edge label is 1 byte (in parent). */
typedef struct {
    int64_t val;
} Leaf1;

/* TAG_LEAFS: 16 bytes (8 per 128B cache line). Edge label is 2..255 bytes (rem_len 1..254). */
typedef struct {
    int64_t val;
    union {
        struct {
            uint8_t rem_len; /* 1..7 inline, 8..254 external */
            uint8_t in[7];
        };
        struct {
            uint8_t  _rem_len_ext;
            uint8_t  _pad[3];
            uint32_t ref;
        } ext;
    };
} LeafS;

/* TAG_NODE2: 32 bytes (4 per 128B cache line). 1..2 children.
 * Invariant: when count == 1, keys[1] == keys[0] for branchless lookup;
 * when count == 2, keys[0] < keys[1]. */
typedef struct {
    int64_t  val;
    uint32_t subtree_count;
    Ref      children[2];
    uint8_t  keys[2];
    uint8_t  meta;    /* bits 0..1: count (1..2), bit 7: has_val */
    uint8_t  rem_len; /* 0..8 inline, 9..254 external */
    Label8   label;
} Node2;

#define N2_COUNT(n)          ((uint32_t)((n)->meta & 3u))
#define N2_HAS_VAL(n)        ((uint32_t)((n)->meta >> 7))
#define N2_META(hv, cnt)     ((uint8_t)(((hv) << 7) | ((cnt) & 3u)))

/* TAG_NODE8: 64 bytes (2 per 128B cache line). Up to 8 sorted children. */
typedef struct {
    int64_t  val;
    uint32_t subtree_count;
    uint8_t  has_val;
    uint8_t  count;
    uint8_t  rem_len;
    uint8_t  _pad;
    Label8   label;
    uint8_t  keys[8];
    Ref      children[8];
} Node8;

/* TAG_NODE16: 128 bytes (exact 1 M3 cache line). Up to 16 sorted children. */
typedef struct {
    int64_t  val;
    uint32_t subtree_count;
    uint8_t  has_val;
    uint8_t  count;
    uint8_t  rem_len;
    uint8_t  _pad0;
    Label8   label;
    uint64_t _pad1[3];
    uint8_t  keys[16];
    Ref      children[16];
} Node16;

/* TAG_NODE48: 512 bytes (4 M3 cache lines). Up to 48 children. */
typedef struct {
    int64_t  val;
    uint32_t subtree_count;
    uint8_t  has_val;
    uint8_t  count;
    uint8_t  rem_len;
    uint8_t  _pad;
    Label8   label;
    uint64_t bitmap[4];
    uint64_t slot_mask;
    uint8_t  child_idx[256];
    Ref      children[48];
} Node48;

/* TAG_NODE256: 1152 bytes (9 M3 cache lines). Up to 256 children. */
typedef struct {
    int64_t  val;
    uint32_t subtree_count;
    uint16_t count;
    uint8_t  has_val;
    uint8_t  rem_len;
    Label8   label;
    uint64_t bitmap[4];
    uint64_t _pad0;
    Ref      children[256];
    uint64_t _pad1[8];
} Node256;

_Static_assert(sizeof(Leaf1)   == 8,    "Leaf1 size");
_Static_assert(sizeof(LeafS)   == 16,   "LeafS size");
_Static_assert(sizeof(Node2)   == 32,   "Node2 size");
_Static_assert(sizeof(Node8)   == 64,   "Node8 size");
_Static_assert(sizeof(Node16)  == 128,  "Node16 size");
_Static_assert(sizeof(Node48)  == 512,  "Node48 size");
_Static_assert(sizeof(Node256) == 1152, "Node256 size");

struct radix {
    /* Root node state (hot in L1). */
    int64_t  root_val;
    uint32_t root_count;
    uint16_t root_nchildren;
    uint8_t  root_has_val;
    uint8_t  _rpad;
    uint64_t root_bitmap[4];

    /* Node pool pointers (kept near front for L1 locality). */
    Leaf1   *leaf1;
    LeafS   *leafs;
    Node2   *node2;
    Node8   *node8;
    Node16  *node16;
    Node48  *node48;
    Node256 *node256;

    /* External label slabs: 16B, 32B, 64B, 256B. */
    uint8_t *lbl[4];

    /* Root direct child table (1024 bytes). */
    Ref      root_child[256];

    /* Pool bookkeeping (only touched during mutations). */
    uint32_t leaf1_len,   leaf1_cap,   leaf1_free;
    uint32_t leafs_len,   leafs_cap,   leafs_free;
    uint32_t node2_len,   node2_cap,   node2_free;
    uint32_t node8_len,   node8_cap,   node8_free;
    uint32_t node16_len,  node16_cap,  node16_free;
    uint32_t node48_len,  node48_cap,  node48_free;
    uint32_t node256_len, node256_cap, node256_free;

    uint32_t lbl_len[4];
    uint32_t lbl_cap[4];
    uint32_t lbl_free[4];
};

/* -------------------------------------------------------------------- Memory & Pools */

static void *xaligned_alloc(size_t align, size_t size) {
    size_t rounded = (size + align - 1u) & ~(align - 1u);
    void *p = aligned_alloc(align, rounded);
    if (UNLIKELY(!p)) abort();
    return p;
}

__attribute__((noinline, cold))
static void grow_pool(void **ptr, uint32_t *cap, size_t elem_size, uint32_t init_cap) {
    uint32_t old_cap = *cap;
    uint32_t new_cap = old_cap ? (old_cap * 2u) : init_cap;
    if (UNLIKELY(new_cap >= (1u << 29))) abort();
    void *new_ptr = xaligned_alloc(128, (size_t)new_cap * elem_size);
    if (old_cap) {
        memcpy(new_ptr, *ptr, (size_t)old_cap * elem_size);
        free(*ptr);
    }
    *ptr = new_ptr;
    *cap = new_cap;
}

#define DEFINE_POOL_OPS(name, Type, field, init_cap)                            \
    static inline uint32_t alloc_##name(radix *t) {                             \
        uint32_t idx = t->field##_free;                                         \
        if (idx != FREE_NONE) {                                                 \
            memcpy(&t->field##_free, &t->field[idx], sizeof(uint32_t));         \
            return idx;                                                         \
        }                                                                       \
        if (UNLIKELY(t->field##_len == t->field##_cap)) {                       \
            grow_pool((void **)&t->field, &t->field##_cap, sizeof(Type), init_cap); \
        }                                                                       \
        return t->field##_len++;                                                \
    }                                                                           \
    static inline void free_##name(radix *t, uint32_t idx) {                    \
        memcpy(&t->field[idx], &t->field##_free, sizeof(uint32_t));             \
        t->field##_free = idx;                                                  \
    }

DEFINE_POOL_OPS(leaf1,   Leaf1,   leaf1,   16)
DEFINE_POOL_OPS(leafs,   LeafS,   leafs,   16)
DEFINE_POOL_OPS(node2,   Node2,   node2,   16)
DEFINE_POOL_OPS(node8,   Node8,   node8,   16)
DEFINE_POOL_OPS(node16,  Node16,  node16,  8)
DEFINE_POOL_OPS(node48,  Node48,  node48,  4)
DEFINE_POOL_OPS(node256, Node256, node256, 2)

/* External label slab helpers: class 0=16B, 1=32B, 2=64B, 3=256B. */
static const uint8_t  LBL_SHIFT[4]    = {4, 5, 6, 8};
static const uint32_t LBL_INIT_CAP[4] = {16, 16, 8, 4};

static inline uint32_t lbl_class(size_t rem_len) {
    if (rem_len <= 16) return 0;
    if (rem_len <= 32) return 1;
    if (rem_len <= 64) return 2;
    return 3;
}

static inline const uint8_t *lbl_ptr(const radix *t, size_t rem_len, uint32_t ref) {
    uint32_t c = lbl_class(rem_len);
    return t->lbl[c] + ((size_t)ref << LBL_SHIFT[c]);
}

static inline uint32_t lbl_alloc(radix *t, const uint8_t *src, size_t rem_len) {
    uint32_t c = lbl_class(rem_len);
    uint32_t idx = t->lbl_free[c];
    if (idx != FREE_NONE) {
        memcpy(&t->lbl_free[c], t->lbl[c] + ((size_t)idx << LBL_SHIFT[c]), sizeof(uint32_t));
    } else {
        if (UNLIKELY(t->lbl_len[c] == t->lbl_cap[c])) {
            grow_pool((void **)&t->lbl[c], &t->lbl_cap[c], (size_t)1u << LBL_SHIFT[c], LBL_INIT_CAP[c]);
        }
        idx = t->lbl_len[c]++;
    }
    memcpy(t->lbl[c] + ((size_t)idx << LBL_SHIFT[c]), src, rem_len);
    return idx;
}

static inline void lbl_free(radix *t, size_t rem_len, uint32_t ref) {
    uint32_t c = lbl_class(rem_len);
    memcpy(t->lbl[c] + ((size_t)ref << LBL_SHIFT[c]), &t->lbl_free[c], sizeof(uint32_t));
    t->lbl_free[c] = ref;
}

/* -------------------------------------------------------------------- Fast Byte / Key Helpers */

/* Exact byte comparison for 1 <= n <= 8 without reading past [0..n-1]. */
static inline bool eq_inline8(const uint8_t *a, const uint8_t *b, size_t n) {
    if (n >= 4) {
        uint32_t a0, b0, a1, b1;
        memcpy(&a0, a, 4);
        memcpy(&b0, b, 4);
        memcpy(&a1, a + n - 4, 4);
        memcpy(&b1, b + n - 4, 4);
        return ((a0 ^ b0) | (a1 ^ b1)) == 0;
    }
    if (n >= 2) {
        uint16_t a0, b0, a1, b1;
        memcpy(&a0, a, 2);
        memcpy(&b0, b, 2);
        memcpy(&a1, a + n - 2, 2);
        memcpy(&b1, b + n - 2, 2);
        return ((a0 ^ b0) | (a1 ^ b1)) == 0;
    }
    return a[0] == b[0];
}

static inline bool eq_bytes(const uint8_t *a, const uint8_t *b, size_t n) {
    if (n == 0) return true;
    if (n <= 8) return eq_inline8(a, b, n);
    return memcmp(a, b, n) == 0;
}

static inline size_t common_prefix_len(const uint8_t *a, const uint8_t *b, size_t n) {
    size_t i = 0;
#if defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
    while (i + 8 <= n) {
        uint64_t wa, wb;
        memcpy(&wa, a + i, 8);
        memcpy(&wb, b + i, 8);
        uint64_t diff = wa ^ wb;
        if (diff) return i + (size_t)(__builtin_ctzll(diff) >> 3);
        i += 8;
    }
#endif
    while (i < n && a[i] == b[i]) i++;
    return i;
}

static inline const uint8_t *label8_ptr(const radix *t, const Label8 *lbl, size_t rl) {
    return LIKELY(rl <= 8) ? lbl->in : lbl_ptr(t, rl, lbl->ext.ref);
}

static inline const uint8_t *leafs_ptr(const radix *t, const LeafS *lf, size_t rl) {
    return LIKELY(rl <= 7) ? lf->in : lbl_ptr(t, rl, lf->ext.ref);
}

static inline bool match_label8(const radix *t, const uint8_t *key, const Label8 *lbl, size_t rl) {
    if (LIKELY(rl <= 8)) return eq_inline8(key, lbl->in, rl);
    return memcmp(key, lbl_ptr(t, rl, lbl->ext.ref), rl) == 0;
}

/* SWAR parallel search in 8-byte key array (count in 1..8). */
static inline int find_key8(const uint8_t keys[8], uint32_t count, uint8_t b) {
#if defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
    uint64_t word;
    memcpy(&word, keys, 8);
    uint64_t bc = 0x0101010101010101ULL * b;
    uint64_t x = word ^ bc;
    uint64_t match = (x - 0x0101010101010101ULL) & ~x & 0x8080808080808080ULL;
    uint64_t mask = (~0ULL) >> ((8u - count) * 8u);
    match &= mask;
    if (!match) return -1;
    return __builtin_ctzll(match) >> 3;
#else
    for (uint32_t i = 0; i < count; i++) {
        if (keys[i] == b) return (int)i;
    }
    return -1;
#endif
}

/* Branchless dual-SWAR parallel search in 16-byte key array (count in 1..16). */
static inline int find_key16(const uint8_t keys[16], uint32_t count, uint8_t b) {
#if defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
    uint64_t w0, w1;
    memcpy(&w0, keys, 8);
    memcpy(&w1, keys + 8, 8);
    uint64_t bc = 0x0101010101010101ULL * b;
    uint64_t x0 = w0 ^ bc;
    uint64_t x1 = w1 ^ bc;
    uint64_t m0 = (x0 - 0x0101010101010101ULL) & ~x0 & 0x8080808080808080ULL;
    uint64_t m1 = (x1 - 0x0101010101010101ULL) & ~x1 & 0x8080808080808080ULL;
    uint64_t mask0 = (count >= 8u) ? ~0ULL : (~0ULL >> ((8u - count) * 8u));
    uint64_t mask1 = (count <= 8u) ? 0ULL  : (~0ULL >> ((16u - count) * 8u));
    m0 &= mask0;
    m1 &= mask1;
    uint64_t any = m0 | m1;
    if (!any) return -1;
    uint64_t m = m0 ? m0 : m1;
    int base = m0 ? 0 : 8;
    return base + (__builtin_ctzll(m) >> 3);
#else
    for (uint32_t i = 0; i < count; i++) {
        if (keys[i] == b) return (int)i;
    }
    return -1;
#endif
}

/* -------------------------------------------------------------------- Lifecycle */

radix *radix_new(void) {
    radix *t = (radix *)xaligned_alloc(128, sizeof(radix));
    memset(t, 0, sizeof(radix));
    t->leaf1_free   = FREE_NONE;
    t->leafs_free   = FREE_NONE;
    t->node2_free   = FREE_NONE;
    t->node8_free   = FREE_NONE;
    t->node16_free  = FREE_NONE;
    t->node48_free  = FREE_NONE;
    t->node256_free = FREE_NONE;
    for (int c = 0; c < 4; c++) t->lbl_free[c] = FREE_NONE;
    return t;
}

void radix_free(radix *t) {
    if (!t) return;
    free(t->leaf1);
    free(t->leafs);
    free(t->node2);
    free(t->node8);
    free(t->node16);
    free(t->node48);
    free(t->node256);
    for (int c = 0; c < 4; c++) free(t->lbl[c]);
    free(t);
}

size_t radix_len(const radix *t) {
    return (size_t)t->root_count;
}

/* -------------------------------------------------------------------- Node Creation / Label Helpers */

static inline Ref make_leaf(radix *t, const uint8_t *rem, size_t rem_len, int64_t val) {
    if (rem_len == 0) {
        uint32_t idx = alloc_leaf1(t);
        t->leaf1[idx].val = val;
        return MAKE_REF(TAG_LEAF1, idx);
    }
    uint32_t ext_ref = 0;
    if (UNLIKELY(rem_len > 7)) {
        ext_ref = lbl_alloc(t, rem, rem_len);
    }
    uint32_t idx = alloc_leafs(t);
    LeafS *lf = &t->leafs[idx];
    lf->val = val;
    lf->rem_len = (uint8_t)rem_len;
    if (LIKELY(rem_len <= 7)) {
        memcpy(lf->in, rem, rem_len);
    } else {
        lf->ext.ref = ext_ref;
    }
    return MAKE_REF(TAG_LEAFS, idx);
}

static inline void init_label8(radix *t, Label8 *lbl, const uint8_t *rem, size_t rem_len) {
    if (rem_len == 0) return;
    if (LIKELY(rem_len <= 8)) {
        memcpy(lbl->in, rem, rem_len);
    } else {
        lbl->ext.ref = lbl_alloc(t, rem, rem_len);
    }
}

static inline void free_label8(radix *t, const Label8 *lbl, size_t rem_len) {
    if (UNLIKELY(rem_len > 8)) {
        lbl_free(t, rem_len, lbl->ext.ref);
    }
}

static inline uint32_t node_subtree_count(const radix *t, Ref r) {
    uint32_t idx = REF_IDX(r);
    switch (REF_TAG(r)) {
        case TAG_LEAF1:
        case TAG_LEAFS:   return 1u;
        case TAG_NODE2:   return t->node2[idx].subtree_count;
        case TAG_NODE8:   return t->node8[idx].subtree_count;
        case TAG_NODE16:  return t->node16[idx].subtree_count;
        case TAG_NODE48:  return t->node48[idx].subtree_count;
        case TAG_NODE256: return t->node256[idx].subtree_count;
        default:          return 0u;
    }
}

/* Copy node's remaining label into buf and return its length. */
static inline size_t node_copy_label(const radix *t, Ref r, uint8_t *buf) {
    uint32_t idx = REF_IDX(r);
    size_t rl;
    const uint8_t *p;
    switch (REF_TAG(r)) {
        case TAG_LEAF1:
            return 0;
        case TAG_LEAFS: {
            const LeafS *lf = &t->leafs[idx];
            rl = lf->rem_len;
            p = leafs_ptr(t, lf, rl);
            break;
        }
        case TAG_NODE2: {
            const Node2 *n = &t->node2[idx];
            rl = n->rem_len;
            if (rl == 0) return 0;
            p = label8_ptr(t, &n->label, rl);
            break;
        }
        case TAG_NODE8: {
            const Node8 *n = &t->node8[idx];
            rl = n->rem_len;
            if (rl == 0) return 0;
            p = label8_ptr(t, &n->label, rl);
            break;
        }
        case TAG_NODE16: {
            const Node16 *n = &t->node16[idx];
            rl = n->rem_len;
            if (rl == 0) return 0;
            p = label8_ptr(t, &n->label, rl);
            break;
        }
        case TAG_NODE48: {
            const Node48 *n = &t->node48[idx];
            rl = n->rem_len;
            if (rl == 0) return 0;
            p = label8_ptr(t, &n->label, rl);
            break;
        }
        default: {
            const Node256 *n = &t->node256[idx];
            rl = n->rem_len;
            if (rl == 0) return 0;
            p = label8_ptr(t, &n->label, rl);
            break;
        }
    }
    memcpy(buf, p, rl);
    return rl;
}

/* Replace a node's remaining label with new_rem[0..new_rl-1].
 * May change Ref when converting between TAG_LEAF1 and TAG_LEAFS. */
static Ref node_set_label(radix *t, Ref r, const uint8_t *new_rem, size_t new_rl) {
    uint32_t idx = REF_IDX(r);
    uint32_t tag = REF_TAG(r);
    if (tag == TAG_LEAF1) {
        if (new_rl == 0) return r;
        int64_t v = t->leaf1[idx].val;
        free_leaf1(t, idx);
        return make_leaf(t, new_rem, new_rl, v);
    }
    if (tag == TAG_LEAFS) {
        LeafS *lf = &t->leafs[idx];
        size_t old_rl = lf->rem_len;
        if (old_rl > 7) lbl_free(t, old_rl, lf->ext.ref);
        if (new_rl == 0) {
            int64_t v = lf->val;
            free_leafs(t, idx);
            uint32_t ni = alloc_leaf1(t);
            t->leaf1[ni].val = v;
            return MAKE_REF(TAG_LEAF1, ni);
        }
        uint32_t ext_ref = 0;
        if (UNLIKELY(new_rl > 7)) ext_ref = lbl_alloc(t, new_rem, new_rl);
        lf = &t->leafs[idx];
        lf->rem_len = (uint8_t)new_rl;
        if (LIKELY(new_rl <= 7)) memcpy(lf->in, new_rem, new_rl);
        else lf->ext.ref = ext_ref;
        return r;
    }

    /* Internal node: free old external label, then allocate new one if needed. */
    uint32_t new_ext = 0;
    if (UNLIKELY(new_rl > 8)) new_ext = lbl_alloc(t, new_rem, new_rl);

    switch (tag) {
        case TAG_NODE2: {
            Node2 *n = &t->node2[idx];
            free_label8(t, &n->label, n->rem_len);
            n->rem_len = (uint8_t)new_rl;
            if (new_rl > 0) {
                if (LIKELY(new_rl <= 8)) memcpy(n->label.in, new_rem, new_rl);
                else n->label.ext.ref = new_ext;
            }
            break;
        }
        case TAG_NODE8: {
            Node8 *n = &t->node8[idx];
            free_label8(t, &n->label, n->rem_len);
            n->rem_len = (uint8_t)new_rl;
            if (new_rl > 0) {
                if (LIKELY(new_rl <= 8)) memcpy(n->label.in, new_rem, new_rl);
                else n->label.ext.ref = new_ext;
            }
            break;
        }
        case TAG_NODE16: {
            Node16 *n = &t->node16[idx];
            free_label8(t, &n->label, n->rem_len);
            n->rem_len = (uint8_t)new_rl;
            if (new_rl > 0) {
                if (LIKELY(new_rl <= 8)) memcpy(n->label.in, new_rem, new_rl);
                else n->label.ext.ref = new_ext;
            }
            break;
        }
        case TAG_NODE48: {
            Node48 *n = &t->node48[idx];
            free_label8(t, &n->label, n->rem_len);
            n->rem_len = (uint8_t)new_rl;
            if (new_rl > 0) {
                if (LIKELY(new_rl <= 8)) memcpy(n->label.in, new_rem, new_rl);
                else n->label.ext.ref = new_ext;
            }
            break;
        }
        default: {
            Node256 *n = &t->node256[idx];
            free_label8(t, &n->label, n->rem_len);
            n->rem_len = (uint8_t)new_rl;
            if (new_rl > 0) {
                if (LIKELY(new_rl <= 8)) memcpy(n->label.in, new_rem, new_rl);
                else n->label.ext.ref = new_ext;
            }
            break;
        }
    }
    return r;
}

/* Update an existing child slot for byte `b` in `parent` (REF_NONE => root). */
static inline void replace_child(radix *t, Ref parent, uint8_t b, Ref new_child) {
    if (parent == REF_NONE) {
        t->root_child[b] = new_child;
        return;
    }
    uint32_t idx = REF_IDX(parent);
    switch (REF_TAG(parent)) {
        case TAG_NODE2: {
            Node2 *n = &t->node2[idx];
            if (n->keys[0] == b) n->children[0] = new_child;
            else n->children[1] = new_child;
            return;
        }
        case TAG_NODE8: {
            Node8 *n = &t->node8[idx];
            int slot = find_key8(n->keys, n->count, b);
            n->children[slot] = new_child;
            return;
        }
        case TAG_NODE16: {
            Node16 *n = &t->node16[idx];
            int slot = find_key16(n->keys, n->count, b);
            n->children[slot] = new_child;
            return;
        }
        case TAG_NODE48: {
            Node48 *n = &t->node48[idx];
            n->children[n->child_idx[b]] = new_child;
            return;
        }
        default: {
            t->node256[idx].children[b] = new_child;
            return;
        }
    }
}

static inline void inc_subtree_count(radix *t, Ref r) {
    uint32_t idx = REF_IDX(r);
    switch (REF_TAG(r)) {
        case TAG_NODE2:   t->node2[idx].subtree_count++;   break;
        case TAG_NODE8:   t->node8[idx].subtree_count++;   break;
        case TAG_NODE16:  t->node16[idx].subtree_count++;  break;
        case TAG_NODE48:  t->node48[idx].subtree_count++;  break;
        case TAG_NODE256: t->node256[idx].subtree_count++; break;
        default: break;
    }
}

static inline void dec_subtree_count(radix *t, Ref r) {
    uint32_t idx = REF_IDX(r);
    switch (REF_TAG(r)) {
        case TAG_NODE2:   t->node2[idx].subtree_count--;   break;
        case TAG_NODE8:   t->node8[idx].subtree_count--;   break;
        case TAG_NODE16:  t->node16[idx].subtree_count--;  break;
        case TAG_NODE48:  t->node48[idx].subtree_count--;  break;
        case TAG_NODE256: t->node256[idx].subtree_count--; break;
        default: break;
    }
}

/* Add a new child (b, child) to internal node `r`. Returns updated Ref (may grow). */
static Ref node_add_child(radix *t, Ref r, uint8_t b, Ref child) {
    uint32_t idx = REF_IDX(r);
    switch (REF_TAG(r)) {
        case TAG_NODE2: {
            Node2 *n = &t->node2[idx];
            uint32_t cnt = N2_COUNT(n);
            if (cnt < 2u) {
                if (b < n->keys[0]) {
                    n->keys[1] = n->keys[0];
                    n->children[1] = n->children[0];
                    n->keys[0] = b;
                    n->children[0] = child;
                } else {
                    n->keys[1] = b;
                    n->children[1] = child;
                }
                n->meta = N2_META(N2_HAS_VAL(n), 2u);
                return r;
            }
            /* Grow Node2 -> Node8 (transfer Label8 directly without reallocating label). */
            uint32_t n8i = alloc_node8(t);
            n = &t->node2[idx]; /* safe: different pool, still reload for clarity */
            Node8 *n8 = &t->node8[n8i];
            n8->val = n->val;
            n8->subtree_count = n->subtree_count;
            n8->has_val = (uint8_t)N2_HAS_VAL(n);
            n8->rem_len = n->rem_len;
            n8->label = n->label;
            n8->keys[0] = n->keys[0];
            n8->keys[1] = n->keys[1];
            n8->children[0] = n->children[0];
            n8->children[1] = n->children[1];
            free_node2(t, idx);

            uint32_t i = 2;
            while (i > 0 && n8->keys[i - 1] > b) {
                n8->keys[i] = n8->keys[i - 1];
                n8->children[i] = n8->children[i - 1];
                i--;
            }
            n8->keys[i] = b;
            n8->children[i] = child;
            n8->count = 3;
            return MAKE_REF(TAG_NODE8, n8i);
        }

        case TAG_NODE8: {
            Node8 *n = &t->node8[idx];
            uint32_t cnt = n->count;
            if (cnt < 8u) {
                uint32_t i = cnt;
                while (i > 0 && n->keys[i - 1] > b) {
                    n->keys[i] = n->keys[i - 1];
                    n->children[i] = n->children[i - 1];
                    i--;
                }
                n->keys[i] = b;
                n->children[i] = child;
                n->count = (uint8_t)(cnt + 1u);
                return r;
            }
            /* Grow Node8 -> Node16. */
            uint32_t n16i = alloc_node16(t);
            n = &t->node8[idx];
            Node16 *n16 = &t->node16[n16i];
            n16->val = n->val;
            n16->subtree_count = n->subtree_count;
            n16->has_val = n->has_val;
            n16->rem_len = n->rem_len;
            n16->label = n->label;
            memcpy(n16->keys, n->keys, 8);
            memcpy(n16->children, n->children, 8 * sizeof(Ref));
            free_node8(t, idx);

            uint32_t i = 8;
            while (i > 0 && n16->keys[i - 1] > b) {
                n16->keys[i] = n16->keys[i - 1];
                n16->children[i] = n16->children[i - 1];
                i--;
            }
            n16->keys[i] = b;
            n16->children[i] = child;
            n16->count = 9;
            return MAKE_REF(TAG_NODE16, n16i);
        }

        case TAG_NODE16: {
            Node16 *n = &t->node16[idx];
            uint32_t cnt = n->count;
            if (cnt < 16u) {
                uint32_t i = cnt;
                while (i > 0 && n->keys[i - 1] > b) {
                    n->keys[i] = n->keys[i - 1];
                    n->children[i] = n->children[i - 1];
                    i--;
                }
                n->keys[i] = b;
                n->children[i] = child;
                n->count = (uint8_t)(cnt + 1u);
                return r;
            }
            /* Grow Node16 -> Node48. */
            uint32_t n48i = alloc_node48(t);
            n = &t->node16[idx];
            Node48 *n48 = &t->node48[n48i];
            n48->val = n->val;
            n48->subtree_count = n->subtree_count;
            n48->has_val = n->has_val;
            n48->rem_len = n->rem_len;
            n48->label = n->label;
            memset(n48->bitmap, 0, sizeof(n48->bitmap));
            memset(n48->child_idx, 0xFF, 256);
            for (uint32_t i = 0; i < 16u; i++) {
                uint8_t k = n->keys[i];
                n48->child_idx[k] = (uint8_t)i;
                n48->children[i] = n->children[i];
                n48->bitmap[k >> 6] |= 1ULL << (k & 63u);
            }
            free_node16(t, idx);

            n48->child_idx[b] = 16;
            n48->children[16] = child;
            n48->bitmap[b >> 6] |= 1ULL << (b & 63u);
            n48->slot_mask = (1ULL << 17) - 1ULL;
            n48->count = 17;
            return MAKE_REF(TAG_NODE48, n48i);
        }

        case TAG_NODE48: {
            Node48 *n = &t->node48[idx];
            if (n->count < 48u) {
                uint32_t slot = (uint32_t)__builtin_ctzll(~n->slot_mask);
                n->slot_mask |= 1ULL << slot;
                n->child_idx[b] = (uint8_t)slot;
                n->children[slot] = child;
                n->bitmap[b >> 6] |= 1ULL << (b & 63u);
                n->count++;
                return r;
            }
            /* Grow Node48 -> Node256. */
            uint32_t n256i = alloc_node256(t);
            n = &t->node48[idx];
            Node256 *n256 = &t->node256[n256i];
            n256->val = n->val;
            n256->subtree_count = n->subtree_count;
            n256->has_val = n->has_val;
            n256->rem_len = n->rem_len;
            n256->label = n->label;
            memcpy(n256->bitmap, n->bitmap, sizeof(n->bitmap));
            memset(n256->children, 0, sizeof(n256->children));
            for (int w = 0; w < 4; w++) {
                uint64_t bits = n->bitmap[w];
                while (bits) {
                    uint32_t bit = (uint32_t)__builtin_ctzll(bits);
                    bits &= bits - 1;
                    uint32_t k = ((uint32_t)w << 6) | bit;
                    n256->children[k] = n->children[n->child_idx[k]];
                }
            }
            free_node48(t, idx);

            n256->children[b] = child;
            n256->bitmap[b >> 6] |= 1ULL << (b & 63u);
            n256->count = 49;
            return MAKE_REF(TAG_NODE256, n256i);
        }

        default: {
            Node256 *n = &t->node256[idx];
            n->children[b] = child;
            n->bitmap[b >> 6] |= 1ULL << (b & 63u);
            n->count++;
            return r;
        }
    }
}

/* -------------------------------------------------------------------- get */

bool radix_get(const radix *t, const uint8_t *key, size_t len, int64_t *value) {
    if (UNLIKELY(len == 0)) {
        if (t->root_has_val) {
            *value = t->root_val;
            return true;
        }
        return false;
    }

    Ref cur = t->root_child[key[0]];
    if (UNLIKELY(cur == REF_NONE)) return false;
    size_t pos = 1;

    for (;;) {
        uint32_t idx = REF_IDX(cur);
        switch (REF_TAG(cur)) {
            case TAG_LEAF1:
                if (LIKELY(pos == len)) {
                    *value = t->leaf1[idx].val;
                    return true;
                }
                return false;

            case TAG_LEAFS: {
                const LeafS *lf = &t->leafs[idx];
                size_t rl = lf->rem_len;
                if (pos + rl != len) return false;
                if (LIKELY(rl <= 7)) {
                    if (!eq_inline8(key + pos, lf->in, rl)) return false;
                } else {
                    if (memcmp(key + pos, lbl_ptr(t, rl, lf->ext.ref), rl) != 0) return false;
                }
                *value = lf->val;
                return true;
            }

            case TAG_NODE2: {
                const Node2 *n = &t->node2[idx];
                size_t rl = n->rem_len;
                if (rl != 0) {
                    if (pos + rl > len) return false;
                    if (!match_label8(t, key + pos, &n->label, rl)) return false;
                    pos += rl;
                }
                if (pos == len) {
                    if (N2_HAS_VAL(n)) {
                        *value = n->val;
                        return true;
                    }
                    return false;
                }
                uint8_t b = key[pos];
                if (n->keys[0] == b) { cur = n->children[0]; pos++; continue; }
                if (n->keys[1] == b) { cur = n->children[1]; pos++; continue; }
                return false;
            }

            case TAG_NODE8: {
                const Node8 *n = &t->node8[idx];
                size_t rl = n->rem_len;
                if (rl != 0) {
                    if (pos + rl > len) return false;
                    if (!match_label8(t, key + pos, &n->label, rl)) return false;
                    pos += rl;
                }
                if (pos == len) {
                    if (n->has_val) {
                        *value = n->val;
                        return true;
                    }
                    return false;
                }
                int slot = find_key8(n->keys, n->count, key[pos]);
                if (slot < 0) return false;
                cur = n->children[slot];
                pos++;
                continue;
            }

            case TAG_NODE16: {
                const Node16 *n = &t->node16[idx];
                size_t rl = n->rem_len;
                if (UNLIKELY(rl != 0)) {
                    if (pos + rl > len) return false;
                    if (!match_label8(t, key + pos, &n->label, rl)) return false;
                    pos += rl;
                }
                if (pos == len) {
                    if (n->has_val) {
                        *value = n->val;
                        return true;
                    }
                    return false;
                }
                int slot = find_key16(n->keys, n->count, key[pos]);
                if (slot < 0) return false;
                cur = n->children[slot];
                pos++;
                continue;
            }

            case TAG_NODE48: {
                const Node48 *n = &t->node48[idx];
                size_t rl = n->rem_len;
                if (rl != 0) {
                    if (pos + rl > len) return false;
                    if (!match_label8(t, key + pos, &n->label, rl)) return false;
                    pos += rl;
                }
                if (pos == len) {
                    if (n->has_val) {
                        *value = n->val;
                        return true;
                    }
                    return false;
                }
                uint8_t slot = n->child_idx[key[pos]];
                if (slot == 0xFFu) return false;
                cur = n->children[slot];
                pos++;
                continue;
            }

            default: {
                const Node256 *n = &t->node256[idx];
                size_t rl = n->rem_len;
                if (rl != 0) {
                    if (pos + rl > len) return false;
                    if (!match_label8(t, key + pos, &n->label, rl)) return false;
                    pos += rl;
                }
                if (pos == len) {
                    if (n->has_val) {
                        *value = n->val;
                        return true;
                    }
                    return false;
                }
                cur = n->children[key[pos]];
                if (cur == REF_NONE) return false;
                pos++;
                continue;
            }
        }
    }
}

/* -------------------------------------------------------------------- longest_prefix */

bool radix_longest_prefix(const radix *t, const uint8_t *key, size_t len,
                          size_t *match_len, int64_t *value) {
    bool found = false;
    size_t best_len = 0;
    int64_t best_val = 0;

    if (UNLIKELY(t->root_has_val)) {
        found = true;
        best_len = 0;
        best_val = t->root_val;
    }
    if (UNLIKELY(len == 0)) {
        if (found) { *match_len = 0; *value = best_val; }
        return found;
    }

    Ref cur = t->root_child[key[0]];
    if (UNLIKELY(cur == REF_NONE)) {
        if (found) { *match_len = 0; *value = best_val; }
        return found;
    }
    size_t pos = 1;

    for (;;) {
        uint32_t idx = REF_IDX(cur);
        switch (REF_TAG(cur)) {
            case TAG_LEAF1:
                /* 1-byte edge already matched key[pos-1], and pos <= len! */
                *match_len = pos;
                *value = t->leaf1[idx].val;
                return true;

            case TAG_LEAFS: {
                const LeafS *lf = &t->leafs[idx];
                size_t rl = lf->rem_len;
                if (pos + rl <= len) {
                    bool ok = LIKELY(rl <= 7)
                                  ? eq_inline8(key + pos, lf->in, rl)
                                  : (memcmp(key + pos, lbl_ptr(t, rl, lf->ext.ref), rl) == 0);
                    if (ok) {
                        *match_len = pos + rl;
                        *value = lf->val;
                        return true;
                    }
                }
                goto done;
            }

            case TAG_NODE2: {
                const Node2 *n = &t->node2[idx];
                size_t rl = n->rem_len;
                if (rl != 0) {
                    if (pos + rl > len || !match_label8(t, key + pos, &n->label, rl)) goto done;
                    pos += rl;
                }
                if (N2_HAS_VAL(n)) {
                    found = true;
                    best_len = pos;
                    best_val = n->val;
                }
                if (pos == len) goto done;
                uint8_t b = key[pos];
                if (n->keys[0] == b) { cur = n->children[0]; pos++; continue; }
                if (n->keys[1] == b) { cur = n->children[1]; pos++; continue; }
                goto done;
            }

            case TAG_NODE8: {
                const Node8 *n = &t->node8[idx];
                size_t rl = n->rem_len;
                if (rl != 0) {
                    if (pos + rl > len || !match_label8(t, key + pos, &n->label, rl)) goto done;
                    pos += rl;
                }
                if (n->has_val) {
                    found = true;
                    best_len = pos;
                    best_val = n->val;
                }
                if (pos == len) goto done;
                int slot = find_key8(n->keys, n->count, key[pos]);
                if (slot < 0) goto done;
                cur = n->children[slot];
                pos++;
                continue;
            }

            case TAG_NODE16: {
                const Node16 *n = &t->node16[idx];
                size_t rl = n->rem_len;
                if (UNLIKELY(rl != 0)) {
                    if (pos + rl > len || !match_label8(t, key + pos, &n->label, rl)) goto done;
                    pos += rl;
                }
                if (n->has_val) {
                    found = true;
                    best_len = pos;
                    best_val = n->val;
                }
                if (pos == len) goto done;
                int slot = find_key16(n->keys, n->count, key[pos]);
                if (slot < 0) goto done;
                cur = n->children[slot];
                pos++;
                continue;
            }

            case TAG_NODE48: {
                const Node48 *n = &t->node48[idx];
                size_t rl = n->rem_len;
                if (rl != 0) {
                    if (pos + rl > len || !match_label8(t, key + pos, &n->label, rl)) goto done;
                    pos += rl;
                }
                if (n->has_val) {
                    found = true;
                    best_len = pos;
                    best_val = n->val;
                }
                if (pos == len) goto done;
                uint8_t slot = n->child_idx[key[pos]];
                if (slot == 0xFFu) goto done;
                cur = n->children[slot];
                pos++;
                continue;
            }

            default: {
                const Node256 *n = &t->node256[idx];
                size_t rl = n->rem_len;
                if (rl != 0) {
                    if (pos + rl > len || !match_label8(t, key + pos, &n->label, rl)) goto done;
                    pos += rl;
                }
                if (n->has_val) {
                    found = true;
                    best_len = pos;
                    best_val = n->val;
                }
                if (pos == len) goto done;
                cur = n->children[key[pos]];
                if (cur == REF_NONE) goto done;
                pos++;
                continue;
            }
        }
    }

done:
    if (found) {
        *match_len = best_len;
        *value = best_val;
    }
    return found;
}

/* -------------------------------------------------------------------- prefix_count */

size_t radix_prefix_count(const radix *t, const uint8_t *prefix, size_t len) {
    if (len == 0) return (size_t)t->root_count;

    Ref cur = t->root_child[prefix[0]];
    if (UNLIKELY(cur == REF_NONE)) return 0;
    size_t pos = 1;

    for (;;) {
        uint32_t idx = REF_IDX(cur);
        switch (REF_TAG(cur)) {
            case TAG_LEAF1:
                /* Zero memory loads: 1-byte leaf matches iff prefix ended right here! */
                return (pos == len) ? 1u : 0u;

            case TAG_LEAFS: {
                size_t need = len - pos;
                if (need == 0) return 1u; /* Zero memory loads! */
                const LeafS *lf = &t->leafs[idx];
                size_t rl = lf->rem_len;
                if (need > rl) return 0u;
                const uint8_t *lp = leafs_ptr(t, lf, rl);
                return eq_bytes(prefix + pos, lp, need) ? 1u : 0u;
            }

            case TAG_NODE2: {
                const Node2 *n = &t->node2[idx];
                size_t need = len - pos;
                if (need == 0) return (size_t)n->subtree_count;
                size_t rl = n->rem_len;
                if (rl != 0) {
                    size_t cmp = need < rl ? need : rl;
                    if (!eq_bytes(prefix + pos, label8_ptr(t, &n->label, rl), cmp)) return 0u;
                    pos += cmp;
                    if (pos == len) return (size_t)n->subtree_count;
                }
                uint8_t b = prefix[pos];
                if (n->keys[0] == b) { cur = n->children[0]; pos++; continue; }
                if (n->keys[1] == b) { cur = n->children[1]; pos++; continue; }
                return 0u;
            }

            case TAG_NODE8: {
                const Node8 *n = &t->node8[idx];
                size_t need = len - pos;
                if (need == 0) return (size_t)n->subtree_count;
                size_t rl = n->rem_len;
                if (rl != 0) {
                    size_t cmp = need < rl ? need : rl;
                    if (!eq_bytes(prefix + pos, label8_ptr(t, &n->label, rl), cmp)) return 0u;
                    pos += cmp;
                    if (pos == len) return (size_t)n->subtree_count;
                }
                int slot = find_key8(n->keys, n->count, prefix[pos]);
                if (slot < 0) return 0u;
                cur = n->children[slot];
                pos++;
                continue;
            }

            case TAG_NODE16: {
                const Node16 *n = &t->node16[idx];
                size_t need = len - pos;
                if (need == 0) return (size_t)n->subtree_count;
                size_t rl = n->rem_len;
                if (UNLIKELY(rl != 0)) {
                    size_t cmp = need < rl ? need : rl;
                    if (!eq_bytes(prefix + pos, label8_ptr(t, &n->label, rl), cmp)) return 0u;
                    pos += cmp;
                    if (pos == len) return (size_t)n->subtree_count;
                }
                int slot = find_key16(n->keys, n->count, prefix[pos]);
                if (slot < 0) return 0u;
                cur = n->children[slot];
                pos++;
                continue;
            }

            case TAG_NODE48: {
                const Node48 *n = &t->node48[idx];
                size_t need = len - pos;
                if (need == 0) return (size_t)n->subtree_count;
                size_t rl = n->rem_len;
                if (rl != 0) {
                    size_t cmp = need < rl ? need : rl;
                    if (!eq_bytes(prefix + pos, label8_ptr(t, &n->label, rl), cmp)) return 0u;
                    pos += cmp;
                    if (pos == len) return (size_t)n->subtree_count;
                }
                uint8_t slot = n->child_idx[prefix[pos]];
                if (slot == 0xFFu) return 0u;
                cur = n->children[slot];
                pos++;
                continue;
            }

            default: {
                const Node256 *n = &t->node256[idx];
                size_t need = len - pos;
                if (need == 0) return (size_t)n->subtree_count;
                size_t rl = n->rem_len;
                if (rl != 0) {
                    size_t cmp = need < rl ? need : rl;
                    if (!eq_bytes(prefix + pos, label8_ptr(t, &n->label, rl), cmp)) return 0u;
                    pos += cmp;
                    if (pos == len) return (size_t)n->subtree_count;
                }
                cur = n->children[prefix[pos]];
                if (cur == REF_NONE) return 0u;
                pos++;
                continue;
            }
        }
    }
}

/* -------------------------------------------------------------------- prefix_values */

static inline void prefetch_node(const radix *t, Ref r) {
    uint32_t idx = REF_IDX(r);
    switch (REF_TAG(r)) {
        case TAG_LEAF1:   __builtin_prefetch(&t->leaf1[idx], 0, 3); break;
        case TAG_LEAFS:   __builtin_prefetch(&t->leafs[idx], 0, 3); break;
        case TAG_NODE2:   __builtin_prefetch(&t->node2[idx], 0, 3); break;
        case TAG_NODE8:   __builtin_prefetch(&t->node8[idx], 0, 3); break;
        case TAG_NODE16:  __builtin_prefetch(&t->node16[idx], 0, 3); break;
        case TAG_NODE48:  __builtin_prefetch(&t->node48[idx], 0, 3); break;
        case TAG_NODE256: __builtin_prefetch(&t->node256[idx], 0, 3); break;
        default: break;
    }
}

/* Unbounded full-subtree collector (zero limit checks; leaves handled inline). */
static int64_t *collect_all(const radix *t, Ref r, int64_t *out) {
    uint32_t idx = REF_IDX(r);
    switch (REF_TAG(r)) {
        case TAG_LEAF1:
            *out++ = t->leaf1[idx].val;
            return out;

        case TAG_LEAFS:
            *out++ = t->leafs[idx].val;
            return out;

        case TAG_NODE2: {
            const Node2 *n = &t->node2[idx];
            if (N2_HAS_VAL(n)) *out++ = n->val;
            uint32_t cnt = N2_COUNT(n);
            for (uint32_t i = 0; i < cnt; i++) {
                Ref c = n->children[i];
                uint32_t ct = REF_TAG(c);
                if (ct == TAG_LEAF1) {
                    *out++ = t->leaf1[REF_IDX(c)].val;
                } else if (ct == TAG_LEAFS) {
                    *out++ = t->leafs[REF_IDX(c)].val;
                } else {
                    if (i + 1u < cnt) prefetch_node(t, n->children[i + 1u]);
                    out = collect_all(t, c, out);
                }
            }
            return out;
        }

        case TAG_NODE8: {
            const Node8 *n = &t->node8[idx];
            if (n->has_val) *out++ = n->val;
            uint32_t cnt = n->count;
            const Ref *ch = n->children;
            for (uint32_t i = 0; i < cnt; i++) {
                Ref c = ch[i];
                uint32_t ct = REF_TAG(c);
                if (ct == TAG_LEAF1) {
                    *out++ = t->leaf1[REF_IDX(c)].val;
                } else if (ct == TAG_LEAFS) {
                    *out++ = t->leafs[REF_IDX(c)].val;
                } else {
                    if (i + 1u < cnt) prefetch_node(t, ch[i + 1u]);
                    out = collect_all(t, c, out);
                }
            }
            return out;
        }

        case TAG_NODE16: {
            const Node16 *n = &t->node16[idx];
            if (n->has_val) *out++ = n->val;
            uint32_t cnt = n->count;
            const Ref *ch = n->children;
            for (uint32_t i = 0; i < cnt; i++) {
                Ref c = ch[i];
                uint32_t ct = REF_TAG(c);
                if (LIKELY(ct == TAG_LEAF1)) {
                    *out++ = t->leaf1[REF_IDX(c)].val;
                } else if (ct == TAG_LEAFS) {
                    *out++ = t->leafs[REF_IDX(c)].val;
                } else {
                    if (i + 1u < cnt) prefetch_node(t, ch[i + 1u]);
                    out = collect_all(t, c, out);
                }
            }
            return out;
        }

        case TAG_NODE48: {
            const Node48 *n = &t->node48[idx];
            if (n->has_val) *out++ = n->val;
            for (int w = 0; w < 4; w++) {
                uint64_t bits = n->bitmap[w];
                while (bits) {
                    uint32_t bit = (uint32_t)__builtin_ctzll(bits);
                    bits &= bits - 1;
                    uint32_t b = ((uint32_t)w << 6) | bit;
                    Ref c = n->children[n->child_idx[b]];
                    uint32_t ct = REF_TAG(c);
                    if (ct == TAG_LEAF1) *out++ = t->leaf1[REF_IDX(c)].val;
                    else if (ct == TAG_LEAFS) *out++ = t->leafs[REF_IDX(c)].val;
                    else out = collect_all(t, c, out);
                }
            }
            return out;
        }

        default: {
            const Node256 *n = &t->node256[idx];
            if (n->has_val) *out++ = n->val;
            for (int w = 0; w < 4; w++) {
                uint64_t bits = n->bitmap[w];
                while (bits) {
                    uint32_t bit = (uint32_t)__builtin_ctzll(bits);
                    bits &= bits - 1;
                    uint32_t b = ((uint32_t)w << 6) | bit;
                    Ref c = n->children[b];
                    uint32_t ct = REF_TAG(c);
                    if (ct == TAG_LEAF1) *out++ = t->leaf1[REF_IDX(c)].val;
                    else if (ct == TAG_LEAFS) *out++ = t->leafs[REF_IDX(c)].val;
                    else out = collect_all(t, c, out);
                }
            }
            return out;
        }
    }
}

/* Bounded subtree collector (stops immediately when out == end). */
static int64_t *collect_limited(const radix *t, Ref r, int64_t *out, int64_t *end) {
    uint32_t idx = REF_IDX(r);
    switch (REF_TAG(r)) {
        case TAG_LEAF1:
            *out++ = t->leaf1[idx].val;
            return out;

        case TAG_LEAFS:
            *out++ = t->leafs[idx].val;
            return out;

        case TAG_NODE2: {
            const Node2 *n = &t->node2[idx];
            if (N2_HAS_VAL(n)) {
                *out++ = n->val;
                if (out == end) return out;
            }
            uint32_t cnt = N2_COUNT(n);
            for (uint32_t i = 0; i < cnt; i++) {
                Ref c = n->children[i];
                uint32_t ct = REF_TAG(c);
                if (ct == TAG_LEAF1) *out++ = t->leaf1[REF_IDX(c)].val;
                else if (ct == TAG_LEAFS) *out++ = t->leafs[REF_IDX(c)].val;
                else out = collect_limited(t, c, out, end);
                if (out == end) return out;
            }
            return out;
        }

        case TAG_NODE8: {
            const Node8 *n = &t->node8[idx];
            if (n->has_val) {
                *out++ = n->val;
                if (out == end) return out;
            }
            uint32_t cnt = n->count;
            const Ref *ch = n->children;
            for (uint32_t i = 0; i < cnt; i++) {
                Ref c = ch[i];
                uint32_t ct = REF_TAG(c);
                if (ct == TAG_LEAF1) *out++ = t->leaf1[REF_IDX(c)].val;
                else if (ct == TAG_LEAFS) *out++ = t->leafs[REF_IDX(c)].val;
                else out = collect_limited(t, c, out, end);
                if (out == end) return out;
            }
            return out;
        }

        case TAG_NODE16: {
            const Node16 *n = &t->node16[idx];
            if (n->has_val) {
                *out++ = n->val;
                if (out == end) return out;
            }
            uint32_t cnt = n->count;
            const Ref *ch = n->children;
            for (uint32_t i = 0; i < cnt; i++) {
                Ref c = ch[i];
                uint32_t ct = REF_TAG(c);
                if (LIKELY(ct == TAG_LEAF1)) *out++ = t->leaf1[REF_IDX(c)].val;
                else if (ct == TAG_LEAFS) *out++ = t->leafs[REF_IDX(c)].val;
                else out = collect_limited(t, c, out, end);
                if (out == end) return out;
            }
            return out;
        }

        case TAG_NODE48: {
            const Node48 *n = &t->node48[idx];
            if (n->has_val) {
                *out++ = n->val;
                if (out == end) return out;
            }
            for (int w = 0; w < 4; w++) {
                uint64_t bits = n->bitmap[w];
                while (bits) {
                    uint32_t bit = (uint32_t)__builtin_ctzll(bits);
                    bits &= bits - 1;
                    uint32_t b = ((uint32_t)w << 6) | bit;
                    Ref c = n->children[n->child_idx[b]];
                    uint32_t ct = REF_TAG(c);
                    if (ct == TAG_LEAF1) *out++ = t->leaf1[REF_IDX(c)].val;
                    else if (ct == TAG_LEAFS) *out++ = t->leafs[REF_IDX(c)].val;
                    else out = collect_limited(t, c, out, end);
                    if (out == end) return out;
                }
            }
            return out;
        }

        default: {
            const Node256 *n = &t->node256[idx];
            if (n->has_val) {
                *out++ = n->val;
                if (out == end) return out;
            }
            for (int w = 0; w < 4; w++) {
                uint64_t bits = n->bitmap[w];
                while (bits) {
                    uint32_t bit = (uint32_t)__builtin_ctzll(bits);
                    bits &= bits - 1;
                    uint32_t b = ((uint32_t)w << 6) | bit;
                    Ref c = n->children[b];
                    uint32_t ct = REF_TAG(c);
                    if (ct == TAG_LEAF1) *out++ = t->leaf1[REF_IDX(c)].val;
                    else if (ct == TAG_LEAFS) *out++ = t->leafs[REF_IDX(c)].val;
                    else out = collect_limited(t, c, out, end);
                    if (out == end) return out;
                }
            }
            return out;
        }
    }
}

size_t radix_prefix_values(const radix *t, const uint8_t *prefix, size_t len,
                           int64_t *out_values, size_t limit) {
    if (UNLIKELY(limit == 0 || t->root_count == 0)) return 0;

    if (len == 0) {
        int64_t *out = out_values;
        if ((size_t)t->root_count <= limit) {
            if (t->root_has_val) *out++ = t->root_val;
            for (int w = 0; w < 4; w++) {
                uint64_t bits = t->root_bitmap[w];
                while (bits) {
                    uint32_t bit = (uint32_t)__builtin_ctzll(bits);
                    bits &= bits - 1;
                    uint32_t b = ((uint32_t)w << 6) | bit;
                    out = collect_all(t, t->root_child[b], out);
                }
            }
        } else {
            int64_t *end = out_values + limit;
            if (t->root_has_val) {
                *out++ = t->root_val;
                if (out == end) return limit;
            }
            for (int w = 0; w < 4; w++) {
                uint64_t bits = t->root_bitmap[w];
                while (bits) {
                    uint32_t bit = (uint32_t)__builtin_ctzll(bits);
                    bits &= bits - 1;
                    uint32_t b = ((uint32_t)w << 6) | bit;
                    out = collect_limited(t, t->root_child[b], out, end);
                    if (out == end) return limit;
                }
            }
        }
        return (size_t)(out - out_values);
    }

    Ref cur = t->root_child[prefix[0]];
    if (UNLIKELY(cur == REF_NONE)) return 0;
    size_t pos = 1;
    uint32_t sub = 0;

    for (;;) {
        uint32_t idx = REF_IDX(cur);
        switch (REF_TAG(cur)) {
            case TAG_LEAF1:
                if (pos == len) {
                    out_values[0] = t->leaf1[idx].val;
                    return 1u;
                }
                return 0u;

            case TAG_LEAFS: {
                const LeafS *lf = &t->leafs[idx];
                size_t need = len - pos;
                if (need != 0) {
                    size_t rl = lf->rem_len;
                    if (need > rl) return 0u;
                    if (!eq_bytes(prefix + pos, leafs_ptr(t, lf, rl), need)) return 0u;
                }
                out_values[0] = lf->val;
                return 1u;
            }

            case TAG_NODE2: {
                const Node2 *n = &t->node2[idx];
                size_t need = len - pos;
                if (need == 0) { sub = n->subtree_count; goto collect; }
                size_t rl = n->rem_len;
                if (rl != 0) {
                    size_t cmp = need < rl ? need : rl;
                    if (!eq_bytes(prefix + pos, label8_ptr(t, &n->label, rl), cmp)) return 0u;
                    pos += cmp;
                    if (pos == len) { sub = n->subtree_count; goto collect; }
                }
                uint8_t b = prefix[pos];
                if (n->keys[0] == b) { cur = n->children[0]; pos++; continue; }
                if (n->keys[1] == b) { cur = n->children[1]; pos++; continue; }
                return 0u;
            }

            case TAG_NODE8: {
                const Node8 *n = &t->node8[idx];
                size_t need = len - pos;
                if (need == 0) { sub = n->subtree_count; goto collect; }
                size_t rl = n->rem_len;
                if (rl != 0) {
                    size_t cmp = need < rl ? need : rl;
                    if (!eq_bytes(prefix + pos, label8_ptr(t, &n->label, rl), cmp)) return 0u;
                    pos += cmp;
                    if (pos == len) { sub = n->subtree_count; goto collect; }
                }
                int slot = find_key8(n->keys, n->count, prefix[pos]);
                if (slot < 0) return 0u;
                cur = n->children[slot];
                pos++;
                continue;
            }

            case TAG_NODE16: {
                const Node16 *n = &t->node16[idx];
                size_t need = len - pos;
                if (need == 0) { sub = n->subtree_count; goto collect; }
                size_t rl = n->rem_len;
                if (UNLIKELY(rl != 0)) {
                    size_t cmp = need < rl ? need : rl;
                    if (!eq_bytes(prefix + pos, label8_ptr(t, &n->label, rl), cmp)) return 0u;
                    pos += cmp;
                    if (pos == len) { sub = n->subtree_count; goto collect; }
                }
                int slot = find_key16(n->keys, n->count, prefix[pos]);
                if (slot < 0) return 0u;
                cur = n->children[slot];
                pos++;
                continue;
            }

            case TAG_NODE48: {
                const Node48 *n = &t->node48[idx];
                size_t need = len - pos;
                if (need == 0) { sub = n->subtree_count; goto collect; }
                size_t rl = n->rem_len;
                if (rl != 0) {
                    size_t cmp = need < rl ? need : rl;
                    if (!eq_bytes(prefix + pos, label8_ptr(t, &n->label, rl), cmp)) return 0u;
                    pos += cmp;
                    if (pos == len) { sub = n->subtree_count; goto collect; }
                }
                uint8_t slot = n->child_idx[prefix[pos]];
                if (slot == 0xFFu) return 0u;
                cur = n->children[slot];
                pos++;
                continue;
            }

            default: {
                const Node256 *n = &t->node256[idx];
                size_t need = len - pos;
                if (need == 0) { sub = n->subtree_count; goto collect; }
                size_t rl = n->rem_len;
                if (rl != 0) {
                    size_t cmp = need < rl ? need : rl;
                    if (!eq_bytes(prefix + pos, label8_ptr(t, &n->label, rl), cmp)) return 0u;
                    pos += cmp;
                    if (pos == len) { sub = n->subtree_count; goto collect; }
                }
                cur = n->children[prefix[pos]];
                if (cur == REF_NONE) return 0u;
                pos++;
                continue;
            }
        }
    }

collect: {
        int64_t *end;
        if ((size_t)sub <= limit) {
            end = collect_all(t, cur, out_values);
        } else {
            end = collect_limited(t, cur, out_values, out_values + limit);
        }
        return (size_t)(end - out_values);
    }
}

/* -------------------------------------------------------------------- insert */

/* Split edge to `cur` at remaining-label offset `k` (k < cur_rl).
 * `cur_rem` holds a stack copy of `cur`'s full remaining label (length `cur_rl`).
 * `parent` (REF_NONE for root) reaches `cur` via byte `edge_byte`. */
static void split_edge(radix *t, Ref parent, uint8_t edge_byte, Ref cur,
                       const uint8_t *cur_rem, size_t cur_rl, size_t k,
                       const uint8_t *key, size_t pos, size_t len, int64_t value) {
    uint32_t old_sub = node_subtree_count(t, cur);
    uint8_t old_byte = cur_rem[k];

    /* Shorten `cur`'s remaining label to cur_rem[k+1 .. cur_rl-1]. */
    Ref shortened = node_set_label(t, cur, cur_rem + k + 1, cur_rl - k - 1);

    if (pos + k == len) {
        /* New key ends inside edge: mid holds value and 1 child (old_byte -> shortened). */
        uint32_t mi = alloc_node2(t);
        Node2 *mid = &t->node2[mi];
        mid->val = value;
        mid->subtree_count = old_sub + 1u;
        mid->children[0] = shortened;
        mid->keys[0] = old_byte;
        mid->keys[1] = old_byte;
        mid->meta = N2_META(1u, 1u);
        mid->rem_len = (uint8_t)k;
        if (k > 0) {
            if (LIKELY(k <= 8)) {
                memcpy(mid->label.in, cur_rem, k);
            } else {
                uint32_t lref = lbl_alloc(t, cur_rem, k);
                t->node2[mi].label.ext.ref = lref;
            }
        }
        replace_child(t, parent, edge_byte, MAKE_REF(TAG_NODE2, mi));
    } else {
        /* Diverges at k: mid has no value and 2 children (old_byte, new_byte). */
        uint8_t new_byte = key[pos + k];
        Ref new_leaf = make_leaf(t, key + pos + k + 1, len - (pos + k + 1), value);
        uint32_t mi = alloc_node2(t);
        Node2 *mid = &t->node2[mi];
        mid->val = 0;
        mid->subtree_count = old_sub + 1u;
        if (old_byte < new_byte) {
            mid->keys[0] = old_byte; mid->children[0] = shortened;
            mid->keys[1] = new_byte; mid->children[1] = new_leaf;
        } else {
            mid->keys[0] = new_byte; mid->children[0] = new_leaf;
            mid->keys[1] = old_byte; mid->children[1] = shortened;
        }
        mid->meta = N2_META(0u, 2u);
        mid->rem_len = (uint8_t)k;
        if (k > 0) {
            if (LIKELY(k <= 8)) {
                memcpy(mid->label.in, cur_rem, k);
            } else {
                uint32_t lref = lbl_alloc(t, cur_rem, k);
                t->node2[mi].label.ext.ref = lref;
            }
        }
        replace_child(t, parent, edge_byte, MAKE_REF(TAG_NODE2, mi));
    }
}

bool radix_insert(radix *t, const uint8_t *key, size_t len, int64_t value) {
    if (UNLIKELY(len == 0)) {
        if (t->root_has_val) {
            t->root_val = value;
            return false;
        }
        t->root_has_val = 1;
        t->root_val = value;
        t->root_count++;
        return true;
    }

    uint8_t b0 = key[0];
    Ref cur = t->root_child[b0];
    if (cur == REF_NONE) {
        Ref lf = make_leaf(t, key + 1, len - 1, value);
        t->root_child[b0] = lf;
        t->root_bitmap[b0 >> 6] |= 1ULL << (b0 & 63u);
        t->root_nchildren++;
        t->root_count++;
        return true;
    }

    Ref path[256];
    uint32_t depth = 0;
    Ref parent = REF_NONE;
    uint8_t edge_byte = b0;
    size_t pos = 1;

    for (;;) {
        uint32_t idx = REF_IDX(cur);
        switch (REF_TAG(cur)) {
            case TAG_LEAF1: {
                if (pos == len) {
                    t->leaf1[idx].val = value;
                    return false;
                }
                /* Extend 1-byte leaf into a Node2 with rem_len == 0 and 1 child. */
                int64_t old_val = t->leaf1[idx].val;
                free_leaf1(t, idx);
                uint8_t cb = key[pos];
                Ref new_leaf = make_leaf(t, key + pos + 1, len - pos - 1, value);
                uint32_t mi = alloc_node2(t);
                Node2 *mid = &t->node2[mi];
                mid->val = old_val;
                mid->subtree_count = 2u;
                mid->children[0] = new_leaf;
                mid->keys[0] = cb;
                mid->keys[1] = cb;
                mid->meta = N2_META(1u, 1u);
                mid->rem_len = 0;
                replace_child(t, parent, edge_byte, MAKE_REF(TAG_NODE2, mi));
                goto inc_ancestors;
            }

            case TAG_LEAFS: {
                LeafS *lf = &t->leafs[idx];
                size_t rl = lf->rem_len;
                const uint8_t *lp = leafs_ptr(t, lf, rl);
                size_t avail = len - pos;
                size_t max_cmp = rl < avail ? rl : avail;
                size_t k = common_prefix_len(key + pos, lp, max_cmp);
                if (k < rl) {
                    uint8_t cur_rem[256];
                    memcpy(cur_rem, lp, rl);
                    split_edge(t, parent, edge_byte, cur, cur_rem, rl, k, key, pos, len, value);
                    goto inc_ancestors;
                }
                pos += rl;
                if (pos == len) {
                    lf->val = value;
                    return false;
                }
                /* Extend LeafS into a Node2 keeping its remaining label and old_val. */
                int64_t old_val = lf->val;
                uint8_t old_rem[256];
                memcpy(old_rem, lp, rl);
                if (rl > 7) lbl_free(t, rl, lf->ext.ref);
                free_leafs(t, idx);

                uint8_t cb = key[pos];
                Ref new_leaf = make_leaf(t, key + pos + 1, len - pos - 1, value);
                uint32_t mi = alloc_node2(t);
                Node2 *mid = &t->node2[mi];
                mid->val = old_val;
                mid->subtree_count = 2u;
                mid->children[0] = new_leaf;
                mid->keys[0] = cb;
                mid->keys[1] = cb;
                mid->meta = N2_META(1u, 1u);
                mid->rem_len = (uint8_t)rl;
                if (LIKELY(rl <= 8)) {
                    memcpy(mid->label.in, old_rem, rl);
                } else {
                    uint32_t lref = lbl_alloc(t, old_rem, rl);
                    t->node2[mi].label.ext.ref = lref;
                }
                replace_child(t, parent, edge_byte, MAKE_REF(TAG_NODE2, mi));
                goto inc_ancestors;
            }

            case TAG_NODE2: {
                Node2 *n = &t->node2[idx];
                size_t rl = n->rem_len;
                if (rl != 0) {
                    const uint8_t *lp = label8_ptr(t, &n->label, rl);
                    size_t avail = len - pos;
                    size_t max_cmp = rl < avail ? rl : avail;
                    size_t k = common_prefix_len(key + pos, lp, max_cmp);
                    if (k < rl) {
                        uint8_t cur_rem[256];
                        memcpy(cur_rem, lp, rl);
                        split_edge(t, parent, edge_byte, cur, cur_rem, rl, k, key, pos, len, value);
                        goto inc_ancestors;
                    }
                    pos += rl;
                }
                if (pos == len) {
                    if (N2_HAS_VAL(n)) { n->val = value; return false; }
                    n->val = value;
                    n->meta = N2_META(1u, N2_COUNT(n));
                    n->subtree_count++;
                    goto inc_ancestors;
                }
                uint8_t b = key[pos];
                Ref next = REF_NONE;
                if (n->keys[0] == b) next = n->children[0];
                else if (n->keys[1] == b) next = n->children[1];
                if (next == REF_NONE) goto add_child;
                path[depth++] = cur;
                parent = cur;
                edge_byte = b;
                cur = next;
                pos++;
                continue;
            }

            case TAG_NODE8: {
                Node8 *n = &t->node8[idx];
                size_t rl = n->rem_len;
                if (rl != 0) {
                    const uint8_t *lp = label8_ptr(t, &n->label, rl);
                    size_t avail = len - pos;
                    size_t max_cmp = rl < avail ? rl : avail;
                    size_t k = common_prefix_len(key + pos, lp, max_cmp);
                    if (k < rl) {
                        uint8_t cur_rem[256];
                        memcpy(cur_rem, lp, rl);
                        split_edge(t, parent, edge_byte, cur, cur_rem, rl, k, key, pos, len, value);
                        goto inc_ancestors;
                    }
                    pos += rl;
                }
                if (pos == len) {
                    if (n->has_val) { n->val = value; return false; }
                    n->val = value; n->has_val = 1; n->subtree_count++;
                    goto inc_ancestors;
                }
                uint8_t b = key[pos];
                int slot = find_key8(n->keys, n->count, b);
                if (slot < 0) goto add_child;
                path[depth++] = cur;
                parent = cur;
                edge_byte = b;
                cur = n->children[slot];
                pos++;
                continue;
            }

            case TAG_NODE16: {
                Node16 *n = &t->node16[idx];
                size_t rl = n->rem_len;
                if (UNLIKELY(rl != 0)) {
                    const uint8_t *lp = label8_ptr(t, &n->label, rl);
                    size_t avail = len - pos;
                    size_t max_cmp = rl < avail ? rl : avail;
                    size_t k = common_prefix_len(key + pos, lp, max_cmp);
                    if (k < rl) {
                        uint8_t cur_rem[256];
                        memcpy(cur_rem, lp, rl);
                        split_edge(t, parent, edge_byte, cur, cur_rem, rl, k, key, pos, len, value);
                        goto inc_ancestors;
                    }
                    pos += rl;
                }
                if (pos == len) {
                    if (n->has_val) { n->val = value; return false; }
                    n->val = value; n->has_val = 1; n->subtree_count++;
                    goto inc_ancestors;
                }
                uint8_t b = key[pos];
                int slot = find_key16(n->keys, n->count, b);
                if (slot < 0) goto add_child;
                path[depth++] = cur;
                parent = cur;
                edge_byte = b;
                cur = n->children[slot];
                pos++;
                continue;
            }

            case TAG_NODE48: {
                Node48 *n = &t->node48[idx];
                size_t rl = n->rem_len;
                if (rl != 0) {
                    const uint8_t *lp = label8_ptr(t, &n->label, rl);
                    size_t avail = len - pos;
                    size_t max_cmp = rl < avail ? rl : avail;
                    size_t k = common_prefix_len(key + pos, lp, max_cmp);
                    if (k < rl) {
                        uint8_t cur_rem[256];
                        memcpy(cur_rem, lp, rl);
                        split_edge(t, parent, edge_byte, cur, cur_rem, rl, k, key, pos, len, value);
                        goto inc_ancestors;
                    }
                    pos += rl;
                }
                if (pos == len) {
                    if (n->has_val) { n->val = value; return false; }
                    n->val = value; n->has_val = 1; n->subtree_count++;
                    goto inc_ancestors;
                }
                uint8_t b = key[pos];
                uint8_t slot = n->child_idx[b];
                if (slot == 0xFFu) goto add_child;
                path[depth++] = cur;
                parent = cur;
                edge_byte = b;
                cur = n->children[slot];
                pos++;
                continue;
            }

            default: {
                Node256 *n = &t->node256[idx];
                size_t rl = n->rem_len;
                if (rl != 0) {
                    const uint8_t *lp = label8_ptr(t, &n->label, rl);
                    size_t avail = len - pos;
                    size_t max_cmp = rl < avail ? rl : avail;
                    size_t k = common_prefix_len(key + pos, lp, max_cmp);
                    if (k < rl) {
                        uint8_t cur_rem[256];
                        memcpy(cur_rem, lp, rl);
                        split_edge(t, parent, edge_byte, cur, cur_rem, rl, k, key, pos, len, value);
                        goto inc_ancestors;
                    }
                    pos += rl;
                }
                if (pos == len) {
                    if (n->has_val) { n->val = value; return false; }
                    n->val = value; n->has_val = 1; n->subtree_count++;
                    goto inc_ancestors;
                }
                uint8_t b = key[pos];
                Ref next = n->children[b];
                if (next == REF_NONE) goto add_child;
                path[depth++] = cur;
                parent = cur;
                edge_byte = b;
                cur = next;
                pos++;
                continue;
            }
        }
    }

add_child: {
        uint8_t b = key[pos];
        Ref new_leaf = make_leaf(t, key + pos + 1, len - pos - 1, value);
        Ref new_cur = node_add_child(t, cur, b, new_leaf);
        if (new_cur != cur) replace_child(t, parent, edge_byte, new_cur);
        inc_subtree_count(t, new_cur);
    }

inc_ancestors:
    t->root_count++;
    for (uint32_t i = 0; i < depth; i++) {
        inc_subtree_count(t, path[i]);
    }
    return true;
}

/* -------------------------------------------------------------------- remove */

/* Free an internal node and its external label (if any). */
static void free_internal_with_label(radix *t, Ref r) {
    uint32_t idx = REF_IDX(r);
    switch (REF_TAG(r)) {
        case TAG_NODE2:
            free_label8(t, &t->node2[idx].label, t->node2[idx].rem_len);
            free_node2(t, idx);
            break;
        case TAG_NODE8:
            free_label8(t, &t->node8[idx].label, t->node8[idx].rem_len);
            free_node8(t, idx);
            break;
        case TAG_NODE16:
            free_label8(t, &t->node16[idx].label, t->node16[idx].rem_len);
            free_node16(t, idx);
            break;
        case TAG_NODE48:
            free_label8(t, &t->node48[idx].label, t->node48[idx].rem_len);
            free_node48(t, idx);
            break;
        default:
            free_label8(t, &t->node256[idx].label, t->node256[idx].rem_len);
            free_node256(t, idx);
            break;
    }
}

/* Merge internal node `node` (which has has_val == 0 and exactly 1 child: only_byte -> only_child)
 * into `only_child`. Frees `node` and returns the merged Ref. */
static Ref merge_with_single_child(radix *t, Ref node, uint8_t only_byte, Ref only_child) {
    uint8_t merged[256];
    size_t prl = node_copy_label(t, node, merged);
    merged[prl] = only_byte;
    size_t crl = node_copy_label(t, only_child, merged + prl + 1);
    free_internal_with_label(t, node);
    return node_set_label(t, only_child, merged, prl + 1 + crl);
}

/* Remove child `b` from internal node `r` (which already had its subtree_count decremented).
 * Handles converting 0-child node to leaf, merging 1-child valueless node, and shrinking.
 * Returns the replacement Ref to store in `r`'s parent. */
static Ref node_remove_child(radix *t, Ref r, uint8_t b) {
    uint32_t idx = REF_IDX(r);
    uint32_t tag = REF_TAG(r);

    switch (tag) {
        case TAG_NODE2: {
            Node2 *n = &t->node2[idx];
            uint32_t cnt = N2_COUNT(n);
            uint32_t hv = N2_HAS_VAL(n);
            if (cnt == 1u) {
                /* Must have has_val == 1; convert to leaf! */
                uint8_t lbuf[256];
                size_t rl = node_copy_label(t, r, lbuf);
                int64_t val = n->val;
                free_internal_with_label(t, r);
                return make_leaf(t, lbuf, rl, val);
            }
            /* cnt == 2 -> becomes 1 child. */
            uint8_t rem_byte;
            Ref rem_child;
            if (n->keys[0] == b) {
                rem_byte = n->keys[1];
                rem_child = n->children[1];
            } else {
                rem_byte = n->keys[0];
                rem_child = n->children[0];
            }
            if (!hv) {
                return merge_with_single_child(t, r, rem_byte, rem_child);
            }
            n->keys[0] = rem_byte;
            n->keys[1] = rem_byte;
            n->children[0] = rem_child;
            n->meta = N2_META(1u, 1u);
            return r;
        }

        case TAG_NODE8: {
            Node8 *n = &t->node8[idx];
            uint32_t cnt = n->count;
            int slot = find_key8(n->keys, cnt, b);
            uint32_t new_cnt = cnt - 1u;
            for (uint32_t i = (uint32_t)slot; i < new_cnt; i++) {
                n->keys[i] = n->keys[i + 1u];
                n->children[i] = n->children[i + 1u];
            }
            n->count = (uint8_t)new_cnt;
            if (new_cnt == 0u) {
                uint8_t lbuf[256];
                size_t rl = node_copy_label(t, r, lbuf);
                int64_t val = n->val;
                free_internal_with_label(t, r);
                return make_leaf(t, lbuf, rl, val);
            }
            if (new_cnt == 1u) {
                if (!n->has_val) {
                    return merge_with_single_child(t, r, n->keys[0], n->children[0]);
                }
                /* Shrink Node8 -> Node2 (transfer Label8 directly). */
                uint32_t n2i = alloc_node2(t);
                n = &t->node8[idx];
                Node2 *n2 = &t->node2[n2i];
                n2->val = n->val;
                n2->subtree_count = n->subtree_count;
                n2->children[0] = n->children[0];
                n2->keys[0] = n->keys[0];
                n2->keys[1] = n->keys[0];
                n2->meta = N2_META(1u, 1u);
                n2->rem_len = n->rem_len;
                n2->label = n->label;
                free_node8(t, idx);
                return MAKE_REF(TAG_NODE2, n2i);
            }
            return r;
        }

        case TAG_NODE16: {
            Node16 *n = &t->node16[idx];
            uint32_t cnt = n->count;
            int slot = find_key16(n->keys, cnt, b);
            uint32_t new_cnt = cnt - 1u;
            for (uint32_t i = (uint32_t)slot; i < new_cnt; i++) {
                n->keys[i] = n->keys[i + 1u];
                n->children[i] = n->children[i + 1u];
            }
            n->count = (uint8_t)new_cnt;
            if (new_cnt <= 6u) {
                /* Shrink Node16 -> Node8 (hysteresis at 6). */
                uint32_t n8i = alloc_node8(t);
                n = &t->node16[idx];
                Node8 *n8 = &t->node8[n8i];
                n8->val = n->val;
                n8->subtree_count = n->subtree_count;
                n8->has_val = n->has_val;
                n8->count = (uint8_t)new_cnt;
                n8->rem_len = n->rem_len;
                n8->label = n->label;
                memcpy(n8->keys, n->keys, new_cnt);
                memcpy(n8->children, n->children, new_cnt * sizeof(Ref));
                free_node16(t, idx);
                return MAKE_REF(TAG_NODE8, n8i);
            }
            return r;
        }

        case TAG_NODE48: {
            Node48 *n = &t->node48[idx];
            uint8_t slot = n->child_idx[b];
            n->child_idx[b] = 0xFFu;
            n->slot_mask &= ~(1ULL << slot);
            n->bitmap[b >> 6] &= ~(1ULL << (b & 63u));
            uint32_t new_cnt = --n->count;
            if (new_cnt <= 12u) {
                /* Shrink Node48 -> Node16 (hysteresis at 12). */
                uint32_t n16i = alloc_node16(t);
                n = &t->node48[idx];
                Node16 *n16 = &t->node16[n16i];
                n16->val = n->val;
                n16->subtree_count = n->subtree_count;
                n16->has_val = n->has_val;
                n16->count = (uint8_t)new_cnt;
                n16->rem_len = n->rem_len;
                n16->label = n->label;
                uint32_t out = 0;
                for (int w = 0; w < 4; w++) {
                    uint64_t bits = n->bitmap[w];
                    while (bits) {
                        uint32_t bit = (uint32_t)__builtin_ctzll(bits);
                        bits &= bits - 1;
                        uint32_t k = ((uint32_t)w << 6) | bit;
                        n16->keys[out] = (uint8_t)k;
                        n16->children[out] = n->children[n->child_idx[k]];
                        out++;
                    }
                }
                free_node48(t, idx);
                return MAKE_REF(TAG_NODE16, n16i);
            }
            return r;
        }

        default: {
            Node256 *n = &t->node256[idx];
            n->children[b] = REF_NONE;
            n->bitmap[b >> 6] &= ~(1ULL << (b & 63u));
            uint32_t new_cnt = --n->count;
            if (new_cnt <= 36u) {
                /* Shrink Node256 -> Node48 (hysteresis at 36). */
                uint32_t n48i = alloc_node48(t);
                n = &t->node256[idx];
                Node48 *n48 = &t->node48[n48i];
                n48->val = n->val;
                n48->subtree_count = n->subtree_count;
                n48->has_val = n->has_val;
                n48->count = (uint8_t)new_cnt;
                n48->rem_len = n->rem_len;
                n48->label = n->label;
                memcpy(n48->bitmap, n->bitmap, sizeof(n->bitmap));
                memset(n48->child_idx, 0xFF, 256);
                uint32_t out = 0;
                for (int w = 0; w < 4; w++) {
                    uint64_t bits = n->bitmap[w];
                    while (bits) {
                        uint32_t bit = (uint32_t)__builtin_ctzll(bits);
                        bits &= bits - 1;
                        uint32_t k = ((uint32_t)w << 6) | bit;
                        n48->child_idx[k] = (uint8_t)out;
                        n48->children[out] = n->children[k];
                        out++;
                    }
                }
                n48->slot_mask = (1ULL << out) - 1ULL;
                free_node256(t, idx);
                return MAKE_REF(TAG_NODE48, n48i);
            }
            return r;
        }
    }
}

bool radix_remove(radix *t, const uint8_t *key, size_t len) {
    if (UNLIKELY(len == 0)) {
        if (!t->root_has_val) return false;
        t->root_has_val = 0;
        t->root_count--;
        return true;
    }

    uint8_t b0 = key[0];
    Ref cur = t->root_child[b0];
    if (UNLIKELY(cur == REF_NONE)) return false;

    Ref path[256];       /* internal ancestors above cur: path[0] is child of root */
    uint8_t pbyte[256];  /* pbyte[i] is edge byte entering path[i] (or cur when i == depth) */
    uint32_t depth = 0;
    pbyte[0] = b0;
    size_t pos = 1;

    for (;;) {
        uint32_t idx = REF_IDX(cur);
        switch (REF_TAG(cur)) {
            case TAG_LEAF1:
                if (pos != len) return false;
                free_leaf1(t, idx);
                goto removed_leaf;

            case TAG_LEAFS: {
                LeafS *lf = &t->leafs[idx];
                size_t rl = lf->rem_len;
                if (pos + rl != len) return false;
                if (LIKELY(rl <= 7)) {
                    if (!eq_inline8(key + pos, lf->in, rl)) return false;
                } else {
                    if (memcmp(key + pos, lbl_ptr(t, rl, lf->ext.ref), rl) != 0) return false;
                    lbl_free(t, rl, lf->ext.ref);
                }
                free_leafs(t, idx);
                goto removed_leaf;
            }

            case TAG_NODE2: {
                Node2 *n = &t->node2[idx];
                size_t rl = n->rem_len;
                if (rl != 0) {
                    if (pos + rl > len || !match_label8(t, key + pos, &n->label, rl)) return false;
                    pos += rl;
                }
                if (pos == len) {
                    if (!N2_HAS_VAL(n)) return false;
                    uint32_t cnt = N2_COUNT(n);
                    n->meta = N2_META(0u, cnt);
                    n->subtree_count--;
                    uint8_t ob = n->keys[0];
                    Ref oc = n->children[0];
                    t->root_count--;
                    for (uint32_t i = 0; i < depth; i++) dec_subtree_count(t, path[i]);
                    if (cnt == 1u) {
                        Ref merged = merge_with_single_child(t, cur, ob, oc);
                        Ref parent = (depth == 0) ? REF_NONE : path[depth - 1];
                        replace_child(t, parent, pbyte[depth], merged);
                    }
                    return true;
                }
                uint8_t b = key[pos];
                Ref next = REF_NONE;
                if (n->keys[0] == b) next = n->children[0];
                else if (n->keys[1] == b) next = n->children[1];
                if (next == REF_NONE) return false;
                path[depth++] = cur;
                pbyte[depth] = b;
                cur = next;
                pos++;
                continue;
            }

            case TAG_NODE8: {
                Node8 *n = &t->node8[idx];
                size_t rl = n->rem_len;
                if (rl != 0) {
                    if (pos + rl > len || !match_label8(t, key + pos, &n->label, rl)) return false;
                    pos += rl;
                }
                if (pos == len) {
                    if (!n->has_val) return false;
                    n->has_val = 0;
                    n->subtree_count--;
                    uint32_t cnt = n->count;
                    uint8_t ob = n->keys[0];
                    Ref oc = n->children[0];
                    t->root_count--;
                    for (uint32_t i = 0; i < depth; i++) dec_subtree_count(t, path[i]);
                    if (UNLIKELY(cnt == 1u)) {
                        Ref merged = merge_with_single_child(t, cur, ob, oc);
                        Ref parent = (depth == 0) ? REF_NONE : path[depth - 1];
                        replace_child(t, parent, pbyte[depth], merged);
                    }
                    return true;
                }
                uint8_t b = key[pos];
                int slot = find_key8(n->keys, n->count, b);
                if (slot < 0) return false;
                path[depth++] = cur;
                pbyte[depth] = b;
                cur = n->children[slot];
                pos++;
                continue;
            }

            case TAG_NODE16: {
                Node16 *n = &t->node16[idx];
                size_t rl = n->rem_len;
                if (UNLIKELY(rl != 0)) {
                    if (pos + rl > len || !match_label8(t, key + pos, &n->label, rl)) return false;
                    pos += rl;
                }
                if (pos == len) {
                    if (!n->has_val) return false;
                    n->has_val = 0;
                    n->subtree_count--;
                    t->root_count--;
                    for (uint32_t i = 0; i < depth; i++) dec_subtree_count(t, path[i]);
                    return true;
                }
                uint8_t b = key[pos];
                int slot = find_key16(n->keys, n->count, b);
                if (slot < 0) return false;
                path[depth++] = cur;
                pbyte[depth] = b;
                cur = n->children[slot];
                pos++;
                continue;
            }

            case TAG_NODE48: {
                Node48 *n = &t->node48[idx];
                size_t rl = n->rem_len;
                if (rl != 0) {
                    if (pos + rl > len || !match_label8(t, key + pos, &n->label, rl)) return false;
                    pos += rl;
                }
                if (pos == len) {
                    if (!n->has_val) return false;
                    n->has_val = 0;
                    n->subtree_count--;
                    t->root_count--;
                    for (uint32_t i = 0; i < depth; i++) dec_subtree_count(t, path[i]);
                    return true;
                }
                uint8_t b = key[pos];
                uint8_t slot = n->child_idx[b];
                if (slot == 0xFFu) return false;
                path[depth++] = cur;
                pbyte[depth] = b;
                cur = n->children[slot];
                pos++;
                continue;
            }

            default: {
                Node256 *n = &t->node256[idx];
                size_t rl = n->rem_len;
                if (rl != 0) {
                    if (pos + rl > len || !match_label8(t, key + pos, &n->label, rl)) return false;
                    pos += rl;
                }
                if (pos == len) {
                    if (!n->has_val) return false;
                    n->has_val = 0;
                    n->subtree_count--;
                    t->root_count--;
                    for (uint32_t i = 0; i < depth; i++) dec_subtree_count(t, path[i]);
                    return true;
                }
                uint8_t b = key[pos];
                Ref next = n->children[b];
                if (next == REF_NONE) return false;
                path[depth++] = cur;
                pbyte[depth] = b;
                cur = next;
                pos++;
                continue;
            }
        }
    }

removed_leaf:
    t->root_count--;
    if (depth == 0) {
        t->root_child[b0] = REF_NONE;
        t->root_bitmap[b0 >> 6] &= ~(1ULL << (b0 & 63u));
        t->root_nchildren--;
        return true;
    }
    for (uint32_t i = 0; i < depth; i++) {
        dec_subtree_count(t, path[i]);
    }
    Ref parent = path[depth - 1];
    Ref new_parent = node_remove_child(t, parent, pbyte[depth]);
    if (new_parent != parent) {
        Ref grandparent = (depth >= 2) ? path[depth - 2] : REF_NONE;
        replace_child(t, grandparent, pbyte[depth - 1], new_parent);
    }
    return true;
}

/* -------------------------------------------------------------------- node_count & height */

static size_t count_nodes_rec(const radix *t, Ref r) {
    uint32_t idx = REF_IDX(r);
    size_t total = 1;
    switch (REF_TAG(r)) {
        case TAG_LEAF1:
        case TAG_LEAFS:
            return 1;
        case TAG_NODE2: {
            const Node2 *n = &t->node2[idx];
            uint32_t cnt = N2_COUNT(n);
            for (uint32_t i = 0; i < cnt; i++) total += count_nodes_rec(t, n->children[i]);
            return total;
        }
        case TAG_NODE8: {
            const Node8 *n = &t->node8[idx];
            for (uint32_t i = 0; i < n->count; i++) total += count_nodes_rec(t, n->children[i]);
            return total;
        }
        case TAG_NODE16: {
            const Node16 *n = &t->node16[idx];
            for (uint32_t i = 0; i < n->count; i++) total += count_nodes_rec(t, n->children[i]);
            return total;
        }
        case TAG_NODE48: {
            const Node48 *n = &t->node48[idx];
            for (int w = 0; w < 4; w++) {
                uint64_t bits = n->bitmap[w];
                while (bits) {
                    uint32_t bit = (uint32_t)__builtin_ctzll(bits);
                    bits &= bits - 1;
                    uint32_t b = ((uint32_t)w << 6) | bit;
                    total += count_nodes_rec(t, n->children[n->child_idx[b]]);
                }
            }
            return total;
        }
        default: {
            const Node256 *n = &t->node256[idx];
            for (int w = 0; w < 4; w++) {
                uint64_t bits = n->bitmap[w];
                while (bits) {
                    uint32_t bit = (uint32_t)__builtin_ctzll(bits);
                    bits &= bits - 1;
                    uint32_t b = ((uint32_t)w << 6) | bit;
                    total += count_nodes_rec(t, n->children[b]);
                }
            }
            return total;
        }
    }
}

size_t radix_node_count(const radix *t) {
    size_t total = 1; /* root */
    for (int w = 0; w < 4; w++) {
        uint64_t bits = t->root_bitmap[w];
        while (bits) {
            uint32_t bit = (uint32_t)__builtin_ctzll(bits);
            bits &= bits - 1;
            uint32_t b = ((uint32_t)w << 6) | bit;
            total += count_nodes_rec(t, t->root_child[b]);
        }
    }
    return total;
}

static size_t height_rec(const radix *t, Ref r) {
    uint32_t idx = REF_IDX(r);
    size_t best = 0;
    switch (REF_TAG(r)) {
        case TAG_LEAF1:
        case TAG_LEAFS:
            return 0;
        case TAG_NODE2: {
            const Node2 *n = &t->node2[idx];
            uint32_t cnt = N2_COUNT(n);
            for (uint32_t i = 0; i < cnt; i++) {
                size_t h = 1 + height_rec(t, n->children[i]);
                if (h > best) best = h;
            }
            return best;
        }
        case TAG_NODE8: {
            const Node8 *n = &t->node8[idx];
            for (uint32_t i = 0; i < n->count; i++) {
                size_t h = 1 + height_rec(t, n->children[i]);
                if (h > best) best = h;
            }
            return best;
        }
        case TAG_NODE16: {
            const Node16 *n = &t->node16[idx];
            for (uint32_t i = 0; i < n->count; i++) {
                size_t h = 1 + height_rec(t, n->children[i]);
                if (h > best) best = h;
            }
            return best;
        }
        case TAG_NODE48: {
            const Node48 *n = &t->node48[idx];
            for (int w = 0; w < 4; w++) {
                uint64_t bits = n->bitmap[w];
                while (bits) {
                    uint32_t bit = (uint32_t)__builtin_ctzll(bits);
                    bits &= bits - 1;
                    uint32_t b = ((uint32_t)w << 6) | bit;
                    size_t h = 1 + height_rec(t, n->children[n->child_idx[b]]);
                    if (h > best) best = h;
                }
            }
            return best;
        }
        default: {
            const Node256 *n = &t->node256[idx];
            for (int w = 0; w < 4; w++) {
                uint64_t bits = n->bitmap[w];
                while (bits) {
                    uint32_t bit = (uint32_t)__builtin_ctzll(bits);
                    bits &= bits - 1;
                    uint32_t b = ((uint32_t)w << 6) | bit;
                    size_t h = 1 + height_rec(t, n->children[b]);
                    if (h > best) best = h;
                }
            }
            return best;
        }
    }
}

size_t radix_height(const radix *t) {
    size_t best = 0;
    for (int w = 0; w < 4; w++) {
        uint64_t bits = t->root_bitmap[w];
        while (bits) {
            uint32_t bit = (uint32_t)__builtin_ctzll(bits);
            bits &= bits - 1;
            uint32_t b = ((uint32_t)w << 6) | bit;
            size_t h = 1 + height_rec(t, t->root_child[b]);
            if (h > best) best = h;
        }
    }
    return best;
}
