Skip to content

Commit

Permalink
Fix custom hash functions used in pathfinding to not drop bits on 32-…
Browse files Browse the repository at this point in the history
…bit systems. (CleverRaven#53019)
  • Loading branch information
eltank authored Nov 26, 2021
1 parent 04d1bce commit ba02317
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 5 deletions.
28 changes: 28 additions & 0 deletions src/hash_utils.h
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,34 @@ struct range_hash {
}
};

namespace hash64_detail
{

template<typename T>
std::enable_if_t < sizeof( T ) < 8, T > maybe_mix_bits( std::uint64_t val )
{
std::uint32_t hi = val >> 32;
std::uint32_t lo = val;
T ret = hi;
hash_combine( ret, lo );
return ret;
}

template<typename T>
std::enable_if_t < sizeof( T ) >= 8, T > maybe_mix_bits( std::uint64_t val )
{
return val;
}

} // namespace hash64_detail

// hash64 hashes a 64-bit integer, either using the identity function (on 64-bit systems)
// or using hash_combine on the two 32-bit halves (on 32-bit systems)
inline std::size_t hash64( std::uint64_t val )
{
return hash64_detail::maybe_mix_bits<std::size_t>( val );
}

} // namespace cata

#endif // CATA_SRC_HASH_UTILS_H
7 changes: 4 additions & 3 deletions src/simple_pathfinding.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

#include "coordinates.h"
#include "enums.h"
#include "hash_utils.h"
#include "line.h"
#include "omdata.h"
#include "point.h"
Expand Down Expand Up @@ -192,10 +193,10 @@ struct node_address {

struct node_address_hasher {
std::size_t operator()( const node_address &addr ) const {
std::size_t val = addr.x;
std::uint64_t val = addr.x;
val = ( val << 16 ) + addr.y;
val = ( val << 16 ) + static_cast<int>( addr.z );
return std::hash<std::size_t> {}( val );
val = ( val << 16 ) + addr.z;
return cata::hash64( val );
}
};

Expand Down
5 changes: 3 additions & 2 deletions src/vehicle_autodrive.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
#include "cuboid_rectangle.h"
#include "debug.h"
#include "enums.h"
#include "hash_utils.h"
#include "map.h"
#include "map_iterator.h"
#include "map_memory.h"
Expand Down Expand Up @@ -197,10 +198,10 @@ struct node_address {

struct node_address_hasher {
std::size_t operator()( const node_address &addr ) const {
std::int64_t val = addr.x;
std::uint64_t val = addr.x;
val = ( val << 16 ) + addr.y;
val = ( val << 16 ) + static_cast<int>( addr.facing_dir );
return std::hash<int64_t> {}( val );
return cata::hash64( val );
}
};

Expand Down

0 comments on commit ba02317

Please sign in to comment.