Implement basic escaping

This commit is contained in:
Victor Zverovich 2021-08-19 14:12:26 -07:00
parent 11d49491cb
commit b559cfd4c0
2 changed files with 25 additions and 1 deletions

View File

@ -232,7 +232,26 @@ template <
FMT_ENABLE_IF(is_std_string_like<typename std::decay<Arg>::type>::value)>
OutputIt write_range_entry(OutputIt out, const Arg& v) {
*out++ = '"';
out = write<Char>(out, v);
for (Char c : basic_string_view<Char>(v)) {
switch (c) {
case '\n':
*out++ = '\\';
c = 'n';
break;
case '\r':
*out++ = '\\';
c = 'r';
break;
case '\t':
*out++ = '\\';
c = 't';
break;
case '"':
*out++ = '\\';
break;
}
*out++ = c;
}
*out++ = '"';
return out;
}

View File

@ -262,3 +262,8 @@ TEST(ranges_test, join_range) {
EXPECT_EQ(fmt::format("{}", fmt::join(z, ",")), "0,0,0");
}
#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\\\"\"]");
}