// Package radix implements a path-compressed byte trie (radix tree) mapping
// byte-string keys to int64 values.
//
// Layout: every node is a 64-byte, pointer-free record in one arena slice
// (so the garbage collector never scans it). The children of a node are
// stored contiguously, sorted by first label byte, in a block of the arena;
// the parent keeps the block offset and the sorted first bytes of its
// children (inline for up to 16 children, a 256-bit bitmap with popcount
// ranks for more). Following an edge therefore costs one cache line: the
// child's label is inline in the child record (up to 28 bytes; longer
// labels live in a separate byte pool).
package radix

import (
	"math/bits"
	"unsafe"
)

const (
	inlineMax = 28
	flagVal   = 1
	clsShift  = 4
	lo8       = 0x0101010101010101
	hi8       = 0x8080808080808080
	numCls    = 16
	maxDepth  = 258
)

var classCap = [numCls]int{1, 2, 3, 4, 6, 8, 12, 16, 24, 32, 48, 64, 96, 128, 192, 256}
var classOf [257]uint8

func init() {
	c := 0
	for n := 1; n <= 256; n++ {
		for classCap[c] < n {
			c++
		}
		classOf[n] = uint8(c)
	}
}

// node is exactly 64 bytes.
type node struct {
	keys  [16]byte // sorted first bytes of children (nkids<=16) or bitmap offset
	value int64
	count uint32 // keys in subtree
	kids  uint32 // offset of the children block (free-list link when freed)
	label [inlineMax]byte
	nkids uint16
	llen  uint8
	flags uint8 // bit0: has value; bits 4..7: block size class
}

var _ [64 - unsafe.Sizeof(node{})]byte
var _ [unsafe.Sizeof(node{}) - 64]byte

type frame struct{ cur, end uint32 }

// RadixTree is a radix tree over bytes.
type RadixTree struct {
	nodes []node
	free  [numCls]uint32
	lpool []byte
	lfree [8]uint32
	bpool []uint64
	bfree uint32
	size  int
	path  [maxDepth]uint32
	stk   [maxDepth]frame
}

// New creates an empty tree.
func New() *RadixTree {
	t := &RadixTree{}
	t.nodes = make([]node, 1, 256)
	return t
}

// ------------------------------------------------------------ allocation

func (t *RadixTree) allocBlock(cls int) uint32 {
	if h := t.free[cls]; h != 0 {
		t.free[cls] = t.nodes[h].kids
		return h
	}
	c := classCap[cls]
	off := len(t.nodes)
	need := off + c
	if need > cap(t.nodes) {
		nc := 2 * cap(t.nodes)
		if nc < need {
			nc = need
		}
		nn := make([]node, need, nc)
		copy(nn, t.nodes)
		t.nodes = nn
	} else {
		t.nodes = t.nodes[:need]
	}
	return uint32(off)
}

func (t *RadixTree) freeBlock(off uint32, cls int) {
	t.nodes[off].kids = t.free[cls]
	t.free[cls] = off
}

func (t *RadixTree) allocLabel(l int) uint32 {
	cls := (l - 1) >> 5
	if h := t.lfree[cls]; h != 0 {
		t.lfree[cls] = *(*uint32)(unsafe.Pointer(&t.lpool[h]))
		return h
	}
	if len(t.lpool) == 0 {
		t.lpool = make([]byte, 32, 4096)
	}
	size := (cls + 1) << 5
	off := len(t.lpool)
	need := off + size
	if need > cap(t.lpool) {
		nc := 2 * cap(t.lpool)
		if nc < need {
			nc = need
		}
		nb := make([]byte, need, nc)
		copy(nb, t.lpool)
		t.lpool = nb
	} else {
		t.lpool = t.lpool[:need]
	}
	return uint32(off)
}

func (t *RadixTree) freeLabel(n *node) {
	l := int(n.llen)
	if l <= inlineMax {
		return
	}
	off := *(*uint32)(unsafe.Pointer(&n.label[0]))
	cls := (l - 1) >> 5
	*(*uint32)(unsafe.Pointer(&t.lpool[off])) = t.lfree[cls]
	t.lfree[cls] = off
}

// setLabel stores lab as the label of n (n's old label must already be
// released if it was pooled).
func (t *RadixTree) setLabel(n *node, lab []byte) {
	l := len(lab)
	n.llen = uint8(l)
	if l <= inlineMax {
		copy(n.label[:], lab)
		return
	}
	off := t.allocLabel(l)
	copy(t.lpool[off:int(off)+l], lab)
	*(*uint32)(unsafe.Pointer(&n.label[0])) = off
}

func (t *RadixTree) labelPtr(n *node) unsafe.Pointer {
	if n.llen <= inlineMax {
		return unsafe.Pointer(&n.label[0])
	}
	return unsafe.Pointer(&t.lpool[*(*uint32)(unsafe.Pointer(&n.label[0]))])
}

func (t *RadixTree) labelBytes(n *node) []byte {
	l := uint32(n.llen)
	if l <= inlineMax {
		return n.label[:l]
	}
	off := *(*uint32)(unsafe.Pointer(&n.label[0]))
	return t.lpool[off : off+l]
}

func (t *RadixTree) allocBitmap() uint32 {
	if h := t.bfree; h != 0 {
		t.bfree = uint32(t.bpool[h])
		t.bpool[h] = 0
		return h
	}
	if len(t.bpool) == 0 {
		t.bpool = make([]uint64, 4, 64)
	}
	off := len(t.bpool)
	t.bpool = append(t.bpool, 0, 0, 0, 0)
	return uint32(off)
}

func (t *RadixTree) freeBitmap(off uint32) {
	t.bpool[off+1], t.bpool[off+2], t.bpool[off+3] = 0, 0, 0
	t.bpool[off] = uint64(t.bfree)
	t.bfree = off
}

// ------------------------------------------------------------ byte helpers

func eqBytes(a, b unsafe.Pointer, n int) bool {
	for n >= 8 {
		if *(*uint64)(a) != *(*uint64)(b) {
			return false
		}
		a = unsafe.Add(a, 8)
		b = unsafe.Add(b, 8)
		n -= 8
	}
	if n >= 4 {
		if *(*uint32)(a) != *(*uint32)(b) {
			return false
		}
		a = unsafe.Add(a, 4)
		b = unsafe.Add(b, 4)
		n -= 4
	}
	for i := 0; i < n; i++ {
		if *(*byte)(unsafe.Add(a, i)) != *(*byte)(unsafe.Add(b, i)) {
			return false
		}
	}
	return true
}

func commonPrefix(a, b unsafe.Pointer, n int) int {
	i := 0
	for i+8 <= n {
		x := *(*uint64)(unsafe.Add(a, i)) ^ *(*uint64)(unsafe.Add(b, i))
		if x != 0 {
			return i + bits.TrailingZeros64(x)>>3
		}
		i += 8
	}
	for i < n && *(*byte)(unsafe.Add(a, i)) == *(*byte)(unsafe.Add(b, i)) {
		i++
	}
	return i
}

// ------------------------------------------------------------ child index

// child returns the position (within n's children block) of the child whose
// label starts with b.
func (t *RadixTree) child(n *node, b byte) (uint32, bool) {
	nk := uint(n.nkids)
	if nk <= 16 {
		bb := uint64(b) * lo8
		x := *(*uint64)(unsafe.Pointer(&n.keys[0])) ^ bb
		m := (x - lo8) &^ x & hi8 & ((uint64(1) << (nk * 8)) - 1)
		if m != 0 {
			return uint32(bits.TrailingZeros64(m) >> 3), true
		}
		if nk > 8 {
			x = *(*uint64)(unsafe.Pointer(&n.keys[8])) ^ bb
			m = (x - lo8) &^ x & hi8 & ((uint64(1) << ((nk - 8) * 8)) - 1)
			if m != 0 {
				return 8 + uint32(bits.TrailingZeros64(m)>>3), true
			}
		}
		return 0, false
	}
	return t.childBig(n, b)
}

func (t *RadixTree) childBig(n *node, b byte) (uint32, bool) {
	off := *(*uint32)(unsafe.Pointer(&n.keys[0]))
	bm := t.bpool[off : off+4 : off+4]
	w := b >> 6
	bit := uint64(1) << (b & 63)
	if bm[w]&bit == 0 {
		return 0, false
	}
	r := bits.OnesCount64(bm[w] & (bit - 1))
	for i := byte(0); i < w; i++ {
		r += bits.OnesCount64(bm[i])
	}
	return uint32(r), true
}

// insertPos is the sorted position for a new child starting with b.
func (t *RadixTree) insertPos(n *node, b byte) int {
	nk := int(n.nkids)
	if nk <= 16 {
		at := 0
		for at < nk && n.keys[at] < b {
			at++
		}
		return at
	}
	off := *(*uint32)(unsafe.Pointer(&n.keys[0]))
	bm := t.bpool[off : off+4 : off+4]
	w := b >> 6
	bit := uint64(1) << (b & 63)
	r := bits.OnesCount64(bm[w] & (bit - 1))
	for i := byte(0); i < w; i++ {
		r += bits.OnesCount64(bm[i])
	}
	return r
}

func (t *RadixTree) keyInsert(p *node, nk, at int, b byte) {
	if nk < 16 {
		copy(p.keys[at+1:nk+1], p.keys[at:nk])
		p.keys[at] = b
		return
	}
	if nk == 16 {
		off := t.allocBitmap()
		bm := t.bpool[off : off+4]
		for i := 0; i < 16; i++ {
			k := p.keys[i]
			bm[k>>6] |= uint64(1) << (k & 63)
		}
		bm[b>>6] |= uint64(1) << (b & 63)
		p.keys = [16]byte{}
		*(*uint32)(unsafe.Pointer(&p.keys[0])) = off
		return
	}
	off := *(*uint32)(unsafe.Pointer(&p.keys[0]))
	t.bpool[off+uint32(b>>6)] |= uint64(1) << (b & 63)
}

func (t *RadixTree) keyRemove(p *node, nk, at int, b byte) {
	if nk <= 16 {
		copy(p.keys[at:nk-1], p.keys[at+1:nk])
		return
	}
	off := *(*uint32)(unsafe.Pointer(&p.keys[0]))
	bm := t.bpool[off : off+4]
	bm[b>>6] &^= uint64(1) << (b & 63)
	if nk == 17 {
		var k [16]byte
		j := 0
		for w := 0; w < 4; w++ {
			x := bm[w]
			for x != 0 {
				k[j] = byte(w*64 + bits.TrailingZeros64(x))
				j++
				x &= x - 1
			}
		}
		t.freeBitmap(off)
		p.keys = k
	}
}

func setCls(p *node, cls int) {
	p.flags = p.flags&^(0xF<<clsShift) | uint8(cls)<<clsShift
}

// addChild opens a slot at sorted position at in pi's children block for a
// child starting with b and returns the slot's arena index.
func (t *RadixTree) addChild(pi uint32, at int, b byte) uint32 {
	p := &t.nodes[pi]
	nk := int(p.nkids)
	if nk == 0 {
		blk := t.allocBlock(0)
		p = &t.nodes[pi]
		p.kids = blk
		setCls(p, 0)
		p.nkids = 1
		p.keys[0] = b
		return blk
	}
	cls := int(p.flags >> clsShift)
	old := p.kids
	u := uint32(at)
	n32 := uint32(nk)
	if nk == classCap[cls] {
		ncls := cls + 1
		blk := t.allocBlock(ncls)
		nodes := t.nodes
		copy(nodes[blk:blk+u], nodes[old:old+u])
		copy(nodes[blk+u+1:blk+n32+1], nodes[old+u:old+n32])
		t.freeBlock(old, cls)
		p = &nodes[pi]
		p.kids = blk
		setCls(p, ncls)
	} else {
		nodes := t.nodes
		copy(nodes[old+u+1:old+n32+1], nodes[old+u:old+n32])
	}
	t.keyInsert(p, nk, at, b)
	p.nkids = uint16(nk + 1)
	return p.kids + u
}

// removeChild deletes the child at position at (first byte b) of pi.
func (t *RadixTree) removeChild(pi uint32, at int, b byte) {
	p := &t.nodes[pi]
	nk := int(p.nkids)
	cls := int(p.flags >> clsShift)
	old := p.kids
	if nk == 1 {
		t.freeBlock(old, cls)
		p.kids = 0
		p.nkids = 0
		return
	}
	nn := nk - 1
	u := uint32(at)
	n32 := uint32(nk)
	c := classCap[cls]
	if c >= 4 && nn*4 <= c {
		ncls := int(classOf[nn])
		blk := t.allocBlock(ncls)
		nodes := t.nodes
		copy(nodes[blk:blk+u], nodes[old:old+u])
		copy(nodes[blk+u:blk+n32-1], nodes[old+u+1:old+n32])
		t.freeBlock(old, cls)
		p = &nodes[pi]
		p.kids = blk
		setCls(p, ncls)
	} else {
		nodes := t.nodes
		copy(nodes[old+u:old+n32-1], nodes[old+u+1:old+n32])
	}
	t.keyRemove(p, nk, at, b)
	p.nkids = uint16(nn)
}

// split splits the edge into node ci after m bytes of its label (0 < m <
// llen). rest is the remainder of the key being inserted, starting at the
// edge; if it ends at the split point the new middle node takes the value,
// otherwise a new leaf is added beside the shortened node.
func (t *RadixTree) split(ci uint32, m int, rest []byte, value int64) {
	var buf [256]byte
	c := &t.nodes[ci]
	ol := int(c.llen)
	copy(buf[:ol], t.labelBytes(c))
	t.freeLabel(c)
	leaf := len(rest) > m
	cls := 0
	if leaf {
		cls = 1
	}
	blk := t.allocBlock(cls)
	nodes := t.nodes
	c = &nodes[ci]
	var cpos, lpos uint32 = 0, 1
	if leaf && rest[m] < buf[m] {
		cpos, lpos = 1, 0
	}
	nc := &nodes[blk+cpos]
	*nc = *c
	t.setLabel(nc, buf[m:ol])
	cnt := c.count
	*c = node{}
	c.count = cnt + 1
	c.kids = blk
	c.flags = uint8(cls) << clsShift
	t.setLabel(c, buf[:m])
	if leaf {
		c.nkids = 2
		c.keys[cpos] = buf[m]
		c.keys[lpos] = rest[m]
		lf := &nodes[blk+lpos]
		*lf = node{value: value, count: 1, flags: flagVal}
		t.setLabel(lf, rest[m:])
	} else {
		c.nkids = 1
		c.keys[0] = buf[m]
		c.value = value
		c.flags |= flagVal
	}
}

// merge folds node pi (no value, one child) together with its child.
func (t *RadixTree) merge(pi uint32) {
	nodes := t.nodes
	p := &nodes[pi]
	ci := p.kids
	c := &nodes[ci]
	var buf [256]byte
	pl := int(p.llen)
	cl := int(c.llen)
	copy(buf[:pl], t.labelBytes(p))
	copy(buf[pl:pl+cl], t.labelBytes(c))
	t.freeLabel(p)
	t.freeLabel(c)
	cls := int(p.flags >> clsShift)
	*p = *c
	t.setLabel(p, buf[:pl+cl])
	t.freeBlock(ci, cls)
}

// ------------------------------------------------------------ operations

// Insert adds key with value, or replaces the value if key is present.
func (t *RadixTree) Insert(key []byte, value int64) bool {
	nodes := t.nodes
	ni := uint32(0)
	pos := 0
	kl := len(key)
	d := 0
	kp := unsafe.Pointer(unsafe.SliceData(key))
	for {
		t.path[d] = ni
		n := &nodes[ni]
		if pos == kl {
			if n.flags&flagVal != 0 {
				n.value = value
				return false
			}
			n.flags |= flagVal
			n.value = value
			break
		}
		b := key[pos]
		idx, ok := t.child(n, b)
		if !ok {
			at := t.insertPos(n, b)
			slot := t.addChild(ni, at, b)
			lf := &t.nodes[slot]
			*lf = node{value: value, count: 1, flags: flagVal}
			t.setLabel(lf, key[pos:])
			break
		}
		ci := n.kids + idx
		c := &nodes[ci]
		ll := int(c.llen)
		lim := kl - pos
		if ll < lim {
			lim = ll
		}
		m := 1
		if lim > 1 {
			m += commonPrefix(unsafe.Add(t.labelPtr(c), 1), unsafe.Add(kp, pos+1), lim-1)
		}
		if m == ll {
			pos += ll
			ni = ci
			d++
			continue
		}
		t.split(ci, m, key[pos:], value)
		break
	}
	nodes = t.nodes
	for i := 0; i <= d; i++ {
		nodes[t.path[i]].count++
	}
	t.size++
	return true
}

// Get returns the value stored for key.
func (t *RadixTree) Get(key []byte) (int64, bool) {
	nodes := t.nodes
	n := &nodes[0]
	pos := 0
	kl := len(key)
	kp := unsafe.Pointer(unsafe.SliceData(key))
	for pos < kl {
		idx, ok := t.child(n, key[pos])
		if !ok {
			return 0, false
		}
		n = &nodes[n.kids+idx]
		ll := int(n.llen)
		if kl-pos < ll {
			return 0, false
		}
		if ll > 1 && !eqBytes(unsafe.Add(t.labelPtr(n), 1), unsafe.Add(kp, pos+1), ll-1) {
			return 0, false
		}
		pos += ll
	}
	if n.flags&flagVal != 0 {
		return n.value, true
	}
	return 0, false
}

// Remove deletes key if present.
func (t *RadixTree) Remove(key []byte) bool {
	nodes := t.nodes
	ni := uint32(0)
	pos := 0
	kl := len(key)
	d := 0
	kp := unsafe.Pointer(unsafe.SliceData(key))
	t.path[0] = 0
	for pos < kl {
		n := &nodes[ni]
		idx, ok := t.child(n, key[pos])
		if !ok {
			return false
		}
		ci := n.kids + idx
		c := &nodes[ci]
		ll := int(c.llen)
		if kl-pos < ll {
			return false
		}
		if ll > 1 && !eqBytes(unsafe.Add(t.labelPtr(c), 1), unsafe.Add(kp, pos+1), ll-1) {
			return false
		}
		pos += ll
		ni = ci
		d++
		t.path[d] = ni
	}
	x := &nodes[ni]
	if x.flags&flagVal == 0 {
		return false
	}
	x.flags &^= flagVal
	x.value = 0
	for i := 0; i <= d; i++ {
		nodes[t.path[i]].count--
	}
	t.size--
	if d == 0 {
		return true
	}
	switch x.nkids {
	case 0:
		pi := t.path[d-1]
		p := &nodes[pi]
		b := key[pos-int(x.llen)]
		at := int(ni - p.kids)
		t.freeLabel(x)
		t.removeChild(pi, at, b)
		if d > 1 {
			p = &t.nodes[pi]
			if p.flags&flagVal == 0 && p.nkids == 1 {
				t.merge(pi)
			}
		}
	case 1:
		t.merge(ni)
	}
	return true
}

// LongestPrefix finds the longest stored key that is a prefix of key.
func (t *RadixTree) LongestPrefix(key []byte) (int, int64, bool) {
	nodes := t.nodes
	n := &nodes[0]
	pos := 0
	kl := len(key)
	kp := unsafe.Pointer(unsafe.SliceData(key))
	best := -1
	var bv int64
	for {
		if n.flags&flagVal != 0 {
			best = pos
			bv = n.value
		}
		if pos >= kl {
			break
		}
		idx, ok := t.child(n, key[pos])
		if !ok {
			break
		}
		c := &nodes[n.kids+idx]
		ll := int(c.llen)
		if kl-pos < ll {
			break
		}
		if ll > 1 && !eqBytes(unsafe.Add(t.labelPtr(c), 1), unsafe.Add(kp, pos+1), ll-1) {
			break
		}
		pos += ll
		n = c
	}
	if best < 0 {
		return 0, 0, false
	}
	return best, bv, true
}

// findPrefix returns the node at or below the end of prefix whose subtree
// holds exactly the keys starting with prefix.
func (t *RadixTree) findPrefix(prefix []byte) (uint32, bool) {
	nodes := t.nodes
	ni := uint32(0)
	pos := 0
	kl := len(prefix)
	kp := unsafe.Pointer(unsafe.SliceData(prefix))
	for pos < kl {
		n := &nodes[ni]
		idx, ok := t.child(n, prefix[pos])
		if !ok {
			return 0, false
		}
		ci := n.kids + idx
		c := &nodes[ci]
		ll := int(c.llen)
		rem := kl - pos
		if rem < ll {
			if rem > 1 && !eqBytes(unsafe.Add(t.labelPtr(c), 1), unsafe.Add(kp, pos+1), rem-1) {
				return 0, false
			}
			return ci, true
		}
		if ll > 1 && !eqBytes(unsafe.Add(t.labelPtr(c), 1), unsafe.Add(kp, pos+1), ll-1) {
			return 0, false
		}
		pos += ll
		ni = ci
	}
	return ni, true
}

// PrefixCount returns the number of keys starting with prefix.
func (t *RadixTree) PrefixCount(prefix []byte) int {
	ni, ok := t.findPrefix(prefix)
	if !ok {
		return 0
	}
	return int(t.nodes[ni].count)
}

// PrefixValues writes the values of keys starting with prefix, in key
// order, up to len(outValues).
func (t *RadixTree) PrefixValues(prefix []byte, outValues []int64) int {
	limit := len(outValues)
	if limit == 0 {
		return 0
	}
	ni, ok := t.findPrefix(prefix)
	if !ok {
		return 0
	}
	nodes := t.nodes
	n := &nodes[ni]
	w := 0
	if n.flags&flagVal != 0 {
		outValues[0] = n.value
		w = 1
		if w == limit {
			return w
		}
	}
	if n.nkids == 0 {
		return w
	}
	stk := &t.stk
	stk[0] = frame{n.kids, n.kids + uint32(n.nkids)}
	sp := 1
	for sp > 0 {
		e := &stk[sp-1]
		i := e.cur
		e.cur++
		c := &nodes[i]
		if c.flags&flagVal != 0 {
			outValues[w] = c.value
			w++
			if w == limit {
				return w
			}
		}
		last := e.cur == e.end
		if c.nkids != 0 {
			f := frame{c.kids, c.kids + uint32(c.nkids)}
			if last {
				*e = f
			} else {
				stk[sp] = f
				sp++
			}
		} else if last {
			sp--
			for sp > 0 && stk[sp-1].cur == stk[sp-1].end {
				sp--
			}
		}
	}
	return w
}

// Len returns the number of keys.
func (t *RadixTree) Len() int { return t.size }

// NodeCount returns the number of nodes, root included.
func (t *RadixTree) NodeCount() int { return t.countNodes(0) }

func (t *RadixTree) countNodes(i uint32) int {
	n := &t.nodes[i]
	s := 1
	for j := uint32(0); j < uint32(n.nkids); j++ {
		s += t.countNodes(n.kids + j)
	}
	return s
}

// Height returns the largest number of edges from the root to a node.
func (t *RadixTree) Height() int { return t.height(0) }

func (t *RadixTree) height(i uint32) int {
	n := &t.nodes[i]
	h := 0
	for j := uint32(0); j < uint32(n.nkids); j++ {
		if x := t.height(n.kids+j) + 1; x > h {
			h = x
		}
	}
	return h
}
