Skip to content

Instantly share code, notes, and snippets.

@oberrich
Last active February 2, 2022 18:08
Show Gist options
  • Save oberrich/06d65656cbbfa0eaab8d91df67509e08 to your computer and use it in GitHub Desktop.
Save oberrich/06d65656cbbfa0eaab8d91df67509e08 to your computer and use it in GitHub Desktop.
FNV-1a hashing a wide-string with multiple of 4 length in chunks of 64-bits
constexpr auto hash_64bitwise(std::wstring_view str) noexcept
{
using SizeType = decltype(str)::size_type;
constexpr auto offset_basis = 0xcbf29ce484222325ull;
constexpr auto prime = 0x00000100000001B3ull;
auto value = offset_basis;
auto size = str.length();
if (size % 4)
return 0ull;
for (SizeType i{}; i < size / 4; ++i) {
std::uint64_t chunk = 0;
if (std::is_constant_evaluated()) {
chunk = []<std::size_t... Is>(wchar_t const *ptr, std::index_sequence<Is...>) constexpr {
return ((static_cast<std::uint64_t>(ptr[Is]) << (16u * Is)) | ...);
}(&str[(i * 4)], std::make_index_sequence<4>{});
} else {
std::memcpy(&chunk, &str[i * 4], 8);
}
value = (value ^ chunk) * prime;
}
return value;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment