Change StringRef::startswith and StringRef::endswith to versions which are a
authorEli Friedman <eli.friedman@gmail.com>
Mon, 21 Dec 2009 06:49:24 +0000 (06:49 +0000)
committerEli Friedman <eli.friedman@gmail.com>
Mon, 21 Dec 2009 06:49:24 +0000 (06:49 +0000)
bit more verbose, but optimize to much shorter code.

git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@91817 91177308-0d34-0410-b5e6-96231b3b80d8

include/llvm/ADT/StringRef.h
unittests/ADT/StringRefTest.cpp

index f299f5fd65179584476fda220f5762e80a0accbb..a7442666d678d0f59c02e0f0ec8f255499f3e2cf 100644 (file)
@@ -159,12 +159,14 @@ namespace llvm {
 
     /// startswith - Check if this string starts with the given \arg Prefix.
     bool startswith(StringRef Prefix) const {
-      return substr(0, Prefix.Length).equals(Prefix);
+      return Length >= Prefix.Length &&
+             memcmp(Data, Prefix.Data, Prefix.Length) == 0;
     }
 
     /// endswith - Check if this string ends with the given \arg Suffix.
     bool endswith(StringRef Suffix) const {
-      return slice(size() - Suffix.Length, size()).equals(Suffix);
+      return Length >= Suffix.Length &&
+             memcmp(end() - Suffix.Length, Suffix.Data, Suffix.Length) == 0;
     }
 
     /// @}
index dfa208abefdc223d2dce9bdd7f949f30d8c86621..19665df88d54eb9d1e67ec85b439da7f3cbf2fc9 100644 (file)
@@ -198,6 +198,14 @@ TEST(StringRefTest, StartsWith) {
   EXPECT_FALSE(Str.startswith("hi"));
 }
 
+TEST(StringRefTest, EndsWith) {
+  StringRef Str("hello");
+  EXPECT_TRUE(Str.endswith("lo"));
+  EXPECT_FALSE(Str.endswith("helloworld"));
+  EXPECT_FALSE(Str.endswith("worldhello"));
+  EXPECT_FALSE(Str.endswith("so"));
+}
+
 TEST(StringRefTest, Find) {
   StringRef Str("hello");
   EXPECT_EQ(2U, Str.find('l'));