From b256e525867235d7fd3ebdd3231873bbf0d08d90 Mon Sep 17 00:00:00 2001 From: Andreas Kling Date: Fri, 25 Aug 2023 17:39:54 +0200 Subject: [PATCH] AK: Make Formatter for NonnullOwnPtr format the T This mirrors the behavior of NonnullRefPtr. If you want to format the pointer address, call .ptr() on it. --- AK/NonnullOwnPtr.h | 9 +++++++++ Tests/AK/TestNonnullOwnPtr.cpp | 17 +++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/AK/NonnullOwnPtr.h b/AK/NonnullOwnPtr.h index 8dd798c22d..843faa4f20 100644 --- a/AK/NonnullOwnPtr.h +++ b/AK/NonnullOwnPtr.h @@ -196,7 +196,16 @@ inline void swap(NonnullOwnPtr& a, NonnullOwnPtr& b) a.swap(b); } +template +struct Formatter> : Formatter { + ErrorOr format(FormatBuilder& builder, NonnullOwnPtr const& value) + { + return Formatter::format(builder, *value); + } +}; + template +requires(!HasFormatter) struct Formatter> : Formatter { ErrorOr format(FormatBuilder& builder, NonnullOwnPtr const& value) { diff --git a/Tests/AK/TestNonnullOwnPtr.cpp b/Tests/AK/TestNonnullOwnPtr.cpp index e67c4dde20..233c65fa6e 100644 --- a/Tests/AK/TestNonnullOwnPtr.cpp +++ b/Tests/AK/TestNonnullOwnPtr.cpp @@ -9,6 +9,7 @@ #include #include #include +#include TEST_CASE(destroy_self_owning_object) { @@ -32,3 +33,19 @@ TEST_CASE(destroy_self_owning_object) object_ptr->inner = make(object.release_nonnull()); object_ptr->inner = nullptr; } + +struct Foo { }; + +template<> +struct AK::Formatter : Formatter { + ErrorOr format(FormatBuilder& builder, Foo const&) + { + return Formatter::format(builder, ":^)"sv); + } +}; + +TEST_CASE(formatter) +{ + auto foo = make(); + EXPECT_EQ(MUST(String::formatted("{}", foo)), ":^)"sv); +}