[llvm] 9f6b13e - [Support] Fix behavior of StringRef::count with overlapping occurrences, add tests
Johannes Doerfert via llvm-commits
llvm-commits at lists.llvm.org
Tue Dec 24 16:31:30 PST 2019
Author: Johannes Doerfert
Date: 2019-12-24T18:30:41-06:00
New Revision: 9f6b13e5cce96066d7262d224c971d93c2724795
URL: https://github.com/llvm/llvm-project/commit/9f6b13e5cce96066d7262d224c971d93c2724795
DIFF: https://github.com/llvm/llvm-project/commit/9f6b13e5cce96066d7262d224c971d93c2724795.diff
LOG: [Support] Fix behavior of StringRef::count with overlapping occurrences, add tests
Summary:
Fix the behavior of StringRef::count(StringRef) to not count overlapping occurrences, as is stated in the documentation.
Fixes bug https://bugs.llvm.org/show_bug.cgi?id=44072
I added Krzysztof Parzyszek to review this change because a use of this function in HexagonInstrInfo::getInlineAsmLength might depend on the overlapping-behavior. I don't have enough domain knowledge to tell if this change could break anything there.
All other uses of this method in LLVM (besides the unit tests) only use single-character search strings. In those cases, search occurrences can not overlap anyway.
Patch by Benno (@Bensge)
Reviewed By: jdoerfert
Differential Revision: https://reviews.llvm.org/D70585
Added:
Modified:
llvm/lib/Support/StringRef.cpp
llvm/unittests/ADT/StringRefTest.cpp
Removed:
################################################################################
diff --git a/llvm/lib/Support/StringRef.cpp b/llvm/lib/Support/StringRef.cpp
index 4bafc4ec7181..d7fa99dbde27 100644
--- a/llvm/lib/Support/StringRef.cpp
+++ b/llvm/lib/Support/StringRef.cpp
@@ -374,9 +374,14 @@ size_t StringRef::count(StringRef Str) const {
size_t N = Str.size();
if (N > Length)
return 0;
- for (size_t i = 0, e = Length - N + 1; i != e; ++i)
- if (substr(i, N).equals(Str))
+ for (size_t i = 0, e = Length - N + 1; i < e;) {
+ if (substr(i, N).equals(Str)) {
++Count;
+ i += N;
+ }
+ else
+ ++i;
+ }
return Count;
}
diff --git a/llvm/unittests/ADT/StringRefTest.cpp b/llvm/unittests/ADT/StringRefTest.cpp
index 2e5159dde1ce..cbb2a30ff17a 100644
--- a/llvm/unittests/ADT/StringRefTest.cpp
+++ b/llvm/unittests/ADT/StringRefTest.cpp
@@ -509,6 +509,13 @@ TEST(StringRefTest, Count) {
EXPECT_EQ(1U, Str.count("hello"));
EXPECT_EQ(1U, Str.count("ello"));
EXPECT_EQ(0U, Str.count("zz"));
+
+ StringRef OverlappingAbba("abbabba");
+ EXPECT_EQ(1U, OverlappingAbba.count("abba"));
+ StringRef NonOverlappingAbba("abbaabba");
+ EXPECT_EQ(2U, NonOverlappingAbba.count("abba"));
+ StringRef ComplexAbba("abbabbaxyzabbaxyz");
+ EXPECT_EQ(2U, ComplexAbba.count("abba"));
}
TEST(StringRefTest, EditDistance) {
More information about the llvm-commits
mailing list