From c936e2e44ec753fb9dfe6c57e29e189bf5d3717d Mon Sep 17 00:00:00 2001 From: Victor Zverovich Date: Sun, 27 Apr 2025 09:06:17 -0700 Subject: [PATCH] Implement debug format for error_code --- include/fmt/std.h | 20 ++++++++++++++------ test/std-test.cc | 2 ++ 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/include/fmt/std.h b/include/fmt/std.h index 62a45f42..f43dc74d 100644 --- a/include/fmt/std.h +++ b/include/fmt/std.h @@ -410,6 +410,7 @@ template <> struct formatter { private: format_specs specs_; detail::arg_ref width_ref_; + bool debug_ = false; public: FMT_CONSTEXPR auto parse(parse_context<>& ctx) -> const char* { @@ -417,14 +418,16 @@ template <> struct formatter { if (it == end) return it; it = detail::parse_align(it, end, specs_); - if (it == end) return it; char c = *it; - if ((c >= '0' && c <= '9') || c == '{') + if (it != end && ((c >= '0' && c <= '9') || c == '{')) it = detail::parse_width(it, end, specs_, width_ref_, ctx); - if (it == end) return it; - if (*it == 's') { + if (it != end && *it == '?') { + debug_ = true; + ++it; + } + if (it != end && *it == 's') { specs_.set_type(presentation_type::string); ++it; } @@ -445,8 +448,13 @@ template <> struct formatter { buf.push_back(':'); detail::write(appender(buf), ec.value()); } - return detail::write(ctx.out(), string_view(buf.data(), buf.size()), - specs); + auto quoted = memory_buffer(); + auto str = string_view(buf.data(), buf.size()); + if (debug_) { + detail::write_escaped_string(std::back_inserter(quoted), str); + str = string_view(quoted.data(), quoted.size()); + } + return detail::write(ctx.out(), str, specs); } }; diff --git a/test/std-test.cc b/test/std-test.cc index a5c2c3c9..8e5fa06c 100644 --- a/test/std-test.cc +++ b/test/std-test.cc @@ -286,6 +286,8 @@ TEST(std_test, error_code) { "system:-42"); auto ec = std::make_error_code(std::errc::value_too_large); EXPECT_EQ(fmt::format("{:s}", ec), ec.message()); + EXPECT_EQ(fmt::format("{:?}", std::error_code(42, generic)), + "\"generic:42\""); } template void exception_test() {