xref: /aosp_15_r20/external/angle/third_party/abseil-cpp/absl/hash/hash_test.cc (revision 8975f5c5ed3d1c378011245431ada316dfb6f244)
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 #include "absl/hash/hash.h"
16 
17 #include <algorithm>
18 #include <array>
19 #include <bitset>
20 #include <cstddef>
21 #include <cstdint>
22 #include <cstdlib>
23 #include <cstring>
24 #include <functional>
25 #include <initializer_list>
26 #include <ios>
27 #include <limits>
28 #include <memory>
29 #include <ostream>
30 #include <set>
31 #include <string>
32 #include <tuple>
33 #include <type_traits>
34 #include <unordered_map>
35 #include <utility>
36 #include <vector>
37 
38 #include "gmock/gmock.h"
39 #include "gtest/gtest.h"
40 #include "absl/base/config.h"
41 #include "absl/container/flat_hash_set.h"
42 #include "absl/hash/hash_testing.h"
43 #include "absl/hash/internal/hash_test.h"
44 #include "absl/hash/internal/spy_hash_state.h"
45 #include "absl/memory/memory.h"
46 #include "absl/meta/type_traits.h"
47 #include "absl/strings/cord_test_helpers.h"
48 #include "absl/strings/string_view.h"
49 #include "absl/types/optional.h"
50 #include "absl/types/variant.h"
51 
52 #ifdef ABSL_INTERNAL_STD_FILESYSTEM_PATH_HASH_AVAILABLE
53 #include <filesystem>  // NOLINT
54 #endif
55 
56 #ifdef ABSL_HAVE_STD_STRING_VIEW
57 #include <string_view>
58 #endif
59 
60 namespace {
61 
62 using ::absl::hash_test_internal::is_hashable;
63 using ::absl::hash_test_internal::TypeErasedContainer;
64 using ::absl::hash_test_internal::TypeErasedValue;
65 using ::testing::SizeIs;
66 
67 template <typename T>
68 using TypeErasedVector = TypeErasedContainer<std::vector<T>>;
69 
70 using absl::Hash;
71 using absl::hash_internal::SpyHashState;
72 
73 template <typename T>
74 class HashValueIntTest : public testing::Test {
75 };
76 TYPED_TEST_SUITE_P(HashValueIntTest);
77 
78 template <typename T>
SpyHash(const T & value)79 SpyHashState SpyHash(const T& value) {
80   return SpyHashState::combine(SpyHashState(), value);
81 }
82 
TYPED_TEST_P(HashValueIntTest,BasicUsage)83 TYPED_TEST_P(HashValueIntTest, BasicUsage) {
84   EXPECT_TRUE((is_hashable<TypeParam>::value));
85 
86   TypeParam n = 42;
87   EXPECT_EQ(SpyHash(n), SpyHash(TypeParam{42}));
88   EXPECT_NE(SpyHash(n), SpyHash(TypeParam{0}));
89   EXPECT_NE(SpyHash(std::numeric_limits<TypeParam>::max()),
90             SpyHash(std::numeric_limits<TypeParam>::min()));
91 }
92 
TYPED_TEST_P(HashValueIntTest,FastPath)93 TYPED_TEST_P(HashValueIntTest, FastPath) {
94   // Test the fast-path to make sure the values are the same.
95   TypeParam n = 42;
96   EXPECT_EQ(absl::Hash<TypeParam>{}(n),
97             absl::Hash<std::tuple<TypeParam>>{}(std::tuple<TypeParam>(n)));
98 }
99 
100 REGISTER_TYPED_TEST_SUITE_P(HashValueIntTest, BasicUsage, FastPath);
101 using IntTypes = testing::Types<unsigned char, char, int, int32_t, int64_t,
102                                 uint32_t, uint64_t, size_t>;
103 INSTANTIATE_TYPED_TEST_SUITE_P(My, HashValueIntTest, IntTypes);
104 
105 enum LegacyEnum { kValue1, kValue2, kValue3 };
106 
107 enum class EnumClass { kValue4, kValue5, kValue6 };
108 
TEST(HashValueTest,EnumAndBool)109 TEST(HashValueTest, EnumAndBool) {
110   EXPECT_TRUE((is_hashable<LegacyEnum>::value));
111   EXPECT_TRUE((is_hashable<EnumClass>::value));
112   EXPECT_TRUE((is_hashable<bool>::value));
113 
114   EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple(
115       LegacyEnum::kValue1, LegacyEnum::kValue2, LegacyEnum::kValue3)));
116   EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple(
117       EnumClass::kValue4, EnumClass::kValue5, EnumClass::kValue6)));
118   EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(
119       std::make_tuple(true, false)));
120 }
121 
TEST(HashValueTest,FloatingPoint)122 TEST(HashValueTest, FloatingPoint) {
123   EXPECT_TRUE((is_hashable<float>::value));
124   EXPECT_TRUE((is_hashable<double>::value));
125   EXPECT_TRUE((is_hashable<long double>::value));
126 
127   EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(
128       std::make_tuple(42.f, 0.f, -0.f, std::numeric_limits<float>::infinity(),
129                       -std::numeric_limits<float>::infinity())));
130 
131   EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(
132       std::make_tuple(42., 0., -0., std::numeric_limits<double>::infinity(),
133                       -std::numeric_limits<double>::infinity())));
134 
135   EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple(
136       // Add some values with small exponent to test that NORMAL values also
137       // append their category.
138       .5L, 1.L, 2.L, 4.L, 42.L, 0.L, -0.L,
139       17 * static_cast<long double>(std::numeric_limits<double>::max()),
140       std::numeric_limits<long double>::infinity(),
141       -std::numeric_limits<long double>::infinity())));
142 }
143 
TEST(HashValueTest,Pointer)144 TEST(HashValueTest, Pointer) {
145   EXPECT_TRUE((is_hashable<int*>::value));
146   EXPECT_TRUE((is_hashable<int(*)(char, float)>::value));
147   EXPECT_TRUE((is_hashable<void(*)(int, int, ...)>::value));
148 
149   int i;
150   int* ptr = &i;
151   int* n = nullptr;
152 
153   EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(
154       std::make_tuple(&i, ptr, nullptr, ptr + 1, n)));
155 }
156 
TEST(HashValueTest,PointerAlignment)157 TEST(HashValueTest, PointerAlignment) {
158   // We want to make sure that pointer alignment will not cause bits to be
159   // stuck.
160 
161   constexpr size_t kTotalSize = 1 << 20;
162   std::unique_ptr<char[]> data(new char[kTotalSize]);
163   constexpr size_t kLog2NumValues = 5;
164   constexpr size_t kNumValues = 1 << kLog2NumValues;
165 
166   for (size_t align = 1; align < kTotalSize / kNumValues;
167        align < 8 ? align += 1 : align < 1024 ? align += 8 : align += 32) {
168     SCOPED_TRACE(align);
169     ASSERT_LE(align * kNumValues, kTotalSize);
170 
171     size_t bits_or = 0;
172     size_t bits_and = ~size_t{};
173 
174     for (size_t i = 0; i < kNumValues; ++i) {
175       size_t hash = absl::Hash<void*>()(data.get() + i * align);
176       bits_or |= hash;
177       bits_and &= hash;
178     }
179 
180     // Limit the scope to the bits we would be using for Swisstable.
181     constexpr size_t kMask = (1 << (kLog2NumValues + 7)) - 1;
182     size_t stuck_bits = (~bits_or | bits_and) & kMask;
183     EXPECT_EQ(stuck_bits, 0u) << "0x" << std::hex << stuck_bits;
184   }
185 }
186 
TEST(HashValueTest,PointerToMember)187 TEST(HashValueTest, PointerToMember) {
188   struct Bass {
189     void q() {}
190   };
191 
192   struct A : Bass {
193     virtual ~A() = default;
194     virtual void vfa() {}
195 
196     static auto pq() -> void (A::*)() { return &A::q; }
197   };
198 
199   struct B : Bass {
200     virtual ~B() = default;
201     virtual void vfb() {}
202 
203     static auto pq() -> void (B::*)() { return &B::q; }
204   };
205 
206   struct Foo : A, B {
207     void f1() {}
208     void f2() const {}
209 
210     int g1() & { return 0; }
211     int g2() const & { return 0; }
212     int g3() && { return 0; }
213     int g4() const && { return 0; }
214 
215     int h1() & { return 0; }
216     int h2() const & { return 0; }
217     int h3() && { return 0; }
218     int h4() const && { return 0; }
219 
220     int a;
221     int b;
222 
223     const int c = 11;
224     const int d = 22;
225   };
226 
227   EXPECT_TRUE((is_hashable<float Foo::*>::value));
228   EXPECT_TRUE((is_hashable<double (Foo::*)(int, int)&&>::value));
229 
230   EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(
231       std::make_tuple(&Foo::a, &Foo::b, static_cast<int Foo::*>(nullptr))));
232 
233   EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(
234       std::make_tuple(&Foo::c, &Foo::d, static_cast<const int Foo::*>(nullptr),
235                       &Foo::a, &Foo::b)));
236 
237   EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple(
238       &Foo::f1, static_cast<void (Foo::*)()>(nullptr))));
239 
240   EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple(
241       &Foo::f2, static_cast<void (Foo::*)() const>(nullptr))));
242 
243   EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple(
244       &Foo::g1, &Foo::h1, static_cast<int (Foo::*)() &>(nullptr))));
245 
246   EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple(
247       &Foo::g2, &Foo::h2, static_cast<int (Foo::*)() const &>(nullptr))));
248 
249   EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple(
250       &Foo::g3, &Foo::h3, static_cast<int (Foo::*)() &&>(nullptr))));
251 
252   EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple(
253       &Foo::g4, &Foo::h4, static_cast<int (Foo::*)() const &&>(nullptr))));
254 
255   EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(
256       std::make_tuple(static_cast<void (Foo::*)()>(&Foo::vfa),
257                       static_cast<void (Foo::*)()>(&Foo::vfb),
258                       static_cast<void (Foo::*)()>(nullptr))));
259 
260   EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(
261       std::make_tuple(static_cast<void (Foo::*)()>(Foo::A::pq()),
262                       static_cast<void (Foo::*)()>(Foo::B::pq()),
263                       static_cast<void (Foo::*)()>(nullptr))));
264 }
265 
TEST(HashValueTest,PairAndTuple)266 TEST(HashValueTest, PairAndTuple) {
267   EXPECT_TRUE((is_hashable<std::pair<int, int>>::value));
268   EXPECT_TRUE((is_hashable<std::pair<const int&, const int&>>::value));
269   EXPECT_TRUE((is_hashable<std::tuple<int&, int&>>::value));
270   EXPECT_TRUE((is_hashable<std::tuple<int&&, int&&>>::value));
271 
272   EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple(
273       std::make_pair(0, 42), std::make_pair(0, 42), std::make_pair(42, 0),
274       std::make_pair(0, 0), std::make_pair(42, 42), std::make_pair(1, 42))));
275 
276   EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(
277       std::make_tuple(std::make_tuple(0, 0, 0), std::make_tuple(0, 0, 42),
278                       std::make_tuple(0, 23, 0), std::make_tuple(17, 0, 0),
279                       std::make_tuple(42, 0, 0), std::make_tuple(3, 9, 9),
280                       std::make_tuple(0, 0, -42))));
281 
282   // Test that tuples of lvalue references work (so we need a few lvalues):
283   int a = 0, b = 1, c = 17, d = 23;
284   EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple(
285       std::tie(a, a), std::tie(a, b), std::tie(b, c), std::tie(c, d))));
286 
287   // Test that tuples of rvalue references work:
288   EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple(
289       std::forward_as_tuple(0, 0, 0), std::forward_as_tuple(0, 0, 42),
290       std::forward_as_tuple(0, 23, 0), std::forward_as_tuple(17, 0, 0),
291       std::forward_as_tuple(42, 0, 0), std::forward_as_tuple(3, 9, 9),
292       std::forward_as_tuple(0, 0, -42))));
293 }
294 
TEST(HashValueTest,CombineContiguousWorks)295 TEST(HashValueTest, CombineContiguousWorks) {
296   std::vector<std::tuple<int>> v1 = {std::make_tuple(1), std::make_tuple(3)};
297   std::vector<std::tuple<int>> v2 = {std::make_tuple(1), std::make_tuple(2)};
298 
299   auto vh1 = SpyHash(v1);
300   auto vh2 = SpyHash(v2);
301   EXPECT_NE(vh1, vh2);
302 }
303 
304 struct DummyDeleter {
305   template <typename T>
operator ()__anoncc6345600111::DummyDeleter306   void operator() (T* ptr) {}
307 };
308 
309 struct SmartPointerEq {
310   template <typename T, typename U>
operator ()__anoncc6345600111::SmartPointerEq311   bool operator()(const T& t, const U& u) const {
312     return GetPtr(t) == GetPtr(u);
313   }
314 
315   template <typename T>
GetPtr__anoncc6345600111::SmartPointerEq316   static auto GetPtr(const T& t) -> decltype(&*t) {
317     return t ? &*t : nullptr;
318   }
319 
GetPtr__anoncc6345600111::SmartPointerEq320   static std::nullptr_t GetPtr(std::nullptr_t) { return nullptr; }
321 };
322 
TEST(HashValueTest,SmartPointers)323 TEST(HashValueTest, SmartPointers) {
324   EXPECT_TRUE((is_hashable<std::unique_ptr<int>>::value));
325   EXPECT_TRUE((is_hashable<std::unique_ptr<int, DummyDeleter>>::value));
326   EXPECT_TRUE((is_hashable<std::shared_ptr<int>>::value));
327 
328   int i, j;
329   std::unique_ptr<int, DummyDeleter> unique1(&i);
330   std::unique_ptr<int, DummyDeleter> unique2(&i);
331   std::unique_ptr<int, DummyDeleter> unique_other(&j);
332   std::unique_ptr<int, DummyDeleter> unique_null;
333 
334   std::shared_ptr<int> shared1(&i, DummyDeleter());
335   std::shared_ptr<int> shared2(&i, DummyDeleter());
336   std::shared_ptr<int> shared_other(&j, DummyDeleter());
337   std::shared_ptr<int> shared_null;
338 
339   // Sanity check of the Eq function.
340   ASSERT_TRUE(SmartPointerEq{}(unique1, shared1));
341   ASSERT_FALSE(SmartPointerEq{}(unique1, shared_other));
342   ASSERT_TRUE(SmartPointerEq{}(unique_null, nullptr));
343   ASSERT_FALSE(SmartPointerEq{}(shared2, nullptr));
344 
345   EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(
346       std::forward_as_tuple(&i, nullptr,                    //
347                             unique1, unique2, unique_null,  //
348                             absl::make_unique<int>(),       //
349                             shared1, shared2, shared_null,  //
350                             std::make_shared<int>()),
351       SmartPointerEq{}));
352 }
353 
TEST(HashValueTest,FunctionPointer)354 TEST(HashValueTest, FunctionPointer) {
355   using Func = int (*)();
356   EXPECT_TRUE(is_hashable<Func>::value);
357 
358   Func p1 = [] { return 2; }, p2 = [] { return 1; };
359   EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(
360       std::make_tuple(p1, p2, nullptr)));
361 }
362 
363 struct WrapInTuple {
364   template <typename T>
operator ()__anoncc6345600111::WrapInTuple365   std::tuple<int, T, size_t> operator()(const T& t) const {
366     return std::make_tuple(7, t, 0xdeadbeef);
367   }
368 };
369 
FlatCord(absl::string_view sv)370 absl::Cord FlatCord(absl::string_view sv) {
371   absl::Cord c(sv);
372   c.Flatten();
373   return c;
374 }
375 
FragmentedCord(absl::string_view sv)376 absl::Cord FragmentedCord(absl::string_view sv) {
377   if (sv.size() < 2) {
378     return absl::Cord(sv);
379   }
380   size_t halfway = sv.size() / 2;
381   std::vector<absl::string_view> parts = {sv.substr(0, halfway),
382                                           sv.substr(halfway)};
383   return absl::MakeFragmentedCord(parts);
384 }
385 
386 #if ABSL_HAVE_INTRINSIC_INT128
TEST(HashValueTest,TestIntrinsicInt128)387 TEST(HashValueTest, TestIntrinsicInt128) {
388   EXPECT_TRUE((is_hashable<__int128_t>::value));
389   EXPECT_TRUE((is_hashable<__uint128_t>::value));
390 
391   absl::flat_hash_set<size_t> hashes;
392   std::vector<__uint128_t> values;
393   for (int i = 0; i < 128; ++i) {
394     // Some arbitrary pattern to check if changing each bit changes the hash.
395     static constexpr __uint128_t kPattern =
396         __uint128_t{0x0123456789abcdef} |
397         (__uint128_t{0x0123456789abcdef} << 64);
398     const __uint128_t value = kPattern ^ (__uint128_t{1} << i);
399     const __int128_t as_signed = static_cast<__int128_t>(value);
400 
401     values.push_back(value);
402     hashes.insert(absl::Hash<__uint128_t>{}(value));
403 
404     // Verify that the fast-path for MixingHashState does not break the hash.
405     EXPECT_EQ(absl::HashOf(value), absl::Hash<__uint128_t>{}(value));
406     EXPECT_EQ(absl::HashOf(as_signed), absl::Hash<__int128_t>{}(as_signed));
407   }
408   EXPECT_THAT(hashes, SizeIs(128));
409 
410   EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(values));
411   EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(
412       std::vector<__int128_t>(values.begin(), values.end())));
413 }
414 #endif  // ABSL_HAVE_INTRINSIC_INT128
415 
TEST(HashValueTest,Strings)416 TEST(HashValueTest, Strings) {
417   EXPECT_TRUE((is_hashable<std::string>::value));
418 
419   const std::string small = "foo";
420   const std::string dup = "foofoo";
421   const std::string large = std::string(2048, 'x');  // multiple of chunk size
422   const std::string huge = std::string(5000, 'a');   // not a multiple
423 
424   EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple(  //
425       std::string(), absl::string_view(), absl::Cord(),                     //
426       std::string(""), absl::string_view(""), absl::Cord(""),               //
427       std::string(small), absl::string_view(small), absl::Cord(small),      //
428       std::string(dup), absl::string_view(dup), absl::Cord(dup),            //
429       std::string(large), absl::string_view(large), absl::Cord(large),      //
430       std::string(huge), absl::string_view(huge), FlatCord(huge),           //
431       FragmentedCord(huge))));
432 
433   // Also check that nested types maintain the same hash.
434   const WrapInTuple t{};
435   EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple(  //
436       t(std::string()), t(absl::string_view()), t(absl::Cord()),            //
437       t(std::string("")), t(absl::string_view("")), t(absl::Cord("")),      //
438       t(std::string(small)), t(absl::string_view(small)),                   //
439           t(absl::Cord(small)),                                             //
440       t(std::string(dup)), t(absl::string_view(dup)), t(absl::Cord(dup)),   //
441       t(std::string(large)), t(absl::string_view(large)),                   //
442           t(absl::Cord(large)),                                             //
443       t(std::string(huge)), t(absl::string_view(huge)),                     //
444           t(FlatCord(huge)), t(FragmentedCord(huge)))));
445 
446   // Make sure that hashing a `const char*` does not use its string-value.
447   EXPECT_NE(SpyHash(static_cast<const char*>("ABC")),
448             SpyHash(absl::string_view("ABC")));
449 }
450 
TEST(HashValueTest,WString)451 TEST(HashValueTest, WString) {
452   EXPECT_TRUE((is_hashable<std::wstring>::value));
453 
454   EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple(
455       std::wstring(), std::wstring(L"ABC"), std::wstring(L"ABC"),
456       std::wstring(L"Some other different string"),
457       std::wstring(L"Iñtërnâtiônàlizætiøn"))));
458 }
459 
TEST(HashValueTest,U16String)460 TEST(HashValueTest, U16String) {
461   EXPECT_TRUE((is_hashable<std::u16string>::value));
462 
463   EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple(
464       std::u16string(), std::u16string(u"ABC"), std::u16string(u"ABC"),
465       std::u16string(u"Some other different string"),
466       std::u16string(u"Iñtërnâtiônàlizætiøn"))));
467 }
468 
TEST(HashValueTest,U32String)469 TEST(HashValueTest, U32String) {
470   EXPECT_TRUE((is_hashable<std::u32string>::value));
471 
472   EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple(
473       std::u32string(), std::u32string(U"ABC"), std::u32string(U"ABC"),
474       std::u32string(U"Some other different string"),
475       std::u32string(U"Iñtërnâtiônàlizætiøn"))));
476 }
477 
TEST(HashValueTest,WStringView)478 TEST(HashValueTest, WStringView) {
479 #ifndef ABSL_HAVE_STD_STRING_VIEW
480   GTEST_SKIP();
481 #else
482   EXPECT_TRUE((is_hashable<std::wstring_view>::value));
483 
484   EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple(
485       std::wstring_view(), std::wstring_view(L"ABC"), std::wstring_view(L"ABC"),
486       std::wstring_view(L"Some other different string_view"),
487       std::wstring_view(L"Iñtërnâtiônàlizætiøn"))));
488 #endif
489 }
490 
TEST(HashValueTest,U16StringView)491 TEST(HashValueTest, U16StringView) {
492 #ifndef ABSL_HAVE_STD_STRING_VIEW
493   GTEST_SKIP();
494 #else
495   EXPECT_TRUE((is_hashable<std::u16string_view>::value));
496 
497   EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(
498       std::make_tuple(std::u16string_view(), std::u16string_view(u"ABC"),
499                       std::u16string_view(u"ABC"),
500                       std::u16string_view(u"Some other different string_view"),
501                       std::u16string_view(u"Iñtërnâtiônàlizætiøn"))));
502 #endif
503 }
504 
TEST(HashValueTest,U32StringView)505 TEST(HashValueTest, U32StringView) {
506 #ifndef ABSL_HAVE_STD_STRING_VIEW
507   GTEST_SKIP();
508 #else
509   EXPECT_TRUE((is_hashable<std::u32string_view>::value));
510 
511   EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(
512       std::make_tuple(std::u32string_view(), std::u32string_view(U"ABC"),
513                       std::u32string_view(U"ABC"),
514                       std::u32string_view(U"Some other different string_view"),
515                       std::u32string_view(U"Iñtërnâtiônàlizætiøn"))));
516 #endif
517 }
518 
TEST(HashValueTest,StdFilesystemPath)519 TEST(HashValueTest, StdFilesystemPath) {
520 #ifndef ABSL_INTERNAL_STD_FILESYSTEM_PATH_HASH_AVAILABLE
521   GTEST_SKIP() << "std::filesystem::path is unavailable on this platform";
522 #else
523   EXPECT_TRUE((is_hashable<std::filesystem::path>::value));
524 
525   // clang-format off
526   const auto kTestCases = std::make_tuple(
527       std::filesystem::path(),
528       std::filesystem::path("/"),
529 #ifndef __GLIBCXX__
530       // libstdc++ has a known issue normalizing "//".
531       // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=106452
532       std::filesystem::path("//"),
533 #endif
534       std::filesystem::path("/a/b"),
535       std::filesystem::path("/a//b"),
536       std::filesystem::path("a/b"),
537       std::filesystem::path("a/b/"),
538       std::filesystem::path("a//b"),
539       std::filesystem::path("a//b/"),
540       std::filesystem::path("c:/"),
541       std::filesystem::path("c:\\"),
542       std::filesystem::path("c:\\/"),
543       std::filesystem::path("c:\\//"),
544       std::filesystem::path("c://"),
545       std::filesystem::path("c://\\"),
546       std::filesystem::path("/e/p"),
547       std::filesystem::path("/s/../e/p"),
548       std::filesystem::path("e/p"),
549       std::filesystem::path("s/../e/p"));
550   // clang-format on
551 
552   EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(kTestCases));
553 #endif
554 }
555 
TEST(HashValueTest,StdArray)556 TEST(HashValueTest, StdArray) {
557   EXPECT_TRUE((is_hashable<std::array<int, 3>>::value));
558 
559   EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(
560       std::make_tuple(std::array<int, 3>{}, std::array<int, 3>{{0, 23, 42}})));
561 }
562 
TEST(HashValueTest,StdBitset)563 TEST(HashValueTest, StdBitset) {
564   EXPECT_TRUE((is_hashable<std::bitset<257>>::value));
565 
566   EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(
567       {std::bitset<2>("00"), std::bitset<2>("01"), std::bitset<2>("10"),
568        std::bitset<2>("11")}));
569   EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(
570       {std::bitset<5>("10101"), std::bitset<5>("10001"), std::bitset<5>()}));
571 
572   constexpr int kNumBits = 256;
573   std::array<std::string, 6> bit_strings;
574   bit_strings.fill(std::string(kNumBits, '1'));
575   bit_strings[1][0] = '0';
576   bit_strings[2][1] = '0';
577   bit_strings[3][kNumBits / 3] = '0';
578   bit_strings[4][kNumBits - 2] = '0';
579   bit_strings[5][kNumBits - 1] = '0';
580   EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(
581       {std::bitset<kNumBits>(bit_strings[0].c_str()),
582        std::bitset<kNumBits>(bit_strings[1].c_str()),
583        std::bitset<kNumBits>(bit_strings[2].c_str()),
584        std::bitset<kNumBits>(bit_strings[3].c_str()),
585        std::bitset<kNumBits>(bit_strings[4].c_str()),
586        std::bitset<kNumBits>(bit_strings[5].c_str())}));
587 }  // namespace
588 
589 // Private type that only supports AbslHashValue to make sure our chosen hash
590 // implementation is recursive within absl::Hash.
591 // It uses std::abs() on the value to provide different bitwise representations
592 // of the same logical value.
593 struct Private {
594   int i;
595   template <typename H>
AbslHashValue(H h,Private p)596   friend H AbslHashValue(H h, Private p) {
597     return H::combine(std::move(h), std::abs(p.i));
598   }
599 
operator ==(Private a,Private b)600   friend bool operator==(Private a, Private b) {
601     return std::abs(a.i) == std::abs(b.i);
602   }
603 
operator <<(std::ostream & o,Private p)604   friend std::ostream& operator<<(std::ostream& o, Private p) {
605     return o << p.i;
606   }
607 };
608 
609 // Test helper for combine_piecewise_buffer.  It holds a string_view to the
610 // buffer-to-be-hashed.  Its AbslHashValue specialization will split up its
611 // contents at the character offsets requested.
612 class PiecewiseHashTester {
613  public:
614   // Create a hash view of a buffer to be hashed contiguously.
PiecewiseHashTester(absl::string_view buf)615   explicit PiecewiseHashTester(absl::string_view buf)
616       : buf_(buf), piecewise_(false), split_locations_() {}
617 
618   // Create a hash view of a buffer to be hashed piecewise, with breaks at the
619   // given locations.
PiecewiseHashTester(absl::string_view buf,std::set<size_t> split_locations)620   PiecewiseHashTester(absl::string_view buf, std::set<size_t> split_locations)
621       : buf_(buf),
622         piecewise_(true),
623         split_locations_(std::move(split_locations)) {}
624 
625   template <typename H>
AbslHashValue(H h,const PiecewiseHashTester & p)626   friend H AbslHashValue(H h, const PiecewiseHashTester& p) {
627     if (!p.piecewise_) {
628       return H::combine_contiguous(std::move(h), p.buf_.data(), p.buf_.size());
629     }
630     absl::hash_internal::PiecewiseCombiner combiner;
631     if (p.split_locations_.empty()) {
632       h = combiner.add_buffer(std::move(h), p.buf_.data(), p.buf_.size());
633       return combiner.finalize(std::move(h));
634     }
635     size_t begin = 0;
636     for (size_t next : p.split_locations_) {
637       absl::string_view chunk = p.buf_.substr(begin, next - begin);
638       h = combiner.add_buffer(std::move(h), chunk.data(), chunk.size());
639       begin = next;
640     }
641     absl::string_view last_chunk = p.buf_.substr(begin);
642     if (!last_chunk.empty()) {
643       h = combiner.add_buffer(std::move(h), last_chunk.data(),
644                               last_chunk.size());
645     }
646     return combiner.finalize(std::move(h));
647   }
648 
649  private:
650   absl::string_view buf_;
651   bool piecewise_;
652   std::set<size_t> split_locations_;
653 };
654 
655 // Dummy object that hashes as two distinct contiguous buffers, "foo" followed
656 // by "bar"
657 struct DummyFooBar {
658   template <typename H>
AbslHashValue(H h,const DummyFooBar &)659   friend H AbslHashValue(H h, const DummyFooBar&) {
660     const char* foo = "foo";
661     const char* bar = "bar";
662     h = H::combine_contiguous(std::move(h), foo, 3);
663     h = H::combine_contiguous(std::move(h), bar, 3);
664     return h;
665   }
666 };
667 
TEST(HashValueTest,CombinePiecewiseBuffer)668 TEST(HashValueTest, CombinePiecewiseBuffer) {
669   absl::Hash<PiecewiseHashTester> hash;
670 
671   // Check that hashing an empty buffer through the piecewise API works.
672   EXPECT_EQ(hash(PiecewiseHashTester("")), hash(PiecewiseHashTester("", {})));
673 
674   // Similarly, small buffers should give consistent results
675   EXPECT_EQ(hash(PiecewiseHashTester("foobar")),
676             hash(PiecewiseHashTester("foobar", {})));
677   EXPECT_EQ(hash(PiecewiseHashTester("foobar")),
678             hash(PiecewiseHashTester("foobar", {3})));
679 
680   // But hashing "foobar" in pieces gives a different answer than hashing "foo"
681   // contiguously, then "bar" contiguously.
682   EXPECT_NE(hash(PiecewiseHashTester("foobar", {3})),
683             absl::Hash<DummyFooBar>()(DummyFooBar{}));
684 
685   // Test hashing a large buffer incrementally, broken up in several different
686   // ways.  Arrange for breaks on and near the stride boundaries to look for
687   // off-by-one errors in the implementation.
688   //
689   // This test is run on a buffer that is a multiple of the stride size, and one
690   // that isn't.
691   for (size_t big_buffer_size : {1024u * 2 + 512u, 1024u * 3}) {
692     SCOPED_TRACE(big_buffer_size);
693     std::string big_buffer;
694     for (size_t i = 0; i < big_buffer_size; ++i) {
695       // Arbitrary string
696       big_buffer.push_back(32 + (i * (i / 3)) % 64);
697     }
698     auto big_buffer_hash = hash(PiecewiseHashTester(big_buffer));
699 
700     const int possible_breaks = 9;
701     size_t breaks[possible_breaks] = {1,    512,  1023, 1024, 1025,
702                                       1536, 2047, 2048, 2049};
703     for (unsigned test_mask = 0; test_mask < (1u << possible_breaks);
704          ++test_mask) {
705       SCOPED_TRACE(test_mask);
706       std::set<size_t> break_locations;
707       for (int j = 0; j < possible_breaks; ++j) {
708         if (test_mask & (1u << j)) {
709           break_locations.insert(breaks[j]);
710         }
711       }
712       EXPECT_EQ(
713           hash(PiecewiseHashTester(big_buffer, std::move(break_locations))),
714           big_buffer_hash);
715     }
716   }
717 }
718 
TEST(HashValueTest,PrivateSanity)719 TEST(HashValueTest, PrivateSanity) {
720   // Sanity check that Private is working as the tests below expect it to work.
721   EXPECT_TRUE(is_hashable<Private>::value);
722   EXPECT_NE(SpyHash(Private{0}), SpyHash(Private{1}));
723   EXPECT_EQ(SpyHash(Private{1}), SpyHash(Private{1}));
724 }
725 
TEST(HashValueTest,Optional)726 TEST(HashValueTest, Optional) {
727   EXPECT_TRUE(is_hashable<absl::optional<Private>>::value);
728 
729   using O = absl::optional<Private>;
730   EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(
731       std::make_tuple(O{}, O{{1}}, O{{-1}}, O{{10}})));
732 }
733 
TEST(HashValueTest,Variant)734 TEST(HashValueTest, Variant) {
735   using V = absl::variant<Private, std::string>;
736   EXPECT_TRUE(is_hashable<V>::value);
737 
738   EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple(
739       V(Private{1}), V(Private{-1}), V(Private{2}), V("ABC"), V("BCD"))));
740 
741 #if ABSL_META_INTERNAL_STD_HASH_SFINAE_FRIENDLY_
742   struct S {};
743   EXPECT_FALSE(is_hashable<absl::variant<S>>::value);
744 #endif
745 }
746 
TEST(HashValueTest,ReferenceWrapper)747 TEST(HashValueTest, ReferenceWrapper) {
748   EXPECT_TRUE(is_hashable<std::reference_wrapper<Private>>::value);
749 
750   Private p1{1}, p10{10};
751   EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple(
752       p1, p10, std::ref(p1), std::ref(p10), std::cref(p1), std::cref(p10))));
753 
754   EXPECT_TRUE(is_hashable<std::reference_wrapper<int>>::value);
755   int one = 1, ten = 10;
756   EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple(
757       one, ten, std::ref(one), std::ref(ten), std::cref(one), std::cref(ten))));
758 
759   EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(
760       std::make_tuple(std::tuple<std::reference_wrapper<int>>(std::ref(one)),
761                       std::tuple<std::reference_wrapper<int>>(std::ref(ten)),
762                       std::tuple<int>(one), std::tuple<int>(ten))));
763 }
764 
765 template <typename T, typename = void>
766 struct IsHashCallable : std::false_type {};
767 
768 template <typename T>
769 struct IsHashCallable<T, absl::void_t<decltype(std::declval<absl::Hash<T>>()(
770                             std::declval<const T&>()))>> : std::true_type {};
771 
772 template <typename T, typename = void>
773 struct IsAggregateInitializable : std::false_type {};
774 
775 template <typename T>
776 struct IsAggregateInitializable<T, absl::void_t<decltype(T{})>>
777     : std::true_type {};
778 
TEST(IsHashableTest,ValidHash)779 TEST(IsHashableTest, ValidHash) {
780   EXPECT_TRUE((is_hashable<int>::value));
781   EXPECT_TRUE(std::is_default_constructible<absl::Hash<int>>::value);
782   EXPECT_TRUE(std::is_copy_constructible<absl::Hash<int>>::value);
783   EXPECT_TRUE(std::is_move_constructible<absl::Hash<int>>::value);
784   EXPECT_TRUE(absl::is_copy_assignable<absl::Hash<int>>::value);
785   EXPECT_TRUE(absl::is_move_assignable<absl::Hash<int>>::value);
786   EXPECT_TRUE(IsHashCallable<int>::value);
787   EXPECT_TRUE(IsAggregateInitializable<absl::Hash<int>>::value);
788 }
789 
790 #if ABSL_META_INTERNAL_STD_HASH_SFINAE_FRIENDLY_
TEST(IsHashableTest,PoisonHash)791 TEST(IsHashableTest, PoisonHash) {
792   struct X {};
793   EXPECT_FALSE((is_hashable<X>::value));
794   EXPECT_FALSE(std::is_default_constructible<absl::Hash<X>>::value);
795   EXPECT_FALSE(std::is_copy_constructible<absl::Hash<X>>::value);
796   EXPECT_FALSE(std::is_move_constructible<absl::Hash<X>>::value);
797   EXPECT_FALSE(absl::is_copy_assignable<absl::Hash<X>>::value);
798   EXPECT_FALSE(absl::is_move_assignable<absl::Hash<X>>::value);
799   EXPECT_FALSE(IsHashCallable<X>::value);
800 #if !defined(__GNUC__) || defined(__clang__)
801   // TODO(b/144368551): As of GCC 8.4 this does not compile.
802   EXPECT_FALSE(IsAggregateInitializable<absl::Hash<X>>::value);
803 #endif
804 }
805 #endif  // ABSL_META_INTERNAL_STD_HASH_SFINAE_FRIENDLY_
806 
807 // Hashable types
808 //
809 // These types exist simply to exercise various AbslHashValue behaviors, so
810 // they are named by what their AbslHashValue overload does.
811 struct NoOp {
812   template <typename HashCode>
AbslHashValue(HashCode h,NoOp n)813   friend HashCode AbslHashValue(HashCode h, NoOp n) {
814     return h;
815   }
816 };
817 
818 struct EmptyCombine {
819   template <typename HashCode>
AbslHashValue(HashCode h,EmptyCombine e)820   friend HashCode AbslHashValue(HashCode h, EmptyCombine e) {
821     return HashCode::combine(std::move(h));
822   }
823 };
824 
825 template <typename Int>
826 struct CombineIterative {
827   template <typename HashCode>
AbslHashValue(HashCode h,CombineIterative c)828   friend HashCode AbslHashValue(HashCode h, CombineIterative c) {
829     for (int i = 0; i < 5; ++i) {
830       h = HashCode::combine(std::move(h), Int(i));
831     }
832     return h;
833   }
834 };
835 
836 template <typename Int>
837 struct CombineVariadic {
838   template <typename HashCode>
AbslHashValue(HashCode h,CombineVariadic c)839   friend HashCode AbslHashValue(HashCode h, CombineVariadic c) {
840     return HashCode::combine(std::move(h), Int(0), Int(1), Int(2), Int(3),
841                              Int(4));
842   }
843 };
844 enum class InvokeTag {
845   kUniquelyRepresented,
846   kHashValue,
847 #if ABSL_HASH_INTERNAL_SUPPORT_LEGACY_HASH_
848   kLegacyHash,
849 #endif  // ABSL_HASH_INTERNAL_SUPPORT_LEGACY_HASH_
850   kStdHash,
851   kNone
852 };
853 
854 template <InvokeTag T>
855 using InvokeTagConstant = std::integral_constant<InvokeTag, T>;
856 
857 template <InvokeTag... Tags>
858 struct MinTag;
859 
860 template <InvokeTag a, InvokeTag b, InvokeTag... Tags>
861 struct MinTag<a, b, Tags...> : MinTag<(a < b ? a : b), Tags...> {};
862 
863 template <InvokeTag a>
864 struct MinTag<a> : InvokeTagConstant<a> {};
865 
866 template <InvokeTag... Tags>
867 struct CustomHashType {
CustomHashType__anoncc6345600111::CustomHashType868   explicit CustomHashType(size_t val) : value(val) {}
869   size_t value;
870 };
871 
872 template <InvokeTag allowed, InvokeTag... tags>
873 struct EnableIfContained
874     : std::enable_if<absl::disjunction<
875           std::integral_constant<bool, allowed == tags>...>::value> {};
876 
877 template <
878     typename H, InvokeTag... Tags,
879     typename = typename EnableIfContained<InvokeTag::kHashValue, Tags...>::type>
AbslHashValue(H state,CustomHashType<Tags...> t)880 H AbslHashValue(H state, CustomHashType<Tags...> t) {
881   static_assert(MinTag<Tags...>::value == InvokeTag::kHashValue, "");
882   return H::combine(std::move(state),
883                     t.value + static_cast<int>(InvokeTag::kHashValue));
884 }
885 
886 }  // namespace
887 
888 namespace absl {
889 ABSL_NAMESPACE_BEGIN
890 namespace hash_internal {
891 template <InvokeTag... Tags>
892 struct is_uniquely_represented<
893     CustomHashType<Tags...>,
894     typename EnableIfContained<InvokeTag::kUniquelyRepresented, Tags...>::type>
895     : std::true_type {};
896 }  // namespace hash_internal
897 ABSL_NAMESPACE_END
898 }  // namespace absl
899 
900 #if ABSL_HASH_INTERNAL_SUPPORT_LEGACY_HASH_
901 namespace ABSL_INTERNAL_LEGACY_HASH_NAMESPACE {
902 template <InvokeTag... Tags>
903 struct hash<CustomHashType<Tags...>> {
904   template <InvokeTag... TagsIn, typename = typename EnableIfContained<
905                                      InvokeTag::kLegacyHash, TagsIn...>::type>
operator ()ABSL_INTERNAL_LEGACY_HASH_NAMESPACE::hash906   size_t operator()(CustomHashType<TagsIn...> t) const {
907     static_assert(MinTag<Tags...>::value == InvokeTag::kLegacyHash, "");
908     return t.value + static_cast<int>(InvokeTag::kLegacyHash);
909   }
910 };
911 }  // namespace ABSL_INTERNAL_LEGACY_HASH_NAMESPACE
912 #endif  // ABSL_HASH_INTERNAL_SUPPORT_LEGACY_HASH_
913 
914 namespace std {
915 template <InvokeTag... Tags>  // NOLINT
916 struct hash<CustomHashType<Tags...>> {
917   template <InvokeTag... TagsIn, typename = typename EnableIfContained<
918                                      InvokeTag::kStdHash, TagsIn...>::type>
operator ()std::hash919   size_t operator()(CustomHashType<TagsIn...> t) const {
920     static_assert(MinTag<Tags...>::value == InvokeTag::kStdHash, "");
921     return t.value + static_cast<int>(InvokeTag::kStdHash);
922   }
923 };
924 }  // namespace std
925 
926 namespace {
927 
928 template <typename... T>
TestCustomHashType(InvokeTagConstant<InvokeTag::kNone>,T...)929 void TestCustomHashType(InvokeTagConstant<InvokeTag::kNone>, T...) {
930   using type = CustomHashType<T::value...>;
931   SCOPED_TRACE(testing::PrintToString(std::vector<InvokeTag>{T::value...}));
932   EXPECT_TRUE(is_hashable<type>());
933   EXPECT_TRUE(is_hashable<const type>());
934   EXPECT_TRUE(is_hashable<const type&>());
935 
936   const size_t offset = static_cast<int>(std::min({T::value...}));
937   EXPECT_EQ(SpyHash(type(7)), SpyHash(size_t{7 + offset}));
938 }
939 
TestCustomHashType(InvokeTagConstant<InvokeTag::kNone>)940 void TestCustomHashType(InvokeTagConstant<InvokeTag::kNone>) {
941 #if ABSL_META_INTERNAL_STD_HASH_SFINAE_FRIENDLY_
942   // is_hashable is false if we don't support any of the hooks.
943   using type = CustomHashType<>;
944   EXPECT_FALSE(is_hashable<type>());
945   EXPECT_FALSE(is_hashable<const type>());
946   EXPECT_FALSE(is_hashable<const type&>());
947 #endif  // ABSL_META_INTERNAL_STD_HASH_SFINAE_FRIENDLY_
948 }
949 
950 template <InvokeTag Tag, typename... T>
TestCustomHashType(InvokeTagConstant<Tag> tag,T...t)951 void TestCustomHashType(InvokeTagConstant<Tag> tag, T... t) {
952   constexpr auto next = static_cast<InvokeTag>(static_cast<int>(Tag) + 1);
953   TestCustomHashType(InvokeTagConstant<next>(), tag, t...);
954   TestCustomHashType(InvokeTagConstant<next>(), t...);
955 }
956 
TEST(HashTest,CustomHashType)957 TEST(HashTest, CustomHashType) {
958   TestCustomHashType(InvokeTagConstant<InvokeTag{}>());
959 }
960 
TEST(HashTest,NoOpsAreEquivalent)961 TEST(HashTest, NoOpsAreEquivalent) {
962   EXPECT_EQ(Hash<NoOp>()({}), Hash<NoOp>()({}));
963   EXPECT_EQ(Hash<NoOp>()({}), Hash<EmptyCombine>()({}));
964 }
965 
966 template <typename T>
967 class HashIntTest : public testing::Test {
968 };
969 TYPED_TEST_SUITE_P(HashIntTest);
970 
TYPED_TEST_P(HashIntTest,BasicUsage)971 TYPED_TEST_P(HashIntTest, BasicUsage) {
972   EXPECT_NE(Hash<NoOp>()({}), Hash<TypeParam>()(0));
973   EXPECT_NE(Hash<NoOp>()({}),
974             Hash<TypeParam>()(std::numeric_limits<TypeParam>::max()));
975   if (std::numeric_limits<TypeParam>::min() != 0) {
976     EXPECT_NE(Hash<NoOp>()({}),
977               Hash<TypeParam>()(std::numeric_limits<TypeParam>::min()));
978   }
979 
980   EXPECT_EQ(Hash<CombineIterative<TypeParam>>()({}),
981             Hash<CombineVariadic<TypeParam>>()({}));
982 }
983 
984 REGISTER_TYPED_TEST_SUITE_P(HashIntTest, BasicUsage);
985 using IntTypes = testing::Types<unsigned char, char, int, int32_t, int64_t,
986                                 uint32_t, uint64_t, size_t>;
987 INSTANTIATE_TYPED_TEST_SUITE_P(My, HashIntTest, IntTypes);
988 
989 struct StructWithPadding {
990   char c;
991   int i;
992 
993   template <typename H>
AbslHashValue(H hash_state,const StructWithPadding & s)994   friend H AbslHashValue(H hash_state, const StructWithPadding& s) {
995     return H::combine(std::move(hash_state), s.c, s.i);
996   }
997 };
998 
999 static_assert(sizeof(StructWithPadding) > sizeof(char) + sizeof(int),
1000               "StructWithPadding doesn't have padding");
1001 static_assert(std::is_standard_layout<StructWithPadding>::value, "");
1002 
1003 // This check has to be disabled because libstdc++ doesn't support it.
1004 // static_assert(std::is_trivially_constructible<StructWithPadding>::value, "");
1005 
1006 template <typename T>
1007 struct ArraySlice {
1008   T* begin;
1009   T* end;
1010 
1011   template <typename H>
AbslHashValue(H hash_state,const ArraySlice & slice)1012   friend H AbslHashValue(H hash_state, const ArraySlice& slice) {
1013     for (auto t = slice.begin; t != slice.end; ++t) {
1014       hash_state = H::combine(std::move(hash_state), *t);
1015     }
1016     return hash_state;
1017   }
1018 };
1019 
TEST(HashTest,HashNonUniquelyRepresentedType)1020 TEST(HashTest, HashNonUniquelyRepresentedType) {
1021   // Create equal StructWithPadding objects that are known to have non-equal
1022   // padding bytes.
1023   static const size_t kNumStructs = 10;
1024   unsigned char buffer1[kNumStructs * sizeof(StructWithPadding)];
1025   std::memset(buffer1, 0, sizeof(buffer1));
1026   auto* s1 = reinterpret_cast<StructWithPadding*>(buffer1);
1027 
1028   unsigned char buffer2[kNumStructs * sizeof(StructWithPadding)];
1029   std::memset(buffer2, 255, sizeof(buffer2));
1030   auto* s2 = reinterpret_cast<StructWithPadding*>(buffer2);
1031   for (size_t i = 0; i < kNumStructs; ++i) {
1032     SCOPED_TRACE(i);
1033     s1[i].c = s2[i].c = static_cast<char>('0' + i);
1034     s1[i].i = s2[i].i = static_cast<int>(i);
1035     ASSERT_FALSE(memcmp(buffer1 + i * sizeof(StructWithPadding),
1036                         buffer2 + i * sizeof(StructWithPadding),
1037                         sizeof(StructWithPadding)) == 0)
1038         << "Bug in test code: objects do not have unequal"
1039         << " object representations";
1040   }
1041 
1042   EXPECT_EQ(Hash<StructWithPadding>()(s1[0]), Hash<StructWithPadding>()(s2[0]));
1043   EXPECT_EQ(Hash<ArraySlice<StructWithPadding>>()({s1, s1 + kNumStructs}),
1044             Hash<ArraySlice<StructWithPadding>>()({s2, s2 + kNumStructs}));
1045 }
1046 
TEST(HashTest,StandardHashContainerUsage)1047 TEST(HashTest, StandardHashContainerUsage) {
1048   std::unordered_map<int, std::string, Hash<int>> map = {{0, "foo"},
1049                                                          {42, "bar"}};
1050 
1051   EXPECT_NE(map.find(0), map.end());
1052   EXPECT_EQ(map.find(1), map.end());
1053   EXPECT_NE(map.find(0u), map.end());
1054 }
1055 
1056 struct ConvertibleFromNoOp {
ConvertibleFromNoOp__anoncc6345600411::ConvertibleFromNoOp1057   ConvertibleFromNoOp(NoOp) {}  // NOLINT(runtime/explicit)
1058 
1059   template <typename H>
AbslHashValue(H hash_state,ConvertibleFromNoOp)1060   friend H AbslHashValue(H hash_state, ConvertibleFromNoOp) {
1061     return H::combine(std::move(hash_state), 1);
1062   }
1063 };
1064 
TEST(HashTest,HeterogeneousCall)1065 TEST(HashTest, HeterogeneousCall) {
1066   EXPECT_NE(Hash<ConvertibleFromNoOp>()(NoOp()),
1067             Hash<NoOp>()(NoOp()));
1068 }
1069 
TEST(IsUniquelyRepresentedTest,SanityTest)1070 TEST(IsUniquelyRepresentedTest, SanityTest) {
1071   using absl::hash_internal::is_uniquely_represented;
1072 
1073   EXPECT_TRUE(is_uniquely_represented<unsigned char>::value);
1074   EXPECT_TRUE(is_uniquely_represented<int>::value);
1075   EXPECT_FALSE(is_uniquely_represented<bool>::value);
1076   EXPECT_FALSE(is_uniquely_represented<int*>::value);
1077 }
1078 
1079 struct IntAndString {
1080   int i;
1081   std::string s;
1082 
1083   template <typename H>
AbslHashValue(H hash_state,IntAndString int_and_string)1084   friend H AbslHashValue(H hash_state, IntAndString int_and_string) {
1085     return H::combine(std::move(hash_state), int_and_string.s,
1086                       int_and_string.i);
1087   }
1088 };
1089 
TEST(HashTest,SmallValueOn64ByteBoundary)1090 TEST(HashTest, SmallValueOn64ByteBoundary) {
1091   Hash<IntAndString>()(IntAndString{0, std::string(63, '0')});
1092 }
1093 
TEST(HashTest,TypeErased)1094 TEST(HashTest, TypeErased) {
1095   EXPECT_TRUE((is_hashable<TypeErasedValue<size_t>>::value));
1096   EXPECT_TRUE((is_hashable<std::pair<TypeErasedValue<size_t>, int>>::value));
1097 
1098   EXPECT_EQ(SpyHash(TypeErasedValue<size_t>(7)), SpyHash(size_t{7}));
1099   EXPECT_NE(SpyHash(TypeErasedValue<size_t>(7)), SpyHash(size_t{13}));
1100 
1101   EXPECT_EQ(SpyHash(std::make_pair(TypeErasedValue<size_t>(7), 17)),
1102             SpyHash(std::make_pair(size_t{7}, 17)));
1103 
1104   absl::flat_hash_set<absl::flat_hash_set<int>> ss = {{1, 2}, {3, 4}};
1105   TypeErasedContainer<absl::flat_hash_set<absl::flat_hash_set<int>>> es = {
1106       absl::flat_hash_set<int>{1, 2}, {3, 4}};
1107   absl::flat_hash_set<TypeErasedContainer<absl::flat_hash_set<int>>> se = {
1108       {1, 2}, {3, 4}};
1109   EXPECT_EQ(SpyHash(ss), SpyHash(es));
1110   EXPECT_EQ(SpyHash(ss), SpyHash(se));
1111 }
1112 
1113 struct ValueWithBoolConversion {
operator bool__anoncc6345600411::ValueWithBoolConversion1114   operator bool() const { return false; }
1115   int i;
1116 };
1117 
1118 }  // namespace
1119 namespace std {
1120 template <>
1121 struct hash<ValueWithBoolConversion> {
operator ()std::hash1122   size_t operator()(ValueWithBoolConversion v) {
1123     return static_cast<size_t>(v.i);
1124   }
1125 };
1126 }  // namespace std
1127 
1128 namespace {
1129 
TEST(HashTest,DoesNotUseImplicitConversionsToBool)1130 TEST(HashTest, DoesNotUseImplicitConversionsToBool) {
1131   EXPECT_NE(absl::Hash<ValueWithBoolConversion>()(ValueWithBoolConversion{0}),
1132             absl::Hash<ValueWithBoolConversion>()(ValueWithBoolConversion{1}));
1133 }
1134 
TEST(HashOf,MatchesHashForSingleArgument)1135 TEST(HashOf, MatchesHashForSingleArgument) {
1136   std::string s = "forty two";
1137   double d = 42.0;
1138   std::tuple<int, int> t{4, 2};
1139   int i = 42;
1140   int neg_i = -42;
1141   int16_t i16 = 42;
1142   int16_t neg_i16 = -42;
1143   int8_t i8 = 42;
1144   int8_t neg_i8 = -42;
1145 
1146   EXPECT_EQ(absl::HashOf(s), absl::Hash<std::string>{}(s));
1147   EXPECT_EQ(absl::HashOf(d), absl::Hash<double>{}(d));
1148   EXPECT_EQ(absl::HashOf(t), (absl::Hash<std::tuple<int, int>>{}(t)));
1149   EXPECT_EQ(absl::HashOf(i), absl::Hash<int>{}(i));
1150   EXPECT_EQ(absl::HashOf(neg_i), absl::Hash<int>{}(neg_i));
1151   EXPECT_EQ(absl::HashOf(i16), absl::Hash<int16_t>{}(i16));
1152   EXPECT_EQ(absl::HashOf(neg_i16), absl::Hash<int16_t>{}(neg_i16));
1153   EXPECT_EQ(absl::HashOf(i8), absl::Hash<int8_t>{}(i8));
1154   EXPECT_EQ(absl::HashOf(neg_i8), absl::Hash<int8_t>{}(neg_i8));
1155 }
1156 
TEST(HashOf,MatchesHashOfTupleForMultipleArguments)1157 TEST(HashOf, MatchesHashOfTupleForMultipleArguments) {
1158   std::string hello = "hello";
1159   std::string world = "world";
1160 
1161   EXPECT_EQ(absl::HashOf(), absl::HashOf(std::make_tuple()));
1162   EXPECT_EQ(absl::HashOf(hello), absl::HashOf(std::make_tuple(hello)));
1163   EXPECT_EQ(absl::HashOf(hello, world),
1164             absl::HashOf(std::make_tuple(hello, world)));
1165 }
1166 
1167 template <typename T>
1168 std::true_type HashOfExplicitParameter(decltype(absl::HashOf<T>(0))) {
1169   return {};
1170 }
1171 template <typename T>
HashOfExplicitParameter(size_t)1172 std::false_type HashOfExplicitParameter(size_t) {
1173   return {};
1174 }
1175 
TEST(HashOf,CantPassExplicitTemplateParameters)1176 TEST(HashOf, CantPassExplicitTemplateParameters) {
1177   EXPECT_FALSE(HashOfExplicitParameter<int>(0));
1178 }
1179 
1180 }  // namespace
1181