Skip to content

Commit 9bb84ce

Browse files
[ADT] Add StringRef::{starts,ends}_with(char) (#90311)
This patch adds to StringRef the equivalent of std::string_view::{starts,ends}_with(char) in C++20.
1 parent 7aa6896 commit 9bb84ce

File tree

2 files changed

+10
-0
lines changed

2 files changed

+10
-0
lines changed

llvm/include/llvm/ADT/StringRef.h

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -258,6 +258,9 @@ namespace llvm {
258258
return Length >= Prefix.Length &&
259259
compareMemory(Data, Prefix.Data, Prefix.Length) == 0;
260260
}
261+
[[nodiscard]] bool starts_with(char Prefix) const {
262+
return !empty() && front() == Prefix;
263+
}
261264

262265
/// Check if this string starts with the given \p Prefix, ignoring case.
263266
[[nodiscard]] bool starts_with_insensitive(StringRef Prefix) const;
@@ -268,6 +271,9 @@ namespace llvm {
268271
compareMemory(end() - Suffix.Length, Suffix.Data, Suffix.Length) ==
269272
0;
270273
}
274+
[[nodiscard]] bool ends_with(char Suffix) const {
275+
return !empty() && back() == Suffix;
276+
}
271277

272278
/// Check if this string ends with the given \p Suffix, ignoring case.
273279
[[nodiscard]] bool ends_with_insensitive(StringRef Suffix) const;

llvm/unittests/ADT/StringRefTest.cpp

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -368,6 +368,8 @@ TEST(StringRefTest, StartsWith) {
368368
EXPECT_TRUE(Str.starts_with("he"));
369369
EXPECT_FALSE(Str.starts_with("helloworld"));
370370
EXPECT_FALSE(Str.starts_with("hi"));
371+
EXPECT_TRUE(Str.starts_with('h'));
372+
EXPECT_FALSE(Str.starts_with('i'));
371373
}
372374

373375
TEST(StringRefTest, StartsWithInsensitive) {
@@ -421,6 +423,8 @@ TEST(StringRefTest, EndsWith) {
421423
EXPECT_FALSE(Str.ends_with("helloworld"));
422424
EXPECT_FALSE(Str.ends_with("worldhello"));
423425
EXPECT_FALSE(Str.ends_with("so"));
426+
EXPECT_TRUE(Str.ends_with('o'));
427+
EXPECT_FALSE(Str.ends_with('p'));
424428
}
425429

426430
TEST(StringRefTest, EndsWithInsensitive) {

0 commit comments

Comments
 (0)