blob: 72db06ac20c104e72d96bd559a258a84eee4461b [file] [log] [blame]
John R. Lenton07205ec2014-01-13 02:31:00 +00001#include <stdlib.h>
2#include <assert.h>
3
4#include "misc.h"
5#include "mpconfig.h"
6#include "obj.h"
7#include "runtime.h"
8
9typedef struct _mp_obj_zip_t {
10 mp_obj_base_t base;
11 int n_iters;
12 mp_obj_t iters[];
13} mp_obj_zip_t;
14
Damien George20006db2014-01-18 14:10:48 +000015static mp_obj_t zip_make_new(mp_obj_t type_in, uint n_args, uint n_kw, const mp_obj_t *args) {
16 // TODO check n_kw == 0
17
John R. Lenton07205ec2014-01-13 02:31:00 +000018 mp_obj_zip_t *o = m_new_obj_var(mp_obj_zip_t, mp_obj_t, n_args);
19 o->base.type = &zip_type;
20 o->n_iters = n_args;
21 for (int i = 0; i < n_args; i++) {
Damien George20006db2014-01-18 14:10:48 +000022 o->iters[i] = rt_getiter(args[i]);
John R. Lenton07205ec2014-01-13 02:31:00 +000023 }
24 return o;
25}
26
Damien George0f592032014-01-14 23:18:35 +000027static mp_obj_t zip_getiter(mp_obj_t self_in) {
28 return self_in;
29}
John R. Lenton07205ec2014-01-13 02:31:00 +000030
31static mp_obj_t zip_iternext(mp_obj_t self_in) {
32 assert(MP_OBJ_IS_TYPE(self_in, &zip_type));
33 mp_obj_zip_t *self = self_in;
34 mp_obj_t *items;
35 if (self->n_iters == 0) {
36 return mp_const_stop_iteration;
37 }
38 mp_obj_t o = mp_obj_new_tuple(self->n_iters, NULL);
39 mp_obj_tuple_get(o, NULL, &items);
40
41 for (int i = 0; i < self->n_iters; i++) {
42 mp_obj_t next = rt_iternext(self->iters[i]);
43 if (next == mp_const_stop_iteration) {
44 mp_obj_tuple_del(o);
45 return mp_const_stop_iteration;
46 }
47 items[i] = next;
48 }
49 return o;
50}
Damien George0f592032014-01-14 23:18:35 +000051
52const mp_obj_type_t zip_type = {
53 { &mp_const_type },
54 "zip",
55 .make_new = zip_make_new,
56 .getiter = zip_getiter,
57 .iternext = zip_iternext,
58};