const std = @import("std");

const EMPTY_KEY: i64 = 0;
const NO_SENTINEL: usize = std.math.maxInt(usize);
const FIB_MULT: u64 = 0x9E3779B97F4A7C15;
const INITIAL_CAPACITY: usize = 16;
const INITIAL_SHIFT: u6 = 60; // 64 - log2(16)

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

// Static all-zero placeholder table used before the first insert so that
// `init` never allocates and `get`/`remove` need no null-pointer check.
// Never written to.
var empty_table: [INITIAL_CAPACITY]Slot = @splat(.{ .key = EMPTY_KEY, .val = 0 });

pub const HashMap = struct {
    slots: [*]Slot,
    mask: usize,
    shift: u6,
    count: usize,
    max_len: usize,
    sentinel_slot: usize,
    allocator: std.mem.Allocator,

    pub fn init(allocator: std.mem.Allocator) HashMap {
        return .{
            .slots = &empty_table,
            .mask = INITIAL_CAPACITY - 1,
            .shift = INITIAL_SHIFT,
            .count = 0,
            .max_len = 0,
            .sentinel_slot = NO_SENTINEL,
            .allocator = allocator,
        };
    }

    pub fn deinit(self: *HashMap) void {
        if (self.max_len != 0) {
            self.allocator.free(self.slots[0 .. self.mask + 1]);
            self.slots = &empty_table;
            self.mask = INITIAL_CAPACITY - 1;
            self.shift = INITIAL_SHIFT;
            self.count = 0;
            self.max_len = 0;
            self.sentinel_slot = NO_SENTINEL;
        }
    }

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

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

    inline fn homeWithShift(key: i64, shift: u6) usize {
        const u: u64 = @bitCast(key);
        return @intCast((u *% FIB_MULT) >> shift);
    }

    inline fn home(self: *const HashMap, key: i64) usize {
        return homeWithShift(key, self.shift);
    }

    pub fn get(self: *const HashMap, key: i64) ?i64 {
        if (key == EMPTY_KEY) {
            @branchHint(.unlikely);
            const ss = self.sentinel_slot;
            if (ss != NO_SENTINEL) return self.slots[ss].val;
            return null;
        }
        const slots = self.slots;
        const mask = self.mask;
        const ss = self.sentinel_slot;
        var idx = self.home(key);
        while (true) {
            const k = slots[idx].key;
            if (k == key) return slots[idx].val;
            if (k == EMPTY_KEY) {
                if (idx != ss) {
                    @branchHint(.likely);
                    return null;
                }
            }
            idx = (idx + 1) & mask;
        }
    }

    pub fn insert(self: *HashMap, key: i64, value: i64) std.mem.Allocator.Error!bool {
        if (key == EMPTY_KEY) {
            @branchHint(.unlikely);
            return self.insertSentinel(value);
        }
        const slots = self.slots;
        const mask = self.mask;
        const ss = self.sentinel_slot;
        var idx = self.home(key);
        while (true) {
            const k = slots[idx].key;
            if (k == key) {
                slots[idx].val = value;
                return false;
            }
            if (k == EMPTY_KEY) {
                if (idx != ss) {
                    @branchHint(.likely);
                    if (self.count == self.max_len) {
                        @branchHint(.unlikely);
                        try self.grow();
                        self.insertNewAfterGrow(key, value);
                        return true;
                    }
                    slots[idx] = .{ .key = key, .val = value };
                    self.count += 1;
                    return true;
                }
            }
            idx = (idx + 1) & mask;
        }
    }

    noinline fn insertSentinel(self: *HashMap, value: i64) std.mem.Allocator.Error!bool {
        const ss = self.sentinel_slot;
        if (ss != NO_SENTINEL) {
            self.slots[ss].val = value;
            return false;
        }
        if (self.count == self.max_len) {
            try self.grow();
        }
        const slots = self.slots;
        const mask = self.mask;
        var idx: usize = 0; // home(0) == 0
        while (slots[idx].key != EMPTY_KEY) {
            idx = (idx + 1) & mask;
        }
        slots[idx] = .{ .key = EMPTY_KEY, .val = value };
        self.sentinel_slot = idx;
        self.count += 1;
        return true;
    }

    fn insertNewAfterGrow(self: *HashMap, key: i64, value: i64) void {
        const slots = self.slots;
        const mask = self.mask;
        const ss = self.sentinel_slot;
        var idx = self.home(key);
        while (slots[idx].key != EMPTY_KEY or idx == ss) {
            idx = (idx + 1) & mask;
        }
        slots[idx] = .{ .key = key, .val = value };
        self.count += 1;
    }

    noinline fn grow(self: *HashMap) std.mem.Allocator.Error!void {
        @branchHint(.cold);
        if (self.max_len == 0) {
            const new_slots = try self.allocator.alloc(Slot, INITIAL_CAPACITY);
            @memset(std.mem.sliceAsBytes(new_slots), 0);
            self.slots = new_slots.ptr;
            self.mask = INITIAL_CAPACITY - 1;
            self.shift = INITIAL_SHIFT;
            self.max_len = INITIAL_CAPACITY - (INITIAL_CAPACITY >> 3);
            return;
        }

        const old_cap = self.mask + 1;
        const new_cap = old_cap << 1;
        const new_mask = new_cap - 1;
        const new_shift: u6 = self.shift - 1;

        const new_slots_slice = try self.allocator.alloc(Slot, new_cap);
        @memset(std.mem.sliceAsBytes(new_slots_slice), 0);
        const new_slots = new_slots_slice.ptr;
        const old_slots = self.slots;

        if (old_cap >= 1024) {
            // Because home(k) uses the top bits of the hash, doubling maps
            // slot `i` to roughly `2 * i` in `new_slots`. Prefetching one
            // 128-byte cache line ahead every 4 old slots crosses 16 KB page
            // boundaries cleanly without extra hash work.
            var i: usize = 0;
            const pf_limit = old_cap - 64;
            while (i < pf_limit) : (i += 4) {
                @prefetch(&new_slots[(i << 1) + 128], .{ .rw = .write, .locality = 1, .cache = .data });
                inline for (0..4) |k| {
                    const s = old_slots[i + k];
                    if (s.key != EMPTY_KEY) {
                        var idx = homeWithShift(s.key, new_shift);
                        while (new_slots[idx].key != EMPTY_KEY) {
                            idx = (idx + 1) & new_mask;
                        }
                        new_slots[idx] = s;
                    }
                }
            }
            while (i < old_cap) : (i += 1) {
                const s = old_slots[i];
                if (s.key != EMPTY_KEY) {
                    var idx = homeWithShift(s.key, new_shift);
                    while (new_slots[idx].key != EMPTY_KEY) {
                        idx = (idx + 1) & new_mask;
                    }
                    new_slots[idx] = s;
                }
            }
        } else {
            for (0..old_cap) |i| {
                const s = old_slots[i];
                if (s.key != EMPTY_KEY) {
                    var idx = homeWithShift(s.key, new_shift);
                    while (new_slots[idx].key != EMPTY_KEY) {
                        idx = (idx + 1) & new_mask;
                    }
                    new_slots[idx] = s;
                }
            }
        }

        if (self.sentinel_slot != NO_SENTINEL) {
            @branchHint(.unlikely);
            const sv = old_slots[self.sentinel_slot].val;
            var idx: usize = 0; // home(0) == 0
            while (new_slots[idx].key != EMPTY_KEY) {
                idx = (idx + 1) & new_mask;
            }
            new_slots[idx] = .{ .key = EMPTY_KEY, .val = sv };
            self.sentinel_slot = idx;
        }

        self.allocator.free(old_slots[0..old_cap]);
        self.slots = new_slots;
        self.mask = new_mask;
        self.shift = new_shift;
        self.max_len = new_cap - (new_cap >> 3);
    }

    pub fn remove(self: *HashMap, key: i64) bool {
        if (key == EMPTY_KEY) {
            @branchHint(.unlikely);
            return self.removeSentinel();
        }
        const slots = self.slots;
        const mask = self.mask;
        const ss = self.sentinel_slot;
        var idx = self.home(key);
        while (true) {
            const k = slots[idx].key;
            if (k == key) {
                self.backwardShiftDelete(idx);
                return true;
            }
            if (k == EMPTY_KEY) {
                if (idx != ss) {
                    @branchHint(.likely);
                    return false;
                }
            }
            idx = (idx + 1) & mask;
        }
    }

    noinline fn removeSentinel(self: *HashMap) bool {
        const ss = self.sentinel_slot;
        if (ss == NO_SENTINEL) return false;
        self.sentinel_slot = NO_SENTINEL;
        self.backwardShiftDelete(ss);
        return true;
    }

    inline fn backwardShiftDelete(self: *HashMap, start_hole: usize) void {
        const slots = self.slots;
        const mask = self.mask;
        const shift = self.shift;
        var ss = self.sentinel_slot;
        var hole = start_hole;
        var cur = (hole + 1) & mask;
        while (true) {
            const k = slots[cur].key;
            if (k == EMPTY_KEY) {
                if (cur != ss) {
                    @branchHint(.likely);
                    break;
                }
                // Sentinel key 0 has home(0) == 0, so ((hole - 0) & mask) < ((cur - 0) & mask)
                // simplifies directly to `hole < cur`.
                if (hole < cur) {
                    slots[hole] = slots[cur];
                    ss = hole;
                    self.sentinel_slot = hole;
                    hole = cur;
                }
            } else {
                const h = homeWithShift(k, shift);
                if (((hole -% h) & mask) < ((cur -% h) & mask)) {
                    slots[hole] = slots[cur];
                    hole = cur;
                }
            }
            cur = (cur + 1) & mask;
        }
        slots[hole].key = EMPTY_KEY;
        self.count -= 1;
    }

    pub fn scan(self: *const HashMap, out_keys: []i64, out_vals: []i64) usize {
        const target = self.count;
        if (target == 0) return 0;

        const slots = self.slots;
        const ok = out_keys.ptr;
        const ov = out_vals.ptr;
        var out: usize = 0;

        if (self.sentinel_slot != NO_SENTINEL) {
            @branchHint(.unlikely);
            ok[0] = EMPTY_KEY;
            ov[0] = slots[self.sentinel_slot].val;
            out = 1;
        }

        // Branchless 4x-unrolled compaction. Whenever `out + 4 <= target`,
        // at least 4 non-empty slots remain in `slots[i..cap]`, so both
        // `slots[i..i+4]` and `ok/ov[out..out+4]` are strictly in bounds.
        var i: usize = 0;
        while (out + 4 <= target) : (i += 4) {
            const s0 = slots[i];
            const s1 = slots[i + 1];
            const s2 = slots[i + 2];
            const s3 = slots[i + 3];

            const b0: usize = @intFromBool(s0.key != EMPTY_KEY);
            const b1: usize = @intFromBool(s1.key != EMPTY_KEY);
            const b2: usize = @intFromBool(s2.key != EMPTY_KEY);
            const b3: usize = @intFromBool(s3.key != EMPTY_KEY);

            const p01 = b0 + b1;
            const p23 = b2 + b3;

            const o1 = out + b0;
            const o2 = out + p01;
            const o3 = o2 + b2;

            ok[out] = s0.key;
            ov[out] = s0.val;
            ok[o1] = s1.key;
            ov[o1] = s1.val;
            ok[o2] = s2.key;
            ov[o2] = s2.val;
            ok[o3] = s3.key;
            ov[o3] = s3.val;

            out += p01 + p23;
        }

        while (out < target) : (i += 1) {
            const s = slots[i];
            ok[out] = s.key;
            ov[out] = s.val;
            out += @intFromBool(s.key != EMPTY_KEY);
        }

        return target;
    }
};
