Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix point hash to be well distributed. #76250

Merged
merged 1 commit into from
Sep 8, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 29 additions & 12 deletions src/point.h
Original file line number Diff line number Diff line change
Expand Up @@ -303,11 +303,20 @@ namespace std
template <>
struct hash<point> {
std::size_t operator()( const point &k ) const noexcept {
constexpr uint64_t a = 2862933555777941757;
size_t result = k.y;
result *= a;
result += k.x;
return result;
// We cast k.y to uint32_t because otherwise when promoting to uint64_t for binary `or` it
// will sign extend and turn the upper 32 bits into all 1s.
uint64_t x = static_cast<uint64_t>( k.x ) << 32 | static_cast<uint32_t>( k.y );

// Found through https://nullprogram.com/blog/2018/07/31/
// Public domain source from https://xoshiro.di.unimi.it/splitmix64.c
x ^= x >> 30;
x *= 0xbf58476d1ce4e5b9U;
x ^= x >> 27;
x *= 0x94d049bb133111ebU;
x ^= x >> 31;
return x;

return x;
}
};
} // namespace std
Expand All @@ -319,13 +328,21 @@ namespace std
template <>
struct hash<tripoint> {
std::size_t operator()( const tripoint &k ) const noexcept {
constexpr uint64_t a = 2862933555777941757;
size_t result = k.z;
result *= a;
result += k.y;
result *= a;
result += k.x;
return result;
// We cast k.y to uint32_t because otherwise when promoting to uint64_t for binary `or` it
// will sign extend and turn the upper 32 bits into all 1s.
uint64_t x = static_cast<uint64_t>( k.x ) << 32 | static_cast<uint32_t>( k.y );

// Found through https://nullprogram.com/blog/2018/07/31/
// Public domain source from https://xoshiro.di.unimi.it/splitmix64.c
x ^= x >> 30;
x *= 0xbf58476d1ce4e5b9U;
x ^= x >> 27;

// Sprinkle in z now.
x ^= static_cast<uint64_t>( k.z );
x *= 0x94d049bb133111ebU;
x ^= x >> 31;
return x;
}
};
} // namespace std
Expand Down
Loading