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