diff options
Diffstat (limited to 'libs')
| -rw-r--r-- | libs/kstd/kstd/bits/basic_string.hpp | 21 | ||||
| -rw-r--r-- | libs/kstd/kstd/string.test.cpp | 35 |
2 files changed, 56 insertions, 0 deletions
diff --git a/libs/kstd/kstd/bits/basic_string.hpp b/libs/kstd/kstd/bits/basic_string.hpp index 212aa8ac..4d690ac3 100644 --- a/libs/kstd/kstd/bits/basic_string.hpp +++ b/libs/kstd/kstd/bits/basic_string.hpp @@ -10,6 +10,7 @@ #include <array> #include <compare> #include <cstddef> +#include <functional> #include <initializer_list> #include <iterator> #include <limits> @@ -1546,4 +1547,24 @@ namespace kstd } // namespace kstd +//! A specialization of std::hash for kstd::string. +//! +//! This specialization allows for the use of kstd::string in hashed containers. +//! +//! @note Under the hood, this specialization delegates to the specialization for std::string_view. This saves +//! implementation work and automatically guarantees that the hash for a kstd::string with some contents X is equal to +//! the hash of a std::string_view of the same X. This is a standard requirement for the specialization for std::string, +//! so providing the same for kstd::string yields the same interoperability. +template<typename Allocator> +struct std::hash<kstd::basic_string<char, kstd::char_traits<char>, Allocator>> +{ + constexpr auto static implementation = std::hash<std::string_view>{}; + + constexpr auto operator()(kstd::basic_string<char, kstd::char_traits<char>, Allocator> string) const noexcept + -> std::size_t + { + return implementation(string); + }; +}; + #endif diff --git a/libs/kstd/kstd/string.test.cpp b/libs/kstd/kstd/string.test.cpp index 3fbf6c0c..2de8b513 100644 --- a/libs/kstd/kstd/string.test.cpp +++ b/libs/kstd/kstd/string.test.cpp @@ -8,9 +8,11 @@ #include <algorithm> #include <cstring> #include <forward_list> +#include <functional> #include <iterator> #include <memory> #include <sstream> +#include <string> #include <string_view> #include <type_traits> #include <utility> @@ -2942,3 +2944,36 @@ SCENARIO("String iteration", "[string]") } } } + +SCENARIO("String STL integration", "[string]") +{ + GIVEN("An empty string") + { + auto s = kstd::string{""}; + + WHEN("hashing the string") + { + auto hash_result = std::hash<kstd::string>{}(s); + + THEN("the result is equal to hashing an empty std::string") + { + REQUIRE(hash_result == std::hash<std::string>{}("")); + } + } + } + + GIVEN("A non-empty string") + { + auto s = kstd::string{"abcd"}; + + WHEN("hashing the string") + { + auto hash_result = std::hash<kstd::string>{}(s); + + THEN("the result is equal to hashing the same std::string") + { + REQUIRE(hash_result == std::hash<std::string>{}("abcd")); + } + } + } +} |
