#include "hashmap.h"

#include <stdlib.h>

#define INITIAL_CAP   16u
#define INITIAL_SHIFT 60u
#define HASH_MULT     0x9E3779B97F4A7C15ULL
#define NO_SLOT       (~(size_t)0)

#if defined(__GNUC__) || defined(__clang__)
#define LIKELY(x)   __builtin_expect(!!(x), 1)
#define UNLIKELY(x) __builtin_expect(!!(x), 0)
#define NOINLINE    __attribute__((noinline))
#define COLD        __attribute__((noinline, cold))
#else
#define LIKELY(x)   (x)
#define UNLIKELY(x) (x)
#define NOINLINE
#define COLD
#endif

typedef struct {
    int64_t key;
    int64_t val;
} Slot;

struct hashmap {
    Slot    *slots;
    size_t   mask;
    size_t   zero_slot;
    uint64_t shift;
    size_t   len;
    size_t   max_load;
    size_t   cap;
};

static inline size_t hash_slot(int64_t key, uint64_t shift) {
    return (size_t)(((uint64_t)key * HASH_MULT) >> shift);
}

hashmap *hashmap_new(void) {
    hashmap *m = (hashmap *)malloc(sizeof(hashmap));
    if (UNLIKELY(!m)) abort();

    Slot *slots = (Slot *)calloc(INITIAL_CAP, sizeof(Slot));
    if (UNLIKELY(!slots)) abort();

    m->slots     = slots;
    m->mask      = INITIAL_CAP - 1;
    m->zero_slot = NO_SLOT;
    m->shift     = INITIAL_SHIFT;
    m->len       = 0;
    m->max_load  = INITIAL_CAP - (INITIAL_CAP >> 3); /* 14 */
    m->cap       = INITIAL_CAP;
    return m;
}

void hashmap_free(hashmap *m) {
    if (!m) return;
    free(m->slots);
    free(m);
}

size_t hashmap_len(const hashmap *m) {
    return m->len;
}

size_t hashmap_capacity(const hashmap *m) {
    return m->cap;
}

static NOINLINE void hashmap_grow(hashmap *m) {
    size_t old_cap = m->cap;
    size_t new_cap = old_cap << 1;
    if (UNLIKELY(new_cap < old_cap)) abort();

    Slot * restrict new_slots = (Slot *)calloc(new_cap, sizeof(Slot));
    if (UNLIKELY(!new_slots)) abort();

    const Slot * restrict old_slots = m->slots;
    size_t new_mask    = new_cap - 1;
    uint64_t new_shift = m->shift - 1;
    size_t old_zslot   = m->zero_slot;

    for (size_t i = 0; i < old_cap; i++) {
        Slot s = old_slots[i];
        if (LIKELY(s.key != 0)) {
            size_t idx = hash_slot(s.key, new_shift);
            while (new_slots[idx].key != 0) {
                idx = (idx + 1) & new_mask;
            }
            new_slots[idx] = s;
        }
    }

    if (UNLIKELY(old_zslot != NO_SLOT)) {
        size_t idx = 0;
        while (new_slots[idx].key != 0) {
            idx = (idx + 1) & new_mask;
        }
        new_slots[idx].key = 0;
        new_slots[idx].val = old_slots[old_zslot].val;
        m->zero_slot = idx;
    }

    free(m->slots);
    m->slots    = new_slots;
    m->cap      = new_cap;
    m->mask     = new_mask;
    m->max_load = new_cap - (new_cap >> 3);
    m->shift    = new_shift;
}

static NOINLINE bool hashmap_grow_and_insert(hashmap *m, int64_t key, int64_t value) {
    hashmap_grow(m);

    Slot *slots  = m->slots;
    size_t mask  = m->mask;
    size_t zslot = m->zero_slot;
    size_t idx   = hash_slot(key, m->shift);
    while (slots[idx].key != 0 || UNLIKELY(idx == zslot)) {
        idx = (idx + 1) & mask;
    }
    slots[idx].key = key;
    slots[idx].val = value;
    m->len++;
    return true;
}

static COLD bool hashmap_insert_zero(hashmap *m, int64_t value) {
    size_t zslot = m->zero_slot;
    if (zslot != NO_SLOT) {
        m->slots[zslot].val = value;
        return false;
    }
    if (UNLIKELY(m->len >= m->max_load)) {
        hashmap_grow(m);
    }
    Slot *slots = m->slots;
    size_t mask = m->mask;
    size_t idx  = 0;
    while (slots[idx].key != 0) {
        idx = (idx + 1) & mask;
    }
    slots[idx].key = 0;
    slots[idx].val = value;
    m->zero_slot   = idx;
    m->len++;
    return true;
}

bool hashmap_insert(hashmap *m, int64_t key, int64_t value) {
    if (UNLIKELY(key == 0)) {
        return hashmap_insert_zero(m, value);
    }

    Slot *slots  = m->slots;
    size_t mask  = m->mask;
    size_t zslot = m->zero_slot;
    size_t idx   = hash_slot(key, m->shift);

    for (;;) {
        int64_t k = slots[idx].key;
        if (k == key) {
            slots[idx].val = value;
            return false;
        }
        if (k == 0) {
            if (LIKELY(idx != zslot)) {
                if (UNLIKELY(m->len >= m->max_load)) {
                    return hashmap_grow_and_insert(m, key, value);
                }
                slots[idx].key = key;
                slots[idx].val = value;
                m->len++;
                return true;
            }
        }
        idx = (idx + 1) & mask;
    }
}

bool hashmap_get(const hashmap *m, int64_t key, int64_t *value) {
    if (UNLIKELY(key == 0)) {
        size_t zslot = m->zero_slot;
        if (zslot == NO_SLOT) return false;
        *value = m->slots[zslot].val;
        return true;
    }

    const Slot *slots = m->slots;
    size_t mask       = m->mask;
    size_t zslot      = m->zero_slot;
    size_t idx        = hash_slot(key, m->shift);

    for (;;) {
        int64_t k = slots[idx].key;
        if (k == key) {
            *value = slots[idx].val;
            return true;
        }
        if (k == 0) {
            if (LIKELY(idx != zslot)) {
                return false;
            }
        }
        idx = (idx + 1) & mask;
    }
}

static inline void backward_shift(hashmap *m, size_t hole) {
    Slot *slots    = m->slots;
    size_t mask    = m->mask;
    size_t zslot   = m->zero_slot;
    uint64_t shift = m->shift;
    size_t cur     = hole;
    size_t dist    = 1;

    for (;;) {
        cur = (cur + 1) & mask;
        int64_t k = slots[cur].key;
        if (k == 0) {
            if (LIKELY(cur != zslot)) {
                slots[hole].key = 0;
                m->len--;
                return;
            }
            /* Entry at cur is key == 0, whose home slot is 0. */
            if (cur >= dist) {
                slots[hole].key = 0;
                slots[hole].val = slots[cur].val;
                m->zero_slot    = hole;
                zslot           = hole;
                hole            = cur;
                dist            = 1;
            } else {
                dist++;
            }
            continue;
        }
        size_t home = hash_slot(k, shift);
        if (((cur - home) & mask) >= dist) {
            slots[hole] = slots[cur];
            hole = cur;
            dist = 1;
        } else {
            dist++;
        }
    }
}

static COLD bool hashmap_remove_zero(hashmap *m) {
    size_t hole = m->zero_slot;
    if (hole == NO_SLOT) return false;
    m->zero_slot = NO_SLOT;
    backward_shift(m, hole);
    return true;
}

bool hashmap_remove(hashmap *m, int64_t key) {
    if (UNLIKELY(key == 0)) {
        return hashmap_remove_zero(m);
    }

    Slot *slots  = m->slots;
    size_t mask  = m->mask;
    size_t zslot = m->zero_slot;
    size_t idx   = hash_slot(key, m->shift);

    for (;;) {
        int64_t k = slots[idx].key;
        if (k == key) {
            backward_shift(m, idx);
            return true;
        }
        if (k == 0) {
            if (LIKELY(idx != zslot)) {
                return false;
            }
        }
        idx = (idx + 1) & mask;
    }
}

size_t hashmap_scan(const hashmap *m, int64_t *out_keys, int64_t *out_vals) {
    size_t len = m->len;
    if (UNLIKELY(len == 0)) return 0;

    const Slot * restrict slots = m->slots;
    int64_t * restrict ok       = out_keys;
    int64_t * restrict ov       = out_vals;

    size_t out   = 0;
    size_t zslot = m->zero_slot;
    if (UNLIKELY(zslot != NO_SLOT)) {
        ok[0] = 0;
        ov[0] = slots[zslot].val;
        out   = 1;
    }

    size_t i = 0;
    while (out + 4 <= len) {
        int64_t k0 = slots[i + 0].key, v0 = slots[i + 0].val;
        int64_t k1 = slots[i + 1].key, v1 = slots[i + 1].val;
        int64_t k2 = slots[i + 2].key, v2 = slots[i + 2].val;
        int64_t k3 = slots[i + 3].key, v3 = slots[i + 3].val;

        size_t c0  = (size_t)(k0 != 0);
        size_t c1  = (size_t)(k1 != 0);
        size_t c2  = (size_t)(k2 != 0);
        size_t c3  = (size_t)(k3 != 0);
        size_t c01 = c0 + c1;
        size_t c23 = c2 + c3;

        size_t o1 = out + c0;
        size_t o2 = out + c01;
        size_t o3 = o2 + c2;

        ok[out] = k0; ov[out] = v0;
        ok[o1]  = k1; ov[o1]  = v1;
        ok[o2]  = k2; ov[o2]  = v2;
        ok[o3]  = k3; ov[o3]  = v3;

        out += c01 + c23;
        i += 4;
    }

    while (out < len) {
        int64_t k = slots[i].key;
        int64_t v = slots[i].val;
        ok[out] = k;
        ov[out] = v;
        out += (size_t)(k != 0);
        i++;
    }

    return len;
}
