entt  2.5.0
hashed_string.hpp
1 #ifndef ENTT_CORE_HASHED_STRING_HPP
2 #define ENTT_CORE_HASHED_STRING_HPP
3 
4 
5 #include <cstddef>
6 #include <cstdint>
7 
8 
9 namespace entt {
10 
11 
21 class HashedString final {
22  struct ConstCharWrapper final {
23  // non-explicit constructor on purpose
24  constexpr ConstCharWrapper(const char *str) noexcept: str{str} {}
25  const char *str;
26  };
27 
28  static constexpr std::uint64_t offset = 14695981039346656037ull;
29  static constexpr std::uint64_t prime = 1099511628211ull;
30 
31  // Fowler–Noll–Vo hash function v. 1a - the good
32  static constexpr std::uint64_t helper(std::uint64_t partial, const char *str) noexcept {
33  return str[0] == 0 ? partial : helper((partial^str[0])*prime, str+1);
34  }
35 
36 public:
38  using hash_type = std::uint64_t;
39 
54  template <std::size_t N>
55  constexpr HashedString(const char (&str)[N]) noexcept
56  : hash{helper(offset, str)}, str{str}
57  {}
58 
65  explicit constexpr HashedString(ConstCharWrapper wrapper) noexcept
66  : hash{helper(offset, wrapper.str)}, str{wrapper.str}
67  {}
68 
73  constexpr operator const char *() const noexcept { return str; }
74 
79  constexpr operator hash_type() const noexcept { return hash; }
80 
86  constexpr bool operator==(const HashedString &other) const noexcept {
87  return hash == other.hash;
88  }
89 
90 private:
91  const hash_type hash;
92  const char *str;
93 };
94 
95 
102 constexpr bool operator!=(const HashedString &lhs, const HashedString &rhs) noexcept {
103  return !(lhs == rhs);
104 }
105 
106 
107 }
108 
109 
110 #endif // ENTT_CORE_HASHED_STRING_HPP
constexpr HashedString(ConstCharWrapper wrapper) noexcept
Explicit constructor on purpose to avoid constructing a hashed string directly from a const char *...
EnTT default namespace.
Definition: family.hpp:10
Zero overhead resource identifier.
constexpr HashedString(const char(&str)[N]) noexcept
Constructs a hashed string from an array of const chars.
std::uint64_t hash_type
Unsigned integer type.
constexpr bool operator!=(const HashedString &lhs, const HashedString &rhs) noexcept
Compares two hashed strings.
constexpr bool operator==(const HashedString &other) const noexcept
Compares two hashed strings.