// Package hashmap implements an open-addressing hash table with linear
// probing and backward-shift deletion, mapping int64 keys to int64 values.
//
// Layout: one flat array of 16-byte slots {key, val}. Key 0 marks an empty
// slot. A real entry with key 0 lives in an ordinary slot of the table; its
// slot index is remembered in zeroSlot so that it can be told apart from
// the empty slots.
package hashmap

import "unsafe"

const (
	hashMul  uint64 = 0x9E3779B97F4A7C15
	noSlot   uint64 = ^uint64(0)
	initBits        = 4
)

type slot struct {
	key int64
	val int64
}

type HashMap struct {
	base     unsafe.Pointer // &slots[0]
	mask     uint64         // capacity - 1
	shift    uint64         // 64 - log2(capacity)
	zeroSlot uint64         // slot holding key 0, or noSlot
	length   int
	growAt   int // maximum length allowed: capacity*7/8
	slots    []slot
}

func New() *HashMap {
	m := &HashMap{}
	m.alloc(1 << initBits)
	m.zeroSlot = noSlot
	return m
}

func (m *HashMap) alloc(capacity uint64) {
	s := make([]slot, capacity)
	m.slots = s
	m.base = unsafe.Pointer(&s[0])
	m.mask = capacity - 1
	bits := uint64(0)
	for (uint64(1) << bits) < capacity {
		bits++
	}
	m.shift = 64 - bits
	m.growAt = int(capacity - capacity/8)
}

func at(base unsafe.Pointer, i uint64) *slot {
	return (*slot)(unsafe.Add(base, uintptr(i)<<4))
}

func (m *HashMap) Get(key int64) (int64, bool) {
	if key == 0 {
		return m.getZero()
	}
	base, mask, z := m.base, m.mask, m.zeroSlot
	i := (uint64(key) * hashMul) >> m.shift
	for {
		s := at(base, i)
		k := s.key
		if k == key {
			return s.val, true
		}
		if k == 0 && i != z {
			return 0, false
		}
		i = (i + 1) & mask
	}
}

func (m *HashMap) getZero() (int64, bool) {
	if m.zeroSlot == noSlot {
		return 0, false
	}
	return at(m.base, m.zeroSlot).val, true
}

func (m *HashMap) Insert(key, value int64) bool {
	if key == 0 {
		return m.insertZero(value)
	}
	base, mask, z := m.base, m.mask, m.zeroSlot
	i := (uint64(key) * hashMul) >> m.shift
	for {
		s := at(base, i)
		k := s.key
		if k == key {
			s.val = value
			return false
		}
		if k == 0 && i != z {
			if m.length >= m.growAt {
				m.grow()
				m.placeNew(key, value)
			} else {
				s.key = key
				s.val = value
			}
			m.length++
			return true
		}
		i = (i + 1) & mask
	}
}

// placeNew stores a nonzero key known to be absent.
func (m *HashMap) placeNew(key, value int64) {
	base, mask, z := m.base, m.mask, m.zeroSlot
	i := (uint64(key) * hashMul) >> m.shift
	for {
		s := at(base, i)
		if s.key == 0 && i != z {
			s.key = key
			s.val = value
			return
		}
		i = (i + 1) & mask
	}
}

func (m *HashMap) insertZero(value int64) bool {
	if m.zeroSlot != noSlot {
		at(m.base, m.zeroSlot).val = value
		return false
	}
	if m.length >= m.growAt {
		m.grow()
	}
	// home(0) == 0; with no zero key present, key 0 means empty.
	base, mask := m.base, m.mask
	i := uint64(0)
	for at(base, i).key != 0 {
		i = (i + 1) & mask
	}
	at(base, i).val = value
	m.zeroSlot = i
	m.length++
	return true
}

func (m *HashMap) grow() {
	oldBase := m.base
	oldCap := m.mask + 1
	oldZero := m.zeroSlot
	var zeroVal int64
	if oldZero != noSlot {
		zeroVal = at(oldBase, oldZero).val
	}
	oldSlots := m.slots

	m.alloc(oldCap * 2)
	m.zeroSlot = noSlot
	base, mask, shift := m.base, m.mask, m.shift

	// Multiplicative hashing keeps home slots ordered, so walking the old
	// table in order writes the new table nearly sequentially.
	for i := uint64(0); i < oldCap; i++ {
		s := at(oldBase, i)
		k := s.key
		if k == 0 {
			continue
		}
		j := (uint64(k) * hashMul) >> shift
		for at(base, j).key != 0 {
			j = (j + 1) & mask
		}
		*at(base, j) = *s
	}
	_ = oldSlots

	if oldZero != noSlot {
		j := uint64(0)
		for at(base, j).key != 0 {
			j = (j + 1) & mask
		}
		at(base, j).val = zeroVal
		m.zeroSlot = j
	}
}

func (m *HashMap) Remove(key int64) bool {
	base, mask := m.base, m.mask
	var pos uint64
	if key == 0 {
		if m.zeroSlot == noSlot {
			return false
		}
		pos = m.zeroSlot
		m.zeroSlot = noSlot
	} else {
		z := m.zeroSlot
		i := (uint64(key) * hashMul) >> m.shift
		for {
			k := at(base, i).key
			if k == key {
				break
			}
			if k == 0 && i != z {
				return false
			}
			i = (i + 1) & mask
		}
		pos = i
	}
	m.length--

	// Backward-shift deletion.
	shift := m.shift
	z := m.zeroSlot
	hole := pos
	j := (pos + 1) & mask
	for {
		s := at(base, j)
		k := s.key
		if k == 0 && j != z {
			break
		}
		home := (uint64(k) * hashMul) >> shift
		if (j-home)&mask >= (j-hole)&mask {
			*at(base, hole) = *s
			if j == z {
				z = hole
				m.zeroSlot = hole
			}
			hole = j
		}
		j = (j + 1) & mask
	}
	h := at(base, hole)
	h.key = 0
	h.val = 0
	return true
}

func (m *HashMap) Scan(outKeys, outVals []int64) int {
	base := m.base
	n := m.mask + 1
	c := 0
	outKeys = outKeys[:m.length]
	outVals = outVals[:m.length]
	for i := uint64(0); i < n; i++ {
		s := at(base, i)
		if s.key != 0 {
			outKeys[c] = s.key
			outVals[c] = s.val
			c++
		}
	}
	if m.zeroSlot != noSlot {
		outKeys[c] = 0
		outVals[c] = at(base, m.zeroSlot).val
		c++
	}
	return c
}

func (m *HashMap) Len() int { return m.length }

func (m *HashMap) Capacity() int { return int(m.mask + 1) }
