From cb1a40859029f33184355475e51fec95afb79a73 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Yaroslav=20de=20la=20Pe=C3=B1a=20Smirnov?= Date: Sat, 22 Jul 2023 03:03:09 +0300 Subject: init Just some C wares; hmap, list, optional, unit tests. --- hmap/hash.h | 61 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 hmap/hash.h (limited to 'hmap/hash.h') 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 +#include + +#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 */ -- cgit v1.2.3