Skip to content

Commit 33860b2

Browse files
authored
[lldb] Streamline ConstString -> std::string conversion (NFC) (#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).
1 parent cfd9119 commit 33860b2

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
@@ -167,8 +167,14 @@ class ConstString {
167167

168168
// Implicitly convert \class ConstString instances to \class StringRef.
169169
operator llvm::StringRef() const { return GetStringRef(); }
170-
// Implicitly convert \class ConstString instances to \calss std::string_view.
171-
operator std::string_view() const { return std::string_view(m_string, GetLength()); }
170+
171+
// Implicitly convert \class ConstString instances to \class std::string_view.
172+
operator std::string_view() const {
173+
return std::string_view(m_string, GetLength());
174+
}
175+
176+
// Explicitly convert \class ConstString instances to \class std::string.
177+
explicit operator std::string() const { return GetString(); }
172178

173179
/// Get the string value as a C string.
174180
///
@@ -192,6 +198,9 @@ class ConstString {
192198
return llvm::StringRef(m_string, GetLength());
193199
}
194200

201+
/// Get the string value as a std::string
202+
std::string GetString() const { return std::string(m_string, GetLength()); }
203+
195204
/// Get the string value as a C string.
196205
///
197206
/// 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)