Skip to content

Commit

Permalink
chore: merge pull request #30 from threeal/error-format-with-fmtlib
Browse files Browse the repository at this point in the history
Error: Add Support for Formatting `Error` Using {fmt}
  • Loading branch information
threeal authored Jul 3, 2023
2 parents ce1d453 + 860d488 commit 42f0377
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 2 deletions.
7 changes: 7 additions & 0 deletions error/include/error/error.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -77,3 +77,10 @@ bool operator==(const Error& lhs, const Error& rhs);
bool operator!=(const Error& lhs, const Error& rhs);

} // namespace error

template <>
struct fmt::formatter<error::Error> {
format_parse_context::iterator parse(format_parse_context& ctx) const;
format_context::iterator format(const error::Error& err,
format_context& ctx) const;
};
14 changes: 14 additions & 0 deletions error/src/error.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,17 @@ bool operator!=(const Error& lhs, const Error& rhs) {
}

} // namespace error

namespace fmt {

format_parse_context::iterator formatter<error::Error>::parse(
format_parse_context& ctx) const {
return ctx.begin();
}

format_context::iterator formatter<error::Error>::format(
const error::Error& err, format_context& ctx) const {
return format_to(ctx.out(), "error: {}", err.what());
}

} // namespace fmt
13 changes: 11 additions & 2 deletions error/test/error_test.cpp
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
#include <fmt/core.h>

#include <catch2/catch_test_macros.hpp>
#include <error/error.hpp>
#include <sstream>
Expand Down Expand Up @@ -47,6 +49,13 @@ TEST_CASE("Error Comparison") {

TEST_CASE("Error Printing") {
const error::Error err("unknown error");
const auto ss = std::stringstream() << err;
REQUIRE(ss.str() == "error: unknown error");

SECTION("Using ostream") {
const auto ss = std::stringstream() << err;
REQUIRE(ss.str() == "error: unknown error");
}

SECTION("Using fmtlib") {
REQUIRE(fmt::format("{}", err) == "error: unknown error");
}
}

0 comments on commit 42f0377

Please sign in to comment.