Skip to content

Commit

Permalink
Fix a discrepancy between absl::Hash and absl::HashOf for some negati…
Browse files Browse the repository at this point in the history
…ve signed integral types and improve the performance of absl::Hash.

PiperOrigin-RevId: 507598042
Change-Id: I96a7bd6b9c360f435f216b2671ae84d9768a46e8
  • Loading branch information
Abseil Team authored and copybara-github committed Feb 6, 2023
1 parent cdad8cd commit 92fc445
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 3 deletions.
15 changes: 13 additions & 2 deletions absl/hash/hash_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
#include <algorithm>
#include <array>
#include <bitset>
#include <cstdint>
#include <cstring>
#include <deque>
#include <forward_list>
Expand Down Expand Up @@ -1241,14 +1242,24 @@ TEST(HashTest, DoesNotUseImplicitConversionsToBool) {

TEST(HashOf, MatchesHashForSingleArgument) {
std::string s = "forty two";
int i = 42;
double d = 42.0;
std::tuple<int, int> t{4, 2};
int i = 42;
int neg_i = -42;
int16_t i16 = 42;
int16_t neg_i16 = -42;
int8_t i8 = 42;
int8_t neg_i8 = -42;

EXPECT_EQ(absl::HashOf(s), absl::Hash<std::string>{}(s));
EXPECT_EQ(absl::HashOf(i), absl::Hash<int>{}(i));
EXPECT_EQ(absl::HashOf(d), absl::Hash<double>{}(d));
EXPECT_EQ(absl::HashOf(t), (absl::Hash<std::tuple<int, int>>{}(t)));
EXPECT_EQ(absl::HashOf(i), absl::Hash<int>{}(i));
EXPECT_EQ(absl::HashOf(neg_i), absl::Hash<int>{}(neg_i));
EXPECT_EQ(absl::HashOf(i16), absl::Hash<int16_t>{}(i16));
EXPECT_EQ(absl::HashOf(neg_i16), absl::Hash<int16_t>{}(neg_i16));
EXPECT_EQ(absl::HashOf(i8), absl::Hash<int8_t>{}(i8));
EXPECT_EQ(absl::HashOf(neg_i8), absl::Hash<int8_t>{}(neg_i8));
}

TEST(HashOf, MatchesHashOfTupleForMultipleArguments) {
Expand Down
3 changes: 2 additions & 1 deletion absl/hash/internal/hash.h
Original file line number Diff line number Diff line change
Expand Up @@ -969,7 +969,8 @@ class ABSL_DLL MixingHashState : public HashStateBase<MixingHashState> {
// The result should be the same as running the whole algorithm, but faster.
template <typename T, absl::enable_if_t<IntegralFastPath<T>::value, int> = 0>
static size_t hash(T value) {
return static_cast<size_t>(Mix(Seed(), static_cast<uint64_t>(value)));
return static_cast<size_t>(
Mix(Seed(), static_cast<std::make_unsigned_t<T>>(value)));
}

// Overload of MixingHashState::hash()
Expand Down

0 comments on commit 92fc445

Please sign in to comment.