package radix

import (
	"math/bits"
	"unsafe"
)

const (
	nullNode uint32 = 0

	tagLeaf uint32 = 1
	tagN4   uint32 = 2
	tagN16  uint32 = 3
	tagN48  uint32 = 4
	tagN256 uint32 = 5

	tagShift = 29
	idxMask  = (1 << tagShift) - 1
	freeEnd  = ^uint32(0)

	leafInline = 7
	n4Inline   = 29
	n16Inline  = 32
	n48Inline  = 8
	n256Inline = 16

	swarLo64 = uint64(0x0101010101010101)
	swarHi64 = uint64(0x8080808080808080)
	swarLo32 = uint64(0x01010101)
	swarHi32 = uint64(0x80808080)
)

// Compile-time struct size assertions guaranteeing exact shift strides in unsafe.Add.
const (
	_ = uint(16 - unsafe.Sizeof(leafNode{}))
	_ = uint(unsafe.Sizeof(leafNode{}) - 16)
	_ = uint(64 - unsafe.Sizeof(node4{}))
	_ = uint(unsafe.Sizeof(node4{}) - 64)
	_ = uint(128 - unsafe.Sizeof(node16{}))
	_ = uint(unsafe.Sizeof(node16{}) - 128)
)

// Node structs: all pointer-free (noscan by Go GC) and cache-line friendly on
// 128-byte cache lines (Apple M3):
//   leafNode: 16 bytes (8 per cache line)
//   node4:    64 bytes (2 per cache line)
//   node16:  128 bytes (1 per cache line)
//   node48:  512 bytes (4 cache lines)
//   node256: 1088 bytes
//
// In every node struct, label[0] is 8-byte aligned so storing a uint32 external
// slab index in label[0..3] when labelLen > inlineCap is aligned and fast.

type leafNode struct {
	val      int64
	label    [leafInline]byte
	labelLen uint8
}

type node4 struct {
	val      int64
	subCount uint32
	keys     [4]byte
	children [4]uint32
	label    [n4Inline]byte
	labelLen uint8
	count    uint8
	hasVal   uint8
}

type node16 struct {
	val      int64
	subCount uint32
	labelLen uint8
	count    uint8
	hasVal   uint8
	_        uint8
	keys     [16]byte
	children [16]uint32
	label    [n16Inline]byte
}

type node48 struct {
	val        int64
	subCount   uint32
	labelLen   uint8
	count      uint8
	hasVal     uint8
	_          uint8
	label      [n48Inline]byte
	slotMask   uint64
	bitmap     [4]uint64
	children   [48]uint32
	childIndex [256]uint8
}

type node256 struct {
	val      int64
	subCount uint32
	count    uint16
	labelLen uint8
	hasVal   uint8
	label    [n256Inline]byte
	bitmap   [4]uint64
	children [256]uint32
}

type walkFrame struct {
	node uint32
	idx  uint16
	_    uint16
}

// RadixTree is an in-memory path-compressed radix tree over byte strings.
type RadixTree struct {
	root uint32

	leaves []leafNode
	n4     []node4
	n16    []node16
	n48    []node48
	n256   []node256

	freeLeaf uint32
	freeN4   uint32
	freeN16  uint32
	freeN48  uint32
	freeN256 uint32

	// Size-class slab pools for external labels (> inlineCap, up to 255 bytes).
	slab16   [][16]byte
	slab32   [][32]byte
	slab64   [][64]byte
	slab128  [][128]byte
	slab256  [][256]byte
	freeSlab [5]uint32

	// Reusable scratch buffers (zero stack-zeroing per operation; max height is 255).
	walkStack [256]walkFrame
	pathNodes [256]uint32
	pathEdges [256]byte
	mergeBuf  [256]byte
}

// New creates an empty RadixTree.
func New() *RadixTree {
	t := &RadixTree{
		freeLeaf: freeEnd,
		freeN4:   freeEnd,
		freeN16:  freeEnd,
		freeN48:  freeEnd,
		freeN256: freeEnd,
		freeSlab: [5]uint32{freeEnd, freeEnd, freeEnd, freeEnd, freeEnd},
	}
	t.n4 = make([]node4, 1, 16)
	t.root = (tagN4 << tagShift) | 0
	return t
}

// ------------------------------------------------------------------ pool helpers

func growPool[T any](s []T, minCap int) []T {
	newCap := cap(s) * 2
	if newCap < minCap {
		newCap = minCap
	}
	ns := make([]T, len(s), newCap)
	copy(ns, s)
	return ns
}

func (t *RadixTree) allocLeaf() uint32 {
	if t.freeLeaf != freeEnd {
		idx := t.freeLeaf
		t.freeLeaf = *(*uint32)(unsafe.Pointer(&t.leaves[idx]))
		return (tagLeaf << tagShift) | idx
	}
	if len(t.leaves) == cap(t.leaves) {
		t.leaves = growPool(t.leaves, 16)
	}
	idx := uint32(len(t.leaves))
	t.leaves = t.leaves[:idx+1]
	return (tagLeaf << tagShift) | idx
}

func (t *RadixTree) freeLeafNode(h uint32) {
	idx := h & idxMask
	lf := &t.leaves[idx]
	if lf.labelLen > leafInline {
		t.freeExtLabel(getExtIdx(&lf.label[0]), int(lf.labelLen))
	}
	*(*uint32)(unsafe.Pointer(lf)) = t.freeLeaf
	t.freeLeaf = idx
}

func (t *RadixTree) allocN4() uint32 {
	if t.freeN4 != freeEnd {
		idx := t.freeN4
		t.freeN4 = *(*uint32)(unsafe.Pointer(&t.n4[idx]))
		return (tagN4 << tagShift) | idx
	}
	if len(t.n4) == cap(t.n4) {
		t.n4 = growPool(t.n4, 16)
	}
	idx := uint32(len(t.n4))
	t.n4 = t.n4[:idx+1]
	return (tagN4 << tagShift) | idx
}

func (t *RadixTree) freeN4Slot(idx uint32) {
	*(*uint32)(unsafe.Pointer(&t.n4[idx])) = t.freeN4
	t.freeN4 = idx
}

func (t *RadixTree) allocN16() uint32 {
	if t.freeN16 != freeEnd {
		idx := t.freeN16
		t.freeN16 = *(*uint32)(unsafe.Pointer(&t.n16[idx]))
		return (tagN16 << tagShift) | idx
	}
	if len(t.n16) == cap(t.n16) {
		t.n16 = growPool(t.n16, 16)
	}
	idx := uint32(len(t.n16))
	t.n16 = t.n16[:idx+1]
	return (tagN16 << tagShift) | idx
}

func (t *RadixTree) freeN16Slot(idx uint32) {
	*(*uint32)(unsafe.Pointer(&t.n16[idx])) = t.freeN16
	t.freeN16 = idx
}

func (t *RadixTree) allocN48() uint32 {
	if t.freeN48 != freeEnd {
		idx := t.freeN48
		t.freeN48 = *(*uint32)(unsafe.Pointer(&t.n48[idx]))
		t.n48[idx] = node48{}
		return (tagN48 << tagShift) | idx
	}
	if len(t.n48) == cap(t.n48) {
		t.n48 = growPool(t.n48, 4)
	}
	idx := uint32(len(t.n48))
	t.n48 = t.n48[:idx+1]
	return (tagN48 << tagShift) | idx
}

func (t *RadixTree) freeN48Slot(idx uint32) {
	*(*uint32)(unsafe.Pointer(&t.n48[idx])) = t.freeN48
	t.freeN48 = idx
}

func (t *RadixTree) allocN256() uint32 {
	if t.freeN256 != freeEnd {
		idx := t.freeN256
		t.freeN256 = *(*uint32)(unsafe.Pointer(&t.n256[idx]))
		t.n256[idx] = node256{}
		return (tagN256 << tagShift) | idx
	}
	if len(t.n256) == cap(t.n256) {
		t.n256 = growPool(t.n256, 4)
	}
	idx := uint32(len(t.n256))
	t.n256 = t.n256[:idx+1]
	return (tagN256 << tagShift) | idx
}

func (t *RadixTree) freeN256Slot(idx uint32) {
	*(*uint32)(unsafe.Pointer(&t.n256[idx])) = t.freeN256
	t.freeN256 = idx
}

// ------------------------------------------------------------------ external label slabs

func getExtIdx(p *byte) uint32 {
	return *(*uint32)(unsafe.Pointer(p))
}

func setExtIdx(p *byte, idx uint32) {
	*(*uint32)(unsafe.Pointer(p)) = idx
}

func (t *RadixTree) allocExtLabel(src []byte) uint32 {
	n := len(src)
	switch {
	case n <= 16:
		var idx uint32
		if t.freeSlab[0] != freeEnd {
			idx = t.freeSlab[0]
			t.freeSlab[0] = *(*uint32)(unsafe.Pointer(&t.slab16[idx][0]))
		} else {
			if len(t.slab16) == cap(t.slab16) {
				t.slab16 = growPool(t.slab16, 16)
			}
			idx = uint32(len(t.slab16))
			t.slab16 = t.slab16[:idx+1]
		}
		copy(t.slab16[idx][:n], src)
		return idx
	case n <= 32:
		var idx uint32
		if t.freeSlab[1] != freeEnd {
			idx = t.freeSlab[1]
			t.freeSlab[1] = *(*uint32)(unsafe.Pointer(&t.slab32[idx][0]))
		} else {
			if len(t.slab32) == cap(t.slab32) {
				t.slab32 = growPool(t.slab32, 16)
			}
			idx = uint32(len(t.slab32))
			t.slab32 = t.slab32[:idx+1]
		}
		copy(t.slab32[idx][:n], src)
		return idx
	case n <= 64:
		var idx uint32
		if t.freeSlab[2] != freeEnd {
			idx = t.freeSlab[2]
			t.freeSlab[2] = *(*uint32)(unsafe.Pointer(&t.slab64[idx][0]))
		} else {
			if len(t.slab64) == cap(t.slab64) {
				t.slab64 = growPool(t.slab64, 8)
			}
			idx = uint32(len(t.slab64))
			t.slab64 = t.slab64[:idx+1]
		}
		copy(t.slab64[idx][:n], src)
		return idx
	case n <= 128:
		var idx uint32
		if t.freeSlab[3] != freeEnd {
			idx = t.freeSlab[3]
			t.freeSlab[3] = *(*uint32)(unsafe.Pointer(&t.slab128[idx][0]))
		} else {
			if len(t.slab128) == cap(t.slab128) {
				t.slab128 = growPool(t.slab128, 4)
			}
			idx = uint32(len(t.slab128))
			t.slab128 = t.slab128[:idx+1]
		}
		copy(t.slab128[idx][:n], src)
		return idx
	default:
		var idx uint32
		if t.freeSlab[4] != freeEnd {
			idx = t.freeSlab[4]
			t.freeSlab[4] = *(*uint32)(unsafe.Pointer(&t.slab256[idx][0]))
		} else {
			if len(t.slab256) == cap(t.slab256) {
				t.slab256 = growPool(t.slab256, 4)
			}
			idx = uint32(len(t.slab256))
			t.slab256 = t.slab256[:idx+1]
		}
		copy(t.slab256[idx][:n], src)
		return idx
	}
}

func (t *RadixTree) freeExtLabel(idx uint32, n int) {
	switch {
	case n <= 16:
		*(*uint32)(unsafe.Pointer(&t.slab16[idx][0])) = t.freeSlab[0]
		t.freeSlab[0] = idx
	case n <= 32:
		*(*uint32)(unsafe.Pointer(&t.slab32[idx][0])) = t.freeSlab[1]
		t.freeSlab[1] = idx
	case n <= 64:
		*(*uint32)(unsafe.Pointer(&t.slab64[idx][0])) = t.freeSlab[2]
		t.freeSlab[2] = idx
	case n <= 128:
		*(*uint32)(unsafe.Pointer(&t.slab128[idx][0])) = t.freeSlab[3]
		t.freeSlab[3] = idx
	default:
		*(*uint32)(unsafe.Pointer(&t.slab256[idx][0])) = t.freeSlab[4]
		t.freeSlab[4] = idx
	}
}

func (t *RadixTree) getExtLabel(idx uint32, n int) []byte {
	switch {
	case n <= 16:
		return t.slab16[idx][:n]
	case n <= 32:
		return t.slab32[idx][:n]
	case n <= 64:
		return t.slab64[idx][:n]
	case n <= 128:
		return t.slab128[idx][:n]
	default:
		return t.slab256[idx][:n]
	}
}

// getLabel returns a temporary view of h's label. Must not be held across pool mutations.
func (t *RadixTree) getLabel(h uint32) []byte {
	idx := h & idxMask
	switch h >> tagShift {
	case tagLeaf:
		n := &t.leaves[idx]
		l := int(n.labelLen)
		if l <= leafInline {
			return n.label[:l]
		}
		return t.getExtLabel(getExtIdx(&n.label[0]), l)
	case tagN4:
		n := &t.n4[idx]
		l := int(n.labelLen)
		if l <= n4Inline {
			return n.label[:l]
		}
		return t.getExtLabel(getExtIdx(&n.label[0]), l)
	case tagN16:
		n := &t.n16[idx]
		l := int(n.labelLen)
		if l <= n16Inline {
			return n.label[:l]
		}
		return t.getExtLabel(getExtIdx(&n.label[0]), l)
	case tagN48:
		n := &t.n48[idx]
		l := int(n.labelLen)
		if l <= n48Inline {
			return n.label[:l]
		}
		return t.getExtLabel(getExtIdx(&n.label[0]), l)
	default:
		n := &t.n256[idx]
		l := int(n.labelLen)
		if l <= n256Inline {
			return n.label[:l]
		}
		return t.getExtLabel(getExtIdx(&n.label[0]), l)
	}
}

// setFreshLabel sets the label of a newly allocated node (does not free any previous label).
func (t *RadixTree) setFreshLabel(h uint32, src []byte) {
	idx := h & idxMask
	l := len(src)
	switch h >> tagShift {
	case tagLeaf:
		n := &t.leaves[idx]
		n.labelLen = uint8(l)
		if l <= leafInline {
			copy(n.label[:l], src)
		} else {
			ext := t.allocExtLabel(src)
			setExtIdx(&t.leaves[idx].label[0], ext)
		}
	case tagN4:
		n := &t.n4[idx]
		n.labelLen = uint8(l)
		if l <= n4Inline {
			copy(n.label[:l], src)
		} else {
			ext := t.allocExtLabel(src)
			setExtIdx(&t.n4[idx].label[0], ext)
		}
	case tagN16:
		n := &t.n16[idx]
		n.labelLen = uint8(l)
		if l <= n16Inline {
			copy(n.label[:l], src)
		} else {
			ext := t.allocExtLabel(src)
			setExtIdx(&t.n16[idx].label[0], ext)
		}
	case tagN48:
		n := &t.n48[idx]
		n.labelLen = uint8(l)
		if l <= n48Inline {
			copy(n.label[:l], src)
		} else {
			ext := t.allocExtLabel(src)
			setExtIdx(&t.n48[idx].label[0], ext)
		}
	default:
		n := &t.n256[idx]
		n.labelLen = uint8(l)
		if l <= n256Inline {
			copy(n.label[:l], src)
		} else {
			ext := t.allocExtLabel(src)
			setExtIdx(&t.n256[idx].label[0], ext)
		}
	}
}

// replaceLabel replaces h's existing label with src (src must not alias h's old label),
// freeing any old external label slab.
func (t *RadixTree) replaceLabel(h uint32, src []byte) {
	idx := h & idxMask
	switch h >> tagShift {
	case tagLeaf:
		n := &t.leaves[idx]
		if n.labelLen > leafInline {
			t.freeExtLabel(getExtIdx(&n.label[0]), int(n.labelLen))
		}
	case tagN4:
		n := &t.n4[idx]
		if n.labelLen > n4Inline {
			t.freeExtLabel(getExtIdx(&n.label[0]), int(n.labelLen))
		}
	case tagN16:
		n := &t.n16[idx]
		if n.labelLen > n16Inline {
			t.freeExtLabel(getExtIdx(&n.label[0]), int(n.labelLen))
		}
	case tagN48:
		n := &t.n48[idx]
		if n.labelLen > n48Inline {
			t.freeExtLabel(getExtIdx(&n.label[0]), int(n.labelLen))
		}
	default:
		n := &t.n256[idx]
		if n.labelLen > n256Inline {
			t.freeExtLabel(getExtIdx(&n.label[0]), int(n.labelLen))
		}
	}
	t.setFreshLabel(h, src)
}

// ------------------------------------------------------------------ node helpers

func (t *RadixTree) subCount(h uint32) uint32 {
	idx := h & idxMask
	switch h >> tagShift {
	case tagLeaf:
		return 1
	case tagN4:
		return t.n4[idx].subCount
	case tagN16:
		return t.n16[idx].subCount
	case tagN48:
		return t.n48[idx].subCount
	default:
		return t.n256[idx].subCount
	}
}

func (t *RadixTree) incSubCount(h uint32) {
	idx := h & idxMask
	switch h >> tagShift {
	case tagN4:
		t.n4[idx].subCount++
	case tagN16:
		t.n16[idx].subCount++
	case tagN48:
		t.n48[idx].subCount++
	case tagN256:
		t.n256[idx].subCount++
	}
}

func (t *RadixTree) decSubCount(h uint32) {
	idx := h & idxMask
	switch h >> tagShift {
	case tagN4:
		t.n4[idx].subCount--
	case tagN16:
		t.n16[idx].subCount--
	case tagN48:
		t.n48[idx].subCount--
	case tagN256:
		t.n256[idx].subCount--
	}
}

func (t *RadixTree) findChildLarge(cur uint32, b byte) uint32 {
	idx := cur & idxMask
	if cur>>tagShift == tagN48 {
		n := &t.n48[idx]
		slot := n.childIndex[b]
		if slot == 0 {
			return nullNode
		}
		return n.children[slot-1]
	}
	return t.n256[idx].children[b]
}

// matchRest compares a[1:] against b[1:], assuming len(a) == len(b) >= 2.
func matchRest(a, b []byte) bool {
	n := len(b)
	_ = a[n-1]
	if n <= 8 {
		for i := 1; i < n; i++ {
			if a[i] != b[i] {
				return false
			}
		}
		return true
	}
	return string(a[1:]) == string(b[1:])
}

func (t *RadixTree) matchExt(extIdx uint32, lLen int, key []byte, pos int, cmpLen int) bool {
	lbl := t.getExtLabel(extIdx, lLen)
	return matchRest(key[pos:pos+cmpLen], lbl[:cmpLen])
}

func nextBit(bm *[4]uint64, start int) int {
	if start >= 256 {
		return 256
	}
	wIdx := start >> 6
	w := bm[wIdx] & (^uint64(0) << uint(start&63))
	if w != 0 {
		return (wIdx << 6) + bits.TrailingZeros64(w)
	}
	for wIdx++; wIdx < 4; wIdx++ {
		if bm[wIdx] != 0 {
			return (wIdx << 6) + bits.TrailingZeros64(bm[wIdx])
		}
	}
	return 256
}

// setChild replaces an existing child for byte b in parent h.
func (t *RadixTree) setChild(h uint32, b byte, child uint32) {
	idx := h & idxMask
	switch h >> tagShift {
	case tagN4:
		n := &t.n4[idx]
		for i := uint8(0); i < n.count; i++ {
			if n.keys[i] == b {
				n.children[i] = child
				return
			}
		}
	case tagN16:
		n := &t.n16[idx]
		pat := uint64(b) * swarLo64
		w0 := *(*uint64)(unsafe.Pointer(&n.keys[0]))
		w1 := *(*uint64)(unsafe.Pointer(&n.keys[8]))
		x0 := w0 ^ pat
		x1 := w1 ^ pat
		m0 := (x0 - swarLo64) & ^x0 & swarHi64
		m1 := (x1 - swarLo64) & ^x1 & swarHi64
		i0 := bits.TrailingZeros64(m0) >> 3
		i1 := 8 + (bits.TrailingZeros64(m1) >> 3)
		ci := i1
		if m0 != 0 {
			ci = i0
		}
		n.children[ci&15] = child
	case tagN48:
		n := &t.n48[idx]
		n.children[n.childIndex[b]-1] = child
	case tagN256:
		t.n256[idx].children[b] = child
	}
}

// addChild adds a new (b, child) entry to internal node h, upgrading h if full.
// Returns the (possibly new) handle for h.
func (t *RadixTree) addChild(h uint32, b byte, child uint32) uint32 {
	idx := h & idxMask
	switch h >> tagShift {
	case tagN4:
		n := &t.n4[idx]
		cnt := int(n.count)
		if cnt < 4 {
			i := cnt
			for i > 0 && n.keys[i-1] > b {
				n.keys[i] = n.keys[i-1]
				n.children[i] = n.children[i-1]
				i--
			}
			n.keys[i] = b
			n.children[i] = child
			n.count++
			return h
		}
		// Upgrade node4 -> node16.
		nh := t.allocN16()
		n = &t.n4[idx]
		nn := &t.n16[nh&idxMask]
		nn.val = n.val
		nn.subCount = n.subCount
		nn.hasVal = n.hasVal
		nn.labelLen = n.labelLen
		if n.labelLen <= n4Inline {
			copy(nn.label[:n.labelLen], n.label[:n.labelLen])
		} else {
			// External in n4 (>29). Fits inline in n16 if <= 32, else steal handle!
			ext := getExtIdx(&n.label[0])
			if n.labelLen <= n16Inline {
				copy(nn.label[:n.labelLen], t.getExtLabel(ext, int(n.labelLen)))
				t.freeExtLabel(ext, int(n.labelLen))
			} else {
				setExtIdx(&nn.label[0], ext)
			}
		}
		// Insert sorted into nn.
		i := 4
		for j := 0; j < 4; j++ {
			if n.keys[j] > b {
				i = j
				break
			}
		}
		for j := 0; j < i; j++ {
			nn.keys[j] = n.keys[j]
			nn.children[j] = n.children[j]
		}
		nn.keys[i] = b
		nn.children[i] = child
		for j := i; j < 4; j++ {
			nn.keys[j+1] = n.keys[j]
			nn.children[j+1] = n.children[j]
		}
		nn.count = 5
		t.freeN4Slot(idx)
		return nh

	case tagN16:
		n := &t.n16[idx]
		cnt := int(n.count)
		if cnt < 16 {
			i := cnt
			for i > 0 && n.keys[i-1] > b {
				n.keys[i] = n.keys[i-1]
				n.children[i] = n.children[i-1]
				i--
			}
			n.keys[i] = b
			n.children[i] = child
			n.count++
			return h
		}
		// Upgrade node16 -> node48.
		nh := t.allocN48()
		n = &t.n16[idx]
		nn := &t.n48[nh&idxMask]
		nn.val = n.val
		nn.subCount = n.subCount
		nn.hasVal = n.hasVal
		nn.labelLen = n.labelLen
		l := int(n.labelLen)
		if l <= n48Inline {
			copy(nn.label[:l], n.label[:l])
		} else if l <= n16Inline {
			// Was inline in n16, needs external in n48.
			copy(t.mergeBuf[:l], n.label[:l])
			ext := t.allocExtLabel(t.mergeBuf[:l])
			nn = &t.n48[nh&idxMask]
			setExtIdx(&nn.label[0], ext)
		} else {
			// External in both: steal handle.
			setExtIdx(&nn.label[0], getExtIdx(&n.label[0]))
		}
		n = &t.n16[idx]
		for j := 0; j < 16; j++ {
			k := n.keys[j]
			nn.children[j] = n.children[j]
			nn.childIndex[k] = uint8(j + 1)
			nn.bitmap[k>>6] |= uint64(1) << uint(k&63)
		}
		nn.children[16] = child
		nn.childIndex[b] = 17
		nn.bitmap[b>>6] |= uint64(1) << uint(b&63)
		nn.slotMask = (uint64(1) << 17) - 1
		nn.count = 17
		t.freeN16Slot(idx)
		return nh

	case tagN48:
		n := &t.n48[idx]
		if n.count < 48 {
			slot := bits.TrailingZeros64(^n.slotMask)
			n.slotMask |= uint64(1) << uint(slot)
			n.children[slot] = child
			n.childIndex[b] = uint8(slot + 1)
			n.bitmap[b>>6] |= uint64(1) << uint(b&63)
			n.count++
			return h
		}
		// Upgrade node48 -> node256.
		nh := t.allocN256()
		n = &t.n48[idx]
		nn := &t.n256[nh&idxMask]
		nn.val = n.val
		nn.subCount = n.subCount
		nn.hasVal = n.hasVal
		nn.labelLen = n.labelLen
		l := int(n.labelLen)
		if l <= n48Inline {
			copy(nn.label[:l], n.label[:l])
		} else if l <= n256Inline {
			// External in n48, fits inline in n256.
			ext := getExtIdx(&n.label[0])
			copy(nn.label[:l], t.getExtLabel(ext, l))
			t.freeExtLabel(ext, l)
		} else {
			// External in both: steal handle.
			setExtIdx(&nn.label[0], getExtIdx(&n.label[0]))
		}
		nn.bitmap = n.bitmap
		for kb := nextBit(&n.bitmap, 0); kb < 256; kb = nextBit(&n.bitmap, kb+1) {
			nn.children[kb] = n.children[n.childIndex[kb]-1]
		}
		nn.children[b] = child
		nn.bitmap[b>>6] |= uint64(1) << uint(b&63)
		nn.count = 49
		t.freeN48Slot(idx)
		return nh

	default:
		n := &t.n256[idx]
		n.children[b] = child
		n.bitmap[b>>6] |= uint64(1) << uint(b&63)
		n.count++
		return h
	}
}

// removeChild deletes byte b from internal node h, shrinking h with hysteresis.
// Returns the (possibly new) handle for h.
func (t *RadixTree) removeChild(h uint32, b byte) uint32 {
	idx := h & idxMask
	switch h >> tagShift {
	case tagN4:
		n := &t.n4[idx]
		cnt := int(n.count)
		i := 0
		for i < cnt && n.keys[i] != b {
			i++
		}
		for ; i < cnt-1; i++ {
			n.keys[i] = n.keys[i+1]
			n.children[i] = n.children[i+1]
		}
		n.count--
		return h

	case tagN16:
		n := &t.n16[idx]
		cnt := int(n.count)
		i := 0
		for i < cnt && n.keys[i] != b {
			i++
		}
		for ; i < cnt-1; i++ {
			n.keys[i] = n.keys[i+1]
			n.children[i] = n.children[i+1]
		}
		n.count--
		if n.count > 3 {
			return h
		}
		// Shrink node16 -> node4 (count == 3).
		nh := t.allocN4()
		n = &t.n16[idx]
		nn := &t.n4[nh&idxMask]
		nn.val = n.val
		nn.subCount = n.subCount
		nn.hasVal = n.hasVal
		nn.labelLen = n.labelLen
		nn.count = n.count
		for j := uint8(0); j < n.count; j++ {
			nn.keys[j] = n.keys[j]
			nn.children[j] = n.children[j]
		}
		l := int(n.labelLen)
		if l <= n4Inline {
			copy(nn.label[:l], n.label[:l])
		} else if l <= n16Inline {
			copy(t.mergeBuf[:l], n.label[:l])
			ext := t.allocExtLabel(t.mergeBuf[:l])
			setExtIdx(&t.n4[nh&idxMask].label[0], ext)
		} else {
			setExtIdx(&nn.label[0], getExtIdx(&n.label[0]))
		}
		t.freeN16Slot(idx)
		return nh

	case tagN48:
		n := &t.n48[idx]
		slot := n.childIndex[b] - 1
		n.childIndex[b] = 0
		n.slotMask &^= uint64(1) << uint(slot)
		n.bitmap[b>>6] &^= uint64(1) << uint(b&63)
		n.count--
		if n.count > 12 {
			return h
		}
		// Shrink node48 -> node16 (count == 12).
		nh := t.allocN16()
		n = &t.n48[idx]
		nn := &t.n16[nh&idxMask]
		nn.val = n.val
		nn.subCount = n.subCount
		nn.hasVal = n.hasVal
		nn.labelLen = n.labelLen
		nn.count = n.count
		l := int(n.labelLen)
		if l <= n48Inline {
			copy(nn.label[:l], n.label[:l])
		} else if l <= n16Inline {
			ext := getExtIdx(&n.label[0])
			copy(nn.label[:l], t.getExtLabel(ext, l))
			t.freeExtLabel(ext, l)
		} else {
			setExtIdx(&nn.label[0], getExtIdx(&n.label[0]))
		}
		j := 0
		for kb := nextBit(&n.bitmap, 0); kb < 256; kb = nextBit(&n.bitmap, kb+1) {
			nn.keys[j] = byte(kb)
			nn.children[j] = n.children[n.childIndex[kb]-1]
			j++
		}
		t.freeN48Slot(idx)
		return nh

	default:
		n := &t.n256[idx]
		n.children[b] = nullNode
		n.bitmap[b>>6] &^= uint64(1) << uint(b&63)
		n.count--
		if n.count > 36 {
			return h
		}
		// Shrink node256 -> node48 (count == 36).
		nh := t.allocN48()
		n = &t.n256[idx]
		nn := &t.n48[nh&idxMask]
		nn.val = n.val
		nn.subCount = n.subCount
		nn.hasVal = n.hasVal
		nn.labelLen = n.labelLen
		nn.count = uint8(n.count)
		l := int(n.labelLen)
		if l <= n48Inline {
			copy(nn.label[:l], n.label[:l])
		} else if l <= n256Inline {
			copy(t.mergeBuf[:l], n.label[:l])
			ext := t.allocExtLabel(t.mergeBuf[:l])
			nn = &t.n48[nh&idxMask]
			setExtIdx(&nn.label[0], ext)
		} else {
			setExtIdx(&nn.label[0], getExtIdx(&n.label[0]))
		}
		n = &t.n256[idx]
		nn.bitmap = n.bitmap
		slot := 0
		for kb := nextBit(&n.bitmap, 0); kb < 256; kb = nextBit(&n.bitmap, kb+1) {
			nn.children[slot] = n.children[kb]
			nn.childIndex[kb] = uint8(slot + 1)
			slot++
		}
		nn.slotMask = (uint64(1) << uint(slot)) - 1
		t.freeN256Slot(idx)
		return nh
	}
}

// ------------------------------------------------------------------ public API

// Len returns the number of keys stored in the tree.
func (t *RadixTree) Len() int {
	return int(t.subCount(t.root))
}

// Get looks up key in the tree.
func (t *RadixTree) Get(key []byte) (value int64, ok bool) {
	cur := t.root
	keyLen := len(key)
	if keyLen == 0 {
		idx := cur & idxMask
		switch cur >> tagShift {
		case tagN4:
			n := &t.n4[idx]
			return n.val, n.hasVal != 0
		case tagN16:
			n := &t.n16[idx]
			return n.val, n.hasVal != 0
		case tagN48:
			n := &t.n48[idx]
			return n.val, n.hasVal != 0
		default:
			n := &t.n256[idx]
			return n.val, n.hasVal != 0
		}
	}

	pos := 0
	for {
		b := key[pos]
		var child uint32
		tag := cur >> tagShift
		cIdx := cur & idxMask
		if tag == tagN16 {
			n := &t.n16[cIdx]
			pat := uint64(b) * swarLo64
			w0 := *(*uint64)(unsafe.Pointer(&n.keys[0]))
			w1 := *(*uint64)(unsafe.Pointer(&n.keys[8]))
			x0 := w0 ^ pat
			x1 := w1 ^ pat
			m0 := (x0 - swarLo64) & ^x0 & swarHi64
			m1 := (x1 - swarLo64) & ^x1 & swarHi64
			i0 := bits.TrailingZeros64(m0) >> 3
			i1 := 8 + (bits.TrailingZeros64(m1) >> 3)
			ci := i1
			if m0 != 0 {
				ci = i0
			}
			if ci < int(n.count) {
				child = n.children[ci&15]
			}
		} else if tag == tagN4 {
			n := &t.n4[cIdx]
			pat := uint64(b) * swarLo32
			w := uint64(*(*uint32)(unsafe.Pointer(&n.keys[0])))
			x := w ^ pat
			m := (x - swarLo32) & ^x & swarHi32
			if m != 0 {
				ci := bits.TrailingZeros64(m) >> 3
				if ci < int(n.count) {
					child = n.children[ci&3]
				}
			}
		} else {
			child = t.findChildLarge(cur, b)
		}

		if child == nullNode {
			return 0, false
		}

		chTag := child >> tagShift
		chIdx := child & idxMask
		if chTag == tagLeaf {
			lf := &t.leaves[chIdx]
			lLen := int(lf.labelLen)
			if pos+lLen != keyLen {
				return 0, false
			}
			if lLen == 1 {
				return lf.val, true
			}
			if lLen <= leafInline {
				if matchRest(key[pos:keyLen], lf.label[:lLen]) {
					return lf.val, true
				}
				return 0, false
			}
			if t.matchExt(getExtIdx(&lf.label[0]), lLen, key, pos, lLen) {
				return lf.val, true
			}
			return 0, false
		}

		var lLen int
		var val int64
		var hasVal uint8
		if chTag == tagN16 {
			n := &t.n16[chIdx]
			lLen = int(n.labelLen)
			if keyLen-pos < lLen {
				return 0, false
			}
			if lLen > 1 {
				if lLen <= n16Inline {
					if !matchRest(key[pos:pos+lLen], n.label[:lLen]) {
						return 0, false
					}
				} else if !t.matchExt(getExtIdx(&n.label[0]), lLen, key, pos, lLen) {
					return 0, false
				}
			}
			val = n.val
			hasVal = n.hasVal
		} else if chTag == tagN4 {
			n := &t.n4[chIdx]
			lLen = int(n.labelLen)
			if keyLen-pos < lLen {
				return 0, false
			}
			if lLen > 1 {
				if lLen <= n4Inline {
					if !matchRest(key[pos:pos+lLen], n.label[:lLen]) {
						return 0, false
					}
				} else if !t.matchExt(getExtIdx(&n.label[0]), lLen, key, pos, lLen) {
					return 0, false
				}
			}
			val = n.val
			hasVal = n.hasVal
		} else if chTag == tagN48 {
			n := &t.n48[chIdx]
			lLen = int(n.labelLen)
			if keyLen-pos < lLen {
				return 0, false
			}
			if lLen > 1 {
				if lLen <= n48Inline {
					if !matchRest(key[pos:pos+lLen], n.label[:lLen]) {
						return 0, false
					}
				} else if !t.matchExt(getExtIdx(&n.label[0]), lLen, key, pos, lLen) {
					return 0, false
				}
			}
			val = n.val
			hasVal = n.hasVal
		} else {
			n := &t.n256[chIdx]
			lLen = int(n.labelLen)
			if keyLen-pos < lLen {
				return 0, false
			}
			if lLen > 1 {
				if lLen <= n256Inline {
					if !matchRest(key[pos:pos+lLen], n.label[:lLen]) {
						return 0, false
					}
				} else if !t.matchExt(getExtIdx(&n.label[0]), lLen, key, pos, lLen) {
					return 0, false
				}
			}
			val = n.val
			hasVal = n.hasVal
		}

		pos += lLen
		if pos == keyLen {
			return val, hasVal != 0
		}
		cur = child
	}
}

// LongestPrefix finds the longest stored key that is a prefix of key.
func (t *RadixTree) LongestPrefix(key []byte) (length int, value int64, ok bool) {
	cur := t.root
	bestLen := 0
	var bestVal int64
	bestOk := false

	{
		idx := cur & idxMask
		switch cur >> tagShift {
		case tagN4:
			if t.n4[idx].hasVal != 0 {
				bestVal = t.n4[idx].val
				bestOk = true
			}
		case tagN16:
			if t.n16[idx].hasVal != 0 {
				bestVal = t.n16[idx].val
				bestOk = true
			}
		case tagN48:
			if t.n48[idx].hasVal != 0 {
				bestVal = t.n48[idx].val
				bestOk = true
			}
		default:
			if t.n256[idx].hasVal != 0 {
				bestVal = t.n256[idx].val
				bestOk = true
			}
		}
	}

	keyLen := len(key)
	pos := 0
	for pos < keyLen {
		b := key[pos]
		var child uint32
		tag := cur >> tagShift
		cIdx := cur & idxMask
		if tag == tagN16 {
			n := &t.n16[cIdx]
			pat := uint64(b) * swarLo64
			w0 := *(*uint64)(unsafe.Pointer(&n.keys[0]))
			w1 := *(*uint64)(unsafe.Pointer(&n.keys[8]))
			x0 := w0 ^ pat
			x1 := w1 ^ pat
			m0 := (x0 - swarLo64) & ^x0 & swarHi64
			m1 := (x1 - swarLo64) & ^x1 & swarHi64
			i0 := bits.TrailingZeros64(m0) >> 3
			i1 := 8 + (bits.TrailingZeros64(m1) >> 3)
			ci := i1
			if m0 != 0 {
				ci = i0
			}
			if ci < int(n.count) {
				child = n.children[ci&15]
			}
		} else if tag == tagN4 {
			n := &t.n4[cIdx]
			pat := uint64(b) * swarLo32
			w := uint64(*(*uint32)(unsafe.Pointer(&n.keys[0])))
			x := w ^ pat
			m := (x - swarLo32) & ^x & swarHi32
			if m != 0 {
				ci := bits.TrailingZeros64(m) >> 3
				if ci < int(n.count) {
					child = n.children[ci&3]
				}
			}
		} else {
			child = t.findChildLarge(cur, b)
		}

		if child == nullNode {
			break
		}

		chTag := child >> tagShift
		chIdx := child & idxMask
		if chTag == tagLeaf {
			lf := &t.leaves[chIdx]
			lLen := int(lf.labelLen)
			if keyLen-pos < lLen {
				break
			}
			if lLen == 1 {
				return pos + 1, lf.val, true
			}
			if lLen <= leafInline {
				if matchRest(key[pos:pos+lLen], lf.label[:lLen]) {
					return pos + lLen, lf.val, true
				}
				break
			}
			if t.matchExt(getExtIdx(&lf.label[0]), lLen, key, pos, lLen) {
				return pos + lLen, lf.val, true
			}
			break
		}

		var lLen int
		var val int64
		var hasVal uint8
		if chTag == tagN16 {
			n := &t.n16[chIdx]
			lLen = int(n.labelLen)
			if keyLen-pos < lLen {
				break
			}
			if lLen > 1 {
				if lLen <= n16Inline {
					if !matchRest(key[pos:pos+lLen], n.label[:lLen]) {
						break
					}
				} else if !t.matchExt(getExtIdx(&n.label[0]), lLen, key, pos, lLen) {
					break
				}
			}
			val = n.val
			hasVal = n.hasVal
		} else if chTag == tagN4 {
			n := &t.n4[chIdx]
			lLen = int(n.labelLen)
			if keyLen-pos < lLen {
				break
			}
			if lLen > 1 {
				if lLen <= n4Inline {
					if !matchRest(key[pos:pos+lLen], n.label[:lLen]) {
						break
					}
				} else if !t.matchExt(getExtIdx(&n.label[0]), lLen, key, pos, lLen) {
					break
				}
			}
			val = n.val
			hasVal = n.hasVal
		} else if chTag == tagN48 {
			n := &t.n48[chIdx]
			lLen = int(n.labelLen)
			if keyLen-pos < lLen {
				break
			}
			if lLen > 1 {
				if lLen <= n48Inline {
					if !matchRest(key[pos:pos+lLen], n.label[:lLen]) {
						break
					}
				} else if !t.matchExt(getExtIdx(&n.label[0]), lLen, key, pos, lLen) {
					break
				}
			}
			val = n.val
			hasVal = n.hasVal
		} else {
			n := &t.n256[chIdx]
			lLen = int(n.labelLen)
			if keyLen-pos < lLen {
				break
			}
			if lLen > 1 {
				if lLen <= n256Inline {
					if !matchRest(key[pos:pos+lLen], n.label[:lLen]) {
						break
					}
				} else if !t.matchExt(getExtIdx(&n.label[0]), lLen, key, pos, lLen) {
					break
				}
			}
			val = n.val
			hasVal = n.hasVal
		}

		pos += lLen
		if hasVal != 0 {
			bestLen = pos
			bestVal = val
			bestOk = true
		}
		cur = child
	}

	return bestLen, bestVal, bestOk
}

// PrefixCount returns the number of stored keys starting with prefix.
func (t *RadixTree) PrefixCount(prefix []byte) int {
	prefLen := len(prefix)
	cur := t.root
	if prefLen == 0 {
		return int(t.subCount(cur))
	}

	pos := 0
	for {
		b := prefix[pos]
		var child uint32
		tag := cur >> tagShift
		cIdx := cur & idxMask
		if tag == tagN16 {
			n := &t.n16[cIdx]
			pat := uint64(b) * swarLo64
			w0 := *(*uint64)(unsafe.Pointer(&n.keys[0]))
			w1 := *(*uint64)(unsafe.Pointer(&n.keys[8]))
			x0 := w0 ^ pat
			x1 := w1 ^ pat
			m0 := (x0 - swarLo64) & ^x0 & swarHi64
			m1 := (x1 - swarLo64) & ^x1 & swarHi64
			i0 := bits.TrailingZeros64(m0) >> 3
			i1 := 8 + (bits.TrailingZeros64(m1) >> 3)
			ci := i1
			if m0 != 0 {
				ci = i0
			}
			if ci < int(n.count) {
				child = n.children[ci&15]
			}
		} else if tag == tagN4 {
			n := &t.n4[cIdx]
			pat := uint64(b) * swarLo32
			w := uint64(*(*uint32)(unsafe.Pointer(&n.keys[0])))
			x := w ^ pat
			m := (x - swarLo32) & ^x & swarHi32
			if m != 0 {
				ci := bits.TrailingZeros64(m) >> 3
				if ci < int(n.count) {
					child = n.children[ci&3]
				}
			}
		} else {
			child = t.findChildLarge(cur, b)
		}

		if child == nullNode {
			return 0
		}

		rem := prefLen - pos
		chTag := child >> tagShift
		chIdx := child & idxMask
		if chTag == tagLeaf {
			lf := &t.leaves[chIdx]
			lLen := int(lf.labelLen)
			if rem > lLen {
				return 0
			}
			if rem == 1 {
				return 1
			}
			if lLen <= leafInline {
				if matchRest(prefix[pos:prefLen], lf.label[:rem]) {
					return 1
				}
				return 0
			}
			if t.matchExt(getExtIdx(&lf.label[0]), lLen, prefix, pos, rem) {
				return 1
			}
			return 0
		}

		var lLen int
		var sc uint32
		if chTag == tagN16 {
			n := &t.n16[chIdx]
			lLen = int(n.labelLen)
			sc = n.subCount
			cmpLen := lLen
			if rem < cmpLen {
				cmpLen = rem
			}
			if cmpLen > 1 {
				if lLen <= n16Inline {
					if !matchRest(prefix[pos:pos+cmpLen], n.label[:cmpLen]) {
						return 0
					}
				} else if !t.matchExt(getExtIdx(&n.label[0]), lLen, prefix, pos, cmpLen) {
					return 0
				}
			}
		} else if chTag == tagN4 {
			n := &t.n4[chIdx]
			lLen = int(n.labelLen)
			sc = n.subCount
			cmpLen := lLen
			if rem < cmpLen {
				cmpLen = rem
			}
			if cmpLen > 1 {
				if lLen <= n4Inline {
					if !matchRest(prefix[pos:pos+cmpLen], n.label[:cmpLen]) {
						return 0
					}
				} else if !t.matchExt(getExtIdx(&n.label[0]), lLen, prefix, pos, cmpLen) {
					return 0
				}
			}
		} else if chTag == tagN48 {
			n := &t.n48[chIdx]
			lLen = int(n.labelLen)
			sc = n.subCount
			cmpLen := lLen
			if rem < cmpLen {
				cmpLen = rem
			}
			if cmpLen > 1 {
				if lLen <= n48Inline {
					if !matchRest(prefix[pos:pos+cmpLen], n.label[:cmpLen]) {
						return 0
					}
				} else if !t.matchExt(getExtIdx(&n.label[0]), lLen, prefix, pos, cmpLen) {
					return 0
				}
			}
		} else {
			n := &t.n256[chIdx]
			lLen = int(n.labelLen)
			sc = n.subCount
			cmpLen := lLen
			if rem < cmpLen {
				cmpLen = rem
			}
			if cmpLen > 1 {
				if lLen <= n256Inline {
					if !matchRest(prefix[pos:pos+cmpLen], n.label[:cmpLen]) {
						return 0
					}
				} else if !t.matchExt(getExtIdx(&n.label[0]), lLen, prefix, pos, cmpLen) {
					return 0
				}
			}
		}

		if rem <= lLen {
			return int(sc)
		}
		pos += lLen
		cur = child
	}
}

// PrefixValues writes up to len(outValues) values of keys starting with prefix
// in lexicographic key order and returns the count written.
func (t *RadixTree) PrefixValues(prefix []byte, outValues []int64) int {
	limit := len(outValues)
	if limit == 0 {
		return 0
	}

	prefLen := len(prefix)
	cur := t.root
	var startNode uint32
	if prefLen == 0 {
		startNode = cur
	} else {
		pos := 0
		for {
			b := prefix[pos]
			var child uint32
			tag := cur >> tagShift
			cIdx := cur & idxMask
			if tag == tagN16 {
				n := &t.n16[cIdx]
				pat := uint64(b) * swarLo64
				w0 := *(*uint64)(unsafe.Pointer(&n.keys[0]))
				w1 := *(*uint64)(unsafe.Pointer(&n.keys[8]))
				x0 := w0 ^ pat
				x1 := w1 ^ pat
				m0 := (x0 - swarLo64) & ^x0 & swarHi64
				m1 := (x1 - swarLo64) & ^x1 & swarHi64
				i0 := bits.TrailingZeros64(m0) >> 3
				i1 := 8 + (bits.TrailingZeros64(m1) >> 3)
				ci := i1
				if m0 != 0 {
					ci = i0
				}
				if ci < int(n.count) {
					child = n.children[ci&15]
				}
			} else if tag == tagN4 {
				n := &t.n4[cIdx]
				pat := uint64(b) * swarLo32
				w := uint64(*(*uint32)(unsafe.Pointer(&n.keys[0])))
				x := w ^ pat
				m := (x - swarLo32) & ^x & swarHi32
				if m != 0 {
					ci := bits.TrailingZeros64(m) >> 3
					if ci < int(n.count) {
						child = n.children[ci&3]
					}
				}
			} else {
				child = t.findChildLarge(cur, b)
			}

			if child == nullNode {
				return 0
			}

			rem := prefLen - pos
			chTag := child >> tagShift
			chIdx := child & idxMask
			if chTag == tagLeaf {
				lf := &t.leaves[chIdx]
				lLen := int(lf.labelLen)
				if rem > lLen {
					return 0
				}
				if rem > 1 {
					if lLen <= leafInline {
						if !matchRest(prefix[pos:prefLen], lf.label[:rem]) {
							return 0
						}
					} else if !t.matchExt(getExtIdx(&lf.label[0]), lLen, prefix, pos, rem) {
						return 0
					}
				}
				outValues[0] = lf.val
				return 1
			}

			var lLen int
			if chTag == tagN16 {
				n := &t.n16[chIdx]
				lLen = int(n.labelLen)
				cmpLen := lLen
				if rem < cmpLen {
					cmpLen = rem
				}
				if cmpLen > 1 {
					if lLen <= n16Inline {
						if !matchRest(prefix[pos:pos+cmpLen], n.label[:cmpLen]) {
							return 0
						}
					} else if !t.matchExt(getExtIdx(&n.label[0]), lLen, prefix, pos, cmpLen) {
						return 0
					}
				}
			} else if chTag == tagN4 {
				n := &t.n4[chIdx]
				lLen = int(n.labelLen)
				cmpLen := lLen
				if rem < cmpLen {
					cmpLen = rem
				}
				if cmpLen > 1 {
					if lLen <= n4Inline {
						if !matchRest(prefix[pos:pos+cmpLen], n.label[:cmpLen]) {
							return 0
						}
					} else if !t.matchExt(getExtIdx(&n.label[0]), lLen, prefix, pos, cmpLen) {
						return 0
					}
				}
			} else if chTag == tagN48 {
				n := &t.n48[chIdx]
				lLen = int(n.labelLen)
				cmpLen := lLen
				if rem < cmpLen {
					cmpLen = rem
				}
				if cmpLen > 1 {
					if lLen <= n48Inline {
						if !matchRest(prefix[pos:pos+cmpLen], n.label[:cmpLen]) {
							return 0
						}
					} else if !t.matchExt(getExtIdx(&n.label[0]), lLen, prefix, pos, cmpLen) {
						return 0
					}
				}
			} else {
				n := &t.n256[chIdx]
				lLen = int(n.labelLen)
				cmpLen := lLen
				if rem < cmpLen {
					cmpLen = rem
				}
				if cmpLen > 1 {
					if lLen <= n256Inline {
						if !matchRest(prefix[pos:pos+cmpLen], n.label[:cmpLen]) {
							return 0
						}
					} else if !t.matchExt(getExtIdx(&n.label[0]), lLen, prefix, pos, cmpLen) {
						return 0
					}
				}
			}

			if rem <= lLen {
				startNode = child
				break
			}
			pos += lLen
			cur = child
		}
	}

	sc := int(t.subCount(startNode))
	if sc == 0 {
		return 0
	}
	if sc <= limit {
		return t.collectAll(startNode, outValues[:sc])
	}
	return t.collectLimit(startNode, outValues)
}

func (t *RadixTree) collectAll(start uint32, out []int64) int {
	outBase := unsafe.Pointer(unsafe.SliceData(out))
	var leavesBase, n4Base, n16Base unsafe.Pointer
	if len(t.leaves) > 0 {
		leavesBase = unsafe.Pointer(unsafe.SliceData(t.leaves))
	}
	if len(t.n4) > 0 {
		n4Base = unsafe.Pointer(unsafe.SliceData(t.n4))
	}
	if len(t.n16) > 0 {
		n16Base = unsafe.Pointer(unsafe.SliceData(t.n16))
	}

	written := 0
	sp := 0
	cur := start
	idx := 0
	emit := true

	for {
		switch cur >> tagShift {
		case tagN16:
			n := (*node16)(unsafe.Add(n16Base, uintptr(cur&idxMask)<<7))
			if emit && n.hasVal != 0 {
				*(*int64)(unsafe.Add(outBase, uintptr(written)<<3)) = n.val
				written++
			}
			cnt := int(n.count)
			descended := false
			for i := idx; i < cnt; i++ {
				ch := n.children[i&15]
				if ch>>tagShift == tagLeaf {
					*(*int64)(unsafe.Add(outBase, uintptr(written)<<3)) = (*leafNode)(unsafe.Add(leavesBase, uintptr(ch&idxMask)<<4)).val
					written++
				} else {
					if i+1 < cnt {
						t.walkStack[sp] = walkFrame{node: cur, idx: uint16(i + 1)}
						sp++
					}
					cur = ch
					idx = 0
					emit = true
					descended = true
					break
				}
			}
			if descended {
				continue
			}

		case tagN4:
			n := (*node4)(unsafe.Add(n4Base, uintptr(cur&idxMask)<<6))
			if emit && n.hasVal != 0 {
				*(*int64)(unsafe.Add(outBase, uintptr(written)<<3)) = n.val
				written++
			}
			cnt := int(n.count)
			descended := false
			for i := idx; i < cnt; i++ {
				ch := n.children[i&3]
				if ch>>tagShift == tagLeaf {
					*(*int64)(unsafe.Add(outBase, uintptr(written)<<3)) = (*leafNode)(unsafe.Add(leavesBase, uintptr(ch&idxMask)<<4)).val
					written++
				} else {
					if i+1 < cnt {
						t.walkStack[sp] = walkFrame{node: cur, idx: uint16(i + 1)}
						sp++
					}
					cur = ch
					idx = 0
					emit = true
					descended = true
					break
				}
			}
			if descended {
				continue
			}

		case tagN48:
			n := &t.n48[cur&idxMask]
			if emit && n.hasVal != 0 {
				*(*int64)(unsafe.Add(outBase, uintptr(written)<<3)) = n.val
				written++
			}
			descended := false
			for b := nextBit(&n.bitmap, idx); b < 256; b = nextBit(&n.bitmap, b+1) {
				ch := n.children[n.childIndex[b]-1]
				if ch>>tagShift == tagLeaf {
					*(*int64)(unsafe.Add(outBase, uintptr(written)<<3)) = (*leafNode)(unsafe.Add(leavesBase, uintptr(ch&idxMask)<<4)).val
					written++
				} else {
					if b+1 < 256 {
						t.walkStack[sp] = walkFrame{node: cur, idx: uint16(b + 1)}
						sp++
					}
					cur = ch
					idx = 0
					emit = true
					descended = true
					break
				}
			}
			if descended {
				continue
			}

		case tagN256:
			n := &t.n256[cur&idxMask]
			if emit && n.hasVal != 0 {
				*(*int64)(unsafe.Add(outBase, uintptr(written)<<3)) = n.val
				written++
			}
			descended := false
			for b := nextBit(&n.bitmap, idx); b < 256; b = nextBit(&n.bitmap, b+1) {
				ch := n.children[b]
				if ch>>tagShift == tagLeaf {
					*(*int64)(unsafe.Add(outBase, uintptr(written)<<3)) = (*leafNode)(unsafe.Add(leavesBase, uintptr(ch&idxMask)<<4)).val
					written++
				} else {
					if b+1 < 256 {
						t.walkStack[sp] = walkFrame{node: cur, idx: uint16(b + 1)}
						sp++
					}
					cur = ch
					idx = 0
					emit = true
					descended = true
					break
				}
			}
			if descended {
				continue
			}
		}

		if sp == 0 {
			return written
		}
		sp--
		f := t.walkStack[sp]
		cur = f.node
		idx = int(f.idx)
		emit = false
	}
}

func (t *RadixTree) collectLimit(start uint32, out []int64) int {
	limit := len(out)
	outBase := unsafe.Pointer(unsafe.SliceData(out))
	var leavesBase, n4Base, n16Base unsafe.Pointer
	if len(t.leaves) > 0 {
		leavesBase = unsafe.Pointer(unsafe.SliceData(t.leaves))
	}
	if len(t.n4) > 0 {
		n4Base = unsafe.Pointer(unsafe.SliceData(t.n4))
	}
	if len(t.n16) > 0 {
		n16Base = unsafe.Pointer(unsafe.SliceData(t.n16))
	}

	written := 0
	sp := 0
	cur := start
	idx := 0
	emit := true

	for {
		switch cur >> tagShift {
		case tagN16:
			n := (*node16)(unsafe.Add(n16Base, uintptr(cur&idxMask)<<7))
			if emit && n.hasVal != 0 {
				*(*int64)(unsafe.Add(outBase, uintptr(written)<<3)) = n.val
				written++
				if written == limit {
					return written
				}
			}
			cnt := int(n.count)
			descended := false
			for i := idx; i < cnt; i++ {
				ch := n.children[i&15]
				if ch>>tagShift == tagLeaf {
					*(*int64)(unsafe.Add(outBase, uintptr(written)<<3)) = (*leafNode)(unsafe.Add(leavesBase, uintptr(ch&idxMask)<<4)).val
					written++
					if written == limit {
						return written
					}
				} else {
					if i+1 < cnt {
						t.walkStack[sp] = walkFrame{node: cur, idx: uint16(i + 1)}
						sp++
					}
					cur = ch
					idx = 0
					emit = true
					descended = true
					break
				}
			}
			if descended {
				continue
			}

		case tagN4:
			n := (*node4)(unsafe.Add(n4Base, uintptr(cur&idxMask)<<6))
			if emit && n.hasVal != 0 {
				*(*int64)(unsafe.Add(outBase, uintptr(written)<<3)) = n.val
				written++
				if written == limit {
					return written
				}
			}
			cnt := int(n.count)
			descended := false
			for i := idx; i < cnt; i++ {
				ch := n.children[i&3]
				if ch>>tagShift == tagLeaf {
					*(*int64)(unsafe.Add(outBase, uintptr(written)<<3)) = (*leafNode)(unsafe.Add(leavesBase, uintptr(ch&idxMask)<<4)).val
					written++
					if written == limit {
						return written
					}
				} else {
					if i+1 < cnt {
						t.walkStack[sp] = walkFrame{node: cur, idx: uint16(i + 1)}
						sp++
					}
					cur = ch
					idx = 0
					emit = true
					descended = true
					break
				}
			}
			if descended {
				continue
			}

		case tagN48:
			n := &t.n48[cur&idxMask]
			if emit && n.hasVal != 0 {
				*(*int64)(unsafe.Add(outBase, uintptr(written)<<3)) = n.val
				written++
				if written == limit {
					return written
				}
			}
			descended := false
			for b := nextBit(&n.bitmap, idx); b < 256; b = nextBit(&n.bitmap, b+1) {
				ch := n.children[n.childIndex[b]-1]
				if ch>>tagShift == tagLeaf {
					*(*int64)(unsafe.Add(outBase, uintptr(written)<<3)) = (*leafNode)(unsafe.Add(leavesBase, uintptr(ch&idxMask)<<4)).val
					written++
					if written == limit {
						return written
					}
				} else {
					if b+1 < 256 {
						t.walkStack[sp] = walkFrame{node: cur, idx: uint16(b + 1)}
						sp++
					}
					cur = ch
					idx = 0
					emit = true
					descended = true
					break
				}
			}
			if descended {
				continue
			}

		case tagN256:
			n := &t.n256[cur&idxMask]
			if emit && n.hasVal != 0 {
				*(*int64)(unsafe.Add(outBase, uintptr(written)<<3)) = n.val
				written++
				if written == limit {
					return written
				}
			}
			descended := false
			for b := nextBit(&n.bitmap, idx); b < 256; b = nextBit(&n.bitmap, b+1) {
				ch := n.children[b]
				if ch>>tagShift == tagLeaf {
					*(*int64)(unsafe.Add(outBase, uintptr(written)<<3)) = (*leafNode)(unsafe.Add(leavesBase, uintptr(ch&idxMask)<<4)).val
					written++
					if written == limit {
						return written
					}
				} else {
					if b+1 < 256 {
						t.walkStack[sp] = walkFrame{node: cur, idx: uint16(b + 1)}
						sp++
					}
					cur = ch
					idx = 0
					emit = true
					descended = true
					break
				}
			}
			if descended {
				continue
			}
		}

		if sp == 0 {
			return written
		}
		sp--
		f := t.walkStack[sp]
		cur = f.node
		idx = int(f.idx)
		emit = false
	}
}

// Insert inserts (key, value) into the tree. Returns true if key was newly
// added, false if key was already present (its value is updated).
func (t *RadixTree) Insert(key []byte, value int64) bool {
	keyLen := len(key)
	cur := t.root
	if keyLen == 0 {
		idx := cur & idxMask
		switch cur >> tagShift {
		case tagN4:
			n := &t.n4[idx]
			if n.hasVal != 0 {
				n.val = value
				return false
			}
			n.hasVal = 1
			n.val = value
			n.subCount++
			return true
		case tagN16:
			n := &t.n16[idx]
			if n.hasVal != 0 {
				n.val = value
				return false
			}
			n.hasVal = 1
			n.val = value
			n.subCount++
			return true
		case tagN48:
			n := &t.n48[idx]
			if n.hasVal != 0 {
				n.val = value
				return false
			}
			n.hasVal = 1
			n.val = value
			n.subCount++
			return true
		default:
			n := &t.n256[idx]
			if n.hasVal != 0 {
				n.val = value
				return false
			}
			n.hasVal = 1
			n.val = value
			n.subCount++
			return true
		}
	}

	pos := 0
	depth := 0
	for {
		b := key[pos]
		var child uint32
		tag := cur >> tagShift
		cIdx := cur & idxMask
		if tag == tagN16 {
			n := &t.n16[cIdx]
			pat := uint64(b) * swarLo64
			w0 := *(*uint64)(unsafe.Pointer(&n.keys[0]))
			w1 := *(*uint64)(unsafe.Pointer(&n.keys[8]))
			x0 := w0 ^ pat
			x1 := w1 ^ pat
			m0 := (x0 - swarLo64) & ^x0 & swarHi64
			m1 := (x1 - swarLo64) & ^x1 & swarHi64
			i0 := bits.TrailingZeros64(m0) >> 3
			i1 := 8 + (bits.TrailingZeros64(m1) >> 3)
			ci := i1
			if m0 != 0 {
				ci = i0
			}
			if ci < int(n.count) {
				child = n.children[ci&15]
			}
		} else if tag == tagN4 {
			n := &t.n4[cIdx]
			pat := uint64(b) * swarLo32
			w := uint64(*(*uint32)(unsafe.Pointer(&n.keys[0])))
			x := w ^ pat
			m := (x - swarLo32) & ^x & swarHi32
			if m != 0 {
				ci := bits.TrailingZeros64(m) >> 3
				if ci < int(n.count) {
					child = n.children[ci&3]
				}
			}
		} else {
			child = t.findChildLarge(cur, b)
		}

		// Case A: no child for b — attach new leaf directly to cur.
		if child == nullNode {
			lf := t.allocLeaf()
			lfIdx := lf & idxMask
			remSlice := key[pos:]
			lfNode := &t.leaves[lfIdx]
			lfNode.val = value
			lfNode.labelLen = uint8(len(remSlice))
			if len(remSlice) <= leafInline {
				copy(lfNode.label[:len(remSlice)], remSlice)
			} else {
				ext := t.allocExtLabel(remSlice)
				setExtIdx(&t.leaves[lfIdx].label[0], ext)
			}
			newCur := t.addChild(cur, b, lf)
			if newCur != cur {
				if depth == 0 {
					t.root = newCur
				} else {
					t.setChild(t.pathNodes[depth-1], t.pathEdges[depth-1], newCur)
				}
				cur = newCur
			}
			t.incSubCount(cur)
			for i := 0; i < depth; i++ {
				t.incSubCount(t.pathNodes[i])
			}
			return true
		}

		t.pathNodes[depth] = cur
		t.pathEdges[depth] = b
		depth++

		chTag := child >> tagShift
		chIdx := child & idxMask
		rem := keyLen - pos

		// Fast path: 1-byte internal edge with more key bytes remaining.
		if chTag == tagN16 {
			n := &t.n16[chIdx]
			if n.labelLen == 1 {
				if rem > 1 {
					pos++
					cur = child
					continue
				}
				// Exact match at n16.
				if n.hasVal != 0 {
					n.val = value
					return false
				}
				n.hasVal = 1
				n.val = value
				n.subCount++
				for i := 0; i < depth; i++ {
					t.incSubCount(t.pathNodes[i])
				}
				return true
			}
		} else if chTag == tagN4 {
			n := &t.n4[chIdx]
			if n.labelLen == 1 {
				if rem > 1 {
					pos++
					cur = child
					continue
				}
				// Exact match at n4.
				if n.hasVal != 0 {
					n.val = value
					return false
				}
				n.hasVal = 1
				n.val = value
				n.subCount++
				for i := 0; i < depth; i++ {
					t.incSubCount(t.pathNodes[i])
				}
				return true
			}
		}

		// Compare child's label against key[pos:]. Byte 0 already matches.
		lbl := t.getLabel(child)
		lLen := len(lbl)
		maxMatch := lLen
		if rem < maxMatch {
			maxMatch = rem
		}
		match := 1
		for match < maxMatch && lbl[match] == key[pos+match] {
			match++
		}

		// Sub-case B1: exact match at child.
		if match == lLen && match == rem {
			if chTag == tagLeaf {
				t.leaves[chIdx].val = value
				return false
			}
			switch chTag {
			case tagN4:
				n := &t.n4[chIdx]
				if n.hasVal != 0 {
					n.val = value
					return false
				}
				n.hasVal = 1
				n.val = value
				n.subCount++
			case tagN16:
				n := &t.n16[chIdx]
				if n.hasVal != 0 {
					n.val = value
					return false
				}
				n.hasVal = 1
				n.val = value
				n.subCount++
			case tagN48:
				n := &t.n48[chIdx]
				if n.hasVal != 0 {
					n.val = value
					return false
				}
				n.hasVal = 1
				n.val = value
				n.subCount++
			default:
				n := &t.n256[chIdx]
				if n.hasVal != 0 {
					n.val = value
					return false
				}
				n.hasVal = 1
				n.val = value
				n.subCount++
			}
			for i := 0; i < depth; i++ {
				t.incSubCount(t.pathNodes[i])
			}
			return true
		}

		// Sub-case B2: matched full label of child, more key bytes remain.
		if match == lLen {
			pos += lLen
			if chTag != tagLeaf {
				cur = child
				continue
			}
			// Promote leaf into node4 with 1 new leaf child.
			lf := &t.leaves[chIdx]
			oldVal := lf.val
			copy(t.mergeBuf[:lLen], lbl)
			t.freeLeafNode(child)

			newLeaf := t.allocLeaf()
			t.leaves[newLeaf&idxMask].val = value
			t.setFreshLabel(newLeaf, key[pos:])

			nh := t.allocN4()
			nn := &t.n4[nh&idxMask]
			nn.val = oldVal
			nn.subCount = 2
			nn.hasVal = 1
			nn.count = 1
			nn.keys[0] = key[pos]
			nn.children[0] = newLeaf
			t.setFreshLabel(nh, t.mergeBuf[:lLen])

			t.setChild(t.pathNodes[depth-1], t.pathEdges[depth-1], nh)
			for i := 0; i < depth; i++ {
				t.incSubCount(t.pathNodes[i])
			}
			return true
		}

		// Sub-cases B3 & B4: split edge child at match (1 <= match < lLen).
		copy(t.mergeBuf[:lLen], lbl)
		childSC := t.subCount(child)
		bOld := t.mergeBuf[match]

		// Update child's label to suffix [match:lLen].
		t.replaceLabel(child, t.mergeBuf[match:lLen])

		if match == rem {
			// Sub-case B3: new key ends inside child's label.
			mid := t.allocN4()
			mn := &t.n4[mid&idxMask]
			mn.val = value
			mn.subCount = childSC + 1
			mn.hasVal = 1
			mn.count = 1
			mn.keys[0] = bOld
			mn.children[0] = child
			t.setFreshLabel(mid, t.mergeBuf[:match])

			t.setChild(t.pathNodes[depth-1], t.pathEdges[depth-1], mid)
			for i := 0; i < depth; i++ {
				t.incSubCount(t.pathNodes[i])
			}
			return true
		}

		// Sub-case B4: key diverges from child's label at match.
		newLeaf := t.allocLeaf()
		t.leaves[newLeaf&idxMask].val = value
		t.setFreshLabel(newLeaf, key[pos+match:])

		mid := t.allocN4()
		mn := &t.n4[mid&idxMask]
		mn.val = 0
		mn.subCount = childSC + 1
		mn.hasVal = 0
		mn.count = 2
		bNew := key[pos+match]
		if bOld < bNew {
			mn.keys[0] = bOld
			mn.children[0] = child
			mn.keys[1] = bNew
			mn.children[1] = newLeaf
		} else {
			mn.keys[0] = bNew
			mn.children[0] = newLeaf
			mn.keys[1] = bOld
			mn.children[1] = child
		}
		t.setFreshLabel(mid, t.mergeBuf[:match])

		t.setChild(t.pathNodes[depth-1], t.pathEdges[depth-1], mid)
		for i := 0; i < depth; i++ {
			t.incSubCount(t.pathNodes[i])
		}
		return true
	}
}

// Remove deletes key from the tree if present, restoring path compression.
func (t *RadixTree) Remove(key []byte) bool {
	keyLen := len(key)
	cur := t.root
	if keyLen == 0 {
		idx := cur & idxMask
		switch cur >> tagShift {
		case tagN4:
			n := &t.n4[idx]
			if n.hasVal == 0 {
				return false
			}
			n.hasVal = 0
			n.subCount--
			return true
		case tagN16:
			n := &t.n16[idx]
			if n.hasVal == 0 {
				return false
			}
			n.hasVal = 0
			n.subCount--
			return true
		case tagN48:
			n := &t.n48[idx]
			if n.hasVal == 0 {
				return false
			}
			n.hasVal = 0
			n.subCount--
			return true
		default:
			n := &t.n256[idx]
			if n.hasVal == 0 {
				return false
			}
			n.hasVal = 0
			n.subCount--
			return true
		}
	}

	pos := 0
	depth := 0
	var target uint32
	for {
		b := key[pos]
		var child uint32
		tag := cur >> tagShift
		cIdx := cur & idxMask
		if tag == tagN16 {
			n := &t.n16[cIdx]
			pat := uint64(b) * swarLo64
			w0 := *(*uint64)(unsafe.Pointer(&n.keys[0]))
			w1 := *(*uint64)(unsafe.Pointer(&n.keys[8]))
			x0 := w0 ^ pat
			x1 := w1 ^ pat
			m0 := (x0 - swarLo64) & ^x0 & swarHi64
			m1 := (x1 - swarLo64) & ^x1 & swarHi64
			i0 := bits.TrailingZeros64(m0) >> 3
			i1 := 8 + (bits.TrailingZeros64(m1) >> 3)
			ci := i1
			if m0 != 0 {
				ci = i0
			}
			if ci < int(n.count) {
				child = n.children[ci&15]
			}
		} else if tag == tagN4 {
			n := &t.n4[cIdx]
			pat := uint64(b) * swarLo32
			w := uint64(*(*uint32)(unsafe.Pointer(&n.keys[0])))
			x := w ^ pat
			m := (x - swarLo32) & ^x & swarHi32
			if m != 0 {
				ci := bits.TrailingZeros64(m) >> 3
				if ci < int(n.count) {
					child = n.children[ci&3]
				}
			}
		} else {
			child = t.findChildLarge(cur, b)
		}

		if child == nullNode {
			return false
		}

		t.pathNodes[depth] = cur
		t.pathEdges[depth] = b

		chTag := child >> tagShift
		chIdx := child & idxMask
		if chTag == tagLeaf {
			lf := &t.leaves[chIdx]
			lLen := int(lf.labelLen)
			if pos+lLen != keyLen {
				return false
			}
			if lLen > 1 {
				if lLen <= leafInline {
					if !matchRest(key[pos:keyLen], lf.label[:lLen]) {
						return false
					}
				} else if !t.matchExt(getExtIdx(&lf.label[0]), lLen, key, pos, lLen) {
					return false
				}
			}
			target = child
			break
		}

		var lLen int
		if chTag == tagN16 {
			n := &t.n16[chIdx]
			lLen = int(n.labelLen)
			if keyLen-pos < lLen {
				return false
			}
			if lLen > 1 {
				if lLen <= n16Inline {
					if !matchRest(key[pos:pos+lLen], n.label[:lLen]) {
						return false
					}
				} else if !t.matchExt(getExtIdx(&n.label[0]), lLen, key, pos, lLen) {
					return false
				}
			}
		} else if chTag == tagN4 {
			n := &t.n4[chIdx]
			lLen = int(n.labelLen)
			if keyLen-pos < lLen {
				return false
			}
			if lLen > 1 {
				if lLen <= n4Inline {
					if !matchRest(key[pos:pos+lLen], n.label[:lLen]) {
						return false
					}
				} else if !t.matchExt(getExtIdx(&n.label[0]), lLen, key, pos, lLen) {
					return false
				}
			}
		} else if chTag == tagN48 {
			n := &t.n48[chIdx]
			lLen = int(n.labelLen)
			if keyLen-pos < lLen {
				return false
			}
			if lLen > 1 {
				if lLen <= n48Inline {
					if !matchRest(key[pos:pos+lLen], n.label[:lLen]) {
						return false
					}
				} else if !t.matchExt(getExtIdx(&n.label[0]), lLen, key, pos, lLen) {
					return false
				}
			}
		} else {
			n := &t.n256[chIdx]
			lLen = int(n.labelLen)
			if keyLen-pos < lLen {
				return false
			}
			if lLen > 1 {
				if lLen <= n256Inline {
					if !matchRest(key[pos:pos+lLen], n.label[:lLen]) {
						return false
					}
				} else if !t.matchExt(getExtIdx(&n.label[0]), lLen, key, pos, lLen) {
					return false
				}
			}
		}

		pos += lLen
		if pos == keyLen {
			target = child
			break
		}
		depth++
		cur = child
	}

	// pathNodes[depth] is parent of target via pathEdges[depth].
	tTag := target >> tagShift
	tIdx := target & idxMask

	// Case R1: target is a leaf.
	if tTag == tagLeaf {
		t.freeLeafNode(target)
		parent := t.pathNodes[depth]
		newParent := t.removeChild(parent, t.pathEdges[depth])
		if newParent != parent {
			if depth == 0 {
				t.root = newParent
			} else {
				t.setChild(t.pathNodes[depth-1], t.pathEdges[depth-1], newParent)
			}
			parent = newParent
			t.pathNodes[depth] = parent
		}

		// If parent is non-root and is node4, check for leaf conversion or merge.
		if depth > 0 && parent>>tagShift == tagN4 {
			pIdx := parent & idxMask
			pn := &t.n4[pIdx]
			if pn.count == 0 {
				// Parent held a key and lost its only child -> convert parent to leaf.
				pVal := pn.val
				pLbl := t.getLabel(parent)
				pLen := len(pLbl)
				copy(t.mergeBuf[:pLen], pLbl)
				if pn.labelLen > n4Inline {
					t.freeExtLabel(getExtIdx(&pn.label[0]), int(pn.labelLen))
				}
				t.freeN4Slot(pIdx)

				lf := t.allocLeaf()
				t.leaves[lf&idxMask].val = pVal
				t.setFreshLabel(lf, t.mergeBuf[:pLen])
				t.setChild(t.pathNodes[depth-1], t.pathEdges[depth-1], lf)
				for i := 0; i < depth; i++ {
					t.decSubCount(t.pathNodes[i])
				}
				return true
			}
			if pn.count == 1 && pn.hasVal == 0 {
				// Parent has no key and 1 child -> merge parent into its only child.
				onlyChild := pn.children[0]
				pLbl := t.getLabel(parent)
				pLen := len(pLbl)
				copy(t.mergeBuf[:pLen], pLbl)
				cLbl := t.getLabel(onlyChild)
				cLen := len(cLbl)
				copy(t.mergeBuf[pLen:pLen+cLen], cLbl)

				if pn.labelLen > n4Inline {
					t.freeExtLabel(getExtIdx(&pn.label[0]), int(pn.labelLen))
				}
				t.freeN4Slot(pIdx)

				t.replaceLabel(onlyChild, t.mergeBuf[:pLen+cLen])
				t.setChild(t.pathNodes[depth-1], t.pathEdges[depth-1], onlyChild)
				for i := 0; i < depth; i++ {
					t.decSubCount(t.pathNodes[i])
				}
				return true
			}
		}

		for i := 0; i <= depth; i++ {
			t.decSubCount(t.pathNodes[i])
		}
		return true
	}

	// Target is an internal node (non-root). Verify it holds a key.
	switch tTag {
	case tagN4:
		tn := &t.n4[tIdx]
		if tn.hasVal == 0 {
			return false
		}
		if tn.count == 1 {
			// Case R2: target has no key now and only 1 child -> merge into onlyChild.
			onlyChild := tn.children[0]
			uLbl := t.getLabel(target)
			uLen := len(uLbl)
			copy(t.mergeBuf[:uLen], uLbl)
			cLbl := t.getLabel(onlyChild)
			cLen := len(cLbl)
			copy(t.mergeBuf[uLen:uLen+cLen], cLbl)

			if tn.labelLen > n4Inline {
				t.freeExtLabel(getExtIdx(&tn.label[0]), int(tn.labelLen))
			}
			t.freeN4Slot(tIdx)

			t.replaceLabel(onlyChild, t.mergeBuf[:uLen+cLen])
			t.setChild(t.pathNodes[depth], t.pathEdges[depth], onlyChild)
			for i := 0; i <= depth; i++ {
				t.decSubCount(t.pathNodes[i])
			}
			return true
		}
		// Case R3: count >= 2.
		tn.hasVal = 0
		tn.subCount--
	case tagN16:
		tn := &t.n16[tIdx]
		if tn.hasVal == 0 {
			return false
		}
		tn.hasVal = 0
		tn.subCount--
	case tagN48:
		tn := &t.n48[tIdx]
		if tn.hasVal == 0 {
			return false
		}
		tn.hasVal = 0
		tn.subCount--
	default:
		tn := &t.n256[tIdx]
		if tn.hasVal == 0 {
			return false
		}
		tn.hasVal = 0
		tn.subCount--
	}

	for i := 0; i <= depth; i++ {
		t.decSubCount(t.pathNodes[i])
	}
	return true
}

// NodeCount returns the exact number of nodes in the compressed trie (root included).
func (t *RadixTree) NodeCount() int {
	return t.countNodes(t.root)
}

func (t *RadixTree) countNodes(h uint32) int {
	idx := h & idxMask
	switch h >> tagShift {
	case tagLeaf:
		return 1
	case tagN4:
		n := &t.n4[idx]
		total := 1
		for i := uint8(0); i < n.count; i++ {
			total += t.countNodes(n.children[i])
		}
		return total
	case tagN16:
		n := &t.n16[idx]
		total := 1
		for i := uint8(0); i < n.count; i++ {
			total += t.countNodes(n.children[i])
		}
		return total
	case tagN48:
		n := &t.n48[idx]
		total := 1
		for b := nextBit(&n.bitmap, 0); b < 256; b = nextBit(&n.bitmap, b+1) {
			total += t.countNodes(n.children[n.childIndex[b]-1])
		}
		return total
	default:
		n := &t.n256[idx]
		total := 1
		for b := nextBit(&n.bitmap, 0); b < 256; b = nextBit(&n.bitmap, b+1) {
			total += t.countNodes(n.children[b])
		}
		return total
	}
}

// Height returns the maximum number of edges from the root to any node.
func (t *RadixTree) Height() int {
	return t.calcHeight(t.root)
}

func (t *RadixTree) calcHeight(h uint32) int {
	idx := h & idxMask
	switch h >> tagShift {
	case tagLeaf:
		return 0
	case tagN4:
		n := &t.n4[idx]
		if n.count == 0 {
			return 0
		}
		best := 0
		for i := uint8(0); i < n.count; i++ {
			ch := t.calcHeight(n.children[i])
			if ch > best {
				best = ch
			}
		}
		return best + 1
	case tagN16:
		n := &t.n16[idx]
		if n.count == 0 {
			return 0
		}
		best := 0
		for i := uint8(0); i < n.count; i++ {
			ch := t.calcHeight(n.children[i])
			if ch > best {
				best = ch
			}
		}
		return best + 1
	case tagN48:
		n := &t.n48[idx]
		if n.count == 0 {
			return 0
		}
		best := 0
		for b := nextBit(&n.bitmap, 0); b < 256; b = nextBit(&n.bitmap, b+1) {
			ch := t.calcHeight(n.children[n.childIndex[b]-1])
			if ch > best {
				best = ch
			}
		}
		return best + 1
	default:
		n := &t.n256[idx]
		if n.count == 0 {
			return 0
		}
		best := 0
		for b := nextBit(&n.bitmap, 0); b < 256; b = nextBit(&n.bitmap, b+1) {
			ch := t.calcHeight(n.children[b])
			if ch > best {
				best = ch
			}
		}
		return best + 1
	}
}
