Skip to content

Commit

Permalink
Actually escape characters. (#2559)
Browse files Browse the repository at this point in the history
* Actually escape characters.
Close #2558

* Wrap initialization to satisfy older compiler.
  • Loading branch information
abellgithub committed Jun 7, 2019
1 parent cd3ad19 commit 047fbd7
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 11 deletions.
36 changes: 27 additions & 9 deletions pdal/util/Utils.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@

#include <pdal/util/Utils.hpp>

#include <array>
#include <cassert>
#include <cstdlib>
#include <cctype>
Expand Down Expand Up @@ -416,20 +417,37 @@ std::string Utils::replaceAll(std::string result,
}


// Adapted from http://stackoverflow.com/a/11969098.
std::string Utils::escapeJSON(const std::string &str)
{
std::string escaped(str);

size_t pos(0);

while((pos = escaped.find_first_of("\"\\", pos)) != std::string::npos)
std::string s(str);

std::array<std::string, 35> replacements {
{ "\\u0000", "\\u0001", "\\u0002", "\\u0003", "\\u0004",
"\\u0005", "\\u0006", "\\u0007", "\\u0008", "\\t",
"\\n", "\\b", "\\f", "\\r", "\\u000E",
"\\u000F", "\\u0010", "\\u0011", "\\0012", "\\u0013",
"\\u0014", "\\u0015", "\\u0016", "\\u0017", "\\u0018",
"\\u0019", "\\u001A", "\\u001B", "\\u001C", "\\u001D",
"\\u001E", "\\u001F", " ", "!", "\\\"" }
};
for (std::string::size_type i = 0; i < s.size();)
{
escaped.insert(pos, "\\");
pos += 2;
char val = s[i];
if (val < (char)replacements.size())
{
s.replace(i, 1, replacements[val]);
i += replacements[val].size();
}
else if (val == '\\')
{
s.replace(i, 1, "\\\\");
i += 2;
}
else
i++;
}

return escaped;
return s;
}


Expand Down
4 changes: 2 additions & 2 deletions test/unit/UtilsTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -458,6 +458,6 @@ TEST(UtilsTest, numeric_cast)

TEST(UtilsTest, escapeJSON)
{
std::string escaped = Utils::escapeJSON("0.1234\n-0.9876");
EXPECT_EQ("0.1234\n-0.9876", escaped);
std::string escaped = Utils::escapeJSON("\u0001\t\f\n\\\"\u0016");
EXPECT_EQ(escaped, "\\u0001\\t\\f\\n\\\\\\\"\\u0016");
}

0 comments on commit 047fbd7

Please sign in to comment.