EnTT  2.7.3
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 #include "../config/config.h"
8 
9 
10 namespace entt {
11 
12 
22 class HashedString final {
23  struct ConstCharWrapper final {
24  // non-explicit constructor on purpose
25  constexpr ConstCharWrapper(const char *str) ENTT_NOEXCEPT: str{str} {}
26  const char *str;
27  };
28 
29  static constexpr std::uint64_t offset = 14695981039346656037ull;
30  static constexpr std::uint64_t prime = 1099511628211ull;
31 
32  // Fowler–Noll–Vo hash function v. 1a - the good
33  static constexpr std::uint64_t helper(std::uint64_t partial, const char *str) ENTT_NOEXCEPT {
34  return str[0] == 0 ? partial : helper((partial^str[0])*prime, str+1);
35  }
36 
37 public:
39  using hash_type = std::uint64_t;
40 
55  template<std::size_t N>
56  constexpr HashedString(const char (&str)[N]) ENTT_NOEXCEPT
57  : hash{helper(offset, str)}, str{str}
58  {}
59 
66  explicit constexpr HashedString(ConstCharWrapper wrapper) ENTT_NOEXCEPT
67  : hash{helper(offset, wrapper.str)}, str{wrapper.str}
68  {}
69 
74  constexpr operator const char *() const ENTT_NOEXCEPT { return str; }
75 
80  constexpr operator hash_type() const ENTT_NOEXCEPT { return hash; }
81 
87  constexpr bool operator==(const HashedString &other) const ENTT_NOEXCEPT {
88  return hash == other.hash;
89  }
90 
91 private:
92  const hash_type hash;
93  const char *str;
94 };
95 
96 
103 constexpr bool operator!=(const HashedString &lhs, const HashedString &rhs) ENTT_NOEXCEPT {
104  return !(lhs == rhs);
105 }
106 
107 
108 }
109 
110 
116 constexpr entt::HashedString operator"" ENTT_HS_SUFFIX(const char *str, std::size_t) ENTT_NOEXCEPT {
117  return entt::HashedString{str};
118 }
119 
120 
121 #endif // ENTT_CORE_HASHED_STRING_HPP
constexpr bool operator!=(const HashedString &lhs, const HashedString &rhs) ENTT_NOEXCEPT
Compares two hashed strings.
EnTT default namespace.
Definition: algorithm.hpp:10
constexpr HashedString(ConstCharWrapper wrapper) ENTT_NOEXCEPT
Explicit constructor on purpose to avoid constructing a hashed string directly from a const char *...
constexpr bool operator==(const HashedString &other) const ENTT_NOEXCEPT
Compares two hashed strings.
Zero overhead resource identifier.
constexpr HashedString(const char(&str)[N]) ENTT_NOEXCEPT
Constructs a hashed string from an array of const chars.
std::uint64_t hash_type
Unsigned integer type.