From 1686c4906b765810fcc44e36d3b4121b86708e28 Mon Sep 17 00:00:00 2001 From: Andreas Kling Date: Wed, 24 Jul 2019 09:33:26 +0200 Subject: [PATCH] AK: Delete Vector::resize() from Nonnull{Own,Ref}PtrVector. It's not possible to grow one of these vectors beyond what's already in them since it's not possible to default-construct Nonnull{Own,Ref}Ptr. Add Vector::shrink() which can be used when you want to shrink the Vector and delete resize() from the specialized Vectors. --- AK/NonnullOwnPtrVector.h | 6 ++++++ AK/NonnullRefPtrVector.h | 6 ++++++ AK/Vector.h | 24 +++++++++++++++--------- 3 files changed, 27 insertions(+), 9 deletions(-) diff --git a/AK/NonnullOwnPtrVector.h b/AK/NonnullOwnPtrVector.h index 358f80679f5..0616658ced7 100644 --- a/AK/NonnullOwnPtrVector.h +++ b/AK/NonnullOwnPtrVector.h @@ -41,6 +41,12 @@ public: const T& first() const { return at(0); } T& last() { return at(size() - 1); } const T& last() const { return at(size() - 1); } + +private: + // NOTE: You can't use resize() on a NonnullOwnPtrVector since making the vector + // bigger would require being able to default-construct NonnullOwnPtrs. + // Instead, use shrink(new_size). + void resize(int) = delete; }; } diff --git a/AK/NonnullRefPtrVector.h b/AK/NonnullRefPtrVector.h index f5e438f3de9..296b92402e5 100644 --- a/AK/NonnullRefPtrVector.h +++ b/AK/NonnullRefPtrVector.h @@ -41,6 +41,12 @@ public: const T& first() const { return at(0); } T& last() { return at(size() - 1); } const T& last() const { return at(size() - 1); } + +private: + // NOTE: You can't use resize() on a NonnullRefPtrVector since making the vector + // bigger would require being able to default-construct NonnullRefPtrs. + // Instead, use shrink(new_size). + void resize(int) = delete; }; } diff --git a/AK/Vector.h b/AK/Vector.h index 646a767bd16..c5c857aa63e 100644 --- a/AK/Vector.h +++ b/AK/Vector.h @@ -407,8 +407,9 @@ public: m_capacity = new_capacity; } - void resize(int new_size) + void shrink(int new_size) { + ASSERT(new_size <= size()); if (new_size == size()) return; @@ -417,14 +418,19 @@ public: return; } - if (new_size > size()) { - ensure_capacity(new_size); - for (int i = size(); i < new_size; ++i) - new (slot(i)) T; - } else { - for (int i = new_size; i < size(); ++i) - at(i).~T(); - } + for (int i = new_size; i < size(); ++i) + at(i).~T(); + m_size = new_size; + } + + void resize(int new_size) + { + if (new_size <= size()) + return shrink(new_size); + + ensure_capacity(new_size); + for (int i = size(); i < new_size; ++i) + new (slot(i)) T; m_size = new_size; }