From ed1c194ebf12c1e894d7620ca89c70f87b5d5709 Mon Sep 17 00:00:00 2001 From: Paul Sokolovsky Date: Mon, 25 Jul 2016 19:02:51 +0300 Subject: [PATCH] py/objstrunicode: str_index_to_ptr: Implement positive indexing properly. Order out-of-bounds check, completion check, and increment in the right way. --- py/objstrunicode.c | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/py/objstrunicode.c b/py/objstrunicode.c index c3aa008332..495ef3ae94 100644 --- a/py/objstrunicode.c +++ b/py/objstrunicode.c @@ -149,26 +149,29 @@ const byte *str_index_to_ptr(const mp_obj_type_t *type, const byte *self_data, s } } ++s; - } else if (!i) { - return self_data; // Shortcut - str[0] is its base pointer } else { // Positive indexing, correspondingly, counts from the start of the string. // It's assumed that negative indexing will generally be used with small // absolute values (eg str[-1], not str[-1000000]), which means it'll be // more efficient this way. - for (s = self_data; true; ++s) { + s = self_data; + while (1) { + // First check out-of-bounds if (s >= top) { if (is_slice) { return top; } nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_IndexError, "string index out of range")); } + // Then check completion + if (i-- == 0) { + break; + } + // Then skip UTF-8 char + ++s; while (UTF8_IS_CONT(*s)) { ++s; } - if (!i--) { - return s; - } } } return s;