From fb7a94c9594d0891d30594edaf9fdc04736aee50 Mon Sep 17 00:00:00 2001 From: asynts Date: Wed, 30 Sep 2020 14:38:47 +0200 Subject: [PATCH] AK: Add formatter for pointer types. --- AK/Format.cpp | 18 +++++++++++++++++- AK/Format.h | 9 +++++++++ AK/Tests/TestFormat.cpp | 15 +++++++++++++++ 3 files changed, 41 insertions(+), 1 deletion(-) diff --git a/AK/Format.cpp b/AK/Format.cpp index d31a3c7790..e9211cc570 100644 --- a/AK/Format.cpp +++ b/AK/Format.cpp @@ -367,6 +367,22 @@ void Formatter::value>::Type>::format(StringB if (m_precision != value_not_set) ASSERT_NOT_REACHED(); + if (m_mode == Mode::Pointer) { + if (m_sign != Sign::Default) + ASSERT_NOT_REACHED(); + if (m_align != Align::Default) + ASSERT_NOT_REACHED(); + if (m_alternative_form) + ASSERT_NOT_REACHED(); + if (m_width != value_not_set) + ASSERT_NOT_REACHED(); + + m_mode = Mode::Hexadecimal; + m_alternative_form = true; + m_width = 2 * sizeof(void*) + 2; + m_zero_pad = true; + } + u8 base = 0; bool upper_case = false; if (m_mode == Mode::Binary) { @@ -389,7 +405,7 @@ void Formatter::value>::Type>::format(StringB ASSERT_NOT_REACHED(); } - auto width = decode_value(m_width, context); + const auto width = decode_value(m_width, context); const auto put_padding = [&](size_t amount, char fill) { for (size_t i = 0; i < amount; ++i) diff --git a/AK/Format.h b/AK/Format.h index 5389565865..cf20ae942c 100644 --- a/AK/Format.h +++ b/AK/Format.h @@ -198,6 +198,15 @@ struct Formatter::value>::Type> : StandardFor void format(StringBuilder&, T value, FormatterContext&); }; +template +struct Formatter : StandardFormatter { + void format(StringBuilder& builder, T* value, FormatterContext& context) + { + Formatter formatter { *this }; + formatter.format(builder, reinterpret_cast(value), context); + } +}; + template<> struct Formatter : StandardFormatter { void format(StringBuilder&, bool value, FormatterContext&); diff --git a/AK/Tests/TestFormat.cpp b/AK/Tests/TestFormat.cpp index fe8c6032e0..2441303e6d 100644 --- a/AK/Tests/TestFormat.cpp +++ b/AK/Tests/TestFormat.cpp @@ -147,4 +147,19 @@ TEST_CASE(boolean_values) EXPECT_EQ(String::formatted("{:#08x}", true), "0x000001"); } +TEST_CASE(pointers) +{ + void* ptr = reinterpret_cast(0x4000); + + if (sizeof(void*) == 4) { + EXPECT_EQ(String::formatted("{:p}", 32), "0x00000020"); + EXPECT_EQ(String::formatted("{:p}", ptr), "0x00004000"); + } else if (sizeof(void*) == 8) { + EXPECT_EQ(String::formatted("{:p}", 32), "0x0000000000000020"); + EXPECT_EQ(String::formatted("{:p}", ptr), "0x0000000000004000"); + } else { + ASSERT_NOT_REACHED(); + } +} + TEST_MAIN(Format)