Fix SmallVector's insert to handle non-random-access iterators.
authorDan Gohman <gohman@apple.com>
Fri, 26 Mar 2010 18:53:37 +0000 (18:53 +0000)
committerDan Gohman <gohman@apple.com>
Fri, 26 Mar 2010 18:53:37 +0000 (18:53 +0000)
git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@99633 91177308-0d34-0410-b5e6-96231b3b80d8

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

index c2afb7e681d18895a2090e62fdfc45e1d2eca73b..2d79a029d0191e3a44ca391e41a0b30f33a8a2c4 100644 (file)
@@ -239,11 +239,20 @@ public:
   /// starting with "Dest", constructing elements into it as needed.
   template<typename It1, typename It2>
   static void uninitialized_copy(It1 I, It1 E, It2 Dest) {
-    // Use memcpy for PODs: std::uninitialized_copy optimizes to memmove, memcpy
-    // is better.
-    memcpy(&*Dest, &*I, (E-I)*sizeof(T));
+    // Arbitrary iterator types; just use the basic implementation.
+    std::uninitialized_copy(I, E, Dest);
   }
-  
+
+  /// uninitialized_copy - Copy the range [I, E) onto the uninitialized memory
+  /// starting with "Dest", constructing elements into it as needed.
+  template<typename T1, typename T2>
+  static void uninitialized_copy(T1 *I, T1 *E, T2 *Dest) {
+    // Use memcpy for PODs iterated by pointers (which includes SmallVector
+    // iterators): std::uninitialized_copy optimizes to memmove, but we can
+    // use memcpy here.
+    memcpy(Dest, I, (E-I)*sizeof(T));
+  }
+
   /// grow - double the size of the allocated memory, guaranteeing space for at
   /// least one more element or MinSize if specified.
   void grow(size_t MinSize = 0) {
@@ -501,10 +510,13 @@ public:
     this->uninitialized_copy(I, OldEnd, this->end()-NumOverwritten);
     
     // Replace the overwritten part.
-    std::copy(From, From+NumOverwritten, I);
+    for (; NumOverwritten > 0; --NumOverwritten) {
+      *I = *From;
+      ++I; ++From;
+    }
     
     // Insert the non-overwritten middle part.
-    this->uninitialized_copy(From+NumOverwritten, To, OldEnd);
+    this->uninitialized_copy(From, To, OldEnd);
     return I;
   }
   
index d7dc3af52febc22ccca0d5f41aacf01ca974ae97..991c7d6caac758e2095cc7d9ea2b724cd768a202 100644 (file)
@@ -14,6 +14,7 @@
 #include "gtest/gtest.h"
 #include "llvm/ADT/SmallVector.h"
 #include <stdarg.h>
+#include <list>
 
 using namespace llvm;
 
@@ -399,4 +400,9 @@ TEST_F(SmallVectorTest, DirectVectorTest) {
   EXPECT_EQ(4, theVector[3].getValue());
 }
 
+TEST_F(SmallVectorTest, IteratorTest) {
+  std::list<int> L;
+  theVector.insert(theVector.end(), L.begin(), L.end());
+}
+
 }