From d2ca7ca017a1d5e3b524ceccf9dbbf4e826fbef5 Mon Sep 17 00:00:00 2001 From: asynts Date: Tue, 6 Oct 2020 13:57:20 +0200 Subject: [PATCH] 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.) --- AK/Format.h | 35 ++++++++++++++++++++++------------- AK/Tests/TestFormat.cpp | 6 ++++++ 2 files changed, 28 insertions(+), 13 deletions(-) diff --git a/AK/Format.h b/AK/Format.h index ff74e19799..9d7ab3bc42 100644 --- a/AK/Format.h +++ b/AK/Format.h @@ -238,6 +238,17 @@ struct StandardFormatter { void parse(TypeErasedFormatParams&, FormatParser&); }; +template +struct Formatter::value>::Type> : StandardFormatter { + Formatter() { } + explicit Formatter(StandardFormatter formatter) + : StandardFormatter(formatter) + { + } + + void format(TypeErasedFormatParams&, FormatBuilder&, T value); +}; + template<> struct Formatter : StandardFormatter { Formatter() { } @@ -250,12 +261,21 @@ struct Formatter : StandardFormatter { }; template<> struct Formatter : Formatter { + void format(TypeErasedFormatParams& params, FormatBuilder& builder, const char* value) + { + if (m_mode == Mode::Pointer) { + Formatter formatter { *this }; + formatter.format(params, builder, reinterpret_cast(value)); + } else { + Formatter::format(params, builder, value); + } + } }; template<> -struct Formatter : Formatter { +struct Formatter : Formatter { }; template -struct Formatter : Formatter { +struct Formatter : Formatter { }; template<> struct Formatter : Formatter { @@ -264,17 +284,6 @@ template<> struct Formatter : Formatter { }; -template -struct Formatter::value>::Type> : StandardFormatter { - Formatter() { } - explicit Formatter(StandardFormatter formatter) - : StandardFormatter(formatter) - { - } - - void format(TypeErasedFormatParams&, FormatBuilder&, T value); -}; - template struct Formatter : StandardFormatter { void format(TypeErasedFormatParams& params, FormatBuilder& builder, T* value) diff --git a/AK/Tests/TestFormat.cpp b/AK/Tests/TestFormat.cpp index ea7fb5db19..7df8430b5e 100644 --- a/AK/Tests/TestFormat.cpp +++ b/AK/Tests/TestFormat.cpp @@ -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(literal))); +} + TEST_MAIN(Format)