/*Licensed under MIT or Public Domain. See bottom of file for details. ferr_hash.h This is a collection of hashing functions that I use in various projects. It's mostly an effort to consolidate and clean the stuff I've scattered around my code! Included is an FNV-1a hash that I use often, plus a compile-time variant that can be great for avoiding runtime hashing costs. They don't match eachother, but I added a runtime variant that does match. Just in case. Works on strings and data chunks. Example usage: struct test_t { float x, y, z; }; const char *str = "test a hash!"; uint32_t h_const = hashc_constfnv32_string("test a hash!"); // Compile time: 3166176921 uint32_t h_dyn = hash_constfnv32_string(str); // Runtime: 3166176921 uint32_t h_fnv = hash_fnv32_string(str); // 1193034313 uint64_t h64_const = hashc_constfnv64_string("test a hash!"); // Compile time: 9942215223050522873 uint64_t h64_dyn = hash_constfnv64_string(str); // Runtime: 9942215223050522873 uint64_t h64_fnv = hash_fnv64_string(str); // 15918807425826589481 test_t tmp = { 10, 1, 10 }; uint32_t h_struct1 = hash_fnv32_data(&tmp, sizeof(test_t)); // 1650533608 test_t tmp2 = { 10, 1, 10 }; uint32_t h_struct2 = hash_fnv32_data(&tmp2, sizeof(test_t)); // 1650533608 */ #pragma once #include #include #ifdef __cplusplus #define FERR_HASH_DEFAULT(x) = x #else #define FERR_HASH_DEFAULT(x) #endif /////////////////////////////////////////// // FNV-1a hash! // /////////////////////////////////////////// // See: http://isthe.com/chongo/tech/comp/fnv/ // for details about FNV-1a #define HASH_FNV32_START 2166136261 #define HASH_FNV64_START 14695981039346656037UL uint64_t hash_fnv64_string(const char *string, uint64_t start_hash FERR_HASH_DEFAULT( HASH_FNV64_START )); uint64_t hash_fnv64_data (const void *data, size_t data_size, uint64_t start_hash FERR_HASH_DEFAULT( HASH_FNV64_START )); uint32_t hash_fnv32_string(const char *string, uint32_t start_hash FERR_HASH_DEFAULT( HASH_FNV32_START )); uint32_t hash_fnv32_data (const void *data, size_t data_size, uint32_t start_hash FERR_HASH_DEFAULT( HASH_FNV32_START )); /////////////////////////////////////////// // Compile time hash! // /////////////////////////////////////////// // // hash64c_constfnv_string and hash32c_constfnv_string execute at compile // time, so you don't have to worry about cost to calculate during runtime. // They're based on FNV-1a but don't produce the same results. They also have // a limit of 64 characters. Characters after that will be ignored. // See http://lolengine.net/blog/2011/12/20/cpp-constant-string-hash for // details about this implementation. // // You can also use hash32_constfnv_string or hash64_constfnv_string to run // the exact same hash at runtime, if you need to compare a dynamic string // with one built at compile time. It's slower than the regular fnv hash too. #ifndef hash32c_constfnv_string #define _h32_H1(s,i,x) (((x)^s[(i)