Skip to content

Commit 6c14611

Browse files
JDevlieghereadrian-prantl
authored andcommitted
[lldb] Streamline ConstString -> std::string conversion (NFC) (llvm#79649)
Make it easier to go from a ConstString to a std::string without having to go through a C-String or a llvm::StringRef. I made the conversion operator explicit as this is a relatively expensive operations (compared to a StringRef or string_view). (cherry picked from commit 33860b2)
1 parent 32d7841 commit 6c14611

File tree

2 files changed

+25
-2
lines changed

2 files changed

+25
-2
lines changed

lldb/include/lldb/Utility/ConstString.h

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -183,8 +183,14 @@ class ConstString {
183183

184184
// Implicitly convert \class ConstString instances to \class StringRef.
185185
operator llvm::StringRef() const { return GetStringRef(); }
186-
// Implicitly convert \class ConstString instances to \calss std::string_view.
187-
operator std::string_view() const { return std::string_view(m_string, GetLength()); }
186+
187+
// Implicitly convert \class ConstString instances to \class std::string_view.
188+
operator std::string_view() const {
189+
return std::string_view(m_string, GetLength());
190+
}
191+
192+
// Explicitly convert \class ConstString instances to \class std::string.
193+
explicit operator std::string() const { return GetString(); }
188194

189195
/// Get the string value as a C string.
190196
///
@@ -208,6 +214,9 @@ class ConstString {
208214
return llvm::StringRef(m_string, GetLength());
209215
}
210216

217+
/// Get the string value as a std::string
218+
std::string GetString() const { return std::string(m_string, GetLength()); }
219+
211220
/// Get the string value as a C string.
212221
///
213222
/// Get the value of the contained string as a NULL terminated C string

lldb/unittests/Utility/ConstStringTest.cpp

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -137,3 +137,17 @@ TEST(ConstStringTest, CompareStringRef) {
137137
EXPECT_TRUE(null == static_cast<const char *>(nullptr));
138138
EXPECT_TRUE(null != "bar");
139139
}
140+
141+
TEST(ConstStringTest, StringConversions) {
142+
ConstString foo("foo");
143+
144+
// Member functions.
145+
EXPECT_EQ(llvm::StringRef("foo"), foo.GetStringRef());
146+
EXPECT_EQ(std::string("foo"), foo.GetString());
147+
EXPECT_STREQ("foo", foo.AsCString());
148+
149+
// Conversion operators.
150+
EXPECT_EQ(llvm::StringRef("foo"), llvm::StringRef(foo));
151+
EXPECT_EQ(std::string("foo"), std::string_view(foo));
152+
EXPECT_EQ(std::string("foo"), std::string(foo));
153+
}

0 commit comments

Comments
 (0)