Coverage Report

Created: 2026-02-26 07:14

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/abseil-cpp/absl/hash/internal/hash.h
Line
Count
Source
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
#ifdef __APPLE__
23
#include <Availability.h>
24
#include <TargetConditionals.h>
25
#endif
26
27
// We include config.h here to make sure that ABSL_INTERNAL_CPLUSPLUS_LANG is
28
// defined.
29
#include "absl/base/config.h"
30
31
// GCC15 warns that <ciso646> is deprecated in C++17 and suggests using
32
// <version> instead, even though <version> is not available in C++17 mode prior
33
// to GCC9.
34
#if defined(__has_include)
35
#if __has_include(<version>)
36
#define ABSL_INTERNAL_VERSION_HEADER_AVAILABLE 1
37
#endif
38
#endif
39
40
// For feature testing and determining which headers can be included.
41
#if ABSL_INTERNAL_CPLUSPLUS_LANG >= 202002L || \
42
    defined(ABSL_INTERNAL_VERSION_HEADER_AVAILABLE)
43
#include <version>
44
#else
45
#include <ciso646>
46
#endif
47
48
#undef ABSL_INTERNAL_VERSION_HEADER_AVAILABLE
49
50
#include <algorithm>
51
#include <array>
52
#include <bitset>
53
#include <cassert>
54
#include <cmath>
55
#include <cstddef>
56
#include <cstdint>
57
#include <cstring>
58
#include <deque>
59
#include <forward_list>
60
#include <functional>
61
#include <iterator>
62
#include <limits>
63
#include <list>
64
#include <map>
65
#include <memory>
66
#include <optional>
67
#include <set>
68
#include <string>
69
#include <string_view>
70
#include <tuple>
71
#include <type_traits>
72
#include <unordered_map>
73
#include <unordered_set>
74
#include <utility>
75
#include <variant>
76
#include <vector>
77
78
#include "absl/base/attributes.h"
79
#include "absl/base/internal/endian.h"
80
#include "absl/base/internal/unaligned_access.h"
81
#include "absl/base/optimization.h"
82
#include "absl/base/port.h"
83
#include "absl/container/fixed_array.h"
84
#include "absl/hash/internal/city.h"
85
#include "absl/hash/internal/weakly_mixed_integer.h"
86
#include "absl/meta/type_traits.h"
87
#include "absl/numeric/bits.h"
88
#include "absl/numeric/int128.h"
89
#include "absl/strings/string_view.h"
90
#include "absl/types/optional.h"
91
#include "absl/types/variant.h"
92
#include "absl/utility/utility.h"
93
94
#if defined(__cpp_lib_filesystem) && __cpp_lib_filesystem >= 201703L && \
95
    !defined(__XTENSA__)
96
#include <filesystem>  // NOLINT
97
#endif
98
99
// 32-bit builds with SSE 4.2 do not have _mm_crc32_u64, so the
100
// __x86_64__ condition is necessary.
101
#if defined(__SSE4_2__) && defined(__x86_64__)
102
103
#include <x86intrin.h>
104
#define ABSL_HASH_INTERNAL_HAS_CRC32
105
#define ABSL_HASH_INTERNAL_CRC32_U64 _mm_crc32_u64
106
#define ABSL_HASH_INTERNAL_CRC32_U32 _mm_crc32_u32
107
#define ABSL_HASH_INTERNAL_CRC32_U8 _mm_crc32_u8
108
109
// 32-bit builds with AVX do not have _mm_crc32_u64, so the _M_X64 condition is
110
// necessary.
111
#elif defined(_MSC_VER) && !defined(__clang__) && defined(__AVX__) && \
112
    defined(_M_X64)
113
114
// MSVC AVX (/arch:AVX) implies SSE 4.2.
115
#include <intrin.h>
116
#define ABSL_HASH_INTERNAL_HAS_CRC32
117
#define ABSL_HASH_INTERNAL_CRC32_U64 _mm_crc32_u64
118
#define ABSL_HASH_INTERNAL_CRC32_U32 _mm_crc32_u32
119
#define ABSL_HASH_INTERNAL_CRC32_U8 _mm_crc32_u8
120
121
#elif defined(__ARM_FEATURE_CRC32)
122
123
#include <arm_acle.h>
124
#define ABSL_HASH_INTERNAL_HAS_CRC32
125
// Casting to uint32_t to be consistent with x86 intrinsic (_mm_crc32_u64
126
// accepts crc as 64 bit integer).
127
#define ABSL_HASH_INTERNAL_CRC32_U64(crc, data) \
128
  __crc32cd(static_cast<uint32_t>(crc), data)
129
#define ABSL_HASH_INTERNAL_CRC32_U32 __crc32cw
130
#define ABSL_HASH_INTERNAL_CRC32_U8 __crc32cb
131
132
#endif
133
134
namespace absl {
135
ABSL_NAMESPACE_BEGIN
136
137
class HashState;
138
139
namespace hash_internal {
140
141
// Internal detail: Large buffers are hashed in smaller chunks.  This function
142
// returns the size of these chunks.
143
5.42M
constexpr size_t PiecewiseChunkSize() { return 1024; }
144
145
// PiecewiseCombiner is an internal-only helper class for hashing a piecewise
146
// buffer of `char` or `unsigned char` as though it were contiguous.  This class
147
// provides two methods:
148
//
149
//   H add_buffer(state, data, size)
150
//   H finalize(state)
151
//
152
// `add_buffer` can be called zero or more times, followed by a single call to
153
// `finalize`.  This will produce the same hash expansion as concatenating each
154
// buffer piece into a single contiguous buffer, and passing this to
155
// `H::combine_contiguous`.
156
//
157
//  Example usage:
158
//    PiecewiseCombiner combiner;
159
//    for (const auto& piece : pieces) {
160
//      state = combiner.add_buffer(std::move(state), piece.data, piece.size);
161
//    }
162
//    return combiner.finalize(std::move(state));
163
class PiecewiseCombiner {
164
 public:
165
  PiecewiseCombiner() = default;
166
  PiecewiseCombiner(const PiecewiseCombiner&) = delete;
167
  PiecewiseCombiner& operator=(const PiecewiseCombiner&) = delete;
168
169
  // Appends the given range of bytes to the sequence to be hashed, which may
170
  // modify the provided hash state.
171
  template <typename H>
172
  H add_buffer(H state, const unsigned char* data, size_t size);
173
  template <typename H>
174
0
  H add_buffer(H state, const char* data, size_t size) {
175
0
    return add_buffer(std::move(state),
176
0
                      reinterpret_cast<const unsigned char*>(data), size);
177
0
  }
178
179
  // Finishes combining the hash sequence, which may may modify the provided
180
  // hash state.
181
  //
182
  // Once finalize() is called, add_buffer() may no longer be called. The
183
  // resulting hash state will be the same as if the pieces passed to
184
  // add_buffer() were concatenated into a single flat buffer, and then provided
185
  // to H::combine_contiguous().
186
  template <typename H>
187
  H finalize(H state);
188
189
 private:
190
  unsigned char buf_[PiecewiseChunkSize()];
191
  size_t position_ = 0;
192
  bool added_something_ = false;
193
};
194
195
// Trait class which returns true if T is hashable by the absl::Hash framework.
196
// Used for the AbslHashValue implementations for composite types below.
197
template <typename T>
198
struct is_hashable;
199
200
// HashStateBase is an internal implementation detail that contains common
201
// implementation details for all of the "hash state objects" objects generated
202
// by Abseil.  This is not a public API; users should not create classes that
203
// inherit from this.
204
//
205
// A hash state object is the template argument `H` passed to `AbslHashValue`.
206
// It represents an intermediate state in the computation of an unspecified hash
207
// algorithm. `HashStateBase` provides a CRTP style base class for hash state
208
// implementations. Developers adding type support for `absl::Hash` should not
209
// rely on any parts of the state object other than the following member
210
// functions:
211
//
212
//   * HashStateBase::combine()
213
//   * HashStateBase::combine_contiguous()
214
//   * HashStateBase::combine_unordered()
215
//
216
// A derived hash state class of type `H` must provide a public member function
217
// with a signature similar to the following:
218
//
219
//    `static H combine_contiguous(H state, const unsigned char*, size_t)`.
220
//
221
// It must also provide a private template method named RunCombineUnordered.
222
//
223
// A "consumer" is a 1-arg functor returning void.  Its argument is a reference
224
// to an inner hash state object, and it may be called multiple times.  When
225
// called, the functor consumes the entropy from the provided state object,
226
// and resets that object to its empty state.
227
//
228
// A "combiner" is a stateless 2-arg functor returning void.  Its arguments are
229
// an inner hash state object and an ElementStateConsumer functor.  A combiner
230
// uses the provided inner hash state object to hash each element of the
231
// container, passing the inner hash state object to the consumer after hashing
232
// each element.
233
//
234
// Given these definitions, a derived hash state class of type H
235
// must provide a private template method with a signature similar to the
236
// following:
237
//
238
//    `template <typename CombinerT>`
239
//    `static H RunCombineUnordered(H outer_state, CombinerT combiner)`
240
//
241
// This function is responsible for constructing the inner state object and
242
// providing a consumer to the combiner.  It uses side effects of the consumer
243
// and combiner to mix the state of each element in an order-independent manner,
244
// and uses this to return an updated value of `outer_state`.
245
//
246
// This inside-out approach generates efficient object code in the normal case,
247
// but allows us to use stack storage to implement the absl::HashState type
248
// erasure mechanism (avoiding heap allocations while hashing).
249
//
250
// `HashStateBase` will provide a complete implementation for a hash state
251
// object in terms of these two methods.
252
//
253
// Example:
254
//
255
//   // Use CRTP to define your derived class.
256
//   struct MyHashState : HashStateBase<MyHashState> {
257
//       static H combine_contiguous(H state, const unsigned char*, size_t);
258
//       using MyHashState::HashStateBase::combine;
259
//       using MyHashState::HashStateBase::combine_contiguous;
260
//       using MyHashState::HashStateBase::combine_unordered;
261
//     private:
262
//       template <typename CombinerT>
263
//       static H RunCombineUnordered(H state, CombinerT combiner);
264
//   };
265
template <typename H>
266
class HashStateBase {
267
 public:
268
  // Combines an arbitrary number of values into a hash state, returning the
269
  // updated state.
270
  //
271
  // Each of the value types `T` must be separately hashable by the Abseil
272
  // hashing framework.
273
  //
274
  // NOTE:
275
  //
276
  //   state = H::combine(std::move(state), value1, value2, value3);
277
  //
278
  // is guaranteed to produce the same hash expansion as:
279
  //
280
  //   state = H::combine(std::move(state), value1);
281
  //   state = H::combine(std::move(state), value2);
282
  //   state = H::combine(std::move(state), value3);
283
  template <typename T, typename... Ts>
284
  static H combine(H state, const T& value, const Ts&... values);
285
0
  static H combine(H state) { return state; }
286
287
  // Combines a contiguous array of `size` elements into a hash state, returning
288
  // the updated state.
289
  //
290
  // NOTE:
291
  //
292
  //   state = H::combine_contiguous(std::move(state), data, size);
293
  //
294
  // is NOT guaranteed to produce the same hash expansion as a for-loop (it may
295
  // perform internal optimizations).  If you need this guarantee, use the
296
  // for-loop instead.
297
  template <typename T>
298
  static H combine_contiguous(H state, const T* data, size_t size);
299
300
  template <typename I>
301
  static H combine_unordered(H state, I begin, I end);
302
303
  using AbslInternalPiecewiseCombiner = PiecewiseCombiner;
304
305
  template <typename T>
306
  using is_hashable = absl::hash_internal::is_hashable<T>;
307
308
 private:
309
  // Common implementation of the iteration step of a "combiner", as described
310
  // above.
311
  template <typename I>
312
  struct CombineUnorderedCallback {
313
    I begin;
314
    I end;
315
316
    template <typename InnerH, typename ElementStateConsumer>
317
    void operator()(InnerH inner_state, ElementStateConsumer cb) {
318
      for (; begin != end; ++begin) {
319
        inner_state = H::combine(std::move(inner_state), *begin);
320
        cb(inner_state);
321
      }
322
    }
323
  };
324
};
325
326
// `is_uniquely_represented<T>` is a trait class that indicates whether `T`
327
// is uniquely represented.
328
//
329
// A type is "uniquely represented" if two equal values of that type are
330
// guaranteed to have the same bytes in their underlying storage. In other
331
// words, if `a == b`, then `memcmp(&a, &b, sizeof(T))` is guaranteed to be
332
// zero. This property cannot be detected automatically, so this trait is false
333
// by default, but can be specialized by types that wish to assert that they are
334
// uniquely represented. This makes them eligible for certain optimizations.
335
//
336
// If you have any doubt whatsoever, do not specialize this template.
337
// The default is completely safe, and merely disables some optimizations
338
// that will not matter for most types. Specializing this template,
339
// on the other hand, can be very hazardous.
340
//
341
// To be uniquely represented, a type must not have multiple ways of
342
// representing the same value; for example, float and double are not
343
// uniquely represented, because they have distinct representations for
344
// +0 and -0. Furthermore, the type's byte representation must consist
345
// solely of user-controlled data, with no padding bits and no compiler-
346
// controlled data such as vptrs or sanitizer metadata. This is usually
347
// very difficult to guarantee, because in most cases the compiler can
348
// insert data and padding bits at its own discretion.
349
//
350
// If you specialize this template for a type `T`, you must do so in the file
351
// that defines that type (or in this file). If you define that specialization
352
// anywhere else, `is_uniquely_represented<T>` could have different meanings
353
// in different places.
354
//
355
// The Enable parameter is meaningless; it is provided as a convenience,
356
// to support certain SFINAE techniques when defining specializations.
357
template <typename T, typename Enable = void>
358
struct is_uniquely_represented : std::false_type {};
359
360
// unsigned char is a synonym for "byte", so it is guaranteed to be
361
// uniquely represented.
362
template <>
363
struct is_uniquely_represented<unsigned char> : std::true_type {};
364
365
// is_uniquely_represented for non-standard integral types
366
//
367
// Integral types other than bool should be uniquely represented on any
368
// platform that this will plausibly be ported to.
369
template <typename Integral>
370
struct is_uniquely_represented<
371
    Integral, typename std::enable_if<std::is_integral<Integral>::value>::type>
372
    : std::true_type {};
373
374
template <>
375
struct is_uniquely_represented<bool> : std::false_type {};
376
377
#ifdef ABSL_HAVE_INTRINSIC_INT128
378
// Specialize the trait for GNU extension types.
379
template <>
380
struct is_uniquely_represented<__int128> : std::true_type {};
381
template <>
382
struct is_uniquely_represented<unsigned __int128> : std::true_type {};
383
#endif  // ABSL_HAVE_INTRINSIC_INT128
384
385
template <typename T>
386
struct FitsIn64Bits : std::integral_constant<bool, sizeof(T) <= 8> {};
387
388
struct CombineRaw {
389
  template <typename H>
390
0
  H operator()(H state, uint64_t value) const {
391
0
    return H::combine_raw(std::move(state), value);
392
0
  }
393
};
394
395
// For use in `raw_hash_set` to pass a seed to the hash function.
396
struct HashWithSeed {
397
  template <typename Hasher, typename T>
398
0
  size_t hash(const Hasher& hasher, const T& value, size_t seed) const {
399
0
    // NOLINTNEXTLINE(clang-diagnostic-sign-conversion)
400
0
    return hasher.hash_with_seed(value, seed);
401
0
  }
Unexecuted instantiation: unsigned long absl::hash_internal::HashWithSeed::hash<absl::hash_internal::Hash<std::__1::basic_string_view<char, std::__1::char_traits<char> > >, std::__1::basic_string_view<char, std::__1::char_traits<char> > >(absl::hash_internal::Hash<std::__1::basic_string_view<char, std::__1::char_traits<char> > > const&, std::__1::basic_string_view<char, std::__1::char_traits<char> > const&, unsigned long) const
Unexecuted instantiation: unsigned long absl::hash_internal::HashWithSeed::hash<absl::hash_internal::Hash<absl::Cord>, absl::Cord>(absl::hash_internal::Hash<absl::Cord> const&, absl::Cord const&, unsigned long) const
402
};
403
404
// Convenience function that combines `hash_state` with the byte representation
405
// of `value`.
406
template <typename H, typename T,
407
          absl::enable_if_t<FitsIn64Bits<T>::value, int> = 0>
408
0
H hash_bytes(H hash_state, const T& value) {
409
0
  const unsigned char* start = reinterpret_cast<const unsigned char*>(&value);
410
0
  uint64_t v;
411
  if constexpr (sizeof(T) == 1) {
412
    v = *start;
413
  } else if constexpr (sizeof(T) == 2) {
414
    v = absl::base_internal::UnalignedLoad16(start);
415
0
  } else if constexpr (sizeof(T) == 4) {
416
0
    v = absl::base_internal::UnalignedLoad32(start);
417
0
  } else {
418
0
    static_assert(sizeof(T) == 8);
419
0
    v = absl::base_internal::UnalignedLoad64(start);
420
0
  }
421
0
  return CombineRaw()(std::move(hash_state), v);
422
0
}
Unexecuted instantiation: _ZN4absl13hash_internal10hash_bytesINS0_15MixingHashStateEiTnNSt3__19enable_ifIXsr12FitsIn64BitsIT0_EE5valueEiE4typeELi0EEET_S8_RKS5_
Unexecuted instantiation: _ZN4absl13hash_internal10hash_bytesINS0_15MixingHashStateEmTnNSt3__19enable_ifIXsr12FitsIn64BitsIT0_EE5valueEiE4typeELi0EEET_S8_RKS5_
423
template <typename H, typename T,
424
          absl::enable_if_t<!FitsIn64Bits<T>::value, int> = 0>
425
H hash_bytes(H hash_state, const T& value) {
426
  const unsigned char* start = reinterpret_cast<const unsigned char*>(&value);
427
  return H::combine_contiguous(std::move(hash_state), start, sizeof(value));
428
}
429
430
template <typename H>
431
H hash_weakly_mixed_integer(H hash_state, WeaklyMixedInteger value) {
432
  return H::combine_weakly_mixed_integer(std::move(hash_state), value);
433
}
434
435
// -----------------------------------------------------------------------------
436
// AbslHashValue for Basic Types
437
// -----------------------------------------------------------------------------
438
439
// Note: Default `AbslHashValue` implementations live in `hash_internal`. This
440
// allows us to block lexical scope lookup when doing an unqualified call to
441
// `AbslHashValue` below. User-defined implementations of `AbslHashValue` can
442
// only be found via ADL.
443
444
// AbslHashValue() for hashing bool values
445
//
446
// We use SFINAE to ensure that this overload only accepts bool, not types that
447
// are convertible to bool.
448
template <typename H, typename B>
449
typename std::enable_if<std::is_same<B, bool>::value, H>::type AbslHashValue(
450
    H hash_state, B value) {
451
  // We use ~size_t{} instead of 1 so that all bits are different between
452
  // true/false instead of only 1.
453
  return H::combine(std::move(hash_state),
454
                    static_cast<size_t>(value ? ~size_t{} : 0));
455
}
456
457
// AbslHashValue() for hashing enum values
458
template <typename H, typename Enum>
459
typename std::enable_if<std::is_enum<Enum>::value, H>::type AbslHashValue(
460
    H hash_state, Enum e) {
461
  // In practice, we could almost certainly just invoke hash_bytes directly,
462
  // but it's possible that a sanitizer might one day want to
463
  // store data in the unused bits of an enum. To avoid that risk, we
464
  // convert to the underlying type before hashing. Hopefully this will get
465
  // optimized away; if not, we can reopen discussion with c-toolchain-team.
466
  return H::combine(std::move(hash_state),
467
                    static_cast<typename std::underlying_type<Enum>::type>(e));
468
}
469
// AbslHashValue() for hashing floating-point values
470
template <typename H, typename Float>
471
typename std::enable_if<std::is_same<Float, float>::value ||
472
                            std::is_same<Float, double>::value,
473
                        H>::type
474
AbslHashValue(H hash_state, Float value) {
475
  return hash_internal::hash_bytes(std::move(hash_state),
476
                                   value == 0 ? 0 : value);
477
}
478
479
// Long double has the property that it might have extra unused bytes in it.
480
// For example, in x86 sizeof(long double)==16 but it only really uses 80-bits
481
// of it. This means we can't use hash_bytes on a long double and have to
482
// convert it to something else first.
483
template <typename H, typename LongDouble>
484
typename std::enable_if<std::is_same<LongDouble, long double>::value, H>::type
485
AbslHashValue(H hash_state, LongDouble value) {
486
  const int category = std::fpclassify(value);
487
  switch (category) {
488
    case FP_INFINITE:
489
      // Add the sign bit to differentiate between +Inf and -Inf
490
      hash_state = H::combine(std::move(hash_state), std::signbit(value));
491
      break;
492
493
    case FP_NAN:
494
    case FP_ZERO:
495
    default:
496
      // Category is enough for these.
497
      break;
498
499
    case FP_NORMAL:
500
    case FP_SUBNORMAL:
501
      // We can't convert `value` directly to double because this would have
502
      // undefined behavior if the value is out of range.
503
      // std::frexp gives us a value in the range (-1, -.5] or [.5, 1) that is
504
      // guaranteed to be in range for `double`. The truncation is
505
      // implementation defined, but that works as long as it is deterministic.
506
      int exp;
507
      auto mantissa = static_cast<double>(std::frexp(value, &exp));
508
      hash_state = H::combine(std::move(hash_state), mantissa, exp);
509
  }
510
511
  return H::combine(std::move(hash_state), category);
512
}
513
514
// Without this overload, an array decays to a pointer and we hash that, which
515
// is not likely to be what the caller intended.
516
template <typename H, typename T, size_t N>
517
H AbslHashValue(H hash_state, T (&)[N]) {
518
  static_assert(
519
      sizeof(T) == -1,
520
      "Hashing C arrays is not allowed. For string literals, wrap the literal "
521
      "in absl::string_view(). To hash the array contents, use "
522
      "absl::MakeSpan() or make the array an std::array. To hash the array "
523
      "address, use &array[0].");
524
  return hash_state;
525
}
526
527
// AbslHashValue() for hashing pointers
528
template <typename H, typename T>
529
std::enable_if_t<std::is_pointer<T>::value, H> AbslHashValue(H hash_state,
530
                                                             T ptr) {
531
  auto v = reinterpret_cast<uintptr_t>(ptr);
532
  // Due to alignment, pointers tend to have low bits as zero, and the next few
533
  // bits follow a pattern since they are also multiples of some base value.
534
  // The PointerAlignment test verifies that our mixing is good enough to handle
535
  // these cases.
536
  return H::combine(std::move(hash_state), v);
537
}
538
539
// AbslHashValue() for hashing nullptr_t
540
template <typename H>
541
H AbslHashValue(H hash_state, std::nullptr_t) {
542
  return H::combine(std::move(hash_state), static_cast<void*>(nullptr));
543
}
544
545
// AbslHashValue() for hashing pointers-to-member
546
template <typename H, typename T, typename C>
547
H AbslHashValue(H hash_state, T C::*ptr) {
548
  auto salient_ptm_size = [](std::size_t n) -> std::size_t {
549
#if defined(_MSC_VER)
550
    // Pointers-to-member-function on MSVC consist of one pointer plus 0, 1, 2,
551
    // or 3 ints. In 64-bit mode, they are 8-byte aligned and thus can contain
552
    // padding (namely when they have 1 or 3 ints). The value below is a lower
553
    // bound on the number of salient, non-padding bytes that we use for
554
    // hashing.
555
    if constexpr (alignof(T C::*) == alignof(int)) {
556
      // No padding when all subobjects have the same size as the total
557
      // alignment. This happens in 32-bit mode.
558
      return n;
559
    } else {
560
      // Padding for 1 int (size 16) or 3 ints (size 24).
561
      // With 2 ints, the size is 16 with no padding, which we pessimize.
562
      return n == 24 ? 20 : n == 16 ? 12 : n;
563
    }
564
#else
565
  // On other platforms, we assume that pointers-to-members do not have
566
  // padding.
567
#ifdef __cpp_lib_has_unique_object_representations
568
    static_assert(std::has_unique_object_representations<T C::*>::value);
569
#endif  // __cpp_lib_has_unique_object_representations
570
    return n;
571
#endif
572
  };
573
  return H::combine_contiguous(std::move(hash_state),
574
                               reinterpret_cast<unsigned char*>(&ptr),
575
                               salient_ptm_size(sizeof ptr));
576
}
577
578
// -----------------------------------------------------------------------------
579
// AbslHashValue for Composite Types
580
// -----------------------------------------------------------------------------
581
582
// AbslHashValue() for hashing pairs
583
template <typename H, typename T1, typename T2>
584
typename std::enable_if<is_hashable<T1>::value && is_hashable<T2>::value,
585
                        H>::type
586
AbslHashValue(H hash_state, const std::pair<T1, T2>& p) {
587
  return H::combine(std::move(hash_state), p.first, p.second);
588
}
589
590
// Helper function for hashing a tuple. The third argument should
591
// be an index_sequence running from 0 to tuple_size<Tuple> - 1.
592
template <typename H, typename Tuple, size_t... Is>
593
0
H hash_tuple(H hash_state, const Tuple& t, absl::index_sequence<Is...>) {
594
0
  return H::combine(std::move(hash_state), std::get<Is>(t)...);
595
0
}
Unexecuted instantiation: absl::hash_internal::MixingHashState absl::hash_internal::hash_tuple<absl::hash_internal::MixingHashState, std::__1::tuple<std::__1::basic_string_view<char, std::__1::char_traits<char> > const&, int const&>, 0ul, 1ul>(absl::hash_internal::MixingHashState, std::__1::tuple<std::__1::basic_string_view<char, std::__1::char_traits<char> > const&, int const&> const&, std::__1::integer_sequence<unsigned long, 0ul, 1ul>)
Unexecuted instantiation: absl::hash_internal::MixingHashState absl::hash_internal::hash_tuple<absl::hash_internal::MixingHashState, std::__1::tuple<unsigned long const&>, 0ul>(absl::hash_internal::MixingHashState, std::__1::tuple<unsigned long const&> const&, std::__1::integer_sequence<unsigned long, 0ul>)
596
597
// AbslHashValue for hashing tuples
598
template <typename H, typename... Ts>
599
#if defined(_MSC_VER)
600
// This SFINAE gets MSVC confused under some conditions. Let's just disable it
601
// for now.
602
H
603
#else   // _MSC_VER
604
typename std::enable_if<absl::conjunction<is_hashable<Ts>...>::value, H>::type
605
#endif  // _MSC_VER
606
0
AbslHashValue(H hash_state, const std::tuple<Ts...>& t) {
607
0
  return hash_internal::hash_tuple(std::move(hash_state), t,
608
0
                                   absl::make_index_sequence<sizeof...(Ts)>());
609
0
}
Unexecuted instantiation: _ZN4absl13hash_internal13AbslHashValueINS0_15MixingHashStateEJRKNSt3__117basic_string_viewIcNS3_11char_traitsIcEEEERKiEEENS3_9enable_ifIXsr4absl11conjunctionIDpNS0_11is_hashableIT0_EEEE5valueET_E4typeESH_RKNS3_5tupleIJDpSE_EEE
Unexecuted instantiation: _ZN4absl13hash_internal13AbslHashValueINS0_15MixingHashStateEJRKmEEENSt3__19enable_ifIXsr4absl11conjunctionIDpNS0_11is_hashableIT0_EEEE5valueET_E4typeESB_RKNS5_5tupleIJDpS8_EEE
610
611
// -----------------------------------------------------------------------------
612
// AbslHashValue for Pointers
613
// -----------------------------------------------------------------------------
614
615
// AbslHashValue for hashing unique_ptr
616
template <typename H, typename T, typename D>
617
H AbslHashValue(H hash_state, const std::unique_ptr<T, D>& ptr) {
618
  return H::combine(std::move(hash_state), ptr.get());
619
}
620
621
// AbslHashValue for hashing shared_ptr
622
template <typename H, typename T>
623
H AbslHashValue(H hash_state, const std::shared_ptr<T>& ptr) {
624
  return H::combine(std::move(hash_state), ptr.get());
625
}
626
627
// -----------------------------------------------------------------------------
628
// AbslHashValue for String-Like Types
629
// -----------------------------------------------------------------------------
630
631
// AbslHashValue for hashing strings
632
//
633
// All the string-like types supported here provide the same hash expansion for
634
// the same character sequence. These types are:
635
//
636
//  - `absl::Cord`
637
//  - `std::string` (and std::basic_string<T, std::char_traits<T>, A> for
638
//      any allocator A and any T in {char, wchar_t, char16_t, char32_t})
639
//  - `absl::string_view`, `std::string_view`, `std::wstring_view`,
640
//    `std::u16string_view`, and `std::u32_string_view`.
641
//
642
// For simplicity, we currently support only strings built on `char`, `wchar_t`,
643
// `char16_t`, or `char32_t`. This support may be broadened, if necessary, but
644
// with some caution - this overload would misbehave in cases where the traits'
645
// `eq()` member isn't equivalent to `==` on the underlying character type.
646
template <typename H>
647
0
H AbslHashValue(H hash_state, absl::string_view str) {
648
0
  return H::combine_contiguous(std::move(hash_state), str.data(), str.size());
649
0
}
650
651
// Support std::wstring, std::u16string and std::u32string.
652
template <typename Char, typename Alloc, typename H,
653
          typename = absl::enable_if_t<std::is_same<Char, wchar_t>::value ||
654
                                       std::is_same<Char, char16_t>::value ||
655
                                       std::is_same<Char, char32_t>::value>>
656
H AbslHashValue(
657
    H hash_state,
658
    const std::basic_string<Char, std::char_traits<Char>, Alloc>& str) {
659
  return H::combine_contiguous(std::move(hash_state), str.data(), str.size());
660
}
661
662
// Support std::wstring_view, std::u16string_view and std::u32string_view.
663
template <typename Char, typename H,
664
          typename = absl::enable_if_t<std::is_same<Char, wchar_t>::value ||
665
                                       std::is_same<Char, char16_t>::value ||
666
                                       std::is_same<Char, char32_t>::value>>
667
H AbslHashValue(H hash_state, std::basic_string_view<Char> str) {
668
  return H::combine_contiguous(std::move(hash_state), str.data(), str.size());
669
}
670
671
#if defined(__cpp_lib_filesystem) && __cpp_lib_filesystem >= 201703L && \
672
    (!defined(__ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__) ||        \
673
     __ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__ >= 130000) &&       \
674
    (!defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) ||         \
675
     __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ >= 101500) &&        \
676
    (!defined(__XTENSA__))
677
678
#define ABSL_INTERNAL_STD_FILESYSTEM_PATH_HASH_AVAILABLE 1
679
680
// Support std::filesystem::path. The SFINAE is required because some string
681
// types are implicitly convertible to std::filesystem::path.
682
template <typename Path, typename H,
683
          typename = absl::enable_if_t<
684
              std::is_same_v<Path, std::filesystem::path>>>
685
H AbslHashValue(H hash_state, const Path& path) {
686
  // This is implemented by deferring to the standard library to compute the
687
  // hash.  The standard library requires that for two paths, `p1 == p2`, then
688
  // `hash_value(p1) == hash_value(p2)`. `AbslHashValue` has the same
689
  // requirement. Since `operator==` does platform specific matching, deferring
690
  // to the standard library is the simplest approach.
691
  return H::combine(std::move(hash_state), std::filesystem::hash_value(path));
692
}
693
694
#endif  // ABSL_INTERNAL_STD_FILESYSTEM_PATH_HASH_AVAILABLE
695
696
// -----------------------------------------------------------------------------
697
// AbslHashValue for Sequence Containers
698
// -----------------------------------------------------------------------------
699
700
// AbslHashValue for hashing std::array
701
template <typename H, typename T, size_t N>
702
typename std::enable_if<is_hashable<T>::value, H>::type AbslHashValue(
703
    H hash_state, const std::array<T, N>& array) {
704
  return H::combine_contiguous(std::move(hash_state), array.data(),
705
                               array.size());
706
}
707
708
// AbslHashValue for hashing std::deque
709
template <typename H, typename T, typename Allocator>
710
typename std::enable_if<is_hashable<T>::value, H>::type AbslHashValue(
711
    H hash_state, const std::deque<T, Allocator>& deque) {
712
  // TODO(gromer): investigate a more efficient implementation taking
713
  // advantage of the chunk structure.
714
  for (const auto& t : deque) {
715
    hash_state = H::combine(std::move(hash_state), t);
716
  }
717
  return H::combine(std::move(hash_state), WeaklyMixedInteger{deque.size()});
718
}
719
720
// AbslHashValue for hashing std::forward_list
721
template <typename H, typename T, typename Allocator>
722
typename std::enable_if<is_hashable<T>::value, H>::type AbslHashValue(
723
    H hash_state, const std::forward_list<T, Allocator>& list) {
724
  size_t size = 0;
725
  for (const T& t : list) {
726
    hash_state = H::combine(std::move(hash_state), t);
727
    ++size;
728
  }
729
  return H::combine(std::move(hash_state), WeaklyMixedInteger{size});
730
}
731
732
// AbslHashValue for hashing std::list
733
template <typename H, typename T, typename Allocator>
734
typename std::enable_if<is_hashable<T>::value, H>::type AbslHashValue(
735
    H hash_state, const std::list<T, Allocator>& list) {
736
  for (const auto& t : list) {
737
    hash_state = H::combine(std::move(hash_state), t);
738
  }
739
  return H::combine(std::move(hash_state), WeaklyMixedInteger{list.size()});
740
}
741
742
// AbslHashValue for hashing std::vector
743
//
744
// Do not use this for vector<bool> on platforms that have a working
745
// implementation of std::hash. It does not have a .data(), and a fallback for
746
// std::hash<> is most likely faster.
747
template <typename H, typename T, typename Allocator>
748
typename std::enable_if<is_hashable<T>::value && !std::is_same<T, bool>::value,
749
                        H>::type
750
AbslHashValue(H hash_state, const std::vector<T, Allocator>& vector) {
751
  return H::combine_contiguous(std::move(hash_state), vector.data(),
752
                               vector.size());
753
}
754
755
// AbslHashValue special cases for hashing std::vector<bool>
756
757
#if defined(ABSL_IS_BIG_ENDIAN) && \
758
    (defined(__GLIBCXX__) || defined(__GLIBCPP__))
759
760
// std::hash in libstdc++ does not work correctly with vector<bool> on Big
761
// Endian platforms therefore we need to implement a custom AbslHashValue for
762
// it. More details on the bug:
763
// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=102531
764
template <typename H, typename T, typename Allocator>
765
typename std::enable_if<is_hashable<T>::value && std::is_same<T, bool>::value,
766
                        H>::type
767
AbslHashValue(H hash_state, const std::vector<T, Allocator>& vector) {
768
  typename H::AbslInternalPiecewiseCombiner combiner;
769
  for (const auto& i : vector) {
770
    unsigned char c = static_cast<unsigned char>(i);
771
    hash_state = combiner.add_buffer(std::move(hash_state), &c, sizeof(c));
772
  }
773
  return H::combine(combiner.finalize(std::move(hash_state)),
774
                    WeaklyMixedInteger{vector.size()});
775
}
776
#else
777
// When not working around the libstdc++ bug above, we still have to contend
778
// with the fact that std::hash<vector<bool>> is often poor quality, hashing
779
// directly on the internal words and on no other state.  On these platforms,
780
// vector<bool>{1, 1} and vector<bool>{1, 1, 0} hash to the same value.
781
//
782
// Mixing in the size (as we do in our other vector<> implementations) on top
783
// of the library-provided hash implementation avoids this QOI issue.
784
template <typename H, typename T, typename Allocator>
785
typename std::enable_if<is_hashable<T>::value && std::is_same<T, bool>::value,
786
                        H>::type
787
AbslHashValue(H hash_state, const std::vector<T, Allocator>& vector) {
788
  return H::combine(std::move(hash_state),
789
                    std::hash<std::vector<T, Allocator>>{}(vector),
790
                    WeaklyMixedInteger{vector.size()});
791
}
792
#endif
793
794
// -----------------------------------------------------------------------------
795
// AbslHashValue for Ordered Associative Containers
796
// -----------------------------------------------------------------------------
797
798
// AbslHashValue for hashing std::map
799
template <typename H, typename Key, typename T, typename Compare,
800
          typename Allocator>
801
typename std::enable_if<is_hashable<Key>::value && is_hashable<T>::value,
802
                        H>::type
803
AbslHashValue(H hash_state, const std::map<Key, T, Compare, Allocator>& map) {
804
  for (const auto& t : map) {
805
    hash_state = H::combine(std::move(hash_state), t);
806
  }
807
  return H::combine(std::move(hash_state), WeaklyMixedInteger{map.size()});
808
}
809
810
// AbslHashValue for hashing std::multimap
811
template <typename H, typename Key, typename T, typename Compare,
812
          typename Allocator>
813
typename std::enable_if<is_hashable<Key>::value && is_hashable<T>::value,
814
                        H>::type
815
AbslHashValue(H hash_state,
816
              const std::multimap<Key, T, Compare, Allocator>& map) {
817
  for (const auto& t : map) {
818
    hash_state = H::combine(std::move(hash_state), t);
819
  }
820
  return H::combine(std::move(hash_state), WeaklyMixedInteger{map.size()});
821
}
822
823
// AbslHashValue for hashing std::set
824
template <typename H, typename Key, typename Compare, typename Allocator>
825
typename std::enable_if<is_hashable<Key>::value, H>::type AbslHashValue(
826
    H hash_state, const std::set<Key, Compare, Allocator>& set) {
827
  for (const auto& t : set) {
828
    hash_state = H::combine(std::move(hash_state), t);
829
  }
830
  return H::combine(std::move(hash_state), WeaklyMixedInteger{set.size()});
831
}
832
833
// AbslHashValue for hashing std::multiset
834
template <typename H, typename Key, typename Compare, typename Allocator>
835
typename std::enable_if<is_hashable<Key>::value, H>::type AbslHashValue(
836
    H hash_state, const std::multiset<Key, Compare, Allocator>& set) {
837
  for (const auto& t : set) {
838
    hash_state = H::combine(std::move(hash_state), t);
839
  }
840
  return H::combine(std::move(hash_state), WeaklyMixedInteger{set.size()});
841
}
842
843
// -----------------------------------------------------------------------------
844
// AbslHashValue for Unordered Associative Containers
845
// -----------------------------------------------------------------------------
846
847
// AbslHashValue for hashing std::unordered_set
848
template <typename H, typename Key, typename Hash, typename KeyEqual,
849
          typename Alloc>
850
typename std::enable_if<is_hashable<Key>::value, H>::type AbslHashValue(
851
    H hash_state, const std::unordered_set<Key, Hash, KeyEqual, Alloc>& s) {
852
  return H::combine(
853
      H::combine_unordered(std::move(hash_state), s.begin(), s.end()),
854
      WeaklyMixedInteger{s.size()});
855
}
856
857
// AbslHashValue for hashing std::unordered_multiset
858
template <typename H, typename Key, typename Hash, typename KeyEqual,
859
          typename Alloc>
860
typename std::enable_if<is_hashable<Key>::value, H>::type AbslHashValue(
861
    H hash_state,
862
    const std::unordered_multiset<Key, Hash, KeyEqual, Alloc>& s) {
863
  return H::combine(
864
      H::combine_unordered(std::move(hash_state), s.begin(), s.end()),
865
      WeaklyMixedInteger{s.size()});
866
}
867
868
// AbslHashValue for hashing std::unordered_set
869
template <typename H, typename Key, typename T, typename Hash,
870
          typename KeyEqual, typename Alloc>
871
typename std::enable_if<is_hashable<Key>::value && is_hashable<T>::value,
872
                        H>::type
873
AbslHashValue(H hash_state,
874
              const std::unordered_map<Key, T, Hash, KeyEqual, Alloc>& s) {
875
  return H::combine(
876
      H::combine_unordered(std::move(hash_state), s.begin(), s.end()),
877
      WeaklyMixedInteger{s.size()});
878
}
879
880
// AbslHashValue for hashing std::unordered_multiset
881
template <typename H, typename Key, typename T, typename Hash,
882
          typename KeyEqual, typename Alloc>
883
typename std::enable_if<is_hashable<Key>::value && is_hashable<T>::value,
884
                        H>::type
885
AbslHashValue(H hash_state,
886
              const std::unordered_multimap<Key, T, Hash, KeyEqual, Alloc>& s) {
887
  return H::combine(
888
      H::combine_unordered(std::move(hash_state), s.begin(), s.end()),
889
      WeaklyMixedInteger{s.size()});
890
}
891
892
// -----------------------------------------------------------------------------
893
// AbslHashValue for Wrapper Types
894
// -----------------------------------------------------------------------------
895
896
// AbslHashValue for hashing std::reference_wrapper
897
template <typename H, typename T>
898
typename std::enable_if<is_hashable<T>::value, H>::type AbslHashValue(
899
    H hash_state, std::reference_wrapper<T> opt) {
900
  return H::combine(std::move(hash_state), opt.get());
901
}
902
903
// AbslHashValue for hashing std::optional
904
template <typename H, typename T>
905
typename std::enable_if<is_hashable<T>::value, H>::type AbslHashValue(
906
    H hash_state, const std::optional<T>& opt) {
907
  if (opt) hash_state = H::combine(std::move(hash_state), *opt);
908
  return H::combine(std::move(hash_state), opt.has_value());
909
}
910
911
template <typename H>
912
struct VariantVisitor {
913
  H&& hash_state;
914
  template <typename T>
915
  H operator()(const T& t) const {
916
    return H::combine(std::move(hash_state), t);
917
  }
918
};
919
920
// AbslHashValue for hashing std::variant
921
template <typename H, typename... T>
922
typename std::enable_if<conjunction<is_hashable<T>...>::value, H>::type
923
AbslHashValue(H hash_state, const std::variant<T...>& v) {
924
  if (!v.valueless_by_exception()) {
925
    hash_state = std::visit(VariantVisitor<H>{std::move(hash_state)}, v);
926
  }
927
  return H::combine(std::move(hash_state), v.index());
928
}
929
930
// -----------------------------------------------------------------------------
931
// AbslHashValue for Other Types
932
// -----------------------------------------------------------------------------
933
934
// AbslHashValue for hashing std::bitset is not defined on Little Endian
935
// platforms, for the same reason as for vector<bool> (see std::vector above):
936
// It does not expose the raw bytes, and a fallback to std::hash<> is most
937
// likely faster.
938
939
#if defined(ABSL_IS_BIG_ENDIAN) && \
940
    (defined(__GLIBCXX__) || defined(__GLIBCPP__))
941
// AbslHashValue for hashing std::bitset
942
//
943
// std::hash in libstdc++ does not work correctly with std::bitset on Big Endian
944
// platforms therefore we need to implement a custom AbslHashValue for it. More
945
// details on the bug: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=102531
946
template <typename H, size_t N>
947
H AbslHashValue(H hash_state, const std::bitset<N>& set) {
948
  typename H::AbslInternalPiecewiseCombiner combiner;
949
  for (size_t i = 0; i < N; i++) {
950
    unsigned char c = static_cast<unsigned char>(set[i]);
951
    hash_state = combiner.add_buffer(std::move(hash_state), &c, sizeof(c));
952
  }
953
  return H::combine(combiner.finalize(std::move(hash_state)), N);
954
}
955
#endif
956
957
// -----------------------------------------------------------------------------
958
959
// Mixes all values in the range [data, data+size) into the hash state.
960
// This overload accepts only uniquely-represented types, and hashes them by
961
// hashing the entire range of bytes.
962
template <typename H, typename T>
963
typename std::enable_if<is_uniquely_represented<T>::value, H>::type
964
0
hash_range_or_bytes(H hash_state, const T* data, size_t size) {
965
0
  const auto* bytes = reinterpret_cast<const unsigned char*>(data);
966
0
  return H::combine_contiguous(std::move(hash_state), bytes, sizeof(T) * size);
967
0
}
968
969
template <typename H, typename T>
970
typename std::enable_if<!is_uniquely_represented<T>::value, H>::type
971
hash_range_or_bytes(H hash_state, const T* data, size_t size) {
972
  for (const auto end = data + size; data < end; ++data) {
973
    hash_state = H::combine(std::move(hash_state), *data);
974
  }
975
  return H::combine(std::move(hash_state),
976
                    hash_internal::WeaklyMixedInteger{size});
977
}
978
979
inline constexpr uint64_t kMul = uint64_t{0x79d5f9e0de1e8cf5};
980
981
// Random data taken from the hexadecimal digits of Pi's fractional component.
982
// https://en.wikipedia.org/wiki/Nothing-up-my-sleeve_number
983
ABSL_CACHELINE_ALIGNED inline constexpr uint64_t kStaticRandomData[] = {
984
    0x243f'6a88'85a3'08d3, 0x1319'8a2e'0370'7344, 0xa409'3822'299f'31d0,
985
    0x082e'fa98'ec4e'6c89, 0x4528'21e6'38d0'1377,
986
};
987
988
// Extremely weak mixture of length that is mixed into the state before
989
// combining the data. It is used only for small strings. This also ensures that
990
// we have high entropy in all bits of the state.
991
9.37k
inline uint64_t PrecombineLengthMix(uint64_t state, size_t len) {
992
9.37k
  ABSL_ASSUME(len + sizeof(uint64_t) <= sizeof(kStaticRandomData));
993
9.37k
  uint64_t data = absl::base_internal::UnalignedLoad64(
994
9.37k
      reinterpret_cast<const unsigned char*>(&kStaticRandomData[0]) + len);
995
9.37k
  return state ^ data;
996
9.37k
}
997
998
83.7M
ABSL_ATTRIBUTE_ALWAYS_INLINE inline uint64_t Mix(uint64_t lhs, uint64_t rhs) {
999
  // Though the 128-bit product needs multiple instructions on non-x86-64
1000
  // platforms, it is still a good balance between speed and hash quality.
1001
83.7M
  absl::uint128 m = lhs;
1002
83.7M
  m *= rhs;
1003
83.7M
  return Uint128High64(m) ^ Uint128Low64(m);
1004
83.7M
}
1005
1006
// Suppress erroneous array bounds errors on GCC.
1007
#if defined(__GNUC__) && !defined(__clang__)
1008
#pragma GCC diagnostic push
1009
#pragma GCC diagnostic ignored "-Warray-bounds"
1010
#endif
1011
0
inline uint32_t Read4(const unsigned char* p) {
1012
0
  return absl::base_internal::UnalignedLoad32(p);
1013
0
}
1014
6.32k
inline uint64_t Read8(const unsigned char* p) {
1015
6.32k
  return absl::base_internal::UnalignedLoad64(p);
1016
6.32k
}
1017
#if defined(__GNUC__) && !defined(__clang__)
1018
#pragma GCC diagnostic pop
1019
#endif
1020
1021
// Reads 9 to 16 bytes from p.
1022
// The first 8 bytes are in .first, and the rest of the bytes are in .second
1023
// along with duplicated bytes from .first if len<16.
1024
inline std::pair<uint64_t, uint64_t> Read9To16(const unsigned char* p,
1025
652
                                               size_t len) {
1026
652
  return {Read8(p), Read8(p + len - 8)};
1027
652
}
1028
1029
// Reads 4 to 8 bytes from p.
1030
// Bytes are permuted and some input bytes may be duplicated in output.
1031
7.35k
inline uint64_t Read4To8(const unsigned char* p, size_t len) {
1032
  // If `len < 8`, we duplicate bytes. We always put low memory at the end.
1033
  // E.g., on little endian platforms:
1034
  // `ABCD` will be read as `ABCDABCD`.
1035
  // `ABCDE` will be read as `BCDEABCD`.
1036
  // `ABCDEF` will be read as `CDEFABCD`.
1037
  // `ABCDEFG` will be read as `DEFGABCD`.
1038
  // `ABCDEFGH` will be read as `EFGHABCD`.
1039
  // We also do not care about endianness. On big-endian platforms, bytes will
1040
  // be permuted differently. We always shift low memory by 32, because that
1041
  // can be pipelined earlier. Reading high memory requires computing
1042
  // `p + len - 4`.
1043
7.35k
  uint64_t most_significant =
1044
7.35k
      static_cast<uint64_t>(absl::base_internal::UnalignedLoad32(p)) << 32;
1045
7.35k
  uint64_t least_significant =
1046
7.35k
      absl::base_internal::UnalignedLoad32(p + len - 4);
1047
7.35k
  return most_significant | least_significant;
1048
7.35k
}
1049
1050
// Reads 1 to 3 bytes from p. Some input bytes may be duplicated in output.
1051
116
inline uint32_t Read1To3(const unsigned char* p, size_t len) {
1052
  // The trick used by this implementation is to avoid branches.
1053
  // We always read three bytes by duplicating.
1054
  // E.g.,
1055
  // `A` is read as `AAA`.
1056
  // `AB` is read as `ABB`.
1057
  // `ABC` is read as `ABC`.
1058
  // We always shift `p[0]` so that it can be pipelined better.
1059
  // Other bytes require extra computation to find indices.
1060
116
  uint32_t mem0 = (static_cast<uint32_t>(p[0]) << 16) | p[len - 1];
1061
116
  uint32_t mem1 = static_cast<uint32_t>(p[len / 2]) << 8;
1062
116
  return mem0 | mem1;
1063
116
}
1064
1065
#ifdef ABSL_HASH_INTERNAL_HAS_CRC32
1066
1067
ABSL_ATTRIBUTE_ALWAYS_INLINE inline uint64_t CombineRawImpl(uint64_t state,
1068
                                                            uint64_t value) {
1069
  // We use a union to access the high and low 32 bits of the state.
1070
  union {
1071
    uint64_t u64;
1072
    struct {
1073
#ifdef ABSL_IS_LITTLE_ENDIAN
1074
      uint32_t low, high;
1075
#else  // big endian
1076
      uint32_t high, low;
1077
#endif
1078
    } u32s;
1079
  } s;
1080
  s.u64 = state;
1081
  // The general idea here is to do two CRC32 operations in parallel using the
1082
  // low and high 32 bits of state as CRC states. Note that: (1) when absl::Hash
1083
  // is inlined into swisstable lookups, we know that the seed's high bits are
1084
  // zero so s.u32s.high is available immediately. (2) We chose to multiply
1085
  // value by 3 for the low CRC because (a) multiplication by 3 can be done in 1
1086
  // cycle on x86/ARM and (b) multiplication has carry bits so it's nonlinear in
1087
  // GF(2) and therefore ensures that the two CRCs are independent (unlike bit
1088
  // rotation, XOR, etc). (3) We also tried using addition instead of
1089
  // multiplication by 3, but (a) code size is larger and (b) if the input keys
1090
  // all have 0s in the bits where the addition constant has 1s, then the
1091
  // addition is equivalent to XOR and linear in GF(2). (4) The union makes it
1092
  // easy for the compiler to understand that the high and low CRC states are
1093
  // independent from each other so that when CombineRawImpl is repeated (e.g.
1094
  // for std::pair<size_t, size_t>), the CRC chains can run in parallel. We
1095
  // originally tried using bswaps rather than shifting by 32 bits (to get from
1096
  // high to low bits) because bswap is one byte smaller in code size, but the
1097
  // compiler couldn't understand that the CRC chains were independent.
1098
  s.u32s.high =
1099
      static_cast<uint32_t>(ABSL_HASH_INTERNAL_CRC32_U64(s.u32s.high, value));
1100
  s.u32s.low = static_cast<uint32_t>(
1101
      ABSL_HASH_INTERNAL_CRC32_U64(s.u32s.low, 3 * value));
1102
  return s.u64;
1103
}
1104
#else   // ABSL_HASH_INTERNAL_HAS_CRC32
1105
ABSL_ATTRIBUTE_ALWAYS_INLINE inline uint64_t CombineRawImpl(uint64_t state,
1106
7.46k
                                                            uint64_t value) {
1107
7.46k
  return Mix(state ^ value, kMul);
1108
7.46k
}
1109
#endif  // ABSL_HASH_INTERNAL_HAS_CRC32
1110
1111
// Slow dispatch path for calls to CombineContiguousImpl with a size argument
1112
// larger than inlined size. Has the same effect as calling
1113
// CombineContiguousImpl() repeatedly with the chunk stride size.
1114
uint64_t CombineLargeContiguousImplOn32BitLengthGt8(uint64_t state,
1115
                                                    const unsigned char* first,
1116
                                                    size_t len);
1117
uint64_t CombineLargeContiguousImplOn64BitLengthGt32(uint64_t state,
1118
                                                     const unsigned char* first,
1119
                                                     size_t len);
1120
1121
ABSL_ATTRIBUTE_ALWAYS_INLINE inline uint64_t CombineSmallContiguousImpl(
1122
7.46k
    uint64_t state, const unsigned char* first, size_t len) {
1123
7.46k
  ABSL_ASSUME(len <= 8);
1124
7.46k
  uint64_t v;
1125
7.46k
  if (len >= 4) {
1126
7.35k
    v = Read4To8(first, len);
1127
7.35k
  } else if (len > 0) {
1128
116
    v = Read1To3(first, len);
1129
116
  } else {
1130
    // Empty string must modify the state.
1131
0
    v = 0x57;
1132
0
  }
1133
7.46k
  return CombineRawImpl(state, v);
1134
7.46k
}
1135
1136
ABSL_ATTRIBUTE_ALWAYS_INLINE inline uint64_t CombineContiguousImpl9to16(
1137
652
    uint64_t state, const unsigned char* first, size_t len) {
1138
652
  ABSL_ASSUME(len >= 9);
1139
652
  ABSL_ASSUME(len <= 16);
1140
  // Note: any time one half of the mix function becomes zero it will fail to
1141
  // incorporate any bits from the other half. However, there is exactly 1 in
1142
  // 2^64 values for each side that achieve this, and only when the size is
1143
  // exactly 16 -- for smaller sizes there is an overlapping byte that makes
1144
  // this impossible unless the seed is *also* incredibly unlucky.
1145
652
  auto p = Read9To16(first, len);
1146
652
  return Mix(state ^ p.first, kMul ^ p.second);
1147
652
}
1148
1149
ABSL_ATTRIBUTE_ALWAYS_INLINE inline uint64_t CombineContiguousImpl17to32(
1150
1.25k
    uint64_t state, const unsigned char* first, size_t len) {
1151
1.25k
  ABSL_ASSUME(len >= 17);
1152
1.25k
  ABSL_ASSUME(len <= 32);
1153
  // Do two mixes of overlapping 16-byte ranges in parallel to minimize
1154
  // latency.
1155
1.25k
  const uint64_t m0 =
1156
1.25k
      Mix(Read8(first) ^ kStaticRandomData[1], Read8(first + 8) ^ state);
1157
1158
1.25k
  const unsigned char* tail_16b_ptr = first + (len - 16);
1159
1.25k
  const uint64_t m1 = Mix(Read8(tail_16b_ptr) ^ kStaticRandomData[3],
1160
1.25k
                          Read8(tail_16b_ptr + 8) ^ state);
1161
1.25k
  return m0 ^ m1;
1162
1.25k
}
1163
1164
// Implementation of the base case for combine_contiguous where we actually
1165
// mix the bytes into the state.
1166
// Dispatch to different implementations of combine_contiguous depending
1167
// on the value of `sizeof(size_t)`.
1168
inline uint64_t CombineContiguousImpl(
1169
    uint64_t state, const unsigned char* first, size_t len,
1170
0
    std::integral_constant<int, 4> /* sizeof_size_t */) {
1171
0
  // For large values we use CityHash, for small ones we use custom low latency
1172
0
  // hash.
1173
0
  if (len <= 8) {
1174
0
    return CombineSmallContiguousImpl(PrecombineLengthMix(state, len), first,
1175
0
                                      len);
1176
0
  }
1177
0
  return CombineLargeContiguousImplOn32BitLengthGt8(state, first, len);
1178
0
}
1179
1180
#ifdef ABSL_HASH_INTERNAL_HAS_CRC32
1181
inline uint64_t CombineContiguousImpl(
1182
    uint64_t state, const unsigned char* first, size_t len,
1183
    std::integral_constant<int, 8> /* sizeof_size_t */) {
1184
  if (ABSL_PREDICT_FALSE(len > 32)) {
1185
    return CombineLargeContiguousImplOn64BitLengthGt32(state, first, len);
1186
  }
1187
  // `mul` is the salt that is used for final mixing. It is important to fill
1188
  // high 32 bits because CRC wipes out high 32 bits.
1189
  // `rotr` is important to mix `len` into high 32 bits.
1190
  uint64_t mul = absl::rotr(kMul, static_cast<int>(len));
1191
  // Only low 32 bits of each uint64_t are used in CRC32 so we use gbswap_64 to
1192
  // move high 32 bits to low 32 bits. It has slightly smaller binary size than
1193
  // `>> 32`. `state + 8 * len` is a single instruction on both x86 and ARM, so
1194
  // we use it to better mix length. Although only the low 32 bits of the pair
1195
  // elements are used, we use pair<uint64_t, uint64_t> for better generated
1196
  // code.
1197
  std::pair<uint64_t, uint64_t> crcs = {state + 8 * len,
1198
                                        absl::gbswap_64(state)};
1199
1200
  // All CRC operations here directly read bytes from the memory.
1201
  // Single fused instructions are used, like `crc32 rcx, qword ptr [rsi]`.
1202
  // On x86, llvm-mca reports latency `R + 2` for such fused instructions, while
1203
  // `R + 3` for two separate `mov` + `crc` instructions. `R` is the latency of
1204
  // reading the memory. Fused instructions also reduce register pressure
1205
  // allowing surrounding code to be more efficient when this code is inlined.
1206
  if (len > 8) {
1207
    crcs = {ABSL_HASH_INTERNAL_CRC32_U64(crcs.first, Read8(first)),
1208
            ABSL_HASH_INTERNAL_CRC32_U64(crcs.second, Read8(first + len - 8))};
1209
    if (len > 16) {
1210
      // We compute the second round of dependent CRC32 operations.
1211
      crcs = {ABSL_HASH_INTERNAL_CRC32_U64(crcs.first, Read8(first + len - 16)),
1212
              ABSL_HASH_INTERNAL_CRC32_U64(crcs.second, Read8(first + 8))};
1213
    }
1214
  } else {
1215
    if (len >= 4) {
1216
      // We use CRC for 4 bytes to benefit from the fused instruction and better
1217
      // hash quality.
1218
      // Using `xor` or `add` may reduce latency for this case, but would
1219
      // require more registers, more instructions and will have worse hash
1220
      // quality.
1221
      crcs = {ABSL_HASH_INTERNAL_CRC32_U32(static_cast<uint32_t>(crcs.first),
1222
                                           Read4(first)),
1223
              ABSL_HASH_INTERNAL_CRC32_U32(static_cast<uint32_t>(crcs.second),
1224
                                           Read4(first + len - 4))};
1225
    } else if (len >= 1) {
1226
      // We mix three bytes all into different output registers.
1227
      // This way, we do not need shifting of these bytes (so they don't overlap
1228
      // with each other).
1229
      crcs = {ABSL_HASH_INTERNAL_CRC32_U8(static_cast<uint32_t>(crcs.first),
1230
                                          first[0]),
1231
              ABSL_HASH_INTERNAL_CRC32_U8(static_cast<uint32_t>(crcs.second),
1232
                                          first[len - 1])};
1233
      // Middle byte is mixed weaker. It is a new byte only for len == 3.
1234
      // Mixing is independent from CRC operations so it is scheduled ASAP.
1235
      mul += first[len / 2];
1236
    }
1237
  }
1238
  // `mul` is mixed into both sides of `Mix` to guarantee non-zero values for
1239
  // both multiplicands. Using Mix instead of just multiplication here improves
1240
  // hash quality, especially for short strings.
1241
  return Mix(mul - crcs.first, crcs.second - mul);
1242
}
1243
#else
1244
inline uint64_t CombineContiguousImpl(
1245
    uint64_t state, const unsigned char* first, size_t len,
1246
126k
    std::integral_constant<int, 8> /* sizeof_size_t */) {
1247
  // For large values we use LowLevelHash or CityHash depending on the platform,
1248
  // for small ones we use custom low latency hash.
1249
126k
  if (len <= 8) {
1250
7.46k
    return CombineSmallContiguousImpl(PrecombineLengthMix(state, len), first,
1251
7.46k
                                      len);
1252
7.46k
  }
1253
119k
  if (len <= 16) {
1254
652
    return CombineContiguousImpl9to16(PrecombineLengthMix(state, len), first,
1255
652
                                      len);
1256
652
  }
1257
118k
  if (len <= 32) {
1258
1.25k
    return CombineContiguousImpl17to32(PrecombineLengthMix(state, len), first,
1259
1.25k
                                       len);
1260
1.25k
  }
1261
  // We must not mix length into the state here because calling
1262
  // CombineContiguousImpl twice with PiecewiseChunkSize() must be equivalent
1263
  // to calling CombineLargeContiguousImpl once with 2 * PiecewiseChunkSize().
1264
117k
  return CombineLargeContiguousImplOn64BitLengthGt32(state, first, len);
1265
118k
}
1266
#endif  // ABSL_HASH_INTERNAL_HAS_CRC32
1267
1268
#if defined(ABSL_INTERNAL_LEGACY_HASH_NAMESPACE)
1269
#define ABSL_HASH_INTERNAL_SUPPORT_LEGACY_HASH_ 1
1270
#else
1271
#define ABSL_HASH_INTERNAL_SUPPORT_LEGACY_HASH_ 0
1272
#endif
1273
1274
// Type trait to select the appropriate hash implementation to use.
1275
// HashSelect::type<T> will give the proper hash implementation, to be invoked
1276
// as:
1277
//   HashSelect::type<T>::Invoke(state, value)
1278
// Also, HashSelect::type<T>::value is a boolean equal to `true` if there is a
1279
// valid `Invoke` function. Types that are not hashable will have a ::value of
1280
// `false`.
1281
struct HashSelect {
1282
 private:
1283
  struct WeaklyMixedIntegerProbe {
1284
    template <typename H>
1285
    static H Invoke(H state, WeaklyMixedInteger value) {
1286
      return hash_internal::hash_weakly_mixed_integer(std::move(state), value);
1287
    }
1288
  };
1289
1290
  struct State : HashStateBase<State> {
1291
    static State combine_contiguous(State hash_state, const unsigned char*,
1292
                                    size_t);
1293
    using State::HashStateBase::combine_contiguous;
1294
    static State combine_raw(State state, uint64_t value);
1295
    static State combine_weakly_mixed_integer(State hash_state,
1296
                                              WeaklyMixedInteger value);
1297
  };
1298
1299
  struct UniquelyRepresentedProbe {
1300
    template <typename H, typename T>
1301
    static auto Invoke(H state, const T& value)
1302
0
        -> absl::enable_if_t<is_uniquely_represented<T>::value, H> {
1303
0
      return hash_internal::hash_bytes(std::move(state), value);
1304
0
    }
Unexecuted instantiation: _ZN4absl13hash_internal10HashSelect24UniquelyRepresentedProbe6InvokeINS0_15MixingHashStateEiEENSt3__19enable_ifIXsr23is_uniquely_representedIT0_EE5valueET_E4typeES8_RKS7_
Unexecuted instantiation: _ZN4absl13hash_internal10HashSelect24UniquelyRepresentedProbe6InvokeINS0_15MixingHashStateEmEENSt3__19enable_ifIXsr23is_uniquely_representedIT0_EE5valueET_E4typeES8_RKS7_
1305
  };
1306
1307
  struct HashValueProbe {
1308
    template <typename H, typename T>
1309
    static auto Invoke(H state, const T& value) -> absl::enable_if_t<
1310
        std::is_same<H,
1311
                     decltype(AbslHashValue(std::move(state), value))>::value,
1312
0
        H> {
1313
0
      return AbslHashValue(std::move(state), value);
1314
0
    }
Unexecuted instantiation: _ZN4absl13hash_internal10HashSelect14HashValueProbe6InvokeINS0_15MixingHashStateENSt3__15tupleIJRKNS5_17basic_string_viewIcNS5_11char_traitsIcEEEERKiEEEEENS5_9enable_ifIXsr3std7is_sameIT_DTcl13AbslHashValueclsr3stdE4movefp_Efp0_EEEE5valueESH_E4typeESH_RKT0_
Unexecuted instantiation: _ZN4absl13hash_internal10HashSelect14HashValueProbe6InvokeINS0_15MixingHashStateENSt3__117basic_string_viewIcNS5_11char_traitsIcEEEEEENS5_9enable_ifIXsr3std7is_sameIT_DTcl13AbslHashValueclsr3stdE4movefp_Efp0_EEEE5valueESB_E4typeESB_RKT0_
Unexecuted instantiation: _ZN4absl13hash_internal10HashSelect14HashValueProbe6InvokeINS0_15MixingHashStateENSt3__15tupleIJRKmEEEEENS5_9enable_ifIXsr3std7is_sameIT_DTcl13AbslHashValueclsr3stdE4movefp_Efp0_EEEE5valueESB_E4typeESB_RKT0_
Unexecuted instantiation: _ZN4absl13hash_internal10HashSelect14HashValueProbe6InvokeINS0_15MixingHashStateENS_4CordEEENSt3__19enable_ifIXsr3std7is_sameIT_DTcl13AbslHashValueclsr3stdE4movefp_Efp0_EEEE5valueES8_E4typeES8_RKT0_
1315
  };
1316
1317
  struct LegacyHashProbe {
1318
#if ABSL_HASH_INTERNAL_SUPPORT_LEGACY_HASH_
1319
    template <typename H, typename T>
1320
    static auto Invoke(H state, const T& value) -> absl::enable_if_t<
1321
        std::is_convertible<
1322
            decltype(ABSL_INTERNAL_LEGACY_HASH_NAMESPACE::hash<T>()(value)),
1323
            size_t>::value,
1324
        H> {
1325
      return hash_internal::hash_bytes(
1326
          std::move(state),
1327
          ABSL_INTERNAL_LEGACY_HASH_NAMESPACE::hash<T>{}(value));
1328
    }
1329
#endif  // ABSL_HASH_INTERNAL_SUPPORT_LEGACY_HASH_
1330
  };
1331
1332
  struct StdHashProbe {
1333
    template <typename H, typename T>
1334
    static auto Invoke(H state, const T& value)
1335
        -> absl::enable_if_t<type_traits_internal::IsHashable<T>::value, H> {
1336
      return hash_internal::hash_bytes(std::move(state), std::hash<T>{}(value));
1337
    }
1338
  };
1339
1340
  template <typename Hash, typename T>
1341
  struct Probe : Hash {
1342
   private:
1343
    template <typename H, typename = decltype(H::Invoke(
1344
                              std::declval<State>(), std::declval<const T&>()))>
1345
    static std::true_type Test(int);
1346
    template <typename U>
1347
    static std::false_type Test(char);
1348
1349
   public:
1350
    static constexpr bool value = decltype(Test<Hash>(0))::value;
1351
  };
1352
1353
 public:
1354
  // Probe each implementation in order.
1355
  // disjunction provides short circuiting wrt instantiation.
1356
  template <typename T>
1357
  using Apply = absl::disjunction<         //
1358
      Probe<WeaklyMixedIntegerProbe, T>,   //
1359
      Probe<UniquelyRepresentedProbe, T>,  //
1360
      Probe<HashValueProbe, T>,            //
1361
      Probe<LegacyHashProbe, T>,           //
1362
      Probe<StdHashProbe, T>,              //
1363
      std::false_type>;
1364
};
1365
1366
template <typename T>
1367
struct is_hashable
1368
    : std::integral_constant<bool, HashSelect::template Apply<T>::value> {};
1369
1370
class ABSL_DLL MixingHashState : public HashStateBase<MixingHashState> {
1371
  template <typename T>
1372
  using IntegralFastPath =
1373
      conjunction<std::is_integral<T>, is_uniquely_represented<T>,
1374
                  FitsIn64Bits<T>>;
1375
1376
 public:
1377
  // Move only
1378
  MixingHashState(MixingHashState&&) = default;
1379
  MixingHashState& operator=(MixingHashState&&) = default;
1380
1381
  // Fundamental base case for hash recursion: mixes the given range of bytes
1382
  // into the hash state.
1383
  static MixingHashState combine_contiguous(MixingHashState hash_state,
1384
                                            const unsigned char* first,
1385
0
                                            size_t size) {
1386
0
    return MixingHashState(
1387
0
        CombineContiguousImpl(hash_state.state_, first, size,
1388
0
                              std::integral_constant<int, sizeof(size_t)>{}));
1389
0
  }
1390
  using MixingHashState::HashStateBase::combine_contiguous;
1391
1392
  template <typename T>
1393
0
  static size_t hash(const T& value) {
1394
0
    return hash_with_seed(value, Seed());
1395
0
  }
Unexecuted instantiation: unsigned long absl::hash_internal::MixingHashState::hash<std::__1::tuple<std::__1::basic_string_view<char, std::__1::char_traits<char> > const&, int const&> >(std::__1::tuple<std::__1::basic_string_view<char, std::__1::char_traits<char> > const&, int const&> const&)
Unexecuted instantiation: unsigned long absl::hash_internal::MixingHashState::hash<std::__1::tuple<unsigned long const&> >(std::__1::tuple<unsigned long const&> const&)
Unexecuted instantiation: unsigned long absl::hash_internal::MixingHashState::hash<std::__1::basic_string_view<char, std::__1::char_traits<char> > >(std::__1::basic_string_view<char, std::__1::char_traits<char> > const&)
Unexecuted instantiation: unsigned long absl::hash_internal::MixingHashState::hash<absl::Cord>(absl::Cord const&)
1396
1397
  // For performance reasons in non-opt mode, we specialize this for
1398
  // integral types.
1399
  // Otherwise we would be instantiating and calling dozens of functions for
1400
  // something that is just one multiplication and a couple xor's.
1401
  // The result should be the same as running the whole algorithm, but faster.
1402
  template <typename T, absl::enable_if_t<IntegralFastPath<T>::value, int> = 0>
1403
  static size_t hash_with_seed(T value, size_t seed) {
1404
    return static_cast<size_t>(
1405
        CombineRawImpl(seed, static_cast<std::make_unsigned_t<T>>(value)));
1406
  }
1407
1408
  template <typename T, absl::enable_if_t<!IntegralFastPath<T>::value, int> = 0>
1409
0
  static size_t hash_with_seed(const T& value, size_t seed) {
1410
0
    return static_cast<size_t>(combine(MixingHashState{seed}, value).state_);
1411
0
  }
Unexecuted instantiation: _ZN4absl13hash_internal15MixingHashState14hash_with_seedINSt3__15tupleIJRKNS3_17basic_string_viewIcNS3_11char_traitsIcEEEERKiEEETnNS3_9enable_ifIXntsr16IntegralFastPathIT_EE5valueEiE4typeELi0EEEmRKSF_m
Unexecuted instantiation: _ZN4absl13hash_internal15MixingHashState14hash_with_seedINSt3__15tupleIJRKmEEETnNS3_9enable_ifIXntsr16IntegralFastPathIT_EE5valueEiE4typeELi0EEEmRKS9_m
Unexecuted instantiation: _ZN4absl13hash_internal15MixingHashState14hash_with_seedINSt3__117basic_string_viewIcNS3_11char_traitsIcEEEETnNS3_9enable_ifIXntsr16IntegralFastPathIT_EE5valueEiE4typeELi0EEEmRKS9_m
Unexecuted instantiation: _ZN4absl13hash_internal15MixingHashState14hash_with_seedINS_4CordETnNSt3__19enable_ifIXntsr16IntegralFastPathIT_EE5valueEiE4typeELi0EEEmRKS6_m
1412
1413
 private:
1414
  friend class MixingHashState::HashStateBase;
1415
  template <typename H>
1416
  friend H absl::hash_internal::hash_weakly_mixed_integer(H,
1417
                                                          WeaklyMixedInteger);
1418
  // Allow the HashState type-erasure implementation to invoke
1419
  // RunCombinedUnordered() directly.
1420
  friend class absl::HashState;
1421
  friend struct CombineRaw;
1422
1423
  // For use in Seed().
1424
  static const void* const kSeed;
1425
1426
  // Invoked only once for a given argument; that plus the fact that this is
1427
  // move-only ensures that there is only one non-moved-from object.
1428
0
  MixingHashState() : state_(Seed()) {}
1429
1430
  // Workaround for MSVC bug.
1431
  // We make the type copyable to fix the calling convention, even though we
1432
  // never actually copy it. Keep it private to not affect the public API of the
1433
  // type.
1434
  MixingHashState(const MixingHashState&) = default;
1435
1436
0
  explicit MixingHashState(uint64_t state) : state_(state) {}
1437
1438
  // Combines a raw value from e.g. integrals/floats/pointers/etc. This allows
1439
  // us to be consistent with IntegralFastPath when combining raw types, but
1440
  // optimize Read1To3 and Read4To8 differently for the string case.
1441
  static MixingHashState combine_raw(MixingHashState hash_state,
1442
0
                                     uint64_t value) {
1443
0
    return MixingHashState(CombineRawImpl(hash_state.state_, value));
1444
0
  }
1445
1446
  static MixingHashState combine_weakly_mixed_integer(
1447
0
      MixingHashState hash_state, WeaklyMixedInteger value) {
1448
0
    // Some transformation for the value is needed to make an empty
1449
0
    // string/container change the mixing hash state.
1450
0
    // We use constant smaller than 8 bits to make compiler use
1451
0
    // `add` with an immediate operand with 1 byte value.
1452
0
    return MixingHashState{hash_state.state_ + (0x57 + value.value)};
1453
0
  }
1454
1455
  template <typename CombinerT>
1456
  static MixingHashState RunCombineUnordered(MixingHashState state,
1457
                                             CombinerT combiner) {
1458
    uint64_t unordered_state = 0;
1459
    combiner(MixingHashState{}, [&](MixingHashState& inner_state) {
1460
      // Add the hash state of the element to the running total, but mix the
1461
      // carry bit back into the low bit.  This in intended to avoid losing
1462
      // entropy to overflow, especially when unordered_multisets contain
1463
      // multiple copies of the same value.
1464
      auto element_state = inner_state.state_;
1465
      unordered_state += element_state;
1466
      if (unordered_state < element_state) {
1467
        ++unordered_state;
1468
      }
1469
      inner_state = MixingHashState{};
1470
    });
1471
    return MixingHashState::combine(std::move(state), unordered_state);
1472
  }
1473
1474
  // A non-deterministic seed.
1475
  //
1476
  // The current purpose of this seed is to generate non-deterministic results
1477
  // and prevent having users depend on the particular hash values.
1478
  // It is not meant as a security feature right now, but it leaves the door
1479
  // open to upgrade it to a true per-process random seed. A true random seed
1480
  // costs more and we don't need to pay for that right now.
1481
  //
1482
  // On platforms with ASLR, we take advantage of it to make a per-process
1483
  // random value.
1484
  // See https://en.wikipedia.org/wiki/Address_space_layout_randomization
1485
  //
1486
  // On other platforms this is still going to be non-deterministic but most
1487
  // probably per-build and not per-process.
1488
0
  ABSL_ATTRIBUTE_ALWAYS_INLINE static size_t Seed() {
1489
0
#if (!defined(__clang__) || __clang_major__ > 11) && \
1490
0
    (!defined(__apple_build_version__) ||            \
1491
0
     __apple_build_version__ >= 19558921)  // Xcode 12
1492
0
    return static_cast<size_t>(reinterpret_cast<uintptr_t>(&kSeed));
1493
#else
1494
    // Workaround the absence of
1495
    // https://github.com/llvm/llvm-project/commit/bc15bf66dcca76cc06fe71fca35b74dc4d521021.
1496
    return static_cast<size_t>(reinterpret_cast<uintptr_t>(kSeed));
1497
#endif
1498
0
  }
1499
1500
  uint64_t state_;
1501
};
1502
1503
struct AggregateBarrier {};
1504
1505
// Add a private base class to make sure this type is not an aggregate.
1506
// Aggregates can be aggregate initialized even if the default constructor is
1507
// deleted.
1508
struct PoisonedHash : private AggregateBarrier {
1509
  PoisonedHash() = delete;
1510
  PoisonedHash(const PoisonedHash&) = delete;
1511
  PoisonedHash& operator=(const PoisonedHash&) = delete;
1512
};
1513
1514
template <typename T>
1515
struct HashImpl {
1516
0
  size_t operator()(const T& value) const {
1517
0
    return MixingHashState::hash(value);
1518
0
  }
Unexecuted instantiation: absl::hash_internal::HashImpl<std::__1::tuple<std::__1::basic_string_view<char, std::__1::char_traits<char> > const&, int const&> >::operator()(std::__1::tuple<std::__1::basic_string_view<char, std::__1::char_traits<char> > const&, int const&> const&) const
Unexecuted instantiation: absl::hash_internal::HashImpl<std::__1::tuple<unsigned long const&> >::operator()(std::__1::tuple<unsigned long const&> const&) const
Unexecuted instantiation: absl::hash_internal::HashImpl<std::__1::basic_string_view<char, std::__1::char_traits<char> > >::operator()(std::__1::basic_string_view<char, std::__1::char_traits<char> > const&) const
Unexecuted instantiation: absl::hash_internal::HashImpl<absl::Cord>::operator()(absl::Cord const&) const
1519
1520
 private:
1521
  friend struct HashWithSeed;
1522
1523
0
  size_t hash_with_seed(const T& value, size_t seed) const {
1524
0
    return MixingHashState::hash_with_seed(value, seed);
1525
0
  }
Unexecuted instantiation: absl::hash_internal::HashImpl<std::__1::basic_string_view<char, std::__1::char_traits<char> > >::hash_with_seed(std::__1::basic_string_view<char, std::__1::char_traits<char> > const&, unsigned long) const
Unexecuted instantiation: absl::hash_internal::HashImpl<absl::Cord>::hash_with_seed(absl::Cord const&, unsigned long) const
1526
};
1527
1528
template <typename T>
1529
struct Hash
1530
    : absl::conditional_t<is_hashable<T>::value, HashImpl<T>, PoisonedHash> {};
1531
1532
template <typename H>
1533
template <typename T, typename... Ts>
1534
0
H HashStateBase<H>::combine(H state, const T& value, const Ts&... values) {
1535
0
  return H::combine(hash_internal::HashSelect::template Apply<T>::Invoke(
1536
0
                        std::move(state), value),
1537
0
                    values...);
1538
0
}
Unexecuted instantiation: absl::hash_internal::MixingHashState absl::hash_internal::HashStateBase<absl::hash_internal::MixingHashState>::combine<std::__1::tuple<std::__1::basic_string_view<char, std::__1::char_traits<char> > const&, int const&>>(absl::hash_internal::MixingHashState, std::__1::tuple<std::__1::basic_string_view<char, std::__1::char_traits<char> > const&, int const&> const&)
Unexecuted instantiation: absl::hash_internal::MixingHashState absl::hash_internal::HashStateBase<absl::hash_internal::MixingHashState>::combine<std::__1::basic_string_view<char, std::__1::char_traits<char> >, int>(absl::hash_internal::MixingHashState, std::__1::basic_string_view<char, std::__1::char_traits<char> > const&, int const&)
Unexecuted instantiation: absl::hash_internal::MixingHashState absl::hash_internal::HashStateBase<absl::hash_internal::MixingHashState>::combine<int>(absl::hash_internal::MixingHashState, int const&)
Unexecuted instantiation: absl::hash_internal::MixingHashState absl::hash_internal::HashStateBase<absl::hash_internal::MixingHashState>::combine<std::__1::tuple<unsigned long const&>>(absl::hash_internal::MixingHashState, std::__1::tuple<unsigned long const&> const&)
Unexecuted instantiation: absl::hash_internal::MixingHashState absl::hash_internal::HashStateBase<absl::hash_internal::MixingHashState>::combine<unsigned long>(absl::hash_internal::MixingHashState, unsigned long const&)
Unexecuted instantiation: absl::hash_internal::MixingHashState absl::hash_internal::HashStateBase<absl::hash_internal::MixingHashState>::combine<std::__1::basic_string_view<char, std::__1::char_traits<char> >>(absl::hash_internal::MixingHashState, std::__1::basic_string_view<char, std::__1::char_traits<char> > const&)
Unexecuted instantiation: absl::hash_internal::MixingHashState absl::hash_internal::HashStateBase<absl::hash_internal::MixingHashState>::combine<absl::Cord>(absl::hash_internal::MixingHashState, absl::Cord const&)
1539
1540
template <typename H>
1541
template <typename T>
1542
0
H HashStateBase<H>::combine_contiguous(H state, const T* data, size_t size) {
1543
0
  return hash_internal::hash_range_or_bytes(std::move(state), data, size);
1544
0
}
1545
1546
template <typename H>
1547
template <typename I>
1548
H HashStateBase<H>::combine_unordered(H state, I begin, I end) {
1549
  return H::RunCombineUnordered(std::move(state),
1550
                                CombineUnorderedCallback<I>{begin, end});
1551
}
1552
1553
template <typename H>
1554
H PiecewiseCombiner::add_buffer(H state, const unsigned char* data,
1555
0
                                size_t size) {
1556
0
  if (position_ + size < PiecewiseChunkSize()) {
1557
0
    // This partial chunk does not fill our existing buffer
1558
0
    memcpy(buf_ + position_, data, size);
1559
0
    position_ += size;
1560
0
    return state;
1561
0
  }
1562
0
  added_something_ = true;
1563
0
  // If the buffer is partially filled we need to complete the buffer
1564
0
  // and hash it.
1565
0
  if (position_ != 0) {
1566
0
    const size_t bytes_needed = PiecewiseChunkSize() - position_;
1567
0
    memcpy(buf_ + position_, data, bytes_needed);
1568
0
    state = H::combine_contiguous(std::move(state), buf_, PiecewiseChunkSize());
1569
0
    data += bytes_needed;
1570
0
    size -= bytes_needed;
1571
0
  }
1572
0
1573
0
  // Hash whatever chunks we can without copying
1574
0
  while (size >= PiecewiseChunkSize()) {
1575
0
    state = H::combine_contiguous(std::move(state), data, PiecewiseChunkSize());
1576
0
    data += PiecewiseChunkSize();
1577
0
    size -= PiecewiseChunkSize();
1578
0
  }
1579
0
  // Fill the buffer with the remainder
1580
0
  memcpy(buf_, data, size);
1581
0
  position_ = size;
1582
0
  return state;
1583
0
}
1584
1585
template <typename H>
1586
0
H PiecewiseCombiner::finalize(H state) {
1587
0
  // Do not call combine_contiguous with empty remainder since it is modifying
1588
0
  // state.
1589
0
  if (added_something_ && position_ == 0) {
1590
0
    return state;
1591
0
  }
1592
0
  // We still call combine_contiguous for the entirely empty buffer.
1593
0
  return H::combine_contiguous(std::move(state), buf_, position_);
1594
0
}
1595
1596
}  // namespace hash_internal
1597
ABSL_NAMESPACE_END
1598
}  // namespace absl
1599
1600
#undef ABSL_HASH_INTERNAL_HAS_CRC32
1601
#undef ABSL_HASH_INTERNAL_CRC32_U64
1602
#undef ABSL_HASH_INTERNAL_CRC32_U32
1603
#undef ABSL_HASH_INTERNAL_CRC32_U8
1604
1605
#endif  // ABSL_HASH_INTERNAL_HASH_H_