Created
April 5, 2024 13:53
-
-
Save 3llena/3835ee8a3ed1c6adc1948fc5e6dd9979 to your computer and use it in GitHub Desktop.
fnv1 hash utilities
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#pragma once | |
namespace uti | |
{ | |
static constexpr std::uint32_t fnv1_basis = 0x811c9dc5; | |
static constexpr std::uint32_t fnv1_prime = 0x01000193; | |
[[ nodiscard ]] | |
constexpr std::uint32_t fnv1_hash_ct( const char* string, const std::uint32_t basis = fnv1_basis ) | |
{ | |
return ( string[0] == '\0' ) ? basis : fnv1_hash_ct( &string[1], ( string[0] ^ basis ) * fnv1_prime ); | |
} | |
[[ nodiscard ]] | |
constexpr std::uint32_t fnv1_hash_ct_w( const wchar_t* string, const std::uint32_t basis = fnv1_basis ) | |
{ | |
return ( string[0] == L'\0' ) ? basis : fnv1_hash_ct_w( &string[1], ( string[0] ^ basis ) * fnv1_prime ); | |
} | |
[[ nodiscard ]] | |
std::uint32_t fnv1_hash( const char* string ) | |
{ | |
auto fnv_ret = fnv1_basis; | |
auto fnv_len = std::strlen( string ); | |
for ( std::size_t idx{}; idx < fnv_len; idx++ ) | |
{ | |
fnv_ret ^= string[idx]; | |
fnv_ret *= fnv1_prime; | |
} | |
return fnv_ret; | |
} | |
[[ nodiscard ]] | |
std::uint32_t fnv1_hash_w( const wchar_t* string ) | |
{ | |
auto fnv_ret = fnv1_basis; | |
auto fnv_len = std::wcslen( string ); | |
for ( std::size_t idx{}; idx < fnv_len; idx++ ) | |
{ | |
fnv_ret ^= string[idx]; | |
fnv_ret *= fnv1_prime; | |
} | |
return fnv_ret; | |
} | |
} | |
#define _fnv1_ctw( wstr ) []( ){ constexpr std::uint32_t ctx = uti::fnv1_hash_ct_w( wstr ); return ctx; }( ) | |
#define _fnv1_ct( str ) []( ){ constexpr std::uint32_t ctx = uti::fnv1_hash_ct( str ); return ctx; }( ) | |
#define _fnv1_w( wstr ) uti::fnv1_hash_w( wstr ) | |
#define _fnv1( str ) uti::fnv1_hash( str ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment