From b559cfd4c0a155112fcf3db8c060fea8204c51d8 Mon Sep 17 00:00:00 2001 From: Victor Zverovich Date: Thu, 19 Aug 2021 14:12:26 -0700 Subject: [PATCH] Implement basic escaping --- include/fmt/ranges.h | 21 ++++++++++++++++++++- test/ranges-test.cc | 5 +++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/include/fmt/ranges.h b/include/fmt/ranges.h index 317b7298..f4bbffe2 100644 --- a/include/fmt/ranges.h +++ b/include/fmt/ranges.h @@ -232,7 +232,26 @@ template < FMT_ENABLE_IF(is_std_string_like::type>::value)> OutputIt write_range_entry(OutputIt out, const Arg& v) { *out++ = '"'; - out = write(out, v); + for (Char c : basic_string_view(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; } diff --git a/test/ranges-test.cc b/test/ranges-test.cc index 4932fe21..f3fc9df1 100644 --- a/test/ranges-test.cc +++ b/test/ranges-test.cc @@ -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{"\n\r\t\""}; + EXPECT_EQ(fmt::format("{}", v), "[\"\\n\\r\\t\\\"\"]"); +} \ No newline at end of file