AK: Add formatter for pointer types.

This commit is contained in:
asynts 2020-09-30 14:38:47 +02:00 committed by Andreas Kling
parent ebafc5b4d2
commit fb7a94c959
Notes: sideshowbarker 2024-07-19 02:06:21 +09:00
3 changed files with 41 additions and 1 deletions

View file

@ -367,6 +367,22 @@ void Formatter<T, typename EnableIf<IsIntegral<T>::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<T, typename EnableIf<IsIntegral<T>::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)

View file

@ -198,6 +198,15 @@ struct Formatter<T, typename EnableIf<IsIntegral<T>::value>::Type> : StandardFor
void format(StringBuilder&, T value, FormatterContext&);
};
template<typename T>
struct Formatter<T*> : StandardFormatter {
void format(StringBuilder& builder, T* value, FormatterContext& context)
{
Formatter<FlatPtr> formatter { *this };
formatter.format(builder, reinterpret_cast<FlatPtr>(value), context);
}
};
template<>
struct Formatter<bool> : StandardFormatter {
void format(StringBuilder&, bool value, FormatterContext&);

View file

@ -147,4 +147,19 @@ TEST_CASE(boolean_values)
EXPECT_EQ(String::formatted("{:#08x}", true), "0x000001");
}
TEST_CASE(pointers)
{
void* ptr = reinterpret_cast<void*>(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)