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