userver: userver/utils/cached_hash.hpp Source File
⚠️ This is the documentation for an old userver version. Click here to switch to the latest version.
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages Concepts
cached_hash.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/utils/cached_hash.hpp
4/// @brief @copybrief utils::CachedHash
5
6#include <functional>
7#include <type_traits>
8
9USERVER_NAMESPACE_BEGIN
10
11namespace utils {
12
13/// @ingroup userver_universal
14///
15/// @brief Holds the key and its hash for faster comparisons and hashing
16template <class Key>
17struct CachedHash final {
18 std::size_t hash;
19 Key key;
20};
21
22/// @brief Compares utils::CachedHash by hash first and then by keys
23template <class T>
24constexpr bool operator==(const CachedHash<T>& x, const CachedHash<T>& y) {
25 return x.hash == y.hash && x.key == y.key;
26}
27
28/// @brief Compares utils::CachedHash by hash first and then by keys
29template <class T>
30constexpr bool operator!=(const CachedHash<T>& x, const CachedHash<T>& y) {
31 return !(x.key == y.key);
32}
33
34/// @brief Compares utils::CachedHash only by keys
35template <class Equal, class = std::enable_if_t<!std::is_final_v<Equal>>>
36class CachedHashKeyEqual : private Equal {
37 public:
38 explicit constexpr CachedHashKeyEqual(const Equal& eq) : Equal(eq) {}
39
40 template <class T>
41 constexpr bool operator()(const CachedHash<T>& x,
42 const CachedHash<T>& y) const {
43 return Equal::operator()(x.key, y.key);
44 }
45};
46
47template <class Equal>
48class CachedHashKeyEqual<Equal, std::false_type> {
49 public:
50 explicit constexpr CachedHashKeyEqual(const Equal& eq) : equality_(eq) {}
51
52 template <class T>
53 constexpr bool operator()(const CachedHash<T>& x,
54 const CachedHash<T>& y) const {
55 return equality_(x.key, y.key);
56 }
57
58 private:
59 Equal equality_;
60};
61
62} // namespace utils
63
64USERVER_NAMESPACE_END
65
66template <class T>
67struct std::hash<USERVER_NAMESPACE::utils::CachedHash<T>> {
68 constexpr std::size_t operator()(
69 const USERVER_NAMESPACE::utils::CachedHash<T>& value) const noexcept {
70 return value.hash;
71 }
72};