summary refs log tree commit diff
path: root/ihash.h
blob: 242e97c8a72699046be7e3b3eaa7fba4f683dbb7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#ifndef IHASH_H
#define IHASH_H

#include <stdlib.h>
#include <stdint.h>
#include <ctype.h>

#include "dynarr.h"
#include "str.h"

#ifndef IHASH_SLOTS
#define IHASH_SLOTS 8192
#endif

typedef uint64_t hash_t;

typedef struct {
	intptr_t key;
	void *value;
	hash_t hash;
} IntHashEntry;

typedef struct {
	DYNARR(IntHashEntry) entries;
} IntHashSlot;

typedef struct {
	IntHashSlot slots[IHASH_SLOTS];
} IntHashTable;

hash_t ihash(intptr_t s);
void ihash_init(IntHashTable *h);
void ihash_free(IntHashTable *h);
void *ihash_get(IntHashTable *h, intptr_t key);
void ihash_put(IntHashTable *h, intptr_t key, void *value);
IntHashEntry *ihash_find(IntHashTable *h, intptr_t key);

#ifdef IHASH_IMPL

/* murmur64 integer hash */

hash_t ihash(intptr_t h) {
	h *= h >> 33;
	h *= 0xff51afd7ed558ccdL;
	h *= h >> 33;
	h *= 0xc4ceb9fe1a85ec53L;
	h *= h >> 33;
	return h;
}

/* hash table */

void ihash_init(IntHashTable *h) {
	*h = (IntHashTable) { 0 };
}

void ihash_free(IntHashTable *h) {
	for (unsigned i = 0; i < IHASH_SLOTS; i++) {
		IntHashSlot *s = &h->slots[i];
		if (!s->entries) continue;
		DA_FREE(s->entries);
	}
}

static inline int ihash_entry_match(IntHashEntry *h, intptr_t s, hash_t ihash) {
	return s == ihash;
}

static inline IntHashEntry *ihash_find_hashed(IntHashTable *h, intptr_t key, hash_t k) {
	size_t i = k & (IHASH_SLOTS - 1);
	if (h->slots[i].entries) {
		DA_FOR(h->slots[i].entries, e) {
			if (ihash_entry_match(e, key, k)) {
				return e;
			}
		}
	}
	return NULL;
}

IntHashEntry *ihash_find(IntHashTable *h, intptr_t key) {
	return ihash_find_hashed(h, key, ihash(key));
}

void *ihash_get(IntHashTable *h, intptr_t key) {
	IntHashEntry *e = ihash_find(h, key);
	return e ? e->value : NULL;
}

void ihash_put(IntHashTable *h, intptr_t key, void *value) {
	hash_t keyh = ihash(key);
	IntHashEntry *e = ihash_find_hashed(h, key, keyh);
	if (e) {
		e->value = value;
	} else {
		hash_t keyi = keyh & (IHASH_SLOTS - 1);
		if (!h->slots[keyi].entries) {
			DA_INIT(h->slots[keyi].entries);
		}
		DA_PUSH(h->slots[keyi].entries, (IntHashEntry) {
			.key = key,
			.value = value,
			.hash = keyh
		});
	}
}

#endif
#endif