summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorKazu Hirata <kazu@google.com>2024-04-27 00:37:06 -0700
committerGitHub <noreply@github.com>2024-04-27 00:37:06 -0700
commit9bb84cec1b5375c24e5fa9cf7700070d9d1b4184 (patch)
tree6f0b933b5fc66b69f4f6f3ee6dd60789472db082
parent7aa6896dd7bcdcb1d09f4f98e356c43d723d9d6b (diff)
[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.
-rw-r--r--llvm/include/llvm/ADT/StringRef.h6
-rw-r--r--llvm/unittests/ADT/StringRefTest.cpp4
2 files changed, 10 insertions, 0 deletions
diff --git a/llvm/include/llvm/ADT/StringRef.h b/llvm/include/llvm/ADT/StringRef.h
index 0360174c5231..04496c76e072 100644
--- a/llvm/include/llvm/ADT/StringRef.h
+++ b/llvm/include/llvm/ADT/StringRef.h
@@ -258,6 +258,9 @@ namespace llvm {
return Length >= Prefix.Length &&
compareMemory(Data, Prefix.Data, Prefix.Length) == 0;
}
+ [[nodiscard]] bool starts_with(char Prefix) const {
+ return !empty() && front() == Prefix;
+ }
/// Check if this string starts with the given \p Prefix, ignoring case.
[[nodiscard]] bool starts_with_insensitive(StringRef Prefix) const;
@@ -268,6 +271,9 @@ namespace llvm {
compareMemory(end() - Suffix.Length, Suffix.Data, Suffix.Length) ==
0;
}
+ [[nodiscard]] bool ends_with(char Suffix) const {
+ return !empty() && back() == Suffix;
+ }
/// Check if this string ends with the given \p Suffix, ignoring case.
[[nodiscard]] bool ends_with_insensitive(StringRef Suffix) const;
diff --git a/llvm/unittests/ADT/StringRefTest.cpp b/llvm/unittests/ADT/StringRefTest.cpp
index 8df71e8ad033..fa537e816fc8 100644
--- a/llvm/unittests/ADT/StringRefTest.cpp
+++ b/llvm/unittests/ADT/StringRefTest.cpp
@@ -368,6 +368,8 @@ TEST(StringRefTest, StartsWith) {
EXPECT_TRUE(Str.starts_with("he"));
EXPECT_FALSE(Str.starts_with("helloworld"));
EXPECT_FALSE(Str.starts_with("hi"));
+ EXPECT_TRUE(Str.starts_with('h'));
+ EXPECT_FALSE(Str.starts_with('i'));
}
TEST(StringRefTest, StartsWithInsensitive) {
@@ -421,6 +423,8 @@ TEST(StringRefTest, EndsWith) {
EXPECT_FALSE(Str.ends_with("helloworld"));
EXPECT_FALSE(Str.ends_with("worldhello"));
EXPECT_FALSE(Str.ends_with("so"));
+ EXPECT_TRUE(Str.ends_with('o'));
+ EXPECT_FALSE(Str.ends_with('p'));
}
TEST(StringRefTest, EndsWithInsensitive) {