Skip to content

Commit

Permalink
Ensure quote formatter is compatible with JSON.
Browse files Browse the repository at this point in the history
  • Loading branch information
asoffer committed Dec 6, 2024
1 parent 19c2eec commit 54ef856
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 10 deletions.
12 changes: 3 additions & 9 deletions nth/format/common_formatters.h
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ struct byte_formatter {
uint8_t n = static_cast<uint8_t>(b);
buffer[0] = hex[n >> 4];
buffer[1] = hex[n & 0x0f];
io::write_text(w, buffer);
io::write_text(w, std::string_view(buffer, 2));
}
};

Expand Down Expand Up @@ -126,21 +126,15 @@ struct quote_formatter {
i = 0;
io::write_text(w, R"(\\)");
break;
case '\0':
io::write_text(w, s.substr(0, i));
s.remove_prefix(i + 1);
i = 0;
io::write_text(w, R"(\0)");
break;
default:
if (std::isprint(c)) {
++i;
continue;
} else {
io::write_text(w, s.substr(0, i));
io::write_text(w, "\\x");
s.remove_prefix(i + 1);
io::write_text(w, "\\u00");
byte_formatter{}.format(w, static_cast<std::byte>(c));
s.remove_prefix(i);
i = 0;
}
}
Expand Down
6 changes: 5 additions & 1 deletion nth/format/json_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,11 @@ NTH_TEST("format/json/string") {
NTH_EXPECT(json(std::string("\"hello\n\"")) == R"("\"hello\n\"")");
NTH_EXPECT(json(std::string("hello\\world")) == R"("hello\\world")");
NTH_EXPECT(json(std::string("hello\0world", 11)) ==
std::string_view(R"("hello\0world")", 14));
std::string_view(R"("hello\u0000world")"));
NTH_EXPECT(json(std::string("hello\u0000world", 11)) ==
std::string_view(R"("hello\u0000world")"));
NTH_EXPECT(json(std::string("hello\7world")) ==
std::string_view(R"("hello\u0007world")"));
NTH_EXPECT(json(std::string("hello\\0world")) ==
std::string_view(R"("hello\\0world")"));
}
Expand Down

0 comments on commit 54ef856

Please sign in to comment.