Skip to content

Commit 0fd1654

Browse files
feat: Implement hash module for enhanced type hashing and value retrieval
Signed-off-by: FrozenlemonTee <1115306170@qq.com>
1 parent e33c615 commit 0fd1654

1 file changed

Lines changed: 79 additions & 0 deletions

File tree

src/algorithms/hash.cppm

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
module;
2+
3+
#include <concepts>
4+
#include <cstddef>
5+
#include <functional>
6+
#include <type_traits>
7+
8+
export module mcpplibs.primitives.algorithms.hash;
9+
10+
import mcpplibs.primitives.underlying;
11+
12+
namespace mcpplibs::primitives::algorithms::details {
13+
14+
template <typename T>
15+
concept std_hashable = requires(std::remove_cv_t<T> const &value) {
16+
{
17+
std::hash<std::remove_cv_t<T>>{}(value)
18+
} -> std::convertible_to<std::size_t>;
19+
};
20+
21+
} // namespace mcpplibs::primitives::algorithms::details
22+
23+
export namespace mcpplibs::primitives::algorithms {
24+
25+
template <typename T> struct hash {
26+
using value_type = std::remove_cv_t<T>;
27+
using result_type = std::size_t;
28+
29+
static constexpr bool enabled = false;
30+
31+
auto operator()(value_type const &) const noexcept -> result_type {
32+
return result_type{};
33+
}
34+
};
35+
36+
template <typename T>
37+
using hash_result_t = hash<std::remove_cvref_t<T>>::result_type;
38+
39+
template <typename T>
40+
concept hashable = hash<std::remove_cvref_t<T>>::enabled;
41+
42+
template <typename T>
43+
requires details::std_hashable<T>
44+
struct hash<T> {
45+
using value_type = std::remove_cv_t<T>;
46+
using result_type = std::size_t;
47+
48+
static constexpr bool enabled = true;
49+
50+
auto operator()(value_type const &value) const noexcept(
51+
noexcept(std::hash<value_type>{}(value))) -> result_type {
52+
return std::hash<value_type>{}(value);
53+
}
54+
};
55+
56+
template <underlying_type T>
57+
requires (!details::std_hashable<T> &&
58+
hash<typename underlying::traits<std::remove_cv_t<T>>::rep_type>::enabled)
59+
struct hash<T> {
60+
using value_type = std::remove_cv_t<T>;
61+
using rep_type = underlying::traits<value_type>::rep_type;
62+
using result_type = hash_result_t<rep_type>;
63+
64+
static constexpr bool enabled = true;
65+
66+
auto operator()(value_type const &value) const noexcept(
67+
noexcept(hash<rep_type>{}(underlying::traits<value_type>::to_rep(value))))
68+
-> result_type {
69+
return hash<rep_type>{}(underlying::traits<value_type>::to_rep(value));
70+
}
71+
};
72+
73+
template <hashable T>
74+
auto hash_value(T const &value) noexcept(
75+
noexcept(hash<std::remove_cvref_t<T>>{}(value))) -> hash_result_t<T> {
76+
return hash<std::remove_cvref_t<T>>{}(value);
77+
}
78+
79+
} // namespace mcpplibs::primitives::algorithms

0 commit comments

Comments
 (0)