const std = @import("std");

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

comptime {
    if (@sizeOf(Node) != 16) @compileError("Node must be 16 bytes");
    if (@alignOf(Node) != 8) @compileError("Node must be 8-byte aligned");
}

const NODE_SIZE: u32 = @sizeOf(Node);
const INITIAL_CAP_NODES: u32 = 16;
const MAX_CAP_NODES: u32 = std.math.maxInt(u32) / NODE_SIZE;

// Read-only sentinel used by freshly initialized empty lists so `init` cannot
// fail and `front`/`back`/`popFront`/`popBack` work without null-pointer checks.
const empty_sentinel: Node = .{ .next = 0, .prev = 0, .value = 0 };

pub const DList = struct {
    // Byte pointer to the contiguous node pool (always at least 8-byte aligned;
    // offset 0 is the circular sentinel node, real nodes live at offsets 16, 32, ...).
    nodes: [*]align(8) u8,
    used_bytes: u32,
    cap_bytes: u32,
    free_head: u32,
    count: u32,
    allocator: std.mem.Allocator,

    pub fn init(allocator: std.mem.Allocator) DList {
        return .{
            .nodes = @ptrCast(@constCast(&empty_sentinel)),
            .used_bytes = NODE_SIZE,
            .cap_bytes = 0,
            .free_head = 0,
            .count = 0,
            .allocator = allocator,
        };
    }

    pub fn deinit(self: *DList) void {
        if (self.cap_bytes != 0) {
            const cap_nodes: usize = self.cap_bytes / NODE_SIZE;
            const slice: []Node = @as([*]Node, @ptrCast(self.nodes))[0..cap_nodes];
            self.allocator.free(slice);
            self.nodes = @ptrCast(@constCast(&empty_sentinel));
            self.used_bytes = NODE_SIZE;
            self.cap_bytes = 0;
            self.free_head = 0;
            self.count = 0;
        }
    }

    inline fn nodeAt(buf: [*]align(8) u8, off: usize) *Node {
        return @ptrCast(@alignCast(buf + off));
    }

    noinline fn grow(self: *DList) std.mem.Allocator.Error!void {
        @branchHint(.cold);
        if (self.cap_bytes == 0) {
            const mem = try self.allocator.alloc(Node, INITIAL_CAP_NODES);
            mem[0] = .{ .next = 0, .prev = 0, .value = 0 };
            self.nodes = @ptrCast(mem.ptr);
            self.cap_bytes = INITIAL_CAP_NODES * NODE_SIZE;
            return;
        }
        const old_cap_nodes: u32 = self.cap_bytes / NODE_SIZE;
        if (old_cap_nodes >= MAX_CAP_NODES) return error.OutOfMemory;
        const new_cap_nodes: u32 = if (old_cap_nodes > MAX_CAP_NODES / 2)
            MAX_CAP_NODES
        else
            old_cap_nodes * 2;
        const old_slice: []Node = @as([*]Node, @ptrCast(self.nodes))[0..old_cap_nodes];
        const new_slice = try self.allocator.realloc(old_slice, new_cap_nodes);
        self.nodes = @ptrCast(new_slice.ptr);
        self.cap_bytes = new_cap_nodes * NODE_SIZE;
    }

    inline fn allocNode(self: *DList) std.mem.Allocator.Error!u32 {
        const fh = self.free_head;
        if (fh != 0) {
            self.free_head = nodeAt(self.nodes, fh).next;
            return fh;
        }
        const off = self.used_bytes;
        if (off >= self.cap_bytes) {
            @branchHint(.unlikely);
            try self.grow();
        }
        self.used_bytes = off + NODE_SIZE;
        return off;
    }

    pub inline fn pushFront(self: *DList, value: i64) std.mem.Allocator.Error!u64 {
        const off = try self.allocNode();
        const buf = self.nodes;
        const head = nodeAt(buf, 0);
        const first = head.next;
        nodeAt(buf, off).* = .{ .next = first, .prev = 0, .value = value };
        nodeAt(buf, first).prev = off;
        head.next = off;
        self.count += 1;
        return off;
    }

    pub inline fn pushBack(self: *DList, value: i64) std.mem.Allocator.Error!u64 {
        const off = try self.allocNode();
        const buf = self.nodes;
        const head = nodeAt(buf, 0);
        const tail = head.prev;
        nodeAt(buf, off).* = .{ .next = 0, .prev = tail, .value = value };
        nodeAt(buf, tail).next = off;
        head.prev = off;
        self.count += 1;
        return off;
    }

    pub inline fn insertBefore(self: *DList, node: u64, value: i64) std.mem.Allocator.Error!u64 {
        const off = try self.allocNode();
        const buf = self.nodes;
        const t: u32 = @truncate(node);
        const target = nodeAt(buf, t);
        const p = target.prev;
        nodeAt(buf, off).* = .{ .next = t, .prev = p, .value = value };
        nodeAt(buf, p).next = off;
        target.prev = off;
        self.count += 1;
        return off;
    }

    pub inline fn insertAfter(self: *DList, node: u64, value: i64) std.mem.Allocator.Error!u64 {
        const off = try self.allocNode();
        const buf = self.nodes;
        const t: u32 = @truncate(node);
        const target = nodeAt(buf, t);
        const n = target.next;
        nodeAt(buf, off).* = .{ .next = n, .prev = t, .value = value };
        nodeAt(buf, n).prev = off;
        target.next = off;
        self.count += 1;
        return off;
    }

    pub inline fn remove(self: *DList, node: u64) i64 {
        const buf = self.nodes;
        const off: u32 = @truncate(node);
        const cur = nodeAt(buf, off);
        const nxt = cur.next;
        const prv = cur.prev;
        const val = cur.value;
        nodeAt(buf, prv).next = nxt;
        nodeAt(buf, nxt).prev = prv;
        cur.next = self.free_head;
        self.free_head = off;
        self.count -= 1;
        return val;
    }

    pub inline fn popFront(self: *DList) ?i64 {
        const buf = self.nodes;
        const head = nodeAt(buf, 0);
        const first = head.next;
        if (first == 0) {
            @branchHint(.unlikely);
            return null;
        }
        const n = nodeAt(buf, first);
        const nxt = n.next;
        const val = n.value;
        head.next = nxt;
        nodeAt(buf, nxt).prev = 0;
        n.next = self.free_head;
        self.free_head = first;
        self.count -= 1;
        return val;
    }

    pub inline fn popBack(self: *DList) ?i64 {
        const buf = self.nodes;
        const head = nodeAt(buf, 0);
        const last = head.prev;
        if (last == 0) {
            @branchHint(.unlikely);
            return null;
        }
        const n = nodeAt(buf, last);
        const prv = n.prev;
        const val = n.value;
        head.prev = prv;
        nodeAt(buf, prv).next = 0;
        n.next = self.free_head;
        self.free_head = last;
        self.count -= 1;
        return val;
    }

    pub inline fn moveToFront(self: *DList, node: u64) void {
        const buf = self.nodes;
        const off: u32 = @truncate(node);
        const head = nodeAt(buf, 0);
        const first = head.next;
        if (off == first) {
            @branchHint(.unlikely);
            return;
        }
        const cur = nodeAt(buf, off);
        const nxt = cur.next;
        const prv = cur.prev;
        nodeAt(buf, prv).next = nxt;
        nodeAt(buf, nxt).prev = prv;
        cur.next = first;
        cur.prev = 0;
        nodeAt(buf, first).prev = off;
        head.next = off;
    }

    pub inline fn front(self: *const DList) u64 {
        return nodeAt(self.nodes, 0).next;
    }

    pub inline fn back(self: *const DList) u64 {
        return nodeAt(self.nodes, 0).prev;
    }

    pub inline fn next(self: *const DList, node: u64) u64 {
        return nodeAt(self.nodes, @intCast(node)).next;
    }

    pub inline fn prev(self: *const DList, node: u64) u64 {
        return nodeAt(self.nodes, @intCast(node)).prev;
    }

    pub inline fn get(self: *const DList, node: u64) i64 {
        return nodeAt(self.nodes, @intCast(node)).value;
    }

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