const std = @import("std");

// Open addressing, linear probing, backward-shift deletion.
//
// Slots are interleaved {key, value} pairs (16 bytes, 8 per 128-byte line).
// A slot whose key is EMPTY (0) is free, unless it is the one slot recorded
// in `special`, which holds the entry whose key really is 0.

const Slot = struct {
    key: i64,
    val: i64,
};

const EMPTY: i64 = 0;
const NONE: usize = std.math.maxInt(usize);
const MUL: u64 = 0x9E3779B97F4A7C15;
const INIT_CAP: usize = 16;

pub const HashMap = struct {
    slots: [*]Slot,
    mask: usize, // capacity - 1
    shift: u6, // 64 - log2(capacity)
    count: usize,
    special: usize, // slot index holding key EMPTY, or NONE
    allocated: bool,
    allocator: std.mem.Allocator,

    pub fn init(allocator: std.mem.Allocator) HashMap {
        return .{
            .slots = undefined,
            .mask = INIT_CAP - 1,
            .shift = 64 - 4,
            .count = 0,
            .special = NONE,
            .allocated = false,
            .allocator = allocator,
        };
    }

    pub fn deinit(self: *HashMap) void {
        if (self.allocated) {
            self.allocator.free(self.slots[0 .. self.mask + 1]);
            self.allocated = false;
        }
    }

    inline fn home(self: *const HashMap, key: i64) usize {
        return @intCast((@as(u64, @bitCast(key)) *% MUL) >> self.shift);
    }

    fn allocTable(self: *HashMap, cap: usize) std.mem.Allocator.Error![*]Slot {
        const mem = try self.allocator.alloc(Slot, cap);
        @memset(std.mem.sliceAsBytes(mem), 0); // EMPTY == 0
        return mem.ptr;
    }

    fn ensureAllocated(self: *HashMap) std.mem.Allocator.Error!void {
        if (!self.allocated) {
            self.slots = try self.allocTable(INIT_CAP);
            self.allocated = true;
        }
    }

    fn grow(self: *HashMap) std.mem.Allocator.Error!void {
        @branchHint(.cold);
        const old_cap = self.mask + 1;
        const new_cap = old_cap * 2;
        const new_slots = try self.allocTable(new_cap);
        const old = self.slots;
        const old_special = self.special;
        const new_mask = new_cap - 1;
        const new_shift: u6 = self.shift - 1;

        // Re-insert all entries with non-EMPTY keys. Walking the old table in
        // order produces (mostly) increasing home slots in the new table.
        var i: usize = 0;
        while (i < old_cap) : (i += 1) {
            const s = old[i];
            if (s.key != EMPTY) {
                var j: usize = @intCast((@as(u64, @bitCast(s.key)) *% MUL) >> new_shift);
                while (new_slots[j].key != EMPTY) j = (j + 1) & new_mask;
                new_slots[j] = s;
            }
        }
        var new_special: usize = NONE;
        if (old_special != NONE) {
            var j: usize = @intCast((@as(u64, @bitCast(EMPTY)) *% MUL) >> new_shift);
            while (new_slots[j].key != EMPTY) j = (j + 1) & new_mask;
            new_slots[j].val = old[old_special].val;
            new_special = j;
        }

        self.allocator.free(old[0..old_cap]);
        self.slots = new_slots;
        self.mask = new_mask;
        self.shift = new_shift;
        self.special = new_special;
    }

    pub fn insert(self: *HashMap, key: i64, value: i64) std.mem.Allocator.Error!bool {
        if (!self.allocated) try self.ensureAllocated();
        if (key == EMPTY) {
            @branchHint(.unlikely);
            return self.insertSpecial(value);
        }
        const slots = self.slots;
        const mask = self.mask;
        const special = self.special;
        var i = self.home(key);
        while (true) {
            const k = slots[i].key;
            if (k == key) {
                slots[i].val = value;
                return false;
            }
            if (k == EMPTY and i != special) break;
            i = (i + 1) & mask;
        }
        // Key absent; slot i is free.
        if ((self.count + 1) * 8 > (mask + 1) * 7) {
            @branchHint(.unlikely);
            try self.grow();
            const s2 = self.slots;
            const m2 = self.mask;
            const sp2 = self.special;
            i = self.home(key);
            while (s2[i].key != EMPTY or i == sp2) i = (i + 1) & m2;
            s2[i] = .{ .key = key, .val = value };
        } else {
            slots[i] = .{ .key = key, .val = value };
        }
        self.count += 1;
        return true;
    }

    fn insertSpecial(self: *HashMap, value: i64) std.mem.Allocator.Error!bool {
        @branchHint(.cold);
        if (self.special != NONE) {
            self.slots[self.special].val = value;
            return false;
        }
        if ((self.count + 1) * 8 > (self.mask + 1) * 7) try self.grow();
        const slots = self.slots;
        const mask = self.mask;
        var i = self.home(EMPTY);
        while (slots[i].key != EMPTY) i = (i + 1) & mask;
        slots[i].val = value;
        self.special = i;
        self.count += 1;
        return true;
    }

    pub fn get(self: *const HashMap, key: i64) ?i64 {
        if (key == EMPTY) {
            @branchHint(.unlikely);
            if (self.special != NONE) return self.slots[self.special].val;
            return null;
        }
        if (!self.allocated) return null;
        const slots = self.slots;
        const mask = self.mask;
        var i = self.home(key);
        while (true) {
            const s = &slots[i];
            const k = s.key;
            if (k == key) return s.val;
            if (k == EMPTY and i != self.special) return null;
            i = (i + 1) & mask;
        }
    }

    pub fn remove(self: *HashMap, key: i64) bool {
        if (!self.allocated) return false;
        var i: usize = undefined;
        if (key == EMPTY) {
            @branchHint(.unlikely);
            if (self.special == NONE) return false;
            i = self.special;
            self.special = NONE;
        } else {
            const slots = self.slots;
            const mask = self.mask;
            const special = self.special;
            i = self.home(key);
            while (true) {
                const k = slots[i].key;
                if (k == key) break;
                if (k == EMPTY and i != special) return false;
                i = (i + 1) & mask;
            }
        }
        self.count -= 1;
        self.backshift(i);
        return true;
    }

    // Close the hole at `hole` by shifting later entries of the cluster back.
    inline fn backshift(self: *HashMap, hole_in: usize) void {
        const slots = self.slots;
        const mask = self.mask;
        const shift = self.shift;
        var hole = hole_in;
        var j = (hole + 1) & mask;
        while (true) {
            const s = slots[j];
            if (s.key == EMPTY) {
                if (j != self.special) break;
                // The key-0 entry: its home is home(0).
                const h: usize = @intCast((@as(u64, @bitCast(EMPTY)) *% MUL) >> shift);
                if (((j -% h) & mask) >= ((j -% hole) & mask)) {
                    slots[hole] = s;
                    self.special = hole;
                    hole = j;
                }
            } else {
                const h: usize = @intCast((@as(u64, @bitCast(s.key)) *% MUL) >> shift);
                if (((j -% h) & mask) >= ((j -% hole) & mask)) {
                    slots[hole] = s;
                    hole = j;
                }
            }
            j = (j + 1) & mask;
        }
        slots[hole].key = EMPTY;
    }

    pub fn scan(self: *const HashMap, out_keys: []i64, out_vals: []i64) usize {
        if (self.count == 0) return 0;
        const slots = self.slots;
        const target = self.count - @intFromBool(self.special != NONE);
        const ok = out_keys.ptr;
        const ov = out_vals.ptr;
        var c: usize = 0;
        var i: usize = 0;
        // Branchless compaction: writes at index c are always < target while
        // c < target, so they stay in bounds.
        while (c < target) : (i += 1) {
            const s = slots[i];
            ok[c] = s.key;
            ov[c] = s.val;
            c += @intFromBool(s.key != EMPTY);
        }
        if (self.special != NONE) {
            ok[c] = EMPTY;
            ov[c] = slots[self.special].val;
            c += 1;
        }
        return c;
    }

    pub fn len(self: *const HashMap) usize {
        return self.count;
    }

    pub fn capacity(self: *const HashMap) usize {
        return self.mask + 1;
    }
};
