summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--include/cxxformat/formatters.hpp49
-rw-r--r--main.cpp1
2 files changed, 50 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> {
diff --git a/main.cpp b/main.cpp
index a86e1e8..bb041f6 100644
--- a/main.cpp
+++ b/main.cpp
@@ -33,6 +33,7 @@ int main(int argc, char* argv[])
format_to("Hallo %%du %1$s %s%c %s %u = %4$#x = %4$#X = %4$#o %f!\n", std::cout, "Knirp", 's', argv[0], 42u, 1.337);
assert(format("Hallo %%du %1$s %s%c %s %u = %4$#x = %4$#X = %4$#o %f!\n", "Knirp", 's', argv[0], 42u, 1.337) == "Hallo %%du %1$s %s%c %s %u = %4$#x = %4$#X = %4$#o %f!\n"_format("Knirp", 's', argv[0], 42u, 1.337));
+ "-%5s-%5s-%u-%u-\n"_format_to(stdout, true, false, true, false);
"-%20g-\n"_format_to(stdout, 0x1.8p0);
"-%20.0a-\n"_format_to(stdout, 0.0);
"-%#+20.0a-\n"_format_to(stdout, 1.0);