Skip to content

Commit 6ee1e38

Browse files
committed
str slice: Trim slice indexes to be in range.
1 parent c8d1384 commit 6ee1e38

2 files changed

Lines changed: 16 additions & 0 deletions

File tree

py/objstr.c

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,9 +41,20 @@ mp_obj_t str_binary_op(int op, mp_obj_t lhs_in, mp_obj_t rhs_in) {
4141
int len = strlen(lhs_str);
4242
if (start < 0) {
4343
start = len + start;
44+
if (start < 0) {
45+
start = 0;
46+
}
47+
} else if (start > len) {
48+
start = len;
4449
}
4550
if (stop <= 0) {
4651
stop = len + stop;
52+
// CPython returns empty string in such case
53+
if (stop < 0) {
54+
stop = start;
55+
}
56+
} else if (stop > len) {
57+
stop = len;
4758
}
4859
return mp_obj_new_str(qstr_from_strn_copy(lhs_str + start, stop - start));
4960
#endif

tests/basics/tests/slice-bstr1.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,11 @@
2222
print(b"123"[:0])
2323
print(b"123"[:-3])
2424
print(b"123"[:-4])
25+
# Range check testing, don't segfault, please ;-)
26+
print(b"123"[:1000000])
27+
print(b"123"[1000000:])
28+
print(b"123"[:-1000000])
29+
print(b"123"[-1000000:])
2530
# No IndexError!
2631
print(b""[1:1])
2732
print(b""[-1:-1])

0 commit comments

Comments
 (0)