From ebafc5b4d230d1b5ab8546b194af64bc615c0b48 Mon Sep 17 00:00:00 2001 From: asynts Date: Wed, 30 Sep 2020 13:26:24 +0200 Subject: [PATCH] AK: Add formatter for boolean values. --- AK/Format.cpp | 11 +++++++++++ AK/Format.h | 17 +++++++++++++++++ AK/Tests/TestFormat.cpp | 11 +++++++++++ 3 files changed, 39 insertions(+) diff --git a/AK/Format.cpp b/AK/Format.cpp index e09a160d100..d31a3c77908 100644 --- a/AK/Format.cpp +++ b/AK/Format.cpp @@ -460,6 +460,17 @@ void Formatter::value>::Type>::format(StringB PrintfImplementation::convert_signed_to_string(value, builder, base, m_alternative_form, upper_case, m_zero_pad, align, width, m_fill, sign_mode); } +void Formatter::format(StringBuilder& builder, bool value, FormatterContext& context) +{ + if (m_mode == Mode::Binary || m_mode == Mode::BinaryUppercase || m_mode == Mode::Decimal || m_mode == Mode::Octal || m_mode == Mode::Hexadecimal || m_mode == Mode::HexadecimalUppercase) { + Formatter formatter { *this }; + return formatter.format(builder, static_cast(value), context); + } else { + Formatter formatter { *this }; + formatter.format(builder, value ? "true" : "false", context); + } +} + template struct Formatter; template struct Formatter; template struct Formatter; diff --git a/AK/Format.h b/AK/Format.h index 78f2d4f10c8..53895658659 100644 --- a/AK/Format.h +++ b/AK/Format.h @@ -166,6 +166,12 @@ struct StandardFormatter { template<> struct Formatter : StandardFormatter { + Formatter() { } + explicit Formatter(StandardFormatter formatter) + : StandardFormatter(formatter) + { + } + void format(StringBuilder& builder, StringView value, FormatterContext&); }; template<> @@ -183,9 +189,20 @@ struct Formatter : Formatter { template struct Formatter::value>::Type> : StandardFormatter { + Formatter() { } + explicit Formatter(StandardFormatter formatter) + : StandardFormatter(formatter) + { + } + void format(StringBuilder&, T value, FormatterContext&); }; +template<> +struct Formatter : StandardFormatter { + void format(StringBuilder&, bool value, FormatterContext&); +}; + template Array make_type_erased_parameters(const Parameters&... parameters) { diff --git a/AK/Tests/TestFormat.cpp b/AK/Tests/TestFormat.cpp index fa26f0caf21..fe8c6032e03 100644 --- a/AK/Tests/TestFormat.cpp +++ b/AK/Tests/TestFormat.cpp @@ -136,4 +136,15 @@ TEST_CASE(cast_integer_to_character) EXPECT_EQ(String::formatted("{:c}", static_cast('f')), "f"); } +TEST_CASE(boolean_values) +{ + EXPECT_EQ(String::formatted("{}", true), "true"); + EXPECT_EQ(String::formatted("{}", false), "false"); + EXPECT_EQ(String::formatted("{:6}", true), "true "); + EXPECT_EQ(String::formatted("{:>4}", false), "false"); + EXPECT_EQ(String::formatted("{:d}", false), "0"); + EXPECT_EQ(String::formatted("{:d}", true), "1"); + EXPECT_EQ(String::formatted("{:#08x}", true), "0x000001"); +} + TEST_MAIN(Format)