//! Doubly linked list backed by a single growable pool of 16-byte nodes.
//!
//! - Node: { value: i64, next: u32, prev: u32 } — 16 bytes, 8 per cache line.
//! - Links are u32 indices into the pool. Index 0 is a sentinel node, so the
//!   list is circular through it: sentinel.next is the front, sentinel.prev
//!   the back, and the last node's `next` is 0. A handle is the node index,
//!   which is therefore never 0, and next()/prev()/front()/back() return the
//!   stored link directly with no branches.
//! - Removed nodes go onto a free list threaded through their `next` field and
//!   are reused (LIFO) before fresh pool slots are taken.
//! - The pool doubles via realloc; nodes are addressed by index, so moving the
//!   pool never changes a handle.

const std = @import("std");

const Node = struct {
    value: i64,
    next: u32,
    prev: u32,
};

comptime {
    std.debug.assert(@sizeOf(Node) == 16);
}

/// Read-only sentinel used before the pool is allocated, so that front(),
/// back(), len() and the pops need no special case. Never written to: every
/// writing path allocates the pool first.
var empty_sentinel: [1]Node = .{.{ .value = 0, .next = 0, .prev = 0 }};

const MAX_NODES: usize = std.math.maxInt(u32); // indices 0..maxInt(u32)-1
const INITIAL_CAP: usize = 1024;

pub const DList = struct {
    nodes: [*]Node,
    cap: usize, // number of slots in the pool (0 while unallocated)
    used: u32, // slots ever handed out, including the sentinel
    free_head: u32, // head of the free list, 0 if empty
    count: usize,
    allocator: std.mem.Allocator,

    pub fn init(allocator: std.mem.Allocator) DList {
        return .{
            .nodes = &empty_sentinel,
            .cap = 0,
            .used = 1,
            .free_head = 0,
            .count = 0,
            .allocator = allocator,
        };
    }

    pub fn deinit(self: *DList) void {
        if (self.cap != 0) self.allocator.free(self.nodes[0..self.cap]);
        self.* = undefined;
    }

    fn grow(self: *DList) std.mem.Allocator.Error!void {
        @branchHint(.cold);
        if (self.cap == 0) {
            const mem = try self.allocator.alloc(Node, INITIAL_CAP);
            mem[0] = .{ .value = 0, .next = 0, .prev = 0 };
            self.nodes = mem.ptr;
            self.cap = INITIAL_CAP;
            return;
        }
        if (self.cap >= MAX_NODES) return error.OutOfMemory;
        const new_cap = @min(self.cap * 2, MAX_NODES);
        const mem = try self.allocator.realloc(self.nodes[0..self.cap], new_cap);
        self.nodes = mem.ptr;
        self.cap = new_cap;
    }

    /// Get a node slot: a recycled one if any, otherwise a fresh one.
    inline fn allocNode(self: *DList) std.mem.Allocator.Error!u32 {
        const f = self.free_head;
        if (f != 0) {
            self.free_head = self.nodes[f].next;
            return f;
        }
        if (self.used >= self.cap) {
            @branchHint(.unlikely);
            try self.grow();
        }
        const i = self.used;
        self.used = i + 1;
        return i;
    }

    inline fn unlink(self: *DList, i: u32) i64 {
        const nodes = self.nodes;
        const nd = nodes[i];
        nodes[nd.prev].next = nd.next;
        nodes[nd.next].prev = nd.prev;
        nodes[i].next = self.free_head;
        self.free_head = i;
        self.count -= 1;
        return nd.value;
    }

    pub fn pushFront(self: *DList, value: i64) std.mem.Allocator.Error!u64 {
        const i = try self.allocNode();
        const nodes = self.nodes;
        const n = nodes[0].next;
        nodes[i] = .{ .value = value, .next = n, .prev = 0 };
        nodes[n].prev = i;
        nodes[0].next = i;
        self.count += 1;
        return i;
    }

    pub fn pushBack(self: *DList, value: i64) std.mem.Allocator.Error!u64 {
        const i = try self.allocNode();
        const nodes = self.nodes;
        const p = nodes[0].prev;
        nodes[i] = .{ .value = value, .next = 0, .prev = p };
        nodes[p].next = i;
        nodes[0].prev = i;
        self.count += 1;
        return i;
    }

    pub fn insertBefore(self: *DList, node: u64, value: i64) std.mem.Allocator.Error!u64 {
        const n: u32 = @truncate(node);
        // allocNode may move the pool, so reload `nodes` after it.
        const i = try self.allocNode();
        const nodes = self.nodes;
        const p = nodes[n].prev;
        nodes[i] = .{ .value = value, .next = n, .prev = p };
        nodes[p].next = i;
        nodes[n].prev = i;
        self.count += 1;
        return i;
    }

    pub fn insertAfter(self: *DList, node: u64, value: i64) std.mem.Allocator.Error!u64 {
        const p: u32 = @truncate(node);
        const i = try self.allocNode();
        const nodes = self.nodes;
        const n = nodes[p].next;
        nodes[i] = .{ .value = value, .next = n, .prev = p };
        nodes[p].next = i;
        nodes[n].prev = i;
        self.count += 1;
        return i;
    }

    pub fn remove(self: *DList, node: u64) i64 {
        return self.unlink(@truncate(node));
    }

    pub fn popFront(self: *DList) ?i64 {
        const f = self.nodes[0].next;
        if (f == 0) return null;
        return self.unlink(f);
    }

    pub fn popBack(self: *DList) ?i64 {
        const b = self.nodes[0].prev;
        if (b == 0) return null;
        return self.unlink(b);
    }

    pub fn moveToFront(self: *DList, node: u64) void {
        const i: u32 = @truncate(node);
        const nodes = self.nodes;
        const f = nodes[0].next;
        if (f == i) return;
        const nd = nodes[i];
        // Unlink.
        nodes[nd.prev].next = nd.next;
        nodes[nd.next].prev = nd.prev;
        // Relink at the front (f != i, so f is still a valid neighbour).
        nodes[i].next = f;
        nodes[i].prev = 0;
        nodes[f].prev = i;
        nodes[0].next = i;
    }

    pub fn front(self: *const DList) u64 {
        return self.nodes[0].next;
    }

    pub fn back(self: *const DList) u64 {
        return self.nodes[0].prev;
    }

    pub fn next(self: *const DList, node: u64) u64 {
        return self.nodes[@as(u32, @truncate(node))].next;
    }

    pub fn prev(self: *const DList, node: u64) u64 {
        return self.nodes[@as(u32, @truncate(node))].prev;
    }

    pub fn get(self: *const DList, node: u64) i64 {
        return self.nodes[@as(u32, @truncate(node))].value;
    }

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