[PATCH] D93532: [ADT] Add resize_for_overwrite method to SmallVector.

Nathan James via Phabricator via llvm-commits llvm-commits at lists.llvm.org
Tue Dec 22 09:19:20 PST 2020


This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG5d10b8ad595d: [ADT] Add resize_for_overwrite method to SmallVector. (authored by njames93).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D93532/new/

https://reviews.llvm.org/D93532

Files:
  llvm/include/llvm/ADT/SmallVector.h
  llvm/unittests/ADT/SmallVectorTest.cpp


Index: llvm/unittests/ADT/SmallVectorTest.cpp
===================================================================
--- llvm/unittests/ADT/SmallVectorTest.cpp
+++ llvm/unittests/ADT/SmallVectorTest.cpp
@@ -341,6 +341,31 @@
   this->assertValuesInOrder(this->theVector, 3u, 77, 77, 77);
 }
 
+TEST(SmallVectorTest, ResizeForOverwrite) {
+  {
+    // Heap allocated storage.
+    SmallVector<unsigned, 0> V;
+    V.push_back(5);
+    V.pop_back();
+    V.resize_for_overwrite(V.size() + 1);
+    EXPECT_EQ(5, V.back());
+    V.pop_back();
+    V.resize(V.size() + 1);
+    EXPECT_EQ(0, V.back());
+  }
+  {
+    // Inline storage.
+    SmallVector<unsigned, 2> V;
+    V.push_back(5);
+    V.pop_back();
+    V.resize_for_overwrite(V.size() + 1);
+    EXPECT_EQ(5, V.back());
+    V.pop_back();
+    V.resize(V.size() + 1);
+    EXPECT_EQ(0, V.back());
+  }
+}
+
 // Overflow past fixed size.
 TYPED_TEST(SmallVectorTest, OverflowTest) {
   SCOPED_TRACE("OverflowTest");
Index: llvm/include/llvm/ADT/SmallVector.h
===================================================================
--- llvm/include/llvm/ADT/SmallVector.h
+++ llvm/include/llvm/ADT/SmallVector.h
@@ -460,7 +460,8 @@
     this->Size = 0;
   }
 
-  void resize(size_type N) {
+private:
+  template <bool ForOverwrite> void resizeImpl(size_type N) {
     if (N < this->size()) {
       this->destroy_range(this->begin()+N, this->end());
       this->set_size(N);
@@ -468,11 +469,20 @@
       if (this->capacity() < N)
         this->grow(N);
       for (auto I = this->end(), E = this->begin() + N; I != E; ++I)
-        new (&*I) T();
+        if (ForOverwrite)
+          new (&*I) T;
+        else
+          new (&*I) T();
       this->set_size(N);
     }
   }
 
+public:
+  void resize(size_type N) { resizeImpl<false>(N); }
+
+  /// Like resize, but \ref T is POD, the new values won't be initialized.
+  void resize_for_overwrite(size_type N) { resizeImpl<true>(N); }
+
   void resize(size_type N, const T &NV) {
     if (N == this->size())
       return;


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D93532.313369.patch
Type: text/x-patch
Size: 2022 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/llvm-commits/attachments/20201222/2f2cf42d/attachment.bin>


More information about the llvm-commits mailing list