From 278256683f3be86d21e008670ab1bc1b76cdc3b1 Mon Sep 17 00:00:00 2001 From: Felix Morgner Date: Wed, 1 Jul 2026 09:12:09 +0200 Subject: kstd: implement string hash support --- libs/kstd/kstd/bits/basic_string.hpp | 21 +++++++++++++++++++++ libs/kstd/kstd/string.test.cpp | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+) 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 #include #include +#include #include #include #include @@ -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 +struct std::hash, Allocator>> +{ + constexpr auto static implementation = std::hash{}; + + constexpr auto operator()(kstd::basic_string, 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 #include #include +#include #include #include #include +#include #include #include #include @@ -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{}(s); + + THEN("the result is equal to hashing an empty std::string") + { + REQUIRE(hash_result == std::hash{}("")); + } + } + } + + GIVEN("A non-empty string") + { + auto s = kstd::string{"abcd"}; + + WHEN("hashing the string") + { + auto hash_result = std::hash{}(s); + + THEN("the result is equal to hashing the same std::string") + { + REQUIRE(hash_result == std::hash{}("abcd")); + } + } + } +} -- cgit v1.2.3