modstruct.c 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. /*
  2. * This file is part of the MicroPython project, http://micropython.org/
  3. *
  4. * The MIT License (MIT)
  5. *
  6. * Copyright (c) 2013, 2014 Damien P. George
  7. * Copyright (c) 2014 Paul Sokolovsky
  8. *
  9. * Permission is hereby granted, free of charge, to any person obtaining a copy
  10. * of this software and associated documentation files (the "Software"), to deal
  11. * in the Software without restriction, including without limitation the rights
  12. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. * copies of the Software, and to permit persons to whom the Software is
  14. * furnished to do so, subject to the following conditions:
  15. *
  16. * The above copyright notice and this permission notice shall be included in
  17. * all copies or substantial portions of the Software.
  18. *
  19. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. * THE SOFTWARE.
  26. */
  27. #include <assert.h>
  28. #include <string.h>
  29. #include "py/runtime.h"
  30. #include "py/builtin.h"
  31. #include "py/objtuple.h"
  32. #include "py/binary.h"
  33. #include "py/parsenum.h"
  34. #if MICROPY_PY_STRUCT
  35. /*
  36. This module implements most of character typecodes from CPython, with
  37. some extensions:
  38. O - (Pointer to) an arbitrary Python object. This is useful for callback
  39. data, etc. Note that you must keep reference to passed object in
  40. your Python application, otherwise it may be garbage-collected,
  41. and then when you get back this value from callback it may be
  42. invalid (and lead to crash).
  43. S - Pointer to a string (returned as a Python string). Note the
  44. difference from "Ns", - the latter says "in this place of structure
  45. is character data of up to N bytes length", while "S" means
  46. "in this place of a structure is a pointer to zero-terminated
  47. character data".
  48. */
  49. static char get_fmt_type(const char **fmt) {
  50. char t = **fmt;
  51. switch (t) {
  52. case '!':
  53. t = '>';
  54. break;
  55. case '@':
  56. case '=':
  57. case '<':
  58. case '>':
  59. break;
  60. default:
  61. return '@';
  62. }
  63. // Skip type char
  64. (*fmt)++;
  65. return t;
  66. }
  67. static mp_uint_t get_fmt_num(const char **p) {
  68. const char *num = *p;
  69. uint len = 1;
  70. while (unichar_isdigit(*++num)) {
  71. len++;
  72. }
  73. mp_uint_t val = (mp_uint_t)MP_OBJ_SMALL_INT_VALUE(mp_parse_num_integer(*p, len, 10, NULL));
  74. *p = num;
  75. return val;
  76. }
  77. static size_t calc_size_items(const char *fmt, size_t *total_sz) {
  78. char fmt_type = get_fmt_type(&fmt);
  79. size_t total_cnt = 0;
  80. size_t size;
  81. for (size = 0; *fmt; fmt++) {
  82. mp_uint_t cnt = 1;
  83. if (unichar_isdigit(*fmt)) {
  84. cnt = get_fmt_num(&fmt);
  85. }
  86. if (*fmt == 'x') {
  87. size += cnt;
  88. } else if (*fmt == 's') {
  89. total_cnt += 1;
  90. size += cnt;
  91. } else {
  92. total_cnt += cnt;
  93. size_t align;
  94. size_t sz = mp_binary_get_size(fmt_type, *fmt, &align);
  95. while (cnt--) {
  96. // Apply alignment
  97. size = (size + align - 1) & ~(align - 1);
  98. size += sz;
  99. }
  100. }
  101. }
  102. *total_sz = size;
  103. return total_cnt;
  104. }
  105. static mp_obj_t struct_calcsize(mp_obj_t fmt_in) {
  106. const char *fmt = mp_obj_str_get_str(fmt_in);
  107. size_t size;
  108. calc_size_items(fmt, &size);
  109. return MP_OBJ_NEW_SMALL_INT(size);
  110. }
  111. MP_DEFINE_CONST_FUN_OBJ_1(struct_calcsize_obj, struct_calcsize);
  112. static mp_obj_t struct_unpack_from(size_t n_args, const mp_obj_t *args) {
  113. // unpack requires that the buffer be exactly the right size.
  114. // unpack_from requires that the buffer be "big enough".
  115. // Since we implement unpack and unpack_from using the same function
  116. // we relax the "exact" requirement, and only implement "big enough".
  117. const char *fmt = mp_obj_str_get_str(args[0]);
  118. size_t total_sz;
  119. size_t num_items = calc_size_items(fmt, &total_sz);
  120. char fmt_type = get_fmt_type(&fmt);
  121. mp_obj_tuple_t *res = MP_OBJ_TO_PTR(mp_obj_new_tuple(num_items, NULL));
  122. mp_buffer_info_t bufinfo;
  123. mp_get_buffer_raise(args[1], &bufinfo, MP_BUFFER_READ);
  124. byte *p = bufinfo.buf;
  125. byte *end_p = &p[bufinfo.len];
  126. mp_int_t offset = 0;
  127. if (n_args > 2) {
  128. // offset arg provided
  129. offset = mp_obj_get_int(args[2]);
  130. if (offset < 0) {
  131. // negative offsets are relative to the end of the buffer
  132. offset = bufinfo.len + offset;
  133. if (offset < 0) {
  134. mp_raise_ValueError(MP_ERROR_TEXT("buffer too small"));
  135. }
  136. }
  137. p += offset;
  138. }
  139. byte *p_base = p;
  140. // Check that the input buffer is big enough to unpack all the values
  141. if (p + total_sz > end_p) {
  142. mp_raise_ValueError(MP_ERROR_TEXT("buffer too small"));
  143. }
  144. for (size_t i = 0; i < num_items;) {
  145. mp_uint_t cnt = 1;
  146. if (unichar_isdigit(*fmt)) {
  147. cnt = get_fmt_num(&fmt);
  148. }
  149. mp_obj_t item;
  150. if (*fmt == 'x') {
  151. p += cnt;
  152. } else if (*fmt == 's') {
  153. item = mp_obj_new_bytes(p, cnt);
  154. p += cnt;
  155. res->items[i++] = item;
  156. } else {
  157. while (cnt--) {
  158. item = mp_binary_get_val(fmt_type, *fmt, p_base, &p);
  159. res->items[i++] = item;
  160. }
  161. }
  162. fmt++;
  163. }
  164. return MP_OBJ_FROM_PTR(res);
  165. }
  166. MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(struct_unpack_from_obj, 2, 3, struct_unpack_from);
  167. // This function assumes there is enough room in p to store all the values
  168. static void struct_pack_into_internal(mp_obj_t fmt_in, byte *p, size_t n_args, const mp_obj_t *args) {
  169. const char *fmt = mp_obj_str_get_str(fmt_in);
  170. char fmt_type = get_fmt_type(&fmt);
  171. byte *p_base = p;
  172. size_t i;
  173. for (i = 0; i < n_args;) {
  174. mp_uint_t cnt = 1;
  175. if (*fmt == '\0') {
  176. // more arguments given than used by format string; CPython raises struct.error here
  177. break;
  178. }
  179. if (unichar_isdigit(*fmt)) {
  180. cnt = get_fmt_num(&fmt);
  181. }
  182. if (*fmt == 'x') {
  183. memset(p, 0, cnt);
  184. p += cnt;
  185. } else if (*fmt == 's') {
  186. mp_buffer_info_t bufinfo;
  187. mp_get_buffer_raise(args[i++], &bufinfo, MP_BUFFER_READ);
  188. mp_uint_t to_copy = cnt;
  189. if (bufinfo.len < to_copy) {
  190. to_copy = bufinfo.len;
  191. }
  192. memcpy(p, bufinfo.buf, to_copy);
  193. memset(p + to_copy, 0, cnt - to_copy);
  194. p += cnt;
  195. } else {
  196. // If we run out of args then we just finish; CPython would raise struct.error
  197. while (cnt-- && i < n_args) {
  198. mp_binary_set_val(fmt_type, *fmt, args[i++], p_base, &p);
  199. }
  200. }
  201. fmt++;
  202. }
  203. }
  204. static mp_obj_t struct_pack(size_t n_args, const mp_obj_t *args) {
  205. // TODO: "The arguments must match the values required by the format exactly."
  206. mp_int_t size = MP_OBJ_SMALL_INT_VALUE(struct_calcsize(args[0]));
  207. vstr_t vstr;
  208. vstr_init_len(&vstr, size);
  209. byte *p = (byte *)vstr.buf;
  210. memset(p, 0, size);
  211. struct_pack_into_internal(args[0], p, n_args - 1, &args[1]);
  212. return mp_obj_new_bytes_from_vstr(&vstr);
  213. }
  214. MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(struct_pack_obj, 1, MP_OBJ_FUN_ARGS_MAX, struct_pack);
  215. static mp_obj_t struct_pack_into(size_t n_args, const mp_obj_t *args) {
  216. mp_buffer_info_t bufinfo;
  217. mp_get_buffer_raise(args[1], &bufinfo, MP_BUFFER_WRITE);
  218. mp_int_t offset = mp_obj_get_int(args[2]);
  219. if (offset < 0) {
  220. // negative offsets are relative to the end of the buffer
  221. offset = (mp_int_t)bufinfo.len + offset;
  222. if (offset < 0) {
  223. mp_raise_ValueError(MP_ERROR_TEXT("buffer too small"));
  224. }
  225. }
  226. byte *p = (byte *)bufinfo.buf;
  227. byte *end_p = &p[bufinfo.len];
  228. p += offset;
  229. // Check that the output buffer is big enough to hold all the values
  230. mp_int_t sz = MP_OBJ_SMALL_INT_VALUE(struct_calcsize(args[0]));
  231. if (p + sz > end_p) {
  232. mp_raise_ValueError(MP_ERROR_TEXT("buffer too small"));
  233. }
  234. struct_pack_into_internal(args[0], p, n_args - 3, &args[3]);
  235. return mp_const_none;
  236. }
  237. MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(struct_pack_into_obj, 3, MP_OBJ_FUN_ARGS_MAX, struct_pack_into);
  238. static const mp_rom_map_elem_t mp_module_struct_globals_table[] = {
  239. { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_struct) },
  240. { MP_ROM_QSTR(MP_QSTR_calcsize), MP_ROM_PTR(&struct_calcsize_obj) },
  241. { MP_ROM_QSTR(MP_QSTR_pack), MP_ROM_PTR(&struct_pack_obj) },
  242. { MP_ROM_QSTR(MP_QSTR_pack_into), MP_ROM_PTR(&struct_pack_into_obj) },
  243. { MP_ROM_QSTR(MP_QSTR_unpack), MP_ROM_PTR(&struct_unpack_from_obj) },
  244. { MP_ROM_QSTR(MP_QSTR_unpack_from), MP_ROM_PTR(&struct_unpack_from_obj) },
  245. };
  246. static MP_DEFINE_CONST_DICT(mp_module_struct_globals, mp_module_struct_globals_table);
  247. const mp_obj_module_t mp_module_struct = {
  248. .base = { &mp_type_module },
  249. .globals = (mp_obj_dict_t *)&mp_module_struct_globals,
  250. };
  251. MP_REGISTER_EXTENSIBLE_MODULE(MP_QSTR_struct, mp_module_struct);
  252. #endif