sandbox
Loading...
Searching...
No Matches
hashed_string.hpp
1#ifndef LIBSBX_UTILITY_HASHED_STRING_HPP_
2#define LIBSBX_UTILITY_HASHED_STRING_HPP_
3
4#include <concepts>
5#include <cinttypes>
6#include <string>
7
9
10namespace sbx::utility {
11
12template<character Char, typename Hash = std::uint64_t, typename HashFunction = fnv1a_hash<Char, Hash>>
14
15public:
16
17 using char_type = HashFunction::char_type;
18 using size_type = HashFunction::size_type;
19 using hash_type = HashFunction::hash_type;
20
22 : _string{},
23 _hash{} {}
24
25 basic_hashed_string(const char_type* string, const size_type length)
26 : _string{string, length},
27 _hash{HashFunction{}(_string)} {}
28
29 template<std::size_t Size>
30 basic_hashed_string(const char_type (&string)[Size])
31 : _string{string, Size - 1},
32 _hash{HashFunction{}(_string)} {}
33
34 basic_hashed_string(const std::basic_string<char_type>& string)
35 : _string{string},
36 _hash{HashFunction{}(_string)} {}
37
38 basic_hashed_string(const basic_hashed_string& other) = default;
39
40 basic_hashed_string(basic_hashed_string&& other) noexcept = default;
41
42 ~basic_hashed_string() = default;
43
44 auto operator=(const basic_hashed_string& other) -> basic_hashed_string& = default;
45
46 auto operator=(basic_hashed_string&& other) noexcept -> basic_hashed_string& = default;
47
48 auto operator==(const basic_hashed_string& other) const noexcept -> bool {
49 return _hash == other._hash;
50 }
51
52 auto data() const noexcept -> const char_type* {
53 return _string.data();
54 }
55
56 auto size() const noexcept -> size_type {
57 return _string.size();
58 }
59
60 auto hash() const noexcept -> hash_type {
61 return _hash;
62 }
63
64 auto c_str() const noexcept -> const char_type* {
65 return _string.c_str();
66 }
67
68 operator hash_type() const noexcept {
69 return _hash;
70 }
71
72private:
73
74 std::basic_string<char_type> _string{};
75 hash_type _hash{};
76
77}; // class basic_hashed_string
78
80
82
83namespace literals {
84
85inline auto operator""_hs(const char* string, const std::size_t length) -> hashed_string {
86 return hashed_string{string, length};
87}
88
89inline auto operator""_hs(const wchar_t* string, const std::size_t length) -> hashed_wstring {
90 return hashed_wstring{string, length};
91}
92
93} // namespace literals
94
95} // namespace sbx::utility
96
97template<sbx::utility::character Char, typename Hash, typename HashFunction>
98struct std::hash<sbx::utility::basic_hashed_string<Char, Hash, HashFunction>> {
99 auto operator()(const sbx::utility::basic_hashed_string<Char, Hash, HashFunction>& string) const noexcept -> std::size_t {
100 return string.hash();
101 }
102}; // struct std::hash
103
104#endif // LIBSBX_UTILITY_HASHED_STRING_HPP_
Definition: hashed_string.hpp:13