Escape string in json renderer

This commit is contained in:
Patrick Niklaus 2015-02-25 21:10:09 +01:00
parent fdf2e5934d
commit 440eda3807
2 changed files with 42 additions and 10 deletions

View File

@ -56,19 +56,11 @@ std::string PolylineCompressor::encode_number(int number_to_encode) const
{ {
const int next_value = (0x20 | (number_to_encode & 0x1f)) + 63; const int next_value = (0x20 | (number_to_encode & 0x1f)) + 63;
output += static_cast<char>(next_value); output += static_cast<char>(next_value);
if (92 == next_value)
{
output += static_cast<char>(next_value);
}
number_to_encode >>= 5; number_to_encode >>= 5;
} }
number_to_encode += 63; number_to_encode += 63;
output += static_cast<char>(number_to_encode); output += static_cast<char>(number_to_encode);
if (92 == number_to_encode)
{
output += static_cast<char>(number_to_encode);
}
return output; return output;
} }

View File

@ -40,11 +40,33 @@ namespace osrm
namespace json namespace json
{ {
struct Renderer : mapbox::util::static_visitor<> struct Renderer : mapbox::util::static_visitor<>
{ {
explicit Renderer(std::ostream &_out) : out(_out) {} explicit Renderer(std::ostream &_out) : out(_out) {}
void operator()(const String &string) const { out << "\"" << string.value << "\""; } void operator()(const String &string) const {
out << "\"";
// check if we need escaping
std::size_t pos = string.value.find_first_of('\\');
if (pos != std::string::npos)
{
std::string escapedString(string.value);
do
{
escapedString.insert(pos, 1, '\\');
pos = escapedString.find_first_of('\\', pos);
} while (pos != std::string::npos);
}
// no need to escape
else
{
out << string.value;
}
out << "\"";
}
void operator()(const Number &number) const void operator()(const Number &number) const
{ {
@ -101,7 +123,25 @@ struct ArrayRenderer : mapbox::util::static_visitor<>
void operator()(const String &string) const void operator()(const String &string) const
{ {
out.push_back('\"'); out.push_back('\"');
out.insert(out.end(), string.value.begin(), string.value.end());
// check if we need escaping
std::size_t pos = string.value.find_first_of('\\');
if (pos != std::string::npos)
{
std::string escapedString(string.value);
do
{
escapedString.insert(pos, 1, '\\');
pos = escapedString.find_first_of('\\', pos+2);
} while (pos != std::string::npos);
out.insert(out.end(), escapedString.begin(), escapedString.end());
}
// no need to escape
else
{
out.insert(out.end(), string.value.begin(), string.value.end());
}
out.push_back('\"'); out.push_back('\"');
} }