Skip to content

Commit c5d70ba

Browse files
committed
Fix issues in str.count implementation.
See pull request adafruit#343.
1 parent 9e1e8cd commit c5d70ba

3 files changed

Lines changed: 17 additions & 21 deletions

File tree

py/obj.c

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -224,24 +224,24 @@ uint mp_get_index(const mp_obj_type_t *type, machine_uint_t len, mp_obj_t index,
224224
if (MP_OBJ_IS_SMALL_INT(index)) {
225225
i = MP_OBJ_SMALL_INT_VALUE(index);
226226
} else if (MP_OBJ_IS_TYPE(index, &bool_type)) {
227-
i = index == mp_const_true ? 1 : 0;
227+
i = (index == mp_const_true ? 1 : 0);
228228
} else {
229229
nlr_jump(mp_obj_new_exception_msg_varg(&mp_type_TypeError, "%s indices must be integers, not %s", qstr_str(type->name), mp_obj_get_type_str(index)));
230230
}
231231

232232
if (i < 0) {
233-
i += len;
233+
i += len;
234234
}
235235
if (is_slice) {
236-
if (i < 0) {
237-
i = 0;
238-
} else if (i > len) {
239-
i = len;
240-
}
236+
if (i < 0) {
237+
i = 0;
238+
} else if (i > len) {
239+
i = len;
240+
}
241241
} else {
242-
if (i < 0 || i >= len) {
243-
nlr_jump(mp_obj_new_exception_msg_varg(&mp_type_IndexError, "%s index out of range", qstr_str(type->name)));
244-
}
242+
if (i < 0 || i >= len) {
243+
nlr_jump(mp_obj_new_exception_msg_varg(&mp_type_IndexError, "%s index out of range", qstr_str(type->name)));
244+
}
245245
}
246246
return i;
247247
}

py/objstr.c

Lines changed: 6 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -509,19 +509,14 @@ STATIC mp_obj_t str_count(uint n_args, const mp_obj_t *args) {
509509

510510
// needle won't exist in haystack if it's longer, so nothing to count
511511
if (needle_len > haystack_len) {
512-
MP_OBJ_NEW_SMALL_INT(0);
512+
MP_OBJ_NEW_SMALL_INT(0);
513513
}
514514

515-
for (machine_uint_t haystack_index = start; haystack_index <= end; haystack_index++) {
516-
for (machine_uint_t needle_index = 0; needle_index < needle_len; needle_index++) {
517-
if ((haystack_index + needle_len) > end) {
518-
return MP_OBJ_NEW_SMALL_INT(num_occurrences);
519-
}
520-
if (haystack[haystack_index + needle_index] == needle[needle_index] && needle_index == (needle_len - 1)) {
521-
num_occurrences++;
522-
}
523-
524-
}
515+
for (machine_uint_t haystack_index = start; haystack_index + needle_len <= end; haystack_index++) {
516+
if (memcmp(&haystack[haystack_index], needle, needle_len) == 0) {
517+
num_occurrences++;
518+
haystack_index += needle_len - 1;
519+
}
525520
}
526521

527522
return MP_OBJ_NEW_SMALL_INT(num_occurrences);

tests/basics/string_count.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
print("aaaa".count('a', 0, 5))
1515
print("aaaa".count('a', 1, 5))
1616
print("aaaa".count('a', -1, 5))
17+
print("abbabba".count("abba"))
1718

1819
def t():
1920
return True

0 commit comments

Comments
 (0)