From a4cb1c8ba61531a63f9d309eea01ac1d43d8371d Mon Sep 17 00:00:00 2001 From: Abseil Team Date: Wed, 30 Jan 2019 10:59:43 -0800 Subject: Export of internal Abseil changes. -- 6fdf24a197b964f9bacbebd0ceca305aef1654fc by Shaindel Schwartz : Internal change PiperOrigin-RevId: 231627312 -- 65f7faf52bff01384171efb85fee159378dedf70 by CJ Johnson : Relocates the definitions of the InputIterator-accepting parts of the InlinedVector API into the top-level. The removed functions had no other callers so there was no reason to keep the layer of indirection in the form of the function call. PiperOrigin-RevId: 231527459 -- 30e105b749b5ecc50fdaf26c7da589617efce425 by CJ Johnson : Relocates closing brace for absl namespace in InlinedVector to the correct end location PiperOrigin-RevId: 231477871 -- 063c1e8b9d1f032662c46d574e20ecc357b87d0c by Eric Fiselier : Cleanup std::hash probing metafunctions. Previously there were two different ways to probe for std::hash. One in hash.h and another in type_traits.h, and they were both implemented differently, and neither correctly worked around bad STL implementations. This patch unifies the implementations into a single IsHashable trait. It also: * Correctly checks for old libc++ versions where this won't work. * Avoids undefined behavior which resulted from calling std::is_constructible incomplete types. * Unifies the feature test macro used in the headers and the tests. Additionally it also slightly changes the behavior of when absl::variant is hashable. Previously we disable hashing when std::hash()(key) was formed but when std::hash couldn't be destructed. This seems wrong. If a user provides a evil specialization of std::hash, then it's OK for variant's hash to blow up. PiperOrigin-RevId: 231468345 -- 05d75dd4b07c893de9b104731644d0d207b01253 by Abseil Team : Import of CCTZ from GitHub. PiperOrigin-RevId: 231397518 -- a0ee9032f9e04039f3410ed17fcf45ae1a3868f5 by CJ Johnson : Remove unused EnableIfAtLeastInputIterator from InlinedVector PiperOrigin-RevId: 231348903 -- 4dcd4e9a6780a81d7a6974c7bf22a037e6482b49 by Abseil Team : Remove unnecessary register keyword from absl/base/internal/endian.h. PiperOrigin-RevId: 231316570 -- c8584836caa3a10f90a8604a85d4b831310b72ee by Abseil Team : Fix hashtablez_sampler compilation on older Android NDK builds PiperOrigin-RevId: 231283542 GitOrigin-RevId: 6fdf24a197b964f9bacbebd0ceca305aef1654fc Change-Id: I185b12fb8347e3ad0ffcb2cbb83a53450e5eb938 --- absl/base/internal/endian.h | 2 +- absl/base/macros.h | 1 - absl/container/inlined_vector.h | 62 +--- absl/container/internal/hashtablez_sampler.cc | 2 +- absl/hash/hash_test.cc | 331 ++++++++++++++++++++- absl/hash/internal/hash.h | 19 +- absl/hash/internal/spy_hash_state.h | 2 +- absl/meta/type_traits.h | 72 ++++- .../internal/cctz/src/time_zone_lookup_test.cc | 2 +- absl/types/internal/variant.h | 3 +- absl/types/optional.h | 1 + absl/types/optional_test.cc | 21 +- absl/types/variant_test.cc | 35 +-- 13 files changed, 435 insertions(+), 118 deletions(-) diff --git a/absl/base/internal/endian.h b/absl/base/internal/endian.h index d5dc51ad..3f59184a 100644 --- a/absl/base/internal/endian.h +++ b/absl/base/internal/endian.h @@ -75,7 +75,7 @@ inline uint64_t gbswap_64(uint64_t host_int) { if (__builtin_constant_p(host_int)) { return __bswap_constant_64(host_int); } else { - register uint64_t result; + uint64_t result; __asm__("bswap %0" : "=r"(result) : "0"(host_int)); return result; } diff --git a/absl/base/macros.h b/absl/base/macros.h index 9e7ab375..5ed12cb0 100644 --- a/absl/base/macros.h +++ b/absl/base/macros.h @@ -24,7 +24,6 @@ // This code is compiled directly on many platforms, including client // platforms like Windows, Mac, and embedded systems. Before making // any changes here, make sure that you're not breaking any platforms. -// #ifndef ABSL_BASE_MACROS_H_ #define ABSL_BASE_MACROS_H_ diff --git a/absl/container/inlined_vector.h b/absl/container/inlined_vector.h index e0f1714c..493bd8eb 100644 --- a/absl/container/inlined_vector.h +++ b/absl/container/inlined_vector.h @@ -71,20 +71,11 @@ class InlinedVector { return static_cast(N); } - template - using IsAtLeastInputIterator = std::is_convertible< - typename std::iterator_traits::iterator_category, - std::input_iterator_tag>; - template using IsAtLeastForwardIterator = std::is_convertible< typename std::iterator_traits::iterator_category, std::forward_iterator_tag>; - template - using EnableIfAtLeastInputIterator = - absl::enable_if_t::value>; - template using EnableIfAtLeastForwardIterator = absl::enable_if_t::value>; @@ -163,7 +154,7 @@ class InlinedVector { InlinedVector(InputIterator first, InputIterator last, const allocator_type& alloc = allocator_type()) : allocator_and_tag_(alloc) { - AppendInputRange(first, last); + std::copy(first, last, std::back_inserter(*this)); } // Creates a copy of `other` using `other`'s allocator. @@ -534,7 +525,13 @@ class InlinedVector { template * = nullptr> void assign(InputIterator first, InputIterator last) { - AssignInputRange(first, last); + size_type assign_index = 0; + for (; (assign_index < size()) && (first != last); + static_cast(++assign_index), static_cast(++first)) { + *(data() + assign_index) = *first; + } + erase(data() + assign_index, data() + size()); + std::copy(first, last, std::back_inserter(*this)); } // `InlinedVector::resize()` @@ -630,7 +627,12 @@ class InlinedVector { template * = nullptr> iterator insert(const_iterator pos, InputIterator first, InputIterator last) { - return InsertWithInputRange(pos, first, last); + size_type initial_insert_index = std::distance(cbegin(), pos); + for (size_type insert_index = initial_insert_index; first != last; + static_cast(++insert_index), static_cast(++first)) { + insert(data() + insert_index, *first); + } + return iterator(data() + initial_insert_index); } // `InlinedVector::emplace()` @@ -1131,20 +1133,6 @@ class InlinedVector { } } - template - void AssignInputRange(InputIterator first, InputIterator last) { - static_assert(IsAtLeastInputIterator::value, ""); - - // Optimized to avoid reallocation. - // Prefer reassignment to copy construction for elements. - iterator out = begin(); - for (; first != last && out != end(); ++first, ++out) { - *out = *first; - } - erase(out, end()); - std::copy(first, last, std::back_inserter(*this)); - } - template void AppendForwardRange(ForwardIterator first, ForwardIterator last) { static_assert(IsAtLeastForwardIterator::value, ""); @@ -1160,13 +1148,6 @@ class InlinedVector { } } - template - void AppendInputRange(InputIterator first, InputIterator last) { - static_assert(IsAtLeastInputIterator::value, ""); - - std::copy(first, last, std::back_inserter(*this)); - } - iterator InsertWithCount(const_iterator position, size_type n, const_reference v) { assert(position >= begin() && position <= end()); @@ -1198,18 +1179,6 @@ class InlinedVector { return it_pair.first; } - template - iterator InsertWithInputRange(const_iterator position, InputIterator first, - InputIterator last) { - static_assert(IsAtLeastInputIterator::value, ""); - assert(position >= begin() && position <= end()); - - size_type index = position - cbegin(); - size_type i = index; - while (first != last) insert(begin() + i++, *first++); - return begin() + index; - } - void SwapImpl(InlinedVector& other) { using std::swap; // Augment ADL with `std::swap`. @@ -1393,6 +1362,7 @@ auto AbslHashValue(H h, const InlinedVector& v) -> H { auto n = v.size(); return H::combine(H::combine_contiguous(std::move(h), p, n), n); } +} // namespace absl // ----------------------------------------------------------------------------- // Implementation of InlinedVector @@ -1400,6 +1370,4 @@ auto AbslHashValue(H h, const InlinedVector& v) -> H { // Do not depend on any below implementation details! // ----------------------------------------------------------------------------- -} // namespace absl - #endif // ABSL_CONTAINER_INLINED_VECTOR_H_ diff --git a/absl/container/internal/hashtablez_sampler.cc b/absl/container/internal/hashtablez_sampler.cc index 7c411140..99cd8344 100644 --- a/absl/container/internal/hashtablez_sampler.cc +++ b/absl/container/internal/hashtablez_sampler.cc @@ -93,7 +93,7 @@ int64_t GetGeometricVariable(int64_t mean) { // under piii debug for some binaries. double q = static_cast(rng >> (prng_mod_power - 26)) + 1.0; // Put the computed p-value through the CDF of a geometric. - double interval = (std::log2(q) - 26) * (-std::log(2.0) * mean); + double interval = (log2(q) - 26) * (-std::log(2.0) * mean); // Very large values of interval overflow int64_t. If we happen to // hit such improbable condition, we simply cheat and clamp interval diff --git a/absl/hash/hash_test.cc b/absl/hash/hash_test.cc index 224832b1..a5af93ad 100644 --- a/absl/hash/hash_test.cc +++ b/absl/hash/hash_test.cc @@ -15,6 +15,7 @@ #include "absl/hash/hash.h" #include +#include #include #include #include @@ -84,6 +85,327 @@ using IntTypes = testing::Types; INSTANTIATE_TYPED_TEST_CASE_P(My, HashValueIntTest, IntTypes); +enum LegacyEnum { kValue1, kValue2, kValue3 }; + +enum class EnumClass { kValue4, kValue5, kValue6 }; + +TEST(HashValueTest, EnumAndBool) { + EXPECT_TRUE((is_hashable::value)); + EXPECT_TRUE((is_hashable::value)); + EXPECT_TRUE((is_hashable::value)); + + EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple( + LegacyEnum::kValue1, LegacyEnum::kValue2, LegacyEnum::kValue3))); + EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple( + EnumClass::kValue4, EnumClass::kValue5, EnumClass::kValue6))); + EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly( + std::make_tuple(true, false))); +} + +TEST(HashValueTest, FloatingPoint) { + EXPECT_TRUE((is_hashable::value)); + EXPECT_TRUE((is_hashable::value)); + EXPECT_TRUE((is_hashable::value)); + + EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly( + std::make_tuple(42.f, 0.f, -0.f, std::numeric_limits::infinity(), + -std::numeric_limits::infinity()))); + + EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly( + std::make_tuple(42., 0., -0., std::numeric_limits::infinity(), + -std::numeric_limits::infinity()))); + + EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple( + // Add some values with small exponent to test that NORMAL values also + // append their category. + .5L, 1.L, 2.L, 4.L, 42.L, 0.L, -0.L, + 17 * static_cast(std::numeric_limits::max()), + std::numeric_limits::infinity(), + -std::numeric_limits::infinity()))); +} + +TEST(HashValueTest, Pointer) { + EXPECT_TRUE((is_hashable::value)); + + int i; + int* ptr = &i; + int* n = nullptr; + + EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly( + std::make_tuple(&i, ptr, nullptr, ptr + 1, n))); +} + +// TODO(EricWF): MSVC 15 has a bug that causes it to incorrectly evaluate the +// SFINAE in internal/hash.h, causing this test to fail. +#if !defined(_MSC_VER) +TEST(HashValueTest, PairAndTuple) { + EXPECT_TRUE((is_hashable>::value)); + EXPECT_TRUE((is_hashable>::value)); + EXPECT_TRUE((is_hashable>::value)); + EXPECT_TRUE((is_hashable>::value)); + + EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple( + std::make_pair(0, 42), std::make_pair(0, 42), std::make_pair(42, 0), + std::make_pair(0, 0), std::make_pair(42, 42), std::make_pair(1, 42)))); + + EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly( + std::make_tuple(std::make_tuple(0, 0, 0), std::make_tuple(0, 0, 42), + std::make_tuple(0, 23, 0), std::make_tuple(17, 0, 0), + std::make_tuple(42, 0, 0), std::make_tuple(3, 9, 9), + std::make_tuple(0, 0, -42)))); + + // Test that tuples of lvalue references work (so we need a few lvalues): + int a = 0, b = 1, c = 17, d = 23; + EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple( + std::tie(a, a), std::tie(a, b), std::tie(b, c), std::tie(c, d)))); + + // Test that tuples of rvalue references work: + EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple( + std::forward_as_tuple(0, 0, 0), std::forward_as_tuple(0, 0, 42), + std::forward_as_tuple(0, 23, 0), std::forward_as_tuple(17, 0, 0), + std::forward_as_tuple(42, 0, 0), std::forward_as_tuple(3, 9, 9), + std::forward_as_tuple(0, 0, -42)))); +} +#endif // !defined(_MSC_VER) + +TEST(HashValueTest, CombineContiguousWorks) { + std::vector> v1 = {std::make_tuple(1), std::make_tuple(3)}; + std::vector> v2 = {std::make_tuple(1), std::make_tuple(2)}; + + auto vh1 = SpyHash(v1); + auto vh2 = SpyHash(v2); + EXPECT_NE(vh1, vh2); +} + +struct DummyDeleter { + template + void operator() (T* ptr) {} +}; + +struct SmartPointerEq { + template + bool operator()(const T& t, const U& u) const { + return GetPtr(t) == GetPtr(u); + } + + template + static auto GetPtr(const T& t) -> decltype(&*t) { + return t ? &*t : nullptr; + } + + static std::nullptr_t GetPtr(std::nullptr_t) { return nullptr; } +}; + +TEST(HashValueTest, SmartPointers) { + EXPECT_TRUE((is_hashable>::value)); + EXPECT_TRUE((is_hashable>::value)); + EXPECT_TRUE((is_hashable>::value)); + + int i, j; + std::unique_ptr unique1(&i); + std::unique_ptr unique2(&i); + std::unique_ptr unique_other(&j); + std::unique_ptr unique_null; + + std::shared_ptr shared1(&i, DummyDeleter()); + std::shared_ptr shared2(&i, DummyDeleter()); + std::shared_ptr shared_other(&j, DummyDeleter()); + std::shared_ptr shared_null; + + // Sanity check of the Eq function. + ASSERT_TRUE(SmartPointerEq{}(unique1, shared1)); + ASSERT_FALSE(SmartPointerEq{}(unique1, shared_other)); + ASSERT_TRUE(SmartPointerEq{}(unique_null, nullptr)); + ASSERT_FALSE(SmartPointerEq{}(shared2, nullptr)); + + EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly( + std::forward_as_tuple(&i, nullptr, // + unique1, unique2, unique_null, // + absl::make_unique(), // + shared1, shared2, shared_null, // + std::make_shared()), + SmartPointerEq{})); +} + +TEST(HashValueTest, FunctionPointer) { + using Func = int (*)(); + EXPECT_TRUE(is_hashable::value); + + Func p1 = [] { return 2; }, p2 = [] { return 1; }; + EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly( + std::make_tuple(p1, p2, nullptr))); +} + +struct WrapInTuple { + template + std::tuple operator()(const T& t) const { + return std::make_tuple(7, t, 0xdeadbeef); + } +}; + +TEST(HashValueTest, Strings) { + EXPECT_TRUE((is_hashable::value)); + EXPECT_TRUE((is_hashable::value)); + + const std::string small = "foo"; + const std::string dup = "foofoo"; + const std::string large = "large"; + const std::string huge = std::string(5000, 'a'); + EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple( + std::string(), absl::string_view(), + std::string(""), absl::string_view(""), + std::string(small), absl::string_view(small), + std::string(dup), absl::string_view(dup), + std::string(large), absl::string_view(large), + std::string(huge), absl::string_view(huge)))); + + // Also check that nested types maintain the same hash. + const WrapInTuple t{}; + EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple( + // + t(std::string()), t(absl::string_view()), + t(std::string("")), t(absl::string_view("")), + t(std::string(small)), t(absl::string_view(small)), + t(std::string(dup)), t(absl::string_view(dup)), + t(std::string(large)), t(absl::string_view(large)), + t(std::string(huge)), t(absl::string_view(huge))))); + + // Make sure that hashing a `const char*` does not use its std::string-value. + EXPECT_NE(SpyHash(static_cast("ABC")), + SpyHash(absl::string_view("ABC"))); +} + +// TODO(EricWF): MSVC 15 has a bug that causes it to incorrectly evaluate the +// SFINAE in internal/hash.h, causing this test to fail. +#if !defined(_MSC_VER) +TEST(HashValueTest, StdArray) { + EXPECT_TRUE((is_hashable>::value)); + + EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly( + std::make_tuple(std::array{}, std::array{{0, 23, 42}}))); +} +#endif // !defined(_MSC_VER) + +TEST(HashValueTest, StdBitset) { + EXPECT_TRUE((is_hashable>::value)); + + EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly( + {std::bitset<2>("00"), std::bitset<2>("01"), std::bitset<2>("10"), + std::bitset<2>("11")})); + EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly( + {std::bitset<5>("10101"), std::bitset<5>("10001"), std::bitset<5>()})); + + constexpr int kNumBits = 256; + std::array bit_strings; + bit_strings.fill(std::string(kNumBits, '1')); + bit_strings[1][0] = '0'; + bit_strings[2][1] = '0'; + bit_strings[3][kNumBits / 3] = '0'; + bit_strings[4][kNumBits - 2] = '0'; + bit_strings[5][kNumBits - 1] = '0'; + EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly( + {std::bitset(bit_strings[0].c_str()), + std::bitset(bit_strings[1].c_str()), + std::bitset(bit_strings[2].c_str()), + std::bitset(bit_strings[3].c_str()), + std::bitset(bit_strings[4].c_str()), + std::bitset(bit_strings[5].c_str())})); +} // namespace + +template +class HashValueSequenceTest : public testing::Test { +}; +TYPED_TEST_SUITE_P(HashValueSequenceTest); + +TYPED_TEST_P(HashValueSequenceTest, BasicUsage) { + EXPECT_TRUE((is_hashable::value)); + + using ValueType = typename TypeParam::value_type; + auto a = static_cast(0); + auto b = static_cast(23); + auto c = static_cast(42); + + EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly( + std::make_tuple(TypeParam(), TypeParam{}, TypeParam{a, b, c}, + TypeParam{a, b}, TypeParam{b, c}))); +} + +REGISTER_TYPED_TEST_CASE_P(HashValueSequenceTest, BasicUsage); +using IntSequenceTypes = + testing::Types, std::forward_list, std::list, + std::vector, std::vector, std::set, + std::multiset>; +INSTANTIATE_TYPED_TEST_CASE_P(My, HashValueSequenceTest, IntSequenceTypes); + +// Private type that only supports AbslHashValue to make sure our chosen hash +// implentation is recursive within absl::Hash. +// It uses std::abs() on the value to provide different bitwise representations +// of the same logical value. +struct Private { + int i; + template + friend H AbslHashValue(H h, Private p) { + return H::combine(std::move(h), std::abs(p.i)); + } + + friend bool operator==(Private a, Private b) { + return std::abs(a.i) == std::abs(b.i); + } + + friend std::ostream& operator<<(std::ostream& o, Private p) { + return o << p.i; + } +}; + +TEST(HashValueTest, PrivateSanity) { + // Sanity check that Private is working as the tests below expect it to work. + EXPECT_TRUE(is_hashable::value); + EXPECT_NE(SpyHash(Private{0}), SpyHash(Private{1})); + EXPECT_EQ(SpyHash(Private{1}), SpyHash(Private{1})); +} + +TEST(HashValueTest, Optional) { + EXPECT_TRUE(is_hashable>::value); + + using O = absl::optional; + EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly( + std::make_tuple(O{}, O{{1}}, O{{-1}}, O{{10}}))); +} + +TEST(HashValueTest, Variant) { + using V = absl::variant; + EXPECT_TRUE(is_hashable::value); + + EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple( + V(Private{1}), V(Private{-1}), V(Private{2}), V("ABC"), V("BCD")))); + +#if ABSL_META_INTERNAL_STD_HASH_SFINAE_FRIENDLY_ + struct S {}; + EXPECT_FALSE(is_hashable>::value); +#endif +} + +// TODO(EricWF): MSVC 15 has a bug that causes it to incorrectly evaluate the +// SFINAE in internal/hash.h, causing this test to fail. +#if !defined(_MSC_VER) +TEST(HashValueTest, Maps) { + EXPECT_TRUE((is_hashable>::value)); + + using M = std::map; + EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple( + M{}, M{{0, "foo"}}, M{{1, "foo"}}, M{{0, "bar"}}, M{{1, "bar"}}, + M{{0, "foo"}, {42, "bar"}}, M{{1, "foo"}, {42, "bar"}}, + M{{1, "foo"}, {43, "bar"}}, M{{1, "foo"}, {43, "baz"}}))); + + using MM = std::multimap; + EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(std::make_tuple( + MM{}, MM{{0, "foo"}}, MM{{1, "foo"}}, MM{{0, "bar"}}, MM{{1, "bar"}}, + MM{{0, "foo"}, {0, "bar"}}, MM{{0, "bar"}, {0, "foo"}}, + MM{{0, "foo"}, {42, "bar"}}, MM{{1, "foo"}, {42, "bar"}}, + MM{{1, "foo"}, {1, "foo"}, {43, "bar"}}, MM{{1, "foo"}, {43, "baz"}}))); +} +#endif // !defined(_MSC_VER) + template struct IsHashCallble : std::false_type {}; @@ -108,7 +430,8 @@ TEST(IsHashableTest, ValidHash) { EXPECT_TRUE(IsHashCallble::value); EXPECT_TRUE(IsAggregateInitializable>::value); } -#if ABSL_HASH_INTERNAL_CAN_POISON_ && !defined(__APPLE__) + +#if ABSL_META_INTERNAL_STD_HASH_SFINAE_FRIENDLY_ TEST(IsHashableTest, PoisonHash) { struct X {}; EXPECT_FALSE((is_hashable::value)); @@ -120,7 +443,7 @@ TEST(IsHashableTest, PoisonHash) { EXPECT_FALSE(IsHashCallble::value); EXPECT_FALSE(IsAggregateInitializable>::value); } -#endif // ABSL_HASH_INTERNAL_CAN_POISON_ +#endif // ABSL_META_INTERNAL_STD_HASH_SFINAE_FRIENDLY_ // Hashable types // @@ -245,13 +568,13 @@ void TestCustomHashType(InvokeTagConstant, T...) { } void TestCustomHashType(InvokeTagConstant) { -#if ABSL_HASH_INTERNAL_CAN_POISON_ +#if ABSL_META_INTERNAL_STD_HASH_SFINAE_FRIENDLY_ // is_hashable is false if we don't support any of the hooks. using type = CustomHashType<>; EXPECT_FALSE(is_hashable()); EXPECT_FALSE(is_hashable()); EXPECT_FALSE(is_hashable()); -#endif // ABSL_HASH_INTERNAL_CAN_POISON_ +#endif // ABSL_META_INTERNAL_STD_HASH_SFINAE_FRIENDLY_ } template diff --git a/absl/hash/internal/hash.h b/absl/hash/internal/hash.h index 6c00f354..ba6d7468 100644 --- a/absl/hash/internal/hash.h +++ b/absl/hash/internal/hash.h @@ -541,17 +541,8 @@ hash_range_or_bytes(H hash_state, const T* data, size_t size) { // * If is_uniquely_represented, hash bytes directly. // * ADL AbslHashValue(H, const T&) call. // * std::hash - -// In MSVC we can't probe std::hash or stdext::hash because it triggers a -// static_assert instead of failing substitution. -#if defined(_MSC_VER) -#define ABSL_HASH_INTERNAL_CAN_POISON_ 0 -#else // _MSC_VER -#define ABSL_HASH_INTERNAL_CAN_POISON_ 1 -#endif // _MSC_VER - #if defined(ABSL_INTERNAL_LEGACY_HASH_NAMESPACE) && \ - ABSL_HASH_INTERNAL_CAN_POISON_ + ABSL_META_INTERNAL_STD_HASH_SFINAE_FRIENDLY_ #define ABSL_HASH_INTERNAL_SUPPORT_LEGACY_HASH_ 1 #else #define ABSL_HASH_INTERNAL_SUPPORT_LEGACY_HASH_ 0 @@ -616,13 +607,7 @@ struct HashSelect { #endif // ABSL_HASH_INTERNAL_SUPPORT_LEGACY_HASH_ template - using ProbeStdHash = -#if ABSL_HASH_INTERNAL_CAN_POISON_ - std::is_convertible()(std::declval())), - size_t>; -#else // ABSL_HASH_INTERNAL_CAN_POISON_ - std::true_type; -#endif // ABSL_HASH_INTERNAL_CAN_POISON_ + using ProbeStdHash = absl::type_traits_internal::IsHashable; template using ProbeNone = std::true_type; diff --git a/absl/hash/internal/spy_hash_state.h b/absl/hash/internal/spy_hash_state.h index 03d795b0..e7d1dfef 100644 --- a/absl/hash/internal/spy_hash_state.h +++ b/absl/hash/internal/spy_hash_state.h @@ -200,7 +200,7 @@ bool RunOnStartup::run = (f(), true); template < typename T, typename U, // Only trigger for when (T != U), - absl::enable_if_t::value, int> = 0, + typename = absl::enable_if_t::value>, // This statement works in two ways: // - First, it instantiates RunOnStartup and forces the initialization of // `run`, which set the global variable. diff --git a/absl/meta/type_traits.h b/absl/meta/type_traits.h index 23ebd6ed..88853974 100644 --- a/absl/meta/type_traits.h +++ b/absl/meta/type_traits.h @@ -413,21 +413,73 @@ template using result_of_t = typename std::result_of::type; namespace type_traits_internal { +// In MSVC we can't probe std::hash or stdext::hash because it triggers a +// static_assert instead of failing substitution. Libc++ prior to 4.0 +// also used a static_assert. +// +#if defined(_MSC_VER) || (defined(_LIBCPP_VERSION) && \ + _LIBCPP_VERSION < 4000 && _LIBCPP_STD_VER > 11) +#define ABSL_META_INTERNAL_STD_HASH_SFINAE_FRIENDLY_ 0 +#else +#define ABSL_META_INTERNAL_STD_HASH_SFINAE_FRIENDLY_ 1 +#endif + +#if !ABSL_META_INTERNAL_STD_HASH_SFINAE_FRIENDLY_ template +struct IsHashable : std::true_type {}; +#else // ABSL_META_INTERNAL_STD_HASH_SFINAE_FRIENDLY_ +template struct IsHashable : std::false_type {}; template -struct IsHashable>()(std::declval()))> - : std::true_type {}; +struct IsHashable< + Key, + absl::enable_if_t&>()(std::declval())), + std::size_t>::value>> : std::true_type {}; +#endif // !ABSL_META_INTERNAL_STD_HASH_SFINAE_FRIENDLY_ + +struct AssertHashEnabledHelper { + private: + static void Sink(...) {} + struct NAT {}; + + template + static auto GetReturnType(int) + -> decltype(std::declval>()(std::declval())); + template + static NAT GetReturnType(...); + + template + static std::nullptr_t DoIt() { + static_assert(IsHashable::value, + "std::hash does not provide a call operator"); + static_assert( + std::is_default_constructible>::value, + "std::hash must be default constructible when it is enabled"); + static_assert( + std::is_copy_constructible>::value, + "std::hash must be copy constructible when it is enabled"); + static_assert(absl::is_copy_assignable>::value, + "std::hash must be copy assignable when it is enabled"); + // is_destructible is unchecked as it's implied by each of the + // is_constructible checks. + using ReturnType = decltype(GetReturnType(0)); + static_assert(std::is_same::value || + std::is_same::value, + "std::hash must return size_t"); + return nullptr; + } + + template + friend void AssertHashEnabled(); +}; -template -struct IsHashEnabled - : absl::conjunction>, - std::is_copy_constructible>, - std::is_destructible>, - absl::is_copy_assignable>, - IsHashable> {}; +template +inline void AssertHashEnabled() { + using Helper = AssertHashEnabledHelper; + Helper::Sink(Helper::DoIt()...); +} } // namespace type_traits_internal diff --git a/absl/time/internal/cctz/src/time_zone_lookup_test.cc b/absl/time/internal/cctz/src/time_zone_lookup_test.cc index 3dca822c..2e49e48c 100644 --- a/absl/time/internal/cctz/src/time_zone_lookup_test.cc +++ b/absl/time/internal/cctz/src/time_zone_lookup_test.cc @@ -1021,7 +1021,7 @@ TEST(MakeTime, LocalTimeLibC) { // 1) we know how to change the time zone used by localtime()/mktime(), // 2) cctz and localtime()/mktime() will use similar-enough tzdata, and // 3) we have some idea about how mktime() behaves during transitions. -#if defined(__linux__) +#if defined(__linux__) && !defined(__ANDROID__) const char* const ep = getenv("TZ"); std::string tz_name = (ep != nullptr) ? ep : ""; for (const char* const* np = kTimeZoneNames; *np != nullptr; ++np) { diff --git a/absl/types/internal/variant.h b/absl/types/internal/variant.h index 477e5895..a0ab1e8f 100644 --- a/absl/types/internal/variant.h +++ b/absl/types/internal/variant.h @@ -1605,11 +1605,12 @@ struct VariantHashVisitor { template struct VariantHashBase...>::value>, + type_traits_internal::IsHashable...>::value>, Ts...> { using argument_type = Variant; using result_type = size_t; size_t operator()(const Variant& var) const { + type_traits_internal::AssertHashEnabled(); if (var.valueless_by_exception()) { return 239799884; } diff --git a/absl/types/optional.h b/absl/types/optional.h index 7677fe52..fd185f35 100644 --- a/absl/types/optional.h +++ b/absl/types/optional.h @@ -467,6 +467,7 @@ struct optional_hash_base >()( using argument_type = absl::optional; using result_type = size_t; size_t operator()(const absl::optional& opt) const { + absl::type_traits_internal::AssertHashEnabled>(); if (opt) { return std::hash >()(*opt); } else { diff --git a/absl/types/optional_test.cc b/absl/types/optional_test.cc index fc4f00a4..bedf5b0e 100644 --- a/absl/types/optional_test.cc +++ b/absl/types/optional_test.cc @@ -1504,18 +1504,19 @@ TEST(optionalTest, Hash) { static_assert(is_hash_enabled_for>::value, ""); static_assert(is_hash_enabled_for>::value, ""); + static_assert( + absl::type_traits_internal::IsHashable>::value, ""); + static_assert( + absl::type_traits_internal::IsHashable>::value, + ""); + absl::type_traits_internal::AssertHashEnabled>(); + absl::type_traits_internal::AssertHashEnabled>(); -#if defined(_MSC_VER) || (defined(_LIBCPP_VERSION) && \ - _LIBCPP_VERSION < 4000 && _LIBCPP_STD_VER > 11) - // For MSVC and libc++ (< 4.0 and c++14), std::hash primary template has a - // static_assert to catch any user-defined type that doesn't provide a hash - // specialization. So instantiating std::hash> will result - // in a hard error which is not SFINAE friendly. -#define ABSL_STD_HASH_NOT_SFINAE_FRIENDLY 1 -#endif - -#ifndef ABSL_STD_HASH_NOT_SFINAE_FRIENDLY +#if ABSL_META_INTERNAL_STD_HASH_SFINAE_FRIENDLY_ static_assert(!is_hash_enabled_for>::value, ""); + static_assert(!absl::type_traits_internal::IsHashable< + absl::optional>::value, + ""); #endif // libstdc++ std::optional is missing remove_const_t, i.e. it's using diff --git a/absl/types/variant_test.cc b/absl/types/variant_test.cc index 80e8467e..463d775a 100644 --- a/absl/types/variant_test.cc +++ b/absl/types/variant_test.cc @@ -1977,29 +1977,17 @@ TEST(VariantTest, MonostateHash) { } TEST(VariantTest, Hash) { - static_assert(type_traits_internal::IsHashEnabled>::value, ""); - static_assert(type_traits_internal::IsHashEnabled>::value, + static_assert(type_traits_internal::IsHashable>::value, ""); + static_assert(type_traits_internal::IsHashable>::value, ""); + static_assert(type_traits_internal::IsHashable>::value, ""); - static_assert( - type_traits_internal::IsHashEnabled>::value, ""); - -#if defined(_MSC_VER) || \ - (defined(_LIBCPP_VERSION) && _LIBCPP_VERSION < 4000 && \ - _LIBCPP_STD_VER > 11) || \ - defined(__APPLE__) - // For MSVC and libc++ (< 4.0 and c++14), std::hash primary template has a - // static_assert to catch any user-defined type T that doesn't provide a hash - // specialization. So instantiating std::hash> will result - // in a hard error which is not SFINAE friendly. -#define ABSL_STD_HASH_NOT_SFINAE_FRIENDLY 1 -#endif -#ifndef ABSL_STD_HASH_NOT_SFINAE_FRIENDLY - static_assert( - !type_traits_internal::IsHashEnabled>::value, ""); - static_assert(!type_traits_internal::IsHashEnabled< - variant>::value, +#if ABSL_META_INTERNAL_STD_HASH_SFINAE_FRIENDLY_ + static_assert(!type_traits_internal::IsHashable>::value, ""); + static_assert( + !type_traits_internal::IsHashable>::value, + ""); #endif // MSVC std::hash does not use the index, thus produce the same @@ -2023,11 +2011,10 @@ TEST(VariantTest, Hash) { EXPECT_GT(hashcodes.size(), 90); // test const-qualified + static_assert(type_traits_internal::IsHashable>::value, + ""); static_assert( - type_traits_internal::IsHashEnabled>::value, ""); - static_assert( - type_traits_internal::IsHashEnabled>::value, - ""); + type_traits_internal::IsHashable>::value, ""); std::hash> c_hash; for (int i = 0; i < 100; ++i) { EXPECT_EQ(hash(i), c_hash(i)); -- cgit v1.2.3