hash.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  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. //
  15. // -----------------------------------------------------------------------------
  16. // File: hash.h
  17. // -----------------------------------------------------------------------------
  18. //
  19. // This header file defines the Abseil `hash` library and the Abseil hashing
  20. // framework. This framework consists of the following:
  21. //
  22. // * The `absl::Hash` functor, which is used to invoke the hasher within the
  23. // Abseil hashing framework. `absl::Hash<T>` supports most basic types and
  24. // a number of Abseil types out of the box.
  25. // * `AbslHashValue`, an extension point that allows you to extend types to
  26. // support Abseil hashing without requiring you to define a hashing
  27. // algorithm.
  28. // * `HashState`, a type-erased class which implements the manipulation of the
  29. // hash state (H) itself; contains member functions `combine()`,
  30. // `combine_contiguous()`, and `combine_unordered()`; and which you can use
  31. // to contribute to an existing hash state when hashing your types.
  32. //
  33. // Unlike `std::hash` or other hashing frameworks, the Abseil hashing framework
  34. // provides most of its utility by abstracting away the hash algorithm (and its
  35. // implementation) entirely. Instead, a type invokes the Abseil hashing
  36. // framework by simply combining its state with the state of known, hashable
  37. // types. Hashing of that combined state is separately done by `absl::Hash`.
  38. //
  39. // One should assume that a hash algorithm is chosen randomly at the start of
  40. // each process. E.g., `absl::Hash<int>{}(9)` in one process and
  41. // `absl::Hash<int>{}(9)` in another process are likely to differ.
  42. //
  43. // `absl::Hash` may also produce different values from different dynamically
  44. // loaded libraries. For this reason, `absl::Hash` values must never cross
  45. // boundaries in dynamically loaded libraries (including when used in types like
  46. // hash containers.)
  47. //
  48. // `absl::Hash` is intended to strongly mix input bits with a target of passing
  49. // an [Avalanche Test](https://en.wikipedia.org/wiki/Avalanche_effect).
  50. //
  51. // Example:
  52. //
  53. // // Suppose we have a class `Circle` for which we want to add hashing:
  54. // class Circle {
  55. // public:
  56. // ...
  57. // private:
  58. // std::pair<int, int> center_;
  59. // int radius_;
  60. // };
  61. //
  62. // // To add hashing support to `Circle`, we simply need to add a free
  63. // // (non-member) function `AbslHashValue()`, and return the combined hash
  64. // // state of the existing hash state and the class state. You can add such a
  65. // // free function using a friend declaration within the body of the class:
  66. // class Circle {
  67. // public:
  68. // ...
  69. // template <typename H>
  70. // friend H AbslHashValue(H h, const Circle& c) {
  71. // return H::combine(std::move(h), c.center_, c.radius_);
  72. // }
  73. // ...
  74. // };
  75. //
  76. // For more information, see Adding Type Support to `absl::Hash` below.
  77. //
  78. #ifndef ABSL_HASH_HASH_H_
  79. #define ABSL_HASH_HASH_H_
  80. #include <tuple>
  81. #include <utility>
  82. #include "absl/functional/function_ref.h"
  83. #include "absl/hash/internal/hash.h"
  84. namespace absl {
  85. ABSL_NAMESPACE_BEGIN
  86. // -----------------------------------------------------------------------------
  87. // `absl::Hash`
  88. // -----------------------------------------------------------------------------
  89. //
  90. // `absl::Hash<T>` is a convenient general-purpose hash functor for any type `T`
  91. // satisfying any of the following conditions (in order):
  92. //
  93. // * T is an arithmetic or pointer type
  94. // * T defines an overload for `AbslHashValue(H, const T&)` for an arbitrary
  95. // hash state `H`.
  96. // - T defines a specialization of `std::hash<T>`
  97. //
  98. // `absl::Hash` intrinsically supports the following types:
  99. //
  100. // * All integral types (including bool)
  101. // * All enum types
  102. // * All floating-point types (although hashing them is discouraged)
  103. // * All pointer types, including nullptr_t
  104. // * std::pair<T1, T2>, if T1 and T2 are hashable
  105. // * std::tuple<Ts...>, if all the Ts... are hashable
  106. // * std::unique_ptr and std::shared_ptr
  107. // * All string-like types including:
  108. // * absl::Cord
  109. // * std::string (as well as any instance of std::basic_string that
  110. // uses one of {char, wchar_t, char16_t, char32_t} and its associated
  111. // std::char_traits)
  112. // * std::string_view (as well as any instance of std::basic_string_view
  113. // that uses one of {char, wchar_t, char16_t, char32_t} and its associated
  114. // std::char_traits)
  115. // * All the standard sequence containers (provided the elements are hashable)
  116. // * All the standard associative containers (provided the elements are
  117. // hashable)
  118. // * absl types such as the following:
  119. // * absl::string_view
  120. // * absl::uint128
  121. // * absl::Time, absl::Duration, and absl::TimeZone
  122. // * absl containers (provided the elements are hashable) such as the
  123. // following:
  124. // * absl::flat_hash_set, absl::node_hash_set, absl::btree_set
  125. // * absl::flat_hash_map, absl::node_hash_map, absl::btree_map
  126. // * absl::btree_multiset, absl::btree_multimap
  127. // * absl::InlinedVector
  128. // * absl::FixedArray
  129. //
  130. // When absl::Hash is used to hash an unordered container with a custom hash
  131. // functor, the elements are hashed using default absl::Hash semantics, not
  132. // the custom hash functor. This is consistent with the behavior of
  133. // operator==() on unordered containers, which compares elements pairwise with
  134. // operator==() rather than the custom equality functor. It is usually a
  135. // mistake to use either operator==() or absl::Hash on unordered collections
  136. // that use functors incompatible with operator==() equality.
  137. //
  138. // Note: the list above is not meant to be exhaustive. Additional type support
  139. // may be added, in which case the above list will be updated.
  140. //
  141. // -----------------------------------------------------------------------------
  142. // absl::Hash Invocation Evaluation
  143. // -----------------------------------------------------------------------------
  144. //
  145. // When invoked, `absl::Hash<T>` searches for supplied hash functions in the
  146. // following order:
  147. //
  148. // * Natively supported types out of the box (see above)
  149. // * Types for which an `AbslHashValue()` overload is provided (such as
  150. // user-defined types). See "Adding Type Support to `absl::Hash`" below.
  151. // * Types which define a `std::hash<T>` specialization
  152. //
  153. // The fallback to legacy hash functions exists mainly for backwards
  154. // compatibility. If you have a choice, prefer defining an `AbslHashValue`
  155. // overload instead of specializing any legacy hash functors.
  156. //
  157. // -----------------------------------------------------------------------------
  158. // The Hash State Concept, and using `HashState` for Type Erasure
  159. // -----------------------------------------------------------------------------
  160. //
  161. // The `absl::Hash` framework relies on the Concept of a "hash state." Such a
  162. // hash state is used in several places:
  163. //
  164. // * Within existing implementations of `absl::Hash<T>` to store the hashed
  165. // state of an object. Note that it is up to the implementation how it stores
  166. // such state. A hash table, for example, may mix the state to produce an
  167. // integer value; a testing framework may simply hold a vector of that state.
  168. // * Within implementations of `AbslHashValue()` used to extend user-defined
  169. // types. (See "Adding Type Support to absl::Hash" below.)
  170. // * Inside a `HashState`, providing type erasure for the concept of a hash
  171. // state, which you can use to extend the `absl::Hash` framework for types
  172. // that are otherwise difficult to extend using `AbslHashValue()`. (See the
  173. // `HashState` class below.)
  174. //
  175. // The "hash state" concept contains three member functions for mixing hash
  176. // state:
  177. //
  178. // * `H::combine(state, values...)`
  179. //
  180. // Combines an arbitrary number of values into a hash state, returning the
  181. // updated state. Note that the existing hash state is move-only and must be
  182. // passed by value.
  183. //
  184. // Each of the value types T must be hashable by H.
  185. //
  186. // NOTE:
  187. //
  188. // state = H::combine(std::move(state), value1, value2, value3);
  189. //
  190. // must be guaranteed to produce the same hash expansion as
  191. //
  192. // state = H::combine(std::move(state), value1);
  193. // state = H::combine(std::move(state), value2);
  194. // state = H::combine(std::move(state), value3);
  195. //
  196. // * `H::combine_contiguous(state, data, size)`
  197. //
  198. // Combines a contiguous array of `size` elements into a hash state,
  199. // returning the updated state. Note that the existing hash state is
  200. // move-only and must be passed by value.
  201. //
  202. // NOTE:
  203. //
  204. // state = H::combine_contiguous(std::move(state), data, size);
  205. //
  206. // need NOT be guaranteed to produce the same hash expansion as a loop
  207. // (it may perform internal optimizations). If you need this guarantee, use a
  208. // loop instead.
  209. //
  210. // * `H::combine_unordered(state, begin, end)`
  211. //
  212. // Combines a set of elements denoted by an iterator pair into a hash
  213. // state, returning the updated state. Note that the existing hash
  214. // state is move-only and must be passed by value.
  215. //
  216. // Unlike the other two methods, the hashing is order-independent.
  217. // This can be used to hash unordered collections.
  218. //
  219. // -----------------------------------------------------------------------------
  220. // Adding Type Support to `absl::Hash`
  221. // -----------------------------------------------------------------------------
  222. //
  223. // To add support for your user-defined type, add a proper `AbslHashValue()`
  224. // overload as a free (non-member) function. The overload will take an
  225. // existing hash state and should combine that state with state from the type.
  226. //
  227. // Example:
  228. //
  229. // template <typename H>
  230. // H AbslHashValue(H state, const MyType& v) {
  231. // return H::combine(std::move(state), v.field1, ..., v.fieldN);
  232. // }
  233. //
  234. // where `(field1, ..., fieldN)` are the members you would use on your
  235. // `operator==` to define equality.
  236. //
  237. // Notice that `AbslHashValue` is not a class member, but an ordinary function.
  238. // An `AbslHashValue` overload for a type should only be declared in the same
  239. // file and namespace as said type. The proper `AbslHashValue` implementation
  240. // for a given type will be discovered via ADL.
  241. //
  242. // Note: unlike `std::hash', `absl::Hash` should never be specialized. It must
  243. // only be extended by adding `AbslHashValue()` overloads.
  244. //
  245. template <typename T>
  246. using Hash = absl::hash_internal::Hash<T>;
  247. // HashOf
  248. //
  249. // absl::HashOf() is a helper that generates a hash from the values of its
  250. // arguments. It dispatches to absl::Hash directly, as follows:
  251. // * HashOf(t) == absl::Hash<T>{}(t)
  252. // * HashOf(a, b, c) == HashOf(std::make_tuple(a, b, c))
  253. //
  254. // HashOf(a1, a2, ...) == HashOf(b1, b2, ...) is guaranteed when
  255. // * The argument lists have pairwise identical C++ types
  256. // * a1 == b1 && a2 == b2 && ...
  257. //
  258. // The requirement that the arguments match in both type and value is critical.
  259. // It means that `a == b` does not necessarily imply `HashOf(a) == HashOf(b)` if
  260. // `a` and `b` have different types. For example, `HashOf(2) != HashOf(2.0)`.
  261. template <int&... ExplicitArgumentBarrier, typename... Types>
  262. size_t HashOf(const Types&... values) {
  263. auto tuple = std::tie(values...);
  264. return absl::Hash<decltype(tuple)>{}(tuple);
  265. }
  266. // HashState
  267. //
  268. // A type erased version of the hash state concept, for use in user-defined
  269. // `AbslHashValue` implementations that can't use templates (such as PImpl
  270. // classes, virtual functions, etc.). The type erasure adds overhead so it
  271. // should be avoided unless necessary.
  272. //
  273. // Note: This wrapper will only erase calls to
  274. // combine_contiguous(H, const unsigned char*, size_t)
  275. // RunCombineUnordered(H, CombinerF)
  276. //
  277. // All other calls will be handled internally and will not invoke overloads
  278. // provided by the wrapped class.
  279. //
  280. // Users of this class should still define a template `AbslHashValue` function,
  281. // but can use `absl::HashState::Create(&state)` to erase the type of the hash
  282. // state and dispatch to their private hashing logic.
  283. //
  284. // This state can be used like any other hash state. In particular, you can call
  285. // `HashState::combine()` and `HashState::combine_contiguous()` on it.
  286. //
  287. // Example:
  288. //
  289. // class Interface {
  290. // public:
  291. // template <typename H>
  292. // friend H AbslHashValue(H state, const Interface& value) {
  293. // state = H::combine(std::move(state), std::type_index(typeid(*this)));
  294. // value.HashValue(absl::HashState::Create(&state));
  295. // return state;
  296. // }
  297. // private:
  298. // virtual void HashValue(absl::HashState state) const = 0;
  299. // };
  300. //
  301. // class Impl : Interface {
  302. // private:
  303. // void HashValue(absl::HashState state) const override {
  304. // absl::HashState::combine(std::move(state), v1_, v2_);
  305. // }
  306. // int v1_;
  307. // std::string v2_;
  308. // };
  309. class HashState : public hash_internal::HashStateBase<HashState> {
  310. public:
  311. // HashState::Create()
  312. //
  313. // Create a new `HashState` instance that wraps `state`. All calls to
  314. // `combine()` and `combine_contiguous()` on the new instance will be
  315. // redirected to the original `state` object. The `state` object must outlive
  316. // the `HashState` instance.
  317. template <typename T>
  318. static HashState Create(T* state) {
  319. HashState s;
  320. s.Init(state);
  321. return s;
  322. }
  323. HashState(const HashState&) = delete;
  324. HashState& operator=(const HashState&) = delete;
  325. HashState(HashState&&) = default;
  326. HashState& operator=(HashState&&) = default;
  327. // HashState::combine()
  328. //
  329. // Combines an arbitrary number of values into a hash state, returning the
  330. // updated state.
  331. using HashState::HashStateBase::combine;
  332. // HashState::combine_contiguous()
  333. //
  334. // Combines a contiguous array of `size` elements into a hash state, returning
  335. // the updated state.
  336. static HashState combine_contiguous(HashState hash_state,
  337. const unsigned char* first, size_t size) {
  338. hash_state.combine_contiguous_(hash_state.state_, first, size);
  339. return hash_state;
  340. }
  341. using HashState::HashStateBase::combine_contiguous;
  342. private:
  343. HashState() = default;
  344. friend class HashState::HashStateBase;
  345. template <typename T>
  346. static void CombineContiguousImpl(void* p, const unsigned char* first,
  347. size_t size) {
  348. T& state = *static_cast<T*>(p);
  349. state = T::combine_contiguous(std::move(state), first, size);
  350. }
  351. template <typename T>
  352. void Init(T* state) {
  353. state_ = state;
  354. combine_contiguous_ = &CombineContiguousImpl<T>;
  355. run_combine_unordered_ = &RunCombineUnorderedImpl<T>;
  356. }
  357. template <typename HS>
  358. struct CombineUnorderedInvoker {
  359. template <typename T, typename ConsumerT>
  360. void operator()(T inner_state, ConsumerT inner_cb) {
  361. f(HashState::Create(&inner_state),
  362. [&](HashState& inner_erased) { inner_cb(inner_erased.Real<T>()); });
  363. }
  364. absl::FunctionRef<void(HS, absl::FunctionRef<void(HS&)>)> f;
  365. };
  366. template <typename T>
  367. static HashState RunCombineUnorderedImpl(
  368. HashState state,
  369. absl::FunctionRef<void(HashState, absl::FunctionRef<void(HashState&)>)>
  370. f) {
  371. // Note that this implementation assumes that inner_state and outer_state
  372. // are the same type. This isn't true in the SpyHash case, but SpyHash
  373. // types are move-convertible to each other, so this still works.
  374. T& real_state = state.Real<T>();
  375. real_state = T::RunCombineUnordered(
  376. std::move(real_state), CombineUnorderedInvoker<HashState>{f});
  377. return state;
  378. }
  379. template <typename CombinerT>
  380. static HashState RunCombineUnordered(HashState state, CombinerT combiner) {
  381. auto* run = state.run_combine_unordered_;
  382. return run(std::move(state), std::ref(combiner));
  383. }
  384. // Do not erase an already erased state.
  385. void Init(HashState* state) {
  386. state_ = state->state_;
  387. combine_contiguous_ = state->combine_contiguous_;
  388. run_combine_unordered_ = state->run_combine_unordered_;
  389. }
  390. template <typename T>
  391. T& Real() {
  392. return *static_cast<T*>(state_);
  393. }
  394. void* state_;
  395. void (*combine_contiguous_)(void*, const unsigned char*, size_t);
  396. HashState (*run_combine_unordered_)(
  397. HashState state,
  398. absl::FunctionRef<void(HashState, absl::FunctionRef<void(HashState&)>)>);
  399. };
  400. ABSL_NAMESPACE_END
  401. } // namespace absl
  402. #endif // ABSL_HASH_HASH_H_