On this page
  1. Hash Table from Scratch
  2. Contents
  3. Open-Addressing Linear-Probing Map (FNV-1a)

Hash Table from Scratch

Prev: Dynamic Array Implementation | Up: tutorials | Next: Arena Allocator Pattern
Rel: Linear & Hashed Structures, stdlib.h & string.h
Ref: Wikipedia — Open Addressing
Tags: #public #prog #c #tutorials #dsa #hash-table


Contents


Open-Addressing Linear-Probing Map (FNV-1a)

A minimal, cache-friendly string-to-int hash map using power-of-two capacity (fast bitmasking h & (cap - 1)) and 64-bit FNV-1a hashing:

#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct {
    const char *key;
    int         val;
} Entry;

typedef struct {
    Entry *entries;
    size_t cap;
    size_t len;
} StrMap;

static uint64_t fnv1a(const char *s) {
    uint64_t h = 14695981039346656037ULL;
    for (const unsigned char *p = (const unsigned char *)s; *p; p++) {
        h ^= *p;
        h *= 1099511628211ULL;
    }
    return h;
}

static bool strmap_init(StrMap *m, size_t cap_pow2) {
    m->entries = calloc(cap_pow2, sizeof(Entry));
    if (!m->entries) return false;
    m->cap = cap_pow2;
    m->len = 0;
    return true;
}

static bool strmap_set(StrMap *m, const char *key, int val) {
    size_t mask = m->cap - 1;
    size_t idx = (size_t)fnv1a(key) & mask;
    for (size_t i = 0; i < m->cap; i++) {
        Entry *e = &m->entries[(idx + i) & mask];
        if (!e->key || strcmp(e->key, key) == 0) {
            if (!e->key) m->len++;
            e->key = key;
            e->val = val;
            return true;
        }
    }
    return false;
}

static bool strmap_get(const StrMap *m, const char *key, int *out) {
    size_t mask = m->cap - 1;
    size_t idx = (size_t)fnv1a(key) & mask;
    for (size_t i = 0; i < m->cap; i++) {
        const Entry *e = &m->entries[(idx + i) & mask];
        if (!e->key) return false;
        if (strcmp(e->key, key) == 0) {
            *out = e->val;
            return true;
        }
    }
    return false;
}

int main(void) {
    StrMap m = {0};
    if (!strmap_init(&m, 16)) return 1;
    strmap_set(&m, "alpha", 10);
    strmap_set(&m, "beta", 20);
    int v = 0;
    if (strmap_get(&m, "beta", &v)) printf("beta=%d\n", v);
    free(m.entries);
    return 0;
}

Linked from

Related notes