Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2025-01-18 09:27:18

0001 // Copyright 2018 The Abseil Authors.
0002 //
0003 // Licensed under the Apache License, Version 2.0 (the "License");
0004 // you may not use this file except in compliance with the License.
0005 // You may obtain a copy of the License at
0006 //
0007 //      https://www.apache.org/licenses/LICENSE-2.0
0008 //
0009 // Unless required by applicable law or agreed to in writing, software
0010 // distributed under the License is distributed on an "AS IS" BASIS,
0011 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
0012 // See the License for the specific language governing permissions and
0013 // limitations under the License.
0014 //
0015 // -----------------------------------------------------------------------------
0016 // File: hash.h
0017 // -----------------------------------------------------------------------------
0018 //
0019 #ifndef ABSL_HASH_INTERNAL_HASH_H_
0020 #define ABSL_HASH_INTERNAL_HASH_H_
0021 
0022 #ifdef __APPLE__
0023 #include <Availability.h>
0024 #include <TargetConditionals.h>
0025 #endif
0026 
0027 #include "absl/base/config.h"
0028 
0029 // For feature testing and determining which headers can be included.
0030 #if ABSL_INTERNAL_CPLUSPLUS_LANG >= 202002L
0031 #include <version>
0032 #else
0033 #include <ciso646>
0034 #endif
0035 
0036 #include <algorithm>
0037 #include <array>
0038 #include <bitset>
0039 #include <cmath>
0040 #include <cstddef>
0041 #include <cstring>
0042 #include <deque>
0043 #include <forward_list>
0044 #include <functional>
0045 #include <iterator>
0046 #include <limits>
0047 #include <list>
0048 #include <map>
0049 #include <memory>
0050 #include <set>
0051 #include <string>
0052 #include <tuple>
0053 #include <type_traits>
0054 #include <unordered_map>
0055 #include <unordered_set>
0056 #include <utility>
0057 #include <vector>
0058 
0059 #include "absl/base/internal/unaligned_access.h"
0060 #include "absl/base/port.h"
0061 #include "absl/container/fixed_array.h"
0062 #include "absl/hash/internal/city.h"
0063 #include "absl/hash/internal/low_level_hash.h"
0064 #include "absl/meta/type_traits.h"
0065 #include "absl/numeric/bits.h"
0066 #include "absl/numeric/int128.h"
0067 #include "absl/strings/string_view.h"
0068 #include "absl/types/optional.h"
0069 #include "absl/types/variant.h"
0070 #include "absl/utility/utility.h"
0071 
0072 #if defined(__cpp_lib_filesystem) && __cpp_lib_filesystem >= 201703L && \
0073     !defined(_LIBCPP_HAS_NO_FILESYSTEM_LIBRARY)
0074 #include <filesystem>  // NOLINT
0075 #endif
0076 
0077 #ifdef ABSL_HAVE_STD_STRING_VIEW
0078 #include <string_view>
0079 #endif
0080 
0081 namespace absl {
0082 ABSL_NAMESPACE_BEGIN
0083 
0084 class HashState;
0085 
0086 namespace hash_internal {
0087 
0088 // Internal detail: Large buffers are hashed in smaller chunks.  This function
0089 // returns the size of these chunks.
0090 constexpr size_t PiecewiseChunkSize() { return 1024; }
0091 
0092 // PiecewiseCombiner
0093 //
0094 // PiecewiseCombiner is an internal-only helper class for hashing a piecewise
0095 // buffer of `char` or `unsigned char` as though it were contiguous.  This class
0096 // provides two methods:
0097 //
0098 //   H add_buffer(state, data, size)
0099 //   H finalize(state)
0100 //
0101 // `add_buffer` can be called zero or more times, followed by a single call to
0102 // `finalize`.  This will produce the same hash expansion as concatenating each
0103 // buffer piece into a single contiguous buffer, and passing this to
0104 // `H::combine_contiguous`.
0105 //
0106 //  Example usage:
0107 //    PiecewiseCombiner combiner;
0108 //    for (const auto& piece : pieces) {
0109 //      state = combiner.add_buffer(std::move(state), piece.data, piece.size);
0110 //    }
0111 //    return combiner.finalize(std::move(state));
0112 class PiecewiseCombiner {
0113  public:
0114   PiecewiseCombiner() : position_(0) {}
0115   PiecewiseCombiner(const PiecewiseCombiner&) = delete;
0116   PiecewiseCombiner& operator=(const PiecewiseCombiner&) = delete;
0117 
0118   // PiecewiseCombiner::add_buffer()
0119   //
0120   // Appends the given range of bytes to the sequence to be hashed, which may
0121   // modify the provided hash state.
0122   template <typename H>
0123   H add_buffer(H state, const unsigned char* data, size_t size);
0124   template <typename H>
0125   H add_buffer(H state, const char* data, size_t size) {
0126     return add_buffer(std::move(state),
0127                       reinterpret_cast<const unsigned char*>(data), size);
0128   }
0129 
0130   // PiecewiseCombiner::finalize()
0131   //
0132   // Finishes combining the hash sequence, which may may modify the provided
0133   // hash state.
0134   //
0135   // Once finalize() is called, add_buffer() may no longer be called. The
0136   // resulting hash state will be the same as if the pieces passed to
0137   // add_buffer() were concatenated into a single flat buffer, and then provided
0138   // to H::combine_contiguous().
0139   template <typename H>
0140   H finalize(H state);
0141 
0142  private:
0143   unsigned char buf_[PiecewiseChunkSize()];
0144   size_t position_;
0145 };
0146 
0147 // is_hashable()
0148 //
0149 // Trait class which returns true if T is hashable by the absl::Hash framework.
0150 // Used for the AbslHashValue implementations for composite types below.
0151 template <typename T>
0152 struct is_hashable;
0153 
0154 // HashStateBase
0155 //
0156 // An internal implementation detail that contains common implementation details
0157 // for all of the "hash state objects" objects generated by Abseil.  This is not
0158 // a public API; users should not create classes that inherit from this.
0159 //
0160 // A hash state object is the template argument `H` passed to `AbslHashValue`.
0161 // It represents an intermediate state in the computation of an unspecified hash
0162 // algorithm. `HashStateBase` provides a CRTP style base class for hash state
0163 // implementations. Developers adding type support for `absl::Hash` should not
0164 // rely on any parts of the state object other than the following member
0165 // functions:
0166 //
0167 //   * HashStateBase::combine()
0168 //   * HashStateBase::combine_contiguous()
0169 //   * HashStateBase::combine_unordered()
0170 //
0171 // A derived hash state class of type `H` must provide a public member function
0172 // with a signature similar to the following:
0173 //
0174 //    `static H combine_contiguous(H state, const unsigned char*, size_t)`.
0175 //
0176 // It must also provide a private template method named RunCombineUnordered.
0177 //
0178 // A "consumer" is a 1-arg functor returning void.  Its argument is a reference
0179 // to an inner hash state object, and it may be called multiple times.  When
0180 // called, the functor consumes the entropy from the provided state object,
0181 // and resets that object to its empty state.
0182 //
0183 // A "combiner" is a stateless 2-arg functor returning void.  Its arguments are
0184 // an inner hash state object and an ElementStateConsumer functor.  A combiner
0185 // uses the provided inner hash state object to hash each element of the
0186 // container, passing the inner hash state object to the consumer after hashing
0187 // each element.
0188 //
0189 // Given these definitions, a derived hash state class of type H
0190 // must provide a private template method with a signature similar to the
0191 // following:
0192 //
0193 //    `template <typename CombinerT>`
0194 //    `static H RunCombineUnordered(H outer_state, CombinerT combiner)`
0195 //
0196 // This function is responsible for constructing the inner state object and
0197 // providing a consumer to the combiner.  It uses side effects of the consumer
0198 // and combiner to mix the state of each element in an order-independent manner,
0199 // and uses this to return an updated value of `outer_state`.
0200 //
0201 // This inside-out approach generates efficient object code in the normal case,
0202 // but allows us to use stack storage to implement the absl::HashState type
0203 // erasure mechanism (avoiding heap allocations while hashing).
0204 //
0205 // `HashStateBase` will provide a complete implementation for a hash state
0206 // object in terms of these two methods.
0207 //
0208 // Example:
0209 //
0210 //   // Use CRTP to define your derived class.
0211 //   struct MyHashState : HashStateBase<MyHashState> {
0212 //       static H combine_contiguous(H state, const unsigned char*, size_t);
0213 //       using MyHashState::HashStateBase::combine;
0214 //       using MyHashState::HashStateBase::combine_contiguous;
0215 //       using MyHashState::HashStateBase::combine_unordered;
0216 //     private:
0217 //       template <typename CombinerT>
0218 //       static H RunCombineUnordered(H state, CombinerT combiner);
0219 //   };
0220 template <typename H>
0221 class HashStateBase {
0222  public:
0223   // HashStateBase::combine()
0224   //
0225   // Combines an arbitrary number of values into a hash state, returning the
0226   // updated state.
0227   //
0228   // Each of the value types `T` must be separately hashable by the Abseil
0229   // hashing framework.
0230   //
0231   // NOTE:
0232   //
0233   //   state = H::combine(std::move(state), value1, value2, value3);
0234   //
0235   // is guaranteed to produce the same hash expansion as:
0236   //
0237   //   state = H::combine(std::move(state), value1);
0238   //   state = H::combine(std::move(state), value2);
0239   //   state = H::combine(std::move(state), value3);
0240   template <typename T, typename... Ts>
0241   static H combine(H state, const T& value, const Ts&... values);
0242   static H combine(H state) { return state; }
0243 
0244   // HashStateBase::combine_contiguous()
0245   //
0246   // Combines a contiguous array of `size` elements into a hash state, returning
0247   // the updated state.
0248   //
0249   // NOTE:
0250   //
0251   //   state = H::combine_contiguous(std::move(state), data, size);
0252   //
0253   // is NOT guaranteed to produce the same hash expansion as a for-loop (it may
0254   // perform internal optimizations).  If you need this guarantee, use the
0255   // for-loop instead.
0256   template <typename T>
0257   static H combine_contiguous(H state, const T* data, size_t size);
0258 
0259   template <typename I>
0260   static H combine_unordered(H state, I begin, I end);
0261 
0262   using AbslInternalPiecewiseCombiner = PiecewiseCombiner;
0263 
0264   template <typename T>
0265   using is_hashable = absl::hash_internal::is_hashable<T>;
0266 
0267  private:
0268   // Common implementation of the iteration step of a "combiner", as described
0269   // above.
0270   template <typename I>
0271   struct CombineUnorderedCallback {
0272     I begin;
0273     I end;
0274 
0275     template <typename InnerH, typename ElementStateConsumer>
0276     void operator()(InnerH inner_state, ElementStateConsumer cb) {
0277       for (; begin != end; ++begin) {
0278         inner_state = H::combine(std::move(inner_state), *begin);
0279         cb(inner_state);
0280       }
0281     }
0282   };
0283 };
0284 
0285 // is_uniquely_represented
0286 //
0287 // `is_uniquely_represented<T>` is a trait class that indicates whether `T`
0288 // is uniquely represented.
0289 //
0290 // A type is "uniquely represented" if two equal values of that type are
0291 // guaranteed to have the same bytes in their underlying storage. In other
0292 // words, if `a == b`, then `memcmp(&a, &b, sizeof(T))` is guaranteed to be
0293 // zero. This property cannot be detected automatically, so this trait is false
0294 // by default, but can be specialized by types that wish to assert that they are
0295 // uniquely represented. This makes them eligible for certain optimizations.
0296 //
0297 // If you have any doubt whatsoever, do not specialize this template.
0298 // The default is completely safe, and merely disables some optimizations
0299 // that will not matter for most types. Specializing this template,
0300 // on the other hand, can be very hazardous.
0301 //
0302 // To be uniquely represented, a type must not have multiple ways of
0303 // representing the same value; for example, float and double are not
0304 // uniquely represented, because they have distinct representations for
0305 // +0 and -0. Furthermore, the type's byte representation must consist
0306 // solely of user-controlled data, with no padding bits and no compiler-
0307 // controlled data such as vptrs or sanitizer metadata. This is usually
0308 // very difficult to guarantee, because in most cases the compiler can
0309 // insert data and padding bits at its own discretion.
0310 //
0311 // If you specialize this template for a type `T`, you must do so in the file
0312 // that defines that type (or in this file). If you define that specialization
0313 // anywhere else, `is_uniquely_represented<T>` could have different meanings
0314 // in different places.
0315 //
0316 // The Enable parameter is meaningless; it is provided as a convenience,
0317 // to support certain SFINAE techniques when defining specializations.
0318 template <typename T, typename Enable = void>
0319 struct is_uniquely_represented : std::false_type {};
0320 
0321 // is_uniquely_represented<unsigned char>
0322 //
0323 // unsigned char is a synonym for "byte", so it is guaranteed to be
0324 // uniquely represented.
0325 template <>
0326 struct is_uniquely_represented<unsigned char> : std::true_type {};
0327 
0328 // is_uniquely_represented for non-standard integral types
0329 //
0330 // Integral types other than bool should be uniquely represented on any
0331 // platform that this will plausibly be ported to.
0332 template <typename Integral>
0333 struct is_uniquely_represented<
0334     Integral, typename std::enable_if<std::is_integral<Integral>::value>::type>
0335     : std::true_type {};
0336 
0337 // is_uniquely_represented<bool>
0338 //
0339 //
0340 template <>
0341 struct is_uniquely_represented<bool> : std::false_type {};
0342 
0343 // hash_bytes()
0344 //
0345 // Convenience function that combines `hash_state` with the byte representation
0346 // of `value`.
0347 template <typename H, typename T>
0348 H hash_bytes(H hash_state, const T& value) {
0349   const unsigned char* start = reinterpret_cast<const unsigned char*>(&value);
0350   return H::combine_contiguous(std::move(hash_state), start, sizeof(value));
0351 }
0352 
0353 // -----------------------------------------------------------------------------
0354 // AbslHashValue for Basic Types
0355 // -----------------------------------------------------------------------------
0356 
0357 // Note: Default `AbslHashValue` implementations live in `hash_internal`. This
0358 // allows us to block lexical scope lookup when doing an unqualified call to
0359 // `AbslHashValue` below. User-defined implementations of `AbslHashValue` can
0360 // only be found via ADL.
0361 
0362 // AbslHashValue() for hashing bool values
0363 //
0364 // We use SFINAE to ensure that this overload only accepts bool, not types that
0365 // are convertible to bool.
0366 template <typename H, typename B>
0367 typename std::enable_if<std::is_same<B, bool>::value, H>::type AbslHashValue(
0368     H hash_state, B value) {
0369   return H::combine(std::move(hash_state),
0370                     static_cast<unsigned char>(value ? 1 : 0));
0371 }
0372 
0373 // AbslHashValue() for hashing enum values
0374 template <typename H, typename Enum>
0375 typename std::enable_if<std::is_enum<Enum>::value, H>::type AbslHashValue(
0376     H hash_state, Enum e) {
0377   // In practice, we could almost certainly just invoke hash_bytes directly,
0378   // but it's possible that a sanitizer might one day want to
0379   // store data in the unused bits of an enum. To avoid that risk, we
0380   // convert to the underlying type before hashing. Hopefully this will get
0381   // optimized away; if not, we can reopen discussion with c-toolchain-team.
0382   return H::combine(std::move(hash_state),
0383                     static_cast<typename std::underlying_type<Enum>::type>(e));
0384 }
0385 // AbslHashValue() for hashing floating-point values
0386 template <typename H, typename Float>
0387 typename std::enable_if<std::is_same<Float, float>::value ||
0388                             std::is_same<Float, double>::value,
0389                         H>::type
0390 AbslHashValue(H hash_state, Float value) {
0391   return hash_internal::hash_bytes(std::move(hash_state),
0392                                    value == 0 ? 0 : value);
0393 }
0394 
0395 // Long double has the property that it might have extra unused bytes in it.
0396 // For example, in x86 sizeof(long double)==16 but it only really uses 80-bits
0397 // of it. This means we can't use hash_bytes on a long double and have to
0398 // convert it to something else first.
0399 template <typename H, typename LongDouble>
0400 typename std::enable_if<std::is_same<LongDouble, long double>::value, H>::type
0401 AbslHashValue(H hash_state, LongDouble value) {
0402   const int category = std::fpclassify(value);
0403   switch (category) {
0404     case FP_INFINITE:
0405       // Add the sign bit to differentiate between +Inf and -Inf
0406       hash_state = H::combine(std::move(hash_state), std::signbit(value));
0407       break;
0408 
0409     case FP_NAN:
0410     case FP_ZERO:
0411     default:
0412       // Category is enough for these.
0413       break;
0414 
0415     case FP_NORMAL:
0416     case FP_SUBNORMAL:
0417       // We can't convert `value` directly to double because this would have
0418       // undefined behavior if the value is out of range.
0419       // std::frexp gives us a value in the range (-1, -.5] or [.5, 1) that is
0420       // guaranteed to be in range for `double`. The truncation is
0421       // implementation defined, but that works as long as it is deterministic.
0422       int exp;
0423       auto mantissa = static_cast<double>(std::frexp(value, &exp));
0424       hash_state = H::combine(std::move(hash_state), mantissa, exp);
0425   }
0426 
0427   return H::combine(std::move(hash_state), category);
0428 }
0429 
0430 // Without this overload, an array decays to a pointer and we hash that, which
0431 // is not likely to be what the caller intended.
0432 template <typename H, typename T, size_t N>
0433 H AbslHashValue(H hash_state, T (&)[N]) {
0434   static_assert(
0435       sizeof(T) == -1,
0436       "Hashing C arrays is not allowed. For string literals, wrap the literal "
0437       "in absl::string_view(). To hash the array contents, use "
0438       "absl::MakeSpan() or make the array an std::array. To hash the array "
0439       "address, use &array[0].");
0440   return hash_state;
0441 }
0442 
0443 // AbslHashValue() for hashing pointers
0444 template <typename H, typename T>
0445 std::enable_if_t<std::is_pointer<T>::value, H> AbslHashValue(H hash_state,
0446                                                              T ptr) {
0447   auto v = reinterpret_cast<uintptr_t>(ptr);
0448   // Due to alignment, pointers tend to have low bits as zero, and the next few
0449   // bits follow a pattern since they are also multiples of some base value.
0450   // Mixing the pointer twice helps prevent stuck low bits for certain alignment
0451   // values.
0452   return H::combine(std::move(hash_state), v, v);
0453 }
0454 
0455 // AbslHashValue() for hashing nullptr_t
0456 template <typename H>
0457 H AbslHashValue(H hash_state, std::nullptr_t) {
0458   return H::combine(std::move(hash_state), static_cast<void*>(nullptr));
0459 }
0460 
0461 // AbslHashValue() for hashing pointers-to-member
0462 template <typename H, typename T, typename C>
0463 H AbslHashValue(H hash_state, T C::*ptr) {
0464   auto salient_ptm_size = [](std::size_t n) -> std::size_t {
0465 #if defined(_MSC_VER)
0466     // Pointers-to-member-function on MSVC consist of one pointer plus 0, 1, 2,
0467     // or 3 ints. In 64-bit mode, they are 8-byte aligned and thus can contain
0468     // padding (namely when they have 1 or 3 ints). The value below is a lower
0469     // bound on the number of salient, non-padding bytes that we use for
0470     // hashing.
0471     if (alignof(T C::*) == alignof(int)) {
0472       // No padding when all subobjects have the same size as the total
0473       // alignment. This happens in 32-bit mode.
0474       return n;
0475     } else {
0476       // Padding for 1 int (size 16) or 3 ints (size 24).
0477       // With 2 ints, the size is 16 with no padding, which we pessimize.
0478       return n == 24 ? 20 : n == 16 ? 12 : n;
0479     }
0480 #else
0481   // On other platforms, we assume that pointers-to-members do not have
0482   // padding.
0483 #ifdef __cpp_lib_has_unique_object_representations
0484     static_assert(std::has_unique_object_representations<T C::*>::value);
0485 #endif  // __cpp_lib_has_unique_object_representations
0486     return n;
0487 #endif
0488   };
0489   return H::combine_contiguous(std::move(hash_state),
0490                                reinterpret_cast<unsigned char*>(&ptr),
0491                                salient_ptm_size(sizeof ptr));
0492 }
0493 
0494 // -----------------------------------------------------------------------------
0495 // AbslHashValue for Composite Types
0496 // -----------------------------------------------------------------------------
0497 
0498 // AbslHashValue() for hashing pairs
0499 template <typename H, typename T1, typename T2>
0500 typename std::enable_if<is_hashable<T1>::value && is_hashable<T2>::value,
0501                         H>::type
0502 AbslHashValue(H hash_state, const std::pair<T1, T2>& p) {
0503   return H::combine(std::move(hash_state), p.first, p.second);
0504 }
0505 
0506 // hash_tuple()
0507 //
0508 // Helper function for hashing a tuple. The third argument should
0509 // be an index_sequence running from 0 to tuple_size<Tuple> - 1.
0510 template <typename H, typename Tuple, size_t... Is>
0511 H hash_tuple(H hash_state, const Tuple& t, absl::index_sequence<Is...>) {
0512   return H::combine(std::move(hash_state), std::get<Is>(t)...);
0513 }
0514 
0515 // AbslHashValue for hashing tuples
0516 template <typename H, typename... Ts>
0517 #if defined(_MSC_VER)
0518 // This SFINAE gets MSVC confused under some conditions. Let's just disable it
0519 // for now.
0520 H
0521 #else   // _MSC_VER
0522 typename std::enable_if<absl::conjunction<is_hashable<Ts>...>::value, H>::type
0523 #endif  // _MSC_VER
0524 AbslHashValue(H hash_state, const std::tuple<Ts...>& t) {
0525   return hash_internal::hash_tuple(std::move(hash_state), t,
0526                                    absl::make_index_sequence<sizeof...(Ts)>());
0527 }
0528 
0529 // -----------------------------------------------------------------------------
0530 // AbslHashValue for Pointers
0531 // -----------------------------------------------------------------------------
0532 
0533 // AbslHashValue for hashing unique_ptr
0534 template <typename H, typename T, typename D>
0535 H AbslHashValue(H hash_state, const std::unique_ptr<T, D>& ptr) {
0536   return H::combine(std::move(hash_state), ptr.get());
0537 }
0538 
0539 // AbslHashValue for hashing shared_ptr
0540 template <typename H, typename T>
0541 H AbslHashValue(H hash_state, const std::shared_ptr<T>& ptr) {
0542   return H::combine(std::move(hash_state), ptr.get());
0543 }
0544 
0545 // -----------------------------------------------------------------------------
0546 // AbslHashValue for String-Like Types
0547 // -----------------------------------------------------------------------------
0548 
0549 // AbslHashValue for hashing strings
0550 //
0551 // All the string-like types supported here provide the same hash expansion for
0552 // the same character sequence. These types are:
0553 //
0554 //  - `absl::Cord`
0555 //  - `std::string` (and std::basic_string<T, std::char_traits<T>, A> for
0556 //      any allocator A and any T in {char, wchar_t, char16_t, char32_t})
0557 //  - `absl::string_view`, `std::string_view`, `std::wstring_view`,
0558 //    `std::u16string_view`, and `std::u32_string_view`.
0559 //
0560 // For simplicity, we currently support only strings built on `char`, `wchar_t`,
0561 // `char16_t`, or `char32_t`. This support may be broadened, if necessary, but
0562 // with some caution - this overload would misbehave in cases where the traits'
0563 // `eq()` member isn't equivalent to `==` on the underlying character type.
0564 template <typename H>
0565 H AbslHashValue(H hash_state, absl::string_view str) {
0566   return H::combine(
0567       H::combine_contiguous(std::move(hash_state), str.data(), str.size()),
0568       str.size());
0569 }
0570 
0571 // Support std::wstring, std::u16string and std::u32string.
0572 template <typename Char, typename Alloc, typename H,
0573           typename = absl::enable_if_t<std::is_same<Char, wchar_t>::value ||
0574                                        std::is_same<Char, char16_t>::value ||
0575                                        std::is_same<Char, char32_t>::value>>
0576 H AbslHashValue(
0577     H hash_state,
0578     const std::basic_string<Char, std::char_traits<Char>, Alloc>& str) {
0579   return H::combine(
0580       H::combine_contiguous(std::move(hash_state), str.data(), str.size()),
0581       str.size());
0582 }
0583 
0584 #ifdef ABSL_HAVE_STD_STRING_VIEW
0585 
0586 // Support std::wstring_view, std::u16string_view and std::u32string_view.
0587 template <typename Char, typename H,
0588           typename = absl::enable_if_t<std::is_same<Char, wchar_t>::value ||
0589                                        std::is_same<Char, char16_t>::value ||
0590                                        std::is_same<Char, char32_t>::value>>
0591 H AbslHashValue(H hash_state, std::basic_string_view<Char> str) {
0592   return H::combine(
0593       H::combine_contiguous(std::move(hash_state), str.data(), str.size()),
0594       str.size());
0595 }
0596 
0597 #endif  // ABSL_HAVE_STD_STRING_VIEW
0598 
0599 #if defined(__cpp_lib_filesystem) && __cpp_lib_filesystem >= 201703L && \
0600     !defined(_LIBCPP_HAS_NO_FILESYSTEM_LIBRARY) && \
0601     (!defined(__ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__) ||        \
0602      __ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__ >= 130000) &&       \
0603     (!defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) ||         \
0604      __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ >= 101500)
0605 
0606 #define ABSL_INTERNAL_STD_FILESYSTEM_PATH_HASH_AVAILABLE 1
0607 
0608 // Support std::filesystem::path. The SFINAE is required because some string
0609 // types are implicitly convertible to std::filesystem::path.
0610 template <typename Path, typename H,
0611           typename = absl::enable_if_t<
0612               std::is_same_v<Path, std::filesystem::path>>>
0613 H AbslHashValue(H hash_state, const Path& path) {
0614   // This is implemented by deferring to the standard library to compute the
0615   // hash.  The standard library requires that for two paths, `p1 == p2`, then
0616   // `hash_value(p1) == hash_value(p2)`. `AbslHashValue` has the same
0617   // requirement. Since `operator==` does platform specific matching, deferring
0618   // to the standard library is the simplest approach.
0619   return H::combine(std::move(hash_state), std::filesystem::hash_value(path));
0620 }
0621 
0622 #endif  // ABSL_INTERNAL_STD_FILESYSTEM_PATH_HASH_AVAILABLE
0623 
0624 // -----------------------------------------------------------------------------
0625 // AbslHashValue for Sequence Containers
0626 // -----------------------------------------------------------------------------
0627 
0628 // AbslHashValue for hashing std::array
0629 template <typename H, typename T, size_t N>
0630 typename std::enable_if<is_hashable<T>::value, H>::type AbslHashValue(
0631     H hash_state, const std::array<T, N>& array) {
0632   return H::combine_contiguous(std::move(hash_state), array.data(),
0633                                array.size());
0634 }
0635 
0636 // AbslHashValue for hashing std::deque
0637 template <typename H, typename T, typename Allocator>
0638 typename std::enable_if<is_hashable<T>::value, H>::type AbslHashValue(
0639     H hash_state, const std::deque<T, Allocator>& deque) {
0640   // TODO(gromer): investigate a more efficient implementation taking
0641   // advantage of the chunk structure.
0642   for (const auto& t : deque) {
0643     hash_state = H::combine(std::move(hash_state), t);
0644   }
0645   return H::combine(std::move(hash_state), deque.size());
0646 }
0647 
0648 // AbslHashValue for hashing std::forward_list
0649 template <typename H, typename T, typename Allocator>
0650 typename std::enable_if<is_hashable<T>::value, H>::type AbslHashValue(
0651     H hash_state, const std::forward_list<T, Allocator>& list) {
0652   size_t size = 0;
0653   for (const T& t : list) {
0654     hash_state = H::combine(std::move(hash_state), t);
0655     ++size;
0656   }
0657   return H::combine(std::move(hash_state), size);
0658 }
0659 
0660 // AbslHashValue for hashing std::list
0661 template <typename H, typename T, typename Allocator>
0662 typename std::enable_if<is_hashable<T>::value, H>::type AbslHashValue(
0663     H hash_state, const std::list<T, Allocator>& list) {
0664   for (const auto& t : list) {
0665     hash_state = H::combine(std::move(hash_state), t);
0666   }
0667   return H::combine(std::move(hash_state), list.size());
0668 }
0669 
0670 // AbslHashValue for hashing std::vector
0671 //
0672 // Do not use this for vector<bool> on platforms that have a working
0673 // implementation of std::hash. It does not have a .data(), and a fallback for
0674 // std::hash<> is most likely faster.
0675 template <typename H, typename T, typename Allocator>
0676 typename std::enable_if<is_hashable<T>::value && !std::is_same<T, bool>::value,
0677                         H>::type
0678 AbslHashValue(H hash_state, const std::vector<T, Allocator>& vector) {
0679   return H::combine(H::combine_contiguous(std::move(hash_state), vector.data(),
0680                                           vector.size()),
0681                     vector.size());
0682 }
0683 
0684 // AbslHashValue special cases for hashing std::vector<bool>
0685 
0686 #if defined(ABSL_IS_BIG_ENDIAN) && \
0687     (defined(__GLIBCXX__) || defined(__GLIBCPP__))
0688 
0689 // std::hash in libstdc++ does not work correctly with vector<bool> on Big
0690 // Endian platforms therefore we need to implement a custom AbslHashValue for
0691 // it. More details on the bug:
0692 // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=102531
0693 template <typename H, typename T, typename Allocator>
0694 typename std::enable_if<is_hashable<T>::value && std::is_same<T, bool>::value,
0695                         H>::type
0696 AbslHashValue(H hash_state, const std::vector<T, Allocator>& vector) {
0697   typename H::AbslInternalPiecewiseCombiner combiner;
0698   for (const auto& i : vector) {
0699     unsigned char c = static_cast<unsigned char>(i);
0700     hash_state = combiner.add_buffer(std::move(hash_state), &c, sizeof(c));
0701   }
0702   return H::combine(combiner.finalize(std::move(hash_state)), vector.size());
0703 }
0704 #else
0705 // When not working around the libstdc++ bug above, we still have to contend
0706 // with the fact that std::hash<vector<bool>> is often poor quality, hashing
0707 // directly on the internal words and on no other state.  On these platforms,
0708 // vector<bool>{1, 1} and vector<bool>{1, 1, 0} hash to the same value.
0709 //
0710 // Mixing in the size (as we do in our other vector<> implementations) on top
0711 // of the library-provided hash implementation avoids this QOI issue.
0712 template <typename H, typename T, typename Allocator>
0713 typename std::enable_if<is_hashable<T>::value && std::is_same<T, bool>::value,
0714                         H>::type
0715 AbslHashValue(H hash_state, const std::vector<T, Allocator>& vector) {
0716   return H::combine(std::move(hash_state),
0717                     std::hash<std::vector<T, Allocator>>{}(vector),
0718                     vector.size());
0719 }
0720 #endif
0721 
0722 // -----------------------------------------------------------------------------
0723 // AbslHashValue for Ordered Associative Containers
0724 // -----------------------------------------------------------------------------
0725 
0726 // AbslHashValue for hashing std::map
0727 template <typename H, typename Key, typename T, typename Compare,
0728           typename Allocator>
0729 typename std::enable_if<is_hashable<Key>::value && is_hashable<T>::value,
0730                         H>::type
0731 AbslHashValue(H hash_state, const std::map<Key, T, Compare, Allocator>& map) {
0732   for (const auto& t : map) {
0733     hash_state = H::combine(std::move(hash_state), t);
0734   }
0735   return H::combine(std::move(hash_state), map.size());
0736 }
0737 
0738 // AbslHashValue for hashing std::multimap
0739 template <typename H, typename Key, typename T, typename Compare,
0740           typename Allocator>
0741 typename std::enable_if<is_hashable<Key>::value && is_hashable<T>::value,
0742                         H>::type
0743 AbslHashValue(H hash_state,
0744               const std::multimap<Key, T, Compare, Allocator>& map) {
0745   for (const auto& t : map) {
0746     hash_state = H::combine(std::move(hash_state), t);
0747   }
0748   return H::combine(std::move(hash_state), map.size());
0749 }
0750 
0751 // AbslHashValue for hashing std::set
0752 template <typename H, typename Key, typename Compare, typename Allocator>
0753 typename std::enable_if<is_hashable<Key>::value, H>::type AbslHashValue(
0754     H hash_state, const std::set<Key, Compare, Allocator>& set) {
0755   for (const auto& t : set) {
0756     hash_state = H::combine(std::move(hash_state), t);
0757   }
0758   return H::combine(std::move(hash_state), set.size());
0759 }
0760 
0761 // AbslHashValue for hashing std::multiset
0762 template <typename H, typename Key, typename Compare, typename Allocator>
0763 typename std::enable_if<is_hashable<Key>::value, H>::type AbslHashValue(
0764     H hash_state, const std::multiset<Key, Compare, Allocator>& set) {
0765   for (const auto& t : set) {
0766     hash_state = H::combine(std::move(hash_state), t);
0767   }
0768   return H::combine(std::move(hash_state), set.size());
0769 }
0770 
0771 // -----------------------------------------------------------------------------
0772 // AbslHashValue for Unordered Associative Containers
0773 // -----------------------------------------------------------------------------
0774 
0775 // AbslHashValue for hashing std::unordered_set
0776 template <typename H, typename Key, typename Hash, typename KeyEqual,
0777           typename Alloc>
0778 typename std::enable_if<is_hashable<Key>::value, H>::type AbslHashValue(
0779     H hash_state, const std::unordered_set<Key, Hash, KeyEqual, Alloc>& s) {
0780   return H::combine(
0781       H::combine_unordered(std::move(hash_state), s.begin(), s.end()),
0782       s.size());
0783 }
0784 
0785 // AbslHashValue for hashing std::unordered_multiset
0786 template <typename H, typename Key, typename Hash, typename KeyEqual,
0787           typename Alloc>
0788 typename std::enable_if<is_hashable<Key>::value, H>::type AbslHashValue(
0789     H hash_state,
0790     const std::unordered_multiset<Key, Hash, KeyEqual, Alloc>& s) {
0791   return H::combine(
0792       H::combine_unordered(std::move(hash_state), s.begin(), s.end()),
0793       s.size());
0794 }
0795 
0796 // AbslHashValue for hashing std::unordered_set
0797 template <typename H, typename Key, typename T, typename Hash,
0798           typename KeyEqual, typename Alloc>
0799 typename std::enable_if<is_hashable<Key>::value && is_hashable<T>::value,
0800                         H>::type
0801 AbslHashValue(H hash_state,
0802               const std::unordered_map<Key, T, Hash, KeyEqual, Alloc>& s) {
0803   return H::combine(
0804       H::combine_unordered(std::move(hash_state), s.begin(), s.end()),
0805       s.size());
0806 }
0807 
0808 // AbslHashValue for hashing std::unordered_multiset
0809 template <typename H, typename Key, typename T, typename Hash,
0810           typename KeyEqual, typename Alloc>
0811 typename std::enable_if<is_hashable<Key>::value && is_hashable<T>::value,
0812                         H>::type
0813 AbslHashValue(H hash_state,
0814               const std::unordered_multimap<Key, T, Hash, KeyEqual, Alloc>& s) {
0815   return H::combine(
0816       H::combine_unordered(std::move(hash_state), s.begin(), s.end()),
0817       s.size());
0818 }
0819 
0820 // -----------------------------------------------------------------------------
0821 // AbslHashValue for Wrapper Types
0822 // -----------------------------------------------------------------------------
0823 
0824 // AbslHashValue for hashing std::reference_wrapper
0825 template <typename H, typename T>
0826 typename std::enable_if<is_hashable<T>::value, H>::type AbslHashValue(
0827     H hash_state, std::reference_wrapper<T> opt) {
0828   return H::combine(std::move(hash_state), opt.get());
0829 }
0830 
0831 // AbslHashValue for hashing absl::optional
0832 template <typename H, typename T>
0833 typename std::enable_if<is_hashable<T>::value, H>::type AbslHashValue(
0834     H hash_state, const absl::optional<T>& opt) {
0835   if (opt) hash_state = H::combine(std::move(hash_state), *opt);
0836   return H::combine(std::move(hash_state), opt.has_value());
0837 }
0838 
0839 // VariantVisitor
0840 template <typename H>
0841 struct VariantVisitor {
0842   H&& hash_state;
0843   template <typename T>
0844   H operator()(const T& t) const {
0845     return H::combine(std::move(hash_state), t);
0846   }
0847 };
0848 
0849 // AbslHashValue for hashing absl::variant
0850 template <typename H, typename... T>
0851 typename std::enable_if<conjunction<is_hashable<T>...>::value, H>::type
0852 AbslHashValue(H hash_state, const absl::variant<T...>& v) {
0853   if (!v.valueless_by_exception()) {
0854     hash_state = absl::visit(VariantVisitor<H>{std::move(hash_state)}, v);
0855   }
0856   return H::combine(std::move(hash_state), v.index());
0857 }
0858 
0859 // -----------------------------------------------------------------------------
0860 // AbslHashValue for Other Types
0861 // -----------------------------------------------------------------------------
0862 
0863 // AbslHashValue for hashing std::bitset is not defined on Little Endian
0864 // platforms, for the same reason as for vector<bool> (see std::vector above):
0865 // It does not expose the raw bytes, and a fallback to std::hash<> is most
0866 // likely faster.
0867 
0868 #if defined(ABSL_IS_BIG_ENDIAN) && \
0869     (defined(__GLIBCXX__) || defined(__GLIBCPP__))
0870 // AbslHashValue for hashing std::bitset
0871 //
0872 // std::hash in libstdc++ does not work correctly with std::bitset on Big Endian
0873 // platforms therefore we need to implement a custom AbslHashValue for it. More
0874 // details on the bug: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=102531
0875 template <typename H, size_t N>
0876 H AbslHashValue(H hash_state, const std::bitset<N>& set) {
0877   typename H::AbslInternalPiecewiseCombiner combiner;
0878   for (size_t i = 0; i < N; i++) {
0879     unsigned char c = static_cast<unsigned char>(set[i]);
0880     hash_state = combiner.add_buffer(std::move(hash_state), &c, sizeof(c));
0881   }
0882   return H::combine(combiner.finalize(std::move(hash_state)), N);
0883 }
0884 #endif
0885 
0886 // -----------------------------------------------------------------------------
0887 
0888 // hash_range_or_bytes()
0889 //
0890 // Mixes all values in the range [data, data+size) into the hash state.
0891 // This overload accepts only uniquely-represented types, and hashes them by
0892 // hashing the entire range of bytes.
0893 template <typename H, typename T>
0894 typename std::enable_if<is_uniquely_represented<T>::value, H>::type
0895 hash_range_or_bytes(H hash_state, const T* data, size_t size) {
0896   const auto* bytes = reinterpret_cast<const unsigned char*>(data);
0897   return H::combine_contiguous(std::move(hash_state), bytes, sizeof(T) * size);
0898 }
0899 
0900 // hash_range_or_bytes()
0901 template <typename H, typename T>
0902 typename std::enable_if<!is_uniquely_represented<T>::value, H>::type
0903 hash_range_or_bytes(H hash_state, const T* data, size_t size) {
0904   for (const auto end = data + size; data < end; ++data) {
0905     hash_state = H::combine(std::move(hash_state), *data);
0906   }
0907   return hash_state;
0908 }
0909 
0910 #if defined(ABSL_INTERNAL_LEGACY_HASH_NAMESPACE) && \
0911     ABSL_META_INTERNAL_STD_HASH_SFINAE_FRIENDLY_
0912 #define ABSL_HASH_INTERNAL_SUPPORT_LEGACY_HASH_ 1
0913 #else
0914 #define ABSL_HASH_INTERNAL_SUPPORT_LEGACY_HASH_ 0
0915 #endif
0916 
0917 // HashSelect
0918 //
0919 // Type trait to select the appropriate hash implementation to use.
0920 // HashSelect::type<T> will give the proper hash implementation, to be invoked
0921 // as:
0922 //   HashSelect::type<T>::Invoke(state, value)
0923 // Also, HashSelect::type<T>::value is a boolean equal to `true` if there is a
0924 // valid `Invoke` function. Types that are not hashable will have a ::value of
0925 // `false`.
0926 struct HashSelect {
0927  private:
0928   struct State : HashStateBase<State> {
0929     static State combine_contiguous(State hash_state, const unsigned char*,
0930                                     size_t);
0931     using State::HashStateBase::combine_contiguous;
0932   };
0933 
0934   struct UniquelyRepresentedProbe {
0935     template <typename H, typename T>
0936     static auto Invoke(H state, const T& value)
0937         -> absl::enable_if_t<is_uniquely_represented<T>::value, H> {
0938       return hash_internal::hash_bytes(std::move(state), value);
0939     }
0940   };
0941 
0942   struct HashValueProbe {
0943     template <typename H, typename T>
0944     static auto Invoke(H state, const T& value) -> absl::enable_if_t<
0945         std::is_same<H,
0946                      decltype(AbslHashValue(std::move(state), value))>::value,
0947         H> {
0948       return AbslHashValue(std::move(state), value);
0949     }
0950   };
0951 
0952   struct LegacyHashProbe {
0953 #if ABSL_HASH_INTERNAL_SUPPORT_LEGACY_HASH_
0954     template <typename H, typename T>
0955     static auto Invoke(H state, const T& value) -> absl::enable_if_t<
0956         std::is_convertible<
0957             decltype(ABSL_INTERNAL_LEGACY_HASH_NAMESPACE::hash<T>()(value)),
0958             size_t>::value,
0959         H> {
0960       return hash_internal::hash_bytes(
0961           std::move(state),
0962           ABSL_INTERNAL_LEGACY_HASH_NAMESPACE::hash<T>{}(value));
0963     }
0964 #endif  // ABSL_HASH_INTERNAL_SUPPORT_LEGACY_HASH_
0965   };
0966 
0967   struct StdHashProbe {
0968     template <typename H, typename T>
0969     static auto Invoke(H state, const T& value)
0970         -> absl::enable_if_t<type_traits_internal::IsHashable<T>::value, H> {
0971       return hash_internal::hash_bytes(std::move(state), std::hash<T>{}(value));
0972     }
0973   };
0974 
0975   template <typename Hash, typename T>
0976   struct Probe : Hash {
0977    private:
0978     template <typename H, typename = decltype(H::Invoke(
0979                               std::declval<State>(), std::declval<const T&>()))>
0980     static std::true_type Test(int);
0981     template <typename U>
0982     static std::false_type Test(char);
0983 
0984    public:
0985     static constexpr bool value = decltype(Test<Hash>(0))::value;
0986   };
0987 
0988  public:
0989   // Probe each implementation in order.
0990   // disjunction provides short circuiting wrt instantiation.
0991   template <typename T>
0992   using Apply = absl::disjunction<         //
0993       Probe<UniquelyRepresentedProbe, T>,  //
0994       Probe<HashValueProbe, T>,            //
0995       Probe<LegacyHashProbe, T>,           //
0996       Probe<StdHashProbe, T>,              //
0997       std::false_type>;
0998 };
0999 
1000 template <typename T>
1001 struct is_hashable
1002     : std::integral_constant<bool, HashSelect::template Apply<T>::value> {};
1003 
1004 // MixingHashState
1005 class ABSL_DLL MixingHashState : public HashStateBase<MixingHashState> {
1006   // absl::uint128 is not an alias or a thin wrapper around the intrinsic.
1007   // We use the intrinsic when available to improve performance.
1008 #ifdef ABSL_HAVE_INTRINSIC_INT128
1009   using uint128 = __uint128_t;
1010 #else   // ABSL_HAVE_INTRINSIC_INT128
1011   using uint128 = absl::uint128;
1012 #endif  // ABSL_HAVE_INTRINSIC_INT128
1013 
1014   static constexpr uint64_t kMul =
1015   sizeof(size_t) == 4 ? uint64_t{0xcc9e2d51}
1016                       : uint64_t{0x9ddfea08eb382d69};
1017 
1018   template <typename T>
1019   using IntegralFastPath =
1020       conjunction<std::is_integral<T>, is_uniquely_represented<T>>;
1021 
1022  public:
1023   // Move only
1024   MixingHashState(MixingHashState&&) = default;
1025   MixingHashState& operator=(MixingHashState&&) = default;
1026 
1027   // MixingHashState::combine_contiguous()
1028   //
1029   // Fundamental base case for hash recursion: mixes the given range of bytes
1030   // into the hash state.
1031   static MixingHashState combine_contiguous(MixingHashState hash_state,
1032                                             const unsigned char* first,
1033                                             size_t size) {
1034     return MixingHashState(
1035         CombineContiguousImpl(hash_state.state_, first, size,
1036                               std::integral_constant<int, sizeof(size_t)>{}));
1037   }
1038   using MixingHashState::HashStateBase::combine_contiguous;
1039 
1040   // MixingHashState::hash()
1041   //
1042   // For performance reasons in non-opt mode, we specialize this for
1043   // integral types.
1044   // Otherwise we would be instantiating and calling dozens of functions for
1045   // something that is just one multiplication and a couple xor's.
1046   // The result should be the same as running the whole algorithm, but faster.
1047   template <typename T, absl::enable_if_t<IntegralFastPath<T>::value, int> = 0>
1048   static size_t hash(T value) {
1049     return static_cast<size_t>(
1050         Mix(Seed(), static_cast<std::make_unsigned_t<T>>(value)));
1051   }
1052 
1053   // Overload of MixingHashState::hash()
1054   template <typename T, absl::enable_if_t<!IntegralFastPath<T>::value, int> = 0>
1055   static size_t hash(const T& value) {
1056     return static_cast<size_t>(combine(MixingHashState{}, value).state_);
1057   }
1058 
1059  private:
1060   // Invoked only once for a given argument; that plus the fact that this is
1061   // move-only ensures that there is only one non-moved-from object.
1062   MixingHashState() : state_(Seed()) {}
1063 
1064   friend class MixingHashState::HashStateBase;
1065 
1066   template <typename CombinerT>
1067   static MixingHashState RunCombineUnordered(MixingHashState state,
1068                                              CombinerT combiner) {
1069     uint64_t unordered_state = 0;
1070     combiner(MixingHashState{}, [&](MixingHashState& inner_state) {
1071       // Add the hash state of the element to the running total, but mix the
1072       // carry bit back into the low bit.  This in intended to avoid losing
1073       // entropy to overflow, especially when unordered_multisets contain
1074       // multiple copies of the same value.
1075       auto element_state = inner_state.state_;
1076       unordered_state += element_state;
1077       if (unordered_state < element_state) {
1078         ++unordered_state;
1079       }
1080       inner_state = MixingHashState{};
1081     });
1082     return MixingHashState::combine(std::move(state), unordered_state);
1083   }
1084 
1085   // Allow the HashState type-erasure implementation to invoke
1086   // RunCombinedUnordered() directly.
1087   friend class absl::HashState;
1088 
1089   // Workaround for MSVC bug.
1090   // We make the type copyable to fix the calling convention, even though we
1091   // never actually copy it. Keep it private to not affect the public API of the
1092   // type.
1093   MixingHashState(const MixingHashState&) = default;
1094 
1095   explicit MixingHashState(uint64_t state) : state_(state) {}
1096 
1097   // Implementation of the base case for combine_contiguous where we actually
1098   // mix the bytes into the state.
1099   // Dispatch to different implementations of the combine_contiguous depending
1100   // on the value of `sizeof(size_t)`.
1101   static uint64_t CombineContiguousImpl(uint64_t state,
1102                                         const unsigned char* first, size_t len,
1103                                         std::integral_constant<int, 4>
1104                                         /* sizeof_size_t */);
1105   static uint64_t CombineContiguousImpl(uint64_t state,
1106                                         const unsigned char* first, size_t len,
1107                                         std::integral_constant<int, 8>
1108                                         /* sizeof_size_t */);
1109 
1110   // Slow dispatch path for calls to CombineContiguousImpl with a size argument
1111   // larger than PiecewiseChunkSize().  Has the same effect as calling
1112   // CombineContiguousImpl() repeatedly with the chunk stride size.
1113   static uint64_t CombineLargeContiguousImpl32(uint64_t state,
1114                                                const unsigned char* first,
1115                                                size_t len);
1116   static uint64_t CombineLargeContiguousImpl64(uint64_t state,
1117                                                const unsigned char* first,
1118                                                size_t len);
1119 
1120   // Reads 9 to 16 bytes from p.
1121   // The least significant 8 bytes are in .first, the rest (zero padded) bytes
1122   // are in .second.
1123   static std::pair<uint64_t, uint64_t> Read9To16(const unsigned char* p,
1124                                                  size_t len) {
1125     uint64_t low_mem = absl::base_internal::UnalignedLoad64(p);
1126     uint64_t high_mem = absl::base_internal::UnalignedLoad64(p + len - 8);
1127 #ifdef ABSL_IS_LITTLE_ENDIAN
1128     uint64_t most_significant = high_mem;
1129     uint64_t least_significant = low_mem;
1130 #else
1131     uint64_t most_significant = low_mem;
1132     uint64_t least_significant = high_mem;
1133 #endif
1134     return {least_significant, most_significant};
1135   }
1136 
1137   // Reads 4 to 8 bytes from p. Zero pads to fill uint64_t.
1138   static uint64_t Read4To8(const unsigned char* p, size_t len) {
1139     uint32_t low_mem = absl::base_internal::UnalignedLoad32(p);
1140     uint32_t high_mem = absl::base_internal::UnalignedLoad32(p + len - 4);
1141 #ifdef ABSL_IS_LITTLE_ENDIAN
1142     uint32_t most_significant = high_mem;
1143     uint32_t least_significant = low_mem;
1144 #else
1145     uint32_t most_significant = low_mem;
1146     uint32_t least_significant = high_mem;
1147 #endif
1148     return (static_cast<uint64_t>(most_significant) << (len - 4) * 8) |
1149            least_significant;
1150   }
1151 
1152   // Reads 1 to 3 bytes from p. Zero pads to fill uint32_t.
1153   static uint32_t Read1To3(const unsigned char* p, size_t len) {
1154     // The trick used by this implementation is to avoid branches if possible.
1155     unsigned char mem0 = p[0];
1156     unsigned char mem1 = p[len / 2];
1157     unsigned char mem2 = p[len - 1];
1158 #ifdef ABSL_IS_LITTLE_ENDIAN
1159     unsigned char significant2 = mem2;
1160     unsigned char significant1 = mem1;
1161     unsigned char significant0 = mem0;
1162 #else
1163     unsigned char significant2 = mem0;
1164     unsigned char significant1 = len == 2 ? mem0 : mem1;
1165     unsigned char significant0 = mem2;
1166 #endif
1167     return static_cast<uint32_t>(significant0 |                     //
1168                                  (significant1 << (len / 2 * 8)) |  //
1169                                  (significant2 << ((len - 1) * 8)));
1170   }
1171 
1172   ABSL_ATTRIBUTE_ALWAYS_INLINE static uint64_t Mix(uint64_t state, uint64_t v) {
1173     // Though the 128-bit product on AArch64 needs two instructions, it is
1174     // still a good balance between speed and hash quality.
1175     using MultType =
1176         absl::conditional_t<sizeof(size_t) == 4, uint64_t, uint128>;
1177     // We do the addition in 64-bit space to make sure the 128-bit
1178     // multiplication is fast. If we were to do it as MultType the compiler has
1179     // to assume that the high word is non-zero and needs to perform 2
1180     // multiplications instead of one.
1181     MultType m = state + v;
1182     m *= kMul;
1183     return static_cast<uint64_t>(m ^ (m >> (sizeof(m) * 8 / 2)));
1184   }
1185 
1186   // An extern to avoid bloat on a direct call to LowLevelHash() with fixed
1187   // values for both the seed and salt parameters.
1188   static uint64_t LowLevelHashImpl(const unsigned char* data, size_t len);
1189 
1190   ABSL_ATTRIBUTE_ALWAYS_INLINE static uint64_t Hash64(const unsigned char* data,
1191                                                       size_t len) {
1192 #ifdef ABSL_HAVE_INTRINSIC_INT128
1193     return LowLevelHashImpl(data, len);
1194 #else
1195     return hash_internal::CityHash64(reinterpret_cast<const char*>(data), len);
1196 #endif
1197   }
1198 
1199   // Seed()
1200   //
1201   // A non-deterministic seed.
1202   //
1203   // The current purpose of this seed is to generate non-deterministic results
1204   // and prevent having users depend on the particular hash values.
1205   // It is not meant as a security feature right now, but it leaves the door
1206   // open to upgrade it to a true per-process random seed. A true random seed
1207   // costs more and we don't need to pay for that right now.
1208   //
1209   // On platforms with ASLR, we take advantage of it to make a per-process
1210   // random value.
1211   // See https://en.wikipedia.org/wiki/Address_space_layout_randomization
1212   //
1213   // On other platforms this is still going to be non-deterministic but most
1214   // probably per-build and not per-process.
1215   ABSL_ATTRIBUTE_ALWAYS_INLINE static uint64_t Seed() {
1216 #if (!defined(__clang__) || __clang_major__ > 11) && \
1217     (!defined(__apple_build_version__) ||            \
1218      __apple_build_version__ >= 19558921)  // Xcode 12
1219     return static_cast<uint64_t>(reinterpret_cast<uintptr_t>(&kSeed));
1220 #else
1221     // Workaround the absence of
1222     // https://github.com/llvm/llvm-project/commit/bc15bf66dcca76cc06fe71fca35b74dc4d521021.
1223     return static_cast<uint64_t>(reinterpret_cast<uintptr_t>(kSeed));
1224 #endif
1225   }
1226   static const void* const kSeed;
1227 
1228   uint64_t state_;
1229 };
1230 
1231 // MixingHashState::CombineContiguousImpl()
1232 inline uint64_t MixingHashState::CombineContiguousImpl(
1233     uint64_t state, const unsigned char* first, size_t len,
1234     std::integral_constant<int, 4> /* sizeof_size_t */) {
1235   // For large values we use CityHash, for small ones we just use a
1236   // multiplicative hash.
1237   uint64_t v;
1238   if (len > 8) {
1239     if (ABSL_PREDICT_FALSE(len > PiecewiseChunkSize())) {
1240       return CombineLargeContiguousImpl32(state, first, len);
1241     }
1242     v = hash_internal::CityHash32(reinterpret_cast<const char*>(first), len);
1243   } else if (len >= 4) {
1244     v = Read4To8(first, len);
1245   } else if (len > 0) {
1246     v = Read1To3(first, len);
1247   } else {
1248     // Empty ranges have no effect.
1249     return state;
1250   }
1251   return Mix(state, v);
1252 }
1253 
1254 // Overload of MixingHashState::CombineContiguousImpl()
1255 inline uint64_t MixingHashState::CombineContiguousImpl(
1256     uint64_t state, const unsigned char* first, size_t len,
1257     std::integral_constant<int, 8> /* sizeof_size_t */) {
1258   // For large values we use LowLevelHash or CityHash depending on the platform,
1259   // for small ones we just use a multiplicative hash.
1260   uint64_t v;
1261   if (len > 16) {
1262     if (ABSL_PREDICT_FALSE(len > PiecewiseChunkSize())) {
1263       return CombineLargeContiguousImpl64(state, first, len);
1264     }
1265     v = Hash64(first, len);
1266   } else if (len > 8) {
1267     // This hash function was constructed by the ML-driven algorithm discovery
1268     // using reinforcement learning. We fed the agent lots of inputs from
1269     // microbenchmarks, SMHasher, low hamming distance from generated inputs and
1270     // picked up the one that was good on micro and macrobenchmarks.
1271     auto p = Read9To16(first, len);
1272     uint64_t lo = p.first;
1273     uint64_t hi = p.second;
1274     // Rotation by 53 was found to be most often useful when discovering these
1275     // hashing algorithms with ML techniques.
1276     lo = absl::rotr(lo, 53);
1277     state += kMul;
1278     lo += state;
1279     state ^= hi;
1280     uint128 m = state;
1281     m *= lo;
1282     return static_cast<uint64_t>(m ^ (m >> 64));
1283   } else if (len >= 4) {
1284     v = Read4To8(first, len);
1285   } else if (len > 0) {
1286     v = Read1To3(first, len);
1287   } else {
1288     // Empty ranges have no effect.
1289     return state;
1290   }
1291   return Mix(state, v);
1292 }
1293 
1294 struct AggregateBarrier {};
1295 
1296 // HashImpl
1297 
1298 // Add a private base class to make sure this type is not an aggregate.
1299 // Aggregates can be aggregate initialized even if the default constructor is
1300 // deleted.
1301 struct PoisonedHash : private AggregateBarrier {
1302   PoisonedHash() = delete;
1303   PoisonedHash(const PoisonedHash&) = delete;
1304   PoisonedHash& operator=(const PoisonedHash&) = delete;
1305 };
1306 
1307 template <typename T>
1308 struct HashImpl {
1309   size_t operator()(const T& value) const {
1310     return MixingHashState::hash(value);
1311   }
1312 };
1313 
1314 template <typename T>
1315 struct Hash
1316     : absl::conditional_t<is_hashable<T>::value, HashImpl<T>, PoisonedHash> {};
1317 
1318 template <typename H>
1319 template <typename T, typename... Ts>
1320 H HashStateBase<H>::combine(H state, const T& value, const Ts&... values) {
1321   return H::combine(hash_internal::HashSelect::template Apply<T>::Invoke(
1322                         std::move(state), value),
1323                     values...);
1324 }
1325 
1326 // HashStateBase::combine_contiguous()
1327 template <typename H>
1328 template <typename T>
1329 H HashStateBase<H>::combine_contiguous(H state, const T* data, size_t size) {
1330   return hash_internal::hash_range_or_bytes(std::move(state), data, size);
1331 }
1332 
1333 // HashStateBase::combine_unordered()
1334 template <typename H>
1335 template <typename I>
1336 H HashStateBase<H>::combine_unordered(H state, I begin, I end) {
1337   return H::RunCombineUnordered(std::move(state),
1338                                 CombineUnorderedCallback<I>{begin, end});
1339 }
1340 
1341 // HashStateBase::PiecewiseCombiner::add_buffer()
1342 template <typename H>
1343 H PiecewiseCombiner::add_buffer(H state, const unsigned char* data,
1344                                 size_t size) {
1345   if (position_ + size < PiecewiseChunkSize()) {
1346     // This partial chunk does not fill our existing buffer
1347     memcpy(buf_ + position_, data, size);
1348     position_ += size;
1349     return state;
1350   }
1351 
1352   // If the buffer is partially filled we need to complete the buffer
1353   // and hash it.
1354   if (position_ != 0) {
1355     const size_t bytes_needed = PiecewiseChunkSize() - position_;
1356     memcpy(buf_ + position_, data, bytes_needed);
1357     state = H::combine_contiguous(std::move(state), buf_, PiecewiseChunkSize());
1358     data += bytes_needed;
1359     size -= bytes_needed;
1360   }
1361 
1362   // Hash whatever chunks we can without copying
1363   while (size >= PiecewiseChunkSize()) {
1364     state = H::combine_contiguous(std::move(state), data, PiecewiseChunkSize());
1365     data += PiecewiseChunkSize();
1366     size -= PiecewiseChunkSize();
1367   }
1368   // Fill the buffer with the remainder
1369   memcpy(buf_, data, size);
1370   position_ = size;
1371   return state;
1372 }
1373 
1374 // HashStateBase::PiecewiseCombiner::finalize()
1375 template <typename H>
1376 H PiecewiseCombiner::finalize(H state) {
1377   // Hash the remainder left in the buffer, which may be empty
1378   return H::combine_contiguous(std::move(state), buf_, position_);
1379 }
1380 
1381 }  // namespace hash_internal
1382 ABSL_NAMESPACE_END
1383 }  // namespace absl
1384 
1385 #endif  // ABSL_HASH_INTERNAL_HASH_H_