// Open-addressing hash map with linear probing and backward-shift deletion.
//
// Layout: one flat array of 16-byte slots {key, value}. Key 0 marks an empty
// slot. A real entry with key 0 lives in an ordinary slot whose index is
// remembered in `zslot_` (NONE if key 0 is absent); a slot with key 0 is
// treated as occupied exactly when its index equals `zslot_`.
#pragma once

#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <new>
#include <optional>

class HashMap {
    struct Slot {
        std::int64_t key;
        std::int64_t val;
    };

    static constexpr std::uint64_t MULT = 0x9E3779B97F4A7C15ULL;
    static constexpr std::size_t NONE = ~std::size_t(0);

    Slot* slots_;
    std::size_t mask_;
    std::size_t len_;
    std::size_t zslot_;  // slot index holding key 0, or NONE
    unsigned shift_;     // 64 - log2(capacity)

    static Slot* alloc(std::size_t cap) {
        void* p = std::calloc(cap, sizeof(Slot));
        if (!p) throw std::bad_alloc();
        return static_cast<Slot*>(p);
    }

    inline std::size_t home(std::int64_t k) const {
        return (std::size_t)(((std::uint64_t)k * MULT) >> shift_);
    }

    __attribute__((noinline)) void grow() {
        std::size_t old_cap = mask_ + 1;
        Slot* old = slots_;
        std::size_t new_cap = old_cap * 2;
        Slot* ns = alloc(new_cap);
        std::size_t nmask = new_cap - 1;
        unsigned nshift = shift_ - 1;
        for (std::size_t i = 0; i < old_cap; i++) {
            std::int64_t k = old[i].key;
            if (k == 0) continue;
            std::size_t j = (std::size_t)(((std::uint64_t)k * MULT) >> nshift);
            while (ns[j].key != 0) j = (j + 1) & nmask;
            ns[j] = old[i];
        }
        std::size_t nz = NONE;
        if (zslot_ != NONE) {
            std::int64_t v = old[zslot_].val;
            std::size_t j = 0;  // home(0) == 0
            while (ns[j].key != 0) j = (j + 1) & nmask;
            ns[j].val = v;
            nz = j;
        }
        std::free(old);
        slots_ = ns;
        mask_ = nmask;
        shift_ = nshift;
        zslot_ = nz;
    }

    inline bool needs_grow() const { return (len_ + 1) * 8 > (mask_ + 1) * 7; }

    // Find a free slot for a key known to be absent.
    inline std::size_t find_free(std::size_t i) const {
        const Slot* s = slots_;
        while (s[i].key != 0 || i == zslot_) i = (i + 1) & mask_;
        return i;
    }

    __attribute__((noinline)) bool insert_zero(std::int64_t value) {
        if (zslot_ != NONE) {
            slots_[zslot_].val = value;
            return false;
        }
        if (needs_grow()) grow();
        std::size_t i = find_free(0);
        slots_[i].val = value;
        zslot_ = i;
        len_++;
        return true;
    }

    inline void erase_at(std::size_t i) {
        Slot* s = slots_;
        const std::size_t mask = mask_;
        std::size_t j = i;
        for (;;) {
            j = (j + 1) & mask;
            std::int64_t k = s[j].key;
            if (k == 0 && j != zslot_) break;
            std::size_t h = home(k);
            if (((j - h) & mask) >= ((j - i) & mask)) {
                s[i] = s[j];
                if (__builtin_expect(j == zslot_, 0)) zslot_ = i;
                i = j;
            }
        }
        s[i].key = 0;
        len_--;
    }

public:
    HashMap() : slots_(alloc(16)), mask_(15), len_(0), zslot_(NONE), shift_(60) {}
    ~HashMap() { std::free(slots_); }
    HashMap(const HashMap&) = delete;
    HashMap& operator=(const HashMap&) = delete;

    bool insert(std::int64_t key, std::int64_t value) {
        if (__builtin_expect(key == 0, 0)) return insert_zero(value);
        Slot* s = slots_;
        const std::size_t mask = mask_;
        std::size_t i = home(key);
        for (;;) {
            std::int64_t k = s[i].key;
            if (k == key) {
                s[i].val = value;
                return false;
            }
            if (k == 0 && i != zslot_) break;
            i = (i + 1) & mask;
        }
        if (__builtin_expect(needs_grow(), 0)) {
            grow();
            i = find_free(home(key));
            s = slots_;
        }
        s[i].key = key;
        s[i].val = value;
        len_++;
        return true;
    }

    std::optional<std::int64_t> get(std::int64_t key) const {
        if (__builtin_expect(key == 0, 0)) {
            if (zslot_ == NONE) return std::nullopt;
            return slots_[zslot_].val;
        }
        const Slot* s = slots_;
        const std::size_t mask = mask_;
        std::size_t i = home(key);
        for (;;) {
            std::int64_t k = s[i].key;
            if (k == key) return s[i].val;
            if (k == 0 && i != zslot_) return std::nullopt;
            i = (i + 1) & mask;
        }
    }

    bool remove(std::int64_t key) {
        if (__builtin_expect(key == 0, 0)) {
            if (zslot_ == NONE) return false;
            std::size_t i = zslot_;
            zslot_ = NONE;
            erase_at(i);
            return true;
        }
        const Slot* s = slots_;
        const std::size_t mask = mask_;
        std::size_t i = home(key);
        for (;;) {
            std::int64_t k = s[i].key;
            if (k == key) break;
            if (k == 0 && i != zslot_) return false;
            i = (i + 1) & mask;
        }
        erase_at(i);
        return true;
    }

    std::size_t scan(std::int64_t* out_keys, std::int64_t* out_vals) const {
        const Slot* s = slots_;
        const std::size_t cap = mask_ + 1;
        const std::size_t target = len_ - (zslot_ != NONE ? 1 : 0);
        std::size_t c = 0;
        // Branchless compaction; stop once every nonzero key is written so we
        // never write past the caller's buffer.
        for (std::size_t i = 0; i < cap && c < target; i++) {
            std::int64_t k = s[i].key;
            out_keys[c] = k;
            out_vals[c] = s[i].val;
            c += (k != 0);
        }
        if (zslot_ != NONE) {
            out_keys[c] = 0;
            out_vals[c] = s[zslot_].val;
            c++;
        }
        return c;
    }

    std::size_t len() const { return len_; }
    std::size_t capacity() const { return mask_ + 1; }
};
