[llvm] [ADT] Add std::string_view conversion to SmallString (PR #83397)

Aiden Grossman via llvm-commits llvm-commits at lists.llvm.org
Thu Feb 29 12:23:08 PST 2024


https://github.com/boomanaiden154 updated https://github.com/llvm/llvm-project/pull/83397

>From 229834ecd3b888a1fffcf684c1007383f582d1af Mon Sep 17 00:00:00 2001
From: Aiden Grossman <agrossman154 at yahoo.com>
Date: Thu, 29 Feb 2024 01:50:20 -0800
Subject: [PATCH 1/2] [ADT] Add std::string_view conversion to SmallString

This patch adds a std::string_view conversion to SmallString which we've
recently found a use for downstream in a project that is using c++
standard library IO.
---
 llvm/include/llvm/ADT/SmallString.h    | 5 +++++
 llvm/unittests/ADT/SmallStringTest.cpp | 6 ++++++
 2 files changed, 11 insertions(+)

diff --git a/llvm/include/llvm/ADT/SmallString.h b/llvm/include/llvm/ADT/SmallString.h
index a5b9eec50c8257..df03398c804a77 100644
--- a/llvm/include/llvm/ADT/SmallString.h
+++ b/llvm/include/llvm/ADT/SmallString.h
@@ -265,6 +265,11 @@ class SmallString : public SmallVector<char, InternalLen> {
   /// Implicit conversion to StringRef.
   operator StringRef() const { return str(); }
 
+  /// Implicit conversion to std::string_view
+  operator std::string_view() const {
+    return std::string_view(this->data(), this->size());
+  }
+
   explicit operator std::string() const {
     return std::string(this->data(), this->size());
   }
diff --git a/llvm/unittests/ADT/SmallStringTest.cpp b/llvm/unittests/ADT/SmallStringTest.cpp
index 2f4df8afeafa59..d68d73157988ab 100644
--- a/llvm/unittests/ADT/SmallStringTest.cpp
+++ b/llvm/unittests/ADT/SmallStringTest.cpp
@@ -244,4 +244,10 @@ TEST_F(SmallStringTest, GTestPrinter) {
   EXPECT_EQ(R"("foo")", ::testing::PrintToString(ErasedSmallString));
 }
 
+TEST_F(SmallStringTest, StringView) {
+  theString = "hello from std::string_view";
+  EXPECT_EQ("hello from std::string_view",
+            static_cast<std::string_view>(theString));
+}
+
 } // namespace

>From 7fec826a5f44b432f8c3cd2d7b32660ce914e6d8 Mon Sep 17 00:00:00 2001
From: Aiden Grossman <agrossman154 at yahoo.com>
Date: Thu, 29 Feb 2024 12:22:56 -0800
Subject: [PATCH 2/2] Add missing period.

---
 llvm/include/llvm/ADT/SmallString.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/llvm/include/llvm/ADT/SmallString.h b/llvm/include/llvm/ADT/SmallString.h
index df03398c804a77..ab5d483558cac8 100644
--- a/llvm/include/llvm/ADT/SmallString.h
+++ b/llvm/include/llvm/ADT/SmallString.h
@@ -265,7 +265,7 @@ class SmallString : public SmallVector<char, InternalLen> {
   /// Implicit conversion to StringRef.
   operator StringRef() const { return str(); }
 
-  /// Implicit conversion to std::string_view
+  /// Implicit conversion to std::string_view.
   operator std::string_view() const {
     return std::string_view(this->data(), this->size());
   }



More information about the llvm-commits mailing list