From c9bd4807e59b9e32794c52a02cec43b71c40346b Mon Sep 17 00:00:00 2001 From: cinnaboot Date: Mon, 18 Oct 2021 11:32:43 -0400 Subject: [PATCH] add FNV hashing algorithm --- include/util.h | 9 +++++++++ src/util.cpp | 19 +++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/include/util.h b/include/util.h index e869632..14ad4ad 100644 --- a/include/util.h +++ b/include/util.h @@ -82,6 +82,15 @@ const char* utilBaseName(const char* path_str); // NOTE: returns true if the first 'sz' characters from each string match bool utilMatchPrefix(const char* lhs, const char* rhs, int sz); +//----------------- +// Hashing + +// NOTE: FNV1a hashing algorithm http://www.isthe.com/chongo/tech/comp/fnv/ +#define FNV1_64_INIT ((uint64_t) 0xcbf29ce484222325ULL) +#define FNV_64_PRIME ((uint64_t) 0x100000001b3ULL) +uint64_t +utilFNV64a_str(char *str, uint64_t hval = FNV1_64_INIT); + //----------------- // Memory allocation diff --git a/src/util.cpp b/src/util.cpp index d7974ec..216951f 100644 --- a/src/util.cpp +++ b/src/util.cpp @@ -58,6 +58,25 @@ utilMatchPrefix(const char* lhs, const char* rhs, int sz) return (rc >= 0); } +//----------------- +// Hashing + +uint64_t +utilFNV64a_str(char* str, uint64_t hval) +{ + unsigned char* s = (unsigned char *)str; // unsigned string + + // FNV-1a hash each octet of the string + while (*s) { + // xor the bottom with the current octet + hval ^= (uint64_t)*s++; + // multiply by the 64 bit FNV magic prime mod 2^64 + hval *= FNV_64_PRIME; + } + + return hval; +} + //----------------- // Memory allocation