[llvm] [ADT] Fix llvm::join on containers of char*s (PR #67113)

via llvm-commits llvm-commits at lists.llvm.org
Fri Sep 22 03:36:09 PDT 2023


llvmbot wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-llvm-adt

<details>
<summary>Changes</summary>

Currently it tries to call S.size() when preallocating the target string,
which doesn't compile.
vector<const char*> is used a bunch in e.g. clang driver.


---
Full diff: https://github.com/llvm/llvm-project/pull/67113.diff


2 Files Affected:

- (modified) llvm/include/llvm/ADT/StringExtras.h (+8-2) 
- (modified) llvm/unittests/ADT/StringExtrasTest.cpp (+15-2) 


``````````diff
diff --git a/llvm/include/llvm/ADT/StringExtras.h b/llvm/include/llvm/ADT/StringExtras.h
index 30397b23ab03b37..b2c400f512695e8 100644
--- a/llvm/include/llvm/ADT/StringExtras.h
+++ b/llvm/include/llvm/ADT/StringExtras.h
@@ -26,6 +26,7 @@
 #include <cstring>
 #include <iterator>
 #include <string>
+#include <type_traits>
 #include <utility>
 
 namespace llvm {
@@ -417,8 +418,13 @@ inline std::string join_impl(IteratorT Begin, IteratorT End,
     return S;
 
   size_t Len = (std::distance(Begin, End) - 1) * Separator.size();
-  for (IteratorT I = Begin; I != End; ++I)
-    Len += (*I).size();
+  for (IteratorT I = Begin; I != End; ++I) {
+    if constexpr (std::is_same_v<std::remove_reference_t<decltype(*I)>,
+                                 const char *>)
+      Len += strlen(*I);
+    else
+      Len += (*I).size();
+  }
   S.reserve(Len);
   size_t PrevCapacity = S.capacity();
   (void)PrevCapacity;
diff --git a/llvm/unittests/ADT/StringExtrasTest.cpp b/llvm/unittests/ADT/StringExtrasTest.cpp
index 971560b8eb8c4ee..0fead285e3d9d8a 100644
--- a/llvm/unittests/ADT/StringExtrasTest.cpp
+++ b/llvm/unittests/ADT/StringExtrasTest.cpp
@@ -59,8 +59,8 @@ TEST(StringExtrasTest, isUpper) {
   EXPECT_FALSE(isUpper('\?'));
 }
 
-TEST(StringExtrasTest, Join) {
-  std::vector<std::string> Items;
+template <class ContainerT> void testJoin() {
+  ContainerT Items;
   EXPECT_EQ("", join(Items.begin(), Items.end(), " <sep> "));
 
   Items = {"foo"};
@@ -74,6 +74,19 @@ TEST(StringExtrasTest, Join) {
             join(Items.begin(), Items.end(), " <sep> "));
 }
 
+TEST(StringExtrasTest, Join) {
+  {
+    SCOPED_TRACE("std::vector<std::string>");
+    testJoin<std::vector<std::string>>();
+  }
+  {
+    SCOPED_TRACE("std::vector<const char*>");
+    testJoin<std::vector<const char *>>();
+  }
+}
+
+TEST(StringExtrasTest, JoinCStrings) { std::vector<const char *> Items; }
+
 TEST(StringExtrasTest, JoinItems) {
   const char *Foo = "foo";
   std::string Bar = "bar";

``````````

</details>


https://github.com/llvm/llvm-project/pull/67113


More information about the llvm-commits mailing list