#if canImport(Darwin)
import Darwin
#else
import Glibc
#endif

// Open-addressing hash map with linear probing and backward-shift deletion.
//
// Slots are interleaved (key, value) pairs of 16 bytes, so a probe touches a
// single cache line. The key 0 marks an empty slot. A real entry with key 0
// lives in a slot like any other entry; its slot index is remembered in
// `zeroSlot` (-1 when key 0 is absent), so a slot holding key 0 is empty iff
// its index differs from `zeroSlot`.
@usableFromInline
struct Slot {
    @usableFromInline var key: Int64
    @usableFromInline var val: Int64
    @inline(__always) init(_ key: Int64, _ val: Int64) {
        self.key = key
        self.val = val
    }
}

final class HashMap {
    @exclusivity(unchecked) private var slots: UnsafeMutablePointer<Slot>
    @exclusivity(unchecked) private var mask: Int
    @exclusivity(unchecked) private var shift: UInt64
    @exclusivity(unchecked) private var zeroSlot: Int = -1
    @exclusivity(unchecked) private(set) var count: Int = 0

    @inline(__always)
    private static func allocTable(_ cap: Int) -> UnsafeMutablePointer<Slot> {
        // calloc: zeroed memory == all slots empty (and lazily zeroed pages
        // from the OS for large tables).
        guard let raw = calloc(cap, MemoryLayout<Slot>.stride) else {
            fatalError("HashMap: out of memory")
        }
        return raw.bindMemory(to: Slot.self, capacity: cap)
    }

    init() {
        slots = HashMap.allocTable(16)
        mask = 15
        shift = 64 - 4
    }

    deinit {
        free(slots)
    }

    @inline(__always)
    private func home(_ key: Int64) -> Int {
        Int(truncatingIfNeeded: (UInt64(bitPattern: key) &* 0x9E37_79B9_7F4A_7C15) &>> shift)
    }

    @inline(__always)
    func capacity() -> Int { mask &+ 1 }

    // MARK: - get

    @inline(__always)
    func get(_ key: Int64) -> Int64? {
        let s = slots
        if key == 0 {
            let z = zeroSlot
            return z >= 0 ? s[z].val : nil
        }
        let m = mask
        var i = home(key)
        while true {
            let k = s[i].key
            if k == key { return s[i].val }
            if k == 0 && i != zeroSlot { return nil }
            i = (i &+ 1) & m
        }
    }

    // MARK: - insert

    @inline(__always)
    func insert(_ key: Int64, _ value: Int64) -> Bool {
        if key == 0 { return insertZero(value) }
        let s = slots
        let m = mask
        var i = home(key)
        while true {
            let k = s[i].key
            if k == key {
                s[i].val = value
                return false
            }
            if k == 0 && i != zeroSlot { break }
            i = (i &+ 1) & m
        }
        let c = count &+ 1
        if c &* 8 > (m &+ 1) &* 7 {
            grow()
            i = findEmpty(key)
            slots[i] = Slot(key, value)
        } else {
            s[i] = Slot(key, value)
        }
        count = c
        return true
    }

    @inline(never)
    private func insertZero(_ value: Int64) -> Bool {
        if zeroSlot >= 0 {
            slots[zeroSlot].val = value
            return false
        }
        if (count &+ 1) &* 8 > (mask &+ 1) &* 7 {
            grow()
        }
        // Key 0 is absent, so every slot holding key 0 is empty.
        let s = slots
        let m = mask
        var i = 0  // home(0) == 0
        while s[i].key != 0 { i = (i &+ 1) & m }
        s[i] = Slot(0, value)
        zeroSlot = i
        count &+= 1
        return true
    }

    // First free slot on the probe sequence of a nonzero key known to be absent.
    @inline(__always)
    private func findEmpty(_ key: Int64) -> Int {
        let s = slots
        let m = mask
        let z = zeroSlot
        var i = home(key)
        while s[i].key != 0 || i == z { i = (i &+ 1) & m }
        return i
    }

    @inline(never)
    private func grow() {
        let old = slots
        let oldCap = mask &+ 1
        let newCap = oldCap &* 2
        let s = HashMap.allocTable(newCap)
        let m = newCap &- 1
        let sh = shift &- 1
        // Re-insert nonzero keys. Walking the old table in order makes the new
        // home slots (almost) increasing, so the writes stream through memory.
        var j = 0
        while j < oldCap {
            let e = old[j]
            if e.key != 0 {
                var i = Int(truncatingIfNeeded:
                    (UInt64(bitPattern: e.key) &* 0x9E37_79B9_7F4A_7C15) &>> sh)
                while s[i].key != 0 { i = (i &+ 1) & m }
                s[i] = e
            }
            j &+= 1
        }
        var z = -1
        if zeroSlot >= 0 {
            let v = old[zeroSlot].val
            var i = 0
            while s[i].key != 0 { i = (i &+ 1) & m }
            s[i] = Slot(0, v)
            z = i
        }
        free(old)
        slots = s
        mask = m
        shift = sh
        zeroSlot = z
    }

    // MARK: - remove

    @inline(__always)
    func remove(_ key: Int64) -> Bool {
        let s = slots
        let m = mask
        var i: Int
        if key == 0 {
            i = zeroSlot
            if i < 0 { return false }
            zeroSlot = -1
        } else {
            i = home(key)
            while true {
                let k = s[i].key
                if k == key { break }
                if k == 0 && i != zeroSlot { return false }
                i = (i &+ 1) & m
            }
        }
        count &-= 1
        backShift(i)
        return true
    }

    // Close the hole at `hole` by shifting later entries of the cluster back.
    @inline(__always)
    private func backShift(_ start: Int) {
        let s = slots
        let m = mask
        let sh = shift
        var hole = start
        var j = (start &+ 1) & m
        while true {
            let e = s[j]
            if e.key == 0 {
                if j != zeroSlot { break }
                // The key-0 entry: its home is slot 0.
                if (j & m) >= ((j &- hole) & m) {
                    s[hole] = e
                    zeroSlot = hole
                    hole = j
                }
            } else {
                let h = Int(truncatingIfNeeded:
                    (UInt64(bitPattern: e.key) &* 0x9E37_79B9_7F4A_7C15) &>> sh)
                if ((j &- h) & m) >= ((j &- hole) & m) {
                    s[hole] = e
                    hole = j
                }
            }
            j = (j &+ 1) & m
        }
        s[hole] = Slot(0, 0)
    }

    // MARK: - scan

    func scan(_ outKeys: UnsafeMutablePointer<Int64>,
              _ outVals: UnsafeMutablePointer<Int64>) -> Int {
        let s = slots
        let z = zeroSlot
        let target = z >= 0 ? count &- 1 : count
        var n = 0
        var i = 0
        // Branchless compaction: always write the slot at position n, advance
        // n only for occupied slots. n < target keeps every write in bounds,
        // and target nonzero-key entries remain ahead while n < target.
        while n < target {
            let e = s[i]
            outKeys[n] = e.key
            outVals[n] = e.val
            n &+= e.key != 0 ? 1 : 0
            i &+= 1
        }
        if z >= 0 {
            outKeys[n] = 0
            outVals[n] = s[z].val
            n &+= 1
        }
        return n
    }
}
