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