Abseil Common Libraries (C++) (grcp 依赖) https://abseil.io/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

796 lines
27 KiB

// Copyright 2018 The Abseil Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "absl/hash/hash.h"
#include <array>
Export of internal Abseil changes. -- 6fdf24a197b964f9bacbebd0ceca305aef1654fc by Shaindel Schwartz <shaindel@google.com>: Internal change PiperOrigin-RevId: 231627312 -- 65f7faf52bff01384171efb85fee159378dedf70 by CJ Johnson <johnsoncj@google.com>: 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 <johnsoncj@google.com>: Relocates closing brace for absl namespace in InlinedVector to the correct end location PiperOrigin-RevId: 231477871 -- 063c1e8b9d1f032662c46d574e20ecc357b87d0c by Eric Fiselier <ericwf@google.com>: 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<T>()(key) was formed but when std::hash<T> 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 <absl-team@google.com>: Import of CCTZ from GitHub. PiperOrigin-RevId: 231397518 -- a0ee9032f9e04039f3410ed17fcf45ae1a3868f5 by CJ Johnson <johnsoncj@google.com>: Remove unused EnableIfAtLeastInputIterator from InlinedVector PiperOrigin-RevId: 231348903 -- 4dcd4e9a6780a81d7a6974c7bf22a037e6482b49 by Abseil Team <absl-team@google.com>: Remove unnecessary register keyword from absl/base/internal/endian.h. PiperOrigin-RevId: 231316570 -- c8584836caa3a10f90a8604a85d4b831310b72ee by Abseil Team <absl-team@google.com>: Fix hashtablez_sampler compilation on older Android NDK builds PiperOrigin-RevId: 231283542 GitOrigin-RevId: 6fdf24a197b964f9bacbebd0ceca305aef1654fc Change-Id: I185b12fb8347e3ad0ffcb2cbb83a53450e5eb938
6 years ago
#include <bitset>
#include <cstring>
#include <deque>
#include <forward_list>
#include <functional>
#include <iterator>
#include <limits>
#include <list>
#include <map>
#include <memory>
#include <numeric>
#include <random>
#include <set>
#include <string>
#include <tuple>
#include <type_traits>
#include <unordered_map>
#include <utility>
#include <vector>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/container/flat_hash_set.h"
#include "absl/hash/hash_testing.h"
#include "absl/hash/internal/spy_hash_state.h"
#include "absl/meta/type_traits.h"
#include "absl/numeric/int128.h"
namespace {
using absl::Hash;
using absl::hash_internal::SpyHashState;
template <typename T>
class HashValueIntTest : public testing::Test {
};
TYPED_TEST_SUITE_P(HashValueIntTest);
template <typename T>
SpyHashState SpyHash(const T& value) {
return SpyHashState::combine(SpyHashState(), value);
}
// Helper trait to verify if T is hashable. We use absl::Hash's poison status to
// detect it.
template <typename T>
using is_hashable = std::is_default_constructible<absl::Hash<T>>;
TYPED_TEST_P(HashValueIntTest, BasicUsage) {
EXPECT_TRUE((is_hashable<TypeParam>::value));
TypeParam n = 42;
EXPECT_EQ(SpyHash(n), SpyHash(TypeParam{42}));
EXPECT_NE(SpyHash(n), SpyHash(TypeParam{0}));
EXPECT_NE(SpyHash(std::numeric_limits<TypeParam>::max()),
SpyHash(std::numeric_limits<TypeParam>::min()));
}
TYPED_TEST_P(HashValueIntTest, FastPath) {
// Test the fast-path to make sure the values are the same.
TypeParam n = 42;
EXPECT_EQ(absl::Hash<TypeParam>{}(n),
absl::Hash<std::tuple<TypeParam>>{}(std::tuple<TypeParam>(n)));
}
REGISTER_TYPED_TEST_CASE_P(HashValueIntTest, BasicUsage, FastPath);
using IntTypes = testing::Types<unsigned char, char, int, int32_t, int64_t, uint32_t,
uint64_t, size_t>;
INSTANTIATE_TYPED_TEST_CASE_P(My, HashValueIntTest, IntTypes);
Export of internal Abseil changes. -- 6fdf24a197b964f9bacbebd0ceca305aef1654fc by Shaindel Schwartz <shaindel@google.com>: Internal change PiperOrigin-RevId: 231627312 -- 65f7faf52bff01384171efb85fee159378dedf70 by CJ Johnson <johnsoncj@google.com>: 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 <johnsoncj@google.com>: Relocates closing brace for absl namespace in InlinedVector to the correct end location PiperOrigin-RevId: 231477871 -- 063c1e8b9d1f032662c46d574e20ecc357b87d0c by Eric Fiselier <ericwf@google.com>: 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<T>()(key) was formed but when std::hash<T> 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 <absl-team@google.com>: Import of CCTZ from GitHub. PiperOrigin-RevId: 231397518 -- a0ee9032f9e04039f3410ed17fcf45ae1a3868f5 by CJ Johnson <johnsoncj@google.com>: Remove unused EnableIfAtLeastInputIterator from InlinedVector PiperOrigin-RevId: 231348903 -- 4dcd4e9a6780a81d7a6974c7bf22a037e6482b49 by Abseil Team <absl-team@google.com>: Remove unnecessary register keyword from absl/base/internal/endian.h. PiperOrigin-RevId: 231316570 -- c8584836caa3a10f90a8604a85d4b831310b72ee by Abseil Team <absl-team@google.com>: Fix hashtablez_sampler compilation on older Android NDK builds PiperOrigin-RevId: 231283542 GitOrigin-RevId: 6fdf24a197b964f9bacbebd0ceca305aef1654fc Change-Id: I185b12fb8347e3ad0ffcb2cbb83a53450e5eb938
6 years ago
enum LegacyEnum { kValue1, kValue2, kValue3 };
enum class EnumClass { kValue4, kValue5, kValue6 };
TEST(HashValueTest, EnumAndBool) {
EXPECT_TRUE((is_hashable<LegacyEnum>::value));
EXPECT_TRUE((is_hashable<EnumClass>::value));
EXPECT_TRUE((is_hashable<bool>::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<float>::value));
EXPECT_TRUE((is_hashable<double>::value));
EXPECT_TRUE((is_hashable<long double>::value));
EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(
std::make_tuple(42.f, 0.f, -0.f, std::numeric_limits<float>::infinity(),
-std::numeric_limits<float>::infinity())));
EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(
std::make_tuple(42., 0., -0., std::numeric_limits<double>::infinity(),
-std::numeric_limits<double>::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<long double>(std::numeric_limits<double>::max()),
std::numeric_limits<long double>::infinity(),
-std::numeric_limits<long double>::infinity())));
}
TEST(HashValueTest, Pointer) {
EXPECT_TRUE((is_hashable<int*>::value));
int i;
int* ptr = &i;
int* n = nullptr;
EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(
std::make_tuple(&i, ptr, nullptr, ptr + 1, n)));
}
Export of internal Abseil changes. -- 3d20ce6cd6541579abecaba169d4b8716d511272 by Jon Cohen <cohenjon@google.com>: Only use LSAN for clang version >= 3.5. This should fix https://github.com/abseil/abseil-cpp/issues/244 PiperOrigin-RevId: 234675129 -- e15bd4ec7a81aa95cc3d09fa1e0e81d58ae478fb by Conrad Parker <conradparker@google.com>: Fix errors in apply() sample code The following changes are made: * Make the example method public. * Give the two user functions different names to avoid confusion about whether apply() can select the correct overload of a function based on its tuple argument (it can't). * Pass tuple2 to the second example apply() invocation, instead of passing its contents individually. * Fix a s/tuple/tuple3/ typo in the third example apply() invocation. PiperOrigin-RevId: 234223407 -- de0ed71e21bc76ddf9fe715fdbaef74cd0df95c7 by Abseil Team <absl-team@google.com>: First test if a macro is defined to avoid -Wundef. ABSL clients may need to compile their code with the -Wundef warning flag. It will be helpful if ABSL header files can be compiled without the -Wundef warning. How to avoid the -Wundef warning: If a macro may be undefined, we need to first test whether the macro is defined before testing its value. We can't rely on the C preprocessor rule that an undefined macro has the value 0L. PiperOrigin-RevId: 234201123 -- fa484ad7dae0cac21140a96662809ecb0ec8eb5d by Abseil Team <absl-team@google.com>: Internal change. PiperOrigin-RevId: 234185697 -- d69b1baef681e27954b065375ecf9c2320463b2b by Samuel Benzaquen <sbenza@google.com>: Mix pointers more thoroughly. Some pointer alignments interact badly with the mixing constant. By mixing twice we reduce this problem. PiperOrigin-RevId: 234178401 -- 1041d0e474610f3a8fea0db90958857327d6da1c by Samuel Benzaquen <sbenza@google.com>: Record rehashes in the hashtablez struct. Only recording the probe length on insertion causes a huge overestimation of the total probe length at any given time. With natural growth, elements are inserted when the load factor is between (max load/2, max load). However, after a rehash the majority of elements are actually inserted when the load factor is less than max/2 and have a much lower average probe length. Also reset some values when the table is cleared. PiperOrigin-RevId: 234013580 -- 299205caf3c89c47339f7409bc831746602cea84 by Mark Barolak <mbar@google.com>: Fix a sample code snippet that assumes `absl::string_view::const_iterator` is `const char*`. This is generally true, however in C++17 builds, absl::string_view is an alias for std::string_view and on MSVC, the std::string_view::const_iterator is an object instead of just a pointer. PiperOrigin-RevId: 233844595 -- af6c6370cf51a1e6c1469c79dfb2a486a4009136 by Abseil Team <absl-team@google.com>: Internal change. PiperOrigin-RevId: 233773470 -- 6e59e4b8e2bb6101b448f0f32b0bea81fe399ccf by Abseil Team <absl-team@google.com>: fix typo in {Starts|Ends}WithIgnoreCase comment in match.h PiperOrigin-RevId: 233662951 GitOrigin-RevId: 3d20ce6cd6541579abecaba169d4b8716d511272 Change-Id: Ib9a29b1c38c6aedf5d9f3f7f00596e8d30e864dd
6 years ago
TEST(HashValueTest, PointerAlignment) {
// We want to make sure that pointer alignment will not cause bits to be
// stuck.
constexpr size_t kTotalSize = 1 << 20;
std::unique_ptr<char[]> data(new char[kTotalSize]);
constexpr size_t kLog2NumValues = 5;
constexpr size_t kNumValues = 1 << kLog2NumValues;
for (size_t align = 1; align < kTotalSize / kNumValues;
align < 8 ? align += 1 : align < 1024 ? align += 8 : align += 32) {
SCOPED_TRACE(align);
ASSERT_LE(align * kNumValues, kTotalSize);
size_t bits_or = 0;
size_t bits_and = ~size_t{};
for (size_t i = 0; i < kNumValues; ++i) {
size_t hash = absl::Hash<void*>()(data.get() + i * align);
bits_or |= hash;
bits_and &= hash;
}
// Limit the scope to the bits we would be using for Swisstable.
constexpr size_t kMask = (1 << (kLog2NumValues + 7)) - 1;
size_t stuck_bits = (~bits_or | bits_and) & kMask;
EXPECT_EQ(stuck_bits, 0) << "0x" << std::hex << stuck_bits;
}
}
Export of internal Abseil changes. -- 6fdf24a197b964f9bacbebd0ceca305aef1654fc by Shaindel Schwartz <shaindel@google.com>: Internal change PiperOrigin-RevId: 231627312 -- 65f7faf52bff01384171efb85fee159378dedf70 by CJ Johnson <johnsoncj@google.com>: 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 <johnsoncj@google.com>: Relocates closing brace for absl namespace in InlinedVector to the correct end location PiperOrigin-RevId: 231477871 -- 063c1e8b9d1f032662c46d574e20ecc357b87d0c by Eric Fiselier <ericwf@google.com>: 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<T>()(key) was formed but when std::hash<T> 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 <absl-team@google.com>: Import of CCTZ from GitHub. PiperOrigin-RevId: 231397518 -- a0ee9032f9e04039f3410ed17fcf45ae1a3868f5 by CJ Johnson <johnsoncj@google.com>: Remove unused EnableIfAtLeastInputIterator from InlinedVector PiperOrigin-RevId: 231348903 -- 4dcd4e9a6780a81d7a6974c7bf22a037e6482b49 by Abseil Team <absl-team@google.com>: Remove unnecessary register keyword from absl/base/internal/endian.h. PiperOrigin-RevId: 231316570 -- c8584836caa3a10f90a8604a85d4b831310b72ee by Abseil Team <absl-team@google.com>: Fix hashtablez_sampler compilation on older Android NDK builds PiperOrigin-RevId: 231283542 GitOrigin-RevId: 6fdf24a197b964f9bacbebd0ceca305aef1654fc Change-Id: I185b12fb8347e3ad0ffcb2cbb83a53450e5eb938
6 years ago
TEST(HashValueTest, PairAndTuple) {
EXPECT_TRUE((is_hashable<std::pair<int, int>>::value));
EXPECT_TRUE((is_hashable<std::pair<const int&, const int&>>::value));
EXPECT_TRUE((is_hashable<std::tuple<int&, int&>>::value));
EXPECT_TRUE((is_hashable<std::tuple<int&&, int&&>>::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))));
}
TEST(HashValueTest, CombineContiguousWorks) {
std::vector<std::tuple<int>> v1 = {std::make_tuple(1), std::make_tuple(3)};
std::vector<std::tuple<int>> v2 = {std::make_tuple(1), std::make_tuple(2)};
auto vh1 = SpyHash(v1);
auto vh2 = SpyHash(v2);
EXPECT_NE(vh1, vh2);
}
struct DummyDeleter {
template <typename T>
void operator() (T* ptr) {}
};
struct SmartPointerEq {
template <typename T, typename U>
bool operator()(const T& t, const U& u) const {
return GetPtr(t) == GetPtr(u);
}
template <typename T>
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<std::unique_ptr<int>>::value));
EXPECT_TRUE((is_hashable<std::unique_ptr<int, DummyDeleter>>::value));
EXPECT_TRUE((is_hashable<std::shared_ptr<int>>::value));
int i, j;
std::unique_ptr<int, DummyDeleter> unique1(&i);
std::unique_ptr<int, DummyDeleter> unique2(&i);
std::unique_ptr<int, DummyDeleter> unique_other(&j);
std::unique_ptr<int, DummyDeleter> unique_null;
std::shared_ptr<int> shared1(&i, DummyDeleter());
std::shared_ptr<int> shared2(&i, DummyDeleter());
std::shared_ptr<int> shared_other(&j, DummyDeleter());
std::shared_ptr<int> 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<int>(), //
shared1, shared2, shared_null, //
std::make_shared<int>()),
SmartPointerEq{}));
}
TEST(HashValueTest, FunctionPointer) {
using Func = int (*)();
EXPECT_TRUE(is_hashable<Func>::value);
Func p1 = [] { return 2; }, p2 = [] { return 1; };
EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(
std::make_tuple(p1, p2, nullptr)));
}
struct WrapInTuple {
template <typename T>
std::tuple<int, T, size_t> operator()(const T& t) const {
return std::make_tuple(7, t, 0xdeadbeef);
}
};
TEST(HashValueTest, Strings) {
EXPECT_TRUE((is_hashable<std::string>::value));
const std::string small = "foo";
const std::string dup = "foofoo";
const std::string large = "large";
const std::string huge = std::string(5000, 'a');
Export of internal Abseil changes. -- bdce7e57e9e886eff1114d0266781b443f7ec639 by Derek Mauro <dmauro@google.com>: Change {Get|Set}EnvironmentVariable to {Get|Set}EnvironmentVariableA for compatibility with /DUNICODE. PiperOrigin-RevId: 239229514 -- 2276ed502326a044a84060d34eb19d499e3a3be2 by Derek Mauro <dmauro@google.com>: Import of CCTZ from GitHub. PiperOrigin-RevId: 239228622 -- a462efb970ff43b08a362ef2343fb75ac1295a50 by Derek Mauro <dmauro@google.com>: Adding linking of CoreFoundation to CMakeLists in absl/time. Import https://github.com/abseil/abseil-cpp/pull/280. Fix #283 PiperOrigin-RevId: 239220785 -- fc23327b97f940c682aae1956cf7a1bf87f88c06 by Derek Mauro <dmauro@google.com>: Add hermetic test script that uses Docker to build with a very recent version of gcc (8.3.0 today) with libstdc++ and bazel. PiperOrigin-RevId: 239220448 -- 418c08a8f6a53e63b84e39473035774417ca3aa7 by Derek Mauro <dmauro@google.com>: Disable part of the variant exeception safety test on move assignment when using versions of libstd++ that contain a bug. https://gcc.gnu.org/bugzilla/show_bug.cgi?id=87431#c7 PiperOrigin-RevId: 239062455 -- 799722217aeda79679577843c91d5be62cbcbb42 by Matt Calabrese <calabrese@google.com>: Add internal-only IsSwappable traits corresponding to std::is_swappable and std::is_nothrow_swappable, which are used with the swap implementations of optional and variant. PiperOrigin-RevId: 239049448 -- aa46a036038a3de5c68ac5e5d3b4bf76f818d2ea by CJ Johnson <johnsoncj@google.com>: Make InlinedVectorStorage constructor explicit PiperOrigin-RevId: 239044361 -- 17949715b3aa21c794701f69f2154e91b6acabc3 by CJ Johnson <johnsoncj@google.com>: Add absl namesapce to internal/inlined_vector.h PiperOrigin-RevId: 239030789 -- 834628325953078cc08ed10d23bb8890e5bec897 by Derek Mauro <dmauro@google.com>: Add test script that uses Docker to build Abseil with gcc-4.8, libstdc++, and cmake. PiperOrigin-RevId: 239028433 -- 80fe24149ed73ed2ced995ad1e372fb060c60427 by CJ Johnson <johnsoncj@google.com>: Factors data members of InlinedVector into an impl type called InlinedVectorStorage so that (in future changes) the contents of a vector can be grouped together with a single pointer. PiperOrigin-RevId: 239021086 -- 585331436d5d4d79f845e45dcf79d918a0dc6169 by Derek Mauro <dmauro@google.com>: Add -Wno-missing-field-initializers to gcc compiler flags. gcc-4.x has spurious missing field initializer warnings. https://gcc.gnu.org/bugzilla/show_bug.cgi?id=36750 PiperOrigin-RevId: 239017217 -- 94602fe4e33ee3a552a7f2939c0f57a992f55075 by Abseil Team <absl-team@google.com>: Formatting fixes. PiperOrigin-RevId: 238983038 -- a1c1b63c08505574e0a8c491561840cecb2bb93e by Derek Mauro <dmauro@google.com>: Add hermetic test script that uses Docker to build with a very recent version of clang with libc++ and bazel. PiperOrigin-RevId: 238669118 -- e525f8d20bc2f79a0d69336b902f63858f3bff9d by Derek Mauro <dmauro@google.com>: Disable the test optionalTest.InPlaceTSFINAEBug until libc++ is updated. PiperOrigin-RevId: 238661703 -- f99a2a0b5ec424a059678f7f226600f137b4c74e by Derek Mauro <dmauro@google.com>: Correct the check for the FlatHashMap-Any test bug (list conditions instead of platforms when possible) PiperOrigin-RevId: 238653344 -- 777928035dbcbf39f361eb7d10dc3696822f692f by Jon Cohen <cohenjon@google.com>: Add install rules for Abseil CMake. These are attempted to be limited to in-project installation. This serves two purposes -- first it's morally the same as using Abseil in-source, except you don't have to rebuild us every time. Second, the presence of an install rule makes life massively simpler for package manager maintainers. Currently this doesn't install absl tests or testonly libraries. This can be added in a follow-up patch. Fixes #38, Fixes #80, Closes #182 PiperOrigin-RevId: 238645836 -- ded1c6ce697c191b7a6ff14572b3e6d183117b2c by Derek Mauro <dmauro@google.com>: Add hermetic test script that uses Docker to build with a very recent version of clang with libstdc++ and bazel. PiperOrigin-RevId: 238517815 GitOrigin-RevId: bdce7e57e9e886eff1114d0266781b443f7ec639 Change-Id: I6f745869cb8ef63851891ccac05ae9a7dd241c4f
6 years ago
Export of internal Abseil changes. -- 6fdf24a197b964f9bacbebd0ceca305aef1654fc by Shaindel Schwartz <shaindel@google.com>: Internal change PiperOrigin-RevId: 231627312 -- 65f7faf52bff01384171efb85fee159378dedf70 by CJ Johnson <johnsoncj@google.com>: 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 <johnsoncj@google.com>: Relocates closing brace for absl namespace in InlinedVector to the correct end location PiperOrigin-RevId: 231477871 -- 063c1e8b9d1f032662c46d574e20ecc357b87d0c by Eric Fiselier <ericwf@google.com>: 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<T>()(key) was formed but when std::hash<T> 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 <absl-team@google.com>: Import of CCTZ from GitHub. PiperOrigin-RevId: 231397518 -- a0ee9032f9e04039f3410ed17fcf45ae1a3868f5 by CJ Johnson <johnsoncj@google.com>: Remove unused EnableIfAtLeastInputIterator from InlinedVector PiperOrigin-RevId: 231348903 -- 4dcd4e9a6780a81d7a6974c7bf22a037e6482b49 by Abseil Team <absl-team@google.com>: Remove unnecessary register keyword from absl/base/internal/endian.h. PiperOrigin-RevId: 231316570 -- c8584836caa3a10f90a8604a85d4b831310b72ee by Abseil Team <absl-team@google.com>: Fix hashtablez_sampler compilation on older Android NDK builds PiperOrigin-RevId: 231283542 GitOrigin-RevId: 6fdf24a197b964f9bacbebd0ceca305aef1654fc Change-Id: I185b12fb8347e3ad0ffcb2cbb83a53450e5eb938
6 years ago
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<const char*>("ABC")),
SpyHash(absl::string_view("ABC")));
}
TEST(HashValueTest, StdArray) {
EXPECT_TRUE((is_hashable<std::array<int, 3>>::value));
EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(
std::make_tuple(std::array<int, 3>{}, std::array<int, 3>{{0, 23, 42}})));
}
TEST(HashValueTest, StdBitset) {
EXPECT_TRUE((is_hashable<std::bitset<257>>::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<std::string, 6> 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<kNumBits>(bit_strings[0].c_str()),
std::bitset<kNumBits>(bit_strings[1].c_str()),
std::bitset<kNumBits>(bit_strings[2].c_str()),
std::bitset<kNumBits>(bit_strings[3].c_str()),
std::bitset<kNumBits>(bit_strings[4].c_str()),
std::bitset<kNumBits>(bit_strings[5].c_str())}));
} // namespace
template <typename T>
class HashValueSequenceTest : public testing::Test {
};
TYPED_TEST_SUITE_P(HashValueSequenceTest);
TYPED_TEST_P(HashValueSequenceTest, BasicUsage) {
EXPECT_TRUE((is_hashable<TypeParam>::value));
using ValueType = typename TypeParam::value_type;
auto a = static_cast<ValueType>(0);
auto b = static_cast<ValueType>(23);
auto c = static_cast<ValueType>(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::deque<int>, std::forward_list<int>, std::list<int>,
std::vector<int>, std::vector<bool>, std::set<int>,
std::multiset<int>>;
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 <typename H>
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<Private>::value);
EXPECT_NE(SpyHash(Private{0}), SpyHash(Private{1}));
EXPECT_EQ(SpyHash(Private{1}), SpyHash(Private{1}));
}
TEST(HashValueTest, Optional) {
EXPECT_TRUE(is_hashable<absl::optional<Private>>::value);
using O = absl::optional<Private>;
EXPECT_TRUE(absl::VerifyTypeImplementsAbslHashCorrectly(
std::make_tuple(O{}, O{{1}}, O{{-1}}, O{{10}})));
}
TEST(HashValueTest, Variant) {
using V = absl::variant<Private, std::string>;
EXPECT_TRUE(is_hashable<V>::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<absl::variant<S>>::value);
#endif
}
TEST(HashValueTest, Maps) {
EXPECT_TRUE((is_hashable<std::map<int, std::string>>::value));
using M = std::map<int, std::string>;
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<int, std::string>;
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"}})));
}
template <typename T, typename = void>
struct IsHashCallable : std::false_type {};
template <typename T>
struct IsHashCallable<T, absl::void_t<decltype(std::declval<absl::Hash<T>>()(
std::declval<const T&>()))>> : std::true_type {};
template <typename T, typename = void>
struct IsAggregateInitializable : std::false_type {};
template <typename T>
struct IsAggregateInitializable<T, absl::void_t<decltype(T{})>>
: std::true_type {};
TEST(IsHashableTest, ValidHash) {
EXPECT_TRUE((is_hashable<int>::value));
EXPECT_TRUE(std::is_default_constructible<absl::Hash<int>>::value);
EXPECT_TRUE(std::is_copy_constructible<absl::Hash<int>>::value);
EXPECT_TRUE(std::is_move_constructible<absl::Hash<int>>::value);
EXPECT_TRUE(absl::is_copy_assignable<absl::Hash<int>>::value);
EXPECT_TRUE(absl::is_move_assignable<absl::Hash<int>>::value);
EXPECT_TRUE(IsHashCallable<int>::value);
EXPECT_TRUE(IsAggregateInitializable<absl::Hash<int>>::value);
}
Export of internal Abseil changes. -- 6fdf24a197b964f9bacbebd0ceca305aef1654fc by Shaindel Schwartz <shaindel@google.com>: Internal change PiperOrigin-RevId: 231627312 -- 65f7faf52bff01384171efb85fee159378dedf70 by CJ Johnson <johnsoncj@google.com>: 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 <johnsoncj@google.com>: Relocates closing brace for absl namespace in InlinedVector to the correct end location PiperOrigin-RevId: 231477871 -- 063c1e8b9d1f032662c46d574e20ecc357b87d0c by Eric Fiselier <ericwf@google.com>: 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<T>()(key) was formed but when std::hash<T> 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 <absl-team@google.com>: Import of CCTZ from GitHub. PiperOrigin-RevId: 231397518 -- a0ee9032f9e04039f3410ed17fcf45ae1a3868f5 by CJ Johnson <johnsoncj@google.com>: Remove unused EnableIfAtLeastInputIterator from InlinedVector PiperOrigin-RevId: 231348903 -- 4dcd4e9a6780a81d7a6974c7bf22a037e6482b49 by Abseil Team <absl-team@google.com>: Remove unnecessary register keyword from absl/base/internal/endian.h. PiperOrigin-RevId: 231316570 -- c8584836caa3a10f90a8604a85d4b831310b72ee by Abseil Team <absl-team@google.com>: Fix hashtablez_sampler compilation on older Android NDK builds PiperOrigin-RevId: 231283542 GitOrigin-RevId: 6fdf24a197b964f9bacbebd0ceca305aef1654fc Change-Id: I185b12fb8347e3ad0ffcb2cbb83a53450e5eb938
6 years ago
#if ABSL_META_INTERNAL_STD_HASH_SFINAE_FRIENDLY_
TEST(IsHashableTest, PoisonHash) {
struct X {};
EXPECT_FALSE((is_hashable<X>::value));
EXPECT_FALSE(std::is_default_constructible<absl::Hash<X>>::value);
EXPECT_FALSE(std::is_copy_constructible<absl::Hash<X>>::value);
EXPECT_FALSE(std::is_move_constructible<absl::Hash<X>>::value);
EXPECT_FALSE(absl::is_copy_assignable<absl::Hash<X>>::value);
EXPECT_FALSE(absl::is_move_assignable<absl::Hash<X>>::value);
EXPECT_FALSE(IsHashCallable<X>::value);
EXPECT_FALSE(IsAggregateInitializable<absl::Hash<X>>::value);
}
Export of internal Abseil changes. -- 6fdf24a197b964f9bacbebd0ceca305aef1654fc by Shaindel Schwartz <shaindel@google.com>: Internal change PiperOrigin-RevId: 231627312 -- 65f7faf52bff01384171efb85fee159378dedf70 by CJ Johnson <johnsoncj@google.com>: 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 <johnsoncj@google.com>: Relocates closing brace for absl namespace in InlinedVector to the correct end location PiperOrigin-RevId: 231477871 -- 063c1e8b9d1f032662c46d574e20ecc357b87d0c by Eric Fiselier <ericwf@google.com>: 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<T>()(key) was formed but when std::hash<T> 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 <absl-team@google.com>: Import of CCTZ from GitHub. PiperOrigin-RevId: 231397518 -- a0ee9032f9e04039f3410ed17fcf45ae1a3868f5 by CJ Johnson <johnsoncj@google.com>: Remove unused EnableIfAtLeastInputIterator from InlinedVector PiperOrigin-RevId: 231348903 -- 4dcd4e9a6780a81d7a6974c7bf22a037e6482b49 by Abseil Team <absl-team@google.com>: Remove unnecessary register keyword from absl/base/internal/endian.h. PiperOrigin-RevId: 231316570 -- c8584836caa3a10f90a8604a85d4b831310b72ee by Abseil Team <absl-team@google.com>: Fix hashtablez_sampler compilation on older Android NDK builds PiperOrigin-RevId: 231283542 GitOrigin-RevId: 6fdf24a197b964f9bacbebd0ceca305aef1654fc Change-Id: I185b12fb8347e3ad0ffcb2cbb83a53450e5eb938
6 years ago
#endif // ABSL_META_INTERNAL_STD_HASH_SFINAE_FRIENDLY_
// Hashable types
//
// These types exist simply to exercise various AbslHashValue behaviors, so
// they are named by what their AbslHashValue overload does.
struct NoOp {
template <typename HashCode>
friend HashCode AbslHashValue(HashCode h, NoOp n) {
return h;
}
};
struct EmptyCombine {
template <typename HashCode>
friend HashCode AbslHashValue(HashCode h, EmptyCombine e) {
return HashCode::combine(std::move(h));
}
};
template <typename Int>
struct CombineIterative {
template <typename HashCode>
friend HashCode AbslHashValue(HashCode h, CombineIterative c) {
for (int i = 0; i < 5; ++i) {
h = HashCode::combine(std::move(h), Int(i));
}
return h;
}
};
template <typename Int>
struct CombineVariadic {
template <typename HashCode>
friend HashCode AbslHashValue(HashCode h, CombineVariadic c) {
return HashCode::combine(std::move(h), Int(0), Int(1), Int(2), Int(3),
Int(4));
}
};
Export of internal Abseil changes. -- 5dc8d7504b7c11710b19365a6582c288c8992366 by Derek Mauro <dmauro@google.com>: Fix constexpr Span::last under MSVC and add Span constexpr tests. PiperOrigin-RevId: 237515952 -- 5ea8c146e653bbc49ff7e698699478242df7de35 by Derek Mauro <dmauro@google.com>: Implement Span::first and Span::last from C++20. https://github.com/abseil/abseil-cpp/pull/274 PiperOrigin-RevId: 237494399 -- 08db3417f1d8fe4556255d57a2f0df51b09bdd9a by Derek Mauro <dmauro@google.com>: HTTPS in more URLs. PiperOrigin-RevId: 237486823 -- 83ec63a7f8e47b62af619546f9f7b3bf72e74e86 by Derek Mauro <dmauro@google.com>: Changed HTTP URLs to HTTPS where possible. https://github.com/abseil/abseil-cpp/pull/270 PiperOrigin-RevId: 237445310 -- 220bf279c14cb31efa239500d1a70e0ac0c32e3c by Abseil Team <absl-team@google.com>: Support parsing decltype(nullptr) as a type. PiperOrigin-RevId: 237336739 -- ced234bbe78f5d495c3f6f6a9c2e0a95f7c080a5 by Gennadiy Rozental <rogeeff@google.com>: Introduce internal interface for setting environment variable value in scope PiperOrigin-RevId: 237275806 -- 1f1acb4e294af24d9f7598e85163d5e1d9958ae9 by Samuel Benzaquen <sbenza@google.com>: Avoid using aliases in the SFINAE expressions to make it more compatible with MSVC. Turn on the tests in MSVC. PiperOrigin-RevId: 237261456 -- 06cf7de6250a0572ef90fa1176f742ca0451ce71 by Derek Mauro <dmauro@google.com>: Fix unused variable warning. PiperOrigin-RevId: 237108006 GitOrigin-RevId: 5dc8d7504b7c11710b19365a6582c288c8992366 Change-Id: Ife5182c80942945c4e8700844c8febb482d6ad82
6 years ago
enum class InvokeTag {
kUniquelyRepresented,
kHashValue,
#if ABSL_HASH_INTERNAL_SUPPORT_LEGACY_HASH_
kLegacyHash,
#endif // ABSL_HASH_INTERNAL_SUPPORT_LEGACY_HASH_
kStdHash,
kNone
};
template <InvokeTag T>
using InvokeTagConstant = std::integral_constant<InvokeTag, T>;
template <InvokeTag... Tags>
struct MinTag;
template <InvokeTag a, InvokeTag b, InvokeTag... Tags>
struct MinTag<a, b, Tags...> : MinTag<(a < b ? a : b), Tags...> {};
template <InvokeTag a>
struct MinTag<a> : InvokeTagConstant<a> {};
template <InvokeTag... Tags>
struct CustomHashType {
explicit CustomHashType(size_t val) : value(val) {}
size_t value;
};
template <InvokeTag allowed, InvokeTag... tags>
struct EnableIfContained
: std::enable_if<absl::disjunction<
std::integral_constant<bool, allowed == tags>...>::value> {};
template <
typename H, InvokeTag... Tags,
typename = typename EnableIfContained<InvokeTag::kHashValue, Tags...>::type>
H AbslHashValue(H state, CustomHashType<Tags...> t) {
static_assert(MinTag<Tags...>::value == InvokeTag::kHashValue, "");
return H::combine(std::move(state),
t.value + static_cast<int>(InvokeTag::kHashValue));
}
} // namespace
namespace absl {
namespace hash_internal {
template <InvokeTag... Tags>
struct is_uniquely_represented<
CustomHashType<Tags...>,
typename EnableIfContained<InvokeTag::kUniquelyRepresented, Tags...>::type>
: std::true_type {};
} // namespace hash_internal
} // namespace absl
#if ABSL_HASH_INTERNAL_SUPPORT_LEGACY_HASH_
namespace ABSL_INTERNAL_LEGACY_HASH_NAMESPACE {
template <InvokeTag... Tags>
struct hash<CustomHashType<Tags...>> {
template <InvokeTag... TagsIn, typename = typename EnableIfContained<
InvokeTag::kLegacyHash, TagsIn...>::type>
size_t operator()(CustomHashType<TagsIn...> t) const {
static_assert(MinTag<Tags...>::value == InvokeTag::kLegacyHash, "");
return t.value + static_cast<int>(InvokeTag::kLegacyHash);
}
};
} // namespace ABSL_INTERNAL_LEGACY_HASH_NAMESPACE
#endif // ABSL_HASH_INTERNAL_SUPPORT_LEGACY_HASH_
namespace std {
template <InvokeTag... Tags> // NOLINT
struct hash<CustomHashType<Tags...>> {
template <InvokeTag... TagsIn, typename = typename EnableIfContained<
InvokeTag::kStdHash, TagsIn...>::type>
size_t operator()(CustomHashType<TagsIn...> t) const {
static_assert(MinTag<Tags...>::value == InvokeTag::kStdHash, "");
return t.value + static_cast<int>(InvokeTag::kStdHash);
}
};
} // namespace std
namespace {
template <typename... T>
void TestCustomHashType(InvokeTagConstant<InvokeTag::kNone>, T...) {
using type = CustomHashType<T::value...>;
SCOPED_TRACE(testing::PrintToString(std::vector<InvokeTag>{T::value...}));
EXPECT_TRUE(is_hashable<type>());
EXPECT_TRUE(is_hashable<const type>());
EXPECT_TRUE(is_hashable<const type&>());
const size_t offset = static_cast<int>(std::min({T::value...}));
EXPECT_EQ(SpyHash(type(7)), SpyHash(size_t{7 + offset}));
}
void TestCustomHashType(InvokeTagConstant<InvokeTag::kNone>) {
Export of internal Abseil changes. -- 6fdf24a197b964f9bacbebd0ceca305aef1654fc by Shaindel Schwartz <shaindel@google.com>: Internal change PiperOrigin-RevId: 231627312 -- 65f7faf52bff01384171efb85fee159378dedf70 by CJ Johnson <johnsoncj@google.com>: 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 <johnsoncj@google.com>: Relocates closing brace for absl namespace in InlinedVector to the correct end location PiperOrigin-RevId: 231477871 -- 063c1e8b9d1f032662c46d574e20ecc357b87d0c by Eric Fiselier <ericwf@google.com>: 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<T>()(key) was formed but when std::hash<T> 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 <absl-team@google.com>: Import of CCTZ from GitHub. PiperOrigin-RevId: 231397518 -- a0ee9032f9e04039f3410ed17fcf45ae1a3868f5 by CJ Johnson <johnsoncj@google.com>: Remove unused EnableIfAtLeastInputIterator from InlinedVector PiperOrigin-RevId: 231348903 -- 4dcd4e9a6780a81d7a6974c7bf22a037e6482b49 by Abseil Team <absl-team@google.com>: Remove unnecessary register keyword from absl/base/internal/endian.h. PiperOrigin-RevId: 231316570 -- c8584836caa3a10f90a8604a85d4b831310b72ee by Abseil Team <absl-team@google.com>: Fix hashtablez_sampler compilation on older Android NDK builds PiperOrigin-RevId: 231283542 GitOrigin-RevId: 6fdf24a197b964f9bacbebd0ceca305aef1654fc Change-Id: I185b12fb8347e3ad0ffcb2cbb83a53450e5eb938
6 years ago
#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<type>());
EXPECT_FALSE(is_hashable<const type>());
EXPECT_FALSE(is_hashable<const type&>());
Export of internal Abseil changes. -- 6fdf24a197b964f9bacbebd0ceca305aef1654fc by Shaindel Schwartz <shaindel@google.com>: Internal change PiperOrigin-RevId: 231627312 -- 65f7faf52bff01384171efb85fee159378dedf70 by CJ Johnson <johnsoncj@google.com>: 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 <johnsoncj@google.com>: Relocates closing brace for absl namespace in InlinedVector to the correct end location PiperOrigin-RevId: 231477871 -- 063c1e8b9d1f032662c46d574e20ecc357b87d0c by Eric Fiselier <ericwf@google.com>: 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<T>()(key) was formed but when std::hash<T> 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 <absl-team@google.com>: Import of CCTZ from GitHub. PiperOrigin-RevId: 231397518 -- a0ee9032f9e04039f3410ed17fcf45ae1a3868f5 by CJ Johnson <johnsoncj@google.com>: Remove unused EnableIfAtLeastInputIterator from InlinedVector PiperOrigin-RevId: 231348903 -- 4dcd4e9a6780a81d7a6974c7bf22a037e6482b49 by Abseil Team <absl-team@google.com>: Remove unnecessary register keyword from absl/base/internal/endian.h. PiperOrigin-RevId: 231316570 -- c8584836caa3a10f90a8604a85d4b831310b72ee by Abseil Team <absl-team@google.com>: Fix hashtablez_sampler compilation on older Android NDK builds PiperOrigin-RevId: 231283542 GitOrigin-RevId: 6fdf24a197b964f9bacbebd0ceca305aef1654fc Change-Id: I185b12fb8347e3ad0ffcb2cbb83a53450e5eb938
6 years ago
#endif // ABSL_META_INTERNAL_STD_HASH_SFINAE_FRIENDLY_
}
template <InvokeTag Tag, typename... T>
void TestCustomHashType(InvokeTagConstant<Tag> tag, T... t) {
constexpr auto next = static_cast<InvokeTag>(static_cast<int>(Tag) + 1);
TestCustomHashType(InvokeTagConstant<next>(), tag, t...);
TestCustomHashType(InvokeTagConstant<next>(), t...);
}
TEST(HashTest, CustomHashType) {
TestCustomHashType(InvokeTagConstant<InvokeTag{}>());
}
TEST(HashTest, NoOpsAreEquivalent) {
EXPECT_EQ(Hash<NoOp>()({}), Hash<NoOp>()({}));
EXPECT_EQ(Hash<NoOp>()({}), Hash<EmptyCombine>()({}));
}
template <typename T>
class HashIntTest : public testing::Test {
};
TYPED_TEST_SUITE_P(HashIntTest);
TYPED_TEST_P(HashIntTest, BasicUsage) {
EXPECT_NE(Hash<NoOp>()({}), Hash<TypeParam>()(0));
EXPECT_NE(Hash<NoOp>()({}),
Hash<TypeParam>()(std::numeric_limits<TypeParam>::max()));
if (std::numeric_limits<TypeParam>::min() != 0) {
EXPECT_NE(Hash<NoOp>()({}),
Hash<TypeParam>()(std::numeric_limits<TypeParam>::min()));
}
EXPECT_EQ(Hash<CombineIterative<TypeParam>>()({}),
Hash<CombineVariadic<TypeParam>>()({}));
}
REGISTER_TYPED_TEST_CASE_P(HashIntTest, BasicUsage);
using IntTypes = testing::Types<unsigned char, char, int, int32_t, int64_t, uint32_t,
uint64_t, size_t>;
INSTANTIATE_TYPED_TEST_CASE_P(My, HashIntTest, IntTypes);
struct StructWithPadding {
char c;
int i;
template <typename H>
friend H AbslHashValue(H hash_state, const StructWithPadding& s) {
return H::combine(std::move(hash_state), s.c, s.i);
}
};
static_assert(sizeof(StructWithPadding) > sizeof(char) + sizeof(int),
"StructWithPadding doesn't have padding");
static_assert(std::is_standard_layout<StructWithPadding>::value, "");
// This check has to be disabled because libstdc++ doesn't support it.
// static_assert(std::is_trivially_constructible<StructWithPadding>::value, "");
template <typename T>
struct ArraySlice {
T* begin;
T* end;
template <typename H>
friend H AbslHashValue(H hash_state, const ArraySlice& slice) {
for (auto t = slice.begin; t != slice.end; ++t) {
hash_state = H::combine(std::move(hash_state), *t);
}
return hash_state;
}
};
TEST(HashTest, HashNonUniquelyRepresentedType) {
// Create equal StructWithPadding objects that are known to have non-equal
// padding bytes.
static const size_t kNumStructs = 10;
unsigned char buffer1[kNumStructs * sizeof(StructWithPadding)];
std::memset(buffer1, 0, sizeof(buffer1));
auto* s1 = reinterpret_cast<StructWithPadding*>(buffer1);
unsigned char buffer2[kNumStructs * sizeof(StructWithPadding)];
std::memset(buffer2, 255, sizeof(buffer2));
auto* s2 = reinterpret_cast<StructWithPadding*>(buffer2);
for (int i = 0; i < kNumStructs; ++i) {
SCOPED_TRACE(i);
s1[i].c = s2[i].c = '0' + i;
s1[i].i = s2[i].i = i;
ASSERT_FALSE(memcmp(buffer1 + i * sizeof(StructWithPadding),
buffer2 + i * sizeof(StructWithPadding),
sizeof(StructWithPadding)) == 0)
<< "Bug in test code: objects do not have unequal"
<< " object representations";
}
EXPECT_EQ(Hash<StructWithPadding>()(s1[0]), Hash<StructWithPadding>()(s2[0]));
EXPECT_EQ(Hash<ArraySlice<StructWithPadding>>()({s1, s1 + kNumStructs}),
Hash<ArraySlice<StructWithPadding>>()({s2, s2 + kNumStructs}));
}
TEST(HashTest, StandardHashContainerUsage) {
std::unordered_map<int, std::string, Hash<int>> map = {{0, "foo"},
{42, "bar"}};
EXPECT_NE(map.find(0), map.end());
EXPECT_EQ(map.find(1), map.end());
EXPECT_NE(map.find(0u), map.end());
}
struct ConvertibleFromNoOp {
ConvertibleFromNoOp(NoOp) {} // NOLINT(runtime/explicit)
template <typename H>
friend H AbslHashValue(H hash_state, ConvertibleFromNoOp) {
return H::combine(std::move(hash_state), 1);
}
};
TEST(HashTest, HeterogeneousCall) {
EXPECT_NE(Hash<ConvertibleFromNoOp>()(NoOp()),
Hash<NoOp>()(NoOp()));
}
TEST(IsUniquelyRepresentedTest, SanityTest) {
using absl::hash_internal::is_uniquely_represented;
EXPECT_TRUE(is_uniquely_represented<unsigned char>::value);
EXPECT_TRUE(is_uniquely_represented<int>::value);
EXPECT_FALSE(is_uniquely_represented<bool>::value);
EXPECT_FALSE(is_uniquely_represented<int*>::value);
}
struct IntAndString {
int i;
std::string s;
template <typename H>
friend H AbslHashValue(H hash_state, IntAndString int_and_string) {
return H::combine(std::move(hash_state), int_and_string.s,
int_and_string.i);
}
};
TEST(HashTest, SmallValueOn64ByteBoundary) {
Hash<IntAndString>()(IntAndString{0, std::string(63, '0')});
}
struct TypeErased {
size_t n;
template <typename H>
friend H AbslHashValue(H hash_state, const TypeErased& v) {
v.HashValue(absl::HashState::Create(&hash_state));
return hash_state;
}
void HashValue(absl::HashState state) const {
absl::HashState::combine(std::move(state), n);
}
};
TEST(HashTest, TypeErased) {
EXPECT_TRUE((is_hashable<TypeErased>::value));
EXPECT_TRUE((is_hashable<std::pair<TypeErased, int>>::value));
EXPECT_EQ(SpyHash(TypeErased{7}), SpyHash(size_t{7}));
EXPECT_NE(SpyHash(TypeErased{7}), SpyHash(size_t{13}));
EXPECT_EQ(SpyHash(std::make_pair(TypeErased{7}, 17)),
SpyHash(std::make_pair(size_t{7}, 17)));
}
struct ValueWithBoolConversion {
operator bool() const { return false; }
int i;
};
} // namespace
namespace std {
template <>
struct hash<ValueWithBoolConversion> {
size_t operator()(ValueWithBoolConversion v) { return v.i; }
};
} // namespace std
namespace {
TEST(HashTest, DoesNotUseImplicitConversionsToBool) {
EXPECT_NE(absl::Hash<ValueWithBoolConversion>()(ValueWithBoolConversion{0}),
absl::Hash<ValueWithBoolConversion>()(ValueWithBoolConversion{1}));
}
} // namespace