hash.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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()` and
  30. // `combine_contiguous()`, which you can use to contribute to an existing
  31. // 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` is intended to strongly mix input bits with a target of passing
  44. // an [Avalanche Test](https://en.wikipedia.org/wiki/Avalanche_effect).
  45. //
  46. // Example:
  47. //
  48. // // Suppose we have a class `Circle` for which we want to add hashing:
  49. // class Circle {
  50. // public:
  51. // ...
  52. // private:
  53. // std::pair<int, int> center_;
  54. // int radius_;
  55. // };
  56. //
  57. // // To add hashing support to `Circle`, we simply need to add a free
  58. // // (non-member) function `AbslHashValue()`, and return the combined hash
  59. // // state of the existing hash state and the class state. You can add such a
  60. // // free function using a friend declaration within the body of the class:
  61. // class Circle {
  62. // public:
  63. // ...
  64. // template <typename H>
  65. // friend H AbslHashValue(H h, const Circle& c) {
  66. // return H::combine(std::move(h), c.center_, c.radius_);
  67. // }
  68. // ...
  69. // };
  70. //
  71. // For more information, see Adding Type Support to `absl::Hash` below.
  72. //
  73. #ifndef ABSL_HASH_HASH_H_
  74. #define ABSL_HASH_HASH_H_
  75. #include <tuple>
  76. #include "absl/hash/internal/hash.h"
  77. namespace absl {
  78. ABSL_NAMESPACE_BEGIN
  79. // -----------------------------------------------------------------------------
  80. // `absl::Hash`
  81. // -----------------------------------------------------------------------------
  82. //
  83. // `absl::Hash<T>` is a convenient general-purpose hash functor for any type `T`
  84. // satisfying any of the following conditions (in order):
  85. //
  86. // * T is an arithmetic or pointer type
  87. // * T defines an overload for `AbslHashValue(H, const T&)` for an arbitrary
  88. // hash state `H`.
  89. // - T defines a specialization of `std::hash<T>`
  90. //
  91. // `absl::Hash` intrinsically supports the following types:
  92. //
  93. // * All integral types (including bool)
  94. // * All enum types
  95. // * All floating-point types (although hashing them is discouraged)
  96. // * All pointer types, including nullptr_t
  97. // * std::pair<T1, T2>, if T1 and T2 are hashable
  98. // * std::tuple<Ts...>, if all the Ts... are hashable
  99. // * std::unique_ptr and std::shared_ptr
  100. // * All string-like types including:
  101. // * absl::Cord
  102. // * std::string
  103. // * std::string_view (as well as any instance of std::basic_string that
  104. // uses char and std::char_traits)
  105. // * All the standard sequence containers (provided the elements are hashable)
  106. // * All the standard ordered associative containers (provided the elements are
  107. // hashable)
  108. // * absl types such as the following:
  109. // * absl::string_view
  110. // * absl::InlinedVector
  111. // * absl::FixedArray
  112. // * absl::uint128
  113. // * absl::Time, absl::Duration, and absl::TimeZone
  114. //
  115. // Note: the list above is not meant to be exhaustive. Additional type support
  116. // may be added, in which case the above list will be updated.
  117. //
  118. // -----------------------------------------------------------------------------
  119. // absl::Hash Invocation Evaluation
  120. // -----------------------------------------------------------------------------
  121. //
  122. // When invoked, `absl::Hash<T>` searches for supplied hash functions in the
  123. // following order:
  124. //
  125. // * Natively supported types out of the box (see above)
  126. // * Types for which an `AbslHashValue()` overload is provided (such as
  127. // user-defined types). See "Adding Type Support to `absl::Hash`" below.
  128. // * Types which define a `std::hash<T>` specialization
  129. //
  130. // The fallback to legacy hash functions exists mainly for backwards
  131. // compatibility. If you have a choice, prefer defining an `AbslHashValue`
  132. // overload instead of specializing any legacy hash functors.
  133. //
  134. // -----------------------------------------------------------------------------
  135. // The Hash State Concept, and using `HashState` for Type Erasure
  136. // -----------------------------------------------------------------------------
  137. //
  138. // The `absl::Hash` framework relies on the Concept of a "hash state." Such a
  139. // hash state is used in several places:
  140. //
  141. // * Within existing implementations of `absl::Hash<T>` to store the hashed
  142. // state of an object. Note that it is up to the implementation how it stores
  143. // such state. A hash table, for example, may mix the state to produce an
  144. // integer value; a testing framework may simply hold a vector of that state.
  145. // * Within implementations of `AbslHashValue()` used to extend user-defined
  146. // types. (See "Adding Type Support to absl::Hash" below.)
  147. // * Inside a `HashState`, providing type erasure for the concept of a hash
  148. // state, which you can use to extend the `absl::Hash` framework for types
  149. // that are otherwise difficult to extend using `AbslHashValue()`. (See the
  150. // `HashState` class below.)
  151. //
  152. // The "hash state" concept contains two member functions for mixing hash state:
  153. //
  154. // * `H::combine(state, values...)`
  155. //
  156. // Combines an arbitrary number of values into a hash state, returning the
  157. // updated state. Note that the existing hash state is move-only and must be
  158. // passed by value.
  159. //
  160. // Each of the value types T must be hashable by H.
  161. //
  162. // NOTE:
  163. //
  164. // state = H::combine(std::move(state), value1, value2, value3);
  165. //
  166. // must be guaranteed to produce the same hash expansion as
  167. //
  168. // state = H::combine(std::move(state), value1);
  169. // state = H::combine(std::move(state), value2);
  170. // state = H::combine(std::move(state), value3);
  171. //
  172. // * `H::combine_contiguous(state, data, size)`
  173. //
  174. // Combines a contiguous array of `size` elements into a hash state,
  175. // returning the updated state. Note that the existing hash state is
  176. // move-only and must be passed by value.
  177. //
  178. // NOTE:
  179. //
  180. // state = H::combine_contiguous(std::move(state), data, size);
  181. //
  182. // need NOT be guaranteed to produce the same hash expansion as a loop
  183. // (it may perform internal optimizations). If you need this guarantee, use a
  184. // loop instead.
  185. //
  186. // -----------------------------------------------------------------------------
  187. // Adding Type Support to `absl::Hash`
  188. // -----------------------------------------------------------------------------
  189. //
  190. // To add support for your user-defined type, add a proper `AbslHashValue()`
  191. // overload as a free (non-member) function. The overload will take an
  192. // existing hash state and should combine that state with state from the type.
  193. //
  194. // Example:
  195. //
  196. // template <typename H>
  197. // H AbslHashValue(H state, const MyType& v) {
  198. // return H::combine(std::move(state), v.field1, ..., v.fieldN);
  199. // }
  200. //
  201. // where `(field1, ..., fieldN)` are the members you would use on your
  202. // `operator==` to define equality.
  203. //
  204. // Notice that `AbslHashValue` is not a class member, but an ordinary function.
  205. // An `AbslHashValue` overload for a type should only be declared in the same
  206. // file and namespace as said type. The proper `AbslHashValue` implementation
  207. // for a given type will be discovered via ADL.
  208. //
  209. // Note: unlike `std::hash', `absl::Hash` should never be specialized. It must
  210. // only be extended by adding `AbslHashValue()` overloads.
  211. //
  212. template <typename T>
  213. using Hash = absl::hash_internal::Hash<T>;
  214. // HashOf
  215. //
  216. // absl::HashOf() is a helper that generates a hash from the values of its
  217. // arguments. It dispatches to absl::Hash directly, as follows:
  218. // * HashOf(t) == absl::Hash<T>{}(t)
  219. // * HashOf(a, b, c) == HashOf(std::make_tuple(a, b, c))
  220. //
  221. // HashOf(a1, a2, ...) == HashOf(b1, b2, ...) is guaranteed when
  222. // * The argument lists have pairwise identical C++ types
  223. // * a1 == b1 && a2 == b2 && ...
  224. //
  225. // The requirement that the arguments match in both type and value is critical.
  226. // It means that `a == b` does not necessarily imply `HashOf(a) == HashOf(b)` if
  227. // `a` and `b` have different types. For example, `HashOf(2) != HashOf(2.0)`.
  228. template <int&... ExplicitArgumentBarrier, typename... Types>
  229. size_t HashOf(const Types&... values) {
  230. auto tuple = std::tie(values...);
  231. return absl::Hash<decltype(tuple)>{}(tuple);
  232. }
  233. // HashState
  234. //
  235. // A type erased version of the hash state concept, for use in user-defined
  236. // `AbslHashValue` implementations that can't use templates (such as PImpl
  237. // classes, virtual functions, etc.). The type erasure adds overhead so it
  238. // should be avoided unless necessary.
  239. //
  240. // Note: This wrapper will only erase calls to:
  241. // combine_contiguous(H, const unsigned char*, size_t)
  242. //
  243. // All other calls will be handled internally and will not invoke overloads
  244. // provided by the wrapped class.
  245. //
  246. // Users of this class should still define a template `AbslHashValue` function,
  247. // but can use `absl::HashState::Create(&state)` to erase the type of the hash
  248. // state and dispatch to their private hashing logic.
  249. //
  250. // This state can be used like any other hash state. In particular, you can call
  251. // `HashState::combine()` and `HashState::combine_contiguous()` on it.
  252. //
  253. // Example:
  254. //
  255. // class Interface {
  256. // public:
  257. // template <typename H>
  258. // friend H AbslHashValue(H state, const Interface& value) {
  259. // state = H::combine(std::move(state), std::type_index(typeid(*this)));
  260. // value.HashValue(absl::HashState::Create(&state));
  261. // return state;
  262. // }
  263. // private:
  264. // virtual void HashValue(absl::HashState state) const = 0;
  265. // };
  266. //
  267. // class Impl : Interface {
  268. // private:
  269. // void HashValue(absl::HashState state) const override {
  270. // absl::HashState::combine(std::move(state), v1_, v2_);
  271. // }
  272. // int v1_;
  273. // std::string v2_;
  274. // };
  275. class HashState : public hash_internal::HashStateBase<HashState> {
  276. public:
  277. // HashState::Create()
  278. //
  279. // Create a new `HashState` instance that wraps `state`. All calls to
  280. // `combine()` and `combine_contiguous()` on the new instance will be
  281. // redirected to the original `state` object. The `state` object must outlive
  282. // the `HashState` instance.
  283. template <typename T>
  284. static HashState Create(T* state) {
  285. HashState s;
  286. s.Init(state);
  287. return s;
  288. }
  289. HashState(const HashState&) = delete;
  290. HashState& operator=(const HashState&) = delete;
  291. HashState(HashState&&) = default;
  292. HashState& operator=(HashState&&) = default;
  293. // HashState::combine()
  294. //
  295. // Combines an arbitrary number of values into a hash state, returning the
  296. // updated state.
  297. using HashState::HashStateBase::combine;
  298. // HashState::combine_contiguous()
  299. //
  300. // Combines a contiguous array of `size` elements into a hash state, returning
  301. // the updated state.
  302. static HashState combine_contiguous(HashState hash_state,
  303. const unsigned char* first, size_t size) {
  304. hash_state.combine_contiguous_(hash_state.state_, first, size);
  305. return hash_state;
  306. }
  307. using HashState::HashStateBase::combine_contiguous;
  308. private:
  309. HashState() = default;
  310. template <typename T>
  311. static void CombineContiguousImpl(void* p, const unsigned char* first,
  312. size_t size) {
  313. T& state = *static_cast<T*>(p);
  314. state = T::combine_contiguous(std::move(state), first, size);
  315. }
  316. template <typename T>
  317. void Init(T* state) {
  318. state_ = state;
  319. combine_contiguous_ = &CombineContiguousImpl<T>;
  320. }
  321. // Do not erase an already erased state.
  322. void Init(HashState* state) {
  323. state_ = state->state_;
  324. combine_contiguous_ = state->combine_contiguous_;
  325. }
  326. void* state_;
  327. void (*combine_contiguous_)(void*, const unsigned char*, size_t);
  328. };
  329. ABSL_NAMESPACE_END
  330. } // namespace absl
  331. #endif // ABSL_HASH_HASH_H_