blob: acf1a9f80150df2ed29920d0fcade4713b6b1418 [file] [log] [blame]
Damiend99b0522013-12-21 18:17:45 +00001#include <stdlib.h>
2#include <stdint.h>
3#include <string.h>
4#include <assert.h>
5
6#include "nlr.h"
7#include "misc.h"
8#include "mpconfig.h"
Damien Georgeeb7bfcb2014-01-04 15:57:35 +00009#include "mpqstr.h"
Damiend99b0522013-12-21 18:17:45 +000010#include "obj.h"
11#include "runtime0.h"
12#include "runtime.h"
13#include "map.h"
14
15typedef struct _mp_obj_dict_t {
16 mp_obj_base_t base;
17 mp_map_t map;
18} mp_obj_dict_t;
19
20void dict_print(void (*print)(void *env, const char *fmt, ...), void *env, mp_obj_t self_in) {
21 mp_obj_dict_t *self = self_in;
22 bool first = true;
23 print(env, "{");
24 for (int i = 0; i < self->map.alloc; i++) {
25 if (self->map.table[i].key != NULL) {
26 if (!first) {
27 print(env, ", ");
28 }
29 first = false;
30 mp_obj_print_helper(print, env, self->map.table[i].key);
31 print(env, ": ");
32 mp_obj_print_helper(print, env, self->map.table[i].value);
33 }
34 }
35 print(env, "}");
36}
37
38mp_obj_t dict_binary_op(int op, mp_obj_t lhs_in, mp_obj_t rhs_in) {
39 mp_obj_dict_t *o = lhs_in;
40 switch (op) {
41 case RT_BINARY_OP_SUBSCR:
42 {
43 // dict load
44 mp_map_elem_t *elem = mp_map_lookup_helper(&o->map, rhs_in, false);
45 if (elem == NULL) {
Damien Georgeeb7bfcb2014-01-04 15:57:35 +000046 nlr_jump(mp_obj_new_exception_msg(MP_QSTR_KeyError, "<value>"));
Damiend99b0522013-12-21 18:17:45 +000047 } else {
48 return elem->value;
49 }
50 }
51 default:
52 // op not supported
53 return NULL;
54 }
55}
56
Damiend99b0522013-12-21 18:17:45 +000057const mp_obj_type_t dict_type = {
58 { &mp_const_type },
59 "dict",
60 dict_print, // print
61 NULL, // call_n
62 NULL, // unary_op
63 dict_binary_op, // binary_op
64 NULL, // getiter
65 NULL, // iternext
66 {{NULL, NULL},}, // method list
67};
68
69mp_obj_t mp_obj_new_dict(int n_args) {
70 mp_obj_dict_t *o = m_new_obj(mp_obj_dict_t);
71 o->base.type = &dict_type;
72 mp_map_init(&o->map, MP_MAP_OBJ, n_args);
73 return o;
74}
Damiendae7eb72013-12-29 22:32:51 +000075
76uint mp_obj_dict_len(mp_obj_t self_in) {
77 mp_obj_dict_t *self = self_in;
78 uint len = 0;
79 for (int i = 0; i < self->map.alloc; i++) {
80 if (self->map.table[i].key != NULL) {
81 len += 1;
82 }
83 }
84 return len;
85}
86
87mp_obj_t mp_obj_dict_store(mp_obj_t self_in, mp_obj_t key, mp_obj_t value) {
88 assert(MP_OBJ_IS_TYPE(self_in, &dict_type));
89 mp_obj_dict_t *self = self_in;
90 mp_map_lookup_helper(&self->map, key, true)->value = value;
91 return self_in;
92}