Skip to content

Commit

Permalink
Added formatter for std::source_location
Browse files Browse the repository at this point in the history
  • Loading branch information
felix642 committed Nov 29, 2023
1 parent 5cfd28d commit 54eaa8c
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
31 changes: 31 additions & 0 deletions include/fmt/std.h
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,10 @@
# endif
#endif

#if FMT_CPLUSPLUS > 201703L && FMT_HAS_INCLUDE(<source_location>)
# include <source_location>
#endif

// GCC 4 does not support FMT_HAS_INCLUDE.
#if FMT_HAS_INCLUDE(<cxxabi.h>) || defined(__GLIBCXX__)
# include <cxxabi.h>
Expand Down Expand Up @@ -228,6 +232,33 @@ struct formatter<std::optional<T>, Char,
FMT_END_NAMESPACE
#endif // __cpp_lib_optional

#ifdef __cpp_lib_source_location
FMT_BEGIN_NAMESPACE
FMT_EXPORT
template <typename Char>
struct formatter<std::source_location, Char,
std::enable_if_t<is_formattable<Char>::value>> {
template <typename ParseContext> FMT_CONSTEXPR auto parse(ParseContext& ctx) {
return ctx.begin();
}

template <typename FormatContext>
auto format(const std::source_location& loc, FormatContext& ctx) const
-> decltype(ctx.out()) {
auto out = ctx.out();
out = detail::write_bytes(out, loc.file_name(), format_specs<Char>());
out = detail::write<Char>(out, Char(':'));
out = detail::write<Char>(out, loc.line());
out = detail::write<Char>(out, Char(':'));
out = detail::write<Char>(out, loc.column());
out = detail::write<Char>(out, ": ");
out = detail::write<Char>(out, loc.function_name());
return out;
}
};
FMT_END_NAMESPACE
#endif

#if FMT_CPP_LIB_VARIANT
FMT_BEGIN_NAMESPACE
namespace detail {
Expand Down
10 changes: 10 additions & 0 deletions test/std-test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,16 @@ TEST(std_test, thread_id) {
EXPECT_FALSE(fmt::format("{}", std::this_thread::get_id()).empty());
}

#ifdef __cpp_lib_source_location
TEST(std_test, source_location) {
std::source_location loc = std::source_location::current();
EXPECT_EQ(fmt::format("{}", loc), std::string(loc.file_name()) + ":" +
std::to_string(loc.line()) + ":" +
std::to_string(loc.column()) + ": " +
loc.function_name());
}
#endif

TEST(std_test, optional) {
#ifdef __cpp_lib_optional
EXPECT_EQ(fmt::format("{}", std::optional<int>{}), "none");
Expand Down

0 comments on commit 54eaa8c

Please sign in to comment.