Damien | d99b052 | 2013-12-21 18:17:45 +0000 | [diff] [blame^] | 1 | #include <stdlib.h> |
| 2 | #include <stdint.h> |
| 3 | #include <assert.h> |
| 4 | |
| 5 | #include "nlr.h" |
| 6 | #include "misc.h" |
| 7 | #include "mpconfig.h" |
| 8 | #include "obj.h" |
| 9 | #include "map.h" |
| 10 | |
| 11 | typedef struct _mp_obj_set_t { |
| 12 | mp_obj_base_t base; |
| 13 | mp_set_t set; |
| 14 | } mp_obj_set_t; |
| 15 | |
| 16 | void set_print(void (*print)(void *env, const char *fmt, ...), void *env, mp_obj_t self_in) { |
| 17 | mp_obj_set_t *self = self_in; |
| 18 | bool first = true; |
| 19 | print(env, "{"); |
| 20 | for (int i = 0; i < self->set.alloc; i++) { |
| 21 | if (self->set.table[i] != MP_OBJ_NULL) { |
| 22 | if (!first) { |
| 23 | print(env, ", "); |
| 24 | } |
| 25 | first = false; |
| 26 | mp_obj_print_helper(print, env, self->set.table[i]); |
| 27 | } |
| 28 | } |
| 29 | print(env, "}"); |
| 30 | } |
| 31 | |
| 32 | static const mp_obj_type_t set_type = { |
| 33 | { &mp_const_type }, |
| 34 | "set", |
| 35 | set_print, // print |
| 36 | NULL, // call_n |
| 37 | NULL, // unary_op |
| 38 | NULL, // binary_op |
| 39 | NULL, // getiter |
| 40 | NULL, // iternext |
| 41 | { { NULL, NULL }, }, // method list |
| 42 | }; |
| 43 | |
| 44 | mp_obj_t mp_obj_new_set(int n_args, mp_obj_t *items) { |
| 45 | mp_obj_set_t *o = m_new_obj(mp_obj_set_t); |
| 46 | o->base.type = &set_type; |
| 47 | mp_set_init(&o->set, n_args); |
| 48 | for (int i = 0; i < n_args; i++) { |
| 49 | mp_set_lookup(&o->set, items[i], true); |
| 50 | } |
| 51 | return o; |
| 52 | } |
| 53 | |
| 54 | void mp_obj_set_store(mp_obj_t self_in, mp_obj_t item) { |
| 55 | assert(MP_OBJ_IS_TYPE(self_in, &set_type)); |
| 56 | mp_obj_set_t *self = self_in; |
| 57 | mp_set_lookup(&self->set, item, true); |
| 58 | } |