From c7aab077dfd9228eaf11149e4a87acddbb7507ce Mon Sep 17 00:00:00 2001 From: Martin Michalec Date: Fri, 6 Nov 2026 06:00:22 +0300 Subject: feat(hash): add hashing functions --- include/hash.h | 94 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 94 insertions(+) create mode 100644 include/hash.h (limited to 'include') diff --git a/include/hash.h b/include/hash.h new file mode 100644 index 0000000..4c26b46 --- /dev/null +++ b/include/hash.h @@ -0,0 +1,94 @@ +// hash.h --- hashing functions -*- C -*- +// +// Copyright (c) 2026 Martin Michalec +// +// SPDX-License-Identifier: MIT +// +// This file is part of COSMOS Codebase. +// +// Commentary: +// +// Code: + +#ifndef INCLUDED_COSMOS_HASH_H +#define INCLUDED_COSMOS_HASH_H + +#include "types.h" + +#ifndef HASH_NO_FEAT_CRC_32 + +#define HASH_CRC_32_INIT 0xffffffff + +u32 hash_crc_32_update (u32 crc, const void *buf, usz len); + +static inline u32 +hash_crc_32_final (u32 crc) +{ + return crc ^ 0xffffffff; +} + +static inline u32 +hash_crc_32 (const void *buf, usz len) +{ + return hash_crc_32_final (hash_crc_32_update (HASH_CRC_32_INIT, buf, len)); +} + +#endif // HASH_NO_FEAT_CRC_32 + +#ifndef HASH_NO_FEAT_FNV1A_32 + +#define HASH_FNV1A_32_INIT 0x811c9dc5 +#define HASH_FNV1A_32_PRIME 0x01000193 + +static inline u32 +hash_fnv1a_32_update (u32 hash, const void *buf, usz sz) +{ + const u8 *ptr = buf; + const u8 *end = ptr + sz; + + for (; ptr < end; ptr++) { + hash ^= *ptr; + hash *= HASH_FNV1A_32_PRIME; + } + + return hash; +} + +static inline u32 +hash_fnv1a_32 (const void *buf, usz sz) +{ + return hash_fnv1a_32_update (HASH_FNV1A_32_INIT, buf, sz); +} + +#endif // HASH_NO_FEAT_FNV1A_32 + +#ifndef HASH_NO_FEAT_FNV1A_64 + +#define HASH_FNV1A_64_INIT 0xcbf29ce484222325 +#define HASH_FNV1A_64_PRIME 0x00000100000001b3 + +static inline u64 +hash_fnv1a_64_update (u64 h, const void *buf, usz sz) +{ + const u8 *p = (const u8 *) buf; + const u8 *end = p + sz; + + while (p < end) { + h ^= *p++; + h *= HASH_FNV1A_64_PRIME; + } + + return h; +} + +static inline u64 +hash_fnv1a_64 (const void *buf, usz sz) +{ + return hash_fnv1a_64_update (HASH_FNV1A_64_INIT, buf, sz); +} + +#endif // HASH_NO_FEAT_FNV1A_64 + +#endif // INCLUDED_COSMOS_HASH_H + +// hash.h ends here -- cgit v1.3.1