_struct.c 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596
  1. /* struct module -- pack values into and (out of) bytes objects */
  2. /* New version supporting byte order, alignment and size options,
  3. character strings, and unsigned numbers */
  4. #ifndef Py_BUILD_CORE_BUILTIN
  5. # define Py_BUILD_CORE_MODULE 1
  6. #endif
  7. #define PY_SSIZE_T_CLEAN
  8. #include "Python.h"
  9. #include "pycore_moduleobject.h" // _PyModule_GetState()
  10. #include "structmember.h" // PyMemberDef
  11. #include <ctype.h>
  12. /*[clinic input]
  13. class Struct "PyStructObject *" "&PyStructType"
  14. [clinic start generated code]*/
  15. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=9b032058a83ed7c3]*/
  16. typedef struct {
  17. PyObject *cache;
  18. PyObject *PyStructType;
  19. PyObject *unpackiter_type;
  20. PyObject *StructError;
  21. } _structmodulestate;
  22. static inline _structmodulestate*
  23. get_struct_state(PyObject *module)
  24. {
  25. void *state = _PyModule_GetState(module);
  26. assert(state != NULL);
  27. return (_structmodulestate *)state;
  28. }
  29. static struct PyModuleDef _structmodule;
  30. #define get_struct_state_structinst(self) \
  31. (get_struct_state(PyType_GetModuleByDef(Py_TYPE(self), &_structmodule)))
  32. #define get_struct_state_iterinst(self) \
  33. (get_struct_state(PyType_GetModule(Py_TYPE(self))))
  34. /* The translation function for each format character is table driven */
  35. typedef struct _formatdef {
  36. char format;
  37. Py_ssize_t size;
  38. Py_ssize_t alignment;
  39. PyObject* (*unpack)(_structmodulestate *, const char *,
  40. const struct _formatdef *);
  41. int (*pack)(_structmodulestate *, char *, PyObject *,
  42. const struct _formatdef *);
  43. } formatdef;
  44. typedef struct _formatcode {
  45. const struct _formatdef *fmtdef;
  46. Py_ssize_t offset;
  47. Py_ssize_t size;
  48. Py_ssize_t repeat;
  49. } formatcode;
  50. /* Struct object interface */
  51. typedef struct {
  52. PyObject_HEAD
  53. Py_ssize_t s_size;
  54. Py_ssize_t s_len;
  55. formatcode *s_codes;
  56. PyObject *s_format;
  57. PyObject *weakreflist; /* List of weak references */
  58. } PyStructObject;
  59. #define PyStruct_Check(op, state) PyObject_TypeCheck(op, (PyTypeObject *)(state)->PyStructType)
  60. /* Define various structs to figure out the alignments of types */
  61. typedef struct { char c; short x; } st_short;
  62. typedef struct { char c; int x; } st_int;
  63. typedef struct { char c; long x; } st_long;
  64. typedef struct { char c; float x; } st_float;
  65. typedef struct { char c; double x; } st_double;
  66. typedef struct { char c; void *x; } st_void_p;
  67. typedef struct { char c; size_t x; } st_size_t;
  68. typedef struct { char c; _Bool x; } st_bool;
  69. #define SHORT_ALIGN (sizeof(st_short) - sizeof(short))
  70. #define INT_ALIGN (sizeof(st_int) - sizeof(int))
  71. #define LONG_ALIGN (sizeof(st_long) - sizeof(long))
  72. #define FLOAT_ALIGN (sizeof(st_float) - sizeof(float))
  73. #define DOUBLE_ALIGN (sizeof(st_double) - sizeof(double))
  74. #define VOID_P_ALIGN (sizeof(st_void_p) - sizeof(void *))
  75. #define SIZE_T_ALIGN (sizeof(st_size_t) - sizeof(size_t))
  76. #define BOOL_ALIGN (sizeof(st_bool) - sizeof(_Bool))
  77. /* We can't support q and Q in native mode unless the compiler does;
  78. in std mode, they're 8 bytes on all platforms. */
  79. typedef struct { char c; long long x; } s_long_long;
  80. #define LONG_LONG_ALIGN (sizeof(s_long_long) - sizeof(long long))
  81. #ifdef __powerc
  82. #pragma options align=reset
  83. #endif
  84. /*[python input]
  85. class cache_struct_converter(CConverter):
  86. type = 'PyStructObject *'
  87. converter = 'cache_struct_converter'
  88. c_default = "NULL"
  89. def parse_arg(self, argname, displayname):
  90. return """
  91. if (!{converter}(module, {argname}, &{paramname})) {{{{
  92. goto exit;
  93. }}}}
  94. """.format(argname=argname, paramname=self.name,
  95. converter=self.converter)
  96. def cleanup(self):
  97. return "Py_XDECREF(%s);\n" % self.name
  98. [python start generated code]*/
  99. /*[python end generated code: output=da39a3ee5e6b4b0d input=d6746621c2fb1a7d]*/
  100. static int cache_struct_converter(PyObject *, PyObject *, PyStructObject **);
  101. #include "clinic/_struct.c.h"
  102. /* Helper for integer format codes: converts an arbitrary Python object to a
  103. PyLongObject if possible, otherwise fails. Caller should decref. */
  104. static PyObject *
  105. get_pylong(_structmodulestate *state, PyObject *v)
  106. {
  107. assert(v != NULL);
  108. if (!PyLong_Check(v)) {
  109. /* Not an integer; try to use __index__ to convert. */
  110. if (PyIndex_Check(v)) {
  111. v = _PyNumber_Index(v);
  112. if (v == NULL)
  113. return NULL;
  114. }
  115. else {
  116. PyErr_SetString(state->StructError,
  117. "required argument is not an integer");
  118. return NULL;
  119. }
  120. }
  121. else
  122. Py_INCREF(v);
  123. assert(PyLong_Check(v));
  124. return v;
  125. }
  126. /* Helper routine to get a C long and raise the appropriate error if it isn't
  127. one */
  128. static int
  129. get_long(_structmodulestate *state, PyObject *v, long *p)
  130. {
  131. long x;
  132. v = get_pylong(state, v);
  133. if (v == NULL)
  134. return -1;
  135. assert(PyLong_Check(v));
  136. x = PyLong_AsLong(v);
  137. Py_DECREF(v);
  138. if (x == (long)-1 && PyErr_Occurred()) {
  139. return -1;
  140. }
  141. *p = x;
  142. return 0;
  143. }
  144. /* Same, but handling unsigned long */
  145. static int
  146. get_ulong(_structmodulestate *state, PyObject *v, unsigned long *p)
  147. {
  148. unsigned long x;
  149. v = get_pylong(state, v);
  150. if (v == NULL)
  151. return -1;
  152. assert(PyLong_Check(v));
  153. x = PyLong_AsUnsignedLong(v);
  154. Py_DECREF(v);
  155. if (x == (unsigned long)-1 && PyErr_Occurred()) {
  156. return -1;
  157. }
  158. *p = x;
  159. return 0;
  160. }
  161. /* Same, but handling native long long. */
  162. static int
  163. get_longlong(_structmodulestate *state, PyObject *v, long long *p)
  164. {
  165. long long x;
  166. v = get_pylong(state, v);
  167. if (v == NULL)
  168. return -1;
  169. assert(PyLong_Check(v));
  170. x = PyLong_AsLongLong(v);
  171. Py_DECREF(v);
  172. if (x == (long long)-1 && PyErr_Occurred()) {
  173. return -1;
  174. }
  175. *p = x;
  176. return 0;
  177. }
  178. /* Same, but handling native unsigned long long. */
  179. static int
  180. get_ulonglong(_structmodulestate *state, PyObject *v, unsigned long long *p)
  181. {
  182. unsigned long long x;
  183. v = get_pylong(state, v);
  184. if (v == NULL)
  185. return -1;
  186. assert(PyLong_Check(v));
  187. x = PyLong_AsUnsignedLongLong(v);
  188. Py_DECREF(v);
  189. if (x == (unsigned long long)-1 && PyErr_Occurred()) {
  190. return -1;
  191. }
  192. *p = x;
  193. return 0;
  194. }
  195. /* Same, but handling Py_ssize_t */
  196. static int
  197. get_ssize_t(_structmodulestate *state, PyObject *v, Py_ssize_t *p)
  198. {
  199. Py_ssize_t x;
  200. v = get_pylong(state, v);
  201. if (v == NULL)
  202. return -1;
  203. assert(PyLong_Check(v));
  204. x = PyLong_AsSsize_t(v);
  205. Py_DECREF(v);
  206. if (x == (Py_ssize_t)-1 && PyErr_Occurred()) {
  207. return -1;
  208. }
  209. *p = x;
  210. return 0;
  211. }
  212. /* Same, but handling size_t */
  213. static int
  214. get_size_t(_structmodulestate *state, PyObject *v, size_t *p)
  215. {
  216. size_t x;
  217. v = get_pylong(state, v);
  218. if (v == NULL)
  219. return -1;
  220. assert(PyLong_Check(v));
  221. x = PyLong_AsSize_t(v);
  222. Py_DECREF(v);
  223. if (x == (size_t)-1 && PyErr_Occurred()) {
  224. return -1;
  225. }
  226. *p = x;
  227. return 0;
  228. }
  229. #define RANGE_ERROR(state, f, flag) return _range_error(state, f, flag)
  230. /* Floating-point helpers */
  231. static PyObject *
  232. unpack_halffloat(const char *p, /* start of 2-byte string */
  233. int le) /* true for little-endian, false for big-endian */
  234. {
  235. double x = PyFloat_Unpack2(p, le);
  236. if (x == -1.0 && PyErr_Occurred()) {
  237. return NULL;
  238. }
  239. return PyFloat_FromDouble(x);
  240. }
  241. static int
  242. pack_halffloat(_structmodulestate *state,
  243. char *p, /* start of 2-byte string */
  244. PyObject *v, /* value to pack */
  245. int le) /* true for little-endian, false for big-endian */
  246. {
  247. double x = PyFloat_AsDouble(v);
  248. if (x == -1.0 && PyErr_Occurred()) {
  249. PyErr_SetString(state->StructError,
  250. "required argument is not a float");
  251. return -1;
  252. }
  253. return PyFloat_Pack2(x, p, le);
  254. }
  255. static PyObject *
  256. unpack_float(const char *p, /* start of 4-byte string */
  257. int le) /* true for little-endian, false for big-endian */
  258. {
  259. double x;
  260. x = PyFloat_Unpack4(p, le);
  261. if (x == -1.0 && PyErr_Occurred())
  262. return NULL;
  263. return PyFloat_FromDouble(x);
  264. }
  265. static PyObject *
  266. unpack_double(const char *p, /* start of 8-byte string */
  267. int le) /* true for little-endian, false for big-endian */
  268. {
  269. double x;
  270. x = PyFloat_Unpack8(p, le);
  271. if (x == -1.0 && PyErr_Occurred())
  272. return NULL;
  273. return PyFloat_FromDouble(x);
  274. }
  275. /* Helper to format the range error exceptions */
  276. static int
  277. _range_error(_structmodulestate *state, const formatdef *f, int is_unsigned)
  278. {
  279. /* ulargest is the largest unsigned value with f->size bytes.
  280. * Note that the simpler:
  281. * ((size_t)1 << (f->size * 8)) - 1
  282. * doesn't work when f->size == sizeof(size_t) because C doesn't
  283. * define what happens when a left shift count is >= the number of
  284. * bits in the integer being shifted; e.g., on some boxes it doesn't
  285. * shift at all when they're equal.
  286. */
  287. const size_t ulargest = (size_t)-1 >> ((SIZEOF_SIZE_T - f->size)*8);
  288. assert(f->size >= 1 && f->size <= SIZEOF_SIZE_T);
  289. if (is_unsigned)
  290. PyErr_Format(state->StructError,
  291. "'%c' format requires 0 <= number <= %zu",
  292. f->format,
  293. ulargest);
  294. else {
  295. const Py_ssize_t largest = (Py_ssize_t)(ulargest >> 1);
  296. PyErr_Format(state->StructError,
  297. "'%c' format requires %zd <= number <= %zd",
  298. f->format,
  299. ~ largest,
  300. largest);
  301. }
  302. return -1;
  303. }
  304. /* A large number of small routines follow, with names of the form
  305. [bln][up]_TYPE
  306. [bln] distinguishes among big-endian, little-endian and native.
  307. [pu] distinguishes between pack (to struct) and unpack (from struct).
  308. TYPE is one of char, byte, ubyte, etc.
  309. */
  310. /* Native mode routines. ****************************************************/
  311. /* NOTE:
  312. In all n[up]_<type> routines handling types larger than 1 byte, there is
  313. *no* guarantee that the p pointer is properly aligned for each type,
  314. therefore memcpy is called. An intermediate variable is used to
  315. compensate for big-endian architectures.
  316. Normally both the intermediate variable and the memcpy call will be
  317. skipped by C optimisation in little-endian architectures (gcc >= 2.91
  318. does this). */
  319. static PyObject *
  320. nu_char(_structmodulestate *state, const char *p, const formatdef *f)
  321. {
  322. return PyBytes_FromStringAndSize(p, 1);
  323. }
  324. static PyObject *
  325. nu_byte(_structmodulestate *state, const char *p, const formatdef *f)
  326. {
  327. return PyLong_FromLong((long) *(signed char *)p);
  328. }
  329. static PyObject *
  330. nu_ubyte(_structmodulestate *state, const char *p, const formatdef *f)
  331. {
  332. return PyLong_FromLong((long) *(unsigned char *)p);
  333. }
  334. static PyObject *
  335. nu_short(_structmodulestate *state, const char *p, const formatdef *f)
  336. {
  337. short x;
  338. memcpy((char *)&x, p, sizeof x);
  339. return PyLong_FromLong((long)x);
  340. }
  341. static PyObject *
  342. nu_ushort(_structmodulestate *state, const char *p, const formatdef *f)
  343. {
  344. unsigned short x;
  345. memcpy((char *)&x, p, sizeof x);
  346. return PyLong_FromLong((long)x);
  347. }
  348. static PyObject *
  349. nu_int(_structmodulestate *state, const char *p, const formatdef *f)
  350. {
  351. int x;
  352. memcpy((char *)&x, p, sizeof x);
  353. return PyLong_FromLong((long)x);
  354. }
  355. static PyObject *
  356. nu_uint(_structmodulestate *state, const char *p, const formatdef *f)
  357. {
  358. unsigned int x;
  359. memcpy((char *)&x, p, sizeof x);
  360. return PyLong_FromUnsignedLong((unsigned long)x);
  361. }
  362. static PyObject *
  363. nu_long(_structmodulestate *state, const char *p, const formatdef *f)
  364. {
  365. long x;
  366. memcpy((char *)&x, p, sizeof x);
  367. return PyLong_FromLong(x);
  368. }
  369. static PyObject *
  370. nu_ulong(_structmodulestate *state, const char *p, const formatdef *f)
  371. {
  372. unsigned long x;
  373. memcpy((char *)&x, p, sizeof x);
  374. return PyLong_FromUnsignedLong(x);
  375. }
  376. static PyObject *
  377. nu_ssize_t(_structmodulestate *state, const char *p, const formatdef *f)
  378. {
  379. Py_ssize_t x;
  380. memcpy((char *)&x, p, sizeof x);
  381. return PyLong_FromSsize_t(x);
  382. }
  383. static PyObject *
  384. nu_size_t(_structmodulestate *state, const char *p, const formatdef *f)
  385. {
  386. size_t x;
  387. memcpy((char *)&x, p, sizeof x);
  388. return PyLong_FromSize_t(x);
  389. }
  390. static PyObject *
  391. nu_longlong(_structmodulestate *state, const char *p, const formatdef *f)
  392. {
  393. long long x;
  394. memcpy((char *)&x, p, sizeof x);
  395. return PyLong_FromLongLong(x);
  396. }
  397. static PyObject *
  398. nu_ulonglong(_structmodulestate *state, const char *p, const formatdef *f)
  399. {
  400. unsigned long long x;
  401. memcpy((char *)&x, p, sizeof x);
  402. return PyLong_FromUnsignedLongLong(x);
  403. }
  404. static PyObject *
  405. nu_bool(_structmodulestate *state, const char *p, const formatdef *f)
  406. {
  407. _Bool x;
  408. memcpy((char *)&x, p, sizeof x);
  409. return PyBool_FromLong(x != 0);
  410. }
  411. static PyObject *
  412. nu_halffloat(_structmodulestate *state, const char *p, const formatdef *f)
  413. {
  414. #if PY_LITTLE_ENDIAN
  415. return unpack_halffloat(p, 1);
  416. #else
  417. return unpack_halffloat(p, 0);
  418. #endif
  419. }
  420. static PyObject *
  421. nu_float(_structmodulestate *state, const char *p, const formatdef *f)
  422. {
  423. float x;
  424. memcpy((char *)&x, p, sizeof x);
  425. return PyFloat_FromDouble((double)x);
  426. }
  427. static PyObject *
  428. nu_double(_structmodulestate *state, const char *p, const formatdef *f)
  429. {
  430. double x;
  431. memcpy((char *)&x, p, sizeof x);
  432. return PyFloat_FromDouble(x);
  433. }
  434. static PyObject *
  435. nu_void_p(_structmodulestate *state, const char *p, const formatdef *f)
  436. {
  437. void *x;
  438. memcpy((char *)&x, p, sizeof x);
  439. return PyLong_FromVoidPtr(x);
  440. }
  441. static int
  442. np_byte(_structmodulestate *state, char *p, PyObject *v, const formatdef *f)
  443. {
  444. long x;
  445. if (get_long(state, v, &x) < 0) {
  446. if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
  447. RANGE_ERROR(state, f, 0);
  448. }
  449. return -1;
  450. }
  451. if (x < -128 || x > 127) {
  452. RANGE_ERROR(state, f, 0);
  453. }
  454. *p = (char)x;
  455. return 0;
  456. }
  457. static int
  458. np_ubyte(_structmodulestate *state, char *p, PyObject *v, const formatdef *f)
  459. {
  460. long x;
  461. if (get_long(state, v, &x) < 0) {
  462. if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
  463. RANGE_ERROR(state, f, 1);
  464. }
  465. return -1;
  466. }
  467. if (x < 0 || x > 255) {
  468. RANGE_ERROR(state, f, 1);
  469. }
  470. *(unsigned char *)p = (unsigned char)x;
  471. return 0;
  472. }
  473. static int
  474. np_char(_structmodulestate *state, char *p, PyObject *v, const formatdef *f)
  475. {
  476. if (!PyBytes_Check(v) || PyBytes_Size(v) != 1) {
  477. PyErr_SetString(state->StructError,
  478. "char format requires a bytes object of length 1");
  479. return -1;
  480. }
  481. *p = *PyBytes_AS_STRING(v);
  482. return 0;
  483. }
  484. static int
  485. np_short(_structmodulestate *state, char *p, PyObject *v, const formatdef *f)
  486. {
  487. long x;
  488. short y;
  489. if (get_long(state, v, &x) < 0) {
  490. if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
  491. RANGE_ERROR(state, f, 0);
  492. }
  493. return -1;
  494. }
  495. if (x < SHRT_MIN || x > SHRT_MAX) {
  496. RANGE_ERROR(state, f, 0);
  497. }
  498. y = (short)x;
  499. memcpy(p, (char *)&y, sizeof y);
  500. return 0;
  501. }
  502. static int
  503. np_ushort(_structmodulestate *state, char *p, PyObject *v, const formatdef *f)
  504. {
  505. long x;
  506. unsigned short y;
  507. if (get_long(state, v, &x) < 0) {
  508. if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
  509. RANGE_ERROR(state, f, 1);
  510. }
  511. return -1;
  512. }
  513. if (x < 0 || x > USHRT_MAX) {
  514. RANGE_ERROR(state, f, 1);
  515. }
  516. y = (unsigned short)x;
  517. memcpy(p, (char *)&y, sizeof y);
  518. return 0;
  519. }
  520. static int
  521. np_int(_structmodulestate *state, char *p, PyObject *v, const formatdef *f)
  522. {
  523. long x;
  524. int y;
  525. if (get_long(state, v, &x) < 0) {
  526. if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
  527. RANGE_ERROR(state, f, 0);
  528. }
  529. return -1;
  530. }
  531. #if (SIZEOF_LONG > SIZEOF_INT)
  532. if ((x < ((long)INT_MIN)) || (x > ((long)INT_MAX)))
  533. RANGE_ERROR(state, f, 0);
  534. #endif
  535. y = (int)x;
  536. memcpy(p, (char *)&y, sizeof y);
  537. return 0;
  538. }
  539. static int
  540. np_uint(_structmodulestate *state, char *p, PyObject *v, const formatdef *f)
  541. {
  542. unsigned long x;
  543. unsigned int y;
  544. if (get_ulong(state, v, &x) < 0) {
  545. if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
  546. RANGE_ERROR(state, f, 1);
  547. }
  548. return -1;
  549. }
  550. y = (unsigned int)x;
  551. #if (SIZEOF_LONG > SIZEOF_INT)
  552. if (x > ((unsigned long)UINT_MAX))
  553. RANGE_ERROR(state, f, 1);
  554. #endif
  555. memcpy(p, (char *)&y, sizeof y);
  556. return 0;
  557. }
  558. static int
  559. np_long(_structmodulestate *state, char *p, PyObject *v, const formatdef *f)
  560. {
  561. long x;
  562. if (get_long(state, v, &x) < 0) {
  563. if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
  564. RANGE_ERROR(state, f, 0);
  565. }
  566. return -1;
  567. }
  568. memcpy(p, (char *)&x, sizeof x);
  569. return 0;
  570. }
  571. static int
  572. np_ulong(_structmodulestate *state, char *p, PyObject *v, const formatdef *f)
  573. {
  574. unsigned long x;
  575. if (get_ulong(state, v, &x) < 0) {
  576. if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
  577. RANGE_ERROR(state, f, 1);
  578. }
  579. return -1;
  580. }
  581. memcpy(p, (char *)&x, sizeof x);
  582. return 0;
  583. }
  584. static int
  585. np_ssize_t(_structmodulestate *state, char *p, PyObject *v, const formatdef *f)
  586. {
  587. Py_ssize_t x;
  588. if (get_ssize_t(state, v, &x) < 0) {
  589. if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
  590. RANGE_ERROR(state, f, 0);
  591. }
  592. return -1;
  593. }
  594. memcpy(p, (char *)&x, sizeof x);
  595. return 0;
  596. }
  597. static int
  598. np_size_t(_structmodulestate *state, char *p, PyObject *v, const formatdef *f)
  599. {
  600. size_t x;
  601. if (get_size_t(state, v, &x) < 0) {
  602. if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
  603. RANGE_ERROR(state, f, 1);
  604. }
  605. return -1;
  606. }
  607. memcpy(p, (char *)&x, sizeof x);
  608. return 0;
  609. }
  610. static int
  611. np_longlong(_structmodulestate *state, char *p, PyObject *v, const formatdef *f)
  612. {
  613. long long x;
  614. if (get_longlong(state, v, &x) < 0) {
  615. if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
  616. PyErr_Format(state->StructError,
  617. "'%c' format requires %lld <= number <= %lld",
  618. f->format,
  619. LLONG_MIN,
  620. LLONG_MAX);
  621. }
  622. return -1;
  623. }
  624. memcpy(p, (char *)&x, sizeof x);
  625. return 0;
  626. }
  627. static int
  628. np_ulonglong(_structmodulestate *state, char *p, PyObject *v, const formatdef *f)
  629. {
  630. unsigned long long x;
  631. if (get_ulonglong(state, v, &x) < 0) {
  632. if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
  633. PyErr_Format(state->StructError,
  634. "'%c' format requires 0 <= number <= %llu",
  635. f->format,
  636. ULLONG_MAX);
  637. }
  638. return -1;
  639. }
  640. memcpy(p, (char *)&x, sizeof x);
  641. return 0;
  642. }
  643. static int
  644. np_bool(_structmodulestate *state, char *p, PyObject *v, const formatdef *f)
  645. {
  646. int y;
  647. _Bool x;
  648. y = PyObject_IsTrue(v);
  649. if (y < 0)
  650. return -1;
  651. x = y;
  652. memcpy(p, (char *)&x, sizeof x);
  653. return 0;
  654. }
  655. static int
  656. np_halffloat(_structmodulestate *state, char *p, PyObject *v, const formatdef *f)
  657. {
  658. #if PY_LITTLE_ENDIAN
  659. return pack_halffloat(state, p, v, 1);
  660. #else
  661. return pack_halffloat(state, p, v, 0);
  662. #endif
  663. }
  664. static int
  665. np_float(_structmodulestate *state, char *p, PyObject *v, const formatdef *f)
  666. {
  667. float x = (float)PyFloat_AsDouble(v);
  668. if (x == -1 && PyErr_Occurred()) {
  669. PyErr_SetString(state->StructError,
  670. "required argument is not a float");
  671. return -1;
  672. }
  673. memcpy(p, (char *)&x, sizeof x);
  674. return 0;
  675. }
  676. static int
  677. np_double(_structmodulestate *state, char *p, PyObject *v, const formatdef *f)
  678. {
  679. double x = PyFloat_AsDouble(v);
  680. if (x == -1 && PyErr_Occurred()) {
  681. PyErr_SetString(state->StructError,
  682. "required argument is not a float");
  683. return -1;
  684. }
  685. memcpy(p, (char *)&x, sizeof(double));
  686. return 0;
  687. }
  688. static int
  689. np_void_p(_structmodulestate *state, char *p, PyObject *v, const formatdef *f)
  690. {
  691. void *x;
  692. v = get_pylong(state, v);
  693. if (v == NULL)
  694. return -1;
  695. assert(PyLong_Check(v));
  696. x = PyLong_AsVoidPtr(v);
  697. Py_DECREF(v);
  698. if (x == NULL && PyErr_Occurred())
  699. return -1;
  700. memcpy(p, (char *)&x, sizeof x);
  701. return 0;
  702. }
  703. static const formatdef native_table[] = {
  704. {'x', sizeof(char), 0, NULL},
  705. {'b', sizeof(char), 0, nu_byte, np_byte},
  706. {'B', sizeof(char), 0, nu_ubyte, np_ubyte},
  707. {'c', sizeof(char), 0, nu_char, np_char},
  708. {'s', sizeof(char), 0, NULL},
  709. {'p', sizeof(char), 0, NULL},
  710. {'h', sizeof(short), SHORT_ALIGN, nu_short, np_short},
  711. {'H', sizeof(short), SHORT_ALIGN, nu_ushort, np_ushort},
  712. {'i', sizeof(int), INT_ALIGN, nu_int, np_int},
  713. {'I', sizeof(int), INT_ALIGN, nu_uint, np_uint},
  714. {'l', sizeof(long), LONG_ALIGN, nu_long, np_long},
  715. {'L', sizeof(long), LONG_ALIGN, nu_ulong, np_ulong},
  716. {'n', sizeof(size_t), SIZE_T_ALIGN, nu_ssize_t, np_ssize_t},
  717. {'N', sizeof(size_t), SIZE_T_ALIGN, nu_size_t, np_size_t},
  718. {'q', sizeof(long long), LONG_LONG_ALIGN, nu_longlong, np_longlong},
  719. {'Q', sizeof(long long), LONG_LONG_ALIGN, nu_ulonglong,np_ulonglong},
  720. {'?', sizeof(_Bool), BOOL_ALIGN, nu_bool, np_bool},
  721. {'e', sizeof(short), SHORT_ALIGN, nu_halffloat, np_halffloat},
  722. {'f', sizeof(float), FLOAT_ALIGN, nu_float, np_float},
  723. {'d', sizeof(double), DOUBLE_ALIGN, nu_double, np_double},
  724. {'P', sizeof(void *), VOID_P_ALIGN, nu_void_p, np_void_p},
  725. {0}
  726. };
  727. /* Big-endian routines. *****************************************************/
  728. static PyObject *
  729. bu_short(_structmodulestate *state, const char *p, const formatdef *f)
  730. {
  731. unsigned long x = 0;
  732. /* This function is only ever used in the case f->size == 2. */
  733. assert(f->size == 2);
  734. Py_ssize_t i = 2;
  735. const unsigned char *bytes = (const unsigned char *)p;
  736. do {
  737. x = (x<<8) | *bytes++;
  738. } while (--i > 0);
  739. /* Extend sign, avoiding implementation-defined or undefined behaviour. */
  740. x = (x ^ 0x8000U) - 0x8000U;
  741. return PyLong_FromLong(x & 0x8000U ? -1 - (long)(~x) : (long)x);
  742. }
  743. static PyObject *
  744. bu_int(_structmodulestate *state, const char *p, const formatdef *f)
  745. {
  746. unsigned long x = 0;
  747. /* This function is only ever used in the case f->size == 4. */
  748. assert(f->size == 4);
  749. Py_ssize_t i = 4;
  750. const unsigned char *bytes = (const unsigned char *)p;
  751. do {
  752. x = (x<<8) | *bytes++;
  753. } while (--i > 0);
  754. /* Extend sign, avoiding implementation-defined or undefined behaviour. */
  755. x = (x ^ 0x80000000U) - 0x80000000U;
  756. return PyLong_FromLong(x & 0x80000000U ? -1 - (long)(~x) : (long)x);
  757. }
  758. static PyObject *
  759. bu_uint(_structmodulestate *state, const char *p, const formatdef *f)
  760. {
  761. unsigned long x = 0;
  762. Py_ssize_t i = f->size;
  763. const unsigned char *bytes = (const unsigned char *)p;
  764. do {
  765. x = (x<<8) | *bytes++;
  766. } while (--i > 0);
  767. return PyLong_FromUnsignedLong(x);
  768. }
  769. static PyObject *
  770. bu_longlong(_structmodulestate *state, const char *p, const formatdef *f)
  771. {
  772. unsigned long long x = 0;
  773. /* This function is only ever used in the case f->size == 8. */
  774. assert(f->size == 8);
  775. Py_ssize_t i = 8;
  776. const unsigned char *bytes = (const unsigned char *)p;
  777. do {
  778. x = (x<<8) | *bytes++;
  779. } while (--i > 0);
  780. /* Extend sign, avoiding implementation-defined or undefined behaviour. */
  781. x = (x ^ 0x8000000000000000U) - 0x8000000000000000U;
  782. return PyLong_FromLongLong(
  783. x & 0x8000000000000000U ? -1 - (long long)(~x) : (long long)x);
  784. }
  785. static PyObject *
  786. bu_ulonglong(_structmodulestate *state, const char *p, const formatdef *f)
  787. {
  788. unsigned long long x = 0;
  789. Py_ssize_t i = f->size;
  790. const unsigned char *bytes = (const unsigned char *)p;
  791. do {
  792. x = (x<<8) | *bytes++;
  793. } while (--i > 0);
  794. return PyLong_FromUnsignedLongLong(x);
  795. }
  796. static PyObject *
  797. bu_halffloat(_structmodulestate *state, const char *p, const formatdef *f)
  798. {
  799. return unpack_halffloat(p, 0);
  800. }
  801. static PyObject *
  802. bu_float(_structmodulestate *state, const char *p, const formatdef *f)
  803. {
  804. return unpack_float(p, 0);
  805. }
  806. static PyObject *
  807. bu_double(_structmodulestate *state, const char *p, const formatdef *f)
  808. {
  809. return unpack_double(p, 0);
  810. }
  811. static PyObject *
  812. bu_bool(_structmodulestate *state, const char *p, const formatdef *f)
  813. {
  814. return PyBool_FromLong(*p != 0);
  815. }
  816. static int
  817. bp_int(_structmodulestate *state, char *p, PyObject *v, const formatdef *f)
  818. {
  819. long x;
  820. Py_ssize_t i;
  821. unsigned char *q = (unsigned char *)p;
  822. if (get_long(state, v, &x) < 0) {
  823. if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
  824. RANGE_ERROR(state, f, 0);
  825. }
  826. return -1;
  827. }
  828. i = f->size;
  829. if (i != SIZEOF_LONG) {
  830. if ((i == 2) && (x < -32768 || x > 32767))
  831. RANGE_ERROR(state, f, 0);
  832. #if (SIZEOF_LONG != 4)
  833. else if ((i == 4) && (x < -2147483648L || x > 2147483647L))
  834. RANGE_ERROR(state, f, 0);
  835. #endif
  836. }
  837. do {
  838. q[--i] = (unsigned char)(x & 0xffL);
  839. x >>= 8;
  840. } while (i > 0);
  841. return 0;
  842. }
  843. static int
  844. bp_uint(_structmodulestate *state, char *p, PyObject *v, const formatdef *f)
  845. {
  846. unsigned long x;
  847. Py_ssize_t i;
  848. unsigned char *q = (unsigned char *)p;
  849. if (get_ulong(state, v, &x) < 0) {
  850. if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
  851. RANGE_ERROR(state, f, 1);
  852. }
  853. return -1;
  854. }
  855. i = f->size;
  856. if (i != SIZEOF_LONG) {
  857. unsigned long maxint = 1;
  858. maxint <<= (unsigned long)(i * 8);
  859. if (x >= maxint)
  860. RANGE_ERROR(state, f, 1);
  861. }
  862. do {
  863. q[--i] = (unsigned char)(x & 0xffUL);
  864. x >>= 8;
  865. } while (i > 0);
  866. return 0;
  867. }
  868. static int
  869. bp_longlong(_structmodulestate *state, char *p, PyObject *v, const formatdef *f)
  870. {
  871. int res;
  872. v = get_pylong(state, v);
  873. if (v == NULL)
  874. return -1;
  875. res = _PyLong_AsByteArray((PyLongObject *)v,
  876. (unsigned char *)p,
  877. 8,
  878. 0, /* little_endian */
  879. 1 /* signed */);
  880. Py_DECREF(v);
  881. if (res == -1 && PyErr_Occurred()) {
  882. PyErr_Format(state->StructError,
  883. "'%c' format requires %lld <= number <= %lld",
  884. f->format,
  885. LLONG_MIN,
  886. LLONG_MAX);
  887. return -1;
  888. }
  889. return res;
  890. }
  891. static int
  892. bp_ulonglong(_structmodulestate *state, char *p, PyObject *v, const formatdef *f)
  893. {
  894. int res;
  895. v = get_pylong(state, v);
  896. if (v == NULL)
  897. return -1;
  898. res = _PyLong_AsByteArray((PyLongObject *)v,
  899. (unsigned char *)p,
  900. 8,
  901. 0, /* little_endian */
  902. 0 /* signed */);
  903. Py_DECREF(v);
  904. if (res == -1 && PyErr_Occurred()) {
  905. PyErr_Format(state->StructError,
  906. "'%c' format requires 0 <= number <= %llu",
  907. f->format,
  908. ULLONG_MAX);
  909. return -1;
  910. }
  911. return res;
  912. }
  913. static int
  914. bp_halffloat(_structmodulestate *state, char *p, PyObject *v, const formatdef *f)
  915. {
  916. return pack_halffloat(state, p, v, 0);
  917. }
  918. static int
  919. bp_float(_structmodulestate *state, char *p, PyObject *v, const formatdef *f)
  920. {
  921. double x = PyFloat_AsDouble(v);
  922. if (x == -1 && PyErr_Occurred()) {
  923. PyErr_SetString(state->StructError,
  924. "required argument is not a float");
  925. return -1;
  926. }
  927. return PyFloat_Pack4(x, p, 0);
  928. }
  929. static int
  930. bp_double(_structmodulestate *state, char *p, PyObject *v, const formatdef *f)
  931. {
  932. double x = PyFloat_AsDouble(v);
  933. if (x == -1 && PyErr_Occurred()) {
  934. PyErr_SetString(state->StructError,
  935. "required argument is not a float");
  936. return -1;
  937. }
  938. return PyFloat_Pack8(x, p, 0);
  939. }
  940. static int
  941. bp_bool(_structmodulestate *state, char *p, PyObject *v, const formatdef *f)
  942. {
  943. int y;
  944. y = PyObject_IsTrue(v);
  945. if (y < 0)
  946. return -1;
  947. *p = (char)y;
  948. return 0;
  949. }
  950. static formatdef bigendian_table[] = {
  951. {'x', 1, 0, NULL},
  952. {'b', 1, 0, nu_byte, np_byte},
  953. {'B', 1, 0, nu_ubyte, np_ubyte},
  954. {'c', 1, 0, nu_char, np_char},
  955. {'s', 1, 0, NULL},
  956. {'p', 1, 0, NULL},
  957. {'h', 2, 0, bu_short, bp_int},
  958. {'H', 2, 0, bu_uint, bp_uint},
  959. {'i', 4, 0, bu_int, bp_int},
  960. {'I', 4, 0, bu_uint, bp_uint},
  961. {'l', 4, 0, bu_int, bp_int},
  962. {'L', 4, 0, bu_uint, bp_uint},
  963. {'q', 8, 0, bu_longlong, bp_longlong},
  964. {'Q', 8, 0, bu_ulonglong, bp_ulonglong},
  965. {'?', 1, 0, bu_bool, bp_bool},
  966. {'e', 2, 0, bu_halffloat, bp_halffloat},
  967. {'f', 4, 0, bu_float, bp_float},
  968. {'d', 8, 0, bu_double, bp_double},
  969. {0}
  970. };
  971. /* Little-endian routines. *****************************************************/
  972. static PyObject *
  973. lu_short(_structmodulestate *state, const char *p, const formatdef *f)
  974. {
  975. unsigned long x = 0;
  976. /* This function is only ever used in the case f->size == 2. */
  977. assert(f->size == 2);
  978. Py_ssize_t i = 2;
  979. const unsigned char *bytes = (const unsigned char *)p;
  980. do {
  981. x = (x<<8) | bytes[--i];
  982. } while (i > 0);
  983. /* Extend sign, avoiding implementation-defined or undefined behaviour. */
  984. x = (x ^ 0x8000U) - 0x8000U;
  985. return PyLong_FromLong(x & 0x8000U ? -1 - (long)(~x) : (long)x);
  986. }
  987. static PyObject *
  988. lu_int(_structmodulestate *state, const char *p, const formatdef *f)
  989. {
  990. unsigned long x = 0;
  991. /* This function is only ever used in the case f->size == 4. */
  992. assert(f->size == 4);
  993. Py_ssize_t i = 4;
  994. const unsigned char *bytes = (const unsigned char *)p;
  995. do {
  996. x = (x<<8) | bytes[--i];
  997. } while (i > 0);
  998. /* Extend sign, avoiding implementation-defined or undefined behaviour. */
  999. x = (x ^ 0x80000000U) - 0x80000000U;
  1000. return PyLong_FromLong(x & 0x80000000U ? -1 - (long)(~x) : (long)x);
  1001. }
  1002. static PyObject *
  1003. lu_uint(_structmodulestate *state, const char *p, const formatdef *f)
  1004. {
  1005. unsigned long x = 0;
  1006. Py_ssize_t i = f->size;
  1007. const unsigned char *bytes = (const unsigned char *)p;
  1008. do {
  1009. x = (x<<8) | bytes[--i];
  1010. } while (i > 0);
  1011. return PyLong_FromUnsignedLong(x);
  1012. }
  1013. static PyObject *
  1014. lu_longlong(_structmodulestate *state, const char *p, const formatdef *f)
  1015. {
  1016. unsigned long long x = 0;
  1017. /* This function is only ever used in the case f->size == 8. */
  1018. assert(f->size == 8);
  1019. Py_ssize_t i = 8;
  1020. const unsigned char *bytes = (const unsigned char *)p;
  1021. do {
  1022. x = (x<<8) | bytes[--i];
  1023. } while (i > 0);
  1024. /* Extend sign, avoiding implementation-defined or undefined behaviour. */
  1025. x = (x ^ 0x8000000000000000U) - 0x8000000000000000U;
  1026. return PyLong_FromLongLong(
  1027. x & 0x8000000000000000U ? -1 - (long long)(~x) : (long long)x);
  1028. }
  1029. static PyObject *
  1030. lu_ulonglong(_structmodulestate *state, const char *p, const formatdef *f)
  1031. {
  1032. unsigned long long x = 0;
  1033. Py_ssize_t i = f->size;
  1034. const unsigned char *bytes = (const unsigned char *)p;
  1035. do {
  1036. x = (x<<8) | bytes[--i];
  1037. } while (i > 0);
  1038. return PyLong_FromUnsignedLongLong(x);
  1039. }
  1040. static PyObject *
  1041. lu_halffloat(_structmodulestate *state, const char *p, const formatdef *f)
  1042. {
  1043. return unpack_halffloat(p, 1);
  1044. }
  1045. static PyObject *
  1046. lu_float(_structmodulestate *state, const char *p, const formatdef *f)
  1047. {
  1048. return unpack_float(p, 1);
  1049. }
  1050. static PyObject *
  1051. lu_double(_structmodulestate *state, const char *p, const formatdef *f)
  1052. {
  1053. return unpack_double(p, 1);
  1054. }
  1055. static int
  1056. lp_int(_structmodulestate *state, char *p, PyObject *v, const formatdef *f)
  1057. {
  1058. long x;
  1059. Py_ssize_t i;
  1060. unsigned char *q = (unsigned char *)p;
  1061. if (get_long(state, v, &x) < 0) {
  1062. if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
  1063. RANGE_ERROR(state, f, 0);
  1064. }
  1065. return -1;
  1066. }
  1067. i = f->size;
  1068. if (i != SIZEOF_LONG) {
  1069. if ((i == 2) && (x < -32768 || x > 32767))
  1070. RANGE_ERROR(state, f, 0);
  1071. #if (SIZEOF_LONG != 4)
  1072. else if ((i == 4) && (x < -2147483648L || x > 2147483647L))
  1073. RANGE_ERROR(state, f, 0);
  1074. #endif
  1075. }
  1076. do {
  1077. *q++ = (unsigned char)(x & 0xffL);
  1078. x >>= 8;
  1079. } while (--i > 0);
  1080. return 0;
  1081. }
  1082. static int
  1083. lp_uint(_structmodulestate *state, char *p, PyObject *v, const formatdef *f)
  1084. {
  1085. unsigned long x;
  1086. Py_ssize_t i;
  1087. unsigned char *q = (unsigned char *)p;
  1088. if (get_ulong(state, v, &x) < 0) {
  1089. if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
  1090. RANGE_ERROR(state, f, 1);
  1091. }
  1092. return -1;
  1093. }
  1094. i = f->size;
  1095. if (i != SIZEOF_LONG) {
  1096. unsigned long maxint = 1;
  1097. maxint <<= (unsigned long)(i * 8);
  1098. if (x >= maxint)
  1099. RANGE_ERROR(state, f, 1);
  1100. }
  1101. do {
  1102. *q++ = (unsigned char)(x & 0xffUL);
  1103. x >>= 8;
  1104. } while (--i > 0);
  1105. return 0;
  1106. }
  1107. static int
  1108. lp_longlong(_structmodulestate *state, char *p, PyObject *v, const formatdef *f)
  1109. {
  1110. int res;
  1111. v = get_pylong(state, v);
  1112. if (v == NULL)
  1113. return -1;
  1114. res = _PyLong_AsByteArray((PyLongObject*)v,
  1115. (unsigned char *)p,
  1116. 8,
  1117. 1, /* little_endian */
  1118. 1 /* signed */);
  1119. Py_DECREF(v);
  1120. if (res == -1 && PyErr_Occurred()) {
  1121. PyErr_Format(state->StructError,
  1122. "'%c' format requires %lld <= number <= %lld",
  1123. f->format,
  1124. LLONG_MIN,
  1125. LLONG_MAX);
  1126. return -1;
  1127. }
  1128. return res;
  1129. }
  1130. static int
  1131. lp_ulonglong(_structmodulestate *state, char *p, PyObject *v, const formatdef *f)
  1132. {
  1133. int res;
  1134. v = get_pylong(state, v);
  1135. if (v == NULL)
  1136. return -1;
  1137. res = _PyLong_AsByteArray((PyLongObject*)v,
  1138. (unsigned char *)p,
  1139. 8,
  1140. 1, /* little_endian */
  1141. 0 /* signed */);
  1142. Py_DECREF(v);
  1143. if (res == -1 && PyErr_Occurred()) {
  1144. PyErr_Format(state->StructError,
  1145. "'%c' format requires 0 <= number <= %llu",
  1146. f->format,
  1147. ULLONG_MAX);
  1148. return -1;
  1149. }
  1150. return res;
  1151. }
  1152. static int
  1153. lp_halffloat(_structmodulestate *state, char *p, PyObject *v, const formatdef *f)
  1154. {
  1155. return pack_halffloat(state, p, v, 1);
  1156. }
  1157. static int
  1158. lp_float(_structmodulestate *state, char *p, PyObject *v, const formatdef *f)
  1159. {
  1160. double x = PyFloat_AsDouble(v);
  1161. if (x == -1 && PyErr_Occurred()) {
  1162. PyErr_SetString(state->StructError,
  1163. "required argument is not a float");
  1164. return -1;
  1165. }
  1166. return PyFloat_Pack4(x, p, 1);
  1167. }
  1168. static int
  1169. lp_double(_structmodulestate *state, char *p, PyObject *v, const formatdef *f)
  1170. {
  1171. double x = PyFloat_AsDouble(v);
  1172. if (x == -1 && PyErr_Occurred()) {
  1173. PyErr_SetString(state->StructError,
  1174. "required argument is not a float");
  1175. return -1;
  1176. }
  1177. return PyFloat_Pack8(x, p, 1);
  1178. }
  1179. static formatdef lilendian_table[] = {
  1180. {'x', 1, 0, NULL},
  1181. {'b', 1, 0, nu_byte, np_byte},
  1182. {'B', 1, 0, nu_ubyte, np_ubyte},
  1183. {'c', 1, 0, nu_char, np_char},
  1184. {'s', 1, 0, NULL},
  1185. {'p', 1, 0, NULL},
  1186. {'h', 2, 0, lu_short, lp_int},
  1187. {'H', 2, 0, lu_uint, lp_uint},
  1188. {'i', 4, 0, lu_int, lp_int},
  1189. {'I', 4, 0, lu_uint, lp_uint},
  1190. {'l', 4, 0, lu_int, lp_int},
  1191. {'L', 4, 0, lu_uint, lp_uint},
  1192. {'q', 8, 0, lu_longlong, lp_longlong},
  1193. {'Q', 8, 0, lu_ulonglong, lp_ulonglong},
  1194. {'?', 1, 0, bu_bool, bp_bool}, /* Std rep not endian dep,
  1195. but potentially different from native rep -- reuse bx_bool funcs. */
  1196. {'e', 2, 0, lu_halffloat, lp_halffloat},
  1197. {'f', 4, 0, lu_float, lp_float},
  1198. {'d', 8, 0, lu_double, lp_double},
  1199. {0}
  1200. };
  1201. static const formatdef *
  1202. whichtable(const char **pfmt)
  1203. {
  1204. const char *fmt = (*pfmt)++; /* May be backed out of later */
  1205. switch (*fmt) {
  1206. case '<':
  1207. return lilendian_table;
  1208. case '>':
  1209. case '!': /* Network byte order is big-endian */
  1210. return bigendian_table;
  1211. case '=': { /* Host byte order -- different from native in alignment! */
  1212. #if PY_LITTLE_ENDIAN
  1213. return lilendian_table;
  1214. #else
  1215. return bigendian_table;
  1216. #endif
  1217. }
  1218. default:
  1219. --*pfmt; /* Back out of pointer increment */
  1220. /* Fall through */
  1221. case '@':
  1222. return native_table;
  1223. }
  1224. }
  1225. /* Get the table entry for a format code */
  1226. static const formatdef *
  1227. getentry(_structmodulestate *state, int c, const formatdef *f)
  1228. {
  1229. for (; f->format != '\0'; f++) {
  1230. if (f->format == c) {
  1231. return f;
  1232. }
  1233. }
  1234. PyErr_SetString(state->StructError, "bad char in struct format");
  1235. return NULL;
  1236. }
  1237. /* Align a size according to a format code. Return -1 on overflow. */
  1238. static Py_ssize_t
  1239. align(Py_ssize_t size, char c, const formatdef *e)
  1240. {
  1241. Py_ssize_t extra;
  1242. if (e->format == c) {
  1243. if (e->alignment && size > 0) {
  1244. extra = (e->alignment - 1) - (size - 1) % (e->alignment);
  1245. if (extra > PY_SSIZE_T_MAX - size)
  1246. return -1;
  1247. size += extra;
  1248. }
  1249. }
  1250. return size;
  1251. }
  1252. /*
  1253. * Struct object implementation.
  1254. */
  1255. /* calculate the size of a format string */
  1256. static int
  1257. prepare_s(PyStructObject *self)
  1258. {
  1259. const formatdef *f;
  1260. const formatdef *e;
  1261. formatcode *codes;
  1262. const char *s;
  1263. const char *fmt;
  1264. char c;
  1265. Py_ssize_t size, len, num, itemsize;
  1266. size_t ncodes;
  1267. _structmodulestate *state = get_struct_state_structinst(self);
  1268. fmt = PyBytes_AS_STRING(self->s_format);
  1269. if (strlen(fmt) != (size_t)PyBytes_GET_SIZE(self->s_format)) {
  1270. PyErr_SetString(state->StructError,
  1271. "embedded null character");
  1272. return -1;
  1273. }
  1274. f = whichtable(&fmt);
  1275. s = fmt;
  1276. size = 0;
  1277. len = 0;
  1278. ncodes = 0;
  1279. while ((c = *s++) != '\0') {
  1280. if (Py_ISSPACE(c))
  1281. continue;
  1282. if ('0' <= c && c <= '9') {
  1283. num = c - '0';
  1284. while ('0' <= (c = *s++) && c <= '9') {
  1285. /* overflow-safe version of
  1286. if (num*10 + (c - '0') > PY_SSIZE_T_MAX) { ... } */
  1287. if (num >= PY_SSIZE_T_MAX / 10 && (
  1288. num > PY_SSIZE_T_MAX / 10 ||
  1289. (c - '0') > PY_SSIZE_T_MAX % 10))
  1290. goto overflow;
  1291. num = num*10 + (c - '0');
  1292. }
  1293. if (c == '\0') {
  1294. PyErr_SetString(state->StructError,
  1295. "repeat count given without format specifier");
  1296. return -1;
  1297. }
  1298. }
  1299. else
  1300. num = 1;
  1301. e = getentry(state, c, f);
  1302. if (e == NULL)
  1303. return -1;
  1304. switch (c) {
  1305. case 's': /* fall through */
  1306. case 'p': len++; ncodes++; break;
  1307. case 'x': break;
  1308. default: len += num; if (num) ncodes++; break;
  1309. }
  1310. itemsize = e->size;
  1311. size = align(size, c, e);
  1312. if (size == -1)
  1313. goto overflow;
  1314. /* if (size + num * itemsize > PY_SSIZE_T_MAX) { ... } */
  1315. if (num > (PY_SSIZE_T_MAX - size) / itemsize)
  1316. goto overflow;
  1317. size += num * itemsize;
  1318. }
  1319. /* check for overflow */
  1320. if ((ncodes + 1) > ((size_t)PY_SSIZE_T_MAX / sizeof(formatcode))) {
  1321. PyErr_NoMemory();
  1322. return -1;
  1323. }
  1324. self->s_size = size;
  1325. self->s_len = len;
  1326. codes = PyMem_Malloc((ncodes + 1) * sizeof(formatcode));
  1327. if (codes == NULL) {
  1328. PyErr_NoMemory();
  1329. return -1;
  1330. }
  1331. /* Free any s_codes value left over from a previous initialization. */
  1332. if (self->s_codes != NULL)
  1333. PyMem_Free(self->s_codes);
  1334. self->s_codes = codes;
  1335. s = fmt;
  1336. size = 0;
  1337. while ((c = *s++) != '\0') {
  1338. if (Py_ISSPACE(c))
  1339. continue;
  1340. if ('0' <= c && c <= '9') {
  1341. num = c - '0';
  1342. while ('0' <= (c = *s++) && c <= '9')
  1343. num = num*10 + (c - '0');
  1344. }
  1345. else
  1346. num = 1;
  1347. e = getentry(state, c, f);
  1348. size = align(size, c, e);
  1349. if (c == 's' || c == 'p') {
  1350. codes->offset = size;
  1351. codes->size = num;
  1352. codes->fmtdef = e;
  1353. codes->repeat = 1;
  1354. codes++;
  1355. size += num;
  1356. } else if (c == 'x') {
  1357. size += num;
  1358. } else if (num) {
  1359. codes->offset = size;
  1360. codes->size = e->size;
  1361. codes->fmtdef = e;
  1362. codes->repeat = num;
  1363. codes++;
  1364. size += e->size * num;
  1365. }
  1366. }
  1367. codes->fmtdef = NULL;
  1368. codes->offset = size;
  1369. codes->size = 0;
  1370. codes->repeat = 0;
  1371. return 0;
  1372. overflow:
  1373. PyErr_SetString(state->StructError,
  1374. "total struct size too long");
  1375. return -1;
  1376. }
  1377. static PyObject *
  1378. s_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
  1379. {
  1380. PyObject *self;
  1381. assert(type != NULL);
  1382. allocfunc alloc_func = PyType_GetSlot(type, Py_tp_alloc);
  1383. assert(alloc_func != NULL);
  1384. self = alloc_func(type, 0);
  1385. if (self != NULL) {
  1386. PyStructObject *s = (PyStructObject*)self;
  1387. s->s_format = Py_NewRef(Py_None);
  1388. s->s_codes = NULL;
  1389. s->s_size = -1;
  1390. s->s_len = -1;
  1391. }
  1392. return self;
  1393. }
  1394. /*[clinic input]
  1395. Struct.__init__
  1396. format: object
  1397. Create a compiled struct object.
  1398. Return a new Struct object which writes and reads binary data according to
  1399. the format string.
  1400. See help(struct) for more on format strings.
  1401. [clinic start generated code]*/
  1402. static int
  1403. Struct___init___impl(PyStructObject *self, PyObject *format)
  1404. /*[clinic end generated code: output=b8e80862444e92d0 input=192a4575a3dde802]*/
  1405. {
  1406. int ret = 0;
  1407. if (PyUnicode_Check(format)) {
  1408. format = PyUnicode_AsASCIIString(format);
  1409. if (format == NULL)
  1410. return -1;
  1411. }
  1412. else {
  1413. Py_INCREF(format);
  1414. }
  1415. if (!PyBytes_Check(format)) {
  1416. Py_DECREF(format);
  1417. PyErr_Format(PyExc_TypeError,
  1418. "Struct() argument 1 must be a str or bytes object, "
  1419. "not %.200s",
  1420. _PyType_Name(Py_TYPE(format)));
  1421. return -1;
  1422. }
  1423. Py_SETREF(self->s_format, format);
  1424. ret = prepare_s(self);
  1425. return ret;
  1426. }
  1427. static int
  1428. s_clear(PyStructObject *s)
  1429. {
  1430. Py_CLEAR(s->s_format);
  1431. return 0;
  1432. }
  1433. static int
  1434. s_traverse(PyStructObject *s, visitproc visit, void *arg)
  1435. {
  1436. Py_VISIT(Py_TYPE(s));
  1437. Py_VISIT(s->s_format);
  1438. return 0;
  1439. }
  1440. static void
  1441. s_dealloc(PyStructObject *s)
  1442. {
  1443. PyTypeObject *tp = Py_TYPE(s);
  1444. PyObject_GC_UnTrack(s);
  1445. if (s->weakreflist != NULL)
  1446. PyObject_ClearWeakRefs((PyObject *)s);
  1447. if (s->s_codes != NULL) {
  1448. PyMem_Free(s->s_codes);
  1449. }
  1450. Py_XDECREF(s->s_format);
  1451. freefunc free_func = PyType_GetSlot(Py_TYPE(s), Py_tp_free);
  1452. free_func(s);
  1453. Py_DECREF(tp);
  1454. }
  1455. static PyObject *
  1456. s_unpack_internal(PyStructObject *soself, const char *startfrom,
  1457. _structmodulestate *state) {
  1458. formatcode *code;
  1459. Py_ssize_t i = 0;
  1460. PyObject *result = PyTuple_New(soself->s_len);
  1461. if (result == NULL)
  1462. return NULL;
  1463. for (code = soself->s_codes; code->fmtdef != NULL; code++) {
  1464. const formatdef *e = code->fmtdef;
  1465. const char *res = startfrom + code->offset;
  1466. Py_ssize_t j = code->repeat;
  1467. while (j--) {
  1468. PyObject *v;
  1469. if (e->format == 's') {
  1470. v = PyBytes_FromStringAndSize(res, code->size);
  1471. } else if (e->format == 'p') {
  1472. Py_ssize_t n = *(unsigned char*)res;
  1473. if (n >= code->size)
  1474. n = code->size - 1;
  1475. v = PyBytes_FromStringAndSize(res + 1, n);
  1476. } else {
  1477. v = e->unpack(state, res, e);
  1478. }
  1479. if (v == NULL)
  1480. goto fail;
  1481. PyTuple_SET_ITEM(result, i++, v);
  1482. res += code->size;
  1483. }
  1484. }
  1485. return result;
  1486. fail:
  1487. Py_DECREF(result);
  1488. return NULL;
  1489. }
  1490. /*[clinic input]
  1491. Struct.unpack
  1492. buffer: Py_buffer
  1493. /
  1494. Return a tuple containing unpacked values.
  1495. Unpack according to the format string Struct.format. The buffer's size
  1496. in bytes must be Struct.size.
  1497. See help(struct) for more on format strings.
  1498. [clinic start generated code]*/
  1499. static PyObject *
  1500. Struct_unpack_impl(PyStructObject *self, Py_buffer *buffer)
  1501. /*[clinic end generated code: output=873a24faf02e848a input=3113f8e7038b2f6c]*/
  1502. {
  1503. _structmodulestate *state = get_struct_state_structinst(self);
  1504. assert(self->s_codes != NULL);
  1505. if (buffer->len != self->s_size) {
  1506. PyErr_Format(state->StructError,
  1507. "unpack requires a buffer of %zd bytes",
  1508. self->s_size);
  1509. return NULL;
  1510. }
  1511. return s_unpack_internal(self, buffer->buf, state);
  1512. }
  1513. /*[clinic input]
  1514. Struct.unpack_from
  1515. buffer: Py_buffer
  1516. offset: Py_ssize_t = 0
  1517. Return a tuple containing unpacked values.
  1518. Values are unpacked according to the format string Struct.format.
  1519. The buffer's size in bytes, starting at position offset, must be
  1520. at least Struct.size.
  1521. See help(struct) for more on format strings.
  1522. [clinic start generated code]*/
  1523. static PyObject *
  1524. Struct_unpack_from_impl(PyStructObject *self, Py_buffer *buffer,
  1525. Py_ssize_t offset)
  1526. /*[clinic end generated code: output=57fac875e0977316 input=cafd4851d473c894]*/
  1527. {
  1528. _structmodulestate *state = get_struct_state_structinst(self);
  1529. assert(self->s_codes != NULL);
  1530. if (offset < 0) {
  1531. if (offset + self->s_size > 0) {
  1532. PyErr_Format(state->StructError,
  1533. "not enough data to unpack %zd bytes at offset %zd",
  1534. self->s_size,
  1535. offset);
  1536. return NULL;
  1537. }
  1538. if (offset + buffer->len < 0) {
  1539. PyErr_Format(state->StructError,
  1540. "offset %zd out of range for %zd-byte buffer",
  1541. offset,
  1542. buffer->len);
  1543. return NULL;
  1544. }
  1545. offset += buffer->len;
  1546. }
  1547. if ((buffer->len - offset) < self->s_size) {
  1548. PyErr_Format(state->StructError,
  1549. "unpack_from requires a buffer of at least %zu bytes for "
  1550. "unpacking %zd bytes at offset %zd "
  1551. "(actual buffer size is %zd)",
  1552. (size_t)self->s_size + (size_t)offset,
  1553. self->s_size,
  1554. offset,
  1555. buffer->len);
  1556. return NULL;
  1557. }
  1558. return s_unpack_internal(self, (char*)buffer->buf + offset, state);
  1559. }
  1560. /* Unpack iterator type */
  1561. typedef struct {
  1562. PyObject_HEAD
  1563. PyStructObject *so;
  1564. Py_buffer buf;
  1565. Py_ssize_t index;
  1566. } unpackiterobject;
  1567. static void
  1568. unpackiter_dealloc(unpackiterobject *self)
  1569. {
  1570. /* bpo-31095: UnTrack is needed before calling any callbacks */
  1571. PyTypeObject *tp = Py_TYPE(self);
  1572. PyObject_GC_UnTrack(self);
  1573. Py_XDECREF(self->so);
  1574. PyBuffer_Release(&self->buf);
  1575. PyObject_GC_Del(self);
  1576. Py_DECREF(tp);
  1577. }
  1578. static int
  1579. unpackiter_traverse(unpackiterobject *self, visitproc visit, void *arg)
  1580. {
  1581. Py_VISIT(Py_TYPE(self));
  1582. Py_VISIT(self->so);
  1583. Py_VISIT(self->buf.obj);
  1584. return 0;
  1585. }
  1586. static PyObject *
  1587. unpackiter_len(unpackiterobject *self, PyObject *Py_UNUSED(ignored))
  1588. {
  1589. Py_ssize_t len;
  1590. if (self->so == NULL)
  1591. len = 0;
  1592. else
  1593. len = (self->buf.len - self->index) / self->so->s_size;
  1594. return PyLong_FromSsize_t(len);
  1595. }
  1596. static PyMethodDef unpackiter_methods[] = {
  1597. {"__length_hint__", (PyCFunction) unpackiter_len, METH_NOARGS, NULL},
  1598. {NULL, NULL} /* sentinel */
  1599. };
  1600. static PyObject *
  1601. unpackiter_iternext(unpackiterobject *self)
  1602. {
  1603. _structmodulestate *state = get_struct_state_iterinst(self);
  1604. PyObject *result;
  1605. if (self->so == NULL)
  1606. return NULL;
  1607. if (self->index >= self->buf.len) {
  1608. /* Iterator exhausted */
  1609. Py_CLEAR(self->so);
  1610. PyBuffer_Release(&self->buf);
  1611. return NULL;
  1612. }
  1613. assert(self->index + self->so->s_size <= self->buf.len);
  1614. result = s_unpack_internal(self->so,
  1615. (char*) self->buf.buf + self->index,
  1616. state);
  1617. self->index += self->so->s_size;
  1618. return result;
  1619. }
  1620. static PyType_Slot unpackiter_type_slots[] = {
  1621. {Py_tp_dealloc, unpackiter_dealloc},
  1622. {Py_tp_getattro, PyObject_GenericGetAttr},
  1623. {Py_tp_traverse, unpackiter_traverse},
  1624. {Py_tp_iter, PyObject_SelfIter},
  1625. {Py_tp_iternext, unpackiter_iternext},
  1626. {Py_tp_methods, unpackiter_methods},
  1627. {0, 0},
  1628. };
  1629. static PyType_Spec unpackiter_type_spec = {
  1630. "_struct.unpack_iterator",
  1631. sizeof(unpackiterobject),
  1632. 0,
  1633. (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
  1634. Py_TPFLAGS_IMMUTABLETYPE | Py_TPFLAGS_DISALLOW_INSTANTIATION),
  1635. unpackiter_type_slots
  1636. };
  1637. /*[clinic input]
  1638. Struct.iter_unpack
  1639. buffer: object
  1640. /
  1641. Return an iterator yielding tuples.
  1642. Tuples are unpacked from the given bytes source, like a repeated
  1643. invocation of unpack_from().
  1644. Requires that the bytes length be a multiple of the struct size.
  1645. [clinic start generated code]*/
  1646. static PyObject *
  1647. Struct_iter_unpack(PyStructObject *self, PyObject *buffer)
  1648. /*[clinic end generated code: output=172d83d0cd15dbab input=6d65b3f3107dbc99]*/
  1649. {
  1650. _structmodulestate *state = get_struct_state_structinst(self);
  1651. unpackiterobject *iter;
  1652. assert(self->s_codes != NULL);
  1653. if (self->s_size == 0) {
  1654. PyErr_Format(state->StructError,
  1655. "cannot iteratively unpack with a struct of length 0");
  1656. return NULL;
  1657. }
  1658. iter = (unpackiterobject *) PyType_GenericAlloc((PyTypeObject *)state->unpackiter_type, 0);
  1659. if (iter == NULL)
  1660. return NULL;
  1661. if (PyObject_GetBuffer(buffer, &iter->buf, PyBUF_SIMPLE) < 0) {
  1662. Py_DECREF(iter);
  1663. return NULL;
  1664. }
  1665. if (iter->buf.len % self->s_size != 0) {
  1666. PyErr_Format(state->StructError,
  1667. "iterative unpacking requires a buffer of "
  1668. "a multiple of %zd bytes",
  1669. self->s_size);
  1670. Py_DECREF(iter);
  1671. return NULL;
  1672. }
  1673. iter->so = (PyStructObject*)Py_NewRef(self);
  1674. iter->index = 0;
  1675. return (PyObject *)iter;
  1676. }
  1677. /*
  1678. * Guts of the pack function.
  1679. *
  1680. * Takes a struct object, a tuple of arguments, and offset in that tuple of
  1681. * argument for where to start processing the arguments for packing, and a
  1682. * character buffer for writing the packed string. The caller must insure
  1683. * that the buffer may contain the required length for packing the arguments.
  1684. * 0 is returned on success, 1 is returned if there is an error.
  1685. *
  1686. */
  1687. static int
  1688. s_pack_internal(PyStructObject *soself, PyObject *const *args, int offset,
  1689. char* buf, _structmodulestate *state)
  1690. {
  1691. formatcode *code;
  1692. /* XXX(nnorwitz): why does i need to be a local? can we use
  1693. the offset parameter or do we need the wider width? */
  1694. Py_ssize_t i;
  1695. memset(buf, '\0', soself->s_size);
  1696. i = offset;
  1697. for (code = soself->s_codes; code->fmtdef != NULL; code++) {
  1698. const formatdef *e = code->fmtdef;
  1699. char *res = buf + code->offset;
  1700. Py_ssize_t j = code->repeat;
  1701. while (j--) {
  1702. PyObject *v = args[i++];
  1703. if (e->format == 's') {
  1704. Py_ssize_t n;
  1705. int isstring;
  1706. const void *p;
  1707. isstring = PyBytes_Check(v);
  1708. if (!isstring && !PyByteArray_Check(v)) {
  1709. PyErr_SetString(state->StructError,
  1710. "argument for 's' must be a bytes object");
  1711. return -1;
  1712. }
  1713. if (isstring) {
  1714. n = PyBytes_GET_SIZE(v);
  1715. p = PyBytes_AS_STRING(v);
  1716. }
  1717. else {
  1718. n = PyByteArray_GET_SIZE(v);
  1719. p = PyByteArray_AS_STRING(v);
  1720. }
  1721. if (n > code->size)
  1722. n = code->size;
  1723. if (n > 0)
  1724. memcpy(res, p, n);
  1725. } else if (e->format == 'p') {
  1726. Py_ssize_t n;
  1727. int isstring;
  1728. const void *p;
  1729. isstring = PyBytes_Check(v);
  1730. if (!isstring && !PyByteArray_Check(v)) {
  1731. PyErr_SetString(state->StructError,
  1732. "argument for 'p' must be a bytes object");
  1733. return -1;
  1734. }
  1735. if (isstring) {
  1736. n = PyBytes_GET_SIZE(v);
  1737. p = PyBytes_AS_STRING(v);
  1738. }
  1739. else {
  1740. n = PyByteArray_GET_SIZE(v);
  1741. p = PyByteArray_AS_STRING(v);
  1742. }
  1743. if (n > (code->size - 1))
  1744. n = code->size - 1;
  1745. if (n > 0)
  1746. memcpy(res + 1, p, n);
  1747. if (n > 255)
  1748. n = 255;
  1749. *res = Py_SAFE_DOWNCAST(n, Py_ssize_t, unsigned char);
  1750. } else {
  1751. if (e->pack(state, res, v, e) < 0) {
  1752. if (PyLong_Check(v) && PyErr_ExceptionMatches(PyExc_OverflowError))
  1753. PyErr_SetString(state->StructError,
  1754. "int too large to convert");
  1755. return -1;
  1756. }
  1757. }
  1758. res += code->size;
  1759. }
  1760. }
  1761. /* Success */
  1762. return 0;
  1763. }
  1764. PyDoc_STRVAR(s_pack__doc__,
  1765. "S.pack(v1, v2, ...) -> bytes\n\
  1766. \n\
  1767. Return a bytes object containing values v1, v2, ... packed according\n\
  1768. to the format string S.format. See help(struct) for more on format\n\
  1769. strings.");
  1770. static PyObject *
  1771. s_pack(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
  1772. {
  1773. char *buf;
  1774. PyStructObject *soself;
  1775. _structmodulestate *state = get_struct_state_structinst(self);
  1776. /* Validate arguments. */
  1777. soself = (PyStructObject *)self;
  1778. assert(PyStruct_Check(self, state));
  1779. assert(soself->s_codes != NULL);
  1780. if (nargs != soself->s_len)
  1781. {
  1782. PyErr_Format(state->StructError,
  1783. "pack expected %zd items for packing (got %zd)", soself->s_len, nargs);
  1784. return NULL;
  1785. }
  1786. /* Allocate a new string */
  1787. _PyBytesWriter writer;
  1788. _PyBytesWriter_Init(&writer);
  1789. buf = _PyBytesWriter_Alloc(&writer, soself->s_size);
  1790. if (buf == NULL) {
  1791. _PyBytesWriter_Dealloc(&writer);
  1792. return NULL;
  1793. }
  1794. /* Call the guts */
  1795. if ( s_pack_internal(soself, args, 0, buf, state) != 0 ) {
  1796. _PyBytesWriter_Dealloc(&writer);
  1797. return NULL;
  1798. }
  1799. return _PyBytesWriter_Finish(&writer, buf + soself->s_size);
  1800. }
  1801. PyDoc_STRVAR(s_pack_into__doc__,
  1802. "S.pack_into(buffer, offset, v1, v2, ...)\n\
  1803. \n\
  1804. Pack the values v1, v2, ... according to the format string S.format\n\
  1805. and write the packed bytes into the writable buffer buf starting at\n\
  1806. offset. Note that the offset is a required argument. See\n\
  1807. help(struct) for more on format strings.");
  1808. static PyObject *
  1809. s_pack_into(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
  1810. {
  1811. PyStructObject *soself;
  1812. Py_buffer buffer;
  1813. Py_ssize_t offset;
  1814. _structmodulestate *state = get_struct_state_structinst(self);
  1815. /* Validate arguments. +1 is for the first arg as buffer. */
  1816. soself = (PyStructObject *)self;
  1817. assert(PyStruct_Check(self, state));
  1818. assert(soself->s_codes != NULL);
  1819. if (nargs != (soself->s_len + 2))
  1820. {
  1821. if (nargs == 0) {
  1822. PyErr_Format(state->StructError,
  1823. "pack_into expected buffer argument");
  1824. }
  1825. else if (nargs == 1) {
  1826. PyErr_Format(state->StructError,
  1827. "pack_into expected offset argument");
  1828. }
  1829. else {
  1830. PyErr_Format(state->StructError,
  1831. "pack_into expected %zd items for packing (got %zd)",
  1832. soself->s_len, (nargs - 2));
  1833. }
  1834. return NULL;
  1835. }
  1836. /* Extract a writable memory buffer from the first argument */
  1837. if (!PyArg_Parse(args[0], "w*", &buffer))
  1838. return NULL;
  1839. assert(buffer.len >= 0);
  1840. /* Extract the offset from the first argument */
  1841. offset = PyNumber_AsSsize_t(args[1], PyExc_IndexError);
  1842. if (offset == -1 && PyErr_Occurred()) {
  1843. PyBuffer_Release(&buffer);
  1844. return NULL;
  1845. }
  1846. /* Support negative offsets. */
  1847. if (offset < 0) {
  1848. /* Check that negative offset is low enough to fit data */
  1849. if (offset + soself->s_size > 0) {
  1850. PyErr_Format(state->StructError,
  1851. "no space to pack %zd bytes at offset %zd",
  1852. soself->s_size,
  1853. offset);
  1854. PyBuffer_Release(&buffer);
  1855. return NULL;
  1856. }
  1857. /* Check that negative offset is not crossing buffer boundary */
  1858. if (offset + buffer.len < 0) {
  1859. PyErr_Format(state->StructError,
  1860. "offset %zd out of range for %zd-byte buffer",
  1861. offset,
  1862. buffer.len);
  1863. PyBuffer_Release(&buffer);
  1864. return NULL;
  1865. }
  1866. offset += buffer.len;
  1867. }
  1868. /* Check boundaries */
  1869. if ((buffer.len - offset) < soself->s_size) {
  1870. assert(offset >= 0);
  1871. assert(soself->s_size >= 0);
  1872. PyErr_Format(state->StructError,
  1873. "pack_into requires a buffer of at least %zu bytes for "
  1874. "packing %zd bytes at offset %zd "
  1875. "(actual buffer size is %zd)",
  1876. (size_t)soself->s_size + (size_t)offset,
  1877. soself->s_size,
  1878. offset,
  1879. buffer.len);
  1880. PyBuffer_Release(&buffer);
  1881. return NULL;
  1882. }
  1883. /* Call the guts */
  1884. if (s_pack_internal(soself, args, 2, (char*)buffer.buf + offset, state) != 0) {
  1885. PyBuffer_Release(&buffer);
  1886. return NULL;
  1887. }
  1888. PyBuffer_Release(&buffer);
  1889. Py_RETURN_NONE;
  1890. }
  1891. static PyObject *
  1892. s_get_format(PyStructObject *self, void *unused)
  1893. {
  1894. return PyUnicode_FromStringAndSize(PyBytes_AS_STRING(self->s_format),
  1895. PyBytes_GET_SIZE(self->s_format));
  1896. }
  1897. static PyObject *
  1898. s_get_size(PyStructObject *self, void *unused)
  1899. {
  1900. return PyLong_FromSsize_t(self->s_size);
  1901. }
  1902. PyDoc_STRVAR(s_sizeof__doc__,
  1903. "S.__sizeof__() -> size of S in memory, in bytes");
  1904. static PyObject *
  1905. s_sizeof(PyStructObject *self, void *unused)
  1906. {
  1907. size_t size = _PyObject_SIZE(Py_TYPE(self)) + sizeof(formatcode);
  1908. for (formatcode *code = self->s_codes; code->fmtdef != NULL; code++) {
  1909. size += sizeof(formatcode);
  1910. }
  1911. return PyLong_FromSize_t(size);
  1912. }
  1913. /* List of functions */
  1914. static struct PyMethodDef s_methods[] = {
  1915. STRUCT_ITER_UNPACK_METHODDEF
  1916. {"pack", _PyCFunction_CAST(s_pack), METH_FASTCALL, s_pack__doc__},
  1917. {"pack_into", _PyCFunction_CAST(s_pack_into), METH_FASTCALL, s_pack_into__doc__},
  1918. STRUCT_UNPACK_METHODDEF
  1919. STRUCT_UNPACK_FROM_METHODDEF
  1920. {"__sizeof__", (PyCFunction)s_sizeof, METH_NOARGS, s_sizeof__doc__},
  1921. {NULL, NULL} /* sentinel */
  1922. };
  1923. static PyMemberDef s_members[] = {
  1924. {"__weaklistoffset__", T_PYSSIZET, offsetof(PyStructObject, weakreflist), READONLY},
  1925. {NULL} /* sentinel */
  1926. };
  1927. static PyGetSetDef s_getsetlist[] = {
  1928. {"format", (getter)s_get_format, (setter)NULL, "struct format string", NULL},
  1929. {"size", (getter)s_get_size, (setter)NULL, "struct size in bytes", NULL},
  1930. {NULL} /* sentinel */
  1931. };
  1932. PyDoc_STRVAR(s__doc__,
  1933. "Struct(fmt) --> compiled struct object\n"
  1934. "\n"
  1935. );
  1936. static PyType_Slot PyStructType_slots[] = {
  1937. {Py_tp_dealloc, s_dealloc},
  1938. {Py_tp_getattro, PyObject_GenericGetAttr},
  1939. {Py_tp_setattro, PyObject_GenericSetAttr},
  1940. {Py_tp_doc, (void*)s__doc__},
  1941. {Py_tp_traverse, s_traverse},
  1942. {Py_tp_clear, s_clear},
  1943. {Py_tp_methods, s_methods},
  1944. {Py_tp_members, s_members},
  1945. {Py_tp_getset, s_getsetlist},
  1946. {Py_tp_init, Struct___init__},
  1947. {Py_tp_alloc, PyType_GenericAlloc},
  1948. {Py_tp_new, s_new},
  1949. {Py_tp_free, PyObject_GC_Del},
  1950. {0, 0},
  1951. };
  1952. static PyType_Spec PyStructType_spec = {
  1953. "_struct.Struct",
  1954. sizeof(PyStructObject),
  1955. 0,
  1956. (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
  1957. Py_TPFLAGS_BASETYPE | Py_TPFLAGS_IMMUTABLETYPE),
  1958. PyStructType_slots
  1959. };
  1960. /* ---- Standalone functions ---- */
  1961. #define MAXCACHE 100
  1962. static int
  1963. cache_struct_converter(PyObject *module, PyObject *fmt, PyStructObject **ptr)
  1964. {
  1965. PyObject * s_object;
  1966. _structmodulestate *state = get_struct_state(module);
  1967. if (fmt == NULL) {
  1968. Py_SETREF(*ptr, NULL);
  1969. return 1;
  1970. }
  1971. if (state->cache == NULL) {
  1972. state->cache = PyDict_New();
  1973. if (state->cache == NULL)
  1974. return 0;
  1975. }
  1976. s_object = PyDict_GetItemWithError(state->cache, fmt);
  1977. if (s_object != NULL) {
  1978. *ptr = (PyStructObject *)Py_NewRef(s_object);
  1979. return Py_CLEANUP_SUPPORTED;
  1980. }
  1981. else if (PyErr_Occurred()) {
  1982. return 0;
  1983. }
  1984. s_object = PyObject_CallOneArg(state->PyStructType, fmt);
  1985. if (s_object != NULL) {
  1986. if (PyDict_GET_SIZE(state->cache) >= MAXCACHE)
  1987. PyDict_Clear(state->cache);
  1988. /* Attempt to cache the result */
  1989. if (PyDict_SetItem(state->cache, fmt, s_object) == -1)
  1990. PyErr_Clear();
  1991. *ptr = (PyStructObject *)s_object;
  1992. return Py_CLEANUP_SUPPORTED;
  1993. }
  1994. return 0;
  1995. }
  1996. /*[clinic input]
  1997. _clearcache
  1998. Clear the internal cache.
  1999. [clinic start generated code]*/
  2000. static PyObject *
  2001. _clearcache_impl(PyObject *module)
  2002. /*[clinic end generated code: output=ce4fb8a7bf7cb523 input=463eaae04bab3211]*/
  2003. {
  2004. Py_CLEAR(get_struct_state(module)->cache);
  2005. Py_RETURN_NONE;
  2006. }
  2007. /*[clinic input]
  2008. calcsize -> Py_ssize_t
  2009. format as s_object: cache_struct
  2010. /
  2011. Return size in bytes of the struct described by the format string.
  2012. [clinic start generated code]*/
  2013. static Py_ssize_t
  2014. calcsize_impl(PyObject *module, PyStructObject *s_object)
  2015. /*[clinic end generated code: output=db7d23d09c6932c4 input=96a6a590c7717ecd]*/
  2016. {
  2017. return s_object->s_size;
  2018. }
  2019. PyDoc_STRVAR(pack_doc,
  2020. "pack(format, v1, v2, ...) -> bytes\n\
  2021. \n\
  2022. Return a bytes object containing the values v1, v2, ... packed according\n\
  2023. to the format string. See help(struct) for more on format strings.");
  2024. static PyObject *
  2025. pack(PyObject *module, PyObject *const *args, Py_ssize_t nargs)
  2026. {
  2027. PyObject *s_object = NULL;
  2028. PyObject *format, *result;
  2029. if (nargs == 0) {
  2030. PyErr_SetString(PyExc_TypeError, "missing format argument");
  2031. return NULL;
  2032. }
  2033. format = args[0];
  2034. if (!cache_struct_converter(module, format, (PyStructObject **)&s_object)) {
  2035. return NULL;
  2036. }
  2037. result = s_pack(s_object, args + 1, nargs - 1);
  2038. Py_DECREF(s_object);
  2039. return result;
  2040. }
  2041. PyDoc_STRVAR(pack_into_doc,
  2042. "pack_into(format, buffer, offset, v1, v2, ...)\n\
  2043. \n\
  2044. Pack the values v1, v2, ... according to the format string and write\n\
  2045. the packed bytes into the writable buffer buf starting at offset. Note\n\
  2046. that the offset is a required argument. See help(struct) for more\n\
  2047. on format strings.");
  2048. static PyObject *
  2049. pack_into(PyObject *module, PyObject *const *args, Py_ssize_t nargs)
  2050. {
  2051. PyObject *s_object = NULL;
  2052. PyObject *format, *result;
  2053. if (nargs == 0) {
  2054. PyErr_SetString(PyExc_TypeError, "missing format argument");
  2055. return NULL;
  2056. }
  2057. format = args[0];
  2058. if (!cache_struct_converter(module, format, (PyStructObject **)&s_object)) {
  2059. return NULL;
  2060. }
  2061. result = s_pack_into(s_object, args + 1, nargs - 1);
  2062. Py_DECREF(s_object);
  2063. return result;
  2064. }
  2065. /*[clinic input]
  2066. unpack
  2067. format as s_object: cache_struct
  2068. buffer: Py_buffer
  2069. /
  2070. Return a tuple containing values unpacked according to the format string.
  2071. The buffer's size in bytes must be calcsize(format).
  2072. See help(struct) for more on format strings.
  2073. [clinic start generated code]*/
  2074. static PyObject *
  2075. unpack_impl(PyObject *module, PyStructObject *s_object, Py_buffer *buffer)
  2076. /*[clinic end generated code: output=48ddd4d88eca8551 input=05fa3b91678da727]*/
  2077. {
  2078. return Struct_unpack_impl(s_object, buffer);
  2079. }
  2080. /*[clinic input]
  2081. unpack_from
  2082. format as s_object: cache_struct
  2083. /
  2084. buffer: Py_buffer
  2085. offset: Py_ssize_t = 0
  2086. Return a tuple containing values unpacked according to the format string.
  2087. The buffer's size, minus offset, must be at least calcsize(format).
  2088. See help(struct) for more on format strings.
  2089. [clinic start generated code]*/
  2090. static PyObject *
  2091. unpack_from_impl(PyObject *module, PyStructObject *s_object,
  2092. Py_buffer *buffer, Py_ssize_t offset)
  2093. /*[clinic end generated code: output=1042631674c6e0d3 input=6e80a5398e985025]*/
  2094. {
  2095. return Struct_unpack_from_impl(s_object, buffer, offset);
  2096. }
  2097. /*[clinic input]
  2098. iter_unpack
  2099. format as s_object: cache_struct
  2100. buffer: object
  2101. /
  2102. Return an iterator yielding tuples unpacked from the given bytes.
  2103. The bytes are unpacked according to the format string, like
  2104. a repeated invocation of unpack_from().
  2105. Requires that the bytes length be a multiple of the format struct size.
  2106. [clinic start generated code]*/
  2107. static PyObject *
  2108. iter_unpack_impl(PyObject *module, PyStructObject *s_object,
  2109. PyObject *buffer)
  2110. /*[clinic end generated code: output=0ae50e250d20e74d input=b214a58869a3c98d]*/
  2111. {
  2112. return Struct_iter_unpack(s_object, buffer);
  2113. }
  2114. static struct PyMethodDef module_functions[] = {
  2115. _CLEARCACHE_METHODDEF
  2116. CALCSIZE_METHODDEF
  2117. ITER_UNPACK_METHODDEF
  2118. {"pack", _PyCFunction_CAST(pack), METH_FASTCALL, pack_doc},
  2119. {"pack_into", _PyCFunction_CAST(pack_into), METH_FASTCALL, pack_into_doc},
  2120. UNPACK_METHODDEF
  2121. UNPACK_FROM_METHODDEF
  2122. {NULL, NULL} /* sentinel */
  2123. };
  2124. /* Module initialization */
  2125. PyDoc_STRVAR(module_doc,
  2126. "Functions to convert between Python values and C structs.\n\
  2127. Python bytes objects are used to hold the data representing the C struct\n\
  2128. and also as format strings (explained below) to describe the layout of data\n\
  2129. in the C struct.\n\
  2130. \n\
  2131. The optional first format char indicates byte order, size and alignment:\n\
  2132. @: native order, size & alignment (default)\n\
  2133. =: native order, std. size & alignment\n\
  2134. <: little-endian, std. size & alignment\n\
  2135. >: big-endian, std. size & alignment\n\
  2136. !: same as >\n\
  2137. \n\
  2138. The remaining chars indicate types of args and must match exactly;\n\
  2139. these can be preceded by a decimal repeat count:\n\
  2140. x: pad byte (no data); c:char; b:signed byte; B:unsigned byte;\n\
  2141. ?: _Bool (requires C99; if not available, char is used instead)\n\
  2142. h:short; H:unsigned short; i:int; I:unsigned int;\n\
  2143. l:long; L:unsigned long; f:float; d:double; e:half-float.\n\
  2144. Special cases (preceding decimal count indicates length):\n\
  2145. s:string (array of char); p: pascal string (with count byte).\n\
  2146. Special cases (only available in native format):\n\
  2147. n:ssize_t; N:size_t;\n\
  2148. P:an integer type that is wide enough to hold a pointer.\n\
  2149. Special case (not in native mode unless 'long long' in platform C):\n\
  2150. q:long long; Q:unsigned long long\n\
  2151. Whitespace between formats is ignored.\n\
  2152. \n\
  2153. The variable struct.error is an exception raised on errors.\n");
  2154. static int
  2155. _structmodule_traverse(PyObject *module, visitproc visit, void *arg)
  2156. {
  2157. _structmodulestate *state = get_struct_state(module);
  2158. if (state) {
  2159. Py_VISIT(state->cache);
  2160. Py_VISIT(state->PyStructType);
  2161. Py_VISIT(state->unpackiter_type);
  2162. Py_VISIT(state->StructError);
  2163. }
  2164. return 0;
  2165. }
  2166. static int
  2167. _structmodule_clear(PyObject *module)
  2168. {
  2169. _structmodulestate *state = get_struct_state(module);
  2170. if (state) {
  2171. Py_CLEAR(state->cache);
  2172. Py_CLEAR(state->PyStructType);
  2173. Py_CLEAR(state->unpackiter_type);
  2174. Py_CLEAR(state->StructError);
  2175. }
  2176. return 0;
  2177. }
  2178. static void
  2179. _structmodule_free(void *module)
  2180. {
  2181. _structmodule_clear((PyObject *)module);
  2182. }
  2183. static int
  2184. _structmodule_exec(PyObject *m)
  2185. {
  2186. _structmodulestate *state = get_struct_state(m);
  2187. state->PyStructType = PyType_FromModuleAndSpec(
  2188. m, &PyStructType_spec, NULL);
  2189. if (state->PyStructType == NULL) {
  2190. return -1;
  2191. }
  2192. if (PyModule_AddType(m, (PyTypeObject *)state->PyStructType) < 0) {
  2193. return -1;
  2194. }
  2195. state->unpackiter_type = PyType_FromModuleAndSpec(
  2196. m, &unpackiter_type_spec, NULL);
  2197. if (state->unpackiter_type == NULL) {
  2198. return -1;
  2199. }
  2200. /* Check endian and swap in faster functions */
  2201. {
  2202. const formatdef *native = native_table;
  2203. formatdef *other, *ptr;
  2204. #if PY_LITTLE_ENDIAN
  2205. other = lilendian_table;
  2206. #else
  2207. other = bigendian_table;
  2208. #endif
  2209. /* Scan through the native table, find a matching
  2210. entry in the endian table and swap in the
  2211. native implementations whenever possible
  2212. (64-bit platforms may not have "standard" sizes) */
  2213. while (native->format != '\0' && other->format != '\0') {
  2214. ptr = other;
  2215. while (ptr->format != '\0') {
  2216. if (ptr->format == native->format) {
  2217. /* Match faster when formats are
  2218. listed in the same order */
  2219. if (ptr == other)
  2220. other++;
  2221. /* Only use the trick if the
  2222. size matches */
  2223. if (ptr->size != native->size)
  2224. break;
  2225. /* Skip float and double, could be
  2226. "unknown" float format */
  2227. if (ptr->format == 'd' || ptr->format == 'f')
  2228. break;
  2229. /* Skip _Bool, semantics are different for standard size */
  2230. if (ptr->format == '?')
  2231. break;
  2232. ptr->pack = native->pack;
  2233. ptr->unpack = native->unpack;
  2234. break;
  2235. }
  2236. ptr++;
  2237. }
  2238. native++;
  2239. }
  2240. }
  2241. /* Add some symbolic constants to the module */
  2242. state->StructError = PyErr_NewException("struct.error", NULL, NULL);
  2243. if (state->StructError == NULL) {
  2244. return -1;
  2245. }
  2246. if (PyModule_AddObjectRef(m, "error", state->StructError) < 0) {
  2247. return -1;
  2248. }
  2249. return 0;
  2250. }
  2251. static PyModuleDef_Slot _structmodule_slots[] = {
  2252. {Py_mod_exec, _structmodule_exec},
  2253. {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
  2254. {0, NULL}
  2255. };
  2256. static struct PyModuleDef _structmodule = {
  2257. PyModuleDef_HEAD_INIT,
  2258. .m_name = "_struct",
  2259. .m_doc = module_doc,
  2260. .m_size = sizeof(_structmodulestate),
  2261. .m_methods = module_functions,
  2262. .m_slots = _structmodule_slots,
  2263. .m_traverse = _structmodule_traverse,
  2264. .m_clear = _structmodule_clear,
  2265. .m_free = _structmodule_free,
  2266. };
  2267. PyMODINIT_FUNC
  2268. PyInit__struct(void)
  2269. {
  2270. return PyModuleDef_Init(&_structmodule);
  2271. }