/* 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 */