From a289c39984738bc28617a357017a9a4e50e9d34f Mon Sep 17 00:00:00 2001 From: Vladislav Shchapov Date: Sat, 21 May 2022 20:12:32 +0500 Subject: [PATCH] Use custom escaping function to std::filesystem::path. Signed-off-by: Vladislav Shchapov --- include/fmt/std.h | 45 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 44 insertions(+), 1 deletion(-) diff --git a/include/fmt/std.h b/include/fmt/std.h index 4a7df19c6bd64..db85758a8891a 100644 --- a/include/fmt/std.h +++ b/include/fmt/std.h @@ -20,8 +20,51 @@ # include FMT_BEGIN_NAMESPACE + +namespace detail { + +template +void do_write_escaped_path(basic_memory_buffer& quoted, + const basic_string_view& sv) { + quoted.push_back(Char('"')); + for (auto i = sv.begin(); i != sv.end(); ++i) { + switch (*i) { + case Char('"'): + FMT_FALLTHROUGH; + case Char('\\'): + quoted.push_back(Char('\\')); + FMT_FALLTHROUGH; + default: + quoted.push_back(*i); + } + } + quoted.push_back(Char('"')); +} +template +void write_escaped_path(basic_memory_buffer& quoted, + const std::filesystem::path& p) { + do_write_escaped_path(quoted, p.string()); +} +template <> +void write_escaped_path( + basic_memory_buffer& quoted, + const std::filesystem::path& p) { + do_write_escaped_path(quoted, p.native()); +} + +} // namespace detail + template -struct formatter : basic_ostream_formatter { +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