• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <cstdint>
21 #include <cstring>
22 #include <deque>
23 #include <forward_list>
24 #include <functional>
25 #include <initializer_list>
26 #include <iterator>
27 #include <limits>
28 #include <list>
29 #include <map>
30 #include <memory>
31 #include <numeric>
32 #include <random>
33 #include <set>
34 #include <string>
35 #include <tuple>
36 #include <type_traits>
37 #include <unordered_map>
38 #include <unordered_set>
39 #include <utility>
40 #include <vector>
41 
42 #include "gmock/gmock.h"
43 #include "gtest/gtest.h"
44 #include "absl/container/btree_map.h"
45 #include "absl/container/btree_set.h"
46 #include "absl/container/flat_hash_map.h"
47 #include "absl/container/flat_hash_set.h"
48 #include "absl/container/node_hash_map.h"
49 #include "absl/container/node_hash_set.h"
50 #include "absl/hash/hash_testing.h"
51 #include "absl/hash/internal/hash_test.h"
52 #include "absl/hash/internal/spy_hash_state.h"
53 #include "absl/meta/type_traits.h"
54 #include "absl/numeric/int128.h"
55 #include "absl/strings/cord_test_helpers.h"
56 
57 #ifdef ABSL_HAVE_STD_STRING_VIEW
58 #include <string_view>
59 #endif
60 
61 namespace {
62 
63 using ::absl::hash_test_internal::is_hashable;
64 using ::absl::hash_test_internal::TypeErasedContainer;
65 using ::absl::hash_test_internal::TypeErasedValue;
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 ()__anon475069ff0111::DummyDeleter306   void operator() (T* ptr) {}
307 };
308 
309 struct SmartPointerEq {
310   template <typename T, typename U>
operator ()__anon475069ff0111::SmartPointerEq311   bool operator()(const T& t, const U& u) const {
312     return GetPtr(t) == GetPtr(u);
313   }
314 
315   template <typename T>
GetPtr__anon475069ff0111::SmartPointerEq316   static auto GetPtr(const T& t) -> decltype(&*t) {
317     return t ? &*t : nullptr;
318   }
319 
GetPtr__anon475069ff0111::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 ()__anon475069ff0111::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 
TEST(HashValueTest,Strings)386 TEST(HashValueTest, Strings) {
387   EXPECT_TRUE((is_hashable<std::string>::value));
388 
389   const std::string small = "foo";
390   const std::string dup = "foofoo";
391   const std::string large = std::string(2048, 'x');  // multiple of chunk size
392   const std::string huge = std::string(5000, 'a');   // not a multiple
393 
394   EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple(  //
395       std::string(), absl::string_view(), absl::Cord(),                     //
396       std::string(""), absl::string_view(""), absl::Cord(""),               //
397       std::string(small), absl::string_view(small), absl::Cord(small),      //
398       std::string(dup), absl::string_view(dup), absl::Cord(dup),            //
399       std::string(large), absl::string_view(large), absl::Cord(large),      //
400       std::string(huge), absl::string_view(huge), FlatCord(huge),           //
401       FragmentedCord(huge))));
402 
403   // Also check that nested types maintain the same hash.
404   const WrapInTuple t{};
405   EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple(  //
406       t(std::string()), t(absl::string_view()), t(absl::Cord()),            //
407       t(std::string("")), t(absl::string_view("")), t(absl::Cord("")),      //
408       t(std::string(small)), t(absl::string_view(small)),                   //
409           t(absl::Cord(small)),                                             //
410       t(std::string(dup)), t(absl::string_view(dup)), t(absl::Cord(dup)),   //
411       t(std::string(large)), t(absl::string_view(large)),                   //
412           t(absl::Cord(large)),                                             //
413       t(std::string(huge)), t(absl::string_view(huge)),                     //
414           t(FlatCord(huge)), t(FragmentedCord(huge)))));
415 
416   // Make sure that hashing a `const char*` does not use its string-value.
417   EXPECT_NE(SpyHash(static_cast<const char*>("ABC")),
418             SpyHash(absl::string_view("ABC")));
419 }
420 
TEST(HashValueTest,WString)421 TEST(HashValueTest, WString) {
422   EXPECT_TRUE((is_hashable<std::wstring>::value));
423 
424   EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple(
425       std::wstring(), std::wstring(L"ABC"), std::wstring(L"ABC"),
426       std::wstring(L"Some other different string"),
427       std::wstring(L"Iñtërnâtiônàlizætiøn"))));
428 }
429 
TEST(HashValueTest,U16String)430 TEST(HashValueTest, U16String) {
431   EXPECT_TRUE((is_hashable<std::u16string>::value));
432 
433   EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple(
434       std::u16string(), std::u16string(u"ABC"), std::u16string(u"ABC"),
435       std::u16string(u"Some other different string"),
436       std::u16string(u"Iñtërnâtiônàlizætiøn"))));
437 }
438 
TEST(HashValueTest,U32String)439 TEST(HashValueTest, U32String) {
440   EXPECT_TRUE((is_hashable<std::u32string>::value));
441 
442   EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple(
443       std::u32string(), std::u32string(U"ABC"), std::u32string(U"ABC"),
444       std::u32string(U"Some other different string"),
445       std::u32string(U"Iñtërnâtiônàlizætiøn"))));
446 }
447 
TEST(HashValueTest,WStringView)448 TEST(HashValueTest, WStringView) {
449 #ifndef ABSL_HAVE_STD_STRING_VIEW
450   GTEST_SKIP();
451 #else
452   EXPECT_TRUE((is_hashable<std::wstring_view>::value));
453 
454   EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple(
455       std::wstring_view(), std::wstring_view(L"ABC"), std::wstring_view(L"ABC"),
456       std::wstring_view(L"Some other different string_view"),
457       std::wstring_view(L"Iñtërnâtiônàlizætiøn"))));
458 #endif
459 }
460 
TEST(HashValueTest,U16StringView)461 TEST(HashValueTest, U16StringView) {
462 #ifndef ABSL_HAVE_STD_STRING_VIEW
463   GTEST_SKIP();
464 #else
465   EXPECT_TRUE((is_hashable<std::u16string_view>::value));
466 
467   EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(
468       std::make_tuple(std::u16string_view(), std::u16string_view(u"ABC"),
469                       std::u16string_view(u"ABC"),
470                       std::u16string_view(u"Some other different string_view"),
471                       std::u16string_view(u"Iñtërnâtiônàlizætiøn"))));
472 #endif
473 }
474 
TEST(HashValueTest,U32StringView)475 TEST(HashValueTest, U32StringView) {
476 #ifndef ABSL_HAVE_STD_STRING_VIEW
477   GTEST_SKIP();
478 #else
479   EXPECT_TRUE((is_hashable<std::u32string_view>::value));
480 
481   EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(
482       std::make_tuple(std::u32string_view(), std::u32string_view(U"ABC"),
483                       std::u32string_view(U"ABC"),
484                       std::u32string_view(U"Some other different string_view"),
485                       std::u32string_view(U"Iñtërnâtiônàlizætiøn"))));
486 #endif
487 }
488 
TEST(HashValueTest,StdArray)489 TEST(HashValueTest, StdArray) {
490   EXPECT_TRUE((is_hashable<std::array<int, 3>>::value));
491 
492   EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(
493       std::make_tuple(std::array<int, 3>{}, std::array<int, 3>{{0, 23, 42}})));
494 }
495 
TEST(HashValueTest,StdBitset)496 TEST(HashValueTest, StdBitset) {
497   EXPECT_TRUE((is_hashable<std::bitset<257>>::value));
498 
499   EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(
500       {std::bitset<2>("00"), std::bitset<2>("01"), std::bitset<2>("10"),
501        std::bitset<2>("11")}));
502   EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(
503       {std::bitset<5>("10101"), std::bitset<5>("10001"), std::bitset<5>()}));
504 
505   constexpr int kNumBits = 256;
506   std::array<std::string, 6> bit_strings;
507   bit_strings.fill(std::string(kNumBits, '1'));
508   bit_strings[1][0] = '0';
509   bit_strings[2][1] = '0';
510   bit_strings[3][kNumBits / 3] = '0';
511   bit_strings[4][kNumBits - 2] = '0';
512   bit_strings[5][kNumBits - 1] = '0';
513   EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(
514       {std::bitset<kNumBits>(bit_strings[0].c_str()),
515        std::bitset<kNumBits>(bit_strings[1].c_str()),
516        std::bitset<kNumBits>(bit_strings[2].c_str()),
517        std::bitset<kNumBits>(bit_strings[3].c_str()),
518        std::bitset<kNumBits>(bit_strings[4].c_str()),
519        std::bitset<kNumBits>(bit_strings[5].c_str())}));
520 }  // namespace
521 
522 // Private type that only supports AbslHashValue to make sure our chosen hash
523 // implementation is recursive within absl::Hash.
524 // It uses std::abs() on the value to provide different bitwise representations
525 // of the same logical value.
526 struct Private {
527   int i;
528   template <typename H>
AbslHashValue(H h,Private p)529   friend H AbslHashValue(H h, Private p) {
530     return H::combine(std::move(h), std::abs(p.i));
531   }
532 
operator ==(Private a,Private b)533   friend bool operator==(Private a, Private b) {
534     return std::abs(a.i) == std::abs(b.i);
535   }
536 
operator <<(std::ostream & o,Private p)537   friend std::ostream& operator<<(std::ostream& o, Private p) {
538     return o << p.i;
539   }
540 };
541 
542 // Test helper for combine_piecewise_buffer.  It holds a string_view to the
543 // buffer-to-be-hashed.  Its AbslHashValue specialization will split up its
544 // contents at the character offsets requested.
545 class PiecewiseHashTester {
546  public:
547   // Create a hash view of a buffer to be hashed contiguously.
PiecewiseHashTester(absl::string_view buf)548   explicit PiecewiseHashTester(absl::string_view buf)
549       : buf_(buf), piecewise_(false), split_locations_() {}
550 
551   // Create a hash view of a buffer to be hashed piecewise, with breaks at the
552   // given locations.
PiecewiseHashTester(absl::string_view buf,std::set<size_t> split_locations)553   PiecewiseHashTester(absl::string_view buf, std::set<size_t> split_locations)
554       : buf_(buf),
555         piecewise_(true),
556         split_locations_(std::move(split_locations)) {}
557 
558   template <typename H>
AbslHashValue(H h,const PiecewiseHashTester & p)559   friend H AbslHashValue(H h, const PiecewiseHashTester& p) {
560     if (!p.piecewise_) {
561       return H::combine_contiguous(std::move(h), p.buf_.data(), p.buf_.size());
562     }
563     absl::hash_internal::PiecewiseCombiner combiner;
564     if (p.split_locations_.empty()) {
565       h = combiner.add_buffer(std::move(h), p.buf_.data(), p.buf_.size());
566       return combiner.finalize(std::move(h));
567     }
568     size_t begin = 0;
569     for (size_t next : p.split_locations_) {
570       absl::string_view chunk = p.buf_.substr(begin, next - begin);
571       h = combiner.add_buffer(std::move(h), chunk.data(), chunk.size());
572       begin = next;
573     }
574     absl::string_view last_chunk = p.buf_.substr(begin);
575     if (!last_chunk.empty()) {
576       h = combiner.add_buffer(std::move(h), last_chunk.data(),
577                               last_chunk.size());
578     }
579     return combiner.finalize(std::move(h));
580   }
581 
582  private:
583   absl::string_view buf_;
584   bool piecewise_;
585   std::set<size_t> split_locations_;
586 };
587 
588 // Dummy object that hashes as two distinct contiguous buffers, "foo" followed
589 // by "bar"
590 struct DummyFooBar {
591   template <typename H>
AbslHashValue(H h,const DummyFooBar &)592   friend H AbslHashValue(H h, const DummyFooBar&) {
593     const char* foo = "foo";
594     const char* bar = "bar";
595     h = H::combine_contiguous(std::move(h), foo, 3);
596     h = H::combine_contiguous(std::move(h), bar, 3);
597     return h;
598   }
599 };
600 
TEST(HashValueTest,CombinePiecewiseBuffer)601 TEST(HashValueTest, CombinePiecewiseBuffer) {
602   absl::Hash<PiecewiseHashTester> hash;
603 
604   // Check that hashing an empty buffer through the piecewise API works.
605   EXPECT_EQ(hash(PiecewiseHashTester("")), hash(PiecewiseHashTester("", {})));
606 
607   // Similarly, small buffers should give consistent results
608   EXPECT_EQ(hash(PiecewiseHashTester("foobar")),
609             hash(PiecewiseHashTester("foobar", {})));
610   EXPECT_EQ(hash(PiecewiseHashTester("foobar")),
611             hash(PiecewiseHashTester("foobar", {3})));
612 
613   // But hashing "foobar" in pieces gives a different answer than hashing "foo"
614   // contiguously, then "bar" contiguously.
615   EXPECT_NE(hash(PiecewiseHashTester("foobar", {3})),
616             absl::Hash<DummyFooBar>()(DummyFooBar{}));
617 
618   // Test hashing a large buffer incrementally, broken up in several different
619   // ways.  Arrange for breaks on and near the stride boundaries to look for
620   // off-by-one errors in the implementation.
621   //
622   // This test is run on a buffer that is a multiple of the stride size, and one
623   // that isn't.
624   for (size_t big_buffer_size : {1024u * 2 + 512u, 1024u * 3}) {
625     SCOPED_TRACE(big_buffer_size);
626     std::string big_buffer;
627     for (size_t i = 0; i < big_buffer_size; ++i) {
628       // Arbitrary string
629       big_buffer.push_back(32 + (i * (i / 3)) % 64);
630     }
631     auto big_buffer_hash = hash(PiecewiseHashTester(big_buffer));
632 
633     const int possible_breaks = 9;
634     size_t breaks[possible_breaks] = {1,    512,  1023, 1024, 1025,
635                                       1536, 2047, 2048, 2049};
636     for (unsigned test_mask = 0; test_mask < (1u << possible_breaks);
637          ++test_mask) {
638       SCOPED_TRACE(test_mask);
639       std::set<size_t> break_locations;
640       for (int j = 0; j < possible_breaks; ++j) {
641         if (test_mask & (1u << j)) {
642           break_locations.insert(breaks[j]);
643         }
644       }
645       EXPECT_EQ(
646           hash(PiecewiseHashTester(big_buffer, std::move(break_locations))),
647           big_buffer_hash);
648     }
649   }
650 }
651 
TEST(HashValueTest,PrivateSanity)652 TEST(HashValueTest, PrivateSanity) {
653   // Sanity check that Private is working as the tests below expect it to work.
654   EXPECT_TRUE(is_hashable<Private>::value);
655   EXPECT_NE(SpyHash(Private{0}), SpyHash(Private{1}));
656   EXPECT_EQ(SpyHash(Private{1}), SpyHash(Private{1}));
657 }
658 
TEST(HashValueTest,Optional)659 TEST(HashValueTest, Optional) {
660   EXPECT_TRUE(is_hashable<absl::optional<Private>>::value);
661 
662   using O = absl::optional<Private>;
663   EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(
664       std::make_tuple(O{}, O{{1}}, O{{-1}}, O{{10}})));
665 }
666 
TEST(HashValueTest,Variant)667 TEST(HashValueTest, Variant) {
668   using V = absl::variant<Private, std::string>;
669   EXPECT_TRUE(is_hashable<V>::value);
670 
671   EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple(
672       V(Private{1}), V(Private{-1}), V(Private{2}), V("ABC"), V("BCD"))));
673 
674 #if ABSL_META_INTERNAL_STD_HASH_SFINAE_FRIENDLY_
675   struct S {};
676   EXPECT_FALSE(is_hashable<absl::variant<S>>::value);
677 #endif
678 }
679 
TEST(HashValueTest,ReferenceWrapper)680 TEST(HashValueTest, ReferenceWrapper) {
681   EXPECT_TRUE(is_hashable<std::reference_wrapper<Private>>::value);
682 
683   Private p1{1}, p10{10};
684   EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple(
685       p1, p10, std::ref(p1), std::ref(p10), std::cref(p1), std::cref(p10))));
686 
687   EXPECT_TRUE(is_hashable<std::reference_wrapper<int>>::value);
688   int one = 1, ten = 10;
689   EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple(
690       one, ten, std::ref(one), std::ref(ten), std::cref(one), std::cref(ten))));
691 
692   EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(
693       std::make_tuple(std::tuple<std::reference_wrapper<int>>(std::ref(one)),
694                       std::tuple<std::reference_wrapper<int>>(std::ref(ten)),
695                       std::tuple<int>(one), std::tuple<int>(ten))));
696 }
697 
698 template <typename T, typename = void>
699 struct IsHashCallable : std::false_type {};
700 
701 template <typename T>
702 struct IsHashCallable<T, absl::void_t<decltype(std::declval<absl::Hash<T>>()(
703                             std::declval<const T&>()))>> : std::true_type {};
704 
705 template <typename T, typename = void>
706 struct IsAggregateInitializable : std::false_type {};
707 
708 template <typename T>
709 struct IsAggregateInitializable<T, absl::void_t<decltype(T{})>>
710     : std::true_type {};
711 
TEST(IsHashableTest,ValidHash)712 TEST(IsHashableTest, ValidHash) {
713   EXPECT_TRUE((is_hashable<int>::value));
714   EXPECT_TRUE(std::is_default_constructible<absl::Hash<int>>::value);
715   EXPECT_TRUE(std::is_copy_constructible<absl::Hash<int>>::value);
716   EXPECT_TRUE(std::is_move_constructible<absl::Hash<int>>::value);
717   EXPECT_TRUE(absl::is_copy_assignable<absl::Hash<int>>::value);
718   EXPECT_TRUE(absl::is_move_assignable<absl::Hash<int>>::value);
719   EXPECT_TRUE(IsHashCallable<int>::value);
720   EXPECT_TRUE(IsAggregateInitializable<absl::Hash<int>>::value);
721 }
722 
723 #if ABSL_META_INTERNAL_STD_HASH_SFINAE_FRIENDLY_
TEST(IsHashableTest,PoisonHash)724 TEST(IsHashableTest, PoisonHash) {
725   struct X {};
726   EXPECT_FALSE((is_hashable<X>::value));
727   EXPECT_FALSE(std::is_default_constructible<absl::Hash<X>>::value);
728   EXPECT_FALSE(std::is_copy_constructible<absl::Hash<X>>::value);
729   EXPECT_FALSE(std::is_move_constructible<absl::Hash<X>>::value);
730   EXPECT_FALSE(absl::is_copy_assignable<absl::Hash<X>>::value);
731   EXPECT_FALSE(absl::is_move_assignable<absl::Hash<X>>::value);
732   EXPECT_FALSE(IsHashCallable<X>::value);
733 #if !defined(__GNUC__) || defined(__clang__)
734   // TODO(b/144368551): As of GCC 8.4 this does not compile.
735   EXPECT_FALSE(IsAggregateInitializable<absl::Hash<X>>::value);
736 #endif
737 }
738 #endif  // ABSL_META_INTERNAL_STD_HASH_SFINAE_FRIENDLY_
739 
740 // Hashable types
741 //
742 // These types exist simply to exercise various AbslHashValue behaviors, so
743 // they are named by what their AbslHashValue overload does.
744 struct NoOp {
745   template <typename HashCode>
AbslHashValue(HashCode h,NoOp n)746   friend HashCode AbslHashValue(HashCode h, NoOp n) {
747     return h;
748   }
749 };
750 
751 struct EmptyCombine {
752   template <typename HashCode>
AbslHashValue(HashCode h,EmptyCombine e)753   friend HashCode AbslHashValue(HashCode h, EmptyCombine e) {
754     return HashCode::combine(std::move(h));
755   }
756 };
757 
758 template <typename Int>
759 struct CombineIterative {
760   template <typename HashCode>
AbslHashValue(HashCode h,CombineIterative c)761   friend HashCode AbslHashValue(HashCode h, CombineIterative c) {
762     for (int i = 0; i < 5; ++i) {
763       h = HashCode::combine(std::move(h), Int(i));
764     }
765     return h;
766   }
767 };
768 
769 template <typename Int>
770 struct CombineVariadic {
771   template <typename HashCode>
AbslHashValue(HashCode h,CombineVariadic c)772   friend HashCode AbslHashValue(HashCode h, CombineVariadic c) {
773     return HashCode::combine(std::move(h), Int(0), Int(1), Int(2), Int(3),
774                              Int(4));
775   }
776 };
777 enum class InvokeTag {
778   kUniquelyRepresented,
779   kHashValue,
780 #if ABSL_HASH_INTERNAL_SUPPORT_LEGACY_HASH_
781   kLegacyHash,
782 #endif  // ABSL_HASH_INTERNAL_SUPPORT_LEGACY_HASH_
783   kStdHash,
784   kNone
785 };
786 
787 template <InvokeTag T>
788 using InvokeTagConstant = std::integral_constant<InvokeTag, T>;
789 
790 template <InvokeTag... Tags>
791 struct MinTag;
792 
793 template <InvokeTag a, InvokeTag b, InvokeTag... Tags>
794 struct MinTag<a, b, Tags...> : MinTag<(a < b ? a : b), Tags...> {};
795 
796 template <InvokeTag a>
797 struct MinTag<a> : InvokeTagConstant<a> {};
798 
799 template <InvokeTag... Tags>
800 struct CustomHashType {
CustomHashType__anon475069ff0111::CustomHashType801   explicit CustomHashType(size_t val) : value(val) {}
802   size_t value;
803 };
804 
805 template <InvokeTag allowed, InvokeTag... tags>
806 struct EnableIfContained
807     : std::enable_if<absl::disjunction<
808           std::integral_constant<bool, allowed == tags>...>::value> {};
809 
810 template <
811     typename H, InvokeTag... Tags,
812     typename = typename EnableIfContained<InvokeTag::kHashValue, Tags...>::type>
AbslHashValue(H state,CustomHashType<Tags...> t)813 H AbslHashValue(H state, CustomHashType<Tags...> t) {
814   static_assert(MinTag<Tags...>::value == InvokeTag::kHashValue, "");
815   return H::combine(std::move(state),
816                     t.value + static_cast<int>(InvokeTag::kHashValue));
817 }
818 
819 }  // namespace
820 
821 namespace absl {
822 ABSL_NAMESPACE_BEGIN
823 namespace hash_internal {
824 template <InvokeTag... Tags>
825 struct is_uniquely_represented<
826     CustomHashType<Tags...>,
827     typename EnableIfContained<InvokeTag::kUniquelyRepresented, Tags...>::type>
828     : std::true_type {};
829 }  // namespace hash_internal
830 ABSL_NAMESPACE_END
831 }  // namespace absl
832 
833 #if ABSL_HASH_INTERNAL_SUPPORT_LEGACY_HASH_
834 namespace ABSL_INTERNAL_LEGACY_HASH_NAMESPACE {
835 template <InvokeTag... Tags>
836 struct hash<CustomHashType<Tags...>> {
837   template <InvokeTag... TagsIn, typename = typename EnableIfContained<
838                                      InvokeTag::kLegacyHash, TagsIn...>::type>
operator ()ABSL_INTERNAL_LEGACY_HASH_NAMESPACE::hash839   size_t operator()(CustomHashType<TagsIn...> t) const {
840     static_assert(MinTag<Tags...>::value == InvokeTag::kLegacyHash, "");
841     return t.value + static_cast<int>(InvokeTag::kLegacyHash);
842   }
843 };
844 }  // namespace ABSL_INTERNAL_LEGACY_HASH_NAMESPACE
845 #endif  // ABSL_HASH_INTERNAL_SUPPORT_LEGACY_HASH_
846 
847 namespace std {
848 template <InvokeTag... Tags>  // NOLINT
849 struct hash<CustomHashType<Tags...>> {
850   template <InvokeTag... TagsIn, typename = typename EnableIfContained<
851                                      InvokeTag::kStdHash, TagsIn...>::type>
operator ()std::hash852   size_t operator()(CustomHashType<TagsIn...> t) const {
853     static_assert(MinTag<Tags...>::value == InvokeTag::kStdHash, "");
854     return t.value + static_cast<int>(InvokeTag::kStdHash);
855   }
856 };
857 }  // namespace std
858 
859 namespace {
860 
861 template <typename... T>
TestCustomHashType(InvokeTagConstant<InvokeTag::kNone>,T...)862 void TestCustomHashType(InvokeTagConstant<InvokeTag::kNone>, T...) {
863   using type = CustomHashType<T::value...>;
864   SCOPED_TRACE(testing::PrintToString(std::vector<InvokeTag>{T::value...}));
865   EXPECT_TRUE(is_hashable<type>());
866   EXPECT_TRUE(is_hashable<const type>());
867   EXPECT_TRUE(is_hashable<const type&>());
868 
869   const size_t offset = static_cast<int>(std::min({T::value...}));
870   EXPECT_EQ(SpyHash(type(7)), SpyHash(size_t{7 + offset}));
871 }
872 
TestCustomHashType(InvokeTagConstant<InvokeTag::kNone>)873 void TestCustomHashType(InvokeTagConstant<InvokeTag::kNone>) {
874 #if ABSL_META_INTERNAL_STD_HASH_SFINAE_FRIENDLY_
875   // is_hashable is false if we don't support any of the hooks.
876   using type = CustomHashType<>;
877   EXPECT_FALSE(is_hashable<type>());
878   EXPECT_FALSE(is_hashable<const type>());
879   EXPECT_FALSE(is_hashable<const type&>());
880 #endif  // ABSL_META_INTERNAL_STD_HASH_SFINAE_FRIENDLY_
881 }
882 
883 template <InvokeTag Tag, typename... T>
TestCustomHashType(InvokeTagConstant<Tag> tag,T...t)884 void TestCustomHashType(InvokeTagConstant<Tag> tag, T... t) {
885   constexpr auto next = static_cast<InvokeTag>(static_cast<int>(Tag) + 1);
886   TestCustomHashType(InvokeTagConstant<next>(), tag, t...);
887   TestCustomHashType(InvokeTagConstant<next>(), t...);
888 }
889 
TEST(HashTest,CustomHashType)890 TEST(HashTest, CustomHashType) {
891   TestCustomHashType(InvokeTagConstant<InvokeTag{}>());
892 }
893 
TEST(HashTest,NoOpsAreEquivalent)894 TEST(HashTest, NoOpsAreEquivalent) {
895   EXPECT_EQ(Hash<NoOp>()({}), Hash<NoOp>()({}));
896   EXPECT_EQ(Hash<NoOp>()({}), Hash<EmptyCombine>()({}));
897 }
898 
899 template <typename T>
900 class HashIntTest : public testing::Test {
901 };
902 TYPED_TEST_SUITE_P(HashIntTest);
903 
TYPED_TEST_P(HashIntTest,BasicUsage)904 TYPED_TEST_P(HashIntTest, BasicUsage) {
905   EXPECT_NE(Hash<NoOp>()({}), Hash<TypeParam>()(0));
906   EXPECT_NE(Hash<NoOp>()({}),
907             Hash<TypeParam>()(std::numeric_limits<TypeParam>::max()));
908   if (std::numeric_limits<TypeParam>::min() != 0) {
909     EXPECT_NE(Hash<NoOp>()({}),
910               Hash<TypeParam>()(std::numeric_limits<TypeParam>::min()));
911   }
912 
913   EXPECT_EQ(Hash<CombineIterative<TypeParam>>()({}),
914             Hash<CombineVariadic<TypeParam>>()({}));
915 }
916 
917 REGISTER_TYPED_TEST_SUITE_P(HashIntTest, BasicUsage);
918 using IntTypes = testing::Types<unsigned char, char, int, int32_t, int64_t,
919                                 uint32_t, uint64_t, size_t>;
920 INSTANTIATE_TYPED_TEST_SUITE_P(My, HashIntTest, IntTypes);
921 
922 struct StructWithPadding {
923   char c;
924   int i;
925 
926   template <typename H>
AbslHashValue(H hash_state,const StructWithPadding & s)927   friend H AbslHashValue(H hash_state, const StructWithPadding& s) {
928     return H::combine(std::move(hash_state), s.c, s.i);
929   }
930 };
931 
932 static_assert(sizeof(StructWithPadding) > sizeof(char) + sizeof(int),
933               "StructWithPadding doesn't have padding");
934 static_assert(std::is_standard_layout<StructWithPadding>::value, "");
935 
936 // This check has to be disabled because libstdc++ doesn't support it.
937 // static_assert(std::is_trivially_constructible<StructWithPadding>::value, "");
938 
939 template <typename T>
940 struct ArraySlice {
941   T* begin;
942   T* end;
943 
944   template <typename H>
AbslHashValue(H hash_state,const ArraySlice & slice)945   friend H AbslHashValue(H hash_state, const ArraySlice& slice) {
946     for (auto t = slice.begin; t != slice.end; ++t) {
947       hash_state = H::combine(std::move(hash_state), *t);
948     }
949     return hash_state;
950   }
951 };
952 
TEST(HashTest,HashNonUniquelyRepresentedType)953 TEST(HashTest, HashNonUniquelyRepresentedType) {
954   // Create equal StructWithPadding objects that are known to have non-equal
955   // padding bytes.
956   static const size_t kNumStructs = 10;
957   unsigned char buffer1[kNumStructs * sizeof(StructWithPadding)];
958   std::memset(buffer1, 0, sizeof(buffer1));
959   auto* s1 = reinterpret_cast<StructWithPadding*>(buffer1);
960 
961   unsigned char buffer2[kNumStructs * sizeof(StructWithPadding)];
962   std::memset(buffer2, 255, sizeof(buffer2));
963   auto* s2 = reinterpret_cast<StructWithPadding*>(buffer2);
964   for (size_t i = 0; i < kNumStructs; ++i) {
965     SCOPED_TRACE(i);
966     s1[i].c = s2[i].c = static_cast<char>('0' + i);
967     s1[i].i = s2[i].i = static_cast<int>(i);
968     ASSERT_FALSE(memcmp(buffer1 + i * sizeof(StructWithPadding),
969                         buffer2 + i * sizeof(StructWithPadding),
970                         sizeof(StructWithPadding)) == 0)
971         << "Bug in test code: objects do not have unequal"
972         << " object representations";
973   }
974 
975   EXPECT_EQ(Hash<StructWithPadding>()(s1[0]), Hash<StructWithPadding>()(s2[0]));
976   EXPECT_EQ(Hash<ArraySlice<StructWithPadding>>()({s1, s1 + kNumStructs}),
977             Hash<ArraySlice<StructWithPadding>>()({s2, s2 + kNumStructs}));
978 }
979 
TEST(HashTest,StandardHashContainerUsage)980 TEST(HashTest, StandardHashContainerUsage) {
981   std::unordered_map<int, std::string, Hash<int>> map = {{0, "foo"},
982                                                          {42, "bar"}};
983 
984   EXPECT_NE(map.find(0), map.end());
985   EXPECT_EQ(map.find(1), map.end());
986   EXPECT_NE(map.find(0u), map.end());
987 }
988 
989 struct ConvertibleFromNoOp {
ConvertibleFromNoOp__anon475069ff0411::ConvertibleFromNoOp990   ConvertibleFromNoOp(NoOp) {}  // NOLINT(runtime/explicit)
991 
992   template <typename H>
AbslHashValue(H hash_state,ConvertibleFromNoOp)993   friend H AbslHashValue(H hash_state, ConvertibleFromNoOp) {
994     return H::combine(std::move(hash_state), 1);
995   }
996 };
997 
TEST(HashTest,HeterogeneousCall)998 TEST(HashTest, HeterogeneousCall) {
999   EXPECT_NE(Hash<ConvertibleFromNoOp>()(NoOp()),
1000             Hash<NoOp>()(NoOp()));
1001 }
1002 
TEST(IsUniquelyRepresentedTest,SanityTest)1003 TEST(IsUniquelyRepresentedTest, SanityTest) {
1004   using absl::hash_internal::is_uniquely_represented;
1005 
1006   EXPECT_TRUE(is_uniquely_represented<unsigned char>::value);
1007   EXPECT_TRUE(is_uniquely_represented<int>::value);
1008   EXPECT_FALSE(is_uniquely_represented<bool>::value);
1009   EXPECT_FALSE(is_uniquely_represented<int*>::value);
1010 }
1011 
1012 struct IntAndString {
1013   int i;
1014   std::string s;
1015 
1016   template <typename H>
AbslHashValue(H hash_state,IntAndString int_and_string)1017   friend H AbslHashValue(H hash_state, IntAndString int_and_string) {
1018     return H::combine(std::move(hash_state), int_and_string.s,
1019                       int_and_string.i);
1020   }
1021 };
1022 
TEST(HashTest,SmallValueOn64ByteBoundary)1023 TEST(HashTest, SmallValueOn64ByteBoundary) {
1024   Hash<IntAndString>()(IntAndString{0, std::string(63, '0')});
1025 }
1026 
TEST(HashTest,TypeErased)1027 TEST(HashTest, TypeErased) {
1028   EXPECT_TRUE((is_hashable<TypeErasedValue<size_t>>::value));
1029   EXPECT_TRUE((is_hashable<std::pair<TypeErasedValue<size_t>, int>>::value));
1030 
1031   EXPECT_EQ(SpyHash(TypeErasedValue<size_t>(7)), SpyHash(size_t{7}));
1032   EXPECT_NE(SpyHash(TypeErasedValue<size_t>(7)), SpyHash(size_t{13}));
1033 
1034   EXPECT_EQ(SpyHash(std::make_pair(TypeErasedValue<size_t>(7), 17)),
1035             SpyHash(std::make_pair(size_t{7}, 17)));
1036 
1037   absl::flat_hash_set<absl::flat_hash_set<int>> ss = {{1, 2}, {3, 4}};
1038   TypeErasedContainer<absl::flat_hash_set<absl::flat_hash_set<int>>> es = {
1039       absl::flat_hash_set<int>{1, 2}, {3, 4}};
1040   absl::flat_hash_set<TypeErasedContainer<absl::flat_hash_set<int>>> se = {
1041       {1, 2}, {3, 4}};
1042   EXPECT_EQ(SpyHash(ss), SpyHash(es));
1043   EXPECT_EQ(SpyHash(ss), SpyHash(se));
1044 }
1045 
1046 struct ValueWithBoolConversion {
operator bool__anon475069ff0411::ValueWithBoolConversion1047   operator bool() const { return false; }
1048   int i;
1049 };
1050 
1051 }  // namespace
1052 namespace std {
1053 template <>
1054 struct hash<ValueWithBoolConversion> {
operator ()std::hash1055   size_t operator()(ValueWithBoolConversion v) {
1056     return static_cast<size_t>(v.i);
1057   }
1058 };
1059 }  // namespace std
1060 
1061 namespace {
1062 
TEST(HashTest,DoesNotUseImplicitConversionsToBool)1063 TEST(HashTest, DoesNotUseImplicitConversionsToBool) {
1064   EXPECT_NE(absl::Hash<ValueWithBoolConversion>()(ValueWithBoolConversion{0}),
1065             absl::Hash<ValueWithBoolConversion>()(ValueWithBoolConversion{1}));
1066 }
1067 
TEST(HashOf,MatchesHashForSingleArgument)1068 TEST(HashOf, MatchesHashForSingleArgument) {
1069   std::string s = "forty two";
1070   double d = 42.0;
1071   std::tuple<int, int> t{4, 2};
1072   int i = 42;
1073   int neg_i = -42;
1074   int16_t i16 = 42;
1075   int16_t neg_i16 = -42;
1076   int8_t i8 = 42;
1077   int8_t neg_i8 = -42;
1078 
1079   EXPECT_EQ(absl::HashOf(s), absl::Hash<std::string>{}(s));
1080   EXPECT_EQ(absl::HashOf(d), absl::Hash<double>{}(d));
1081   EXPECT_EQ(absl::HashOf(t), (absl::Hash<std::tuple<int, int>>{}(t)));
1082   EXPECT_EQ(absl::HashOf(i), absl::Hash<int>{}(i));
1083   EXPECT_EQ(absl::HashOf(neg_i), absl::Hash<int>{}(neg_i));
1084   EXPECT_EQ(absl::HashOf(i16), absl::Hash<int16_t>{}(i16));
1085   EXPECT_EQ(absl::HashOf(neg_i16), absl::Hash<int16_t>{}(neg_i16));
1086   EXPECT_EQ(absl::HashOf(i8), absl::Hash<int8_t>{}(i8));
1087   EXPECT_EQ(absl::HashOf(neg_i8), absl::Hash<int8_t>{}(neg_i8));
1088 }
1089 
TEST(HashOf,MatchesHashOfTupleForMultipleArguments)1090 TEST(HashOf, MatchesHashOfTupleForMultipleArguments) {
1091   std::string hello = "hello";
1092   std::string world = "world";
1093 
1094   EXPECT_EQ(absl::HashOf(), absl::HashOf(std::make_tuple()));
1095   EXPECT_EQ(absl::HashOf(hello), absl::HashOf(std::make_tuple(hello)));
1096   EXPECT_EQ(absl::HashOf(hello, world),
1097             absl::HashOf(std::make_tuple(hello, world)));
1098 }
1099 
1100 template <typename T>
1101 std::true_type HashOfExplicitParameter(decltype(absl::HashOf<T>(0))) {
1102   return {};
1103 }
1104 template <typename T>
HashOfExplicitParameter(size_t)1105 std::false_type HashOfExplicitParameter(size_t) {
1106   return {};
1107 }
1108 
TEST(HashOf,CantPassExplicitTemplateParameters)1109 TEST(HashOf, CantPassExplicitTemplateParameters) {
1110   EXPECT_FALSE(HashOfExplicitParameter<int>(0));
1111 }
1112 
1113 }  // namespace
1114