Quickfixes polyline encoder's undefined behavior via left-shifting negative numbers

This commit is contained in:
Daniel J. Hofmann 2016-01-22 19:36:10 +01:00
parent 312b414d8f
commit 0fbdd57835

View File

@ -1,6 +1,7 @@
#include "engine/polyline_compressor.hpp" #include "engine/polyline_compressor.hpp"
#include <cstddef> #include <cstddef>
#include <cmath>
namespace osrm namespace osrm
{ {
@ -27,13 +28,22 @@ std::string encode(int number_to_encode)
std::string encode(std::vector<int> &numbers) std::string encode(std::vector<int> &numbers)
{ {
std::string output; std::string output;
const auto end = numbers.size(); for (auto &number : numbers)
for (std::size_t i = 0; i < end; ++i)
{ {
numbers[i] <<= 1; bool isNegative = number < 0;
if (numbers[i] < 0)
if (isNegative)
{ {
numbers[i] = ~(numbers[i]); const unsigned binary = std::llabs(number);
const unsigned twos = (~binary) + 1u;
number = twos;
}
number <<= 1u;
if (isNegative)
{
number = ~number;
} }
} }
for (const int number : numbers) for (const int number : numbers)