[llvm] 9bb84ce - [ADT] Add StringRef::{starts, ends}_with(char) (#90311)
via llvm-commits
llvm-commits at lists.llvm.org
Sat Apr 27 00:37:10 PDT 2024
Author: Kazu Hirata
Date: 2024-04-27T00:37:06-07:00
New Revision: 9bb84cec1b5375c24e5fa9cf7700070d9d1b4184
URL: https://github.com/llvm/llvm-project/commit/9bb84cec1b5375c24e5fa9cf7700070d9d1b4184
DIFF: https://github.com/llvm/llvm-project/commit/9bb84cec1b5375c24e5fa9cf7700070d9d1b4184.diff
LOG: [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.
Added:
Modified:
llvm/include/llvm/ADT/StringRef.h
llvm/unittests/ADT/StringRefTest.cpp
Removed:
################################################################################
diff --git a/llvm/include/llvm/ADT/StringRef.h b/llvm/include/llvm/ADT/StringRef.h
index 0360174c5231e5..04496c76e07201 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 8df71e8ad03378..fa537e816fc8e2 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) {
More information about the llvm-commits
mailing list