// Package dlist implements a doubly linked list of int64 values.
//
// Design:
//   - All nodes live in one growable pool (a []node). A node is 16 bytes:
//     the value plus 32-bit next/prev links that are indices into the pool,
//     so eight nodes fit in a 128-byte cache line and none straddles a line.
//   - Pool slot 0 is a sentinel that closes the list into a ring:
//     sentinel.next is the first node and sentinel.prev the last. Because the
//     sentinel's index is 0, "no node" (handle 0) falls out of the links
//     directly and every insert/remove is branch-free.
//   - A handle is the node's pool index (never 0, since 0 is the sentinel).
//     The pool only grows (doubling) and slots never move relative to the
//     pool start, so handles stay valid while their node is in the list.
//   - Removed nodes go onto an intrusive LIFO free list threaded through
//     their next field and are reused before fresh slots are taken.
//   - The pool holds no Go pointers, so the GC never scans it; the slice
//     header keeps the pool alive.
package dlist

import "unsafe"

type node struct {
	val  int64
	next uint32
	prev uint32
}

const nodeSize = unsafe.Sizeof(node{})

// DList is a doubly linked list of int64 values.
type DList struct {
	nodes []node // the pool; nodes[0] is the sentinel. len == usable slots.
	free  uint32 // head of the free list (0 = empty)
	hw    uint32 // first never-used slot
	n     int    // number of elements
}

const initCap = 64

// New creates an empty list.
func New() *DList {
	// A zeroed sentinel (next = prev = 0) is an empty ring.
	return &DList{nodes: make([]node, initCap), hw: 1}
}

func nodeAt(b unsafe.Pointer, i uint32) *node {
	return (*node)(unsafe.Add(b, uintptr(i)*nodeSize))
}

func (l *DList) base() unsafe.Pointer {
	return unsafe.Pointer(unsafe.SliceData(l.nodes))
}

// newNode returns the index of a free slot, growing the pool if needed.
func (l *DList) newNode() uint32 {
	i := l.free
	if i != 0 {
		l.free = nodeAt(l.base(), i).next
		return i
	}
	i = l.hw
	if int(i) == len(l.nodes) {
		l.grow()
	}
	l.hw = i + 1
	return i
}

//go:noinline
func (l *DList) grow() {
	n := len(l.nodes)
	if n >= 1<<31 {
		panic("dlist: too many nodes")
	}
	ns := append(l.nodes, make([]node, n)...)
	l.nodes = ns[:cap(ns)]
}

func (l *DList) link(i, p, nx uint32, v int64) uint64 {
	b := l.base()
	nd := nodeAt(b, i)
	nd.val = v
	nd.next = nx
	nd.prev = p
	nodeAt(b, p).next = i
	nodeAt(b, nx).prev = i
	l.n++
	return uint64(i)
}

// PushFront adds value as the new first element.
func (l *DList) PushFront(value int64) uint64 {
	i := l.newNode()
	return l.link(i, 0, nodeAt(l.base(), 0).next, value)
}

// PushBack adds value as the new last element.
func (l *DList) PushBack(value int64) uint64 {
	i := l.newNode()
	return l.link(i, nodeAt(l.base(), 0).prev, 0, value)
}

// InsertBefore adds value immediately before node.
func (l *DList) InsertBefore(node uint64, value int64) uint64 {
	i := l.newNode()
	h := uint32(node)
	return l.link(i, nodeAt(l.base(), h).prev, h, value)
}

// InsertAfter adds value immediately after node.
func (l *DList) InsertAfter(node uint64, value int64) uint64 {
	i := l.newNode()
	h := uint32(node)
	return l.link(i, h, nodeAt(l.base(), h).next, value)
}

func (l *DList) unlink(b unsafe.Pointer, i uint32) int64 {
	nd := nodeAt(b, i)
	p, nx := nd.prev, nd.next
	nodeAt(b, p).next = nx
	nodeAt(b, nx).prev = p
	nd.next = l.free
	l.free = i
	l.n--
	return nd.val
}

// Remove unlinks node and returns its value.
func (l *DList) Remove(node uint64) int64 {
	return l.unlink(l.base(), uint32(node))
}

// PopFront removes the first element.
func (l *DList) PopFront() (value int64, ok bool) {
	b := l.base()
	i := nodeAt(b, 0).next
	if i == 0 {
		return 0, false
	}
	return l.unlink(b, i), true
}

// PopBack removes the last element.
func (l *DList) PopBack() (value int64, ok bool) {
	b := l.base()
	i := nodeAt(b, 0).prev
	if i == 0 {
		return 0, false
	}
	return l.unlink(b, i), true
}

// MoveToFront makes node the first element.
func (l *DList) MoveToFront(node uint64) {
	b := l.base()
	s := nodeAt(b, 0)
	i := uint32(node)
	f := s.next
	if f == i {
		return
	}
	nd := nodeAt(b, i)
	p, nx := nd.prev, nd.next
	nodeAt(b, p).next = nx
	nodeAt(b, nx).prev = p
	nd.prev = 0
	nd.next = f
	nodeAt(b, f).prev = i
	s.next = i
}

// Front returns the first node, or 0 if the list is empty.
func (l *DList) Front() uint64 { return uint64(nodeAt(l.base(), 0).next) }

// Back returns the last node, or 0 if the list is empty.
func (l *DList) Back() uint64 { return uint64(nodeAt(l.base(), 0).prev) }

// Next returns the node after node, or 0 if it is the last.
func (l *DList) Next(node uint64) uint64 {
	return uint64(nodeAt(l.base(), uint32(node)).next)
}

// Prev returns the node before node, or 0 if it is the first.
func (l *DList) Prev(node uint64) uint64 {
	return uint64(nodeAt(l.base(), uint32(node)).prev)
}

// Get returns the value of node.
func (l *DList) Get(node uint64) int64 {
	return nodeAt(l.base(), uint32(node)).val
}

// Len returns the number of elements.
func (l *DList) Len() int { return l.n }
