[STLExtras] Allow for non-member `begin`/`end` in `append_range`
authorJakub Kuderski <kubak@google.com>
Tue, 21 Feb 2023 18:23:17 +0000 (13:23 -0500)
committerJakub Kuderski <kubak@google.com>
Tue, 21 Feb 2023 18:35:19 +0000 (13:35 -0500)
This makes `append_range` useable with, C arrays and types with custom
`begin`/`end` functions.

Reviewed By: kazu

Differential Revision: https://reviews.llvm.org/D144420

llvm/include/llvm/ADT/STLExtras.h
llvm/unittests/ADT/STLExtrasTest.cpp

index a5cb73d..8702024 100644 (file)
@@ -2014,7 +2014,7 @@ void erase_value(Container &C, ValueType V) {
 /// C.insert(C.end(), R.begin(), R.end());
 template <typename Container, typename Range>
 inline void append_range(Container &C, Range &&R) {
-  C.insert(C.end(), R.begin(), R.end());
+  C.insert(C.end(), adl_begin(R), adl_end(R));
 }
 
 /// Given a sequence container Cont, replace the range [ContIt, ContEnd) with
index 4c31b4f..5082087 100644 (file)
@@ -7,6 +7,8 @@
 //===----------------------------------------------------------------------===//
 
 #include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/Sequence.h"
+#include "llvm/ADT/StringRef.h"
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
 
@@ -353,12 +355,23 @@ TEST(STLExtrasTest, EraseIf) {
 }
 
 TEST(STLExtrasTest, AppendRange) {
-  auto AppendVals = {3};
   std::vector<int> V = {1, 2};
-  append_range(V, AppendVals);
-  EXPECT_EQ(1, V[0]);
-  EXPECT_EQ(2, V[1]);
-  EXPECT_EQ(3, V[2]);
+  auto AppendVals1 = {3};
+  append_range(V, AppendVals1);
+  EXPECT_THAT(V, ElementsAre(1, 2, 3));
+
+  int AppendVals2[] = {4, 5};
+  append_range(V, AppendVals2);
+  EXPECT_THAT(V, ElementsAre(1, 2, 3, 4, 5));
+
+  append_range(V, llvm::seq(6, 8));
+  EXPECT_THAT(V, ElementsAre(1, 2, 3, 4, 5, 6, 7));
+
+  std::string Str;
+  append_range(Str, "abc");
+  EXPECT_THAT(Str, ElementsAre('a', 'b', 'c', '\0'));
+  append_range(Str, "def");
+  EXPECT_THAT(Str, ElementsAre('a', 'b', 'c', '\0', 'd', 'e', 'f', '\0'));
 }
 
 namespace some_namespace {