Coverage Report

Created: 2026-07-16 06:43

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