From 297be76c0c97bbf23e864370f44549577b9d4cd8 Mon Sep 17 00:00:00 2001 From: Ivan Poliakov Date: Thu, 21 Jan 2021 16:42:04 +0300 Subject: [PATCH] add bool type handler for compile time check --- include/fmt/format.h | 28 +++++++++++++++++++++++++++- test/format-test.cc | 1 - 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/include/fmt/format.h b/include/fmt/format.h index 86352325dcb2f..822a03eb7cef2 100644 --- a/include/fmt/format.h +++ b/include/fmt/format.h @@ -1423,6 +1423,14 @@ FMT_CONSTEXPR void handle_int_type_spec(char spec, Handler&& handler) { } } +template +FMT_CONSTEXPR void handle_bool_type_spec(const basic_format_specs* specs, + Handler&& handler) { + if (!specs) return handler.on_str(); + if (specs->type && specs->type != 's') return handler.on_int(); + handler.on_str(); +} + template FMT_CONSTEXPR float_specs parse_float_type_spec( const basic_format_specs& specs, ErrorHandler&& eh = {}) { @@ -1542,6 +1550,21 @@ class cstring_type_checker : public ErrorHandler { FMT_CONSTEXPR void on_pointer() {} }; +template +class bool_type_checker : private ErrorHandler { + private: + char type_; + + public: + FMT_CONSTEXPR explicit bool_type_checker(char type, ErrorHandler eh) + : ErrorHandler(eh), type_(type) {} + + FMT_CONSTEXPR void on_int() { + handle_int_type_spec(type_, int_type_checker(*this)); + } + FMT_CONSTEXPR void on_str() {} +}; + template FMT_NOINLINE FMT_CONSTEXPR OutputIt fill(OutputIt it, size_t n, const fill_t& fill) { @@ -3516,10 +3539,13 @@ struct formatter(eh)); break; + case detail::type::bool_type: + handle_bool_type_spec( + &specs_, detail::bool_type_checker(specs_.type, eh)); + break; case detail::type::char_type: handle_char_specs( &specs_, detail::char_specs_checker(specs_.type, eh)); diff --git a/test/format-test.cc b/test/format-test.cc index 9a1470384f938..899a8b4b171ab 100644 --- a/test/format-test.cc +++ b/test/format-test.cc @@ -2438,7 +2438,6 @@ TEST(FormatTest, FormatStringErrors) { EXPECT_ERROR("{:.{}}", "argument not found", double); EXPECT_ERROR("{:.2}", "precision not allowed for this argument type", int); EXPECT_ERROR("{:s}", "invalid type specifier", int); - EXPECT_ERROR("{:s}", "invalid type specifier", bool); EXPECT_ERROR("{:s}", "invalid type specifier", char); EXPECT_ERROR("{:+}", "invalid format specifier for char", char); EXPECT_ERROR("{:s}", "invalid type specifier", double);