hash.h 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328
  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. #ifndef Y_ABSL_HASH_INTERNAL_HASH_H_
  20. #define Y_ABSL_HASH_INTERNAL_HASH_H_
  21. #include <algorithm>
  22. #include <array>
  23. #include <bitset>
  24. #include <cmath>
  25. #include <cstddef>
  26. #include <cstring>
  27. #include <deque>
  28. #include <forward_list>
  29. #include <functional>
  30. #include <iterator>
  31. #include <limits>
  32. #include <list>
  33. #include <map>
  34. #include <memory>
  35. #include <set>
  36. #include <util/generic/string.h>
  37. #include <tuple>
  38. #include <type_traits>
  39. #include <unordered_map>
  40. #include <unordered_set>
  41. #include <utility>
  42. #include <vector>
  43. #include "y_absl/base/config.h"
  44. #include "y_absl/base/internal/unaligned_access.h"
  45. #include "y_absl/base/port.h"
  46. #include "y_absl/container/fixed_array.h"
  47. #include "y_absl/hash/internal/city.h"
  48. #include "y_absl/hash/internal/low_level_hash.h"
  49. #include "y_absl/meta/type_traits.h"
  50. #include "y_absl/numeric/bits.h"
  51. #include "y_absl/numeric/int128.h"
  52. #include "y_absl/strings/string_view.h"
  53. #include "y_absl/types/optional.h"
  54. #include "y_absl/types/variant.h"
  55. #include "y_absl/utility/utility.h"
  56. #ifdef Y_ABSL_HAVE_STD_STRING_VIEW
  57. #include <string_view>
  58. #endif
  59. namespace y_absl {
  60. Y_ABSL_NAMESPACE_BEGIN
  61. class HashState;
  62. namespace hash_internal {
  63. // Internal detail: Large buffers are hashed in smaller chunks. This function
  64. // returns the size of these chunks.
  65. constexpr size_t PiecewiseChunkSize() { return 1024; }
  66. // PiecewiseCombiner
  67. //
  68. // PiecewiseCombiner is an internal-only helper class for hashing a piecewise
  69. // buffer of `char` or `unsigned char` as though it were contiguous. This class
  70. // provides two methods:
  71. //
  72. // H add_buffer(state, data, size)
  73. // H finalize(state)
  74. //
  75. // `add_buffer` can be called zero or more times, followed by a single call to
  76. // `finalize`. This will produce the same hash expansion as concatenating each
  77. // buffer piece into a single contiguous buffer, and passing this to
  78. // `H::combine_contiguous`.
  79. //
  80. // Example usage:
  81. // PiecewiseCombiner combiner;
  82. // for (const auto& piece : pieces) {
  83. // state = combiner.add_buffer(std::move(state), piece.data, piece.size);
  84. // }
  85. // return combiner.finalize(std::move(state));
  86. class PiecewiseCombiner {
  87. public:
  88. PiecewiseCombiner() : position_(0) {}
  89. PiecewiseCombiner(const PiecewiseCombiner&) = delete;
  90. PiecewiseCombiner& operator=(const PiecewiseCombiner&) = delete;
  91. // PiecewiseCombiner::add_buffer()
  92. //
  93. // Appends the given range of bytes to the sequence to be hashed, which may
  94. // modify the provided hash state.
  95. template <typename H>
  96. H add_buffer(H state, const unsigned char* data, size_t size);
  97. template <typename H>
  98. H add_buffer(H state, const char* data, size_t size) {
  99. return add_buffer(std::move(state),
  100. reinterpret_cast<const unsigned char*>(data), size);
  101. }
  102. // PiecewiseCombiner::finalize()
  103. //
  104. // Finishes combining the hash sequence, which may may modify the provided
  105. // hash state.
  106. //
  107. // Once finalize() is called, add_buffer() may no longer be called. The
  108. // resulting hash state will be the same as if the pieces passed to
  109. // add_buffer() were concatenated into a single flat buffer, and then provided
  110. // to H::combine_contiguous().
  111. template <typename H>
  112. H finalize(H state);
  113. private:
  114. unsigned char buf_[PiecewiseChunkSize()];
  115. size_t position_;
  116. };
  117. // is_hashable()
  118. //
  119. // Trait class which returns true if T is hashable by the y_absl::Hash framework.
  120. // Used for the AbslHashValue implementations for composite types below.
  121. template <typename T>
  122. struct is_hashable;
  123. // HashStateBase
  124. //
  125. // An internal implementation detail that contains common implementation details
  126. // for all of the "hash state objects" objects generated by Abseil. This is not
  127. // a public API; users should not create classes that inherit from this.
  128. //
  129. // A hash state object is the template argument `H` passed to `AbslHashValue`.
  130. // It represents an intermediate state in the computation of an unspecified hash
  131. // algorithm. `HashStateBase` provides a CRTP style base class for hash state
  132. // implementations. Developers adding type support for `y_absl::Hash` should not
  133. // rely on any parts of the state object other than the following member
  134. // functions:
  135. //
  136. // * HashStateBase::combine()
  137. // * HashStateBase::combine_contiguous()
  138. // * HashStateBase::combine_unordered()
  139. //
  140. // A derived hash state class of type `H` must provide a public member function
  141. // with a signature similar to the following:
  142. //
  143. // `static H combine_contiguous(H state, const unsigned char*, size_t)`.
  144. //
  145. // It must also provide a private template method named RunCombineUnordered.
  146. //
  147. // A "consumer" is a 1-arg functor returning void. Its argument is a reference
  148. // to an inner hash state object, and it may be called multiple times. When
  149. // called, the functor consumes the entropy from the provided state object,
  150. // and resets that object to its empty state.
  151. //
  152. // A "combiner" is a stateless 2-arg functor returning void. Its arguments are
  153. // an inner hash state object and an ElementStateConsumer functor. A combiner
  154. // uses the provided inner hash state object to hash each element of the
  155. // container, passing the inner hash state object to the consumer after hashing
  156. // each element.
  157. //
  158. // Given these definitions, a derived hash state class of type H
  159. // must provide a private template method with a signature similar to the
  160. // following:
  161. //
  162. // `template <typename CombinerT>`
  163. // `static H RunCombineUnordered(H outer_state, CombinerT combiner)`
  164. //
  165. // This function is responsible for constructing the inner state object and
  166. // providing a consumer to the combiner. It uses side effects of the consumer
  167. // and combiner to mix the state of each element in an order-independent manner,
  168. // and uses this to return an updated value of `outer_state`.
  169. //
  170. // This inside-out approach generates efficient object code in the normal case,
  171. // but allows us to use stack storage to implement the y_absl::HashState type
  172. // erasure mechanism (avoiding heap allocations while hashing).
  173. //
  174. // `HashStateBase` will provide a complete implementation for a hash state
  175. // object in terms of these two methods.
  176. //
  177. // Example:
  178. //
  179. // // Use CRTP to define your derived class.
  180. // struct MyHashState : HashStateBase<MyHashState> {
  181. // static H combine_contiguous(H state, const unsigned char*, size_t);
  182. // using MyHashState::HashStateBase::combine;
  183. // using MyHashState::HashStateBase::combine_contiguous;
  184. // using MyHashState::HashStateBase::combine_unordered;
  185. // private:
  186. // template <typename CombinerT>
  187. // static H RunCombineUnordered(H state, CombinerT combiner);
  188. // };
  189. template <typename H>
  190. class HashStateBase {
  191. public:
  192. // HashStateBase::combine()
  193. //
  194. // Combines an arbitrary number of values into a hash state, returning the
  195. // updated state.
  196. //
  197. // Each of the value types `T` must be separately hashable by the Abseil
  198. // hashing framework.
  199. //
  200. // NOTE:
  201. //
  202. // state = H::combine(std::move(state), value1, value2, value3);
  203. //
  204. // is guaranteed to produce the same hash expansion as:
  205. //
  206. // state = H::combine(std::move(state), value1);
  207. // state = H::combine(std::move(state), value2);
  208. // state = H::combine(std::move(state), value3);
  209. template <typename T, typename... Ts>
  210. static H combine(H state, const T& value, const Ts&... values);
  211. static H combine(H state) { return state; }
  212. // HashStateBase::combine_contiguous()
  213. //
  214. // Combines a contiguous array of `size` elements into a hash state, returning
  215. // the updated state.
  216. //
  217. // NOTE:
  218. //
  219. // state = H::combine_contiguous(std::move(state), data, size);
  220. //
  221. // is NOT guaranteed to produce the same hash expansion as a for-loop (it may
  222. // perform internal optimizations). If you need this guarantee, use the
  223. // for-loop instead.
  224. template <typename T>
  225. static H combine_contiguous(H state, const T* data, size_t size);
  226. template <typename I>
  227. static H combine_unordered(H state, I begin, I end);
  228. using AbslInternalPiecewiseCombiner = PiecewiseCombiner;
  229. template <typename T>
  230. using is_hashable = y_absl::hash_internal::is_hashable<T>;
  231. private:
  232. // Common implementation of the iteration step of a "combiner", as described
  233. // above.
  234. template <typename I>
  235. struct CombineUnorderedCallback {
  236. I begin;
  237. I end;
  238. template <typename InnerH, typename ElementStateConsumer>
  239. void operator()(InnerH inner_state, ElementStateConsumer cb) {
  240. for (; begin != end; ++begin) {
  241. inner_state = H::combine(std::move(inner_state), *begin);
  242. cb(inner_state);
  243. }
  244. }
  245. };
  246. };
  247. // is_uniquely_represented
  248. //
  249. // `is_uniquely_represented<T>` is a trait class that indicates whether `T`
  250. // is uniquely represented.
  251. //
  252. // A type is "uniquely represented" if two equal values of that type are
  253. // guaranteed to have the same bytes in their underlying storage. In other
  254. // words, if `a == b`, then `memcmp(&a, &b, sizeof(T))` is guaranteed to be
  255. // zero. This property cannot be detected automatically, so this trait is false
  256. // by default, but can be specialized by types that wish to assert that they are
  257. // uniquely represented. This makes them eligible for certain optimizations.
  258. //
  259. // If you have any doubt whatsoever, do not specialize this template.
  260. // The default is completely safe, and merely disables some optimizations
  261. // that will not matter for most types. Specializing this template,
  262. // on the other hand, can be very hazardous.
  263. //
  264. // To be uniquely represented, a type must not have multiple ways of
  265. // representing the same value; for example, float and double are not
  266. // uniquely represented, because they have distinct representations for
  267. // +0 and -0. Furthermore, the type's byte representation must consist
  268. // solely of user-controlled data, with no padding bits and no compiler-
  269. // controlled data such as vptrs or sanitizer metadata. This is usually
  270. // very difficult to guarantee, because in most cases the compiler can
  271. // insert data and padding bits at its own discretion.
  272. //
  273. // If you specialize this template for a type `T`, you must do so in the file
  274. // that defines that type (or in this file). If you define that specialization
  275. // anywhere else, `is_uniquely_represented<T>` could have different meanings
  276. // in different places.
  277. //
  278. // The Enable parameter is meaningless; it is provided as a convenience,
  279. // to support certain SFINAE techniques when defining specializations.
  280. template <typename T, typename Enable = void>
  281. struct is_uniquely_represented : std::false_type {};
  282. // is_uniquely_represented<unsigned char>
  283. //
  284. // unsigned char is a synonym for "byte", so it is guaranteed to be
  285. // uniquely represented.
  286. template <>
  287. struct is_uniquely_represented<unsigned char> : std::true_type {};
  288. // is_uniquely_represented for non-standard integral types
  289. //
  290. // Integral types other than bool should be uniquely represented on any
  291. // platform that this will plausibly be ported to.
  292. template <typename Integral>
  293. struct is_uniquely_represented<
  294. Integral, typename std::enable_if<std::is_integral<Integral>::value>::type>
  295. : std::true_type {};
  296. // is_uniquely_represented<bool>
  297. //
  298. //
  299. template <>
  300. struct is_uniquely_represented<bool> : std::false_type {};
  301. // hash_bytes()
  302. //
  303. // Convenience function that combines `hash_state` with the byte representation
  304. // of `value`.
  305. template <typename H, typename T>
  306. H hash_bytes(H hash_state, const T& value) {
  307. const unsigned char* start = reinterpret_cast<const unsigned char*>(&value);
  308. return H::combine_contiguous(std::move(hash_state), start, sizeof(value));
  309. }
  310. // -----------------------------------------------------------------------------
  311. // AbslHashValue for Basic Types
  312. // -----------------------------------------------------------------------------
  313. // Note: Default `AbslHashValue` implementations live in `hash_internal`. This
  314. // allows us to block lexical scope lookup when doing an unqualified call to
  315. // `AbslHashValue` below. User-defined implementations of `AbslHashValue` can
  316. // only be found via ADL.
  317. // AbslHashValue() for hashing bool values
  318. //
  319. // We use SFINAE to ensure that this overload only accepts bool, not types that
  320. // are convertible to bool.
  321. template <typename H, typename B>
  322. typename std::enable_if<std::is_same<B, bool>::value, H>::type AbslHashValue(
  323. H hash_state, B value) {
  324. return H::combine(std::move(hash_state),
  325. static_cast<unsigned char>(value ? 1 : 0));
  326. }
  327. // AbslHashValue() for hashing enum values
  328. template <typename H, typename Enum>
  329. typename std::enable_if<std::is_enum<Enum>::value, H>::type AbslHashValue(
  330. H hash_state, Enum e) {
  331. // In practice, we could almost certainly just invoke hash_bytes directly,
  332. // but it's possible that a sanitizer might one day want to
  333. // store data in the unused bits of an enum. To avoid that risk, we
  334. // convert to the underlying type before hashing. Hopefully this will get
  335. // optimized away; if not, we can reopen discussion with c-toolchain-team.
  336. return H::combine(std::move(hash_state),
  337. static_cast<typename std::underlying_type<Enum>::type>(e));
  338. }
  339. // AbslHashValue() for hashing floating-point values
  340. template <typename H, typename Float>
  341. typename std::enable_if<std::is_same<Float, float>::value ||
  342. std::is_same<Float, double>::value,
  343. H>::type
  344. AbslHashValue(H hash_state, Float value) {
  345. return hash_internal::hash_bytes(std::move(hash_state),
  346. value == 0 ? 0 : value);
  347. }
  348. // Long double has the property that it might have extra unused bytes in it.
  349. // For example, in x86 sizeof(long double)==16 but it only really uses 80-bits
  350. // of it. This means we can't use hash_bytes on a long double and have to
  351. // convert it to something else first.
  352. template <typename H, typename LongDouble>
  353. typename std::enable_if<std::is_same<LongDouble, long double>::value, H>::type
  354. AbslHashValue(H hash_state, LongDouble value) {
  355. const int category = std::fpclassify(value);
  356. switch (category) {
  357. case FP_INFINITE:
  358. // Add the sign bit to differentiate between +Inf and -Inf
  359. hash_state = H::combine(std::move(hash_state), std::signbit(value));
  360. break;
  361. case FP_NAN:
  362. case FP_ZERO:
  363. default:
  364. // Category is enough for these.
  365. break;
  366. case FP_NORMAL:
  367. case FP_SUBNORMAL:
  368. // We can't convert `value` directly to double because this would have
  369. // undefined behavior if the value is out of range.
  370. // std::frexp gives us a value in the range (-1, -.5] or [.5, 1) that is
  371. // guaranteed to be in range for `double`. The truncation is
  372. // implementation defined, but that works as long as it is deterministic.
  373. int exp;
  374. auto mantissa = static_cast<double>(std::frexp(value, &exp));
  375. hash_state = H::combine(std::move(hash_state), mantissa, exp);
  376. }
  377. return H::combine(std::move(hash_state), category);
  378. }
  379. // AbslHashValue() for hashing pointers
  380. template <typename H, typename T>
  381. H AbslHashValue(H hash_state, T* ptr) {
  382. auto v = reinterpret_cast<uintptr_t>(ptr);
  383. // Due to alignment, pointers tend to have low bits as zero, and the next few
  384. // bits follow a pattern since they are also multiples of some base value.
  385. // Mixing the pointer twice helps prevent stuck low bits for certain alignment
  386. // values.
  387. return H::combine(std::move(hash_state), v, v);
  388. }
  389. // AbslHashValue() for hashing nullptr_t
  390. template <typename H>
  391. H AbslHashValue(H hash_state, std::nullptr_t) {
  392. return H::combine(std::move(hash_state), static_cast<void*>(nullptr));
  393. }
  394. // AbslHashValue() for hashing pointers-to-member
  395. template <typename H, typename T, typename C>
  396. H AbslHashValue(H hash_state, T C::*ptr) {
  397. auto salient_ptm_size = [](std::size_t n) -> std::size_t {
  398. #if defined(_MSC_VER)
  399. // Pointers-to-member-function on MSVC consist of one pointer plus 0, 1, 2,
  400. // or 3 ints. In 64-bit mode, they are 8-byte aligned and thus can contain
  401. // padding (namely when they have 1 or 3 ints). The value below is a lower
  402. // bound on the number of salient, non-padding bytes that we use for
  403. // hashing.
  404. if (alignof(T C::*) == alignof(int)) {
  405. // No padding when all subobjects have the same size as the total
  406. // alignment. This happens in 32-bit mode.
  407. return n;
  408. } else {
  409. // Padding for 1 int (size 16) or 3 ints (size 24).
  410. // With 2 ints, the size is 16 with no padding, which we pessimize.
  411. return n == 24 ? 20 : n == 16 ? 12 : n;
  412. }
  413. #else
  414. // On other platforms, we assume that pointers-to-members do not have
  415. // padding.
  416. #ifdef __cpp_lib_has_unique_object_representations
  417. static_assert(std::has_unique_object_representations<T C::*>::value);
  418. #endif // __cpp_lib_has_unique_object_representations
  419. return n;
  420. #endif
  421. };
  422. return H::combine_contiguous(std::move(hash_state),
  423. reinterpret_cast<unsigned char*>(&ptr),
  424. salient_ptm_size(sizeof ptr));
  425. }
  426. // -----------------------------------------------------------------------------
  427. // AbslHashValue for Composite Types
  428. // -----------------------------------------------------------------------------
  429. // AbslHashValue() for hashing pairs
  430. template <typename H, typename T1, typename T2>
  431. typename std::enable_if<is_hashable<T1>::value && is_hashable<T2>::value,
  432. H>::type
  433. AbslHashValue(H hash_state, const std::pair<T1, T2>& p) {
  434. return H::combine(std::move(hash_state), p.first, p.second);
  435. }
  436. // hash_tuple()
  437. //
  438. // Helper function for hashing a tuple. The third argument should
  439. // be an index_sequence running from 0 to tuple_size<Tuple> - 1.
  440. template <typename H, typename Tuple, size_t... Is>
  441. H hash_tuple(H hash_state, const Tuple& t, y_absl::index_sequence<Is...>) {
  442. return H::combine(std::move(hash_state), std::get<Is>(t)...);
  443. }
  444. // AbslHashValue for hashing tuples
  445. template <typename H, typename... Ts>
  446. #if defined(_MSC_VER)
  447. // This SFINAE gets MSVC confused under some conditions. Let's just disable it
  448. // for now.
  449. H
  450. #else // _MSC_VER
  451. typename std::enable_if<y_absl::conjunction<is_hashable<Ts>...>::value, H>::type
  452. #endif // _MSC_VER
  453. AbslHashValue(H hash_state, const std::tuple<Ts...>& t) {
  454. return hash_internal::hash_tuple(std::move(hash_state), t,
  455. y_absl::make_index_sequence<sizeof...(Ts)>());
  456. }
  457. // -----------------------------------------------------------------------------
  458. // AbslHashValue for Pointers
  459. // -----------------------------------------------------------------------------
  460. // AbslHashValue for hashing unique_ptr
  461. template <typename H, typename T, typename D>
  462. H AbslHashValue(H hash_state, const std::unique_ptr<T, D>& ptr) {
  463. return H::combine(std::move(hash_state), ptr.get());
  464. }
  465. // AbslHashValue for hashing shared_ptr
  466. template <typename H, typename T>
  467. H AbslHashValue(H hash_state, const std::shared_ptr<T>& ptr) {
  468. return H::combine(std::move(hash_state), ptr.get());
  469. }
  470. // -----------------------------------------------------------------------------
  471. // AbslHashValue for String-Like Types
  472. // -----------------------------------------------------------------------------
  473. // AbslHashValue for hashing strings
  474. //
  475. // All the string-like types supported here provide the same hash expansion for
  476. // the same character sequence. These types are:
  477. //
  478. // - `y_absl::Cord`
  479. // - `TString` (and std::basic_string<T, std::char_traits<T>, A> for
  480. // any allocator A and any T in {char, wchar_t, char16_t, char32_t})
  481. // - `y_absl::string_view`, `std::string_view`, `std::wstring_view`,
  482. // `std::u16string_view`, and `std::u32_string_view`.
  483. //
  484. // For simplicity, we currently support only strings built on `char`, `wchar_t`,
  485. // `char16_t`, or `char32_t`. This support may be broadened, if necessary, but
  486. // with some caution - this overload would misbehave in cases where the traits'
  487. // `eq()` member isn't equivalent to `==` on the underlying character type.
  488. template <typename H>
  489. H AbslHashValue(H hash_state, y_absl::string_view str) {
  490. return H::combine(
  491. H::combine_contiguous(std::move(hash_state), str.data(), str.size()),
  492. str.size());
  493. }
  494. // Support std::wstring, std::u16string and std::u32string.
  495. template <typename Char, typename Alloc, typename H,
  496. typename = y_absl::enable_if_t<std::is_same<Char, wchar_t>::value ||
  497. std::is_same<Char, char16_t>::value ||
  498. std::is_same<Char, char32_t>::value>>
  499. H AbslHashValue(
  500. H hash_state,
  501. const std::basic_string<Char, std::char_traits<Char>, Alloc>& str) {
  502. return H::combine(
  503. H::combine_contiguous(std::move(hash_state), str.data(), str.size()),
  504. str.size());
  505. }
  506. #ifdef Y_ABSL_HAVE_STD_STRING_VIEW
  507. // Support std::wstring_view, std::u16string_view and std::u32string_view.
  508. template <typename Char, typename H,
  509. typename = y_absl::enable_if_t<std::is_same<Char, wchar_t>::value ||
  510. std::is_same<Char, char16_t>::value ||
  511. std::is_same<Char, char32_t>::value>>
  512. H AbslHashValue(H hash_state, std::basic_string_view<Char> str) {
  513. return H::combine(
  514. H::combine_contiguous(std::move(hash_state), str.data(), str.size()),
  515. str.size());
  516. }
  517. #endif // Y_ABSL_HAVE_STD_STRING_VIEW
  518. // -----------------------------------------------------------------------------
  519. // AbslHashValue for Sequence Containers
  520. // -----------------------------------------------------------------------------
  521. // AbslHashValue for hashing std::array
  522. template <typename H, typename T, size_t N>
  523. typename std::enable_if<is_hashable<T>::value, H>::type AbslHashValue(
  524. H hash_state, const std::array<T, N>& array) {
  525. return H::combine_contiguous(std::move(hash_state), array.data(),
  526. array.size());
  527. }
  528. // AbslHashValue for hashing std::deque
  529. template <typename H, typename T, typename Allocator>
  530. typename std::enable_if<is_hashable<T>::value, H>::type AbslHashValue(
  531. H hash_state, const std::deque<T, Allocator>& deque) {
  532. // TODO(gromer): investigate a more efficient implementation taking
  533. // advantage of the chunk structure.
  534. for (const auto& t : deque) {
  535. hash_state = H::combine(std::move(hash_state), t);
  536. }
  537. return H::combine(std::move(hash_state), deque.size());
  538. }
  539. // AbslHashValue for hashing std::forward_list
  540. template <typename H, typename T, typename Allocator>
  541. typename std::enable_if<is_hashable<T>::value, H>::type AbslHashValue(
  542. H hash_state, const std::forward_list<T, Allocator>& list) {
  543. size_t size = 0;
  544. for (const T& t : list) {
  545. hash_state = H::combine(std::move(hash_state), t);
  546. ++size;
  547. }
  548. return H::combine(std::move(hash_state), size);
  549. }
  550. // AbslHashValue for hashing std::list
  551. template <typename H, typename T, typename Allocator>
  552. typename std::enable_if<is_hashable<T>::value, H>::type AbslHashValue(
  553. H hash_state, const std::list<T, Allocator>& list) {
  554. for (const auto& t : list) {
  555. hash_state = H::combine(std::move(hash_state), t);
  556. }
  557. return H::combine(std::move(hash_state), list.size());
  558. }
  559. // AbslHashValue for hashing std::vector
  560. //
  561. // Do not use this for vector<bool> on platforms that have a working
  562. // implementation of std::hash. It does not have a .data(), and a fallback for
  563. // std::hash<> is most likely faster.
  564. template <typename H, typename T, typename Allocator>
  565. typename std::enable_if<is_hashable<T>::value && !std::is_same<T, bool>::value,
  566. H>::type
  567. AbslHashValue(H hash_state, const std::vector<T, Allocator>& vector) {
  568. return H::combine(H::combine_contiguous(std::move(hash_state), vector.data(),
  569. vector.size()),
  570. vector.size());
  571. }
  572. // AbslHashValue special cases for hashing std::vector<bool>
  573. #if defined(Y_ABSL_IS_BIG_ENDIAN) && \
  574. (defined(__GLIBCXX__) || defined(__GLIBCPP__))
  575. // std::hash in libstdc++ does not work correctly with vector<bool> on Big
  576. // Endian platforms therefore we need to implement a custom AbslHashValue for
  577. // it. More details on the bug:
  578. // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=102531
  579. template <typename H, typename T, typename Allocator>
  580. typename std::enable_if<is_hashable<T>::value && std::is_same<T, bool>::value,
  581. H>::type
  582. AbslHashValue(H hash_state, const std::vector<T, Allocator>& vector) {
  583. typename H::AbslInternalPiecewiseCombiner combiner;
  584. for (const auto& i : vector) {
  585. unsigned char c = static_cast<unsigned char>(i);
  586. hash_state = combiner.add_buffer(std::move(hash_state), &c, sizeof(c));
  587. }
  588. return H::combine(combiner.finalize(std::move(hash_state)), vector.size());
  589. }
  590. #else
  591. // When not working around the libstdc++ bug above, we still have to contend
  592. // with the fact that std::hash<vector<bool>> is often poor quality, hashing
  593. // directly on the internal words and on no other state. On these platforms,
  594. // vector<bool>{1, 1} and vector<bool>{1, 1, 0} hash to the same value.
  595. //
  596. // Mixing in the size (as we do in our other vector<> implementations) on top
  597. // of the library-provided hash implementation avoids this QOI issue.
  598. template <typename H, typename T, typename Allocator>
  599. typename std::enable_if<is_hashable<T>::value && std::is_same<T, bool>::value,
  600. H>::type
  601. AbslHashValue(H hash_state, const std::vector<T, Allocator>& vector) {
  602. return H::combine(std::move(hash_state),
  603. std::hash<std::vector<T, Allocator>>{}(vector),
  604. vector.size());
  605. }
  606. #endif
  607. // -----------------------------------------------------------------------------
  608. // AbslHashValue for Ordered Associative Containers
  609. // -----------------------------------------------------------------------------
  610. // AbslHashValue for hashing std::map
  611. template <typename H, typename Key, typename T, typename Compare,
  612. typename Allocator>
  613. typename std::enable_if<is_hashable<Key>::value && is_hashable<T>::value,
  614. H>::type
  615. AbslHashValue(H hash_state, const std::map<Key, T, Compare, Allocator>& map) {
  616. for (const auto& t : map) {
  617. hash_state = H::combine(std::move(hash_state), t);
  618. }
  619. return H::combine(std::move(hash_state), map.size());
  620. }
  621. // AbslHashValue for hashing std::multimap
  622. template <typename H, typename Key, typename T, typename Compare,
  623. typename Allocator>
  624. typename std::enable_if<is_hashable<Key>::value && is_hashable<T>::value,
  625. H>::type
  626. AbslHashValue(H hash_state,
  627. const std::multimap<Key, T, Compare, Allocator>& map) {
  628. for (const auto& t : map) {
  629. hash_state = H::combine(std::move(hash_state), t);
  630. }
  631. return H::combine(std::move(hash_state), map.size());
  632. }
  633. // AbslHashValue for hashing std::set
  634. template <typename H, typename Key, typename Compare, typename Allocator>
  635. typename std::enable_if<is_hashable<Key>::value, H>::type AbslHashValue(
  636. H hash_state, const std::set<Key, Compare, Allocator>& set) {
  637. for (const auto& t : set) {
  638. hash_state = H::combine(std::move(hash_state), t);
  639. }
  640. return H::combine(std::move(hash_state), set.size());
  641. }
  642. // AbslHashValue for hashing std::multiset
  643. template <typename H, typename Key, typename Compare, typename Allocator>
  644. typename std::enable_if<is_hashable<Key>::value, H>::type AbslHashValue(
  645. H hash_state, const std::multiset<Key, Compare, Allocator>& set) {
  646. for (const auto& t : set) {
  647. hash_state = H::combine(std::move(hash_state), t);
  648. }
  649. return H::combine(std::move(hash_state), set.size());
  650. }
  651. // -----------------------------------------------------------------------------
  652. // AbslHashValue for Unordered Associative Containers
  653. // -----------------------------------------------------------------------------
  654. // AbslHashValue for hashing std::unordered_set
  655. template <typename H, typename Key, typename Hash, typename KeyEqual,
  656. typename Alloc>
  657. typename std::enable_if<is_hashable<Key>::value, H>::type AbslHashValue(
  658. H hash_state, const std::unordered_set<Key, Hash, KeyEqual, Alloc>& s) {
  659. return H::combine(
  660. H::combine_unordered(std::move(hash_state), s.begin(), s.end()),
  661. s.size());
  662. }
  663. // AbslHashValue for hashing std::unordered_multiset
  664. template <typename H, typename Key, typename Hash, typename KeyEqual,
  665. typename Alloc>
  666. typename std::enable_if<is_hashable<Key>::value, H>::type AbslHashValue(
  667. H hash_state,
  668. const std::unordered_multiset<Key, Hash, KeyEqual, Alloc>& s) {
  669. return H::combine(
  670. H::combine_unordered(std::move(hash_state), s.begin(), s.end()),
  671. s.size());
  672. }
  673. // AbslHashValue for hashing std::unordered_set
  674. template <typename H, typename Key, typename T, typename Hash,
  675. typename KeyEqual, typename Alloc>
  676. typename std::enable_if<is_hashable<Key>::value && is_hashable<T>::value,
  677. H>::type
  678. AbslHashValue(H hash_state,
  679. const std::unordered_map<Key, T, Hash, KeyEqual, Alloc>& s) {
  680. return H::combine(
  681. H::combine_unordered(std::move(hash_state), s.begin(), s.end()),
  682. s.size());
  683. }
  684. // AbslHashValue for hashing std::unordered_multiset
  685. template <typename H, typename Key, typename T, typename Hash,
  686. typename KeyEqual, typename Alloc>
  687. typename std::enable_if<is_hashable<Key>::value && is_hashable<T>::value,
  688. H>::type
  689. AbslHashValue(H hash_state,
  690. const std::unordered_multimap<Key, T, Hash, KeyEqual, Alloc>& s) {
  691. return H::combine(
  692. H::combine_unordered(std::move(hash_state), s.begin(), s.end()),
  693. s.size());
  694. }
  695. // -----------------------------------------------------------------------------
  696. // AbslHashValue for Wrapper Types
  697. // -----------------------------------------------------------------------------
  698. // AbslHashValue for hashing std::reference_wrapper
  699. template <typename H, typename T>
  700. typename std::enable_if<is_hashable<T>::value, H>::type AbslHashValue(
  701. H hash_state, std::reference_wrapper<T> opt) {
  702. return H::combine(std::move(hash_state), opt.get());
  703. }
  704. // AbslHashValue for hashing y_absl::optional
  705. template <typename H, typename T>
  706. typename std::enable_if<is_hashable<T>::value, H>::type AbslHashValue(
  707. H hash_state, const y_absl::optional<T>& opt) {
  708. if (opt) hash_state = H::combine(std::move(hash_state), *opt);
  709. return H::combine(std::move(hash_state), opt.has_value());
  710. }
  711. // VariantVisitor
  712. template <typename H>
  713. struct VariantVisitor {
  714. H&& hash_state;
  715. template <typename T>
  716. H operator()(const T& t) const {
  717. return H::combine(std::move(hash_state), t);
  718. }
  719. };
  720. // AbslHashValue for hashing y_absl::variant
  721. template <typename H, typename... T>
  722. typename std::enable_if<conjunction<is_hashable<T>...>::value, H>::type
  723. AbslHashValue(H hash_state, const y_absl::variant<T...>& v) {
  724. if (!v.valueless_by_exception()) {
  725. hash_state = y_absl::visit(VariantVisitor<H>{std::move(hash_state)}, v);
  726. }
  727. return H::combine(std::move(hash_state), v.index());
  728. }
  729. // -----------------------------------------------------------------------------
  730. // AbslHashValue for Other Types
  731. // -----------------------------------------------------------------------------
  732. // AbslHashValue for hashing std::bitset is not defined on Little Endian
  733. // platforms, for the same reason as for vector<bool> (see std::vector above):
  734. // It does not expose the raw bytes, and a fallback to std::hash<> is most
  735. // likely faster.
  736. #if defined(Y_ABSL_IS_BIG_ENDIAN) && \
  737. (defined(__GLIBCXX__) || defined(__GLIBCPP__))
  738. // AbslHashValue for hashing std::bitset
  739. //
  740. // std::hash in libstdc++ does not work correctly with std::bitset on Big Endian
  741. // platforms therefore we need to implement a custom AbslHashValue for it. More
  742. // details on the bug: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=102531
  743. template <typename H, size_t N>
  744. H AbslHashValue(H hash_state, const std::bitset<N>& set) {
  745. typename H::AbslInternalPiecewiseCombiner combiner;
  746. for (int i = 0; i < N; i++) {
  747. unsigned char c = static_cast<unsigned char>(set[i]);
  748. hash_state = combiner.add_buffer(std::move(hash_state), &c, sizeof(c));
  749. }
  750. return H::combine(combiner.finalize(std::move(hash_state)), N);
  751. }
  752. #endif
  753. // -----------------------------------------------------------------------------
  754. // hash_range_or_bytes()
  755. //
  756. // Mixes all values in the range [data, data+size) into the hash state.
  757. // This overload accepts only uniquely-represented types, and hashes them by
  758. // hashing the entire range of bytes.
  759. template <typename H, typename T>
  760. typename std::enable_if<is_uniquely_represented<T>::value, H>::type
  761. hash_range_or_bytes(H hash_state, const T* data, size_t size) {
  762. const auto* bytes = reinterpret_cast<const unsigned char*>(data);
  763. return H::combine_contiguous(std::move(hash_state), bytes, sizeof(T) * size);
  764. }
  765. // hash_range_or_bytes()
  766. template <typename H, typename T>
  767. typename std::enable_if<!is_uniquely_represented<T>::value, H>::type
  768. hash_range_or_bytes(H hash_state, const T* data, size_t size) {
  769. for (const auto end = data + size; data < end; ++data) {
  770. hash_state = H::combine(std::move(hash_state), *data);
  771. }
  772. return hash_state;
  773. }
  774. #if defined(Y_ABSL_INTERNAL_LEGACY_HASH_NAMESPACE) && \
  775. Y_ABSL_META_INTERNAL_STD_HASH_SFINAE_FRIENDLY_
  776. #define Y_ABSL_HASH_INTERNAL_SUPPORT_LEGACY_HASH_ 1
  777. #else
  778. #define Y_ABSL_HASH_INTERNAL_SUPPORT_LEGACY_HASH_ 0
  779. #endif
  780. // HashSelect
  781. //
  782. // Type trait to select the appropriate hash implementation to use.
  783. // HashSelect::type<T> will give the proper hash implementation, to be invoked
  784. // as:
  785. // HashSelect::type<T>::Invoke(state, value)
  786. // Also, HashSelect::type<T>::value is a boolean equal to `true` if there is a
  787. // valid `Invoke` function. Types that are not hashable will have a ::value of
  788. // `false`.
  789. struct HashSelect {
  790. private:
  791. struct State : HashStateBase<State> {
  792. static State combine_contiguous(State hash_state, const unsigned char*,
  793. size_t);
  794. using State::HashStateBase::combine_contiguous;
  795. };
  796. struct UniquelyRepresentedProbe {
  797. template <typename H, typename T>
  798. static auto Invoke(H state, const T& value)
  799. -> y_absl::enable_if_t<is_uniquely_represented<T>::value, H> {
  800. return hash_internal::hash_bytes(std::move(state), value);
  801. }
  802. };
  803. struct HashValueProbe {
  804. template <typename H, typename T>
  805. static auto Invoke(H state, const T& value) -> y_absl::enable_if_t<
  806. std::is_same<H,
  807. decltype(AbslHashValue(std::move(state), value))>::value,
  808. H> {
  809. return AbslHashValue(std::move(state), value);
  810. }
  811. };
  812. struct LegacyHashProbe {
  813. #if Y_ABSL_HASH_INTERNAL_SUPPORT_LEGACY_HASH_
  814. template <typename H, typename T>
  815. static auto Invoke(H state, const T& value) -> y_absl::enable_if_t<
  816. std::is_convertible<
  817. decltype(Y_ABSL_INTERNAL_LEGACY_HASH_NAMESPACE::hash<T>()(value)),
  818. size_t>::value,
  819. H> {
  820. return hash_internal::hash_bytes(
  821. std::move(state),
  822. Y_ABSL_INTERNAL_LEGACY_HASH_NAMESPACE::hash<T>{}(value));
  823. }
  824. #endif // Y_ABSL_HASH_INTERNAL_SUPPORT_LEGACY_HASH_
  825. };
  826. struct StdHashProbe {
  827. template <typename H, typename T>
  828. static auto Invoke(H state, const T& value)
  829. -> y_absl::enable_if_t<type_traits_internal::IsHashable<T>::value, H> {
  830. return hash_internal::hash_bytes(std::move(state), std::hash<T>{}(value));
  831. }
  832. };
  833. template <typename Hash, typename T>
  834. struct Probe : Hash {
  835. private:
  836. template <typename H, typename = decltype(H::Invoke(
  837. std::declval<State>(), std::declval<const T&>()))>
  838. static std::true_type Test(int);
  839. template <typename U>
  840. static std::false_type Test(char);
  841. public:
  842. static constexpr bool value = decltype(Test<Hash>(0))::value;
  843. };
  844. public:
  845. // Probe each implementation in order.
  846. // disjunction provides short circuiting wrt instantiation.
  847. template <typename T>
  848. using Apply = y_absl::disjunction< //
  849. Probe<UniquelyRepresentedProbe, T>, //
  850. Probe<HashValueProbe, T>, //
  851. Probe<LegacyHashProbe, T>, //
  852. Probe<StdHashProbe, T>, //
  853. std::false_type>;
  854. };
  855. template <typename T>
  856. struct is_hashable
  857. : std::integral_constant<bool, HashSelect::template Apply<T>::value> {};
  858. // MixingHashState
  859. class Y_ABSL_DLL MixingHashState : public HashStateBase<MixingHashState> {
  860. // y_absl::uint128 is not an alias or a thin wrapper around the intrinsic.
  861. // We use the intrinsic when available to improve performance.
  862. #ifdef Y_ABSL_HAVE_INTRINSIC_INT128
  863. using uint128 = __uint128_t;
  864. #else // Y_ABSL_HAVE_INTRINSIC_INT128
  865. using uint128 = y_absl::uint128;
  866. #endif // Y_ABSL_HAVE_INTRINSIC_INT128
  867. static constexpr uint64_t kMul =
  868. sizeof(size_t) == 4 ? uint64_t{0xcc9e2d51}
  869. : uint64_t{0x9ddfea08eb382d69};
  870. template <typename T>
  871. using IntegralFastPath =
  872. conjunction<std::is_integral<T>, is_uniquely_represented<T>>;
  873. public:
  874. // Move only
  875. MixingHashState(MixingHashState&&) = default;
  876. MixingHashState& operator=(MixingHashState&&) = default;
  877. // MixingHashState::combine_contiguous()
  878. //
  879. // Fundamental base case for hash recursion: mixes the given range of bytes
  880. // into the hash state.
  881. static MixingHashState combine_contiguous(MixingHashState hash_state,
  882. const unsigned char* first,
  883. size_t size) {
  884. return MixingHashState(
  885. CombineContiguousImpl(hash_state.state_, first, size,
  886. std::integral_constant<int, sizeof(size_t)>{}));
  887. }
  888. using MixingHashState::HashStateBase::combine_contiguous;
  889. // MixingHashState::hash()
  890. //
  891. // For performance reasons in non-opt mode, we specialize this for
  892. // integral types.
  893. // Otherwise we would be instantiating and calling dozens of functions for
  894. // something that is just one multiplication and a couple xor's.
  895. // The result should be the same as running the whole algorithm, but faster.
  896. template <typename T, y_absl::enable_if_t<IntegralFastPath<T>::value, int> = 0>
  897. static size_t hash(T value) {
  898. return static_cast<size_t>(
  899. Mix(Seed(), static_cast<std::make_unsigned_t<T>>(value)));
  900. }
  901. // Overload of MixingHashState::hash()
  902. template <typename T, y_absl::enable_if_t<!IntegralFastPath<T>::value, int> = 0>
  903. static size_t hash(const T& value) {
  904. return static_cast<size_t>(combine(MixingHashState{}, value).state_);
  905. }
  906. private:
  907. // Invoked only once for a given argument; that plus the fact that this is
  908. // move-only ensures that there is only one non-moved-from object.
  909. MixingHashState() : state_(Seed()) {}
  910. friend class MixingHashState::HashStateBase;
  911. template <typename CombinerT>
  912. static MixingHashState RunCombineUnordered(MixingHashState state,
  913. CombinerT combiner) {
  914. uint64_t unordered_state = 0;
  915. combiner(MixingHashState{}, [&](MixingHashState& inner_state) {
  916. // Add the hash state of the element to the running total, but mix the
  917. // carry bit back into the low bit. This in intended to avoid losing
  918. // entropy to overflow, especially when unordered_multisets contain
  919. // multiple copies of the same value.
  920. auto element_state = inner_state.state_;
  921. unordered_state += element_state;
  922. if (unordered_state < element_state) {
  923. ++unordered_state;
  924. }
  925. inner_state = MixingHashState{};
  926. });
  927. return MixingHashState::combine(std::move(state), unordered_state);
  928. }
  929. // Allow the HashState type-erasure implementation to invoke
  930. // RunCombinedUnordered() directly.
  931. friend class y_absl::HashState;
  932. // Workaround for MSVC bug.
  933. // We make the type copyable to fix the calling convention, even though we
  934. // never actually copy it. Keep it private to not affect the public API of the
  935. // type.
  936. MixingHashState(const MixingHashState&) = default;
  937. explicit MixingHashState(uint64_t state) : state_(state) {}
  938. // Implementation of the base case for combine_contiguous where we actually
  939. // mix the bytes into the state.
  940. // Dispatch to different implementations of the combine_contiguous depending
  941. // on the value of `sizeof(size_t)`.
  942. static uint64_t CombineContiguousImpl(uint64_t state,
  943. const unsigned char* first, size_t len,
  944. std::integral_constant<int, 4>
  945. /* sizeof_size_t */);
  946. static uint64_t CombineContiguousImpl(uint64_t state,
  947. const unsigned char* first, size_t len,
  948. std::integral_constant<int, 8>
  949. /* sizeof_size_t */);
  950. // Slow dispatch path for calls to CombineContiguousImpl with a size argument
  951. // larger than PiecewiseChunkSize(). Has the same effect as calling
  952. // CombineContiguousImpl() repeatedly with the chunk stride size.
  953. static uint64_t CombineLargeContiguousImpl32(uint64_t state,
  954. const unsigned char* first,
  955. size_t len);
  956. static uint64_t CombineLargeContiguousImpl64(uint64_t state,
  957. const unsigned char* first,
  958. size_t len);
  959. // Reads 9 to 16 bytes from p.
  960. // The least significant 8 bytes are in .first, the rest (zero padded) bytes
  961. // are in .second.
  962. static std::pair<uint64_t, uint64_t> Read9To16(const unsigned char* p,
  963. size_t len) {
  964. uint64_t low_mem = y_absl::base_internal::UnalignedLoad64(p);
  965. uint64_t high_mem = y_absl::base_internal::UnalignedLoad64(p + len - 8);
  966. #ifdef Y_ABSL_IS_LITTLE_ENDIAN
  967. uint64_t most_significant = high_mem;
  968. uint64_t least_significant = low_mem;
  969. #else
  970. uint64_t most_significant = low_mem;
  971. uint64_t least_significant = high_mem;
  972. #endif
  973. return {least_significant, most_significant};
  974. }
  975. // Reads 4 to 8 bytes from p. Zero pads to fill uint64_t.
  976. static uint64_t Read4To8(const unsigned char* p, size_t len) {
  977. uint32_t low_mem = y_absl::base_internal::UnalignedLoad32(p);
  978. uint32_t high_mem = y_absl::base_internal::UnalignedLoad32(p + len - 4);
  979. #ifdef Y_ABSL_IS_LITTLE_ENDIAN
  980. uint32_t most_significant = high_mem;
  981. uint32_t least_significant = low_mem;
  982. #else
  983. uint32_t most_significant = low_mem;
  984. uint32_t least_significant = high_mem;
  985. #endif
  986. return (static_cast<uint64_t>(most_significant) << (len - 4) * 8) |
  987. least_significant;
  988. }
  989. // Reads 1 to 3 bytes from p. Zero pads to fill uint32_t.
  990. static uint32_t Read1To3(const unsigned char* p, size_t len) {
  991. // The trick used by this implementation is to avoid branches if possible.
  992. unsigned char mem0 = p[0];
  993. unsigned char mem1 = p[len / 2];
  994. unsigned char mem2 = p[len - 1];
  995. #ifdef Y_ABSL_IS_LITTLE_ENDIAN
  996. unsigned char significant2 = mem2;
  997. unsigned char significant1 = mem1;
  998. unsigned char significant0 = mem0;
  999. #else
  1000. unsigned char significant2 = mem0;
  1001. unsigned char significant1 = len == 2 ? mem0 : mem1;
  1002. unsigned char significant0 = mem2;
  1003. #endif
  1004. return static_cast<uint32_t>(significant0 | //
  1005. (significant1 << (len / 2 * 8)) | //
  1006. (significant2 << ((len - 1) * 8)));
  1007. }
  1008. Y_ABSL_ATTRIBUTE_ALWAYS_INLINE static uint64_t Mix(uint64_t state, uint64_t v) {
  1009. // Though the 128-bit product on AArch64 needs two instructions, it is
  1010. // still a good balance between speed and hash quality.
  1011. using MultType =
  1012. y_absl::conditional_t<sizeof(size_t) == 4, uint64_t, uint128>;
  1013. // We do the addition in 64-bit space to make sure the 128-bit
  1014. // multiplication is fast. If we were to do it as MultType the compiler has
  1015. // to assume that the high word is non-zero and needs to perform 2
  1016. // multiplications instead of one.
  1017. MultType m = state + v;
  1018. m *= kMul;
  1019. return static_cast<uint64_t>(m ^ (m >> (sizeof(m) * 8 / 2)));
  1020. }
  1021. // An extern to avoid bloat on a direct call to LowLevelHash() with fixed
  1022. // values for both the seed and salt parameters.
  1023. static uint64_t LowLevelHashImpl(const unsigned char* data, size_t len);
  1024. Y_ABSL_ATTRIBUTE_ALWAYS_INLINE static uint64_t Hash64(const unsigned char* data,
  1025. size_t len) {
  1026. #ifdef Y_ABSL_HAVE_INTRINSIC_INT128
  1027. return LowLevelHashImpl(data, len);
  1028. #else
  1029. return hash_internal::CityHash64(reinterpret_cast<const char*>(data), len);
  1030. #endif
  1031. }
  1032. // Seed()
  1033. //
  1034. // A non-deterministic seed.
  1035. //
  1036. // The current purpose of this seed is to generate non-deterministic results
  1037. // and prevent having users depend on the particular hash values.
  1038. // It is not meant as a security feature right now, but it leaves the door
  1039. // open to upgrade it to a true per-process random seed. A true random seed
  1040. // costs more and we don't need to pay for that right now.
  1041. //
  1042. // On platforms with ASLR, we take advantage of it to make a per-process
  1043. // random value.
  1044. // See https://en.wikipedia.org/wiki/Address_space_layout_randomization
  1045. //
  1046. // On other platforms this is still going to be non-deterministic but most
  1047. // probably per-build and not per-process.
  1048. Y_ABSL_ATTRIBUTE_ALWAYS_INLINE static uint64_t Seed() {
  1049. #if (!defined(__clang__) || __clang_major__ > 11) && \
  1050. (!defined(__apple_build_version__) || \
  1051. __apple_build_version__ >= 19558921) // Xcode 12
  1052. return static_cast<uint64_t>(reinterpret_cast<uintptr_t>(&kSeed));
  1053. #else
  1054. // Workaround the absence of
  1055. // https://github.com/llvm/llvm-project/commit/bc15bf66dcca76cc06fe71fca35b74dc4d521021.
  1056. return static_cast<uint64_t>(reinterpret_cast<uintptr_t>(kSeed));
  1057. #endif
  1058. }
  1059. static const void* const kSeed;
  1060. uint64_t state_;
  1061. };
  1062. // MixingHashState::CombineContiguousImpl()
  1063. inline uint64_t MixingHashState::CombineContiguousImpl(
  1064. uint64_t state, const unsigned char* first, size_t len,
  1065. std::integral_constant<int, 4> /* sizeof_size_t */) {
  1066. // For large values we use CityHash, for small ones we just use a
  1067. // multiplicative hash.
  1068. uint64_t v;
  1069. if (len > 8) {
  1070. if (Y_ABSL_PREDICT_FALSE(len > PiecewiseChunkSize())) {
  1071. return CombineLargeContiguousImpl32(state, first, len);
  1072. }
  1073. v = hash_internal::CityHash32(reinterpret_cast<const char*>(first), len);
  1074. } else if (len >= 4) {
  1075. v = Read4To8(first, len);
  1076. } else if (len > 0) {
  1077. v = Read1To3(first, len);
  1078. } else {
  1079. // Empty ranges have no effect.
  1080. return state;
  1081. }
  1082. return Mix(state, v);
  1083. }
  1084. // Overload of MixingHashState::CombineContiguousImpl()
  1085. inline uint64_t MixingHashState::CombineContiguousImpl(
  1086. uint64_t state, const unsigned char* first, size_t len,
  1087. std::integral_constant<int, 8> /* sizeof_size_t */) {
  1088. // For large values we use LowLevelHash or CityHash depending on the platform,
  1089. // for small ones we just use a multiplicative hash.
  1090. uint64_t v;
  1091. if (len > 16) {
  1092. if (Y_ABSL_PREDICT_FALSE(len > PiecewiseChunkSize())) {
  1093. return CombineLargeContiguousImpl64(state, first, len);
  1094. }
  1095. v = Hash64(first, len);
  1096. } else if (len > 8) {
  1097. // This hash function was constructed by the ML-driven algorithm discovery
  1098. // using reinforcement learning. We fed the agent lots of inputs from
  1099. // microbenchmarks, SMHasher, low hamming distance from generated inputs and
  1100. // picked up the one that was good on micro and macrobenchmarks.
  1101. auto p = Read9To16(first, len);
  1102. uint64_t lo = p.first;
  1103. uint64_t hi = p.second;
  1104. // Rotation by 53 was found to be most often useful when discovering these
  1105. // hashing algorithms with ML techniques.
  1106. lo = y_absl::rotr(lo, 53);
  1107. state += kMul;
  1108. lo += state;
  1109. state ^= hi;
  1110. uint128 m = state;
  1111. m *= lo;
  1112. return static_cast<uint64_t>(m ^ (m >> 64));
  1113. } else if (len >= 4) {
  1114. v = Read4To8(first, len);
  1115. } else if (len > 0) {
  1116. v = Read1To3(first, len);
  1117. } else {
  1118. // Empty ranges have no effect.
  1119. return state;
  1120. }
  1121. return Mix(state, v);
  1122. }
  1123. struct AggregateBarrier {};
  1124. // HashImpl
  1125. // Add a private base class to make sure this type is not an aggregate.
  1126. // Aggregates can be aggregate initialized even if the default constructor is
  1127. // deleted.
  1128. struct PoisonedHash : private AggregateBarrier {
  1129. PoisonedHash() = delete;
  1130. PoisonedHash(const PoisonedHash&) = delete;
  1131. PoisonedHash& operator=(const PoisonedHash&) = delete;
  1132. };
  1133. template <typename T>
  1134. struct HashImpl {
  1135. size_t operator()(const T& value) const {
  1136. return MixingHashState::hash(value);
  1137. }
  1138. };
  1139. template <typename T>
  1140. struct Hash
  1141. : y_absl::conditional_t<is_hashable<T>::value, HashImpl<T>, PoisonedHash> {};
  1142. template <typename H>
  1143. template <typename T, typename... Ts>
  1144. H HashStateBase<H>::combine(H state, const T& value, const Ts&... values) {
  1145. return H::combine(hash_internal::HashSelect::template Apply<T>::Invoke(
  1146. std::move(state), value),
  1147. values...);
  1148. }
  1149. // HashStateBase::combine_contiguous()
  1150. template <typename H>
  1151. template <typename T>
  1152. H HashStateBase<H>::combine_contiguous(H state, const T* data, size_t size) {
  1153. return hash_internal::hash_range_or_bytes(std::move(state), data, size);
  1154. }
  1155. // HashStateBase::combine_unordered()
  1156. template <typename H>
  1157. template <typename I>
  1158. H HashStateBase<H>::combine_unordered(H state, I begin, I end) {
  1159. return H::RunCombineUnordered(std::move(state),
  1160. CombineUnorderedCallback<I>{begin, end});
  1161. }
  1162. // HashStateBase::PiecewiseCombiner::add_buffer()
  1163. template <typename H>
  1164. H PiecewiseCombiner::add_buffer(H state, const unsigned char* data,
  1165. size_t size) {
  1166. if (position_ + size < PiecewiseChunkSize()) {
  1167. // This partial chunk does not fill our existing buffer
  1168. memcpy(buf_ + position_, data, size);
  1169. position_ += size;
  1170. return state;
  1171. }
  1172. // If the buffer is partially filled we need to complete the buffer
  1173. // and hash it.
  1174. if (position_ != 0) {
  1175. const size_t bytes_needed = PiecewiseChunkSize() - position_;
  1176. memcpy(buf_ + position_, data, bytes_needed);
  1177. state = H::combine_contiguous(std::move(state), buf_, PiecewiseChunkSize());
  1178. data += bytes_needed;
  1179. size -= bytes_needed;
  1180. }
  1181. // Hash whatever chunks we can without copying
  1182. while (size >= PiecewiseChunkSize()) {
  1183. state = H::combine_contiguous(std::move(state), data, PiecewiseChunkSize());
  1184. data += PiecewiseChunkSize();
  1185. size -= PiecewiseChunkSize();
  1186. }
  1187. // Fill the buffer with the remainder
  1188. memcpy(buf_, data, size);
  1189. position_ = size;
  1190. return state;
  1191. }
  1192. // HashStateBase::PiecewiseCombiner::finalize()
  1193. template <typename H>
  1194. H PiecewiseCombiner::finalize(H state) {
  1195. // Hash the remainder left in the buffer, which may be empty
  1196. return H::combine_contiguous(std::move(state), buf_, position_);
  1197. }
  1198. } // namespace hash_internal
  1199. Y_ABSL_NAMESPACE_END
  1200. } // namespace y_absl
  1201. #endif // Y_ABSL_HASH_INTERNAL_HASH_H_