Skip to content

Commit

Permalink
Improve quote formatter.
Browse files Browse the repository at this point in the history
  • Loading branch information
asoffer committed Dec 4, 2024
1 parent 7510163 commit 8483aca
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 11 deletions.
4 changes: 4 additions & 0 deletions .bazelversion
Original file line number Diff line number Diff line change
@@ -1 +1,5 @@
<<<<<<< Updated upstream
7.4.0
=======
7.4.1
>>>>>>> Stashed changes
42 changes: 31 additions & 11 deletions nth/format/common_formatters.h
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,17 @@ struct text_formatter {
}
};

struct byte_formatter {
void format(io::writer auto& w, std::byte b) const {
constexpr char hex[] = "0123456789abcdef";
char buffer[2];
uint8_t n = static_cast<uint8_t>(b);
buffer[0] = hex[n >> 4];
buffer[1] = hex[n & 0x0f];
io::write_text(w, buffer);
}
};

// A formatter capable of formatting text as an escaped quotation.
struct quote_formatter {
void format(io::writer auto& w, std::string_view s) const {
Expand All @@ -103,12 +114,32 @@ struct quote_formatter {
i = 0;
io::write_text(w, R"(\")");
break;
case '\t':
io::write_text(w, s.substr(0, i));
s.remove_prefix(i + 1);
i = 0;
io::write_text(w, R"(\t")");
break;
case '\\':
io::write_text(w, s.substr(0, i));
s.remove_prefix(i + 1);
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");
byte_formatter{}.format(w, static_cast<std::byte>(c));
s.remove_prefix(i);
i = 0;
}
Expand All @@ -119,17 +150,6 @@ struct quote_formatter {
}
};

struct byte_formatter {
void format(io::writer auto& w, std::byte b) const {
constexpr char hex[] = "0123456789abcdef";
char buffer[2];
uint8_t n = static_cast<uint8_t>(b);
buffer[0] = hex[n >> 4];
buffer[1] = hex[n & 0x0f];
io::write_text(w, buffer);
}
};

struct pointer_formatter {
void format(io::writer auto& w, void const* ptr) const {
constexpr char hex[] = "0123456789abcdef";
Expand Down
3 changes: 3 additions & 0 deletions nth/format/json_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,9 @@ NTH_TEST("format/json/string") {
NTH_EXPECT(json("\"hello\n\"") == R"("\"hello\n\"")");
NTH_EXPECT(json(std::string_view("\"hello\n\"")) == R"("\"hello\n\"")");
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));
}

NTH_TEST("format/json/array") {
Expand Down

0 comments on commit 8483aca

Please sign in to comment.