|
6 | 6 | #include "obj.h" |
7 | 7 | #include "builtin.h" |
8 | 8 | #include "objtuple.h" |
| 9 | +#include "objstr.h" |
9 | 10 | #include "binary.h" |
10 | 11 |
|
11 | 12 | #if MICROPY_ENABLE_MOD_STRUCT |
@@ -69,9 +70,26 @@ STATIC mp_obj_t struct_unpack(mp_obj_t fmt_in, mp_obj_t data_in) { |
69 | 70 | } |
70 | 71 | MP_DEFINE_CONST_FUN_OBJ_2(struct_unpack_obj, struct_unpack); |
71 | 72 |
|
| 73 | +STATIC mp_obj_t struct_pack(uint n_args, mp_obj_t *args) { |
| 74 | + // TODO: "The arguments must match the values required by the format exactly." |
| 75 | + const char *fmt = mp_obj_str_get_str(args[0]); |
| 76 | + char fmt_type = get_fmt_type(&fmt); |
| 77 | + int size = MP_OBJ_SMALL_INT_VALUE(struct_calcsize(args[0])); |
| 78 | + byte *p; |
| 79 | + mp_obj_t res = mp_obj_str_builder_start(&mp_type_bytes, size, &p); |
| 80 | + memset(p, 0, size); |
| 81 | + |
| 82 | + for (uint i = 1; i < n_args; i++) { |
| 83 | + mp_binary_set_val(fmt_type, *fmt++, args[i], &p); |
| 84 | + } |
| 85 | + return res; |
| 86 | +} |
| 87 | +MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(struct_pack_obj, 1, -1, struct_pack); |
| 88 | + |
72 | 89 | STATIC const mp_map_elem_t mp_module_struct_globals_table[] = { |
73 | 90 | { MP_OBJ_NEW_QSTR(MP_QSTR___name__), MP_OBJ_NEW_QSTR(MP_QSTR_struct) }, |
74 | 91 | { MP_OBJ_NEW_QSTR(MP_QSTR_calcsize), (mp_obj_t)&struct_calcsize_obj }, |
| 92 | + { MP_OBJ_NEW_QSTR(MP_QSTR_pack), (mp_obj_t)&struct_pack_obj }, |
75 | 93 | { MP_OBJ_NEW_QSTR(MP_QSTR_unpack), (mp_obj_t)&struct_unpack_obj }, |
76 | 94 | }; |
77 | 95 |
|
|
0 commit comments