diff options
author | Yaroslav de la Peña Smirnov <yps@yaroslavps.com> | 2023-07-22 03:03:09 +0300 |
---|---|---|
committer | Yaroslav de la Peña Smirnov <yps@yaroslavps.com> | 2023-07-22 03:03:09 +0300 |
commit | cb1a40859029f33184355475e51fec95afb79a73 (patch) | |
tree | 5aea859d3a3e10ddd058beac9d6734d17979d560 /hmap/hash.h | |
download | c-wares-cb1a40859029f33184355475e51fec95afb79a73.tar.gz c-wares-cb1a40859029f33184355475e51fec95afb79a73.zip |
init
Just some C wares; hmap, list, optional, unit tests.
Diffstat (limited to 'hmap/hash.h')
-rw-r--r-- | hmap/hash.h | 61 |
1 files changed, 61 insertions, 0 deletions
diff --git a/hmap/hash.h b/hmap/hash.h new file mode 100644 index 0000000..9d4d8dd --- /dev/null +++ b/hmap/hash.h @@ -0,0 +1,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 */ |