Skip to content

Commit 9f6b13e

Browse files
committed
[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
1 parent a36ddf0 commit 9f6b13e

File tree

2 files changed

+14
-2
lines changed

2 files changed

+14
-2
lines changed

llvm/lib/Support/StringRef.cpp

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -374,9 +374,14 @@ size_t StringRef::count(StringRef Str) const {
374374
size_t N = Str.size();
375375
if (N > Length)
376376
return 0;
377-
for (size_t i = 0, e = Length - N + 1; i != e; ++i)
378-
if (substr(i, N).equals(Str))
377+
for (size_t i = 0, e = Length - N + 1; i < e;) {
378+
if (substr(i, N).equals(Str)) {
379379
++Count;
380+
i += N;
381+
}
382+
else
383+
++i;
384+
}
380385
return Count;
381386
}
382387

llvm/unittests/ADT/StringRefTest.cpp

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -509,6 +509,13 @@ TEST(StringRefTest, Count) {
509509
EXPECT_EQ(1U, Str.count("hello"));
510510
EXPECT_EQ(1U, Str.count("ello"));
511511
EXPECT_EQ(0U, Str.count("zz"));
512+
513+
StringRef OverlappingAbba("abbabba");
514+
EXPECT_EQ(1U, OverlappingAbba.count("abba"));
515+
StringRef NonOverlappingAbba("abbaabba");
516+
EXPECT_EQ(2U, NonOverlappingAbba.count("abba"));
517+
StringRef ComplexAbba("abbabbaxyzabbaxyz");
518+
EXPECT_EQ(2U, ComplexAbba.count("abba"));
512519
}
513520

514521
TEST(StringRefTest, EditDistance) {

0 commit comments

Comments
 (0)