From f75b1127b2f0ae22af04ae590ba22652f5092f5f Mon Sep 17 00:00:00 2001 From: Andreas Kling Date: Wed, 14 Aug 2019 11:02:49 +0200 Subject: [PATCH] OwnPtr: Add a way to turn an OwnPtr into a NonnullOwnPtr Okay, so, OwnPtr::release_nonnull() returns a NonnullOwnPtr. It assumes that the OwnPtr is non-null to begin with. Note that this removes the value from the OwnPtr, as there can only be a single owner. --- AK/OwnPtr.h | 6 ++++++ AK/Tests/TestVector.cpp | 17 +++++++++++++++++ 2 files changed, 23 insertions(+) diff --git a/AK/OwnPtr.h b/AK/OwnPtr.h index 9e40625a71..f52c17ecbd 100644 --- a/AK/OwnPtr.h +++ b/AK/OwnPtr.h @@ -120,6 +120,12 @@ public: return leaked_ptr; } + NonnullOwnPtr release_nonnull() + { + ASSERT(m_ptr); + return NonnullOwnPtr(NonnullOwnPtr::Adopt, *leak_ptr()); + } + T* ptr() { return m_ptr; } const T* ptr() const { return m_ptr; } diff --git a/AK/Tests/TestVector.cpp b/AK/Tests/TestVector.cpp index 351a7aeedd..1ad7aa7c26 100644 --- a/AK/Tests/TestVector.cpp +++ b/AK/Tests/TestVector.cpp @@ -1,6 +1,7 @@ #include #include +#include #include #include @@ -252,4 +253,20 @@ TEST_CASE(vector_remove) EXPECT_EQ(ints[0], 4); } +TEST_CASE(nonnullownptrvector) +{ + struct Object { + String string; + }; + NonnullOwnPtrVector objects; + + objects.append(make()); + EXPECT_EQ(objects.size(), 1); + + OwnPtr o = make(); + objects.append(o.release_nonnull()); + EXPECT(o == nullptr); + EXPECT_EQ(objects.size(), 2); +} + TEST_MAIN(Vector)