}
Py_LOCAL(Py_ssize_t)
-countchar(char *target, int target_len, char c)
+ countchar(char *target, int target_len, char c, Py_ssize_t maxcount)
{
Py_ssize_t count=0;
char *start=target;
while ( (start=findchar(start, end-start, c)) != NULL ) {
count++;
+ if (count >= maxcount)
+ break;
start += 1;
}
-
return count;
}
char *pattern, Py_ssize_t pattern_len,
Py_ssize_t start,
Py_ssize_t end,
- int direction)
+ int direction, Py_ssize_t maxcount)
{
Py_ssize_t count=0;
}
/* zero-length substrings match everywhere */
- if (pattern_len == 0)
- return target_len+1;
+ if (pattern_len == 0 || maxcount == 0) {
+ if (target_len+1 < maxcount)
+ return target_len+1;
+ return maxcount;
+ }
end -= pattern_len;
-
if (direction < 0) {
- for (; end >= start; end--)
+ for (; (end >= start); end--)
if (Py_STRING_MATCH(target, end, pattern, pattern_len)) {
count++;
+ if (--maxcount <= 0) break;
end -= pattern_len-1;
}
} else {
- for (; start <= end; start++)
+ for (; (start <= end); start++)
if (Py_STRING_MATCH(target, start, pattern, pattern_len)) {
count++;
+ if (--maxcount <= 0)
+ break;
start += pattern_len-1;
}
}
self_len = PyString_GET_SIZE(self);
self_s = PyString_AS_STRING(self);
- count = countchar(self_s, self_len, from_c);
+ count = countchar(self_s, self_len, from_c, maxcount);
if (count == 0) {
return return_self(self);
}
- if (count > maxcount)
- count = maxcount;
result_len = self_len - count; /* from_len == 1 */
assert(result_len>=0);
count = countstring(self_s, self_len,
from_s, from_len,
- 0, self_len, 1);
-
- if (count > maxcount)
- count = maxcount;
+ 0, self_len, 1,
+ maxcount);
if (count == 0) {
/* no matches */
self_s = PyString_AS_STRING(self);
self_len = PyString_GET_SIZE(self);
- count = countchar(self_s, self_len, from_c);
- if (count > maxcount)
- count = maxcount;
+ count = countchar(self_s, self_len, from_c, maxcount);
if (count == 0) {
/* no matches, return unchanged */
count = countstring(self_s, self_len,
from_s, from_len,
- 0, self_len, FORWARD);
- if (count > maxcount)
- count = maxcount;
-
+ 0, self_len, FORWARD, maxcount);
if (count == 0) {
/* no matches, return unchanged */
return return_self(self);