// Randomized skip list (Pugh 1990): ordered map i64 -> i64.
//
// Node layout (extern, 8-byte aligned, variable size 16 + 8*h bytes):
//   val: i64, key: i64, next[0..h]: ?*Node
// The key sits directly before next[0] so the fields read while walking level
// 0 share a 16-byte span. The height is not stored: remove recovers it from
// the levels at which the node is found.
//
// Nodes come from per-height pools carved out of large chunks obtained from
// the list's allocator; removed nodes go to a per-height free list and are
// reused by later inserts of the same height. All chunks are released in
// deinit.

const std = @import("std");
const Allocator = std.mem.Allocator;

/// p = 1/2, maximum height 32: (1/p)^32 = 2^32.
const MAX_LEVEL: usize = 32;

const CHUNK_ALIGN = 128;
const CHUNK_HEADER: usize = 16;
const FIRST_CHUNK_NODES: usize = 16;
const MAX_CHUNK_BYTES: usize = 2 << 20;

const Node = extern struct {
    val: i64,
    key: i64,
    // forward links follow in memory
};

const Links = [*]?*Node;

inline fn linksOf(n: *Node) Links {
    return @ptrFromInt(@intFromPtr(n) + @sizeOf(Node));
}

inline fn nodeSize(h: usize) usize {
    return @sizeOf(Node) + h * @sizeOf(?*Node);
}

const ChunkHeader = extern struct {
    next: ?*ChunkHeader,
    len: usize,
};

const Pool = struct {
    free: ?*Node = null,
    bump: usize = 0,
    end: usize = 0,
    chunk_nodes: usize = FIRST_CHUNK_NODES,
};

pub const SkipList = struct {
    head: [MAX_LEVEL]?*Node,
    level: usize,
    count: usize,
    rng: u64,
    allocator: Allocator,
    chunks: ?*ChunkHeader,
    pools: [MAX_LEVEL]Pool,

    pub fn init(allocator: Allocator) SkipList {
        return .{
            .head = @splat(null),
            .level = 0,
            .count = 0,
            .rng = 0x2545F4914F6CDD1D,
            .allocator = allocator,
            .chunks = null,
            .pools = @splat(.{}),
        };
    }

    pub fn deinit(self: *SkipList) void {
        var c = self.chunks;
        while (c) |hdr| {
            c = hdr.next;
            const base: [*]align(CHUNK_ALIGN) u8 = @ptrCast(@alignCast(hdr));
            self.allocator.free(base[0..hdr.len]);
        }
        self.chunks = null;
        self.head = @splat(null);
        self.level = 0;
        self.count = 0;
        self.pools = @splat(.{});
    }

    // splitmix64 step; height = 1 + number of trailing zero bits (p = 1/2).
    inline fn randomHeight(self: *SkipList) usize {
        self.rng +%= 0x9E3779B97F4A7C15;
        var z = self.rng;
        z = (z ^ (z >> 30)) *% 0xBF58476D1CE4E5B9;
        z = (z ^ (z >> 27)) *% 0x94D049BB133111EB;
        z ^= z >> 31;
        const h: usize = @as(usize, @ctz(z)) + 1;
        return @min(h, MAX_LEVEL);
    }

    fn grow(self: *SkipList, p: *Pool, size: usize) Allocator.Error!void {
        @branchHint(.cold);
        const nodes = p.chunk_nodes;
        const bytes = CHUNK_HEADER + nodes * size;
        const mem = try self.allocator.alignedAlloc(u8, .fromByteUnits(CHUNK_ALIGN), bytes);
        const hdr: *ChunkHeader = @ptrCast(mem.ptr);
        hdr.* = .{ .next = self.chunks, .len = bytes };
        self.chunks = hdr;
        p.bump = @intFromPtr(mem.ptr) + CHUNK_HEADER;
        p.end = @intFromPtr(mem.ptr) + bytes;
        if (nodes * 2 * size <= MAX_CHUNK_BYTES) p.chunk_nodes = nodes * 2;
    }

    inline fn allocNode(self: *SkipList, h: usize) Allocator.Error!*Node {
        const p = &self.pools[h - 1];
        if (p.free) |n| {
            p.free = linksOf(n)[0];
            return n;
        }
        const size = nodeSize(h);
        if (p.end - p.bump < size) try self.grow(p, size);
        const n: *Node = @ptrFromInt(p.bump);
        p.bump += size;
        return n;
    }

    inline fn freeNode(self: *SkipList, n: *Node, h: usize) void {
        const p = &self.pools[h - 1];
        linksOf(n)[0] = p.free;
        p.free = n;
    }

    pub fn insert(self: *SkipList, key: i64, value: i64) Allocator.Error!bool {
        var update: [MAX_LEVEL]Links = undefined;
        const head: Links = &self.head;
        var links: Links = head;
        var lvl = self.level;
        while (lvl > 0) {
            lvl -= 1;
            while (links[lvl]) |n| {
                if (n.key >= key) {
                    if (n.key == key) {
                        n.val = value;
                        return false;
                    }
                    break;
                }
                links = linksOf(n);
            }
            update[lvl] = links;
        }

        const h = self.randomHeight();
        const node = try self.allocNode(h);
        node.key = key;
        node.val = value;
        if (h > self.level) {
            for (self.level..h) |i| update[i] = head;
            self.level = h;
        }
        const nl = linksOf(node);
        for (0..h) |i| {
            const u = update[i];
            nl[i] = u[i];
            u[i] = node;
        }
        self.count += 1;
        return true;
    }

    pub fn get(self: *const SkipList, key: i64) ?i64 {
        var links: Links = @constCast(&self.head);
        var lvl = self.level;
        while (lvl > 0) {
            lvl -= 1;
            while (links[lvl]) |n| {
                if (n.key >= key) {
                    if (n.key == key) return n.val;
                    break;
                }
                links = linksOf(n);
            }
        }
        return null;
    }

    pub fn remove(self: *SkipList, key: i64) bool {
        var links: Links = &self.head;
        var lvl = self.level;
        var found: ?*Node = null;
        var h: usize = 0;
        while (lvl > 0) {
            lvl -= 1;
            while (links[lvl]) |n| {
                if (n.key >= key) {
                    if (n.key == key) {
                        // First found at its top level; unlink on the way down.
                        if (found == null) {
                            found = n;
                            h = lvl + 1;
                        }
                        links[lvl] = linksOf(n)[lvl];
                    }
                    break;
                }
                links = linksOf(n);
            }
        }
        const node = found orelse return false;
        self.freeNode(node, h);
        self.count -= 1;
        var l = self.level;
        while (l > 0 and self.head[l - 1] == null) l -= 1;
        self.level = l;
        return true;
    }

    pub fn range(self: *const SkipList, lo: i64, hi: i64, out_keys: []i64, out_vals: []i64) usize {
        const limit = out_keys.len;
        if (lo > hi or limit == 0) return 0;
        var links: Links = @constCast(&self.head);
        var lvl = self.level;
        var cur: ?*Node = null;
        outer: while (lvl > 0) {
            lvl -= 1;
            while (links[lvl]) |n| {
                if (n.key >= lo) {
                    if (n.key == lo) {
                        cur = n;
                        break :outer;
                    }
                    break;
                }
                links = linksOf(n);
            }
            if (lvl == 0) cur = links[0];
        }
        const ko = out_keys.ptr;
        const vo = out_vals.ptr;
        var i: usize = 0;
        while (cur) |n| {
            const k = n.key;
            if (k > hi) break;
            ko[i] = k;
            vo[i] = n.val;
            i += 1;
            if (i == limit) break;
            cur = linksOf(n)[0];
        }
        return i;
    }

    pub fn len(self: *const SkipList) usize {
        return self.count;
    }

    pub fn height(self: *const SkipList) usize {
        return self.level;
    }

    pub fn levelCount(self: *const SkipList, level: usize) usize {
        if (level >= MAX_LEVEL or level >= self.level) return 0;
        var c: usize = 0;
        var cur = self.head[level];
        while (cur) |n| {
            c += 1;
            cur = linksOf(n)[level];
        }
        return c;
    }
};
