diff options
| author | Markus Mittendrein <maxmitti@maxmitti.tk> | 2022-01-08 02:42:12 +0100 |
|---|---|---|
| committer | Markus Mittendrein <maxmitti@maxmitti.tk> | 2022-01-08 02:42:12 +0100 |
| commit | 38b6eae61d15ec410d3a32f1422c1e88848e5e2b (patch) | |
| tree | 7e2330eea7d94daaf952ff81514fdcc4348c1b81 /include | |
| parent | ab2c61054f09e0834cba6008263096f2afdfd4d0 (diff) | |
| download | cxxformat-38b6eae61d15ec410d3a32f1422c1e88848e5e2b.tar.gz cxxformat-38b6eae61d15ec410d3a32f1422c1e88848e5e2b.zip | |
Add bool formatter
Diffstat (limited to 'include')
| -rw-r--r-- | include/cxxformat/formatters.hpp | 49 |
1 files changed, 49 insertions, 0 deletions
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<bool> { + static constexpr format_specifier delegateSpec(format_specifier from) noexcept + { + from.conversion = 'u'; + return from; + } + + using delegated_formatter = formatter<std::uint8_t>; + + static constexpr void format(const format_output auto& out, bool v, format_specifier spec, optional_int<std::size_t> minWidth, optional_int<std::size_t> 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<std::floating_point T> struct formatter<T> { |
