diff options
Diffstat (limited to 'py/objstr.c')
| -rw-r--r-- | py/objstr.c | 26 |
1 files changed, 17 insertions, 9 deletions
diff --git a/py/objstr.c b/py/objstr.c index 9d3460988..e88479459 100644 --- a/py/objstr.c +++ b/py/objstr.c @@ -290,10 +290,16 @@ mp_obj_t mp_obj_str_binary_op(int op, mp_obj_t lhs_in, mp_obj_t rhs_in) { break; case MP_BINARY_OP_MULTIPLY: { - if (!MP_OBJ_IS_SMALL_INT(rhs_in)) { + mp_int_t n; + if (!mp_obj_get_int_maybe(rhs_in, &n)) { return MP_OBJ_NULL; // op not supported } - int n = MP_OBJ_SMALL_INT_VALUE(rhs_in); + if (n <= 0) { + if (lhs_type == &mp_type_str) { + return MP_OBJ_NEW_QSTR(MP_QSTR_); // empty str + } + n = 0; + } byte *data; mp_obj_t s = mp_obj_str_builder_start(lhs_type, lhs_len * n, &data); mp_seq_multiply(lhs_data, sizeof(*lhs_data), lhs_len, n, data); @@ -353,7 +359,8 @@ const byte *str_index_to_ptr(const mp_obj_type_t *type, const byte *self_data, u } #endif -STATIC mp_obj_t str_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) { +// This is used for both bytes and 8-bit strings. This is not used for unicode strings. +STATIC mp_obj_t bytes_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) { mp_obj_type_t *type = mp_obj_get_type(self_in); GET_STR_DATA_LEN(self_in, self_data, self_len); if (value == MP_OBJ_SENTINEL) { @@ -368,11 +375,12 @@ STATIC mp_obj_t str_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) { return mp_obj_new_str_of_type(type, self_data + slice.start, slice.stop - slice.start); } #endif - const byte *p = str_index_to_ptr(type, self_data, self_len, index, false); - if (type == &mp_type_bytes) { - return MP_OBJ_NEW_SMALL_INT(*p); + mp_uint_t index_val = mp_get_index(type, self_len, index, false); + // If we have unicode enabled the type will always be bytes, so take the short cut. + if (MICROPY_PY_BUILTINS_STR_UNICODE || type == &mp_type_bytes) { + return MP_OBJ_NEW_SMALL_INT(self_data[index_val]); } else { - return mp_obj_new_str((char*)p, 1, true); + return mp_obj_new_str((char*)&self_data[index_val], 1, true); } } else { return MP_OBJ_NULL; // op not supported @@ -1704,7 +1712,7 @@ const mp_obj_type_t mp_type_str = { .print = str_print, .make_new = str_make_new, .binary_op = mp_obj_str_binary_op, - .subscr = str_subscr, + .subscr = bytes_subscr, .getiter = mp_obj_new_str_iterator, .buffer_p = { .get_buffer = mp_obj_str_get_buffer }, .locals_dict = (mp_obj_t)&str_locals_dict, @@ -1718,7 +1726,7 @@ const mp_obj_type_t mp_type_bytes = { .print = str_print, .make_new = bytes_make_new, .binary_op = mp_obj_str_binary_op, - .subscr = str_subscr, + .subscr = bytes_subscr, .getiter = mp_obj_new_bytes_iterator, .buffer_p = { .get_buffer = mp_obj_str_get_buffer }, .locals_dict = (mp_obj_t)&str_locals_dict, |
