_struct.c 8.2 KB

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