// Radix tree (path-compressed byte trie) with subtree counts.
//
// Every node is one variable-size block from a size-class pool:
//
//   offset 0   int64  value
//   offset 8   uint32 count     keys stored in the subtree (incl. this node)
//   offset 12  uint16 nchild    number of children
//   offset 14  uint8  len       label length (0 only for the root)
//   offset 15  uint8  hasv      node holds a key
//   offset 16  uint16 cap       capacity of the child arrays (0,2,4,...,256)
//   offset 18  uint8  szc       allocation size / 16
//   offset 19  label[len]       the edge label, first byte included
//              keys[round8(cap)] first bytes of the children, sorted
//              (pad to 8)
//              node *ptrs[cap]  children, in the same order as keys
//
// Header, label and child first bytes sit together at the start of the
// block, so a step down the tree usually touches a single cache line.

#include "radix.h"

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

typedef struct node {
    int64_t value;
    uint32_t count;
    uint16_t nchild;
    uint8_t len;
    uint8_t hasv;
    uint16_t cap;
    uint8_t szc;
    uint8_t data[];
} node;

#define H 19
_Static_assert(offsetof(node, data) == H, "layout");

#define MAXSIZE 2592
#define NCLS (MAXSIZE / 16 + 1)

typedef struct chunk {
    struct chunk *next;
    void *pad;
} chunk;

struct radix {
    node *root;
    size_t size;
    char *cur, *end;
    chunk *chunks;
    size_t chunk_sz;
    void *fl[NCLS];
};

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

// ------------------------------------------------------------ layout helpers

static inline size_t kround(unsigned cap) { return (cap + 7u) & ~(size_t)7; }
static inline size_t ptroff(unsigned len, unsigned cap) {
    return (H + len + kround(cap) + 7) & ~(size_t)7;
}
static inline size_t nsize(unsigned len, unsigned cap) {
    return (ptroff(len, cap) + 8 * (size_t)cap + 15) & ~(size_t)15;
}
static inline uint8_t *lab(const node *n) { return (uint8_t *)n + H; }
static inline uint8_t *nkeys(const node *n) { return (uint8_t *)n + H + n->len; }
static inline node **nptrs(const node *n) {
    return (node **)((char *)n + ptroff(n->len, n->cap));
}

static inline uint64_t ld64(const void *p) {
    uint64_t x;
    memcpy(&x, p, 8);
    return x;
}
static inline uint32_t ld32(const void *p) {
    uint32_t x;
    memcpy(&x, p, 4);
    return x;
}
static inline uint16_t ld16(const void *p) {
    uint16_t x;
    memcpy(&x, p, 2);
    return x;
}

// Index of the first byte where a and b differ (n if equal). Little endian.
static inline size_t mismatch(const uint8_t *a, const uint8_t *b, size_t n) {
    size_t i = 0;
    for (; i + 8 <= n; i += 8) {
        uint64_t x = ld64(a + i) ^ ld64(b + i);
        if (x) return i + ((size_t)__builtin_ctzll(x) >> 3);
    }
    if (i + 4 <= n) {
        uint32_t x = ld32(a + i) ^ ld32(b + i);
        if (x) return i + ((size_t)__builtin_ctz(x) >> 3);
        i += 4;
    }
    while (i < n && a[i] == b[i]) i++;
    return i;
}

static inline bool eq(const uint8_t *a, const uint8_t *b, size_t n) {
    size_t i = 0;
    for (; i + 8 <= n; i += 8) {
        if (ld64(a + i) != ld64(b + i)) return false;
    }
    size_t r = n - i;
    if (r >= 4) return ld32(a + i) == ld32(b + i) && ld32(a + n - 4) == ld32(b + n - 4);
    if (r >= 2) return ld16(a + i) == ld16(b + i) && ld16(a + n - 2) == ld16(b + n - 2);
    if (r == 1) return a[i] == b[i];
    return true;
}

// Index of the child whose label starts with b, or -1.
static inline int find(const node *n, uint8_t b) {
    unsigned nc = n->nchild;
    const uint8_t *k = nkeys(n);
    const uint64_t ones = 0x0101010101010101ULL;
    uint64_t pat = ones * b;
    for (unsigned i = 0; i < nc; i += 8) {
        uint64_t x = ld64(k + i) ^ pat;
        uint64_t m = (x - ones) & ~x & (ones << 7);
        if (m) {
            unsigned j = i + ((unsigned)__builtin_ctzll(m) >> 3);
            return j < nc ? (int)j : -1;
        }
    }
    return -1;
}

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

static void *pool_alloc(radix *t, size_t sz) {
    size_t c = sz >> 4;
    void *p = t->fl[c];
    if (p) {
        t->fl[c] = *(void **)p;
        return p;
    }
    if (UNLIKELY((size_t)(t->end - t->cur) < sz)) {
        size_t rem = (size_t)(t->end - t->cur);
        if (rem >= 16) {
            *(void **)t->cur = t->fl[rem >> 4];
            t->fl[rem >> 4] = t->cur;
        }
        size_t cs = t->chunk_sz;
        if (cs < (8u << 20)) t->chunk_sz = cs * 2;
        chunk *ch = malloc(cs);
        if (!ch) abort();
        ch->next = t->chunks;
        t->chunks = ch;
        t->cur = (char *)ch + sizeof(chunk);
        t->end = (char *)ch + cs;
    }
    p = t->cur;
    t->cur += sz;
    return p;
}

static inline void node_free(radix *t, node *n) {
    size_t c = n->szc;
    *(void **)n = t->fl[c];
    t->fl[c] = n;
}

static inline node *node_alloc(radix *t, unsigned len, unsigned cap) {
    size_t sz = nsize(len, cap);
    node *n = pool_alloc(t, sz);
    n->count = 0;
    n->nchild = 0;
    n->len = (uint8_t)len;
    n->hasv = 0;
    n->cap = (uint16_t)cap;
    n->szc = (uint8_t)(sz >> 4);
    return n;
}

static inline node *new_leaf(radix *t, const uint8_t *s, size_t len, int64_t value) {
    node *n = node_alloc(t, (unsigned)len, 0);
    n->value = value;
    n->count = 1;
    n->hasv = 1;
    memcpy(lab(n), s, len);
    return n;
}

// ------------------------------------------------------------------ public

radix *radix_new(void) {
    radix *t = calloc(1, sizeof *t);
    if (!t) abort();
    t->chunk_sz = 16384;
    t->root = node_alloc(t, 0, 0);
    t->root->value = 0;
    return t;
}

void radix_free(radix *t) {
    if (!t) return;
    chunk *c = t->chunks;
    while (c) {
        chunk *nx = c->next;
        free(c);
        c = nx;
    }
    free(t);
}

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

bool radix_get(const radix *t, const uint8_t *key, size_t len, int64_t *value) {
    const node *n = t->root;
    size_t i = 0;
    for (;;) {
        if (i == len) {
            if (n->hasv) {
                *value = n->value;
                return true;
            }
            return false;
        }
        int j = find(n, key[i]);
        if (j < 0) return false;
        const node *c = nptrs(n)[j];
        __builtin_prefetch((const char *)c + 64);
        unsigned l = c->len;
        if (len - i < l) return false;
        if (!eq(lab(c) + 1, key + i + 1, l - 1)) return false;
        i += l;
        n = c;
    }
}

bool radix_longest_prefix(const radix *t, const uint8_t *key, size_t len, size_t *match_len,
                          int64_t *value) {
    const node *n = t->root;
    const node *best = NULL;
    size_t bestlen = 0;
    size_t i = 0;
    for (;;) {
        if (n->hasv) {
            best = n;
            bestlen = i;
        }
        if (i == len) break;
        int j = find(n, key[i]);
        if (j < 0) break;
        const node *c = nptrs(n)[j];
        __builtin_prefetch((const char *)c + 64);
        unsigned l = c->len;
        if (len - i < l) break;
        if (!eq(lab(c) + 1, key + i + 1, l - 1)) break;
        i += l;
        n = c;
    }
    if (!best) return false;
    *match_len = bestlen;
    *value = best->value;
    return true;
}

// The node whose subtree holds exactly the keys starting with p, or NULL.
static inline const node *locate(const node *n, const uint8_t *p, size_t len) {
    size_t i = 0;
    while (i < len) {
        int j = find(n, p[i]);
        if (j < 0) return NULL;
        const node *c = nptrs(n)[j];
        __builtin_prefetch((const char *)c + 64);
        unsigned l = c->len;
        size_t rem = len - i;
        if (rem <= l) return eq(lab(c) + 1, p + i + 1, rem - 1) ? c : NULL;
        if (!eq(lab(c) + 1, p + i + 1, l - 1)) return NULL;
        i += l;
        n = c;
    }
    return n;
}

size_t radix_prefix_count(const radix *t, const uint8_t *prefix, size_t len) {
    const node *n = locate(t->root, prefix, len);
    return n ? n->count : 0;
}

static inline void prefetch_children(const node *n, size_t want) {
    unsigned nc = n->nchild;
    if (want < nc) nc = (unsigned)want;
    node *const *p = nptrs(n);
    for (unsigned k = 0; k < nc; k++) __builtin_prefetch(p[k]);
}

size_t radix_prefix_values(const radix *t, const uint8_t *prefix, size_t len, int64_t *out,
                           size_t limit) {
    if (limit == 0) return 0;
    const node *n = locate(t->root, prefix, len);
    if (!n) return 0;
    size_t cnt = 0;
    if (n->hasv) {
        out[cnt++] = n->value;
        if (cnt == limit) return cnt;
    }
    if (n->nchild == 0) return cnt;
    const node *stk[258];
    unsigned idx[258];
    int sp = 0;
    prefetch_children(n, limit - cnt);
    stk[0] = n;
    idx[0] = 0;
    sp = 1;
    while (sp) {
        const node *top = stk[sp - 1];
        unsigned k = idx[sp - 1];
        if (k == top->nchild) {
            sp--;
            continue;
        }
        idx[sp - 1] = k + 1;
        const node *c = nptrs(top)[k];
        if (c->hasv) {
            out[cnt++] = c->value;
            if (cnt == limit) return cnt;
        }
        if (c->nchild) {
            prefetch_children(c, limit - cnt);
            stk[sp] = c;
            idx[sp] = 0;
            sp++;
        }
    }
    return cnt;
}

// Add child (first label byte b, absent so far) to n, stored at *slot.
// Returns the (possibly reallocated) node.
static node *add_child(radix *t, node **slot, node *n, uint8_t b, node *child) {
    unsigned nc = n->nchild;
    if (UNLIKELY(nc == n->cap)) {
        unsigned ncap = nc ? nc * 2 : 2;
        node *m = node_alloc(t, n->len, ncap);
        m->value = n->value;
        m->count = n->count;
        m->hasv = n->hasv;
        m->nchild = (uint16_t)nc;
        memcpy(lab(m), lab(n), n->len);
        memcpy(nkeys(m), nkeys(n), nc);
        memcpy(nptrs(m), nptrs(n), (size_t)nc * sizeof(node *));
        node_free(t, n);
        *slot = m;
        n = m;
    }
    uint8_t *k = nkeys(n);
    node **p = nptrs(n);
    unsigned pos = nc;
    while (pos > 0 && k[pos - 1] > b) {
        k[pos] = k[pos - 1];
        p[pos] = p[pos - 1];
        pos--;
    }
    k[pos] = b;
    p[pos] = child;
    n->nchild = (uint16_t)(nc + 1);
    return n;
}

// Drop the first m bytes of c's label (in place).
static void cut_label(node *c, unsigned m) {
    unsigned l = c->len, nl = l - m, cap = c->cap, nc = c->nchild;
    uint8_t *base = (uint8_t *)c;
    memmove(base + H, base + H + m, nl);
    if (cap) {
        memmove(base + H + nl, base + H + l, nc);
        size_t po = ptroff(l, cap), pn = ptroff(nl, cap);
        if (po != pn) memmove(base + pn, base + po, (size_t)nc * sizeof(node *));
    }
    c->len = (uint8_t)nl;
}

bool radix_insert(radix *t, const uint8_t *key, size_t len, int64_t value) {
    node *path[260];
    int d = 0;
    node **slot = &t->root;
    node *n = *slot;
    size_t i = 0;
    for (;;) {
        path[d++] = n;
        if (i == len) {
            if (n->hasv) {
                n->value = value;
                return false;
            }
            n->hasv = 1;
            n->value = value;
            break;
        }
        uint8_t b = key[i];
        int j = find(n, b);
        if (j < 0) {
            node *leaf = new_leaf(t, key + i, len - i, value);
            path[d - 1] = add_child(t, slot, n, b, leaf);
            break;
        }
        node **cs = &nptrs(n)[j];
        node *c = *cs;
        unsigned l = c->len;
        size_t rem = len - i;
        size_t mx = rem < l ? rem : l;
        size_t m = 1 + mismatch(lab(c) + 1, key + i + 1, mx - 1);
        if (m == l) {
            slot = cs;
            n = c;
            i += l;
            continue;
        }
        // Split the edge to c after m bytes.
        node *mid = node_alloc(t, (unsigned)m, 2);
        memcpy(lab(mid), lab(c), m);
        mid->count = c->count + 1;
        cut_label(c, (unsigned)m);
        uint8_t *mk = nkeys(mid);
        node **mp = nptrs(mid);
        uint8_t cb = lab(c)[0];
        if (i + m == len) {
            mid->hasv = 1;
            mid->value = value;
            mid->nchild = 1;
            mk[0] = cb;
            mp[0] = c;
        } else {
            mid->value = 0;
            node *leaf = new_leaf(t, key + i + m, len - i - m, value);
            uint8_t lb = key[i + m];
            mid->nchild = 2;
            if (lb < cb) {
                mk[0] = lb;
                mp[0] = leaf;
                mk[1] = cb;
                mp[1] = c;
            } else {
                mk[0] = cb;
                mp[0] = c;
                mk[1] = lb;
                mp[1] = leaf;
            }
        }
        *cs = mid;
        break;
    }
    for (int k = 0; k < d; k++) path[k]->count++;
    t->size++;
    return true;
}

// x (at *slot) has no key and exactly one child: merge it into that child.
static void merge(radix *t, node **slot, node *x) {
    node *c = nptrs(x)[0];
    unsigned xl = x->len, cl = c->len, nl = xl + cl;
    unsigned cap = c->cap, nc = c->nchild;
    size_t need = nsize(nl, cap);
    node *r;
    if (need <= (size_t)c->szc * 16) {
        uint8_t *base = (uint8_t *)c;
        if (cap) {
            size_t po = ptroff(cl, cap), pn = ptroff(nl, cap);
            if (po != pn) memmove(base + pn, base + po, (size_t)nc * sizeof(node *));
            memmove(base + H + nl, base + H + cl, nc);
        }
        memmove(base + H + xl, base + H, cl);
        memcpy(base + H, lab(x), xl);
        c->len = (uint8_t)nl;
        r = c;
    } else {
        r = node_alloc(t, nl, cap);
        r->value = c->value;
        r->count = c->count;
        r->hasv = c->hasv;
        r->nchild = (uint16_t)nc;
        memcpy(lab(r), lab(x), xl);
        memcpy(lab(r) + xl, lab(c), cl);
        memcpy(nkeys(r), nkeys(c), nc);
        memcpy(nptrs(r), nptrs(c), (size_t)nc * sizeof(node *));
        node_free(t, c);
    }
    *slot = r;
    node_free(t, x);
}

bool radix_remove(radix *t, const uint8_t *key, size_t len) {
    node *path[260];
    node **slots[260];
    int d = 0;
    node **slot = &t->root;
    node *n = *slot;
    size_t i = 0;
    for (;;) {
        path[d] = n;
        slots[d] = slot;
        d++;
        if (i == len) break;
        int j = find(n, key[i]);
        if (j < 0) return false;
        node **cs = &nptrs(n)[j];
        node *c = *cs;
        unsigned l = c->len;
        if (len - i < l) return false;
        if (!eq(lab(c) + 1, key + i + 1, l - 1)) return false;
        slot = cs;
        n = c;
        i += l;
    }
    if (!n->hasv) return false;
    n->hasv = 0;
    for (int k = 0; k < d; k++) path[k]->count--;
    t->size--;
    if (d == 1) return true;  // the root
    unsigned nc = n->nchild;
    if (nc == 0) {
        node *p = path[d - 2];
        node **pp = nptrs(p);
        uint8_t *pk = nkeys(p);
        unsigned idx = (unsigned)(slot - pp);
        unsigned pn = p->nchild - 1u;
        memmove(pk + idx, pk + idx + 1, pn - idx);
        memmove(pp + idx, pp + idx + 1, (size_t)(pn - idx) * sizeof(node *));
        p->nchild = (uint16_t)pn;
        node_free(t, n);
        if (d - 2 > 0 && !p->hasv && pn == 1) merge(t, slots[d - 2], p);
    } else if (nc == 1) {
        merge(t, slot, n);
    }
    return true;
}

static size_t count_nodes(const node *n) {
    size_t s = 1;
    node *const *p = nptrs(n);
    for (unsigned k = 0; k < n->nchild; k++) s += count_nodes(p[k]);
    return s;
}

static size_t node_height(const node *n) {
    size_t h = 0;
    node *const *p = nptrs(n);
    for (unsigned k = 0; k < n->nchild; k++) {
        size_t x = 1 + node_height(p[k]);
        if (x > h) h = x;
    }
    return h;
}

size_t radix_node_count(const radix *t) { return count_nodes(t->root); }

size_t radix_height(const radix *t) { return node_height(t->root); }
