Skip to content

Commit 1c20932

Browse files
authored
[ADT] Make StringRef std::string_view conversion operator constexpr. NFC (#77506)
This would allow us to compare StringRefs via std::string_view, avoiding having to make the existing StringRef compare machinery constexpr for now.
1 parent cd7eaaa commit 1c20932

File tree

2 files changed

+16
-2
lines changed

2 files changed

+16
-2
lines changed

llvm/include/llvm/ADT/StringRef.h

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -128,7 +128,7 @@ namespace llvm {
128128

129129
/// data - Get a pointer to the start of the string (which may not be null
130130
/// terminated).
131-
[[nodiscard]] const char *data() const { return Data; }
131+
[[nodiscard]] constexpr const char *data() const { return Data; }
132132

133133
/// empty - Check if the string is empty.
134134
[[nodiscard]] constexpr bool empty() const { return Length == 0; }
@@ -245,7 +245,7 @@ namespace llvm {
245245
/// @name Type Conversions
246246
/// @{
247247

248-
operator std::string_view() const {
248+
constexpr operator std::string_view() const {
249249
return std::string_view(data(), size());
250250
}
251251

llvm/unittests/ADT/StringRefTest.cpp

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ TEST(StringRefTest, Construction) {
5959
TEST(StringRefTest, Conversion) {
6060
EXPECT_EQ("hello", std::string(StringRef("hello")));
6161
EXPECT_EQ("hello", std::string_view(StringRef("hello")));
62+
static_assert(std::string_view(StringRef("hello")) == "hello");
6263
}
6364

6465
TEST(StringRefTest, EmptyInitializerList) {
@@ -78,9 +79,22 @@ TEST(StringRefTest, Iteration) {
7879

7980
TEST(StringRefTest, StringOps) {
8081
const char *p = "hello";
82+
8183
EXPECT_EQ(p, StringRef(p, 0).data());
84+
static_assert(StringRef("hello").data()[0] == 'h');
85+
static_assert(StringRef("hello").data()[1] == 'e');
86+
static_assert(StringRef("hello").data()[2] == 'l');
87+
static_assert(StringRef("hello").data()[3] == 'l');
88+
static_assert(StringRef("hello").data()[4] == 'o');
89+
static_assert(StringRef("hello").data()[5] == '\0');
90+
8291
EXPECT_TRUE(StringRef().empty());
92+
static_assert(StringRef("").empty());
93+
static_assert(!StringRef("hello").empty());
94+
8395
EXPECT_EQ((size_t) 5, StringRef("hello").size());
96+
static_assert(StringRef("hello").size() == 5);
97+
8498
EXPECT_GT( 0, StringRef("aab").compare("aad"));
8599
EXPECT_EQ( 0, StringRef("aab").compare("aab"));
86100
EXPECT_LT( 0, StringRef("aab").compare("aaa"));

0 commit comments

Comments
 (0)