objenumerate.c 1.31 KB
Newer Older
1
#include <stdlib.h>
John R. Lenton's avatar
John R. Lenton committed
2
3
4
5
#include <assert.h>

#include "misc.h"
#include "mpconfig.h"
6
#include "qstr.h"
John R. Lenton's avatar
John R. Lenton committed
7
8
9
10
11
12
13
14
15
#include "obj.h"
#include "runtime.h"

typedef struct _mp_obj_enumerate_t {
    mp_obj_base_t base;
    mp_obj_t iter;
    machine_int_t cur;
} mp_obj_enumerate_t;

16
STATIC mp_obj_t enumerate_iternext(mp_obj_t self_in);
John R. Lenton's avatar
John R. Lenton committed
17
18
19

/* TODO: enumerate is one of the ones that can take args or kwargs.
   Sticking to args for now */
20
STATIC mp_obj_t enumerate_make_new(mp_obj_t type_in, uint n_args, uint n_kw, const mp_obj_t *args) {
John R. Lenton's avatar
John R. Lenton committed
21
22
    assert(n_args > 0);
    mp_obj_enumerate_t *o = m_new_obj(mp_obj_enumerate_t);
23
    o->base.type = &mp_type_enumerate;
John R. Lenton's avatar
John R. Lenton committed
24
    o->iter = rt_getiter(args[0]);
25
    o->cur = n_args > 1 ? mp_obj_get_int(args[1]) : 0;
John R. Lenton's avatar
John R. Lenton committed
26
27
28
    return o;
}

29
const mp_obj_type_t mp_type_enumerate = {
30
    { &mp_type_type },
31
    .name = MP_QSTR_enumerate,
John R. Lenton's avatar
John R. Lenton committed
32
33
    .make_new = enumerate_make_new,
    .iternext = enumerate_iternext,
34
    .getiter = mp_identity,
John R. Lenton's avatar
John R. Lenton committed
35
36
};

37
STATIC mp_obj_t enumerate_iternext(mp_obj_t self_in) {
38
    assert(MP_OBJ_IS_TYPE(self_in, &mp_type_enumerate));
John R. Lenton's avatar
John R. Lenton committed
39
40
    mp_obj_enumerate_t *self = self_in;
    mp_obj_t next = rt_iternext(self->iter);
41
42
    if (next == MP_OBJ_NULL) {
        return MP_OBJ_NULL;
John R. Lenton's avatar
John R. Lenton committed
43
44
45
46
47
    } else {
        mp_obj_t items[] = {MP_OBJ_NEW_SMALL_INT(self->cur++), next};
        return mp_obj_new_tuple(2, items);
    }
}