Derive-C
Loading...
Searching...
No Matches
hashers.h
Go to the documentation of this file.
1
3
4#pragma once
5#include <stddef.h>
6#include <stdint.h>
7#include <string.h>
8
10
12#define ALWAYS_COLLIDE(type) \
13 static size_t hash_always_collide_##type(type const* key) { return 0; }
14
17#define ID(type) \
18 static size_t hash_id_##type(type const* key) { \
19 _Static_assert(sizeof(type) <= sizeof(size_t), \
20 "ID hashing only supports up to size_t integers"); \
21 return (size_t)(*key); \
22 }
23
27// JUSTIFY: Casting signed to unsigned. This is just a hash, and signed->unsigned is not UB.
28#define MURMURHASH_3_FMIx64(type) \
29 static size_t hash_murmurhash3_##type(type const* key) { \
30 _Static_assert(sizeof(type) <= sizeof(uint64_t), \
31 "MurmurHash3 only supports up to 64-bit integers"); \
32 return (size_t)derive_c_fmix64((uint64_t)(*key)); \
33 }
34
35// clang-format off
36#define INT_HASHERS(_apply) \
37 _apply(int8_t ) \
38 _apply(int16_t ) \
39 _apply(int32_t ) \
40 _apply(int64_t ) \
41 _apply(uint8_t ) \
42 _apply(uint16_t) \
43 _apply(uint32_t) \
44 _apply(uint64_t)
45// clang-format on
46
50
51#undef INT_HASHERS
52#undef ALWAYS_COLLIDE
53#undef ID
54#undef MURMURHASH_3_FMIx64
55
56#define MURMURHASH_DEFAULT_SEED 0x9747b28c
57
58size_t hash_murmurhash_string(const char* str) {
59 return derive_c_murmurhash(str, (int)strlen(str), MURMURHASH_DEFAULT_SEED);
60}
61
62// clang-format off
63#define STRING_SIZES(_apply) \
64 _apply(1) \
65 _apply(2) \
66 _apply(3) \
67 _apply(4) \
68 _apply(5) \
69 _apply(6) \
70 _apply(7) \
71 _apply(8) // clang-format on
72
73#define MURMURHASH_STRING_FIXED_SIZE(size) \
74 static size_t hash_murmurhash_string_##size(const char str[size]) { \
75 return derive_c_murmurhash(str, size, MURMURHASH_DEFAULT_SEED); \
76 }
77
79
80#undef MURMURHASH_STRING_FIXED_SIZE
81#undef MURMURHASH_DEFAULT_SEED
82
83static inline size_t hash_combine(size_t seed, size_t h) {
84 // 0x9e3779b97f4a7c15 is 64-bit fractional part of the golden ratio;
85 // “+ (seed<<6) + (seed>>2)” mixes seed’s bits
86 return seed ^ (h + 0x9e3779b97f4a7c15ULL + (seed << 6) + (seed >> 2));
87}
#define MURMURHASH_3_FMIx64(type)
Definition hashers.h:28
#define INT_HASHERS(_apply)
Definition hashers.h:36
#define MURMURHASH_STRING_FIXED_SIZE(size)
Definition hashers.h:73
size_t hash_murmurhash_string(const char *str)
Definition hashers.h:58
#define MURMURHASH_DEFAULT_SEED
Definition hashers.h:56
#define ALWAYS_COLLIDE(type)
The worst possible hash, for testing purposes.
Definition hashers.h:12
#define STRING_SIZES(_apply)
Definition hashers.h:63
#define ID(type)
Definition hashers.h:17
static size_t hash_combine(size_t seed, size_t h)
Definition hashers.h:83
size_t derive_c_murmurhash(const void *key, int len, uint32_t seed)
Definition murmurhash.h:346