package hashmap

import "unsafe"

const (
	fibMul    uint64  = 0x9E3779B97F4A7C15
	slotSize  uintptr = 16
	initCap   int     = 16
	initShift uint8   = 60 // 64 - log2(16)
)

type slot struct {
	key int64
	val int64
}

// HashMap is an open-addressing hash map with linear probing and backward-shift
// deletion. Key 0 is used as the empty-slot sentinel; if key 0 is present in
// the map, it occupies a slot on its probe sequence (starting at slot 0) and
// zeroPtr points directly to that slot.
type HashMap struct {
	base    unsafe.Pointer // &slots[0]
	last    unsafe.Pointer // &slots[cap-1]
	zeroPtr unsafe.Pointer // pointer to key 0's slot, or nil if key 0 is absent
	len     int
	maxLoad int     // capacity * 7 / 8
	bmask   uintptr // (capacity - 1) * slotSize
	shift   uint8   // 64 - log2(capacity)
	slots   []slot  // backing storage (kept live for GC)
}

// New creates an empty hash map with initial capacity 16.
func New() *HashMap {
	slots := make([]slot, initCap)
	base := unsafe.Pointer(unsafe.SliceData(slots))
	return &HashMap{
		base:    base,
		last:    unsafe.Add(base, uintptr(initCap-1)*slotSize),
		maxLoad: initCap - initCap>>3,
		bmask:   uintptr(initCap-1) * slotSize,
		shift:   initShift,
		slots:   slots,
	}
}

// Len returns the number of entries in the map.
func (m *HashMap) Len() int {
	return m.len
}

// Capacity returns the current number of slots in the table.
func (m *HashMap) Capacity() int {
	return len(m.slots)
}

// Get returns the value stored for key and true, or 0 and false if absent.
func (m *HashMap) Get(key int64) (int64, bool) {
	zeroPtr := m.zeroPtr
	if key == 0 {
		if zeroPtr != nil {
			return (*slot)(zeroPtr).val, true
		}
		return 0, false
	}
	base := m.base
	last := m.last
	p := unsafe.Add(base, uintptr((uint64(key)*fibMul)>>(m.shift&63))<<4)
	for {
		s := (*slot)(p)
		k := s.key
		if k == key {
			return s.val, true
		}
		if k == 0 && p != zeroPtr {
			return 0, false
		}
		if p != last {
			p = unsafe.Add(p, slotSize)
		} else {
			p = base
		}
	}
}

// Insert adds (key, value) if key is absent (returning true) or replaces the
// existing value if key is present (returning false).
func (m *HashMap) Insert(key, value int64) bool {
	if key == 0 {
		return m.insertZero(value)
	}
	base := m.base
	last := m.last
	p := unsafe.Add(base, uintptr((uint64(key)*fibMul)>>(m.shift&63))<<4)
	for {
		s := (*slot)(p)
		k := s.key
		if k == key {
			s.val = value
			return false
		}
		if k == 0 && p != m.zeroPtr {
			if m.len == m.maxLoad {
				m.growAndInsert(key, value)
				return true
			}
			s.key = key
			s.val = value
			m.len++
			return true
		}
		if p != last {
			p = unsafe.Add(p, slotSize)
		} else {
			p = base
		}
	}
}

//go:noinline
func (m *HashMap) insertZero(value int64) bool {
	if m.zeroPtr != nil {
		(*slot)(m.zeroPtr).val = value
		return false
	}
	if m.len == m.maxLoad {
		m.grow()
	}
	// home(0) == 0, and key 0 is absent so the first slot with key == 0 is empty.
	p := m.base
	for (*slot)(p).key != 0 {
		p = unsafe.Add(p, slotSize)
	}
	(*slot)(p).val = value
	m.zeroPtr = p
	m.len++
	return true
}

//go:noinline
func (m *HashMap) growAndInsert(key, value int64) {
	m.grow()
	base := m.base
	last := m.last
	zeroPtr := m.zeroPtr
	p := unsafe.Add(base, uintptr((uint64(key)*fibMul)>>(m.shift&63))<<4)
	for {
		s := (*slot)(p)
		if s.key == 0 && p != zeroPtr {
			s.key = key
			s.val = value
			m.len++
			return
		}
		if p != last {
			p = unsafe.Add(p, slotSize)
		} else {
			p = base
		}
	}
}

//go:noinline
func (m *HashMap) grow() {
	oldSlots := m.slots
	oldZeroPtr := m.zeroPtr
	newCap := len(oldSlots) << 1
	newShift := m.shift - 1
	sh := newShift & 63

	newSlots := make([]slot, newCap)
	newBase := unsafe.Pointer(unsafe.SliceData(newSlots))
	newLast := unsafe.Add(newBase, uintptr(newCap-1)*slotSize)

	for i := range oldSlots {
		os := &oldSlots[i]
		k := os.key
		if k == 0 {
			continue
		}
		p := unsafe.Add(newBase, uintptr((uint64(k)*fibMul)>>sh)<<4)
		for (*slot)(p).key != 0 {
			if p != newLast {
				p = unsafe.Add(p, slotSize)
			} else {
				p = newBase
			}
		}
		ns := (*slot)(p)
		ns.key = k
		ns.val = os.val
	}

	var newZeroPtr unsafe.Pointer
	if oldZeroPtr != nil {
		p := newBase
		for (*slot)(p).key != 0 {
			p = unsafe.Add(p, slotSize)
		}
		(*slot)(p).val = (*slot)(oldZeroPtr).val
		newZeroPtr = p
	}

	m.base = newBase
	m.last = newLast
	m.zeroPtr = newZeroPtr
	m.shift = newShift
	m.maxLoad = newCap - newCap>>3
	m.bmask = uintptr(newCap-1) * slotSize
	m.slots = newSlots
}

// Remove deletes key from the map using backward-shift deletion and returns
// true if it was present.
func (m *HashMap) Remove(key int64) bool {
	base := m.base
	bmask := m.bmask
	sh := m.shift & 63
	zeroPtr := m.zeroPtr

	var pos uintptr
	if key == 0 {
		if zeroPtr == nil {
			return false
		}
		pos = uintptr(zeroPtr) - uintptr(base)
		m.zeroPtr = nil
		zeroPtr = nil
	} else {
		last := m.last
		p := unsafe.Add(base, uintptr((uint64(key)*fibMul)>>sh)<<4)
		for {
			k := (*slot)(p).key
			if k == key {
				pos = uintptr(p) - uintptr(base)
				break
			}
			if k == 0 && p != zeroPtr {
				return false
			}
			if p != last {
				p = unsafe.Add(p, slotSize)
			} else {
				p = base
			}
		}
	}

	// Backward-shift later entries in the probe cluster to close the hole at pos.
	j := (pos + slotSize) & bmask
	for {
		pj := unsafe.Add(base, j)
		kj := (*slot)(pj).key
		if kj == 0 && pj != zeroPtr {
			(*slot)(unsafe.Add(base, pos)).key = 0
			m.len--
			return true
		}
		h := uintptr((uint64(kj)*fibMul)>>sh) << 4
		if ((pos - h) & bmask) < ((j - h) & bmask) {
			pp := unsafe.Add(base, pos)
			sp := (*slot)(pp)
			sp.key = kj
			sp.val = (*slot)(pj).val
			if pj == zeroPtr {
				m.zeroPtr = pp
				zeroPtr = pp
			}
			pos = j
		}
		j = (j + slotSize) & bmask
	}
}

// Scan writes every entry to outKeys and outVals in table order and returns Len().
func (m *HashMap) Scan(outKeys, outVals []int64) int {
	n := m.len
	if n == 0 {
		return 0
	}
	_ = outKeys[n-1]
	_ = outVals[n-1]

	nonZero := n
	if m.zeroPtr != nil {
		nonZero = n - 1
		outKeys[nonZero] = 0
		outVals[nonZero] = (*slot)(m.zeroPtr).val
		if nonZero == 0 {
			return n
		}
	}

	base := m.base
	okBase := unsafe.Pointer(unsafe.SliceData(outKeys))
	ovBase := unsafe.Pointer(unsafe.SliceData(outVals))
	endOut := uintptr(nonZero) << 3
	var out, off uintptr

	if endOut >= 32 {
		safeEnd := endOut - 32
		for out <= safeEnd {
			chunk := (*[4]slot)(unsafe.Add(base, off))

			k0 := chunk[0].key
			*(*int64)(unsafe.Add(okBase, out)) = k0
			*(*int64)(unsafe.Add(ovBase, out)) = chunk[0].val
			u0 := uint64(k0)
			out += uintptr(((u0 | -u0) >> 63) << 3)

			k1 := chunk[1].key
			*(*int64)(unsafe.Add(okBase, out)) = k1
			*(*int64)(unsafe.Add(ovBase, out)) = chunk[1].val
			u1 := uint64(k1)
			out += uintptr(((u1 | -u1) >> 63) << 3)

			k2 := chunk[2].key
			*(*int64)(unsafe.Add(okBase, out)) = k2
			*(*int64)(unsafe.Add(ovBase, out)) = chunk[2].val
			u2 := uint64(k2)
			out += uintptr(((u2 | -u2) >> 63) << 3)

			k3 := chunk[3].key
			*(*int64)(unsafe.Add(okBase, out)) = k3
			*(*int64)(unsafe.Add(ovBase, out)) = chunk[3].val
			u3 := uint64(k3)
			out += uintptr(((u3 | -u3) >> 63) << 3)

			off += 64
		}
	}

	for out < endOut {
		s := (*slot)(unsafe.Add(base, off))
		k := s.key
		*(*int64)(unsafe.Add(okBase, out)) = k
		*(*int64)(unsafe.Add(ovBase, out)) = s.val
		u := uint64(k)
		out += uintptr(((u | -u) >> 63) << 3)
		off += slotSize
	}

	return n
}
