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