spy_hash_state.h 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. // Copyright 2018 The Abseil Authors.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // https://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #ifndef ABSL_HASH_INTERNAL_SPY_HASH_STATE_H_
  15. #define ABSL_HASH_INTERNAL_SPY_HASH_STATE_H_
  16. #include <ostream>
  17. #include <string>
  18. #include <vector>
  19. #include "absl/hash/hash.h"
  20. #include "absl/strings/match.h"
  21. #include "absl/strings/str_format.h"
  22. #include "absl/strings/str_join.h"
  23. namespace absl {
  24. ABSL_NAMESPACE_BEGIN
  25. namespace hash_internal {
  26. // SpyHashState is an implementation of the HashState API that simply
  27. // accumulates all input bytes in an internal buffer. This makes it useful
  28. // for testing AbslHashValue overloads (so long as they are templated on the
  29. // HashState parameter), since it can report the exact hash representation
  30. // that the AbslHashValue overload produces.
  31. //
  32. // Sample usage:
  33. // EXPECT_EQ(SpyHashState::combine(SpyHashState(), foo),
  34. // SpyHashState::combine(SpyHashState(), bar));
  35. template <typename T>
  36. class SpyHashStateImpl : public HashStateBase<SpyHashStateImpl<T>> {
  37. public:
  38. SpyHashStateImpl() : error_(std::make_shared<absl::optional<std::string>>()) {
  39. static_assert(std::is_void<T>::value, "");
  40. }
  41. // Move-only
  42. SpyHashStateImpl(const SpyHashStateImpl&) = delete;
  43. SpyHashStateImpl& operator=(const SpyHashStateImpl&) = delete;
  44. SpyHashStateImpl(SpyHashStateImpl&& other) noexcept {
  45. *this = std::move(other);
  46. }
  47. SpyHashStateImpl& operator=(SpyHashStateImpl&& other) noexcept {
  48. hash_representation_ = std::move(other.hash_representation_);
  49. error_ = other.error_;
  50. moved_from_ = other.moved_from_;
  51. other.moved_from_ = true;
  52. return *this;
  53. }
  54. template <typename U>
  55. SpyHashStateImpl(SpyHashStateImpl<U>&& other) { // NOLINT
  56. hash_representation_ = std::move(other.hash_representation_);
  57. error_ = other.error_;
  58. moved_from_ = other.moved_from_;
  59. other.moved_from_ = true;
  60. }
  61. template <typename A, typename... Args>
  62. static SpyHashStateImpl combine(SpyHashStateImpl s, const A& a,
  63. const Args&... args) {
  64. // Pass an instance of SpyHashStateImpl<A> when trying to combine `A`. This
  65. // allows us to test that the user only uses this instance for combine calls
  66. // and does not call AbslHashValue directly.
  67. // See AbslHashValue implementation at the bottom.
  68. s = SpyHashStateImpl<A>::HashStateBase::combine(std::move(s), a);
  69. return SpyHashStateImpl::combine(std::move(s), args...);
  70. }
  71. static SpyHashStateImpl combine(SpyHashStateImpl s) {
  72. if (direct_absl_hash_value_error_) {
  73. *s.error_ = "AbslHashValue should not be invoked directly.";
  74. } else if (s.moved_from_) {
  75. *s.error_ = "Used moved-from instance of the hash state object.";
  76. }
  77. return s;
  78. }
  79. static void SetDirectAbslHashValueError() {
  80. direct_absl_hash_value_error_ = true;
  81. }
  82. // Two SpyHashStateImpl objects are equal if they hold equal hash
  83. // representations.
  84. friend bool operator==(const SpyHashStateImpl& lhs,
  85. const SpyHashStateImpl& rhs) {
  86. return lhs.hash_representation_ == rhs.hash_representation_;
  87. }
  88. friend bool operator!=(const SpyHashStateImpl& lhs,
  89. const SpyHashStateImpl& rhs) {
  90. return !(lhs == rhs);
  91. }
  92. enum class CompareResult {
  93. kEqual,
  94. kASuffixB,
  95. kBSuffixA,
  96. kUnequal,
  97. };
  98. static CompareResult Compare(const SpyHashStateImpl& a,
  99. const SpyHashStateImpl& b) {
  100. const std::string a_flat = absl::StrJoin(a.hash_representation_, "");
  101. const std::string b_flat = absl::StrJoin(b.hash_representation_, "");
  102. if (a_flat == b_flat) return CompareResult::kEqual;
  103. if (absl::EndsWith(a_flat, b_flat)) return CompareResult::kBSuffixA;
  104. if (absl::EndsWith(b_flat, a_flat)) return CompareResult::kASuffixB;
  105. return CompareResult::kUnequal;
  106. }
  107. // operator<< prints the hash representation as a hex and ASCII dump, to
  108. // facilitate debugging.
  109. friend std::ostream& operator<<(std::ostream& out,
  110. const SpyHashStateImpl& hash_state) {
  111. out << "[\n";
  112. for (auto& s : hash_state.hash_representation_) {
  113. size_t offset = 0;
  114. for (char c : s) {
  115. if (offset % 16 == 0) {
  116. out << absl::StreamFormat("\n0x%04x: ", offset);
  117. }
  118. if (offset % 2 == 0) {
  119. out << " ";
  120. }
  121. out << absl::StreamFormat("%02x", c);
  122. ++offset;
  123. }
  124. out << "\n";
  125. }
  126. return out << "]";
  127. }
  128. // The base case of the combine recursion, which writes raw bytes into the
  129. // internal buffer.
  130. static SpyHashStateImpl combine_contiguous(SpyHashStateImpl hash_state,
  131. const unsigned char* begin,
  132. size_t size) {
  133. const size_t large_chunk_stride = PiecewiseChunkSize();
  134. if (size > large_chunk_stride) {
  135. // Combining a large contiguous buffer must have the same effect as
  136. // doing it piecewise by the stride length, followed by the (possibly
  137. // empty) remainder.
  138. while (size >= large_chunk_stride) {
  139. hash_state = SpyHashStateImpl::combine_contiguous(
  140. std::move(hash_state), begin, large_chunk_stride);
  141. begin += large_chunk_stride;
  142. size -= large_chunk_stride;
  143. }
  144. }
  145. hash_state.hash_representation_.emplace_back(
  146. reinterpret_cast<const char*>(begin), size);
  147. return hash_state;
  148. }
  149. using SpyHashStateImpl::HashStateBase::combine_contiguous;
  150. absl::optional<std::string> error() const {
  151. if (moved_from_) {
  152. return "Returned a moved-from instance of the hash state object.";
  153. }
  154. return *error_;
  155. }
  156. private:
  157. template <typename U>
  158. friend class SpyHashStateImpl;
  159. // This is true if SpyHashStateImpl<T> has been passed to a call of
  160. // AbslHashValue with the wrong type. This detects that the user called
  161. // AbslHashValue directly (because the hash state type does not match).
  162. static bool direct_absl_hash_value_error_;
  163. std::vector<std::string> hash_representation_;
  164. // This is a shared_ptr because we want all instances of the particular
  165. // SpyHashState run to share the field. This way we can set the error for
  166. // use-after-move and all the copies will see it.
  167. std::shared_ptr<absl::optional<std::string>> error_;
  168. bool moved_from_ = false;
  169. };
  170. template <typename T>
  171. bool SpyHashStateImpl<T>::direct_absl_hash_value_error_;
  172. template <bool& B>
  173. struct OdrUse {
  174. constexpr OdrUse() {}
  175. bool& b = B;
  176. };
  177. template <void (*)()>
  178. struct RunOnStartup {
  179. static bool run;
  180. static constexpr OdrUse<run> kOdrUse{};
  181. };
  182. template <void (*f)()>
  183. bool RunOnStartup<f>::run = (f(), true);
  184. template <
  185. typename T, typename U,
  186. // Only trigger for when (T != U),
  187. typename = absl::enable_if_t<!std::is_same<T, U>::value>,
  188. // This statement works in two ways:
  189. // - First, it instantiates RunOnStartup and forces the initialization of
  190. // `run`, which set the global variable.
  191. // - Second, it triggers a SFINAE error disabling the overload to prevent
  192. // compile time errors. If we didn't disable the overload we would get
  193. // ambiguous overload errors, which we don't want.
  194. int = RunOnStartup<SpyHashStateImpl<T>::SetDirectAbslHashValueError>::run>
  195. void AbslHashValue(SpyHashStateImpl<T>, const U&);
  196. using SpyHashState = SpyHashStateImpl<void>;
  197. } // namespace hash_internal
  198. ABSL_NAMESPACE_END
  199. } // namespace absl
  200. #endif // ABSL_HASH_INTERNAL_SPY_HASH_STATE_H_