blob: 9d4d8dd5c98ad64b8911b6e17d5842baff381e74 (
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
|
/* SPDX-License-Identifier: MIT */
/**
* hash.h - implementations of the FNV1a hashing algorithm.
*
* Copyright (c) 2022-2023 - Yaroslav de la Peña Smirnov
*/
#ifndef HMAP_HASH_H
#define HMAP_HASH_H
#include <inttypes.h>
#include <stdlib.h>
#if SIZE_MAX == 0xFFFFFFFF
/* size_t is 32bit */
static const size_t fnv_prime = 16777619u;
static const size_t fnv_offsetb = 2166136261u;
#elif SIZE_MAX == 0xFFFFFFFFFFFFFFFF
/* size_t is 64bit */
static const size_t fnv_prime = 1099511628211u;
static const size_t fnv_offsetb = 14695981039346656037u;
#endif
/**
* fnv1a_bytes_hash() - generic fnv1a hash function.
* @data: pointer to data to hash.
* @len: size of @data in bytes.
*
* Return: hash value.
*/
static inline size_t fnv1a_bytes_hash(const void *data, size_t len)
{
const char *bytes = (const char *)data;
size_t hash = fnv_offsetb;
for (size_t i = 0; i < len; i++) {
hash ^= bytes[i];
hash *= fnv_prime;
}
return hash;
}
/**
* fnv1a_str_hash() - fnv1a hash function for nul-terminated strings.
* @str: nul-terminated string of characters to hash.
*
* Return: hash value.
*/
static inline size_t fnv1a_str_hash(const char *str)
{
size_t hash = fnv_offsetb;
for (size_t i = 0; str[i]; i++) {
hash ^= str[i];
hash *= fnv_prime;
}
return hash;
}
#endif /* HMAP_HASH_H */
|