Skip to content

Commit

Permalink
Add a formatter specialization for std::error_code.
Browse files Browse the repository at this point in the history
  • Loading branch information
phprus committed May 8, 2021
1 parent 84feeb0 commit 434fb5d
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 0 deletions.
18 changes: 18 additions & 0 deletions include/fmt/os.h
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,24 @@ class error_code {
int get() const FMT_NOEXCEPT { return value_; }
};

// A formatter specialization for std::error_code.
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
4 changes: 4 additions & 0 deletions test/compile-test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
// For the license information refer to format.h.

#include "fmt/compile.h"
#include "fmt/os.h"

#include <type_traits>

Expand Down Expand Up @@ -84,6 +85,9 @@ TEST(compile_test, format_default) {
# ifdef __cpp_lib_byte
EXPECT_EQ("42", fmt::format(FMT_COMPILE("{}"), std::byte{42}));
# endif
EXPECT_EQ("generic:42",
fmt::format(FMT_COMPILE("{}"),
std::error_code(42, std::generic_category())));
}

TEST(compile_test, format_wide_string) {
Expand Down
18 changes: 18 additions & 0 deletions test/os-test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,24 @@ TEST(util_test, utf16_to_utf8_convert) {
u.convert(fmt::wstring_view(L"foo", INT_MAX + 1u)));
}

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

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

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

0 comments on commit 434fb5d

Please sign in to comment.