Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a formatter specialization for std::error_code. #2270

Merged
merged 1 commit into from
May 9, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions include/fmt/os.h
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,23 @@ class error_code {
int get() const FMT_NOEXCEPT { return value_; }
};

template <typename Char> struct formatter<std::error_code, Char> {
template <typename ParseContext>
FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
return ctx.begin();
}

template <typename FormatContext>
FMT_CONSTEXPR auto format(const std::error_code& ec, FormatContext& ctx) const
-> decltype(ctx.out()) {
auto out = ctx.out();
out = detail::write<Char>(out, to_string_view(ec.category().name()));
out = detail::write<Char>(out, Char(':'));
out = detail::write<Char>(out, ec.value());
return out;
}
};

#ifdef _WIN32
namespace detail {
// A converter from UTF-16 to UTF-8.
Expand Down
24 changes: 24 additions & 0 deletions test/os-test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,30 @@ TEST(os_test, error_code) {
EXPECT_EQ(error_code(42).get(), 42);
}

TEST(os_test, format_std_error_code) {
EXPECT_EQ("generic:42",
fmt::format(FMT_STRING("{0}"),
std::error_code(42, std::generic_category())));
EXPECT_EQ("system:42",
fmt::format(FMT_STRING("{0}"),
std::error_code(42, std::system_category())));
EXPECT_EQ("system:-42",
fmt::format(FMT_STRING("{0}"),
std::error_code(-42, std::system_category())));
}

TEST(os_test, format_std_error_code_wide) {
EXPECT_EQ(L"generic:42",
fmt::format(FMT_STRING(L"{0}"),
std::error_code(42, std::generic_category())));
EXPECT_EQ(L"system:42",
fmt::format(FMT_STRING(L"{0}"),
std::error_code(42, std::system_category())));
EXPECT_EQ(L"system:-42",
fmt::format(FMT_STRING(L"{0}"),
std::error_code(-42, std::system_category())));
}

TEST(os_test, format_windows_error) {
LPWSTR message = 0;
auto result = FormatMessageW(
Expand Down