Skip to content

Commit

Permalink
JSON-escape strings (#4)
Browse files Browse the repository at this point in the history
  • Loading branch information
d3m3t3r authored Jun 27, 2024
1 parent 496f255 commit 54f7f72
Showing 1 changed file with 44 additions and 3 deletions.
47 changes: 44 additions & 3 deletions src/basset.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,47 @@ using std::unordered_set;
using std::vector;
using std::literals::string_literals::operator""s;

string json_escape(const string &str) {
std::string s;

for (auto c : str) {
if (c >= 0 && c < 0x20) {
s.push_back('\\');

switch (c) {
case '\b':
c = 'b';
break;
case '\t':
c = 't';
break;
case '\n':
c = 'n';
break;
case '\f':
c = 'f';
break;
case '\r':
c = 'r';
break;
default:
static const char hex[] = "0123456789abcdef";
char u[] = "u0000";
u[3] = hex[c >> 4];
u[4] = hex[c & 0xf];
s.append(u);
continue;
}
} else if (c == '\\' || c == '"') {
s.push_back('\\');
}

s.push_back(c);
}

return s;
}

class Pipe {
public:
Pipe();
Expand Down Expand Up @@ -191,7 +232,7 @@ void CompilationDatabase::add(const string &directory,
*this << "\n"
" {\n"
// clang-format off
" \"directory\": \"" << directory << "\",\n"
" \"directory\": \"" << json_escape(directory) << "\",\n"
// clang-format on
" \"arguments\": [";

Expand All @@ -206,14 +247,14 @@ void CompilationDatabase::add(const string &directory,

*this << "\n"
// clang-format off
" \"" << arg << '\"';
" \"" << json_escape(arg) << '\"';
// clang-format on
}

*this << "\n"
" ],\n"
// clang-format off
" \"file\": \"" << file << "\"\n"
" \"file\": \"" << json_escape(file) << "\"\n"
// clang-format on
" }";
}
Expand Down

0 comments on commit 54f7f72

Please sign in to comment.