[ADT] Forward some StringRef::find overloads to std::string_view
authorBenjamin Kramer <benny.kra@googlemail.com>
Sun, 15 Jan 2023 19:58:09 +0000 (20:58 +0100)
committerBenjamin Kramer <benny.kra@googlemail.com>
Sun, 15 Jan 2023 20:20:55 +0000 (21:20 +0100)
These are identical in terms of functionality and performance (checked
libc++ and libstdc++). We could do the same for rfind, but that actually
has a off-by one on its position argument.

StringRef::find(StringRef) seems to be quite a bit more optimized than
the standard library one, so leave it alone.

llvm/include/llvm/ADT/StringRef.h
llvm/lib/Support/StringRef.cpp

index f156f74..8ebd5fc 100644 (file)
@@ -286,13 +286,7 @@ namespace llvm {
     /// \returns The index of the first occurrence of \p C, or npos if not
     /// found.
     [[nodiscard]] size_t find(char C, size_t From = 0) const {
-      size_t FindBegin = std::min(From, Length);
-      if (FindBegin < Length) { // Avoid calling memchr with nullptr.
-        // Just forward to memchr, which is faster than a hand-rolled loop.
-        if (const void *P = ::memchr(Data + FindBegin, C, Length - FindBegin))
-          return static_cast<const char *>(P) - Data;
-      }
-      return npos;
+      return std::string_view(*this).find(C, From);
     }
 
     /// Search for the first character \p C in the string, ignoring case.
index f9fa511..fb93940 100644 (file)
@@ -215,15 +215,7 @@ size_t StringRef::rfind_insensitive(char C, size_t From) const {
 /// \return - The index of the last occurrence of \arg Str, or npos if not
 /// found.
 size_t StringRef::rfind(StringRef Str) const {
-  size_t N = Str.size();
-  if (N > Length)
-    return npos;
-  for (size_t i = Length - N + 1, e = 0; i != e;) {
-    --i;
-    if (substr(i, N).equals(Str))
-      return i;
-  }
-  return npos;
+  return std::string_view(*this).rfind(Str);
 }
 
 size_t StringRef::rfind_insensitive(StringRef Str) const {
@@ -257,10 +249,7 @@ StringRef::size_type StringRef::find_first_of(StringRef Chars,
 /// find_first_not_of - Find the first character in the string that is not
 /// \arg C or npos if not found.
 StringRef::size_type StringRef::find_first_not_of(char C, size_t From) const {
-  for (size_type i = std::min(From, Length), e = Length; i != e; ++i)
-    if (Data[i] != C)
-      return i;
-  return npos;
+  return std::string_view(*this).find_first_not_of(C, From);
 }
 
 /// find_first_not_of - Find the first character in the string that is not