hash.h 12 KB

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