Makes Types in Squared Dist Calculation Explicit, see #3483.
This commit is contained in:
parent
76de3b6ace
commit
7b11cd3a11
@ -21,10 +21,15 @@ namespace coordinate_calculation
|
|||||||
// Does not project the coordinates!
|
// Does not project the coordinates!
|
||||||
std::uint64_t squaredEuclideanDistance(const Coordinate lhs, const Coordinate rhs)
|
std::uint64_t squaredEuclideanDistance(const Coordinate lhs, const Coordinate rhs)
|
||||||
{
|
{
|
||||||
const std::uint64_t dx = static_cast<std::int32_t>(lhs.lon - rhs.lon);
|
std::int64_t d_lon = static_cast<std::int32_t>(lhs.lon - rhs.lon);
|
||||||
const std::uint64_t dy = static_cast<std::int32_t>(lhs.lat - rhs.lat);
|
std::int64_t d_lat = static_cast<std::int32_t>(lhs.lat - rhs.lat);
|
||||||
|
|
||||||
return dx * dx + dy * dy;
|
std::int64_t sq_lon = d_lon * d_lon;
|
||||||
|
std::int64_t sq_lat = d_lat * d_lat;
|
||||||
|
|
||||||
|
std::uint64_t result = static_cast<std::uint64_t>(sq_lon + sq_lat);
|
||||||
|
|
||||||
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
double haversineDistance(const Coordinate coordinate_1, const Coordinate coordinate_2)
|
double haversineDistance(const Coordinate coordinate_1, const Coordinate coordinate_2)
|
||||||
|
@ -311,4 +311,18 @@ BOOST_AUTO_TEST_CASE(circleCenter)
|
|||||||
BOOST_CHECK(!result);
|
BOOST_CHECK(!result);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// For overflow issue #3483, introduced in 68ee4eab61548. Run with -fsanitize=integer.
|
||||||
|
BOOST_AUTO_TEST_CASE(squaredEuclideanDistance)
|
||||||
|
{
|
||||||
|
// Overflow happens when left hand side values are smaller than right hand side values,
|
||||||
|
// then `lhs - rhs` will be negative but stored in a uint64_t (wraps around).
|
||||||
|
|
||||||
|
Coordinate lhs(FloatLongitude{-180}, FloatLatitude{-90});
|
||||||
|
Coordinate rhs(FloatLongitude{180}, FloatLatitude{90});
|
||||||
|
|
||||||
|
const auto result = coordinate_calculation::squaredEuclideanDistance(lhs, rhs);
|
||||||
|
|
||||||
|
BOOST_CHECK_EQUAL(result, 162000000000000000ull);
|
||||||
|
}
|
||||||
|
|
||||||
BOOST_AUTO_TEST_SUITE_END()
|
BOOST_AUTO_TEST_SUITE_END()
|
||||||
|
Loading…
Reference in New Issue
Block a user