John R. Lenton | 07205ec | 2014-01-13 02:31:00 +0000 | [diff] [blame] | 1 | #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 | |
| 9 | typedef 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 George | 20006db | 2014-01-18 14:10:48 +0000 | [diff] [blame^] | 15 | static 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. Lenton | 07205ec | 2014-01-13 02:31:00 +0000 | [diff] [blame] | 18 | 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 George | 20006db | 2014-01-18 14:10:48 +0000 | [diff] [blame^] | 22 | o->iters[i] = rt_getiter(args[i]); |
John R. Lenton | 07205ec | 2014-01-13 02:31:00 +0000 | [diff] [blame] | 23 | } |
| 24 | return o; |
| 25 | } |
| 26 | |
Damien George | 0f59203 | 2014-01-14 23:18:35 +0000 | [diff] [blame] | 27 | static mp_obj_t zip_getiter(mp_obj_t self_in) { |
| 28 | return self_in; |
| 29 | } |
John R. Lenton | 07205ec | 2014-01-13 02:31:00 +0000 | [diff] [blame] | 30 | |
| 31 | static 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 George | 0f59203 | 2014-01-14 23:18:35 +0000 | [diff] [blame] | 51 | |
| 52 | const 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 | }; |