Pass type-erased SwissTable key data via `EncodedHashKey` instead of `const void*`. Using a byte-array struct copied with `std::memcpy` allows passing small trivially copyable keys by value without UB or MSan errors when the key contains padding or uninitialized bytes. Also store keys larger than `EncodedHashKey` by `const&` in `CanonicalHashKey` to avoid an extra stack copy. PiperOrigin-RevId: 1014945755
diff --git a/CMake/AbseilDll.cmake b/CMake/AbseilDll.cmake index 5b24d67..1b0b21e 100644 --- a/CMake/AbseilDll.cmake +++ b/CMake/AbseilDll.cmake
@@ -158,6 +158,7 @@ "functional/internal/function_ref.h" "functional/overload.h" "hash/hash.h" + "hash/internal/canonical_hash.h" "hash/internal/city.cc" "hash/internal/city.h" "hash/internal/hash.cc"
diff --git a/absl/container/BUILD.bazel b/absl/container/BUILD.bazel index 7d74f26..7bbfe2c 100644 --- a/absl/container/BUILD.bazel +++ b/absl/container/BUILD.bazel
@@ -340,6 +340,7 @@ ":unordered_set_members_test", ":unordered_set_modifiers_test", "//absl/base:config", + "//absl/base:core_headers", "//absl/hash", "//absl/log:check", "//absl/memory", @@ -442,6 +443,7 @@ "//absl/base:config", "//absl/base:core_headers", "//absl/hash", + "//absl/hash:canonical_hash", "//absl/memory", "//absl/meta:type_traits", "//absl/utility",
diff --git a/absl/container/CMakeLists.txt b/absl/container/CMakeLists.txt index c249378..d12f4d5 100644 --- a/absl/container/CMakeLists.txt +++ b/absl/container/CMakeLists.txt
@@ -376,6 +376,7 @@ absl::check absl::config absl::container_memory + absl::core_headers absl::flat_hash_set absl::hash absl::hash_container_defaults @@ -489,6 +490,7 @@ COPTS ${ABSL_DEFAULT_COPTS} DEPS + absl::canonical_hash absl::config absl::core_headers absl::hash
diff --git a/absl/container/flat_hash_set_test.cc b/absl/container/flat_hash_set_test.cc index a8d533f..2a17c7c 100644 --- a/absl/container/flat_hash_set_test.cc +++ b/absl/container/flat_hash_set_test.cc
@@ -24,6 +24,7 @@ #include "gmock/gmock.h" #include "gtest/gtest.h" +#include "absl/base/attributes.h" #include "absl/base/config.h" #include "absl/container/hash_container_defaults.h" #include "absl/container/internal/container_memory.h" @@ -428,6 +429,47 @@ (GetTypeErasedApplyToSlotFn<absl::Hash<int*>, int*, true, 0>())); } +// Small trivially copyable key with padding bytes between `a` and `b`. +struct KeyWithPadding { + uint8_t a; + uint32_t b; + + friend bool operator==(const KeyWithPadding& x, const KeyWithPadding& y) { + return x.a == y.a && x.b == y.b; + } + template <typename H> + friend H AbslHashValue(H h, const KeyWithPadding& k) { + return H::combine(std::move(h), k.a, k.b); + } +}; + +// Initializes the fields of `*k` without touching its padding bytes. Not +// inlined so that the compiler keeps the padding uninitialized. +ABSL_ATTRIBUTE_NOINLINE void InitKey(KeyWithPadding* k, uint8_t a, uint32_t b) { + k->a = a; + k->b = b; +} + +// Regression test: keys that are small and trivially copyable but not +// uniquely represented must not be passed by value through the type erased +// hashing path, otherwise MemorySanitizer reports a use of uninitialized value +// for the padding bytes. +TEST(FlatHashSet, SmallKeyWithUninitializedPadding) { + // Keys live in default initialized heap memory so that the padding bytes + // stay uninitialized (stack objects may be split into their fields by the + // optimizer, and `make_unique` would value initialize the array). + std::unique_ptr<KeyWithPadding[]> keys(new KeyWithPadding[100]); + for (uint32_t i = 0; i < 100; ++i) { + InitKey(&keys[i], static_cast<uint8_t>(i), i); + } + absl::flat_hash_set<KeyWithPadding> set; + for (uint32_t i = 0; i < 100; ++i) { + set.insert(keys[i]); + } + EXPECT_EQ(set.size(), 100); + EXPECT_TRUE(set.contains(keys[42])); +} + #if defined(__cpp_lib_containers_ranges) && \ __cpp_lib_containers_ranges >= 202202L TEST(FlatHashSet, FromRange) {
diff --git a/absl/container/internal/container_memory.h b/absl/container/internal/container_memory.h index c821cfd..f3057d1 100644 --- a/absl/container/internal/container_memory.h +++ b/absl/container/internal/container_memory.h
@@ -28,6 +28,7 @@ #include "absl/base/attributes.h" #include "absl/base/config.h" #include "absl/hash/hash.h" +#include "absl/hash/internal/canonical_hash.h" #include "absl/memory/memory.h" #include "absl/meta/type_traits.h" #include "absl/utility/utility.h" @@ -592,22 +593,38 @@ size_t seed; }; -// No arguments function hash function for a specific key. -template <class Hash, class Key, bool kIsAbsl, size_t kSeedShift> +using EncodedHashKey = absl::hash_internal::EncodedHashKey; +using HashForKeyFn = absl::hash_internal::HashForKeyFn; + +// No arguments hash function for a specific key. +// If `kUseCanonical` is true, `Hash` must hash `Key` identically to +// `absl::Hash<Key>`, and `CanonicalHashKey` is used so that `get_hash_fn()` is +// shared across key types with the same canonical hasher. +template <class Hash, class Key, bool kIsAbsl, size_t kSeedShift, + bool kUseCanonical> struct HashKey { - size_t operator()(size_t seed) const { - return HashElement<Hash, kIsAbsl, kSeedShift>{hash, seed}(key); + static size_t GetHash(EncodedHashKey data, size_t seed) { + const auto& self = *data.ToPtr<HashKey>(); + return HashElement<Hash, kIsAbsl, kSeedShift>{self.hash, seed}(self.key); } - // Static version of the above to pass to type erased functions. - static size_t GetHash(void* data, size_t seed) { - return (*static_cast<const HashKey*>(data))(seed); - } + // `data()` and `get_hash_fn()` are passed to type erased functions. + EncodedHashKey data() const { return EncodedHashKey::FromPtr(this); } + static constexpr HashForKeyFn get_hash_fn() { return &GetHash; } + ABSL_ATTRIBUTE_NO_UNIQUE_ADDRESS type_traits_internal::AddConstRefIfExpensiveToCopy<Hash> hash; type_traits_internal::AddConstRefIfExpensiveToCopy<Key> key; }; +template <class Hash, class Key, bool kIsAbsl, size_t kSeedShift> +struct HashKey<Hash, Key, kIsAbsl, kSeedShift, /*kUseCanonical=*/true> + : absl::hash_internal::CanonicalHashKey<Key> { + static_assert(kIsAbsl, "kUseCanonical requires kIsAbsl"); + HashKey(const Hash&, const absl::remove_cvref_t<Key>& k) + : absl::hash_internal::CanonicalHashKey<Key>(k) {} +}; + // Variadic arguments equality function that ignore the rest of the arguments. // Useful for usage with policy traits. template <class K1, class KeyEqual>
diff --git a/absl/container/internal/container_memory_test.cc b/absl/container/internal/container_memory_test.cc index 1bd2dde..c7978df 100644 --- a/absl/container/internal/container_memory_test.cc +++ b/absl/container/internal/container_memory_test.cc
@@ -388,6 +388,18 @@ absl::Hash<MyEnum>{}, seed)(c))); } +TEST(HashKeyTest, NonCanonicalUsesHasher) { + auto hash = [](int32_t v) { return static_cast<size_t>(v + 42); }; + using HashKeyCustom = HashKey<decltype(hash), int32_t, /*kIsAbsl=*/false, + /*kSeedShift=*/0, /*kUseCanonical=*/false>; + int32_t a = 1; + size_t seed = 100; + HashKeyCustom hk{hash, a}; + EXPECT_EQ(hk.data().ToPtr<HashKeyCustom>(), &hk); + EXPECT_EQ(HashKeyCustom::get_hash_fn()(hk.data(), seed), + (HashElement<decltype(hash), /*kIsAbsl=*/false, 0>(hash, seed)(a))); +} + TEST(HashElement, DefaultHash) { size_t x = 7; size_t seed = 100;
diff --git a/absl/container/internal/raw_hash_set.cc b/absl/container/internal/raw_hash_set.cc index 0fb3f83..bd36659 100644 --- a/absl/container/internal/raw_hash_set.cc +++ b/absl/container/internal/raw_hash_set.cc
@@ -1149,7 +1149,7 @@ ABSL_ATTRIBUTE_COLD ABSL_ATTRIBUTE_NOINLINE void ReportSingleElementTableGrowthToInfozAndForceSample( CommonFields& common, const AllocPolicy& __restrict policy, - void* hasher, HashForKeyFn get_hash) { + EncodedHashKey hasher, HashForKeyFn get_hash) { HashtablezInfoHandle infoz = ForcedTrySample(policy); common.generate_new_seed(/*has_infoz=*/true); ReportGrowthToInfozImpl(common, infoz, get_hash(hasher, common.seed().seed()), @@ -1170,7 +1170,8 @@ // `common` is first and `get_hash` is third to match argument order in callers. ABSL_ATTRIBUTE_COLD ABSL_ATTRIBUTE_NOINLINE void ReportInsertMissToInfozAndComputeHash(CommonFields& common, size_t probe_length, - void* hasher, HashForKeyFn get_hash) { + EncodedHashKey hasher, + HashForKeyFn get_hash) { common.infoz().RecordInsertMiss(get_hash(hasher, common.seed().seed()), probe_length); } @@ -1904,7 +1905,7 @@ void* Grow1To3AndPrepareInsert(CommonFields& common, const PolicyFunctions& __restrict policy, - void* hasher, HashForKeyFn get_hash, + EncodedHashKey hasher, HashForKeyFn get_hash, bool has_infoz, void* new_slots) { // TODO(b/413062340): Refactor to reuse more code with // GrowSooTableToNextCapacityAndPrepareInsert. @@ -2077,7 +2078,7 @@ void* PrepareInsertSmallNonSoo(CommonFields& common, const PolicyFunctions& __restrict policy, - void* hasher, HashForKeyFn get_hash) { + EncodedHashKey hasher, HashForKeyFn get_hash) { ABSL_SWISSTABLE_ASSERT(common.is_small()); ABSL_SWISSTABLE_ASSERT(!policy.alloc_policy->soo_enabled); const bool is_empty = common.empty_when_small(); @@ -2238,7 +2239,7 @@ ABSL_ATTRIBUTE_NOINLINE void* GrowEmptySooTableToNextCapacityForceSamplingAndPrepareInsert( CommonFields& common, const AllocPolicy& __restrict policy, - void* hasher, HashForKeyFn get_hash) { + EncodedHashKey hasher, HashForKeyFn get_hash) { const size_t kNewCapacity = NextCapacity(SooCapacity()); ResizeEmptyNonAllocatedTableImpl(common, policy, kNewCapacity, /*blocked_element_count=*/0, @@ -2340,7 +2341,7 @@ template <size_t SooSlotMemcpySize, bool TransferUsesMemcpy> void* GrowSooTableToNextCapacityAndPrepareInsert( CommonFields& common, const PolicyFunctions& __restrict policy, - void* hasher, HashForKeyFn get_hash, bool force_sampling) { + EncodedHashKey hasher, HashForKeyFn get_hash, bool force_sampling) { AssertSoo(common, *policy.alloc_policy); if (ABSL_PREDICT_FALSE(force_sampling)) { // The table is empty, it is only used for forced sampling of SOO tables. @@ -2627,7 +2628,7 @@ void* PrepareInsertLargeGenerationsEnabled( CommonFields& common, const PolicyFunctions& __restrict policy, size_t hash, Group::NonIterableBitMaskType mask_empty, size_t target_group_offset, - absl::FunctionRef<size_t(size_t)> recompute_hash) { + EncodedHashKey hasher, HashForKeyFn recompute_hash) { // NOLINTNEXTLINE(misc-static-assert) ABSL_SWISSTABLE_ASSERT(SwisstableGenerationsEnabled()); const size_t cap = common.capacity(); @@ -2637,7 +2638,7 @@ if (growth_left > 0 && common.should_rehash_for_bug_detection_on_insert()) { // Move to a different heap allocation in order to detect bugs. ResizeAllocatedTableWithSeedChange(common, policy, cap); - hash = recompute_hash(common.seed().seed()); + hash = recompute_hash(hasher, common.seed().seed()); FindInfo target_group; std::tie(target_group, mask_empty) = find_first_non_full_group(common, hash); @@ -2675,17 +2676,19 @@ // We need to instantiate ALL possible template combinations because we define // the function in the cc file. template void* GrowSooTableToNextCapacityAndPrepareInsert<0, false>( - CommonFields&, const PolicyFunctions&, void*, HashForKeyFn, bool); + CommonFields&, const PolicyFunctions&, EncodedHashKey, HashForKeyFn, bool); template void* GrowSooTableToNextCapacityAndPrepareInsert< OptimalMemcpySizeForSooSlotTransfer(1), true>(CommonFields&, - const PolicyFunctions&, void*, - HashForKeyFn, bool); + const PolicyFunctions&, + EncodedHashKey, HashForKeyFn, + bool); static_assert(VerifyOptimalMemcpySizeForSooSlotTransferRange(2, 3)); template void* GrowSooTableToNextCapacityAndPrepareInsert< OptimalMemcpySizeForSooSlotTransfer(3), true>(CommonFields&, - const PolicyFunctions&, void*, - HashForKeyFn, bool); + const PolicyFunctions&, + EncodedHashKey, HashForKeyFn, + bool); #if UINTPTR_MAX == UINT32_MAX static_assert(MaxSooSlotSize() == 4); @@ -2694,8 +2697,9 @@ static_assert(VerifyOptimalMemcpySizeForSooSlotTransferRange(4, 8)); template void* GrowSooTableToNextCapacityAndPrepareInsert< OptimalMemcpySizeForSooSlotTransfer(8), true>(CommonFields&, - const PolicyFunctions&, void*, - HashForKeyFn, bool); + const PolicyFunctions&, + EncodedHashKey, HashForKeyFn, + bool); static_assert(MaxSooSlotSize() == 8); #endif
diff --git a/absl/container/internal/raw_hash_set.h b/absl/container/internal/raw_hash_set.h index 536a767..01703b3 100644 --- a/absl/container/internal/raw_hash_set.h +++ b/absl/container/internal/raw_hash_set.h
@@ -2388,24 +2388,24 @@ return 8; } -using HashForKeyFn = size_t (*)(void* hasher, size_t seed); - // Resizes SOO table to the NextCapacity(SooCapacity()) and prepares insert for // the given new_hash. Returns the new slot. // All possible template combinations are defined in cc file to improve // compilation time. template <size_t SooSlotMemcpySize, bool TransferUsesMemcpy> -void* GrowSooTableToNextCapacityAndPrepareInsert( - CommonFields& common, const PolicyFunctions& policy, void* hasher, - HashForKeyFn get_hash, bool force_sampling); +void* GrowSooTableToNextCapacityAndPrepareInsert(CommonFields& common, + const PolicyFunctions& policy, + EncodedHashKey hasher, + HashForKeyFn get_hash, + bool force_sampling); // PrepareInsert for small tables (is_small()==true). // Returns the new slot. // Hash is only computed if the table is sampled or grew to large size // (is_small()==false). void* PrepareInsertSmallNonSoo(CommonFields& common, - const PolicyFunctions& policy, void* hasher, - HashForKeyFn get_hash); + const PolicyFunctions& policy, + EncodedHashKey hasher, HashForKeyFn get_hash); // Resizes table with allocated slots and change the table seed. // Tables with SOO enabled must have capacity > policy.soo_capacity. @@ -2504,7 +2504,7 @@ void* PrepareInsertLargeGenerationsEnabled( CommonFields& common, const PolicyFunctions& policy, size_t hash, Group::NonIterableBitMaskType mask_empty, size_t target_group_offset, - absl::FunctionRef<size_t(size_t)> recompute_hash); + EncodedHashKey hasher, HashForKeyFn recompute_hash); template <typename Policy, typename Hash, typename Eq, typename Alloc> struct InstantiateRawHashSet { @@ -2770,6 +2770,15 @@ constexpr static size_t kSeedShift = kIsAbslHash ? 0 : HashtableInlineData::kSeedShift; + // When `kIsAbslHash` is true, `hasher` hashes `key_type` identically to + // `absl::Hash<key_type>` (see `GetTypeErasedApplyToSlotFn`), but may convert + // other lookup keys first (e.g. `const char*` for `StringHash`). + template <class K> + using HashKeyFor = + HashKey<hasher, absl::remove_cvref_t<K>, kIsAbslHash, kSeedShift, + /*kUseCanonical=*/kIsAbslHash && + std::is_same_v<absl::remove_cvref_t<K>, key_type>>; + constexpr static bool SooEnabled() { return FitsInSooSlot(sizeof(slot_type), alignof(slot_type)); } @@ -4075,14 +4084,14 @@ } constexpr bool kUseMemcpy = PolicyTraits::transfer_uses_memcpy() && SooEnabled(); - using Hasher = HashKey<hasher, K, kIsAbslHash, kSeedShift>; + using Hasher = HashKeyFor<K>; Hasher hash_key{hash_ref(), key}; slot = to_slot( GrowSooTableToNextCapacityAndPrepareInsert< kUseMemcpy ? OptimalMemcpySizeForSooSlotTransfer(sizeof(slot_type)) : 0, - kUseMemcpy>(common(), GetPolicyFunctions(), &hash_key, - &Hasher::GetHash, force_sampling)); + kUseMemcpy>(common(), GetPolicyFunctions(), hash_key.data(), + Hasher::get_hash_fn(), force_sampling)); return {slot, true}; } @@ -4097,10 +4106,11 @@ return {single_slot(), false}; } } - using Hasher = HashKey<hasher, K, kIsAbslHash, kSeedShift>; + using Hasher = HashKeyFor<K>; Hasher hash_key{hash_ref(), key}; return {to_slot(PrepareInsertSmallNonSoo(common(), GetPolicyFunctions(), - &hash_key, &Hasher::GetHash)), + hash_key.data(), + Hasher::get_hash_fn())), true}; } @@ -4131,15 +4141,17 @@ auto mask_empty = g.MaskEmpty(); if (ABSL_PREDICT_TRUE(mask_empty)) { size_t target_group_offset = seq.offset(); - void* slot = - SwisstableGenerationsEnabled() - ? PrepareInsertLargeGenerationsEnabled( - common(), GetPolicyFunctions(), hash, mask_empty, - target_group_offset, - HashKey<hasher, absl::remove_cvref_t<K>, kIsAbslHash, - kSeedShift>{hash_ref(), key}) - : PrepareInsertLarge(common(), GetPolicyFunctions(), hash, - mask_empty, target_group_offset); + void* slot; + if constexpr (SwisstableGenerationsEnabled()) { + using Hasher = HashKeyFor<K>; + Hasher hash_key{hash_ref(), key}; + slot = PrepareInsertLargeGenerationsEnabled( + common(), GetPolicyFunctions(), hash, mask_empty, + target_group_offset, hash_key.data(), Hasher::get_hash_fn()); + } else { + slot = PrepareInsertLarge(common(), GetPolicyFunctions(), hash, + mask_empty, target_group_offset); + } return {to_slot(slot), true}; } seq.next(); @@ -4650,18 +4662,14 @@ // Extern template instantiations reduce binary size and linker input size. // Function definition is in raw_hash_set.cc. extern template void* GrowSooTableToNextCapacityAndPrepareInsert<0, false>( - CommonFields&, const PolicyFunctions&, void*, HashForKeyFn, - bool); + CommonFields&, const PolicyFunctions&, EncodedHashKey, HashForKeyFn, bool); extern template void* GrowSooTableToNextCapacityAndPrepareInsert<1, true>( - CommonFields&, const PolicyFunctions&, void*, HashForKeyFn, - bool); + CommonFields&, const PolicyFunctions&, EncodedHashKey, HashForKeyFn, bool); extern template void* GrowSooTableToNextCapacityAndPrepareInsert<4, true>( - CommonFields&, const PolicyFunctions&, void*, HashForKeyFn, - bool); + CommonFields&, const PolicyFunctions&, EncodedHashKey, HashForKeyFn, bool); #if UINTPTR_MAX == UINT64_MAX extern template void* GrowSooTableToNextCapacityAndPrepareInsert<8, true>( - CommonFields&, const PolicyFunctions&, void*, HashForKeyFn, - bool); + CommonFields&, const PolicyFunctions&, EncodedHashKey, HashForKeyFn, bool); #endif extern template void
diff --git a/absl/hash/BUILD.bazel b/absl/hash/BUILD.bazel index 50f1692..b8d9cc4 100644 --- a/absl/hash/BUILD.bazel +++ b/absl/hash/BUILD.bazel
@@ -211,6 +211,36 @@ ], ) +cc_library( + name = "canonical_hash", + hdrs = ["internal/canonical_hash.h"], + copts = ABSL_DEFAULT_COPTS, + linkopts = ABSL_DEFAULT_LINKOPTS, + visibility = [ + "//absl/container:__pkg__", + ], + deps = [ + ":hash", + "//absl/base:config", + "//absl/meta:type_traits", + ], +) + +cc_test( + name = "canonical_hash_test", + srcs = ["internal/canonical_hash_test.cc"], + copts = ABSL_TEST_COPTS, + linkopts = ABSL_DEFAULT_LINKOPTS, + deps = [ + ":canonical_hash", + ":hash", + "//absl/base:config", + "//absl/strings:string_view", + "@googletest//:gtest", + "@googletest//:gtest_main", + ], +) + cc_test( name = "low_level_hash_test", srcs = ["internal/low_level_hash_test.cc"],
diff --git a/absl/hash/CMakeLists.txt b/absl/hash/CMakeLists.txt index f8e7afa..3287b30 100644 --- a/absl/hash/CMakeLists.txt +++ b/absl/hash/CMakeLists.txt
@@ -164,6 +164,36 @@ absl::config ) +# Internal-only target, do not depend on directly. +absl_cc_library( + NAME + canonical_hash + HDRS + "internal/canonical_hash.h" + COPTS + ${ABSL_DEFAULT_COPTS} + DEPS + absl::config + absl::hash + absl::type_traits + PUBLIC +) + +absl_cc_test( + NAME + canonical_hash_test + SRCS + "internal/canonical_hash_test.cc" + COPTS + ${ABSL_TEST_COPTS} + DEPS + absl::canonical_hash + absl::config + absl::hash + absl::string_view + GTest::gmock_main +) + absl_cc_test( NAME low_level_hash_test
diff --git a/absl/hash/hash_test.cc b/absl/hash/hash_test.cc index 140a73a..e42e1a0 100644 --- a/absl/hash/hash_test.cc +++ b/absl/hash/hash_test.cc
@@ -1121,52 +1121,6 @@ EXPECT_FALSE(is_uniquely_represented<int*>::value); } -TEST(CanonicalHasherTest, UniquelyRepresentedTypesShareHasher) { - using absl::hash_internal::CanonicalHasher; - enum class Enum8 : uint8_t { kA = 1 }; - enum class Enum16 : uint16_t { kA = 1 }; - enum class Enum32 : uint32_t { kA = 1 }; - enum class SignedEnum32 : int32_t { kA = -1 }; - enum class Enum64 : uint64_t { kA = 1 }; - - EXPECT_TRUE((std::is_same_v<decltype(CanonicalHasher<int8_t>()), - absl::Hash<uint8_t>>)); - EXPECT_TRUE((std::is_same_v<decltype(CanonicalHasher<uint8_t>()), - absl::Hash<uint8_t>>)); - EXPECT_TRUE(( - std::is_same_v<decltype(CanonicalHasher<Enum8>()), absl::Hash<uint8_t>>)); - - EXPECT_TRUE((std::is_same_v<decltype(CanonicalHasher<int16_t>()), - absl::Hash<uint16_t>>)); - EXPECT_TRUE((std::is_same_v<decltype(CanonicalHasher<uint16_t>()), - absl::Hash<uint16_t>>)); - EXPECT_TRUE((std::is_same_v<decltype(CanonicalHasher<Enum16>()), - absl::Hash<uint16_t>>)); - - EXPECT_TRUE((std::is_same_v<decltype(CanonicalHasher<int32_t>()), - absl::Hash<uint32_t>>)); - EXPECT_TRUE((std::is_same_v<decltype(CanonicalHasher<uint32_t>()), - absl::Hash<uint32_t>>)); - EXPECT_TRUE((std::is_same_v<decltype(CanonicalHasher<Enum32>()), - absl::Hash<uint32_t>>)); - EXPECT_TRUE((std::is_same_v<decltype(CanonicalHasher<SignedEnum32>()), - absl::Hash<uint32_t>>)); - - EXPECT_TRUE((std::is_same_v<decltype(CanonicalHasher<int64_t>()), - absl::Hash<uint64_t>>)); - EXPECT_TRUE((std::is_same_v<decltype(CanonicalHasher<uint64_t>()), - absl::Hash<uint64_t>>)); - EXPECT_TRUE((std::is_same_v<decltype(CanonicalHasher<Enum64>()), - absl::Hash<uint64_t>>)); - - EXPECT_TRUE((std::is_same_v<decltype(CanonicalHasher<std::string>()), - absl::Hash<std::string>>)); - EXPECT_TRUE((std::is_same_v<decltype(CanonicalHasher<std::array<char, 3>>()), - absl::Hash<std::array<char, 3>>>)); - EXPECT_TRUE((std::is_same_v<decltype(CanonicalHasher<std::array<char, 5>>()), - absl::Hash<std::array<char, 5>>>)); -} - struct IntAndString { int i; std::string s;
diff --git a/absl/hash/internal/canonical_hash.h b/absl/hash/internal/canonical_hash.h new file mode 100644 index 0000000..a3c9146 --- /dev/null +++ b/absl/hash/internal/canonical_hash.h
@@ -0,0 +1,151 @@ +// Copyright 2026 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. + +#ifndef ABSL_HASH_INTERNAL_CANONICAL_HASH_H_ +#define ABSL_HASH_INTERNAL_CANONICAL_HASH_H_ + +#include <cstddef> +#include <cstdint> +#include <cstring> +#include <new> +#include <type_traits> + +#include "absl/base/config.h" +#include "absl/hash/hash.h" +#include "absl/meta/type_traits.h" + +namespace absl { +ABSL_NAMESPACE_BEGIN +namespace hash_internal { + +// Unsigned integer type of size `N` if `N` is 1, 2, 4, or 8, `void` otherwise. +template <size_t N> +using UintOfSizeT = std::conditional_t< + N == 1, uint8_t, + std::conditional_t< + N == 2, uint16_t, + std::conditional_t<N == 4, uint32_t, + std::conditional_t<N == 8, uint64_t, void>>>>; + +// Returns a canonical `absl::Hash` for `T`. Types with the exact same hash +// implementation (such as `is_uniquely_represented` types of the same size) +// return the same hasher type, which is useful for type erasure. +template <typename T> +constexpr auto CanonicalHasher() { + if constexpr (is_uniquely_represented<T>::value && + FitsIn64BitsPowerOf2<T>::value) { + return Hash<UintOfSizeT<sizeof(T)>>(); + } else { + return Hash<T>(); + } +} + +// Type-erased key argument passed by value in a single register on common ABIs. +struct EncodedHashKey { + template <class T> + static EncodedHashKey FromValue(const T& v) { + static_assert(sizeof(T) <= sizeof(bytes)); + static_assert(std::is_trivially_copyable_v<T>); + EncodedHashKey res{}; + std::memcpy(res.bytes, &v, sizeof(T)); + return res; + } + + template <class T> + static EncodedHashKey FromPtr(const T* ptr) { + return FromValue(ptr); + } + + template <class T> + const T* ToPtr() const { + const T* ptr; + std::memcpy(&ptr, bytes, sizeof(ptr)); + return ptr; + } + + // Byte array (rather than `const void*`) avoids UB and MSan `noundef` errors + // when a small key contains padding or uninitialized bytes. + alignas(void*) unsigned char bytes[sizeof(void*)]; +}; + +using HashForKeyFn = size_t (*)(EncodedHashKey hasher, size_t seed); + +// Returns true if `key` is passed by value inside `EncodedHashKey`, avoiding +// spilling it to the stack at the call site. +template <class T> +constexpr bool PassKeyByValueInEncodedHashKey() { + return FitsIn64BitsPowerOf2<T>::value && + // Not redundant on 32-bit platforms. + sizeof(T) <= sizeof(EncodedHashKey) && + alignof(T) <= alignof(EncodedHashKey) && + // Required to copy `key` by value in `CanonicalHashKey` (false for + // move-only types). + std::is_trivially_copy_constructible_v<T> && + // Required for `memcpy` (false for types with non-trivial `operator=` + // or destructor, such as `std::pair`). + std::is_trivially_copyable_v<T>; +} + +// Type erased function to apply `Hasher` (the result of `CanonicalHasher<T>()`) +// to the key encoded by `CanonicalHashKey::data()`. +template <class Hasher> +size_t TypeErasedApplyAbslHashToKeyFn(EncodedHashKey key, size_t seed) { + using T = typename Hasher::KeyType; + if constexpr (PassKeyByValueInEncodedHashKey<T>()) { + alignas(T) unsigned char buf[sizeof(T)]; + std::memcpy(buf, key.bytes, sizeof(T)); + return HashWithSeed().hash( + Hasher(), *std::launder(reinterpret_cast<const T*>(buf)), seed); + } else { + return HashWithSeed().hash(Hasher(), *key.ToPtr<T>(), seed); + } +} + +// No arguments hash function for a specific key that uses +// `CanonicalHasher<Key>`, so that `get_hash_fn()` is shared across all key +// types with the same canonical hasher. +template <class Key> +struct CanonicalHashKey { + using NonConstK = absl::remove_cvref_t<Key>; + using Canonical = decltype(CanonicalHasher<NonConstK>()); + using CanonicalKey = typename Canonical::KeyType; + + explicit CanonicalHashKey(const NonConstK& k) : key(k) {} + + // `data()` and `get_hash_fn()` are passed to type erased functions. + EncodedHashKey data() const { + // Check `CanonicalKey` to match `TypeErasedApplyAbslHashToKeyFn`. + if constexpr (PassKeyByValueInEncodedHashKey<CanonicalKey>()) { + static_assert(sizeof(NonConstK) == sizeof(CanonicalKey)); + return EncodedHashKey::FromValue(key); + } else { + return EncodedHashKey::FromPtr(&key); + } + } + static constexpr HashForKeyFn get_hash_fn() { + return &TypeErasedApplyAbslHashToKeyFn<Canonical>; + } + + // Store small keys by value so inlined caller keys are not address-taken, and + // larger keys by reference to avoid a stack copy before taking `&key`. + std::conditional_t<PassKeyByValueInEncodedHashKey<CanonicalKey>(), NonConstK, + const NonConstK&> + key; +}; + +} // namespace hash_internal +ABSL_NAMESPACE_END +} // namespace absl + +#endif // ABSL_HASH_INTERNAL_CANONICAL_HASH_H_
diff --git a/absl/hash/internal/canonical_hash_test.cc b/absl/hash/internal/canonical_hash_test.cc new file mode 100644 index 0000000..563d202 --- /dev/null +++ b/absl/hash/internal/canonical_hash_test.cc
@@ -0,0 +1,172 @@ +// Copyright 2026 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/internal/canonical_hash.h" + +#include <array> +#include <cstddef> +#include <cstdint> +#include <cstring> +#include <optional> +#include <string> +#include <type_traits> +#include <utility> + +#include "gtest/gtest.h" +#include "absl/base/config.h" +#include "absl/hash/hash.h" +#include "absl/strings/string_view.h" + +namespace absl { +ABSL_NAMESPACE_BEGIN +namespace hash_internal { +namespace { + +TEST(CanonicalHasherTest, UniquelyRepresentedTypesShareHasher) { + enum class Enum8 : uint8_t { kA = 1 }; + enum class Enum16 : uint16_t { kA = 1 }; + enum class Enum32 : uint32_t { kA = 1 }; + enum class SignedEnum32 : int32_t { kA = -1 }; + enum class Enum64 : uint64_t { kA = 1 }; + + EXPECT_TRUE((std::is_same_v<decltype(CanonicalHasher<int8_t>()), + absl::Hash<uint8_t>>)); + EXPECT_TRUE((std::is_same_v<decltype(CanonicalHasher<uint8_t>()), + absl::Hash<uint8_t>>)); + EXPECT_TRUE(( + std::is_same_v<decltype(CanonicalHasher<Enum8>()), absl::Hash<uint8_t>>)); + + EXPECT_TRUE((std::is_same_v<decltype(CanonicalHasher<int16_t>()), + absl::Hash<uint16_t>>)); + EXPECT_TRUE((std::is_same_v<decltype(CanonicalHasher<uint16_t>()), + absl::Hash<uint16_t>>)); + EXPECT_TRUE((std::is_same_v<decltype(CanonicalHasher<Enum16>()), + absl::Hash<uint16_t>>)); + + EXPECT_TRUE((std::is_same_v<decltype(CanonicalHasher<int32_t>()), + absl::Hash<uint32_t>>)); + EXPECT_TRUE((std::is_same_v<decltype(CanonicalHasher<uint32_t>()), + absl::Hash<uint32_t>>)); + EXPECT_TRUE((std::is_same_v<decltype(CanonicalHasher<Enum32>()), + absl::Hash<uint32_t>>)); + EXPECT_TRUE((std::is_same_v<decltype(CanonicalHasher<SignedEnum32>()), + absl::Hash<uint32_t>>)); + + EXPECT_TRUE((std::is_same_v<decltype(CanonicalHasher<int64_t>()), + absl::Hash<uint64_t>>)); + EXPECT_TRUE((std::is_same_v<decltype(CanonicalHasher<uint64_t>()), + absl::Hash<uint64_t>>)); + EXPECT_TRUE((std::is_same_v<decltype(CanonicalHasher<Enum64>()), + absl::Hash<uint64_t>>)); + + EXPECT_TRUE((std::is_same_v<decltype(CanonicalHasher<std::string>()), + absl::Hash<std::string>>)); + EXPECT_TRUE((std::is_same_v<decltype(CanonicalHasher<std::array<char, 3>>()), + absl::Hash<std::array<char, 3>>>)); + EXPECT_TRUE((std::is_same_v<decltype(CanonicalHasher<std::array<char, 5>>()), + absl::Hash<std::array<char, 5>>>)); +} + +TEST(CanonicalHashKeyTest, UniquelyRepresentedTypesShareHashFn) { + enum class MyEnum : uint32_t { kOne = 1, kTwo = 2 }; + using HashKeyInt32 = CanonicalHashKey<int32_t>; + using HashKeyEnum = CanonicalHashKey<MyEnum>; + EXPECT_EQ(HashKeyInt32::get_hash_fn(), HashKeyEnum::get_hash_fn()); + EXPECT_NE(HashKeyInt32::get_hash_fn(), + CanonicalHashKey<int8_t>::get_hash_fn()); + + const MyEnum c = MyEnum::kTwo; + const size_t seed = 100; + HashKeyEnum hk{c}; + EXPECT_EQ(HashKeyEnum::get_hash_fn()(hk.data(), seed), + HashWithSeed().hash(absl::Hash<MyEnum>{}, c, seed)); +} + +TEST(CanonicalHashKeyTest, DataPointerForSmallAndLargeKeys) { + // Small keys are encoded by value. + int32_t a = 42; + CanonicalHashKey<int32_t> hk_int32{a}; + int32_t decoded = 0; + std::memcpy(&decoded, hk_int32.data().bytes, sizeof(decoded)); + EXPECT_EQ(decoded, 42); + + // Keys larger than EncodedHashKey are stored by reference and encoded by + // address. + absl::string_view sv = "hello"; + CanonicalHashKey<absl::string_view> hk_sv{sv}; + EXPECT_EQ(&hk_sv.key, &sv); + EXPECT_EQ(hk_sv.data().ToPtr<absl::string_view>(), &sv); + + std::string s = "hello"; + CanonicalHashKey<std::string> hk_str{s}; + EXPECT_EQ(&hk_str.key, &s); + EXPECT_EQ(hk_str.data().ToPtr<std::string>(), &s); +} + +struct PaddedSmallKey { + char c; + int16_t i; + template <typename H> + friend H AbslHashValue(H h, const PaddedSmallKey& k) { + return H::combine(std::move(h), k.c, k.i); + } +}; + +struct NonDefaultConstructibleSmallKey { + explicit NonDefaultConstructibleSmallKey(int32_t v) : val(v) {} + template <typename H> + friend H AbslHashValue(H h, const NonDefaultConstructibleSmallKey& k) { + return H::combine(std::move(h), k.val); + } + int32_t val; +}; + +TEST(CanonicalHashKeyTest, PaddedAndPartiallyInitializedSmallKeys) { + const size_t seed = 100; + + // Small trivially copyable key with padding bytes. + EXPECT_TRUE(PassKeyByValueInEncodedHashKey<PaddedSmallKey>()); + PaddedSmallKey padded{'a', 7}; + CanonicalHashKey<PaddedSmallKey> hk_padded{padded}; + HashForKeyFn volatile fn_padded = + CanonicalHashKey<PaddedSmallKey>::get_hash_fn(); + EXPECT_EQ(fn_padded(hk_padded.data(), seed), + HashWithSeed().hash(absl::Hash<PaddedSmallKey>{}, padded, seed)); + + // Disengaged std::optional has uninitialized payload and padding bytes. + EXPECT_TRUE(PassKeyByValueInEncodedHashKey<std::optional<int16_t>>()); + std::optional<int16_t> disengaged = std::nullopt; + CanonicalHashKey<std::optional<int16_t>> hk_opt{disengaged}; + HashForKeyFn volatile fn_opt = + CanonicalHashKey<std::optional<int16_t>>::get_hash_fn(); + EXPECT_EQ(fn_opt(hk_opt.data(), seed), + HashWithSeed().hash(absl::Hash<std::optional<int16_t>>{}, + disengaged, seed)); + + // Small trivially copyable key that is not default-constructible. + EXPECT_TRUE( + PassKeyByValueInEncodedHashKey<NonDefaultConstructibleSmallKey>()); + NonDefaultConstructibleSmallKey non_def{123}; + CanonicalHashKey<NonDefaultConstructibleSmallKey> hk_non_def{non_def}; + HashForKeyFn volatile fn_non_def = + CanonicalHashKey<NonDefaultConstructibleSmallKey>::get_hash_fn(); + EXPECT_EQ(fn_non_def(hk_non_def.data(), seed), + HashWithSeed().hash(absl::Hash<NonDefaultConstructibleSmallKey>{}, + non_def, seed)); +} + +} // namespace +} // namespace hash_internal +ABSL_NAMESPACE_END +} // namespace absl
diff --git a/absl/hash/internal/hash.h b/absl/hash/internal/hash.h index bfa9eaa..861e18e 100644 --- a/absl/hash/internal/hash.h +++ b/absl/hash/internal/hash.h
@@ -1623,23 +1623,6 @@ struct Hash : std::conditional_t<is_hashable<T>::value, HashImpl<T>, PoisonedHash> {}; -// Returns a canonical `absl::Hash` for `T`. Types with the exact same hash -// implementation (such as `is_uniquely_represented` types of the same size) -// return the same hasher type, which is useful for type erasure. -template <typename T> -constexpr auto CanonicalHasher() { - if constexpr (is_uniquely_represented<T>::value && - FitsIn64BitsPowerOf2<T>::value) { - constexpr size_t N = sizeof(T); - return Hash<std::conditional_t< - N == 1, uint8_t, - std::conditional_t<N == 2, uint16_t, - std::conditional_t<N == 4, uint32_t, uint64_t>>>>(); - } else { - return Hash<T>(); - } -} - template <typename T, typename... Ts> inline constexpr bool pack_contains_v = (std::is_same_v<T, Ts> || ...);