We should escape

This commit is contained in:
Victor Zverovich 2021-08-19 14:34:06 -07:00
parent b559cfd4c0
commit 11b07a56b2
2 changed files with 13 additions and 2 deletions

View File

@ -227,6 +227,10 @@ template <typename OutputIt> OutputIt write_delimiter(OutputIt out) {
return out;
}
template <typename Char> inline bool is_printable_ascii(Char c) {
return c >= 0x20 && c < 0x7e;
}
template <
typename Char, typename OutputIt, typename Arg,
FMT_ENABLE_IF(is_std_string_like<typename std::decay<Arg>::type>::value)>
@ -247,8 +251,14 @@ OutputIt write_range_entry(OutputIt out, const Arg& v) {
c = 't';
break;
case '"':
FMT_FALLTHROUGH;
case '\\':
*out++ = '\\';
break;
default:
if (is_printable_ascii(c)) break;
out = format_to(out, "\\x{:02x}", c);
continue;
}
*out++ = c;
}

View File

@ -264,6 +264,7 @@ TEST(ranges_test, join_range) {
#endif // FMT_RANGES_TEST_ENABLE_JOIN
TEST(ranges_test, escape_string) {
auto v = std::vector<std::string>{"\n\r\t\""};
EXPECT_EQ(fmt::format("{}", v), "[\"\\n\\r\\t\\\"\"]");
EXPECT_EQ(fmt::format("{}", std::vector<std::string>{"\n\r\t\"\\"}),
"[\"\\n\\r\\t\\\"\\\\\"]");
EXPECT_EQ(fmt::format("{}", std::vector<std::string>{"\x7"}), "[\"\\x07\"]");
}