Skip to content

Commit ed1c194

Browse files
committed
py/objstrunicode: str_index_to_ptr: Implement positive indexing properly.
Order out-of-bounds check, completion check, and increment in the right way.
1 parent 6af90b2 commit ed1c194

1 file changed

Lines changed: 9 additions & 6 deletions

File tree

py/objstrunicode.c

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -149,26 +149,29 @@ const byte *str_index_to_ptr(const mp_obj_type_t *type, const byte *self_data, s
149149
}
150150
}
151151
++s;
152-
} else if (!i) {
153-
return self_data; // Shortcut - str[0] is its base pointer
154152
} else {
155153
// Positive indexing, correspondingly, counts from the start of the string.
156154
// It's assumed that negative indexing will generally be used with small
157155
// absolute values (eg str[-1], not str[-1000000]), which means it'll be
158156
// more efficient this way.
159-
for (s = self_data; true; ++s) {
157+
s = self_data;
158+
while (1) {
159+
// First check out-of-bounds
160160
if (s >= top) {
161161
if (is_slice) {
162162
return top;
163163
}
164164
nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_IndexError, "string index out of range"));
165165
}
166+
// Then check completion
167+
if (i-- == 0) {
168+
break;
169+
}
170+
// Then skip UTF-8 char
171+
++s;
166172
while (UTF8_IS_CONT(*s)) {
167173
++s;
168174
}
169-
if (!i--) {
170-
return s;
171-
}
172175
}
173176
}
174177
return s;

0 commit comments

Comments
 (0)