_struct.c 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  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
  11. * copy of this software and associated documentation files (the "Software"),
  12. * to deal in the Software without restriction, including without limitation
  13. * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  14. * and/or sell copies of the Software, and to permit persons to whom the
  15. * Software is 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
  23. * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  24. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  25. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  26. * DEALINGS IN THE SOFTWARE.
  27. */
  28. #include "_struct.h"
  29. #include "pika_adapter_mpy.h"
  30. #define _SKIP_COMPILE 1
  31. /*
  32. This module implements most of character typecodes from CPython, with
  33. some extensions:
  34. O - (Pointer to) an arbitrary Python object. This is useful for callback
  35. data, etc. Note that you must keep reference to passed object in
  36. your Python application, otherwise it may be garbage-collected,
  37. and then when you get back this value from callback it may be
  38. invalid (and lead to crash).
  39. S - Pointer to a string (returned as a Python string). Note the
  40. difference from "Ns", - the latter says "in this place of structure
  41. is character data of up to N bytes length", while "S" means
  42. "in this place of a structure is a pointer to zero-terminated
  43. character data".
  44. */
  45. STATIC char get_fmt_type(const char** fmt) {
  46. char t = **fmt;
  47. switch (t) {
  48. case '!':
  49. t = '>';
  50. break;
  51. case '@':
  52. case '=':
  53. case '<':
  54. case '>':
  55. break;
  56. default:
  57. return '@';
  58. }
  59. // Skip type char
  60. (*fmt)++;
  61. return t;
  62. }
  63. STATIC mp_uint_t get_fmt_num(const char** p) {
  64. const char* num = *p;
  65. uint len = 1;
  66. while (unichar_isdigit(*++num)) {
  67. len++;
  68. }
  69. char buff[11] = {0};
  70. pika_platform_memcpy(buff, *p, len);
  71. mp_uint_t val = (mp_uint_t)fast_atoi((char*)buff);
  72. *p = num;
  73. return val;
  74. }
  75. STATIC size_t calc_size_items(const char* fmt, size_t* total_sz) {
  76. char fmt_type = get_fmt_type(&fmt);
  77. size_t total_cnt = 0;
  78. size_t size;
  79. for (size = 0; *fmt; fmt++) {
  80. mp_uint_t cnt = 1;
  81. if (unichar_isdigit(*fmt)) {
  82. cnt = get_fmt_num(&fmt);
  83. }
  84. if (*fmt == 's') {
  85. total_cnt += 1;
  86. size += cnt;
  87. } else {
  88. total_cnt += cnt;
  89. size_t align;
  90. size_t sz = mp_binary_get_size(fmt_type, *fmt, &align);
  91. while (cnt--) {
  92. // Apply alignment
  93. size = (size + align - 1) & ~(align - 1);
  94. size += sz;
  95. }
  96. }
  97. }
  98. *total_sz = size;
  99. return total_cnt;
  100. }
  101. STATIC mp_obj_t struct_calcsize(mp_obj_t fmt_in) {
  102. const char* fmt = mp_obj_str_get_str(fmt_in);
  103. size_t size;
  104. calc_size_items(fmt, &size);
  105. return MP_OBJ_NEW_SMALL_INT(size);
  106. }
  107. STATIC mp_obj_t struct_unpack_from(size_t n_args, mp_obj_t* args) {
  108. // unpack requires that the buffer be exactly the right size.
  109. // unpack_from requires that the buffer be "big enough".
  110. // Since we implement unpack and unpack_from using the same function
  111. // we relax the "exact" requirement, and only implement "big enough".
  112. const char* fmt = mp_obj_str_get_str((Arg*)args[0]);
  113. size_t total_sz;
  114. size_t num_items = calc_size_items(fmt, &total_sz);
  115. char fmt_type = get_fmt_type(&fmt);
  116. mp_obj_t tuple = mp_obj_new_tuple(num_items, NULL);
  117. mp_obj_tuple_t* res = MP_OBJ_TO_PTR(tuple);
  118. mp_buffer_info_t bufinfo;
  119. mp_get_buffer_raise((Arg*)args[1], &bufinfo, MP_BUFFER_READ);
  120. byte* p = bufinfo.buf;
  121. byte* end_p = &p[bufinfo.len];
  122. mp_int_t offset = 0;
  123. if (n_args > 2) {
  124. // offset arg provided
  125. offset = mp_obj_get_int((Arg*)args[2]);
  126. if (offset < 0) {
  127. // negative offsets are relative to the end of the buffer
  128. offset = bufinfo.len + offset;
  129. if (offset < 0) {
  130. mp_raise_ValueError(MP_ERROR_TEXT("buffer too small"));
  131. }
  132. }
  133. p += offset;
  134. }
  135. byte* p_base = p;
  136. // Check that the input buffer is big enough to unpack all the values
  137. if (p + total_sz > end_p) {
  138. mp_raise_ValueError(MP_ERROR_TEXT("buffer too small"));
  139. }
  140. for (size_t i = 0; i < num_items;) {
  141. mp_uint_t cnt = 1;
  142. if (unichar_isdigit(*fmt)) {
  143. cnt = get_fmt_num(&fmt);
  144. }
  145. mp_obj_t item;
  146. if (*fmt == 's') {
  147. item = mp_obj_new_bytes(p, cnt);
  148. p += cnt;
  149. res->items[i++] = item;
  150. } else {
  151. while (cnt--) {
  152. item = mp_binary_get_val(fmt_type, *fmt, p_base, &p);
  153. res->items[i++] = item;
  154. }
  155. }
  156. fmt++;
  157. }
  158. mp_obj_t ret = MP_OBJ_FROM_TUPLE(res);
  159. mp_buff_info_deinit(&bufinfo);
  160. mp_obj_tuple_deinit(tuple);
  161. return ret;
  162. }
  163. Arg* _struct_unpack(PikaObj* self, char* fmt, Arg* data, int offset) {
  164. Arg* aFmt = arg_newStr(fmt);
  165. Arg* aOffset = arg_newInt(offset);
  166. Arg** args = pikaMalloc(sizeof(Arg) * 3);
  167. args[0] = aFmt;
  168. args[1] = data;
  169. args[2] = aOffset;
  170. Arg* tuple = struct_unpack_from(3, args);
  171. arg_deinit(aFmt);
  172. arg_deinit(aOffset);
  173. pikaFree(args, sizeof(Arg) * 3);
  174. return tuple;
  175. }
  176. // This function assumes there is enough room in p to store all the values
  177. STATIC void struct_pack_into_internal(mp_obj_t fmt_in,
  178. byte* p,
  179. size_t n_args,
  180. mp_obj_t* args) {
  181. const char* fmt = mp_obj_str_get_str(fmt_in);
  182. char fmt_type = get_fmt_type(&fmt);
  183. byte* p_base = p;
  184. size_t i;
  185. for (i = 0; i < n_args;) {
  186. mp_uint_t cnt = 1;
  187. if (*fmt == '\0') {
  188. // more arguments given than used by format string; CPython raises
  189. // struct.error here
  190. break;
  191. }
  192. if (unichar_isdigit(*fmt)) {
  193. cnt = get_fmt_num(&fmt);
  194. }
  195. if (*fmt == 's') {
  196. mp_buffer_info_t bufinfo;
  197. mp_get_buffer_raise(args[i++], &bufinfo, MP_BUFFER_READ);
  198. mp_uint_t to_copy = cnt;
  199. if (bufinfo.len < to_copy) {
  200. to_copy = bufinfo.len;
  201. }
  202. pika_platform_memcpy(p, bufinfo.buf, to_copy);
  203. pika_platform_memset(p + to_copy, 0, cnt - to_copy);
  204. p += cnt;
  205. mp_buff_info_deinit(&bufinfo);
  206. } else {
  207. // If we run out of args then we just finish; CPython would raise
  208. // struct.error
  209. while (cnt-- && i < n_args) {
  210. mp_binary_set_val(fmt_type, *fmt, args[i++], p_base, &p);
  211. }
  212. }
  213. fmt++;
  214. }
  215. }
  216. Arg* _struct_pack(PikaObj* self, char* fmt, PikaTuple* vars) {
  217. Arg* aFmt = arg_newStr(fmt);
  218. size_t varlen = pikaTuple_getSize(vars);
  219. Arg* aSize = struct_calcsize(aFmt);
  220. Arg** args = pikaMalloc(sizeof(Arg) * varlen);
  221. for (size_t i = 0; i < varlen; i++) {
  222. args[i] = pikaTuple_get(vars, i);
  223. }
  224. size_t size = arg_getInt(aSize);
  225. Arg* byte = arg_newBytes(NULL, size);
  226. uint8_t* p = arg_getBytes(byte);
  227. struct_pack_into_internal(aFmt, p, varlen, args);
  228. pikaFree(args, sizeof(Arg) * varlen);
  229. arg_deinit(aFmt);
  230. arg_deinit(aSize);
  231. return byte;
  232. }
  233. #ifndef _SKIP_COMPILE
  234. STATIC mp_obj_t struct_pack_into(size_t n_args, const mp_obj_t* args) {
  235. mp_buffer_info_t bufinfo;
  236. mp_get_buffer_raise(args[1], &bufinfo, MP_BUFFER_WRITE);
  237. mp_int_t offset = mp_obj_get_int(args[2]);
  238. if (offset < 0) {
  239. // negative offsets are relative to the end of the buffer
  240. offset = (mp_int_t)bufinfo.len + offset;
  241. if (offset < 0) {
  242. mp_raise_ValueError(MP_ERROR_TEXT("buffer too small"));
  243. }
  244. }
  245. byte* p = (byte*)bufinfo.buf;
  246. byte* end_p = &p[bufinfo.len];
  247. p += offset;
  248. // Check that the output buffer is big enough to hold all the values
  249. mp_int_t sz = MP_OBJ_SMALL_INT_VALUE(struct_calcsize(args[0]));
  250. if (p + sz > end_p) {
  251. mp_raise_ValueError(MP_ERROR_TEXT("buffer too small"));
  252. }
  253. struct_pack_into_internal(args[0], p, n_args - 3, &args[3]);
  254. return mp_const_none;
  255. }
  256. #endif