AK+Format: Make it possible to format string literals as pointers.

String literals are just pointers to a constant character. It should be
possible to format them as such. (The default is to print them as
strings still.)
This commit is contained in:
asynts 2020-10-06 13:57:20 +02:00 committed by Andreas Kling
parent 7c2cd81edb
commit d2ca7ca017
2 changed files with 28 additions and 13 deletions

View file

@ -238,6 +238,17 @@ struct StandardFormatter {
void parse(TypeErasedFormatParams&, FormatParser&);
};
template<typename T>
struct Formatter<T, typename EnableIf<IsIntegral<T>::value>::Type> : StandardFormatter {
Formatter() { }
explicit Formatter(StandardFormatter formatter)
: StandardFormatter(formatter)
{
}
void format(TypeErasedFormatParams&, FormatBuilder&, T value);
};
template<>
struct Formatter<StringView> : StandardFormatter {
Formatter() { }
@ -250,12 +261,21 @@ struct Formatter<StringView> : StandardFormatter {
};
template<>
struct Formatter<const char*> : Formatter<StringView> {
void format(TypeErasedFormatParams& params, FormatBuilder& builder, const char* value)
{
if (m_mode == Mode::Pointer) {
Formatter<FlatPtr> formatter { *this };
formatter.format(params, builder, reinterpret_cast<FlatPtr>(value));
} else {
Formatter<StringView>::format(params, builder, value);
}
}
};
template<>
struct Formatter<char*> : Formatter<StringView> {
struct Formatter<char*> : Formatter<const char*> {
};
template<size_t Size>
struct Formatter<char[Size]> : Formatter<StringView> {
struct Formatter<char[Size]> : Formatter<const char*> {
};
template<>
struct Formatter<String> : Formatter<StringView> {
@ -264,17 +284,6 @@ template<>
struct Formatter<FlyString> : Formatter<StringView> {
};
template<typename T>
struct Formatter<T, typename EnableIf<IsIntegral<T>::value>::Type> : StandardFormatter {
Formatter() { }
explicit Formatter(StandardFormatter formatter)
: StandardFormatter(formatter)
{
}
void format(TypeErasedFormatParams&, FormatBuilder&, T value);
};
template<typename T>
struct Formatter<T*> : StandardFormatter {
void format(TypeErasedFormatParams& params, FormatBuilder& builder, T* value)

View file

@ -182,4 +182,10 @@ TEST_CASE(ensure_that_format_works)
}
}
TEST_CASE(format_string_literal_as_pointer)
{
const char* literal = "abc";
EXPECT_EQ(String::formatted("{:p}", literal), String::formatted("{:p}", reinterpret_cast<FlatPtr>(literal)));
}
TEST_MAIN(Format)