Skip to content

Commit 09ce059

Browse files
committed
array: Implement iterator.
1 parent 3399668 commit 09ce059

1 file changed

Lines changed: 36 additions & 0 deletions

File tree

py/objarray.c

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ typedef struct _mp_obj_array_t {
2929
void *items;
3030
} mp_obj_array_t;
3131

32+
static mp_obj_t array_iterator_new(mp_obj_t array_in);
3233
static mp_obj_array_t *array_new(char typecode, uint n);
3334
static mp_obj_t array_append(mp_obj_t self_in, mp_obj_t arg);
3435

@@ -239,6 +240,7 @@ const mp_obj_type_t array_type = {
239240
"array",
240241
.print = array_print,
241242
.make_new = array_make_new,
243+
.getiter = array_iterator_new,
242244
.binary_op = array_binary_op,
243245
.store_item = array_store_item,
244246
.methods = array_type_methods,
@@ -264,3 +266,37 @@ mp_obj_t mp_obj_new_bytearray(uint n, void *items) {
264266
memcpy(o->items, items, n);
265267
return o;
266268
}
269+
270+
/******************************************************************************/
271+
/* array iterator */
272+
273+
typedef struct _mp_obj_array_it_t {
274+
mp_obj_base_t base;
275+
mp_obj_array_t *array;
276+
machine_uint_t cur;
277+
} mp_obj_array_it_t;
278+
279+
mp_obj_t array_it_iternext(mp_obj_t self_in) {
280+
mp_obj_array_it_t *self = self_in;
281+
if (self->cur < self->array->len) {
282+
machine_int_t val = array_get_el(self->array, self->cur++);
283+
return mp_obj_new_int(val);
284+
} else {
285+
return mp_const_stop_iteration;
286+
}
287+
}
288+
289+
static const mp_obj_type_t array_it_type = {
290+
{ &mp_const_type },
291+
"array_iterator",
292+
.iternext = array_it_iternext,
293+
};
294+
295+
mp_obj_t array_iterator_new(mp_obj_t array_in) {
296+
mp_obj_array_t *array = array_in;
297+
mp_obj_array_it_t *o = m_new_obj(mp_obj_array_it_t);
298+
o->base.type = &array_it_type;
299+
o->array = array;
300+
o->cur = 0;
301+
return o;
302+
}

0 commit comments

Comments
 (0)