#if canImport(Darwin)
import Darwin
#else
import Glibc
#endif

// One node per value: 16 bytes (value + two 32-bit pool indices), so eight
// nodes share one 128-byte cache line.
struct DListNode {
    var value: Int64
    var next: UInt32
    var prev: UInt32
}

// All mutable state lives behind a raw pointer so that accesses carry no
// dynamic exclusivity checks (which class stored `var`s would).
struct DListState {
    var base: UnsafeMutablePointer<DListNode>  // node pool; index 0 is the sentinel
    var freeHead: UInt32                       // singly linked free list through `next`; 0 = empty
    var used: UInt32                           // first never-used pool index
    var cap: Int                               // pool capacity in nodes
    var count: Int
}

final class DList {
    @usableFromInline let st: UnsafeMutablePointer<DListState>

    init() {
        let cap = 1024
        let base = malloc(cap * MemoryLayout<DListNode>.stride)!
            .bindMemory(to: DListNode.self, capacity: cap)
        base[0] = DListNode(value: 0, next: 0, prev: 0)  // sentinel: circular, empty
        st = UnsafeMutablePointer<DListState>.allocate(capacity: 1)
        st.initialize(to: DListState(base: base, freeHead: 0, used: 1, cap: cap, count: 0))
    }

    deinit {
        free(st.pointee.base)
        st.deallocate()
    }

    @inline(never)
    private func grow() {
        let oldCap = st.pointee.cap
        let newCap = oldCap &* 2
        precondition(newCap - 1 <= Int(UInt32.max), "DList: too many nodes")
        let p = realloc(st.pointee.base, newCap * MemoryLayout<DListNode>.stride)!
        st.pointee.base = p.bindMemory(to: DListNode.self, capacity: newCap)
        st.pointee.cap = newCap
    }

    // Returns the index of a fresh node slot; the pool may move (handles are indices).
    @inline(__always)
    private func allocNode() -> UInt32 {
        let f = st.pointee.freeHead
        if _fastPath(f != 0) {
            st.pointee.freeHead = st.pointee.base[Int(f)].next
            return f
        }
        let i = st.pointee.used
        if _slowPath(Int(i) == st.pointee.cap) { grow() }
        st.pointee.used = i &+ 1
        return i
    }

    @inline(__always)
    private func linkAfter(_ p: UInt32, _ value: Int64) -> UInt64 {
        let i = allocNode()
        let b = st.pointee.base
        let n = b[Int(p)].next
        b[Int(i)] = DListNode(value: value, next: n, prev: p)
        b[Int(p)].next = i
        b[Int(n)].prev = i
        st.pointee.count &+= 1
        return UInt64(i)
    }

    @inline(__always)
    private func linkBefore(_ n: UInt32, _ value: Int64) -> UInt64 {
        let i = allocNode()
        let b = st.pointee.base
        let p = b[Int(n)].prev
        b[Int(i)] = DListNode(value: value, next: n, prev: p)
        b[Int(p)].next = i
        b[Int(n)].prev = i
        st.pointee.count &+= 1
        return UInt64(i)
    }

    @inline(__always)
    private func unlink(_ x: UInt32) -> Int64 {
        let b = st.pointee.base
        let node = b[Int(x)]
        b[Int(node.prev)].next = node.next
        b[Int(node.next)].prev = node.prev
        b[Int(x)].next = st.pointee.freeHead
        st.pointee.freeHead = x
        st.pointee.count &-= 1
        return node.value
    }

    @inline(__always)
    func pushFront(_ value: Int64) -> UInt64 { linkAfter(0, value) }

    @inline(__always)
    func pushBack(_ value: Int64) -> UInt64 { linkBefore(0, value) }

    @inline(__always)
    func insertBefore(_ node: UInt64, _ value: Int64) -> UInt64 {
        linkBefore(UInt32(truncatingIfNeeded: node), value)
    }

    @inline(__always)
    func insertAfter(_ node: UInt64, _ value: Int64) -> UInt64 {
        linkAfter(UInt32(truncatingIfNeeded: node), value)
    }

    @inline(__always)
    func remove(_ node: UInt64) -> Int64 {
        unlink(UInt32(truncatingIfNeeded: node))
    }

    @inline(__always)
    func popFront() -> Int64? {
        let f = st.pointee.base[0].next
        if _slowPath(f == 0) { return nil }
        return unlink(f)
    }

    @inline(__always)
    func popBack() -> Int64? {
        let l = st.pointee.base[0].prev
        if _slowPath(l == 0) { return nil }
        return unlink(l)
    }

    @inline(__always)
    func moveToFront(_ node: UInt64) {
        let x = UInt32(truncatingIfNeeded: node)
        let b = st.pointee.base
        let first = b[0].next
        if first == x { return }
        let p = b[Int(x)].prev
        let n = b[Int(x)].next
        b[Int(p)].next = n
        b[Int(n)].prev = p
        b[Int(x)].next = first
        b[Int(x)].prev = 0
        b[Int(first)].prev = x
        b[0].next = x
    }

    @inline(__always)
    func front() -> UInt64 { UInt64(st.pointee.base[0].next) }

    @inline(__always)
    func back() -> UInt64 { UInt64(st.pointee.base[0].prev) }

    @inline(__always)
    func next(_ node: UInt64) -> UInt64 {
        UInt64(st.pointee.base[Int(truncatingIfNeeded: node)].next)
    }

    @inline(__always)
    func prev(_ node: UInt64) -> UInt64 {
        UInt64(st.pointee.base[Int(truncatingIfNeeded: node)].prev)
    }

    @inline(__always)
    func get(_ node: UInt64) -> Int64 {
        st.pointee.base[Int(truncatingIfNeeded: node)].value
    }

    var count: Int {
        @inline(__always) get { st.pointee.count }
    }
}
