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