From 65dd2ea52c23721660cf027525c6640f868381f7 Mon Sep 17 00:00:00 2001 From: Vladislav Shchapov Date: Sat, 21 May 2022 20:12:32 +0500 Subject: [PATCH] Use write_escaped_string to std::filesystem::path. Signed-off-by: Vladislav Shchapov --- include/fmt/std.h | 29 ++++++++++++++++++++++++++++- test/std-test.cc | 2 ++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/include/fmt/std.h b/include/fmt/std.h index 4a7df19c..0ba929fa 100644 --- a/include/fmt/std.h +++ b/include/fmt/std.h @@ -20,8 +20,35 @@ # include FMT_BEGIN_NAMESPACE + +namespace detail { + template -struct formatter : basic_ostream_formatter { +void write_escaped_path(basic_memory_buffer& quoted, + const std::filesystem::path& p) { + write_escaped_string(std::back_inserter(quoted), p.string()); +} +template <> +void write_escaped_path( + basic_memory_buffer& quoted, + const std::filesystem::path& p) { + write_escaped_string( + std::back_inserter(quoted), p.native()); +} + +} // namespace detail + +template +struct formatter + : formatter> { + template + auto format(const std::filesystem::path& p, FormatContext& ctx) const -> + typename FormatContext::iterator { + basic_memory_buffer quoted; + detail::write_escaped_path(quoted, p); + return formatter>::format( + basic_string_view(quoted.data(), quoted.size()), ctx); + } }; FMT_END_NAMESPACE #endif diff --git a/test/std-test.cc b/test/std-test.cc index dcd75d5f..069c8387 100644 --- a/test/std-test.cc +++ b/test/std-test.cc @@ -12,6 +12,8 @@ TEST(std_test, path) { #ifdef __cpp_lib_filesystem EXPECT_EQ(fmt::format("{:8}", std::filesystem::path("foo")), "\"foo\" "); + EXPECT_EQ(fmt::format("{}", std::filesystem::path("foo\"bar.txt")), + "\"foo\\\"bar.txt\""); #endif }