spy_hash_state.h 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  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 <algorithm>
  17. #include <ostream>
  18. #include <string>
  19. #include <vector>
  20. #include "absl/hash/hash.h"
  21. #include "absl/strings/match.h"
  22. #include "absl/strings/str_format.h"
  23. #include "absl/strings/str_join.h"
  24. namespace absl {
  25. ABSL_NAMESPACE_BEGIN
  26. namespace hash_internal {
  27. // SpyHashState is an implementation of the HashState API that simply
  28. // accumulates all input bytes in an internal buffer. This makes it useful
  29. // for testing AbslHashValue overloads (so long as they are templated on the
  30. // HashState parameter), since it can report the exact hash representation
  31. // that the AbslHashValue overload produces.
  32. //
  33. // Sample usage:
  34. // EXPECT_EQ(SpyHashState::combine(SpyHashState(), foo),
  35. // SpyHashState::combine(SpyHashState(), bar));
  36. template <typename T>
  37. class SpyHashStateImpl : public HashStateBase<SpyHashStateImpl<T>> {
  38. public:
  39. SpyHashStateImpl() : error_(std::make_shared<absl::optional<std::string>>()) {
  40. static_assert(std::is_void<T>::value, "");
  41. }
  42. // Move-only
  43. SpyHashStateImpl(const SpyHashStateImpl&) = delete;
  44. SpyHashStateImpl& operator=(const SpyHashStateImpl&) = delete;
  45. SpyHashStateImpl(SpyHashStateImpl&& other) noexcept {
  46. *this = std::move(other);
  47. }
  48. SpyHashStateImpl& operator=(SpyHashStateImpl&& other) noexcept {
  49. hash_representation_ = std::move(other.hash_representation_);
  50. error_ = other.error_;
  51. moved_from_ = other.moved_from_;
  52. other.moved_from_ = true;
  53. return *this;
  54. }
  55. template <typename U>
  56. SpyHashStateImpl(SpyHashStateImpl<U>&& other) { // NOLINT
  57. hash_representation_ = std::move(other.hash_representation_);
  58. error_ = other.error_;
  59. moved_from_ = other.moved_from_;
  60. other.moved_from_ = true;
  61. }
  62. template <typename A, typename... Args>
  63. static SpyHashStateImpl combine(SpyHashStateImpl s, const A& a,
  64. const Args&... args) {
  65. // Pass an instance of SpyHashStateImpl<A> when trying to combine `A`. This
  66. // allows us to test that the user only uses this instance for combine calls
  67. // and does not call AbslHashValue directly.
  68. // See AbslHashValue implementation at the bottom.
  69. s = SpyHashStateImpl<A>::HashStateBase::combine(std::move(s), a);
  70. return SpyHashStateImpl::combine(std::move(s), args...);
  71. }
  72. static SpyHashStateImpl combine(SpyHashStateImpl s) {
  73. if (direct_absl_hash_value_error_) {
  74. *s.error_ = "AbslHashValue should not be invoked directly.";
  75. } else if (s.moved_from_) {
  76. *s.error_ = "Used moved-from instance of the hash state object.";
  77. }
  78. return s;
  79. }
  80. static void SetDirectAbslHashValueError() {
  81. direct_absl_hash_value_error_ = true;
  82. }
  83. // Two SpyHashStateImpl objects are equal if they hold equal hash
  84. // representations.
  85. friend bool operator==(const SpyHashStateImpl& lhs,
  86. const SpyHashStateImpl& rhs) {
  87. return lhs.hash_representation_ == rhs.hash_representation_;
  88. }
  89. friend bool operator!=(const SpyHashStateImpl& lhs,
  90. const SpyHashStateImpl& rhs) {
  91. return !(lhs == rhs);
  92. }
  93. enum class CompareResult {
  94. kEqual,
  95. kASuffixB,
  96. kBSuffixA,
  97. kUnequal,
  98. };
  99. static CompareResult Compare(const SpyHashStateImpl& a,
  100. const SpyHashStateImpl& b) {
  101. const std::string a_flat = absl::StrJoin(a.hash_representation_, "");
  102. const std::string b_flat = absl::StrJoin(b.hash_representation_, "");
  103. if (a_flat == b_flat) return CompareResult::kEqual;
  104. if (absl::EndsWith(a_flat, b_flat)) return CompareResult::kBSuffixA;
  105. if (absl::EndsWith(b_flat, a_flat)) return CompareResult::kASuffixB;
  106. return CompareResult::kUnequal;
  107. }
  108. // operator<< prints the hash representation as a hex and ASCII dump, to
  109. // facilitate debugging.
  110. friend std::ostream& operator<<(std::ostream& out,
  111. const SpyHashStateImpl& hash_state) {
  112. out << "[\n";
  113. for (auto& s : hash_state.hash_representation_) {
  114. size_t offset = 0;
  115. for (char c : s) {
  116. if (offset % 16 == 0) {
  117. out << absl::StreamFormat("\n0x%04x: ", offset);
  118. }
  119. if (offset % 2 == 0) {
  120. out << " ";
  121. }
  122. out << absl::StreamFormat("%02x", c);
  123. ++offset;
  124. }
  125. out << "\n";
  126. }
  127. return out << "]";
  128. }
  129. // The base case of the combine recursion, which writes raw bytes into the
  130. // internal buffer.
  131. static SpyHashStateImpl combine_contiguous(SpyHashStateImpl hash_state,
  132. const unsigned char* begin,
  133. size_t size) {
  134. const size_t large_chunk_stride = PiecewiseChunkSize();
  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. if (size > 0) {
  145. hash_state.hash_representation_.emplace_back(
  146. reinterpret_cast<const char*>(begin), size);
  147. }
  148. return hash_state;
  149. }
  150. using SpyHashStateImpl::HashStateBase::combine_contiguous;
  151. template <typename CombinerT>
  152. static SpyHashStateImpl RunCombineUnordered(SpyHashStateImpl state,
  153. CombinerT combiner) {
  154. UnorderedCombinerCallback cb;
  155. combiner(SpyHashStateImpl<void>{}, std::ref(cb));
  156. std::sort(cb.element_hash_representations.begin(),
  157. cb.element_hash_representations.end());
  158. state.hash_representation_.insert(state.hash_representation_.end(),
  159. cb.element_hash_representations.begin(),
  160. cb.element_hash_representations.end());
  161. if (cb.error && cb.error->has_value()) {
  162. state.error_ = std::move(cb.error);
  163. }
  164. return state;
  165. }
  166. absl::optional<std::string> error() const {
  167. if (moved_from_) {
  168. return "Returned a moved-from instance of the hash state object.";
  169. }
  170. return *error_;
  171. }
  172. private:
  173. template <typename U>
  174. friend class SpyHashStateImpl;
  175. struct UnorderedCombinerCallback {
  176. std::vector<std::string> element_hash_representations;
  177. std::shared_ptr<absl::optional<std::string>> error;
  178. // The inner spy can have a different type.
  179. template <typename U>
  180. void operator()(SpyHashStateImpl<U>& inner) {
  181. element_hash_representations.push_back(
  182. absl::StrJoin(inner.hash_representation_, ""));
  183. if (inner.error_->has_value()) {
  184. error = std::move(inner.error_);
  185. }
  186. inner = SpyHashStateImpl<void>{};
  187. }
  188. };
  189. // This is true if SpyHashStateImpl<T> has been passed to a call of
  190. // AbslHashValue with the wrong type. This detects that the user called
  191. // AbslHashValue directly (because the hash state type does not match).
  192. static bool direct_absl_hash_value_error_;
  193. std::vector<std::string> hash_representation_;
  194. // This is a shared_ptr because we want all instances of the particular
  195. // SpyHashState run to share the field. This way we can set the error for
  196. // use-after-move and all the copies will see it.
  197. std::shared_ptr<absl::optional<std::string>> error_;
  198. bool moved_from_ = false;
  199. };
  200. template <typename T>
  201. bool SpyHashStateImpl<T>::direct_absl_hash_value_error_;
  202. template <bool& B>
  203. struct OdrUse {
  204. constexpr OdrUse() {}
  205. bool& b = B;
  206. };
  207. template <void (*)()>
  208. struct RunOnStartup {
  209. static bool run;
  210. static constexpr OdrUse<run> kOdrUse{};
  211. };
  212. template <void (*f)()>
  213. bool RunOnStartup<f>::run = (f(), true);
  214. template <
  215. typename T, typename U,
  216. // Only trigger for when (T != U),
  217. typename = absl::enable_if_t<!std::is_same<T, U>::value>,
  218. // This statement works in two ways:
  219. // - First, it instantiates RunOnStartup and forces the initialization of
  220. // `run`, which set the global variable.
  221. // - Second, it triggers a SFINAE error disabling the overload to prevent
  222. // compile time errors. If we didn't disable the overload we would get
  223. // ambiguous overload errors, which we don't want.
  224. int = RunOnStartup<SpyHashStateImpl<T>::SetDirectAbslHashValueError>::run>
  225. void AbslHashValue(SpyHashStateImpl<T>, const U&);
  226. using SpyHashState = SpyHashStateImpl<void>;
  227. } // namespace hash_internal
  228. ABSL_NAMESPACE_END
  229. } // namespace absl
  230. #endif // ABSL_HASH_INTERNAL_SPY_HASH_STATE_H_