Helios Engine
A modular ECS based data-oriented C++23 game engine framework
Loading...
Searching...
No Matches
hash.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <cstddef>
4#include <string_view>
5
6namespace helios::utils {
7
8using HashType = size_t;
9
10#if SIZE_MAX == UINT64_MAX
11inline constexpr HashType kFnvBasis = 14695981039346656037ULL;
12inline constexpr HashType kFnvPrime = 1099511628211ULL;
13#elif SIZE_MAX == UINT32_MAX
14inline constexpr HashType kFnvBasis = 2166136261U;
15inline constexpr HashType kFnvPrime = 16777619U;
16#else
17#error "Unsupported platform: size_t must be 32 or 64 bits"
18#endif
19
20/**
21 * @brief Computes the FNV-1a hash of a string.
22 * @param str The input string to hash.
23 * @param hash The initial hash value (default is the FNV basis).
24 * @return The computed FNV-1a hash of the input string.
25 */
26[[nodiscard]] constexpr HashType Fnv1aHash(std::string_view str,
27 HashType hash = kFnvBasis) noexcept {
28 for (const auto ch : str) {
29 hash = (hash ^ static_cast<HashType>(ch)) * kFnvPrime;
30 }
31 return hash;
32}
33
34/**
35 * @brief Computes the FNV-1a hash of a string literal.
36 * @tparam N The size of the string literal (including null terminator).
37 * @param array The string literal to hash.
38 * @return The computed FNV-1a hash of the input string literal.
39 */
40template <size_t N>
41[[nodiscard]] constexpr HashType Fnv1aHash(const char (&array)[N]) noexcept {
42 return Fnv1aHash(std::string_view{array, N - 1});
43}
44
45} // namespace helios::utils
constexpr HashType kFnvPrime
Definition hash.hpp:12
constexpr HashType kFnvBasis
Definition hash.hpp:11
constexpr HashType Fnv1aHash(std::string_view str, HashType hash=kFnvBasis) noexcept
Computes the FNV-1a hash of a string.
Definition hash.hpp:26
size_t HashType
Definition hash.hpp:8