From 38b6eae61d15ec410d3a32f1422c1e88848e5e2b Mon Sep 17 00:00:00 2001 From: Markus Mittendrein Date: Sat, 8 Jan 2022 02:42:12 +0100 Subject: Add bool formatter --- include/cxxformat/formatters.hpp | 49 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) (limited to 'include') diff --git a/include/cxxformat/formatters.hpp b/include/cxxformat/formatters.hpp index 264cc52..03af08e 100644 --- a/include/cxxformat/formatters.hpp +++ b/include/cxxformat/formatters.hpp @@ -233,6 +233,55 @@ namespace format { } }; + template<> + struct formatter { + static constexpr format_specifier delegateSpec(format_specifier from) noexcept + { + from.conversion = 'u'; + return from; + } + + using delegated_formatter = formatter; + + static constexpr void format(const format_output auto& out, bool v, format_specifier spec, optional_int minWidth, optional_int precision) + { + if (spec.conversion == 'u') + { + return delegated_formatter::format(out, v ? 1 : 0, delegateSpec(spec), minWidth, precision); + } + else + { + const auto val = v ? std::string_view{"true"} : std::string_view{"false"}; + formatPadded(out, val, ' ', spec.flags.leftJustified, minWidth); + } + } + + static constexpr void conversionSupported(format_specifier spec) + { + const auto conv = spec.conversion; + simpleConversionSpecifierCheck("usv", conv, "bool"); + noAlternative(spec.flags.alternative, "bools"); + noSignFlags(spec.addSign, "bools"); + + if (conv == 'u') + { + delegated_formatter::conversionSupported(delegateSpec(spec)); + } + else + { + if (spec.precision) + { + throw std::invalid_argument{"Specifying a precision for bool is only supported with %u conversion"}; + } + if (spec.padding != ' ') + { + throw std::invalid_argument{"Zero padding (‘0’ flag) for bool is only supported for %u conversion"}; + } + } + } + }; + + // NOTE: Difference to printf: uses std::to_chars’ minimal width for exact representation when no precision is specified instead of default precision of 6 template struct formatter { -- cgit v1.2.3-54-g00ecf