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