Commit 0cd1dc06 authored by Paul Sokolovsky's avatar Paul Sokolovsky
Browse files

Factor out mp_seq_index_obj() function to implement .index() on sequences.

parent 76f06de9
......@@ -402,3 +402,4 @@ bool m_seq_get_fast_slice_indexes(machine_uint_t len, mp_obj_t slice, machine_ui
#define m_seq_cat(dest, src1, len1, src2, len2, item_t) { memcpy(dest, src1, len1 * sizeof(item_t)); memcpy(dest + len1, src2, len2 * sizeof(item_t)); }
bool mp_seq_cmp_bytes(int op, const byte *data1, uint len1, const byte *data2, uint len2);
bool mp_seq_cmp_objs(int op, const mp_obj_t *items1, uint len1, const mp_obj_t *items2, uint len2);
mp_obj_t mp_seq_index_obj(const mp_obj_t *items, uint len, uint n_args, const mp_obj_t *args);
......@@ -274,24 +274,7 @@ static mp_obj_t list_index(uint n_args, const mp_obj_t *args) {
assert(2 <= n_args && n_args <= 4);
assert(MP_OBJ_IS_TYPE(args[0], &list_type));
mp_obj_list_t *self = args[0];
mp_obj_t *value = args[1];
uint start = 0;
uint stop = self->len;
if (n_args >= 3) {
start = mp_get_index(self->base.type, self->len, args[2]);
if (n_args >= 4) {
stop = mp_get_index(self->base.type, self->len, args[3]);
}
}
for (uint i = start; i < stop; i++) {
if (mp_obj_equal(self->items[i], value)) {
return mp_obj_new_int(i);
}
}
nlr_jump(mp_obj_new_exception_msg(MP_QSTR_ValueError, "object not in list"));
return mp_seq_index_obj(self->items, self->len, n_args, args);
}
static mp_obj_t list_insert(mp_obj_t self_in, mp_obj_t idx, mp_obj_t obj) {
......
......@@ -140,3 +140,26 @@ bool mp_seq_cmp_objs(int op, const mp_obj_t *items1, uint len1, const mp_obj_t *
return true;
}
// Special-case of index() which searches for mp_obj_t
mp_obj_t mp_seq_index_obj(const mp_obj_t *items, uint len, uint n_args, const mp_obj_t *args) {
mp_obj_type_t *type = mp_obj_get_type(args[0]);
mp_obj_t *value = args[1];
uint start = 0;
uint stop = len;
if (n_args >= 3) {
start = mp_get_index(type, len, args[2]);
if (n_args >= 4) {
stop = mp_get_index(type, len, args[3]);
}
}
for (uint i = start; i < stop; i++) {
if (mp_obj_equal(items[i], value)) {
return mp_obj_new_int_from_uint(i);
}
}
nlr_jump(mp_obj_new_exception_msg(MP_QSTR_ValueError, "object not in sequence"));
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment