#include "skiplist.h"

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

/*
 * Classic randomized skip list (p = 1/2, max height = 32).
 *
 * Memory & cache layout tuned for Apple M3 (128B cache lines, 64KB L1D,
 * 4MB L2, 16KB pages):
 *   - Nodes store key, val, and compact 32-bit forward handles (8-byte word
 *     offsets tagged with a 2-bit pool ID in bits 31..30). Handle 0 is NULL.
 *   - 3 height-segregated pools isolate hot upper towers from cold lower nodes:
 *       Pool 0 (tag 0x00000000): heights  1..4  (DRAM; 128B-line-aligned slabs,
 *                                                zero cache-line straddling)
 *       Pool 1 (tag 0x40000000): heights  5..10 (~3.2MB at 1.25M entries -> L2)
 *       Pool 2 (tag 0x80000000): heights 11..32 (~80KB at 1.25M entries  -> L1)
 *   - Search is split into 3 level tiers (lvl >= 10, 4..9, 0..3) so upper
 *     tiers decode handles with 0 or 1 branchless csel, uses stop-handle
 *     skipping to avoid redundant comparisons, early-exits on key match, and
 *     issues branchless downward prefetches on cold levels for MLP.
 *   - Freed nodes are recycled per size class via intrusive freelists stored
 *     in next[0].
 */

#define MAX_HEIGHT 32u
#define NUM_CLASSES 9u

#define POOL0_TAG 0x00000000u
#define POOL1_TAG 0x40000000u
#define POOL2_TAG 0x80000000u
#define OFF_MASK  0x3FFFFFFFu

/* Only issue downward prefetches when the list exceeds L2 cache capacity. */
#define PREFETCH_LEN_THRESH ((size_t)131072u)

#define RNG_SEED 0x9E3779B97F4A7C15ULL

typedef struct Node {
    int64_t key;
    int64_t val;
    uint32_t next[];
} Node;

typedef struct Pool {
    uint8_t *data;
    uint32_t used_words; /* in 8-byte words */
    uint32_t cap_words;  /* in 8-byte words */
} Pool;

typedef struct SlabCursor {
    uint32_t cur_word;
    uint32_t end_word;
} SlabCursor;

struct skiplist {
    uint32_t head[MAX_HEIGHT]; /* 128 bytes: 1 cache line */
    uint8_t *p0;               /* cached pools[0].data */
    uint8_t *p1;               /* cached pools[1].data */
    uint8_t *p2;               /* cached pools[2].data */
    size_t len;
    uint32_t height;
    uint64_t rng;
    uint32_t freelist[NUM_CLASSES];
    SlabCursor slab[NUM_CLASSES];
    Pool pools[3];
};

/* Map tower height h (1..32) to size class (0..8). */
static const uint8_t HEIGHT_TO_CLASS[MAX_HEIGHT + 1u] = {
    0,
    0, 0,                   /* h = 1..2   -> class 0 (24B,  3 words, Pool 0) */
    1, 1,                   /* h = 3..4   -> class 1 (32B,  4 words, Pool 0) */
    2, 2,                   /* h = 5..6   -> class 2 (40B,  5 words, Pool 1) */
    3, 3,                   /* h = 7..8   -> class 3 (48B,  6 words, Pool 1) */
    4, 4,                   /* h = 9..10  -> class 4 (56B,  7 words, Pool 1) */
    5, 5,                   /* h = 11..12 -> class 5 (64B,  8 words, Pool 2) */
    6, 6, 6, 6,             /* h = 13..16 -> class 6 (80B, 10 words, Pool 2) */
    7, 7, 7, 7, 7, 7,       /* h = 17..22 -> class 7 (104B,13 words, Pool 2) */
    8, 8, 8, 8, 8, 8, 8, 8, 8, 8 /* h = 23..32 -> class 8 (144B,18 words, Pool 2) */
};

typedef struct ClassSpec {
    uint8_t pool_id;
    uint8_t node_words;   /* size of one node in 8-byte words */
    uint8_t grab_words;   /* words grabbed from pool per mini-slab */
    uint8_t usable_words; /* usable words within mini-slab (<= grab_words) */
    uint32_t tag;
} ClassSpec;

static const ClassSpec CLASS_SPEC[NUM_CLASSES] = {
    {0,  3, 16, 15, POOL0_TAG}, /* class 0: 5 x 24B per 128B line (0 splits) */
    {0,  4, 16, 16, POOL0_TAG}, /* class 1: 4 x 32B per 128B line (0 splits) */
    {1,  5, 40, 40, POOL1_TAG}, /* class 2: 8 x 40B */
    {1,  6, 48, 48, POOL1_TAG}, /* class 3: 8 x 48B */
    {1,  7, 28, 28, POOL1_TAG}, /* class 4: 4 x 56B */
    {2,  8, 16, 16, POOL2_TAG}, /* class 5: 2 x 64B per 128B line (0 splits) */
    {2, 10, 20, 20, POOL2_TAG}, /* class 6: 2 x 80B */
    {2, 13, 13, 13, POOL2_TAG}, /* class 7: 1 x 104B */
    {2, 18, 18, 18, POOL2_TAG}, /* class 8: 1 x 144B */
};

static const uint32_t POOL_INIT_WORDS[3] = {256u, 128u, 64u};

/* ------------------------------------------------------------------ PRNG */

static inline uint64_t rng_next(uint64_t *state) {
    uint64_t z = (*state += 0x9E3779B97F4A7C15ULL);
    z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ULL;
    z = (z ^ (z >> 27)) * 0x94D049BB133111EBULL;
    return z ^ (z >> 31);
}

/* Geometric(p = 1/2) height in [1, 32], independent of list state. */
static inline uint32_t draw_height(uint64_t *state) {
    uint32_t hi = (uint32_t)(rng_next(state) >> 32) | 1u;
    return (uint32_t)__builtin_clz(hi) + 1u;
}

/* ---------------------------------------------------------- handle decode */

static inline Node *decode_p2(uint8_t *p2, uint32_t h) {
    return (Node *)(p2 + ((size_t)(h & OFF_MASK) << 3));
}

static inline Node *decode_p12(uint8_t *p1, uint8_t *p2, uint32_t h) {
    uint8_t *base = ((int32_t)h < 0) ? p2 : p1;
    return (Node *)(base + ((size_t)(h & OFF_MASK) << 3));
}

static inline Node *decode_any(uint8_t *p0, uint8_t *p1, uint8_t *p2, uint32_t h) {
    uint8_t *base = ((int32_t)h < 0) ? p2 : ((h & POOL1_TAG) ? p1 : p0);
    return (Node *)(base + ((size_t)(h & OFF_MASK) << 3));
}

/* --------------------------------------------------------- node allocator */

__attribute__((noinline, cold))
static void pool_grow(skiplist *t, uint32_t pid, uint32_t needed_words) {
    Pool *pool = &t->pools[pid];
    uint64_t new_cap = pool->cap_words ? (uint64_t)pool->cap_words * 2ULL
                                       : (uint64_t)POOL_INIT_WORDS[pid];
    while (new_cap < (uint64_t)needed_words) {
        new_cap *= 2ULL;
    }
    if (new_cap > (uint64_t)OFF_MASK) {
        new_cap = (uint64_t)OFF_MASK;
        if ((uint64_t)needed_words > new_cap) {
            abort();
        }
    }
    uint8_t *nd = realloc(pool->data, (size_t)new_cap * 8u);
    if (!nd) {
        abort();
    }
    pool->data = nd;
    pool->cap_words = (uint32_t)new_cap;
    if (pid == 0u) {
        t->p0 = nd;
        if (pool->used_words == 0u) {
            /* Reserve first 128B line so handle 0 stays NULL and slabs stay 128B-aligned. */
            pool->used_words = 16u;
        }
    } else if (pid == 1u) {
        t->p1 = nd;
    } else {
        t->p2 = nd;
    }
}

static inline uint32_t alloc_node(skiplist *t, uint32_t node_h, Node **out_node) {
    uint32_t cls = HEIGHT_TO_CLASS[node_h];
    const ClassSpec *spec = &CLASS_SPEC[cls];
    uint32_t pid = spec->pool_id;

    uint32_t fh = t->freelist[cls];
    if (fh != 0u) {
        uint8_t *base = t->pools[pid].data;
        Node *n = (Node *)(base + ((size_t)(fh & OFF_MASK) << 3));
        t->freelist[cls] = n->next[0];
        *out_node = n;
        return fh;
    }

    SlabCursor *sc = &t->slab[cls];
    uint32_t off = sc->cur_word;
    if (off == sc->end_word) {
        Pool *pool = &t->pools[pid];
        uint32_t used = pool->used_words;
        if (pid == 0u && used == 0u) {
            used = 16u;
        }
        uint32_t next_used = used + spec->grab_words;
        if (__builtin_expect(next_used > pool->cap_words, 0)) {
            pool_grow(t, pid, next_used);
            used = pool->used_words;
            next_used = used + spec->grab_words;
        }
        pool->used_words = next_used;
        off = used;
        sc->end_word = used + spec->usable_words;
    }
    sc->cur_word = off + spec->node_words;
    *out_node = (Node *)(t->pools[pid].data + ((size_t)off << 3));
    return spec->tag | off;
}

static inline void free_node(skiplist *t, uint32_t hnd, Node *n, uint32_t node_h) {
    uint32_t cls = HEIGHT_TO_CLASS[node_h];
    n->next[0] = t->freelist[cls];
    t->freelist[cls] = hnd;
}

/* ----------------------------------------------------------- public API */

skiplist *skiplist_new(void) {
    skiplist *t = calloc(1, sizeof *t);
    if (!t) {
        abort();
    }
    t->rng = RNG_SEED;
    return t;
}

void skiplist_free(skiplist *t) {
    if (!t) {
        return;
    }
    free(t->pools[0].data);
    free(t->pools[1].data);
    free(t->pools[2].data);
    free(t);
}

bool skiplist_get(const skiplist *t, int64_t key, int64_t *value) {
    uint32_t th = t->height;
    if (__builtin_expect(th == 0u, 0)) {
        return false;
    }

    uint8_t *p0 = t->p0;
    uint8_t *p1 = t->p1;
    uint8_t *p2 = t->p2;
    const uint32_t *cur_next = t->head;
    uint32_t stop = 0u;
    int32_t lvl = (int32_t)th - 1;

    /* Tier 2: levels >= 10 (all nodes in Pool 2 -> L1D) */
    for (; lvl >= 10; lvl--) {
        uint32_t h = cur_next[lvl];
        while (h != stop) {
            const Node *nx = decode_p2(p2, h);
            int64_t k = nx->key;
            if (k < key) {
                cur_next = nx->next;
                h = cur_next[lvl];
            } else {
                if (k == key) {
                    *value = nx->val;
                    return true;
                }
                stop = h;
                break;
            }
        }
    }

    /* Tier 1: levels 4..9 (all nodes in Pool 1 or Pool 2 -> L2) */
    for (; lvl >= 4; lvl--) {
        uint32_t h = cur_next[lvl];
        while (h != stop) {
            const Node *nx = decode_p12(p1, p2, h);
            int64_t k = nx->key;
            if (k < key) {
                cur_next = nx->next;
                h = cur_next[lvl];
            } else {
                if (k == key) {
                    *value = nx->val;
                    return true;
                }
                stop = h;
                break;
            }
        }
    }

    /* Tier 0: levels 3..1 (cold DRAM levels; prefetch next level down) */
    if (t->len > PREFETCH_LEN_THRESH && p0 != NULL) {
        for (; lvl >= 1; lvl--) {
            uint32_t h = cur_next[lvl];
            while (h != stop) {
                __builtin_prefetch(decode_any(p0, p1, p2, cur_next[lvl - 1]), 0, 1);
                const Node *nx = decode_any(p0, p1, p2, h);
                int64_t k = nx->key;
                if (k < key) {
                    cur_next = nx->next;
                    h = cur_next[lvl];
                } else {
                    if (k == key) {
                        *value = nx->val;
                        return true;
                    }
                    stop = h;
                    break;
                }
            }
        }
    } else {
        for (; lvl >= 1; lvl--) {
            uint32_t h = cur_next[lvl];
            while (h != stop) {
                const Node *nx = decode_any(p0, p1, p2, h);
                int64_t k = nx->key;
                if (k < key) {
                    cur_next = nx->next;
                    h = cur_next[lvl];
                } else {
                    if (k == key) {
                        *value = nx->val;
                        return true;
                    }
                    stop = h;
                    break;
                }
            }
        }
    }

    /* Level 0 */
    {
        uint32_t h = cur_next[0];
        while (h != stop) {
            const Node *nx = decode_any(p0, p1, p2, h);
            int64_t k = nx->key;
            if (k < key) {
                cur_next = nx->next;
                h = cur_next[0];
            } else {
                if (k == key) {
                    *value = nx->val;
                    return true;
                }
                break;
            }
        }
    }

    return false;
}

bool skiplist_insert(skiplist *t, int64_t key, int64_t value) {
    uint32_t th = t->height;
    if (__builtin_expect(th == 0u, 0)) {
        uint32_t new_h = draw_height(&t->rng);
        Node *n;
        uint32_t hnd = alloc_node(t, new_h, &n);
        n->key = key;
        n->val = value;
        for (uint32_t i = 0u; i < new_h; i++) {
            n->next[i] = 0u;
            t->head[i] = hnd;
        }
        t->height = new_h;
        t->len = 1u;
        return true;
    }

    uint8_t *p0 = t->p0;
    uint8_t *p1 = t->p1;
    uint8_t *p2 = t->p2;
    uint32_t *cur_next = t->head;
    uint32_t cur_h = 0u;
    uint32_t stop = 0u;
    uint32_t pred_h[MAX_HEIGHT];
    int32_t lvl = (int32_t)th - 1;

    /* Tier 2: levels >= 10 */
    for (; lvl >= 10; lvl--) {
        uint32_t h = cur_next[lvl];
        while (h != stop) {
            Node *nx = decode_p2(p2, h);
            int64_t k = nx->key;
            if (k < key) {
                cur_h = h;
                cur_next = nx->next;
                h = cur_next[lvl];
            } else {
                if (k == key) {
                    nx->val = value;
                    return false;
                }
                stop = h;
                break;
            }
        }
        pred_h[lvl] = cur_h;
    }

    /* Tier 1: levels 4..9 */
    for (; lvl >= 4; lvl--) {
        uint32_t h = cur_next[lvl];
        while (h != stop) {
            Node *nx = decode_p12(p1, p2, h);
            int64_t k = nx->key;
            if (k < key) {
                cur_h = h;
                cur_next = nx->next;
                h = cur_next[lvl];
            } else {
                if (k == key) {
                    nx->val = value;
                    return false;
                }
                stop = h;
                break;
            }
        }
        pred_h[lvl] = cur_h;
    }

    /* Tier 0: levels 3..1 */
    if (t->len > PREFETCH_LEN_THRESH && p0 != NULL) {
        for (; lvl >= 1; lvl--) {
            uint32_t h = cur_next[lvl];
            while (h != stop) {
                __builtin_prefetch(decode_any(p0, p1, p2, cur_next[lvl - 1]), 0, 1);
                Node *nx = decode_any(p0, p1, p2, h);
                int64_t k = nx->key;
                if (k < key) {
                    cur_h = h;
                    cur_next = nx->next;
                    h = cur_next[lvl];
                } else {
                    if (k == key) {
                        nx->val = value;
                        return false;
                    }
                    stop = h;
                    break;
                }
            }
            pred_h[lvl] = cur_h;
        }
    } else {
        for (; lvl >= 1; lvl--) {
            uint32_t h = cur_next[lvl];
            while (h != stop) {
                Node *nx = decode_any(p0, p1, p2, h);
                int64_t k = nx->key;
                if (k < key) {
                    cur_h = h;
                    cur_next = nx->next;
                    h = cur_next[lvl];
                } else {
                    if (k == key) {
                        nx->val = value;
                        return false;
                    }
                    stop = h;
                    break;
                }
            }
            pred_h[lvl] = cur_h;
        }
    }

    /* Level 0 */
    {
        uint32_t h = cur_next[0];
        while (h != stop) {
            Node *nx = decode_any(p0, p1, p2, h);
            int64_t k = nx->key;
            if (k < key) {
                cur_h = h;
                cur_next = nx->next;
                h = cur_next[0];
            } else {
                if (k == key) {
                    nx->val = value;
                    return false;
                }
                break;
            }
        }
    }

    uint32_t new_h = draw_height(&t->rng);
    Node *n;
    uint32_t new_hnd = alloc_node(t, new_h, &n);
    n->key = key;
    n->val = value;

    /* Reload pool bases in case alloc_node grew a pool via realloc. */
    p0 = t->p0;
    p1 = t->p1;
    p2 = t->p2;

    uint32_t *last_next = (cur_h == 0u) ? t->head : decode_any(p0, p1, p2, cur_h)->next;
    n->next[0] = last_next[0];
    last_next[0] = new_hnd;

    if (new_h > 1u) {
        uint32_t lim = new_h < th ? new_h : th;
        uint32_t last_ph = cur_h;
        for (uint32_t i = 1u; i < lim; i++) {
            uint32_t ph = pred_h[i];
            if (ph != last_ph) {
                last_ph = ph;
                last_next = (ph == 0u) ? t->head : decode_any(p0, p1, p2, ph)->next;
            }
            n->next[i] = last_next[i];
            last_next[i] = new_hnd;
        }

        if (new_h > th) {
            for (uint32_t i = th; i < new_h; i++) {
                n->next[i] = 0u;
                t->head[i] = new_hnd;
            }
            t->height = new_h;
        }
    }

    t->len++;
    return true;
}

bool skiplist_remove(skiplist *t, int64_t key) {
    uint32_t th = t->height;
    if (__builtin_expect(th == 0u, 0)) {
        return false;
    }

    uint8_t *p0 = t->p0;
    uint8_t *p1 = t->p1;
    uint8_t *p2 = t->p2;
    uint32_t *cur_next = t->head;
    uint32_t stop = 0u;
    int32_t lvl = (int32_t)th - 1;
    uint32_t target_h;
    Node *target;

    /* Phase 1: locate target at its highest level (lvl == target_height - 1). */
    for (; lvl >= 10; lvl--) {
        uint32_t h = cur_next[lvl];
        while (h != stop) {
            Node *nx = decode_p2(p2, h);
            int64_t k = nx->key;
            if (k < key) {
                cur_next = nx->next;
                h = cur_next[lvl];
            } else {
                if (k == key) {
                    target_h = h;
                    target = nx;
                    goto found;
                }
                stop = h;
                break;
            }
        }
    }

    for (; lvl >= 4; lvl--) {
        uint32_t h = cur_next[lvl];
        while (h != stop) {
            Node *nx = decode_p12(p1, p2, h);
            int64_t k = nx->key;
            if (k < key) {
                cur_next = nx->next;
                h = cur_next[lvl];
            } else {
                if (k == key) {
                    target_h = h;
                    target = nx;
                    goto found;
                }
                stop = h;
                break;
            }
        }
    }

    if (t->len > PREFETCH_LEN_THRESH && p0 != NULL) {
        for (; lvl >= 1; lvl--) {
            uint32_t h = cur_next[lvl];
            while (h != stop) {
                __builtin_prefetch(decode_any(p0, p1, p2, cur_next[lvl - 1]), 0, 1);
                Node *nx = decode_any(p0, p1, p2, h);
                int64_t k = nx->key;
                if (k < key) {
                    cur_next = nx->next;
                    h = cur_next[lvl];
                } else {
                    if (k == key) {
                        target_h = h;
                        target = nx;
                        goto found;
                    }
                    stop = h;
                    break;
                }
            }
        }
    } else {
        for (; lvl >= 1; lvl--) {
            uint32_t h = cur_next[lvl];
            while (h != stop) {
                Node *nx = decode_any(p0, p1, p2, h);
                int64_t k = nx->key;
                if (k < key) {
                    cur_next = nx->next;
                    h = cur_next[lvl];
                } else {
                    if (k == key) {
                        target_h = h;
                        target = nx;
                        goto found;
                    }
                    stop = h;
                    break;
                }
            }
        }
    }

    /* Level 0 */
    {
        uint32_t h = cur_next[0];
        while (h != stop) {
            Node *nx = decode_any(p0, p1, p2, h);
            int64_t k = nx->key;
            if (k < key) {
                cur_next = nx->next;
                h = cur_next[0];
            } else {
                if (k == key) {
                    target_h = h;
                    target = nx;
                    goto found;
                }
                break;
            }
        }
    }
    return false;

found:
    /* Phase 2: unlink target from lvl down to 0 by handle equality (no key comparisons). */
    cur_next[lvl] = target->next[lvl];
    for (int32_t l = lvl - 1; l >= 0; l--) {
        uint32_t nh = cur_next[l];
        while (nh != target_h) {
            Node *step = decode_any(p0, p1, p2, nh);
            cur_next = step->next;
            nh = cur_next[l];
        }
        cur_next[l] = target->next[l];
    }

    uint32_t node_h = (uint32_t)lvl + 1u;
    free_node(t, target_h, target, node_h);
    t->len--;

    if (node_h == th) {
        while (th > 0u && t->head[th - 1u] == 0u) {
            th--;
        }
        t->height = th;
    }
    return true;
}

size_t skiplist_range(const skiplist *t, int64_t lo, int64_t hi,
                      int64_t *out_keys, int64_t *out_vals, size_t limit) {
    uint32_t th = t->height;
    if (__builtin_expect(limit == 0u || lo > hi || th == 0u, 0)) {
        return 0u;
    }

    uint8_t *p0 = t->p0;
    uint8_t *p1 = t->p1;
    uint8_t *p2 = t->p2;
    const uint32_t *cur_next = t->head;
    uint32_t stop = 0u;
    int32_t lvl = (int32_t)th - 1;
    const Node *nx;

    for (; lvl >= 10; lvl--) {
        uint32_t h = cur_next[lvl];
        while (h != stop) {
            nx = decode_p2(p2, h);
            int64_t k = nx->key;
            if (k < lo) {
                cur_next = nx->next;
                h = cur_next[lvl];
            } else {
                if (k == lo) {
                    goto scan;
                }
                stop = h;
                break;
            }
        }
    }

    for (; lvl >= 4; lvl--) {
        uint32_t h = cur_next[lvl];
        while (h != stop) {
            nx = decode_p12(p1, p2, h);
            int64_t k = nx->key;
            if (k < lo) {
                cur_next = nx->next;
                h = cur_next[lvl];
            } else {
                if (k == lo) {
                    goto scan;
                }
                stop = h;
                break;
            }
        }
    }

    if (t->len > PREFETCH_LEN_THRESH && p0 != NULL) {
        for (; lvl >= 1; lvl--) {
            uint32_t h = cur_next[lvl];
            while (h != stop) {
                __builtin_prefetch(decode_any(p0, p1, p2, cur_next[lvl - 1]), 0, 1);
                nx = decode_any(p0, p1, p2, h);
                int64_t k = nx->key;
                if (k < lo) {
                    cur_next = nx->next;
                    h = cur_next[lvl];
                } else {
                    if (k == lo) {
                        goto scan;
                    }
                    stop = h;
                    break;
                }
            }
        }
    } else {
        for (; lvl >= 1; lvl--) {
            uint32_t h = cur_next[lvl];
            while (h != stop) {
                nx = decode_any(p0, p1, p2, h);
                int64_t k = nx->key;
                if (k < lo) {
                    cur_next = nx->next;
                    h = cur_next[lvl];
                } else {
                    if (k == lo) {
                        goto scan;
                    }
                    stop = h;
                    break;
                }
            }
        }
    }

    /* Level 0 */
    {
        uint32_t h = cur_next[0];
        while (h != stop) {
            nx = decode_any(p0, p1, p2, h);
            int64_t k = nx->key;
            if (k < lo) {
                cur_next = nx->next;
                h = cur_next[0];
            } else {
                goto scan;
            }
        }
    }

    if (stop == 0u) {
        return 0u;
    }
    nx = decode_any(p0, p1, p2, stop);

scan:
    {
        size_t count = 0u;
        for (;;) {
            int64_t k = nx->key;
            if (k > hi) {
                break;
            }
            int64_t v = nx->val;
            uint32_t next_h = nx->next[0];
            out_keys[count] = k;
            out_vals[count] = v;
            count++;
            if (count == limit || next_h == 0u) {
                break;
            }
            nx = decode_any(p0, p1, p2, next_h);
        }
        return count;
    }
}

size_t skiplist_len(const skiplist *t) {
    return t->len;
}

size_t skiplist_height(const skiplist *t) {
    return t->height;
}

size_t skiplist_level_count(const skiplist *t, size_t level) {
    if (level >= (size_t)t->height) {
        return 0u;
    }
    uint8_t *p0 = t->p0;
    uint8_t *p1 = t->p1;
    uint8_t *p2 = t->p2;
    size_t count = 0u;
    uint32_t h = t->head[level];
    while (h != 0u) {
        count++;
        h = decode_any(p0, p1, p2, h)->next[level];
    }
    return count;
}
