// Package rbtree implements a classic (CLRS-style) red-black tree mapping
// int64 keys to int64 values.
//
// Nodes live in a single pointer-free slice and are linked by uint32
// indices, so the garbage collector never has to scan the tree. Index 0 is a
// black sentinel node that stands in for every nil link (as in CLRS), which
// keeps the delete fix-up free of nil checks. Each node is exactly 32 bytes,
// so a node never straddles a cache line.
package rbtree

import "unsafe"

type node struct {
	key    int64
	child  [2]uint32 // 0 = left, 1 = right; 0 means nil (sentinel)
	val    int64
	parent uint32
	red    bool
}

const nodeSize = unsafe.Sizeof(node{})

// Compile-time check that the node is 32 bytes.
var _ [32 - nodeSize]struct{}
var _ [nodeSize - 32]struct{}

const initialCap = 64

type RBTree struct {
	base  unsafe.Pointer // &nodes[0]
	root  uint32
	free  uint32 // head of free list, linked through child[0]
	used  uint32 // next never-used index in nodes
	count int
	nodes []node
}

func New() *RBTree {
	t := &RBTree{}
	t.nodes = make([]node, initialCap)
	t.base = unsafe.Pointer(&t.nodes[0])
	t.used = 1 // index 0 is the sentinel
	return t
}

func (t *RBTree) nd(i uint32) *node {
	return (*node)(unsafe.Add(t.base, uintptr(i)*nodeSize))
}

func (t *RBTree) grow() {
	newCap := 2 * len(t.nodes)
	nn := make([]node, newCap)
	copy(nn, t.nodes)
	t.nodes = nn
	t.base = unsafe.Pointer(&nn[0])
}

func (t *RBTree) alloc() uint32 {
	if i := t.free; i != 0 {
		t.free = t.nd(i).child[0]
		return i
	}
	if int(t.used) == len(t.nodes) {
		t.grow()
	}
	i := t.used
	t.used++
	return i
}

func b2i(b bool) uint32 {
	var r uint32
	if b {
		r = 1
	}
	return r
}

// rotate rotates x in direction d: d == 0 is a left rotation (x's right
// child moves up), d == 1 is a right rotation.
func (t *RBTree) rotate(x uint32, d uint32) {
	xn := t.nd(x)
	y := xn.child[1-d]
	yn := t.nd(y)
	b := yn.child[d]
	xn.child[1-d] = b
	if b != 0 {
		t.nd(b).parent = x
	}
	p := xn.parent
	yn.parent = p
	if p == 0 {
		t.root = y
	} else {
		pn := t.nd(p)
		pn.child[b2i(pn.child[1] == x)] = y
	}
	yn.child[d] = x
	xn.parent = y
}

func (t *RBTree) Insert(key, value int64) bool {
	x := t.root
	var p, dir uint32
	for x != 0 {
		n := t.nd(x)
		if key == n.key {
			n.val = value
			return false
		}
		p = x
		dir = b2i(key > n.key)
		x = n.child[dir]
	}
	z := t.alloc()
	*t.nd(z) = node{key: key, val: value, parent: p, red: true}
	t.count++
	if p == 0 {
		t.root = z
		t.nd(z).red = false
		return true
	}
	pn := t.nd(p)
	pn.child[dir] = z
	if pn.red {
		t.insertFixup(z)
	}
	return true
}

func (t *RBTree) insertFixup(z uint32) {
	for {
		p := t.nd(z).parent
		if p == 0 {
			break
		}
		pn := t.nd(p)
		if !pn.red {
			break
		}
		g := pn.parent // exists: p is red so it is not the root
		gn := t.nd(g)
		d := b2i(gn.child[1] == p)
		u := gn.child[1-d]
		un := t.nd(u) // sentinel is always black
		if un.red {
			pn.red = false
			un.red = false
			gn.red = true
			z = g
			continue
		}
		if pn.child[1-d] == z {
			t.rotate(p, d)
			z = p
			p = t.nd(z).parent
			pn = t.nd(p)
		}
		pn.red = false
		gn.red = true
		t.rotate(g, 1-d)
		break
	}
	t.nd(t.root).red = false
}

func (t *RBTree) Get(key int64) (value int64, ok bool) {
	x := t.root
	for x != 0 {
		n := t.nd(x)
		if key == n.key {
			return n.val, true
		}
		x = n.child[b2i(key > n.key)]
	}
	return 0, false
}

// transplant replaces the subtree rooted at u with the one rooted at v.
// v may be the sentinel; its parent is set regardless (CLRS).
func (t *RBTree) transplant(u, v uint32) {
	p := t.nd(u).parent
	if p == 0 {
		t.root = v
	} else {
		pn := t.nd(p)
		pn.child[b2i(pn.child[1] == u)] = v
	}
	t.nd(v).parent = p
}

func (t *RBTree) Remove(key int64) bool {
	z := t.root
	var zn *node
	for z != 0 {
		zn = t.nd(z)
		if key == zn.key {
			break
		}
		z = zn.child[b2i(key > zn.key)]
	}
	if z == 0 {
		return false
	}
	var x uint32
	removedRed := zn.red
	if zn.child[0] == 0 {
		x = zn.child[1]
		t.transplant(z, x)
	} else if zn.child[1] == 0 {
		x = zn.child[0]
		t.transplant(z, x)
	} else {
		y := zn.child[1]
		yn := t.nd(y)
		for yn.child[0] != 0 {
			y = yn.child[0]
			yn = t.nd(y)
		}
		removedRed = yn.red
		x = yn.child[1]
		if yn.parent == z {
			t.nd(x).parent = y
		} else {
			t.transplant(y, x)
			yn.child[1] = zn.child[1]
			t.nd(yn.child[1]).parent = y
		}
		t.transplant(z, y)
		yn.child[0] = zn.child[0]
		t.nd(yn.child[0]).parent = y
		yn.red = zn.red
	}
	if !removedRed {
		t.deleteFixup(x)
	}
	// Release z to the free list; keep the sentinel clean.
	zn.child[0] = t.free
	t.free = z
	s := t.nd(0)
	s.parent = 0
	s.red = false
	t.count--
	return true
}

func (t *RBTree) deleteFixup(x uint32) {
	xn := t.nd(x)
	for x != t.root && !xn.red {
		xp := xn.parent
		pn := t.nd(xp)
		d := b2i(pn.child[0] != x)
		w := pn.child[1-d]
		wn := t.nd(w)
		if wn.red {
			wn.red = false
			pn.red = true
			t.rotate(xp, d)
			w = pn.child[1-d]
			wn = t.nd(w)
		}
		if !t.nd(wn.child[0]).red && !t.nd(wn.child[1]).red {
			wn.red = true
			x = xp
			xn = pn
			continue
		}
		if !t.nd(wn.child[1-d]).red {
			t.nd(wn.child[d]).red = false
			wn.red = true
			t.rotate(w, 1-d)
			w = pn.child[1-d]
			wn = t.nd(w)
		}
		wn.red = pn.red
		pn.red = false
		t.nd(wn.child[1-d]).red = false
		t.rotate(xp, d)
		x = t.root
		xn = t.nd(x)
		break
	}
	xn.red = false
}

func (t *RBTree) Range(lo, hi int64, outKeys, outVals []int64) int {
	limit := len(outKeys)
	if lo > hi || limit == 0 {
		return 0
	}
	outVals = outVals[:limit]
	// Height is at most 2*log2(n+1) <= 64 for n < 2^32.
	var stack [128]uint32
	sp := 0
	x := t.root
	for x != 0 {
		n := t.nd(x)
		if n.key >= lo {
			stack[sp&127] = x
			sp++
			x = n.child[0]
		} else {
			x = n.child[1]
		}
	}
	cnt := 0
	for sp > 0 {
		sp--
		n := t.nd(stack[sp&127])
		if n.key > hi {
			break
		}
		outKeys[cnt] = n.key
		outVals[cnt] = n.val
		cnt++
		if cnt == limit {
			break
		}
		x = n.child[1]
		for x != 0 {
			stack[sp&127] = x
			sp++
			x = t.nd(x).child[0]
		}
	}
	return cnt
}

func (t *RBTree) Len() int { return t.count }

func (t *RBTree) Height() int { return t.height(t.root) }

func (t *RBTree) height(x uint32) int {
	if x == 0 {
		return 0
	}
	n := t.nd(x)
	l := t.height(n.child[0])
	r := t.height(n.child[1])
	if r > l {
		l = r
	}
	return l + 1
}
