From 4211d8653918282e2f7cad6ec3d70006ffbbce18 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=92=D0=BB=D0=B0=D0=B4=D0=B8=D1=81=D0=BB=D0=B0=D0=B2=20?= =?UTF-8?q?=D0=A9=D0=B0=D0=BF=D0=BE=D0=B2?= Date: Sat, 8 May 2021 16:51:51 +0500 Subject: [PATCH] Add a formatter specialization for std::error_code. --- include/fmt/os.h | 17 +++++++++++++++++ test/os-test.cc | 24 ++++++++++++++++++++++++ 2 files changed, 41 insertions(+) diff --git a/include/fmt/os.h b/include/fmt/os.h index 482b1a81..cd40c031 100644 --- a/include/fmt/os.h +++ b/include/fmt/os.h @@ -129,6 +129,23 @@ class error_code { int get() const FMT_NOEXCEPT { return value_; } }; +template struct formatter { + template + FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) { + return ctx.begin(); + } + + template + FMT_CONSTEXPR auto format(const std::error_code& ec, FormatContext& ctx) const + -> decltype(ctx.out()) { + auto out = ctx.out(); + out = detail::write(out, to_string_view(ec.category().name())); + out = detail::write(out, Char(':')); + out = detail::write(out, ec.value()); + return out; + } +}; + #ifdef _WIN32 namespace detail { // A converter from UTF-16 to UTF-8. diff --git a/test/os-test.cc b/test/os-test.cc index b2c38af7..c7e45021 100644 --- a/test/os-test.cc +++ b/test/os-test.cc @@ -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(