Skip to content

Instantly share code, notes, and snippets.

@S-V
Created March 16, 2023 13:11
Show Gist options
  • Save S-V/7e9e2244ea77d3f32fa25f35815b4685 to your computer and use it in GitHub Desktop.
Save S-V/7e9e2244ea77d3f32fa25f35815b4685 to your computer and use it in GitHub Desktop.
Compile-time strings hashing using FNV-1a algorithm (compiles in C++20)
#include <cstdint>
template< typename Result >
struct FnvHashTraits;
template <>
struct FnvHashTraits<std::uint32_t> {
static constexpr std::uint32_t basis = 2166136261ul;
static constexpr std::uint32_t prime = 16777619ul;
};
template <>
struct FnvHashTraits<std::uint64_t> {
static constexpr std::uint64_t basis = 14695981039346656037ull;
static constexpr std::uint64_t prime = 1099511628211ull;
};
template< typename Result >
[[nodiscard]] constexpr Result hashFNV1a(const char* s, std::size_t len) noexcept {
Result hash = FnvHashTraits<Result>::basis;
while (len --> 0)
hash = (hash ^ *s++) * FnvHashTraits<Result>::prime;
return hash;
}
template< typename Result >
inline [[nodiscard]] Result getDynamicHash(const char* str) noexcept {
Result hash = FnvHashTraits<Result>::basis;
while (*str)
hash = (hash ^ *str++) * FnvHashTraits<Result>::prime;
return hash;
}
inline [[nodiscard]] std::uint32_t getDynamicHash32(const char* str) noexcept {
return getDynamicHash< std::uint32_t >(str);
}
inline [[nodiscard]] std::uint64_t getDynamicHash64(const char* str) noexcept {
return getDynamicHash< std::uint64_t >(str);
}
inline namespace literals
{
[[nodiscard]] constexpr std::uint32_t operator "" _h32(const char* s, std::size_t len) noexcept {
return hashFNV1a< std::uint32_t >(s, len);
}
[[nodiscard]] constexpr std::uint64_t operator "" _h64(const char* s, std::size_t len) noexcept {
return hashFNV1a< std::uint64_t >(s, len);
}
}
/*
TEST_CASE("compile-time string hashing", "")
{
const char* str = "D3D12 Mesh Shader";
SECTION("32-bit hashes") {
u32 a32 = getDynamicHash32(str);
u32 b32 = "D3D12 Mesh Shader"_h32;
REQUIRE(a32 == 1516319581);
REQUIRE(b32 == a32);
}
SECTION("64-bit hashes") {
u64 a64 = getDynamicHash64(str);
u64 b64 = "D3D12 Mesh Shader"_h64;
REQUIRE(a64 == 3514514454079241181ull);
REQUIRE(b64 == a64);
}
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment