// Classic randomized skip list (Pugh 1990), p = 1/2, maximum height 32.
//
// Node layout: { key, value, next[0..h-1] }. Nodes are carved out of
// 128-byte-aligned chunks with sizes rounded up to 32 bytes, so the key, the
// value and the first two links of a node always share one cache line.
// Freed nodes go to per-size-class free lists and are reused.

#include "skiplist.h"

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

#define MAX_LEVEL 32          /* p = 1/2: 2^32 >= 2^32 entries */
#define NUM_CLASSES 10        /* size classes of 32 bytes: 1..9 used */
#define CHUNK_MIN (16u * 1024u)
#define CHUNK_MAX (4u * 1024u * 1024u)
#define RANGE_AHEAD 10        /* levels used as prefetch cursors in range */

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

typedef struct node {
    int64_t key;
    int64_t val;
    struct node *next[];
} node;

struct skiplist {
    node *head;               /* header: MAX_LEVEL links, not an entry */
    size_t len;
    unsigned level;           /* height of the tallest node, 0 if empty */
    uint64_t rng;             /* splitmix64 state */
    char *bump;               /* bump pointer in current chunk */
    char *bump_end;
    void *chunks;             /* singly linked list of chunks (link at start) */
    size_t next_chunk;
    node *free_list[NUM_CLASSES];
};

static inline size_t size_class(unsigned h) {
    /* bytes = 16 + 8h rounded up to 32; class = bytes / 32 */
    return (16u + 8u * h + 31u) >> 5;
}

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

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

/* Geometric height with p = 1/2, capped at MAX_LEVEL. */
static inline unsigned random_height(skiplist *t) {
    uint64_t r = rng_next(&t->rng);
    return 1u + (unsigned)__builtin_ctzll(r | (1ULL << (MAX_LEVEL - 1)));
}

static __attribute__((noinline)) void new_chunk(skiplist *t) {
    size_t sz = t->next_chunk;
    if (sz < CHUNK_MAX) t->next_chunk = sz * 2;
    char *c = xaligned(128, sz);
    *(void **)c = t->chunks;
    t->chunks = c;
    t->bump = c + 128;
    t->bump_end = c + sz;
}

static inline node *alloc_node(skiplist *t, unsigned h) {
    size_t cls = size_class(h);
    node *n = t->free_list[cls];
    if (n) {
        t->free_list[cls] = n->next[0];
        return n;
    }
    size_t bytes = cls << 5;
    if (UNLIKELY((size_t)(t->bump_end - t->bump) < bytes)) new_chunk(t);
    n = (node *)t->bump;
    t->bump += bytes;
    return n;
}

static inline void free_node(skiplist *t, node *n, unsigned h) {
    size_t cls = size_class(h);
    n->next[0] = t->free_list[cls];
    t->free_list[cls] = n;
}

skiplist *skiplist_new(void) {
    skiplist *t = malloc(sizeof *t);
    if (!t) abort();
    memset(t, 0, sizeof *t);
    t->head = xaligned(128, sizeof(node) + MAX_LEVEL * sizeof(node *));
    memset(t->head, 0, sizeof(node) + MAX_LEVEL * sizeof(node *));
    t->rng = 0x5DEECE66D2B7E151ULL;
    t->next_chunk = CHUNK_MIN;
    return t;
}

void skiplist_free(skiplist *t) {
    if (!t) return;
    void *c = t->chunks;
    while (c) {
        void *nx = *(void **)c;
        free(c);
        c = nx;
    }
    free(t->head);
    free(t);
}

/* Descend from the top, filling preds[L] with the last node at level L whose
 * key is < key. `last` remembers the node that stopped the previous level so
 * it is not compared again; every level reaches it before (or at) NULL, so the
 * walk needs no NULL check. */
static inline __attribute__((always_inline)) void
find_preds(const skiplist *t, int64_t key, node **preds) {
    node *x = t->head;
    node *last = NULL;
    for (int L = (int)t->level - 1; L >= 0; L--) {
        node *y = x->next[L];
        while (y != last && y->key < key) {
            x = y;
            y = y->next[L];
        }
        last = y;
        preds[L] = x;
    }
}

bool skiplist_insert(skiplist *t, int64_t key, int64_t value) {
    node *preds[MAX_LEVEL];
    node *x = t->head;
    node *last = NULL;
    for (int L = (int)t->level - 1; L >= 0; L--) {
        node *y = x->next[L];
        while (y != last) {
            int64_t yk = y->key;
            if (yk < key) {
                x = y;
                y = y->next[L];
            } else {
                if (yk == key) {
                    y->val = value;
                    return false;
                }
                break;
            }
        }
        last = y;
        preds[L] = x;
    }
    unsigned h = random_height(t);
    if (h > t->level) {
        for (unsigned L = t->level; L < h; L++) preds[L] = t->head;
        t->level = h;
    }
    node *n = alloc_node(t, h);
    n->key = key;
    n->val = value;
    for (unsigned L = 0; L < h; L++) {
        n->next[L] = preds[L]->next[L];
        preds[L]->next[L] = n;
    }
    t->len++;
    return true;
}

bool skiplist_get(const skiplist *t, int64_t key, int64_t *value) {
    const node *x = t->head;
    const node *last = NULL;
    for (int L = (int)t->level - 1; L >= 0; L--) {
        const node *y = x->next[L];
        while (y != last) {
            int64_t yk = y->key;
            if (yk < key) {
                x = y;
                y = y->next[L];
            } else {
                if (yk == key) {
                    *value = y->val;
                    return true;
                }
                break;
            }
        }
        last = y;
    }
    return false;
}

bool skiplist_remove(skiplist *t, int64_t key) {
    if (UNLIKELY(t->level == 0)) return false;
    node *preds[MAX_LEVEL];
    find_preds(t, key, preds);
    node *y = preds[0]->next[0];
    if (!y || y->key != key) return false;
    unsigned lvl = t->level;
    unsigned L = 0;
    while (L < lvl && preds[L]->next[L] == y) {
        preds[L]->next[L] = y->next[L];
        L++;
    }
    free_node(t, y, L);
    node **hn = t->head->next;
    while (lvl > 0 && hn[lvl - 1] == NULL) lvl--;
    t->level = lvl;
    t->len--;
    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) {
    if (lo > hi || limit == 0 || t->level == 0) return 0;
    node *preds[MAX_LEVEL];
    find_preds(t, lo, preds);

    /* Cursors at levels 1..K: when the level-0 walk reaches ahead[L], that
     * node is in level L, and its level-L successor is prefetched. */
    node *ahead[RANGE_AHEAD + 1];
    unsigned K = t->level - 1;
    if (K > RANGE_AHEAD) K = RANGE_AHEAD;
    for (unsigned L = 1; L <= K; L++) ahead[L] = preds[L]->next[L];

    const node *x = preds[0]->next[0];
    size_t c = 0;
    while (x && x->key <= hi) {
        out_keys[c] = x->key;
        out_vals[c] = x->val;
        if (++c == limit) break;
        for (unsigned L = 1; L <= K && x == ahead[L]; L++) {
            node *a = x->next[L];
            ahead[L] = a;
            __builtin_prefetch(a);
        }
        x = x->next[0];
    }
    return c;
}

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

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

size_t skiplist_level_count(const skiplist *t, size_t level) {
    if (level >= t->level) return 0;
    size_t c = 0;
    for (const node *x = t->head->next[level]; x; x = x->next[level]) c++;
    return c;
}
