Skip to content

Match Python for rfind and count with start/end bounds - #65

Open
bardrop wants to merge 1 commit into
imageworks:masterfrom
bardrop-oss:fix-rfind-count-bounds
Open

bardrop wants to merge 1 commit into
imageworks:masterfrom
bardrop-oss:fix-rfind-count-bounds

Conversation

@bardrop

@bardrop bardrop commented Nov 21, 2026

Copy link
Copy Markdown

Two index-bound cases where pystring and Python disagree:

pystring::rfind("abcabc", "c", 0, 5);     // -1, Python gives 2
pystring::rfind("abcabcabc", "bc", 0, 8); // -1, Python gives 4
pystring::count("abc", "", 5);            // -1, Python gives 0
pystring::count("abc", "", 3, 0);         // -2, Python gives 0
  • rfind: it called str.rfind(sub, end), which can return a match that starts before end but runs past it. That match was rejected and the function returned -1 without looking for an earlier one. It now searches back from end - sub.size(), so the first hit always fits.
  • count with an empty substring: end - start + 1 went negative when start > end after adjusting the indices. It now returns 0 there, like Python.

I compared find, rfind, count, startswith, endswith and slice with Python 3 on 6,000 random strings with random (also negative and out-of-range) bounds: rfind differed in 39 cases and count in 308 before this change, and none after.

Tests: added cases to the rfind and count_python3 tests; 4 checks fail before the change and make test passes after. No new compiler warnings.

rfind searched back from end itself, so it found a match that ran past
end, rejected it, and returned -1 without trying earlier matches:
rfind("abcabc", "c", 0, 5) gave -1 instead of 2.

count with an empty substring returned end - start + 1 even when start
was past end, giving negative counts: count("abc", "", 5) gave -1.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant