Skip to content

Commit

Permalink
Add a path formatter
Browse files Browse the repository at this point in the history
  • Loading branch information
vitaut committed May 17, 2022
1 parent 8833f38 commit f0903ad
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
29 changes: 29 additions & 0 deletions include/fmt/std.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// Formatting library for C++ - formatters for standard library types
//
// Copyright (c) 2012 - present, Victor Zverovich
// All rights reserved.
//
// For the license information refer to format.h.

#ifndef FMT_STD_H_
#define FMT_STD_H_

#include <version>

#ifdef __cpp_lib_filesystem
# include <filesystem>

namespace fmt {

template <> struct formatter<std::filesystem::path> : formatter<string_view> {
template <typename FormatContext>
auto format(const path& p, FormatContext& ctx) const ->
typename FormatContext::iterator {
return formatter<string_view>::format(p.string(), ctx);

This comment has been minimized.

Copy link
@phprus

phprus May 17, 2022

Contributor

The result will be different from operator<<(std::filesystem::path).
For an identical result, you need to use std::quoted or equivalent.

See:

  1. https://en.cppreference.com/w/cpp/filesystem/path/operator_ltltgtgt
  2. https://godbolt.org/z/a6hnq8rhz

This comment has been minimized.

Copy link
@vitaut

vitaut May 17, 2022

Author Contributor

PR is welcome! =)

This comment has been minimized.

Copy link
@ilyapopov

ilyapopov May 18, 2022

On the other topic, path::string() makes an allocation. Could path::native() be used instead? This may need some compile-time logic depending on if a platform uses char or wchar for native().

This comment has been minimized.

Copy link
@vitaut

vitaut May 18, 2022

Author Contributor

Potentially yes.

}
};

} // namespace fmt
#endif

#endif // FMT_STD_H_
16 changes: 16 additions & 0 deletions test/std-test.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// Formatting library for C++ - tests of formatters for standard library types
//
// Copyright (c) 2012 - present, Victor Zverovich
// All rights reserved.
//
// For the license information refer to format.h.

#include "fmt/std.h"

#include "gtest/gtest.h"

TEST(std_test, path) {
#ifdef __cpp_lib_filesystem
EXPECT_EQ(fmt::format("{:8}", std::filesystem::path("foo")), "foo ");
#endif
}

0 comments on commit f0903ad

Please sign in to comment.