Skip to content

Commit

Permalink
Use custom escaping function to std::filesystem::path.
Browse files Browse the repository at this point in the history
Signed-off-by: Vladislav Shchapov <vladislav@shchapov.ru>
  • Loading branch information
phprus committed May 21, 2022
1 parent 42669f3 commit 9a3ce3f
Showing 1 changed file with 46 additions and 1 deletion.
47 changes: 46 additions & 1 deletion include/fmt/std.h
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,53 @@
# include <filesystem>

FMT_BEGIN_NAMESPACE

namespace detail {

template <typename Char>
void write_escaped_path_impl(basic_memory_buffer<Char>& quoted,
const basic_string_view<Char>& 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 <typename Char>
void write_escaped_path(basic_memory_buffer<Char>& quoted,
const std::filesystem::path& p) {
auto str = p.string<Char>();
write_escaped_path_impl<Char>(quoted, str);
}
template <>
void write_escaped_path<std::filesystem::path::value_type>(
basic_memory_buffer<std::filesystem::path::value_type>& quoted,
const std::filesystem::path& p) {
write_escaped_path_impl<std::filesystem::path::value_type>(quoted,
p.native());
}

} // namespace detail

template <typename Char>
struct formatter<std::filesystem::path, Char> : basic_ostream_formatter<Char> {
struct formatter<std::filesystem::path, Char>
: formatter<basic_string_view<Char>> {
template <typename FormatContext>
auto format(const std::filesystem::path& p, FormatContext& ctx) const ->
typename FormatContext::iterator {
basic_memory_buffer<Char> quoted;
detail::write_escaped_path(quoted, p);
return formatter<basic_string_view<Char>>::format(
basic_string_view<Char>(quoted.data(), quoted.size()), ctx);
}
};
FMT_END_NAMESPACE
#endif
Expand Down

0 comments on commit 9a3ce3f

Please sign in to comment.