PageRenderTime 48ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/Modules/_struct.c

http://unladen-swallow.googlecode.com/
C | 2171 lines | 1808 code | 253 blank | 110 comment | 403 complexity | f5e01344d6cd89d1ea0e8b18b427e37d MD5 | raw file
Possible License(s): 0BSD, BSD-3-Clause
  1. /* struct module -- pack values into and (out of) strings */
  2. /* New version supporting byte order, alignment and size options,
  3. character strings, and unsigned numbers */
  4. #define PY_SSIZE_T_CLEAN
  5. #include "Python.h"
  6. #include "structseq.h"
  7. #include "structmember.h"
  8. #include <ctype.h>
  9. static PyTypeObject PyStructType;
  10. /* compatibility macros */
  11. #if (PY_VERSION_HEX < 0x02050000)
  12. typedef int Py_ssize_t;
  13. #endif
  14. /* If PY_STRUCT_OVERFLOW_MASKING is defined, the struct module will wrap all input
  15. numbers for explicit endians such that they fit in the given type, much
  16. like explicit casting in C. A warning will be raised if the number did
  17. not originally fit within the range of the requested type. If it is
  18. not defined, then all range errors and overflow will be struct.error
  19. exceptions. */
  20. #define PY_STRUCT_OVERFLOW_MASKING 1
  21. #ifdef PY_STRUCT_OVERFLOW_MASKING
  22. static PyObject *pylong_ulong_mask = NULL;
  23. static PyObject *pyint_zero = NULL;
  24. #endif
  25. /* If PY_STRUCT_FLOAT_COERCE is defined, the struct module will allow float
  26. arguments for integer formats with a warning for backwards
  27. compatibility. */
  28. #define PY_STRUCT_FLOAT_COERCE 1
  29. #ifdef PY_STRUCT_FLOAT_COERCE
  30. #define FLOAT_COERCE "integer argument expected, got float"
  31. #endif
  32. /* The translation function for each format character is table driven */
  33. typedef struct _formatdef {
  34. char format;
  35. Py_ssize_t size;
  36. Py_ssize_t alignment;
  37. PyObject* (*unpack)(const char *,
  38. const struct _formatdef *);
  39. int (*pack)(char *, PyObject *,
  40. const struct _formatdef *);
  41. } formatdef;
  42. typedef struct _formatcode {
  43. const struct _formatdef *fmtdef;
  44. Py_ssize_t offset;
  45. Py_ssize_t size;
  46. } formatcode;
  47. /* Struct object interface */
  48. typedef struct {
  49. PyObject_HEAD
  50. Py_ssize_t s_size;
  51. Py_ssize_t s_len;
  52. formatcode *s_codes;
  53. PyObject *s_format;
  54. PyObject *weakreflist; /* List of weak references */
  55. } PyStructObject;
  56. #define PyStruct_Check(op) PyObject_TypeCheck(op, &PyStructType)
  57. #define PyStruct_CheckExact(op) (Py_TYPE(op) == &PyStructType)
  58. /* Exception */
  59. static PyObject *StructError;
  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. #define SHORT_ALIGN (sizeof(st_short) - sizeof(short))
  68. #define INT_ALIGN (sizeof(st_int) - sizeof(int))
  69. #define LONG_ALIGN (sizeof(st_long) - sizeof(long))
  70. #define FLOAT_ALIGN (sizeof(st_float) - sizeof(float))
  71. #define DOUBLE_ALIGN (sizeof(st_double) - sizeof(double))
  72. #define VOID_P_ALIGN (sizeof(st_void_p) - sizeof(void *))
  73. /* We can't support q and Q in native mode unless the compiler does;
  74. in std mode, they're 8 bytes on all platforms. */
  75. #ifdef HAVE_LONG_LONG
  76. typedef struct { char c; PY_LONG_LONG x; } s_long_long;
  77. #define LONG_LONG_ALIGN (sizeof(s_long_long) - sizeof(PY_LONG_LONG))
  78. #endif
  79. #ifdef HAVE_C99_BOOL
  80. #define BOOL_TYPE _Bool
  81. typedef struct { char c; _Bool x; } s_bool;
  82. #define BOOL_ALIGN (sizeof(s_bool) - sizeof(BOOL_TYPE))
  83. #else
  84. #define BOOL_TYPE char
  85. #define BOOL_ALIGN 0
  86. #endif
  87. #define STRINGIFY(x) #x
  88. #ifdef __powerc
  89. #pragma options align=reset
  90. #endif
  91. /* Helper to get a PyLongObject by hook or by crook. Caller should decref. */
  92. static PyObject *
  93. get_pylong(PyObject *v)
  94. {
  95. PyNumberMethods *m;
  96. assert(v != NULL);
  97. if (PyInt_Check(v))
  98. return PyLong_FromLong(PyInt_AS_LONG(v));
  99. if (PyLong_Check(v)) {
  100. Py_INCREF(v);
  101. return v;
  102. }
  103. m = Py_TYPE(v)->tp_as_number;
  104. if (m != NULL && m->nb_long != NULL) {
  105. v = m->nb_long(v);
  106. if (v == NULL)
  107. return NULL;
  108. if (PyLong_Check(v))
  109. return v;
  110. Py_DECREF(v);
  111. }
  112. PyErr_SetString(StructError,
  113. "cannot convert argument to long");
  114. return NULL;
  115. }
  116. /* Helper routine to get a Python integer and raise the appropriate error
  117. if it isn't one */
  118. static int
  119. get_long(PyObject *v, long *p)
  120. {
  121. long x = PyInt_AsLong(v);
  122. if (x == -1 && PyErr_Occurred()) {
  123. #ifdef PY_STRUCT_FLOAT_COERCE
  124. if (PyFloat_Check(v)) {
  125. PyObject *o;
  126. int res;
  127. PyErr_Clear();
  128. if (PyErr_WarnEx(PyExc_DeprecationWarning, FLOAT_COERCE, 2) < 0)
  129. return -1;
  130. o = PyNumber_Int(v);
  131. if (o == NULL)
  132. return -1;
  133. res = get_long(o, p);
  134. Py_DECREF(o);
  135. return res;
  136. }
  137. #endif
  138. if (PyErr_ExceptionMatches(PyExc_TypeError))
  139. PyErr_SetString(StructError,
  140. "required argument is not an integer");
  141. return -1;
  142. }
  143. *p = x;
  144. return 0;
  145. }
  146. /* Same, but handling unsigned long */
  147. #ifndef PY_STRUCT_OVERFLOW_MASKING
  148. static int
  149. get_ulong(PyObject *v, unsigned long *p)
  150. {
  151. if (PyLong_Check(v)) {
  152. unsigned long x = PyLong_AsUnsignedLong(v);
  153. if (x == (unsigned long)(-1) && PyErr_Occurred())
  154. return -1;
  155. *p = x;
  156. return 0;
  157. }
  158. if (get_long(v, (long *)p) < 0)
  159. return -1;
  160. if (((long)*p) < 0) {
  161. PyErr_SetString(StructError,
  162. "unsigned argument is < 0");
  163. return -1;
  164. }
  165. return 0;
  166. }
  167. #endif /* PY_STRUCT_OVERFLOW_MASKING */
  168. #ifdef HAVE_LONG_LONG
  169. /* Same, but handling native long long. */
  170. static int
  171. get_longlong(PyObject *v, PY_LONG_LONG *p)
  172. {
  173. PY_LONG_LONG x;
  174. v = get_pylong(v);
  175. if (v == NULL)
  176. return -1;
  177. assert(PyLong_Check(v));
  178. x = PyLong_AsLongLong(v);
  179. Py_DECREF(v);
  180. if (x == (PY_LONG_LONG)-1 && PyErr_Occurred())
  181. return -1;
  182. *p = x;
  183. return 0;
  184. }
  185. /* Same, but handling native unsigned long long. */
  186. static int
  187. get_ulonglong(PyObject *v, unsigned PY_LONG_LONG *p)
  188. {
  189. unsigned PY_LONG_LONG x;
  190. v = get_pylong(v);
  191. if (v == NULL)
  192. return -1;
  193. assert(PyLong_Check(v));
  194. x = PyLong_AsUnsignedLongLong(v);
  195. Py_DECREF(v);
  196. if (x == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred())
  197. return -1;
  198. *p = x;
  199. return 0;
  200. }
  201. #endif
  202. #ifdef PY_STRUCT_OVERFLOW_MASKING
  203. /* Helper routine to get a Python integer and raise the appropriate error
  204. if it isn't one */
  205. #define INT_OVERFLOW "struct integer overflow masking is deprecated"
  206. static int
  207. get_wrapped_long(PyObject *v, long *p)
  208. {
  209. if (get_long(v, p) < 0) {
  210. if (PyLong_Check(v) &&
  211. PyErr_ExceptionMatches(PyExc_OverflowError)) {
  212. PyObject *wrapped;
  213. long x;
  214. PyErr_Clear();
  215. #ifdef PY_STRUCT_FLOAT_COERCE
  216. if (PyFloat_Check(v)) {
  217. PyObject *o;
  218. int res;
  219. PyErr_Clear();
  220. if (PyErr_WarnEx(PyExc_DeprecationWarning, FLOAT_COERCE, 2) < 0)
  221. return -1;
  222. o = PyNumber_Int(v);
  223. if (o == NULL)
  224. return -1;
  225. res = get_wrapped_long(o, p);
  226. Py_DECREF(o);
  227. return res;
  228. }
  229. #endif
  230. if (PyErr_WarnEx(PyExc_DeprecationWarning, INT_OVERFLOW, 2) < 0)
  231. return -1;
  232. wrapped = PyNumber_And(v, pylong_ulong_mask);
  233. if (wrapped == NULL)
  234. return -1;
  235. x = (long)PyLong_AsUnsignedLong(wrapped);
  236. Py_DECREF(wrapped);
  237. if (x == -1 && PyErr_Occurred())
  238. return -1;
  239. *p = x;
  240. } else {
  241. return -1;
  242. }
  243. }
  244. return 0;
  245. }
  246. static int
  247. get_wrapped_ulong(PyObject *v, unsigned long *p)
  248. {
  249. long x = (long)PyLong_AsUnsignedLong(v);
  250. if (x == -1 && PyErr_Occurred()) {
  251. PyObject *wrapped;
  252. PyErr_Clear();
  253. #ifdef PY_STRUCT_FLOAT_COERCE
  254. if (PyFloat_Check(v)) {
  255. PyObject *o;
  256. int res;
  257. PyErr_Clear();
  258. if (PyErr_WarnEx(PyExc_DeprecationWarning, FLOAT_COERCE, 2) < 0)
  259. return -1;
  260. o = PyNumber_Int(v);
  261. if (o == NULL)
  262. return -1;
  263. res = get_wrapped_ulong(o, p);
  264. Py_DECREF(o);
  265. return res;
  266. }
  267. #endif
  268. wrapped = PyNumber_And(v, pylong_ulong_mask);
  269. if (wrapped == NULL)
  270. return -1;
  271. if (PyErr_WarnEx(PyExc_DeprecationWarning, INT_OVERFLOW, 2) < 0) {
  272. Py_DECREF(wrapped);
  273. return -1;
  274. }
  275. x = (long)PyLong_AsUnsignedLong(wrapped);
  276. Py_DECREF(wrapped);
  277. if (x == -1 && PyErr_Occurred())
  278. return -1;
  279. }
  280. *p = (unsigned long)x;
  281. return 0;
  282. }
  283. #define RANGE_ERROR(x, f, flag, mask) \
  284. do { \
  285. if (_range_error(f, flag) < 0) \
  286. return -1; \
  287. else \
  288. (x) &= (mask); \
  289. } while (0)
  290. #else
  291. #define get_wrapped_long get_long
  292. #define get_wrapped_ulong get_ulong
  293. #define RANGE_ERROR(x, f, flag, mask) return _range_error(f, flag)
  294. #endif
  295. /* Floating point helpers */
  296. static PyObject *
  297. unpack_float(const char *p, /* start of 4-byte string */
  298. int le) /* true for little-endian, false for big-endian */
  299. {
  300. double x;
  301. x = _PyFloat_Unpack4((unsigned char *)p, le);
  302. if (x == -1.0 && PyErr_Occurred())
  303. return NULL;
  304. return PyFloat_FromDouble(x);
  305. }
  306. static PyObject *
  307. unpack_double(const char *p, /* start of 8-byte string */
  308. int le) /* true for little-endian, false for big-endian */
  309. {
  310. double x;
  311. x = _PyFloat_Unpack8((unsigned char *)p, le);
  312. if (x == -1.0 && PyErr_Occurred())
  313. return NULL;
  314. return PyFloat_FromDouble(x);
  315. }
  316. /* Helper to format the range error exceptions */
  317. static int
  318. _range_error(const formatdef *f, int is_unsigned)
  319. {
  320. /* ulargest is the largest unsigned value with f->size bytes.
  321. * Note that the simpler:
  322. * ((size_t)1 << (f->size * 8)) - 1
  323. * doesn't work when f->size == sizeof(size_t) because C doesn't
  324. * define what happens when a left shift count is >= the number of
  325. * bits in the integer being shifted; e.g., on some boxes it doesn't
  326. * shift at all when they're equal.
  327. */
  328. const size_t ulargest = (size_t)-1 >> ((SIZEOF_SIZE_T - f->size)*8);
  329. assert(f->size >= 1 && f->size <= SIZEOF_SIZE_T);
  330. if (is_unsigned)
  331. PyErr_Format(StructError,
  332. "'%c' format requires 0 <= number <= %zu",
  333. f->format,
  334. ulargest);
  335. else {
  336. const Py_ssize_t largest = (Py_ssize_t)(ulargest >> 1);
  337. PyErr_Format(StructError,
  338. "'%c' format requires %zd <= number <= %zd",
  339. f->format,
  340. ~ largest,
  341. largest);
  342. }
  343. #ifdef PY_STRUCT_OVERFLOW_MASKING
  344. {
  345. PyObject *ptype, *pvalue, *ptraceback;
  346. PyObject *msg;
  347. int rval;
  348. PyErr_Fetch(&ptype, &pvalue, &ptraceback);
  349. assert(pvalue != NULL);
  350. msg = PyObject_Str(pvalue);
  351. Py_XDECREF(ptype);
  352. Py_XDECREF(pvalue);
  353. Py_XDECREF(ptraceback);
  354. if (msg == NULL)
  355. return -1;
  356. rval = PyErr_WarnEx(PyExc_DeprecationWarning,
  357. PyString_AS_STRING(msg), 2);
  358. Py_DECREF(msg);
  359. if (rval == 0)
  360. return 0;
  361. }
  362. #endif
  363. return -1;
  364. }
  365. /* A large number of small routines follow, with names of the form
  366. [bln][up]_TYPE
  367. [bln] distiguishes among big-endian, little-endian and native.
  368. [pu] distiguishes between pack (to struct) and unpack (from struct).
  369. TYPE is one of char, byte, ubyte, etc.
  370. */
  371. /* Native mode routines. ****************************************************/
  372. /* NOTE:
  373. In all n[up]_<type> routines handling types larger than 1 byte, there is
  374. *no* guarantee that the p pointer is properly aligned for each type,
  375. therefore memcpy is called. An intermediate variable is used to
  376. compensate for big-endian architectures.
  377. Normally both the intermediate variable and the memcpy call will be
  378. skipped by C optimisation in little-endian architectures (gcc >= 2.91
  379. does this). */
  380. static PyObject *
  381. nu_char(const char *p, const formatdef *f)
  382. {
  383. return PyString_FromStringAndSize(p, 1);
  384. }
  385. static PyObject *
  386. nu_byte(const char *p, const formatdef *f)
  387. {
  388. return PyInt_FromLong((long) *(signed char *)p);
  389. }
  390. static PyObject *
  391. nu_ubyte(const char *p, const formatdef *f)
  392. {
  393. return PyInt_FromLong((long) *(unsigned char *)p);
  394. }
  395. static PyObject *
  396. nu_short(const char *p, const formatdef *f)
  397. {
  398. short x;
  399. memcpy((char *)&x, p, sizeof x);
  400. return PyInt_FromLong((long)x);
  401. }
  402. static PyObject *
  403. nu_ushort(const char *p, const formatdef *f)
  404. {
  405. unsigned short x;
  406. memcpy((char *)&x, p, sizeof x);
  407. return PyInt_FromLong((long)x);
  408. }
  409. static PyObject *
  410. nu_int(const char *p, const formatdef *f)
  411. {
  412. int x;
  413. memcpy((char *)&x, p, sizeof x);
  414. return PyInt_FromLong((long)x);
  415. }
  416. static PyObject *
  417. nu_uint(const char *p, const formatdef *f)
  418. {
  419. unsigned int x;
  420. memcpy((char *)&x, p, sizeof x);
  421. #if (SIZEOF_LONG > SIZEOF_INT)
  422. return PyInt_FromLong((long)x);
  423. #else
  424. if (x <= ((unsigned int)LONG_MAX))
  425. return PyInt_FromLong((long)x);
  426. return PyLong_FromUnsignedLong((unsigned long)x);
  427. #endif
  428. }
  429. static PyObject *
  430. nu_long(const char *p, const formatdef *f)
  431. {
  432. long x;
  433. memcpy((char *)&x, p, sizeof x);
  434. return PyInt_FromLong(x);
  435. }
  436. static PyObject *
  437. nu_ulong(const char *p, const formatdef *f)
  438. {
  439. unsigned long x;
  440. memcpy((char *)&x, p, sizeof x);
  441. if (x <= LONG_MAX)
  442. return PyInt_FromLong((long)x);
  443. return PyLong_FromUnsignedLong(x);
  444. }
  445. /* Native mode doesn't support q or Q unless the platform C supports
  446. long long (or, on Windows, __int64). */
  447. #ifdef HAVE_LONG_LONG
  448. static PyObject *
  449. nu_longlong(const char *p, const formatdef *f)
  450. {
  451. PY_LONG_LONG x;
  452. memcpy((char *)&x, p, sizeof x);
  453. if (x >= LONG_MIN && x <= LONG_MAX)
  454. return PyInt_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long));
  455. return PyLong_FromLongLong(x);
  456. }
  457. static PyObject *
  458. nu_ulonglong(const char *p, const formatdef *f)
  459. {
  460. unsigned PY_LONG_LONG x;
  461. memcpy((char *)&x, p, sizeof x);
  462. if (x <= LONG_MAX)
  463. return PyInt_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long));
  464. return PyLong_FromUnsignedLongLong(x);
  465. }
  466. #endif
  467. static PyObject *
  468. nu_bool(const char *p, const formatdef *f)
  469. {
  470. BOOL_TYPE x;
  471. memcpy((char *)&x, p, sizeof x);
  472. return PyBool_FromLong(x != 0);
  473. }
  474. static PyObject *
  475. nu_float(const char *p, const formatdef *f)
  476. {
  477. float x;
  478. memcpy((char *)&x, p, sizeof x);
  479. return PyFloat_FromDouble((double)x);
  480. }
  481. static PyObject *
  482. nu_double(const char *p, const formatdef *f)
  483. {
  484. double x;
  485. memcpy((char *)&x, p, sizeof x);
  486. return PyFloat_FromDouble(x);
  487. }
  488. static PyObject *
  489. nu_void_p(const char *p, const formatdef *f)
  490. {
  491. void *x;
  492. memcpy((char *)&x, p, sizeof x);
  493. return PyLong_FromVoidPtr(x);
  494. }
  495. static int
  496. np_byte(char *p, PyObject *v, const formatdef *f)
  497. {
  498. long x;
  499. if (get_long(v, &x) < 0)
  500. return -1;
  501. if (x < -128 || x > 127){
  502. PyErr_SetString(StructError,
  503. "byte format requires -128 <= number <= 127");
  504. return -1;
  505. }
  506. *p = (char)x;
  507. return 0;
  508. }
  509. static int
  510. np_ubyte(char *p, PyObject *v, const formatdef *f)
  511. {
  512. long x;
  513. if (get_long(v, &x) < 0)
  514. return -1;
  515. if (x < 0 || x > 255){
  516. PyErr_SetString(StructError,
  517. "ubyte format requires 0 <= number <= 255");
  518. return -1;
  519. }
  520. *p = (char)x;
  521. return 0;
  522. }
  523. static int
  524. np_char(char *p, PyObject *v, const formatdef *f)
  525. {
  526. if (!PyString_Check(v) || PyString_Size(v) != 1) {
  527. PyErr_SetString(StructError,
  528. "char format require string of length 1");
  529. return -1;
  530. }
  531. *p = *PyString_AsString(v);
  532. return 0;
  533. }
  534. static int
  535. np_short(char *p, PyObject *v, const formatdef *f)
  536. {
  537. long x;
  538. short y;
  539. if (get_long(v, &x) < 0)
  540. return -1;
  541. if (x < SHRT_MIN || x > SHRT_MAX){
  542. PyErr_SetString(StructError,
  543. "short format requires " STRINGIFY(SHRT_MIN)
  544. " <= number <= " STRINGIFY(SHRT_MAX));
  545. return -1;
  546. }
  547. y = (short)x;
  548. memcpy(p, (char *)&y, sizeof y);
  549. return 0;
  550. }
  551. static int
  552. np_ushort(char *p, PyObject *v, const formatdef *f)
  553. {
  554. long x;
  555. unsigned short y;
  556. if (get_long(v, &x) < 0)
  557. return -1;
  558. if (x < 0 || x > USHRT_MAX){
  559. PyErr_SetString(StructError,
  560. "ushort format requires 0 <= number <= " STRINGIFY(USHRT_MAX));
  561. return -1;
  562. }
  563. y = (unsigned short)x;
  564. memcpy(p, (char *)&y, sizeof y);
  565. return 0;
  566. }
  567. static int
  568. np_int(char *p, PyObject *v, const formatdef *f)
  569. {
  570. long x;
  571. int y;
  572. if (get_long(v, &x) < 0)
  573. return -1;
  574. #if (SIZEOF_LONG > SIZEOF_INT)
  575. if ((x < ((long)INT_MIN)) || (x > ((long)INT_MAX)))
  576. RANGE_ERROR(x, f, 0, -1);
  577. #endif
  578. y = (int)x;
  579. memcpy(p, (char *)&y, sizeof y);
  580. return 0;
  581. }
  582. static int
  583. np_uint(char *p, PyObject *v, const formatdef *f)
  584. {
  585. unsigned long x;
  586. unsigned int y;
  587. if (get_wrapped_ulong(v, &x) < 0)
  588. return -1;
  589. y = (unsigned int)x;
  590. #if (SIZEOF_LONG > SIZEOF_INT)
  591. if (x > ((unsigned long)UINT_MAX))
  592. RANGE_ERROR(y, f, 1, -1);
  593. #endif
  594. memcpy(p, (char *)&y, sizeof y);
  595. return 0;
  596. }
  597. static int
  598. np_long(char *p, PyObject *v, const formatdef *f)
  599. {
  600. long x;
  601. if (get_long(v, &x) < 0)
  602. return -1;
  603. memcpy(p, (char *)&x, sizeof x);
  604. return 0;
  605. }
  606. static int
  607. np_ulong(char *p, PyObject *v, const formatdef *f)
  608. {
  609. unsigned long x;
  610. if (get_wrapped_ulong(v, &x) < 0)
  611. return -1;
  612. memcpy(p, (char *)&x, sizeof x);
  613. return 0;
  614. }
  615. #ifdef HAVE_LONG_LONG
  616. static int
  617. np_longlong(char *p, PyObject *v, const formatdef *f)
  618. {
  619. PY_LONG_LONG x;
  620. if (get_longlong(v, &x) < 0)
  621. return -1;
  622. memcpy(p, (char *)&x, sizeof x);
  623. return 0;
  624. }
  625. static int
  626. np_ulonglong(char *p, PyObject *v, const formatdef *f)
  627. {
  628. unsigned PY_LONG_LONG x;
  629. if (get_ulonglong(v, &x) < 0)
  630. return -1;
  631. memcpy(p, (char *)&x, sizeof x);
  632. return 0;
  633. }
  634. #endif
  635. static int
  636. np_bool(char *p, PyObject *v, const formatdef *f)
  637. {
  638. BOOL_TYPE y;
  639. y = PyObject_IsTrue(v);
  640. memcpy(p, (char *)&y, sizeof y);
  641. return 0;
  642. }
  643. static int
  644. np_float(char *p, PyObject *v, const formatdef *f)
  645. {
  646. float x = (float)PyFloat_AsDouble(v);
  647. if (x == -1 && PyErr_Occurred()) {
  648. PyErr_SetString(StructError,
  649. "required argument is not a float");
  650. return -1;
  651. }
  652. memcpy(p, (char *)&x, sizeof x);
  653. return 0;
  654. }
  655. static int
  656. np_double(char *p, PyObject *v, const formatdef *f)
  657. {
  658. double x = PyFloat_AsDouble(v);
  659. if (x == -1 && PyErr_Occurred()) {
  660. PyErr_SetString(StructError,
  661. "required argument is not a float");
  662. return -1;
  663. }
  664. memcpy(p, (char *)&x, sizeof(double));
  665. return 0;
  666. }
  667. static int
  668. np_void_p(char *p, PyObject *v, const formatdef *f)
  669. {
  670. void *x;
  671. v = get_pylong(v);
  672. if (v == NULL)
  673. return -1;
  674. assert(PyLong_Check(v));
  675. x = PyLong_AsVoidPtr(v);
  676. Py_DECREF(v);
  677. if (x == NULL && PyErr_Occurred())
  678. return -1;
  679. memcpy(p, (char *)&x, sizeof x);
  680. return 0;
  681. }
  682. static formatdef native_table[] = {
  683. {'x', sizeof(char), 0, NULL},
  684. {'b', sizeof(char), 0, nu_byte, np_byte},
  685. {'B', sizeof(char), 0, nu_ubyte, np_ubyte},
  686. {'c', sizeof(char), 0, nu_char, np_char},
  687. {'s', sizeof(char), 0, NULL},
  688. {'p', sizeof(char), 0, NULL},
  689. {'h', sizeof(short), SHORT_ALIGN, nu_short, np_short},
  690. {'H', sizeof(short), SHORT_ALIGN, nu_ushort, np_ushort},
  691. {'i', sizeof(int), INT_ALIGN, nu_int, np_int},
  692. {'I', sizeof(int), INT_ALIGN, nu_uint, np_uint},
  693. {'l', sizeof(long), LONG_ALIGN, nu_long, np_long},
  694. {'L', sizeof(long), LONG_ALIGN, nu_ulong, np_ulong},
  695. #ifdef HAVE_LONG_LONG
  696. {'q', sizeof(PY_LONG_LONG), LONG_LONG_ALIGN, nu_longlong, np_longlong},
  697. {'Q', sizeof(PY_LONG_LONG), LONG_LONG_ALIGN, nu_ulonglong,np_ulonglong},
  698. #endif
  699. {'?', sizeof(BOOL_TYPE), BOOL_ALIGN, nu_bool, np_bool},
  700. {'f', sizeof(float), FLOAT_ALIGN, nu_float, np_float},
  701. {'d', sizeof(double), DOUBLE_ALIGN, nu_double, np_double},
  702. {'P', sizeof(void *), VOID_P_ALIGN, nu_void_p, np_void_p},
  703. {0}
  704. };
  705. /* Big-endian routines. *****************************************************/
  706. static PyObject *
  707. bu_int(const char *p, const formatdef *f)
  708. {
  709. long x = 0;
  710. Py_ssize_t i = f->size;
  711. const unsigned char *bytes = (const unsigned char *)p;
  712. do {
  713. x = (x<<8) | *bytes++;
  714. } while (--i > 0);
  715. /* Extend the sign bit. */
  716. if (SIZEOF_LONG > f->size)
  717. x |= -(x & (1L << ((8 * f->size) - 1)));
  718. return PyInt_FromLong(x);
  719. }
  720. static PyObject *
  721. bu_uint(const char *p, const formatdef *f)
  722. {
  723. unsigned long x = 0;
  724. Py_ssize_t i = f->size;
  725. const unsigned char *bytes = (const unsigned char *)p;
  726. do {
  727. x = (x<<8) | *bytes++;
  728. } while (--i > 0);
  729. if (x <= LONG_MAX)
  730. return PyInt_FromLong((long)x);
  731. return PyLong_FromUnsignedLong(x);
  732. }
  733. static PyObject *
  734. bu_longlong(const char *p, const formatdef *f)
  735. {
  736. #ifdef HAVE_LONG_LONG
  737. PY_LONG_LONG x = 0;
  738. Py_ssize_t i = f->size;
  739. const unsigned char *bytes = (const unsigned char *)p;
  740. do {
  741. x = (x<<8) | *bytes++;
  742. } while (--i > 0);
  743. /* Extend the sign bit. */
  744. if (SIZEOF_LONG_LONG > f->size)
  745. x |= -(x & ((PY_LONG_LONG)1 << ((8 * f->size) - 1)));
  746. if (x >= LONG_MIN && x <= LONG_MAX)
  747. return PyInt_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long));
  748. return PyLong_FromLongLong(x);
  749. #else
  750. return _PyLong_FromByteArray((const unsigned char *)p,
  751. 8,
  752. 0, /* little-endian */
  753. 1 /* signed */);
  754. #endif
  755. }
  756. static PyObject *
  757. bu_ulonglong(const char *p, const formatdef *f)
  758. {
  759. #ifdef HAVE_LONG_LONG
  760. unsigned PY_LONG_LONG x = 0;
  761. Py_ssize_t i = f->size;
  762. const unsigned char *bytes = (const unsigned char *)p;
  763. do {
  764. x = (x<<8) | *bytes++;
  765. } while (--i > 0);
  766. if (x <= LONG_MAX)
  767. return PyInt_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long));
  768. return PyLong_FromUnsignedLongLong(x);
  769. #else
  770. return _PyLong_FromByteArray((const unsigned char *)p,
  771. 8,
  772. 0, /* little-endian */
  773. 0 /* signed */);
  774. #endif
  775. }
  776. static PyObject *
  777. bu_float(const char *p, const formatdef *f)
  778. {
  779. return unpack_float(p, 0);
  780. }
  781. static PyObject *
  782. bu_double(const char *p, const formatdef *f)
  783. {
  784. return unpack_double(p, 0);
  785. }
  786. static PyObject *
  787. bu_bool(const char *p, const formatdef *f)
  788. {
  789. char x;
  790. memcpy((char *)&x, p, sizeof x);
  791. return PyBool_FromLong(x != 0);
  792. }
  793. static int
  794. bp_int(char *p, PyObject *v, const formatdef *f)
  795. {
  796. long x;
  797. Py_ssize_t i;
  798. if (get_wrapped_long(v, &x) < 0)
  799. return -1;
  800. i = f->size;
  801. if (i != SIZEOF_LONG) {
  802. if ((i == 2) && (x < -32768 || x > 32767))
  803. RANGE_ERROR(x, f, 0, 0xffffL);
  804. #if (SIZEOF_LONG != 4)
  805. else if ((i == 4) && (x < -2147483648L || x > 2147483647L))
  806. RANGE_ERROR(x, f, 0, 0xffffffffL);
  807. #endif
  808. #ifdef PY_STRUCT_OVERFLOW_MASKING
  809. else if ((i == 1) && (x < -128 || x > 127))
  810. RANGE_ERROR(x, f, 0, 0xffL);
  811. #endif
  812. }
  813. do {
  814. p[--i] = (char)x;
  815. x >>= 8;
  816. } while (i > 0);
  817. return 0;
  818. }
  819. static int
  820. bp_uint(char *p, PyObject *v, const formatdef *f)
  821. {
  822. unsigned long x;
  823. Py_ssize_t i;
  824. if (get_wrapped_ulong(v, &x) < 0)
  825. return -1;
  826. i = f->size;
  827. if (i != SIZEOF_LONG) {
  828. unsigned long maxint = 1;
  829. maxint <<= (unsigned long)(i * 8);
  830. if (x >= maxint)
  831. RANGE_ERROR(x, f, 1, maxint - 1);
  832. }
  833. do {
  834. p[--i] = (char)x;
  835. x >>= 8;
  836. } while (i > 0);
  837. return 0;
  838. }
  839. static int
  840. bp_longlong(char *p, PyObject *v, const formatdef *f)
  841. {
  842. int res;
  843. v = get_pylong(v);
  844. if (v == NULL)
  845. return -1;
  846. res = _PyLong_AsByteArray((PyLongObject *)v,
  847. (unsigned char *)p,
  848. 8,
  849. 0, /* little_endian */
  850. 1 /* signed */);
  851. Py_DECREF(v);
  852. return res;
  853. }
  854. static int
  855. bp_ulonglong(char *p, PyObject *v, const formatdef *f)
  856. {
  857. int res;
  858. v = get_pylong(v);
  859. if (v == NULL)
  860. return -1;
  861. res = _PyLong_AsByteArray((PyLongObject *)v,
  862. (unsigned char *)p,
  863. 8,
  864. 0, /* little_endian */
  865. 0 /* signed */);
  866. Py_DECREF(v);
  867. return res;
  868. }
  869. static int
  870. bp_float(char *p, PyObject *v, const formatdef *f)
  871. {
  872. double x = PyFloat_AsDouble(v);
  873. if (x == -1 && PyErr_Occurred()) {
  874. PyErr_SetString(StructError,
  875. "required argument is not a float");
  876. return -1;
  877. }
  878. return _PyFloat_Pack4(x, (unsigned char *)p, 0);
  879. }
  880. static int
  881. bp_double(char *p, PyObject *v, const formatdef *f)
  882. {
  883. double x = PyFloat_AsDouble(v);
  884. if (x == -1 && PyErr_Occurred()) {
  885. PyErr_SetString(StructError,
  886. "required argument is not a float");
  887. return -1;
  888. }
  889. return _PyFloat_Pack8(x, (unsigned char *)p, 0);
  890. }
  891. static int
  892. bp_bool(char *p, PyObject *v, const formatdef *f)
  893. {
  894. char y;
  895. y = PyObject_IsTrue(v);
  896. memcpy(p, (char *)&y, sizeof y);
  897. return 0;
  898. }
  899. static formatdef bigendian_table[] = {
  900. {'x', 1, 0, NULL},
  901. #ifdef PY_STRUCT_OVERFLOW_MASKING
  902. /* Native packers do range checking without overflow masking. */
  903. {'b', 1, 0, nu_byte, bp_int},
  904. {'B', 1, 0, nu_ubyte, bp_uint},
  905. #else
  906. {'b', 1, 0, nu_byte, np_byte},
  907. {'B', 1, 0, nu_ubyte, np_ubyte},
  908. #endif
  909. {'c', 1, 0, nu_char, np_char},
  910. {'s', 1, 0, NULL},
  911. {'p', 1, 0, NULL},
  912. {'h', 2, 0, bu_int, bp_int},
  913. {'H', 2, 0, bu_uint, bp_uint},
  914. {'i', 4, 0, bu_int, bp_int},
  915. {'I', 4, 0, bu_uint, bp_uint},
  916. {'l', 4, 0, bu_int, bp_int},
  917. {'L', 4, 0, bu_uint, bp_uint},
  918. {'q', 8, 0, bu_longlong, bp_longlong},
  919. {'Q', 8, 0, bu_ulonglong, bp_ulonglong},
  920. {'?', 1, 0, bu_bool, bp_bool},
  921. {'f', 4, 0, bu_float, bp_float},
  922. {'d', 8, 0, bu_double, bp_double},
  923. {0}
  924. };
  925. /* Little-endian routines. *****************************************************/
  926. static PyObject *
  927. lu_int(const char *p, const formatdef *f)
  928. {
  929. long x = 0;
  930. Py_ssize_t i = f->size;
  931. const unsigned char *bytes = (const unsigned char *)p;
  932. do {
  933. x = (x<<8) | bytes[--i];
  934. } while (i > 0);
  935. /* Extend the sign bit. */
  936. if (SIZEOF_LONG > f->size)
  937. x |= -(x & (1L << ((8 * f->size) - 1)));
  938. return PyInt_FromLong(x);
  939. }
  940. static PyObject *
  941. lu_uint(const char *p, const formatdef *f)
  942. {
  943. unsigned long x = 0;
  944. Py_ssize_t i = f->size;
  945. const unsigned char *bytes = (const unsigned char *)p;
  946. do {
  947. x = (x<<8) | bytes[--i];
  948. } while (i > 0);
  949. if (x <= LONG_MAX)
  950. return PyInt_FromLong((long)x);
  951. return PyLong_FromUnsignedLong((long)x);
  952. }
  953. static PyObject *
  954. lu_longlong(const char *p, const formatdef *f)
  955. {
  956. #ifdef HAVE_LONG_LONG
  957. PY_LONG_LONG x = 0;
  958. Py_ssize_t i = f->size;
  959. const unsigned char *bytes = (const unsigned char *)p;
  960. do {
  961. x = (x<<8) | bytes[--i];
  962. } while (i > 0);
  963. /* Extend the sign bit. */
  964. if (SIZEOF_LONG_LONG > f->size)
  965. x |= -(x & ((PY_LONG_LONG)1 << ((8 * f->size) - 1)));
  966. if (x >= LONG_MIN && x <= LONG_MAX)
  967. return PyInt_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long));
  968. return PyLong_FromLongLong(x);
  969. #else
  970. return _PyLong_FromByteArray((const unsigned char *)p,
  971. 8,
  972. 1, /* little-endian */
  973. 1 /* signed */);
  974. #endif
  975. }
  976. static PyObject *
  977. lu_ulonglong(const char *p, const formatdef *f)
  978. {
  979. #ifdef HAVE_LONG_LONG
  980. unsigned PY_LONG_LONG x = 0;
  981. Py_ssize_t i = f->size;
  982. const unsigned char *bytes = (const unsigned char *)p;
  983. do {
  984. x = (x<<8) | bytes[--i];
  985. } while (i > 0);
  986. if (x <= LONG_MAX)
  987. return PyInt_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long));
  988. return PyLong_FromUnsignedLongLong(x);
  989. #else
  990. return _PyLong_FromByteArray((const unsigned char *)p,
  991. 8,
  992. 1, /* little-endian */
  993. 0 /* signed */);
  994. #endif
  995. }
  996. static PyObject *
  997. lu_float(const char *p, const formatdef *f)
  998. {
  999. return unpack_float(p, 1);
  1000. }
  1001. static PyObject *
  1002. lu_double(const char *p, const formatdef *f)
  1003. {
  1004. return unpack_double(p, 1);
  1005. }
  1006. static int
  1007. lp_int(char *p, PyObject *v, const formatdef *f)
  1008. {
  1009. long x;
  1010. Py_ssize_t i;
  1011. if (get_wrapped_long(v, &x) < 0)
  1012. return -1;
  1013. i = f->size;
  1014. if (i != SIZEOF_LONG) {
  1015. if ((i == 2) && (x < -32768 || x > 32767))
  1016. RANGE_ERROR(x, f, 0, 0xffffL);
  1017. #if (SIZEOF_LONG != 4)
  1018. else if ((i == 4) && (x < -2147483648L || x > 2147483647L))
  1019. RANGE_ERROR(x, f, 0, 0xffffffffL);
  1020. #endif
  1021. #ifdef PY_STRUCT_OVERFLOW_MASKING
  1022. else if ((i == 1) && (x < -128 || x > 127))
  1023. RANGE_ERROR(x, f, 0, 0xffL);
  1024. #endif
  1025. }
  1026. do {
  1027. *p++ = (char)x;
  1028. x >>= 8;
  1029. } while (--i > 0);
  1030. return 0;
  1031. }
  1032. static int
  1033. lp_uint(char *p, PyObject *v, const formatdef *f)
  1034. {
  1035. unsigned long x;
  1036. Py_ssize_t i;
  1037. if (get_wrapped_ulong(v, &x) < 0)
  1038. return -1;
  1039. i = f->size;
  1040. if (i != SIZEOF_LONG) {
  1041. unsigned long maxint = 1;
  1042. maxint <<= (unsigned long)(i * 8);
  1043. if (x >= maxint)
  1044. RANGE_ERROR(x, f, 1, maxint - 1);
  1045. }
  1046. do {
  1047. *p++ = (char)x;
  1048. x >>= 8;
  1049. } while (--i > 0);
  1050. return 0;
  1051. }
  1052. static int
  1053. lp_longlong(char *p, PyObject *v, const formatdef *f)
  1054. {
  1055. int res;
  1056. v = get_pylong(v);
  1057. if (v == NULL)
  1058. return -1;
  1059. res = _PyLong_AsByteArray((PyLongObject*)v,
  1060. (unsigned char *)p,
  1061. 8,
  1062. 1, /* little_endian */
  1063. 1 /* signed */);
  1064. Py_DECREF(v);
  1065. return res;
  1066. }
  1067. static int
  1068. lp_ulonglong(char *p, PyObject *v, const formatdef *f)
  1069. {
  1070. int res;
  1071. v = get_pylong(v);
  1072. if (v == NULL)
  1073. return -1;
  1074. res = _PyLong_AsByteArray((PyLongObject*)v,
  1075. (unsigned char *)p,
  1076. 8,
  1077. 1, /* little_endian */
  1078. 0 /* signed */);
  1079. Py_DECREF(v);
  1080. return res;
  1081. }
  1082. static int
  1083. lp_float(char *p, PyObject *v, const formatdef *f)
  1084. {
  1085. double x = PyFloat_AsDouble(v);
  1086. if (x == -1 && PyErr_Occurred()) {
  1087. PyErr_SetString(StructError,
  1088. "required argument is not a float");
  1089. return -1;
  1090. }
  1091. return _PyFloat_Pack4(x, (unsigned char *)p, 1);
  1092. }
  1093. static int
  1094. lp_double(char *p, PyObject *v, const formatdef *f)
  1095. {
  1096. double x = PyFloat_AsDouble(v);
  1097. if (x == -1 && PyErr_Occurred()) {
  1098. PyErr_SetString(StructError,
  1099. "required argument is not a float");
  1100. return -1;
  1101. }
  1102. return _PyFloat_Pack8(x, (unsigned char *)p, 1);
  1103. }
  1104. static formatdef lilendian_table[] = {
  1105. {'x', 1, 0, NULL},
  1106. #ifdef PY_STRUCT_OVERFLOW_MASKING
  1107. /* Native packers do range checking without overflow masking. */
  1108. {'b', 1, 0, nu_byte, lp_int},
  1109. {'B', 1, 0, nu_ubyte, lp_uint},
  1110. #else
  1111. {'b', 1, 0, nu_byte, np_byte},
  1112. {'B', 1, 0, nu_ubyte, np_ubyte},
  1113. #endif
  1114. {'c', 1, 0, nu_char, np_char},
  1115. {'s', 1, 0, NULL},
  1116. {'p', 1, 0, NULL},
  1117. {'h', 2, 0, lu_int, lp_int},
  1118. {'H', 2, 0, lu_uint, lp_uint},
  1119. {'i', 4, 0, lu_int, lp_int},
  1120. {'I', 4, 0, lu_uint, lp_uint},
  1121. {'l', 4, 0, lu_int, lp_int},
  1122. {'L', 4, 0, lu_uint, lp_uint},
  1123. {'q', 8, 0, lu_longlong, lp_longlong},
  1124. {'Q', 8, 0, lu_ulonglong, lp_ulonglong},
  1125. {'?', 1, 0, bu_bool, bp_bool}, /* Std rep not endian dep,
  1126. but potentially different from native rep -- reuse bx_bool funcs. */
  1127. {'f', 4, 0, lu_float, lp_float},
  1128. {'d', 8, 0, lu_double, lp_double},
  1129. {0}
  1130. };
  1131. static const formatdef *
  1132. whichtable(char **pfmt)
  1133. {
  1134. const char *fmt = (*pfmt)++; /* May be backed out of later */
  1135. switch (*fmt) {
  1136. case '<':
  1137. return lilendian_table;
  1138. case '>':
  1139. case '!': /* Network byte order is big-endian */
  1140. return bigendian_table;
  1141. case '=': { /* Host byte order -- different from native in aligment! */
  1142. int n = 1;
  1143. char *p = (char *) &n;
  1144. if (*p == 1)
  1145. return lilendian_table;
  1146. else
  1147. return bigendian_table;
  1148. }
  1149. default:
  1150. --*pfmt; /* Back out of pointer increment */
  1151. /* Fall through */
  1152. case '@':
  1153. return native_table;
  1154. }
  1155. }
  1156. /* Get the table entry for a format code */
  1157. static const formatdef *
  1158. getentry(int c, const formatdef *f)
  1159. {
  1160. for (; f->format != '\0'; f++) {
  1161. if (f->format == c) {
  1162. return f;
  1163. }
  1164. }
  1165. PyErr_SetString(StructError, "bad char in struct format");
  1166. return NULL;
  1167. }
  1168. /* Align a size according to a format code */
  1169. static int
  1170. align(Py_ssize_t size, char c, const formatdef *e)
  1171. {
  1172. if (e->format == c) {
  1173. if (e->alignment) {
  1174. size = ((size + e->alignment - 1)
  1175. / e->alignment)
  1176. * e->alignment;
  1177. }
  1178. }
  1179. return size;
  1180. }
  1181. /* calculate the size of a format string */
  1182. static int
  1183. prepare_s(PyStructObject *self)
  1184. {
  1185. const formatdef *f;
  1186. const formatdef *e;
  1187. formatcode *codes;
  1188. const char *s;
  1189. const char *fmt;
  1190. char c;
  1191. Py_ssize_t size, len, num, itemsize, x;
  1192. fmt = PyString_AS_STRING(self->s_format);
  1193. f = whichtable((char **)&fmt);
  1194. s = fmt;
  1195. size = 0;
  1196. len = 0;
  1197. while ((c = *s++) != '\0') {
  1198. if (isspace(Py_CHARMASK(c)))
  1199. continue;
  1200. if ('0' <= c && c <= '9') {
  1201. num = c - '0';
  1202. while ('0' <= (c = *s++) && c <= '9') {
  1203. x = num*10 + (c - '0');
  1204. if (x/10 != num) {
  1205. PyErr_SetString(
  1206. StructError,
  1207. "overflow in item count");
  1208. return -1;
  1209. }
  1210. num = x;
  1211. }
  1212. if (c == '\0')
  1213. break;
  1214. }
  1215. else
  1216. num = 1;
  1217. e = getentry(c, f);
  1218. if (e == NULL)
  1219. return -1;
  1220. switch (c) {
  1221. case 's': /* fall through */
  1222. case 'p': len++; break;
  1223. case 'x': break;
  1224. default: len += num; break;
  1225. }
  1226. itemsize = e->size;
  1227. size = align(size, c, e);
  1228. x = num * itemsize;
  1229. size += x;
  1230. if (x/itemsize != num || size < 0) {
  1231. PyErr_SetString(StructError,
  1232. "total struct size too long");
  1233. return -1;
  1234. }
  1235. }
  1236. /* check for overflow */
  1237. if ((len + 1) > (PY_SSIZE_T_MAX / sizeof(formatcode))) {
  1238. PyErr_NoMemory();
  1239. return -1;
  1240. }
  1241. self->s_size = size;
  1242. self->s_len = len;
  1243. codes = PyMem_MALLOC((len + 1) * sizeof(formatcode));
  1244. if (codes == NULL) {
  1245. PyErr_NoMemory();
  1246. return -1;
  1247. }
  1248. self->s_codes = codes;
  1249. s = fmt;
  1250. size = 0;
  1251. while ((c = *s++) != '\0') {
  1252. if (isspace(Py_CHARMASK(c)))
  1253. continue;
  1254. if ('0' <= c && c <= '9') {
  1255. num = c - '0';
  1256. while ('0' <= (c = *s++) && c <= '9')
  1257. num = num*10 + (c - '0');
  1258. if (c == '\0')
  1259. break;
  1260. }
  1261. else
  1262. num = 1;
  1263. e = getentry(c, f);
  1264. size = align(size, c, e);
  1265. if (c == 's' || c == 'p') {
  1266. codes->offset = size;
  1267. codes->size = num;
  1268. codes->fmtdef = e;
  1269. codes++;
  1270. size += num;
  1271. } else if (c == 'x') {
  1272. size += num;
  1273. } else {
  1274. while (--num >= 0) {
  1275. codes->offset = size;
  1276. codes->size = e->size;
  1277. codes->fmtdef = e;
  1278. codes++;
  1279. size += e->size;
  1280. }
  1281. }
  1282. }
  1283. codes->fmtdef = NULL;
  1284. codes->offset = size;
  1285. codes->size = 0;
  1286. return 0;
  1287. }
  1288. static PyObject *
  1289. s_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
  1290. {
  1291. PyObject *self;
  1292. assert(type != NULL && type->tp_alloc != NULL);
  1293. self = type->tp_alloc(type, 0);
  1294. if (self != NULL) {
  1295. PyStructObject *s = (PyStructObject*)self;
  1296. Py_INCREF(Py_None);
  1297. s->s_format = Py_None;
  1298. s->s_codes = NULL;
  1299. s->s_size = -1;
  1300. s->s_len = -1;
  1301. }
  1302. return self;
  1303. }
  1304. static int
  1305. s_init(PyObject *self, PyObject *args, PyObject *kwds)
  1306. {
  1307. PyStructObject *soself = (PyStructObject *)self;
  1308. PyObject *o_format = NULL;
  1309. int ret = 0;
  1310. static char *kwlist[] = {"format", 0};
  1311. assert(PyStruct_Check(self));
  1312. if (!PyArg_ParseTupleAndKeywords(args, kwds, "S:Struct", kwlist,
  1313. &o_format))
  1314. return -1;
  1315. Py_INCREF(o_format);
  1316. Py_CLEAR(soself->s_format);
  1317. soself->s_format = o_format;
  1318. ret = prepare_s(soself);
  1319. return ret;
  1320. }
  1321. static void
  1322. s_dealloc(PyStructObject *s)
  1323. {
  1324. if (s->weakreflist != NULL)
  1325. PyObject_ClearWeakRefs((PyObject *)s);
  1326. if (s->s_codes != NULL) {
  1327. PyMem_FREE(s->s_codes);
  1328. }
  1329. Py_XDECREF(s->s_format);
  1330. Py_TYPE(s)->tp_free((PyObject *)s);
  1331. }
  1332. static PyObject *
  1333. s_unpack_internal(PyStructObject *soself, char *startfrom) {
  1334. formatcode *code;
  1335. Py_ssize_t i = 0;
  1336. PyObject *result = PyTuple_New(soself->s_len);
  1337. if (result == NULL)
  1338. return NULL;
  1339. for (code = soself->s_codes; code->fmtdef != NULL; code++) {
  1340. PyObject *v;
  1341. const formatdef *e = code->fmtdef;
  1342. const char *res = startfrom + code->offset;
  1343. if (e->format == 's') {
  1344. v = PyString_FromStringAndSize(res, code->size);
  1345. } else if (e->format == 'p') {
  1346. Py_ssize_t n = *(unsigned char*)res;
  1347. if (n >= code->size)
  1348. n = code->size - 1;
  1349. v = PyString_FromStringAndSize(res + 1, n);
  1350. } else {
  1351. v = e->unpack(res, e);
  1352. }
  1353. if (v == NULL)
  1354. goto fail;
  1355. PyTuple_SET_ITEM(result, i++, v);
  1356. }
  1357. return result;
  1358. fail:
  1359. Py_DECREF(result);
  1360. return NULL;
  1361. }
  1362. PyDoc_STRVAR(s_unpack__doc__,
  1363. "S.unpack(str) -> (v1, v2, ...)\n\
  1364. \n\
  1365. Return tuple containing values unpacked according to this Struct's format.\n\
  1366. Requires len(str) == self.size. See struct.__doc__ for more on format\n\
  1367. strings.");
  1368. static PyObject *
  1369. s_unpack(PyObject *self, PyObject *inputstr)
  1370. {
  1371. char *start;
  1372. Py_ssize_t len;
  1373. PyObject *args=NULL, *result;
  1374. PyStructObject *soself = (PyStructObject *)self;
  1375. assert(PyStruct_Check(self));
  1376. assert(soself->s_codes != NULL);
  1377. if (inputstr == NULL)
  1378. goto fail;
  1379. if (PyString_Check(inputstr) &&
  1380. PyString_GET_SIZE(inputstr) == soself->s_size) {
  1381. return s_unpack_internal(soself, PyString_AS_STRING(inputstr));
  1382. }
  1383. args = PyTuple_Pack(1, inputstr);
  1384. if (args == NULL)
  1385. return NULL;
  1386. if (!PyArg_ParseTuple(args, "s#:unpack", &start, &len))
  1387. goto fail;
  1388. if (soself->s_size != len)
  1389. goto fail;
  1390. result = s_unpack_internal(soself, start);
  1391. Py_DECREF(args);
  1392. return result;
  1393. fail:
  1394. Py_XDECREF(args);
  1395. PyErr_Format(StructError,
  1396. "unpack requires a string argument of length %zd",
  1397. soself->s_size);
  1398. return NULL;
  1399. }
  1400. PyDoc_STRVAR(s_unpack_from__doc__,
  1401. "S.unpack_from(buffer[, offset]) -> (v1, v2, ...)\n\
  1402. \n\
  1403. Return tuple containing values unpacked according to this Struct's format.\n\
  1404. Unlike unpack, unpack_from can unpack values from any object supporting\n\
  1405. the buffer API, not just str. Requires len(buffer[offset:]) >= self.size.\n\
  1406. See struct.__doc__ for more on format strings.");
  1407. static PyObject *
  1408. s_unpack_from(PyObject *self, PyObject *args, PyObject *kwds)
  1409. {
  1410. static char *kwlist[] = {"buffer", "offset", 0};
  1411. #if (PY_VERSION_HEX < 0x02050000)
  1412. static char *fmt = "z#|i:unpack_from";
  1413. #else
  1414. static char *fmt = "z#|n:unpack_from";
  1415. #endif
  1416. Py_ssize_t buffer_len = 0, offset = 0;
  1417. char *buffer = NULL;
  1418. PyStructObject *soself = (PyStructObject *)self;
  1419. assert(PyStruct_Check(self));
  1420. assert(soself->s_codes != NULL);
  1421. if (!PyArg_ParseTupleAndKeywords(args, kwds, fmt, kwlist,
  1422. &buffer, &buffer_len, &offset))
  1423. return NULL;
  1424. if (buffer == NULL) {
  1425. PyErr_Format(StructError,
  1426. "unpack_from requires a buffer argument");
  1427. return NULL;
  1428. }
  1429. if (offset < 0)
  1430. offset += buffer_len;
  1431. if (offset < 0 || (buffer_len - offset) < soself->s_size) {
  1432. PyErr_Format(StructError,
  1433. "unpack_from requires a buffer of at least %zd bytes",
  1434. soself->s_size);
  1435. return NULL;
  1436. }
  1437. return s_unpack_internal(soself, buffer + offset);
  1438. }
  1439. /*
  1440. * Guts of the pack function.
  1441. *
  1442. * Takes a struct object, a tuple of arguments, and offset in that tuple of
  1443. * argument for where to start processing the arguments for packing, and a
  1444. * character buffer for writing the packed string. The caller must insure
  1445. * that the buffer may contain the required length for packing the arguments.
  1446. * 0 is returned on success, 1 is returned if there is an error.
  1447. *
  1448. */
  1449. static int
  1450. s_pack_internal(PyStructObject *soself, PyObject *args, int offset, char* buf)
  1451. {
  1452. formatcode *code;
  1453. /* XXX(nnorwitz): why does i need to be a local? can we use
  1454. the offset parameter or do we need the wider width? */
  1455. Py_ssize_t i;
  1456. memset(buf, '\0', soself->s_size);
  1457. i = offset;
  1458. for (code = soself->s_codes; code->fmtdef != NULL; code++) {
  1459. Py_ssize_t n;
  1460. PyObject *v = PyTuple_GET_ITEM(args, i++);
  1461. const formatdef *e = code->fmtdef;
  1462. char *res = buf + code->offset;
  1463. if (e->format == 's') {
  1464. if (!PyString_Check(v)) {
  1465. PyErr_SetString(StructError,
  1466. "argument for 's' must be a string");
  1467. return -1;
  1468. }
  1469. n = PyString_GET_SIZE(v);
  1470. if (n > code->size)
  1471. n = code->size;
  1472. if (n > 0)
  1473. memcpy(res, PyString_AS_STRING(v), n);
  1474. } else if (e->format == 'p') {
  1475. if (!PyString_Check(v)) {
  1476. PyErr_SetString(StructError,
  1477. "argument for 'p' must be a string");
  1478. return -1;
  1479. }
  1480. n = PyString_GET_SIZE(v);
  1481. if (n > (code->size - 1))
  1482. n = code->size - 1;
  1483. if (n > 0)
  1484. memcpy(res + 1, PyString_AS_STRING(v), n);
  1485. if (n > 255)
  1486. n = 255;
  1487. *res = Py_SAFE_DOWNCAST(n, Py_ssize_t, unsigned char);
  1488. } else {
  1489. if (e->pack(res, v, e) < 0) {
  1490. if (PyLong_Check(v) && PyErr_ExceptionMatches(PyExc_OverflowError))
  1491. PyErr_SetString(StructError,
  1492. "long too large to convert to int");
  1493. return -1;
  1494. }
  1495. }
  1496. }
  1497. /* Success */
  1498. return 0;
  1499. }
  1500. PyDoc_STRVAR(s_pack__doc__,
  1501. "S.pack(v1, v2, ...) -> string\n\
  1502. \n\
  1503. Return a string containing values v1, v2, ... packed according to this\n\
  1504. Struct's format. See struct.__doc__ for more on format strings.");
  1505. static PyObject *
  1506. s_pack(PyObject *self, PyObject *args)
  1507. {
  1508. PyStructObject *soself;
  1509. PyObject *result;
  1510. /* Validate arguments. */
  1511. soself = (PyStructObject *)self;
  1512. assert(PyStruct_Check(self));
  1513. assert(soself->s_codes != NULL);
  1514. if (PyTuple_GET_SIZE(args) != soself->s_len)
  1515. {
  1516. PyErr_Format(StructError,
  1517. "pack requires exactly %zd arguments", soself->s_len);
  1518. return NULL;
  1519. }
  1520. /* Allocate a new string */
  1521. result = PyString_FromStringAndSize((char *)NULL, soself->s_size);
  1522. if (result == NULL)
  1523. return NULL;
  1524. /* Call the guts */
  1525. if ( s_pack_internal(soself, args, 0, PyString_AS_STRING(result)) != 0 ) {
  1526. Py_DECREF(result);
  1527. return NULL;
  1528. }
  1529. return result;
  1530. }
  1531. PyDoc_STRVAR(s_pack_into__doc__,
  1532. "S.pack_into(buffer, offset, v1, v2, ...)\n\
  1533. \n\
  1534. Pack the values v1, v2, ... according to this Struct's format, write \n\
  1535. the packed bytes into the writable buffer buf starting at offset. Note\n\
  1536. that the offset is not an optional argument. See struct.__doc__ for \n\
  1537. more on format strings.");
  1538. static PyObject *
  1539. s_pack_into(PyObject *self, PyObject *args)
  1540. {
  1541. PyStructObject *soself;
  1542. char *buffer;
  1543. Py_ssize_t buffer_len, offset;
  1544. /* Validate arguments. +1 is for the first arg as buffer. */
  1545. soself = (PyStructObject *)self;
  1546. assert(PyStruct_Check(self));
  1547. assert(soself->s_codes != NULL);
  1548. if (PyTuple_GET_SIZE(args) != (soself->s_len + 2))
  1549. {
  1550. PyErr_Format(StructError,
  1551. "pack_into requires exactly %zd arguments",
  1552. (soself->s_len + 2));
  1553. return NULL;
  1554. }
  1555. /* Extract a writable memory buffer from the first argument */
  1556. if ( PyObject_AsWriteBuffer(PyTuple_GET_ITEM(args, 0),
  1557. (void**)&buffer, &buffer_len) == -1 ) {
  1558. return NULL;
  1559. }
  1560. assert( buffer_len >= 0 );
  1561. /* Extract the offset from the first argument */
  1562. offset = PyInt_AsSsize_t(PyTuple_GET_ITEM(args, 1));
  1563. if (offset == -1 && PyErr_Occurred())
  1564. return NULL;
  1565. /* Support negative offsets. */
  1566. if (offset < 0)
  1567. offset += buffer_len;
  1568. /* Check boundaries */
  1569. if (offset < 0 || (buffer_len - offset) < soself->s_size) {
  1570. PyErr_Format(StructError,
  1571. "pack_into requires a buffer of at least %zd bytes",
  1572. soself->s_size);
  1573. return NULL;
  1574. }
  1575. /* Call the guts */
  1576. if ( s_pack_internal(soself, args, 2, buffer + offset) != 0 ) {
  1577. return NULL;
  1578. }
  1579. Py_RETURN_NONE;
  1580. }
  1581. static PyObject *
  1582. s_get_format(PyStructObject *self, void *unused)
  1583. {
  1584. Py_INCREF(self->s_format);
  1585. return self->s_format;
  1586. }
  1587. static PyObject *
  1588. s_get_size(PyStructObject *self, void *unused)
  1589. {
  1590. return PyInt_FromSsize_t(self->s_size);
  1591. }
  1592. /* List of functions */
  1593. static struct PyMethodDef s_methods[] = {
  1594. {"pack", s_pack, METH_VARARGS, s_pack__doc__},
  1595. {"pack_into", s_pack_into, METH_VARARGS, s_pack_into__doc__},
  1596. {"unpack", s_unpack, METH_O, s_unpack__doc__},
  1597. {"unpack_from", (PyCFunction)s_unpack_from, METH_VARARGS|METH_KEYWORDS,
  1598. s_unpack_from__doc__},
  1599. {NULL, NULL} /* sentinel */
  1600. };
  1601. PyDoc_STRVAR(s__doc__, "Compiled struct object");
  1602. #define OFF(x) offsetof(PyStructObject, x)
  1603. static PyGetSetDef s_getsetlist[] = {
  1604. {"format", (getter)s_get_format, (setter)NULL, "struct format string", NULL},
  1605. {"size", (getter)s_get_size, (setter)NULL, "struct size in bytes", NULL},
  1606. {NULL} /* sentinel */
  1607. };
  1608. static
  1609. PyTypeObject PyStructType = {
  1610. PyVarObject_HEAD_INIT(NULL, 0)
  1611. "Struct",
  1612. sizeof(PyStructObject),
  1613. 0,
  1614. (destructor)s_dealloc, /* tp_dealloc */
  1615. 0, /* tp_print */
  1616. 0, /* tp_getattr */
  1617. 0, /* tp_setattr */
  1618. 0, /* tp_compare */
  1619. 0, /* tp_repr */
  1620. 0, /* tp_as_number */
  1621. 0, /* tp_as_sequence */
  1622. 0, /* tp_as_mapping */
  1623. 0, /* tp_hash */
  1624. 0, /* tp_call */
  1625. 0, /* tp_str */
  1626. PyObject_GenericGetAttr, /* tp_getattro */
  1627. PyObject_GenericSetAttr, /* tp_setattro */
  1628. 0, /* tp_as_buffer */
  1629. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_WEAKREFS,/* tp_flags */
  1630. s__doc__, /* tp_doc */
  1631. 0, /* tp_traverse */
  1632. 0, /* tp_clear */
  1633. 0, /* tp_richcompare */
  1634. offsetof(PyStructObject, weakreflist), /* tp_weaklistoffset */
  1635. 0, /* tp_iter */
  1636. 0, /* tp_iternext */
  1637. s_methods, /* tp_methods */
  1638. NULL, /* tp_members */
  1639. s_getsetlist, /* tp_getset */
  1640. 0, /* tp_base */
  1641. 0, /* tp_dict */
  1642. 0, /* tp_descr_get */
  1643. 0, /* tp_descr_set */
  1644. 0, /* tp_dictoffset */
  1645. s_init, /* tp_init */
  1646. PyType_GenericAlloc,/* tp_alloc */
  1647. s_new, /* tp_new */
  1648. PyObject_Del, /* tp_free */
  1649. };
  1650. /* ---- Standalone functions ---- */
  1651. #define MAXCACHE 100
  1652. static PyObject *cache = NULL;
  1653. static PyObject *
  1654. cache_struct(PyObject *fmt)
  1655. {
  1656. PyObject * s_object;
  1657. if (cache == NULL) {
  1658. cache = PyDict_New();
  1659. if (cache == NULL)
  1660. return NULL;
  1661. }
  1662. s_object = PyDict_GetItem(cache, fmt);
  1663. if (s_object != NULL) {
  1664. Py_INCREF(s_object);
  1665. return s_object;
  1666. }
  1667. s_object = PyObject_CallFunctionObjArgs((PyObject *)(&PyStructType), fmt, NULL);
  1668. if (s_object != NULL) {
  1669. if (PyDict_Size(cache) >= MAXCACHE)
  1670. PyDict_Clear(cache);
  1671. /* Attempt to cache the result */
  1672. if (PyDict_SetItem(cache, fmt, s_object) == -1)
  1673. PyErr_Clear();
  1674. }
  1675. return s_object;
  1676. }
  1677. PyDoc_STRVAR(clearcache_doc,
  1678. "Clear the internal cache.");
  1679. static PyObject *
  1680. clearcache(PyObject *self)
  1681. {
  1682. Py_CLEAR(cache);
  1683. Py_RETURN_NONE;
  1684. }
  1685. PyDoc_STRVAR(calcsize_doc,
  1686. "Return size of C struct described by format string fmt.");
  1687. static PyObject *
  1688. calcsize(PyObject *self, PyObject *fmt)
  1689. {
  1690. Py_ssize_t n;
  1691. PyObject *s_object = cache_struct(fmt);
  1692. if (s_object == NULL)
  1693. return NULL;
  1694. n = ((PyStructObject *)s_object)->s_size;
  1695. Py_DECREF(s_object);
  1696. return PyInt_FromSsize_t(n);
  1697. }
  1698. PyDoc_STRVAR(pack_doc,
  1699. "Return string containing values v1, v2, ... packed according to fmt.");
  1700. static PyObject *
  1701. pack(PyObject *self, PyObject *args)
  1702. {
  1703. PyObject *s_object, *fmt, *newargs, *result;
  1704. Py_ssize_t n = PyTuple_GET_SIZE(args);
  1705. if (n == 0) {
  1706. PyErr_SetString(PyExc_TypeError, "missing format argument");
  1707. return NULL;
  1708. }
  1709. fmt = PyTuple_GET_ITEM(args, 0);
  1710. newargs = PyTuple_GetSlice(args, 1, n);
  1711. if (newargs == NULL)
  1712. return NULL;
  1713. s_object = cache_struct(fmt);
  1714. if (s_object == NULL) {
  1715. Py_DECREF(newargs);
  1716. return NULL;
  1717. }
  1718. result = s_pack(s_object, newargs);
  1719. Py_DECREF(newargs);
  1720. Py_DECREF(s_object);
  1721. return result;
  1722. }
  1723. PyDoc_STRVAR(pack_into_doc,
  1724. "Pack the values v1, v2, ... according to fmt.\n\
  1725. Write the packed bytes into the writable buffer buf starting at offset.");
  1726. static PyObject *
  1727. pack_into(PyObject *self, PyObject *args)
  1728. {
  1729. PyObject *s_object, *fmt, *newargs, *result;
  1730. Py_ssize_t n = PyTuple_GET_SIZE(args);
  1731. if (n == 0) {
  1732. PyErr_SetString(PyExc_TypeError, "missing format argument");
  1733. return NULL;
  1734. }
  1735. fmt = PyTuple_GET_ITEM(args, 0);
  1736. newargs = PyTuple_GetSlice(args, 1, n);
  1737. if (newargs == NULL)
  1738. return NULL;
  1739. s_object = cache_struct(fmt);
  1740. if (s_object == NULL) {
  1741. Py_DECREF(newargs);
  1742. return NULL;
  1743. }
  1744. result = s_pack_into(s_object, newargs);
  1745. Py_DECREF(newargs);
  1746. Py_DECREF(s_object);
  1747. return result;
  1748. }
  1749. PyDoc_STRVAR(unpack_doc,
  1750. "Unpack the string containing packed C structure data, according to fmt.\n\
  1751. Requires len(string) == calcsize(fmt).");
  1752. static PyObject *
  1753. unpack(PyObject *self, PyObject *args)
  1754. {
  1755. PyObject *s_object, *fmt, *inputstr, *result;
  1756. if (!PyArg_UnpackTuple(args, "unpack", 2, 2, &fmt, &inputstr))
  1757. return NULL;
  1758. s_object = cache_struct(fmt);
  1759. if (s_object == NULL)
  1760. return NULL;
  1761. result = s_unpack(s_object, inputstr);
  1762. Py_DECREF(s_object);
  1763. return result;
  1764. }
  1765. PyDoc_STRVAR(unpack_from_doc,
  1766. "Unpack the buffer, containing packed C structure data, according to\n\
  1767. fmt, starting at offset. Requires len(buffer[offset:]) >= calcsize(fmt).");
  1768. static PyObject *
  1769. unpack_from(PyObject *self, PyObject *args, PyObject *kwds)
  1770. {
  1771. PyObject *s_object, *fmt, *newargs, *result;
  1772. Py_ssize_t n = PyTuple_GET_SIZE(args);
  1773. if (n == 0) {
  1774. PyErr_SetString(PyExc_TypeError, "missing format argument");
  1775. return NULL;
  1776. }
  1777. fmt = PyTuple_GET_ITEM(args, 0);
  1778. newargs = PyTuple_GetSlice(args, 1, n);
  1779. if (newargs == NULL)
  1780. return NULL;
  1781. s_object = cache_struct(fmt);
  1782. if (s_object == NULL) {
  1783. Py_DECREF(newargs);
  1784. return NULL;
  1785. }
  1786. result = s_unpack_from(s_object, newargs, kwds);
  1787. Py_DECREF(newargs);
  1788. Py_DECREF(s_object);
  1789. return result;
  1790. }
  1791. static struct PyMethodDef module_functions[] = {
  1792. {"_clearcache", (PyCFunction)clearcache, METH_NOARGS, clearcache_doc},
  1793. {"calcsize", calcsize, METH_O, calcsize_doc},
  1794. {"pack", pack, METH_VARARGS, pack_doc},
  1795. {"pack_into", pack_into, METH_VARARGS, pack_into_doc},
  1796. {"unpack", unpack, METH_VARARGS, unpack_doc},
  1797. {"unpack_from", (PyCFunction)unpack_from,
  1798. METH_VARARGS|METH_KEYWORDS, unpack_from_doc},
  1799. {NULL, NULL} /* sentinel */
  1800. };
  1801. /* Module initialization */
  1802. PyDoc_STRVAR(module_doc,
  1803. "Functions to convert between Python values and C structs.\n\
  1804. Python strings are used to hold the data representing the C struct\n\
  1805. and also as format strings to describe the layout of data in the C struct.\n\
  1806. \n\
  1807. The optional first format char indicates byte order, size and alignment:\n\
  1808. @: native order, size & alignment (default)\n\
  1809. =: native order, std. size & alignment\n\
  1810. <: little-endian, std. size & alignment\n\
  1811. >: big-endian, std. size & alignment\n\
  1812. !: same as >\n\
  1813. \n\
  1814. The remaining chars indicate types of args and must match exactly;\n\
  1815. these can be preceded by a decimal repeat count:\n\
  1816. x: pad byte (no data); c:char; b:signed byte; B:unsigned byte;\n\
  1817. h:short; H:unsigned short; i:int; I:unsigned int;\n\
  1818. l:long; L:unsigned long; f:float; d:double.\n\
  1819. Special cases (preceding decimal count indicates length):\n\
  1820. s:string (array of char); p: pascal string (with count byte).\n\
  1821. Special case (only available in native format):\n\
  1822. P:an integer type that is wide enough to hold a pointer.\n\
  1823. Special case (not in native mode unless 'long long' in platform C):\n\
  1824. q:long long; Q:unsigned long long\n\
  1825. Whitespace between formats is ignored.\n\
  1826. \n\
  1827. The variable struct.error is an exception raised on errors.\n");
  1828. PyMODINIT_FUNC
  1829. init_struct(void)
  1830. {
  1831. PyObject *ver, *m;
  1832. ver = PyString_FromString("0.2");
  1833. if (ver == NULL)
  1834. return;
  1835. m = Py_InitModule3("_struct", module_functions, module_doc);
  1836. if (m == NULL)
  1837. return;
  1838. Py_TYPE(&PyStructType) = &PyType_Type;
  1839. if (PyType_Ready(&PyStructType) < 0)
  1840. return;
  1841. #ifdef PY_STRUCT_OVERFLOW_MASKING
  1842. if (pyint_zero == NULL) {
  1843. pyint_zero = PyInt_FromLong(0);
  1844. if (pyint_zero == NULL)
  1845. return;
  1846. }
  1847. if (pylong_ulong_mask == NULL) {
  1848. #if (SIZEOF_LONG == 4)
  1849. pylong_ulong_mask = PyLong_FromString("FFFFFFFF", NULL, 16);
  1850. #else
  1851. pylong_ulong_mask = PyLong_FromString("FFFFFFFFFFFFFFFF", NULL, 16);
  1852. #endif
  1853. if (pylong_ulong_mask == NULL)
  1854. return;
  1855. }
  1856. #else
  1857. /* This speed trick can't be used until overflow masking goes away, because
  1858. native endian always raises exceptions instead of overflow masking. */
  1859. /* Check endian and swap in faster functions */
  1860. {
  1861. int one = 1;
  1862. formatdef *native = native_table;
  1863. formatdef *other, *ptr;
  1864. if ((int)*(unsigned char*)&one)
  1865. other = lilendian_table;
  1866. else
  1867. other = bigendian_table;
  1868. /* Scan through the native table, find a matching
  1869. entry in the endian table and swap in the
  1870. native implementations whenever possible
  1871. (64-bit platforms may not have "standard" sizes) */
  1872. while (native->format != '\0' && other->format != '\0') {
  1873. ptr = other;
  1874. while (ptr->format != '\0') {
  1875. if (ptr->format == native->format) {
  1876. /* Match faster when formats are
  1877. listed in the same order */
  1878. if (ptr == other)
  1879. other++;
  1880. /* Only use the trick if the
  1881. size matches */
  1882. if (ptr->size != native->size)
  1883. break;
  1884. /* Skip float and double, could be
  1885. "unknown" float format */
  1886. if (ptr->format == 'd' || ptr->format == 'f')
  1887. break;
  1888. ptr->pack = native->pack;
  1889. ptr->unpack = native->unpack;
  1890. break;
  1891. }
  1892. ptr++;
  1893. }
  1894. native++;
  1895. }
  1896. }
  1897. #endif
  1898. /* Add some symbolic constants to the module */
  1899. if (StructError == NULL) {
  1900. StructError = PyErr_NewException("struct.error", NULL, NULL);
  1901. if (StructError == NULL)
  1902. return;
  1903. }
  1904. Py_INCREF(StructError);
  1905. PyModule_AddObject(m, "error", StructError);
  1906. Py_INCREF((PyObject*)&PyStructType);
  1907. PyModule_AddObject(m, "Struct", (PyObject*)&PyStructType);
  1908. PyModule_AddObject(m, "__version__", ver);
  1909. PyModule_AddIntConstant(m, "_PY_STRUCT_RANGE_CHECKING", 1);
  1910. #ifdef PY_STRUCT_OVERFLOW_MASKING
  1911. PyModule_AddIntConstant(m, "_PY_STRUCT_OVERFLOW_MASKING", 1);
  1912. #endif
  1913. #ifdef PY_STRUCT_FLOAT_COERCE
  1914. PyModule_AddIntConstant(m, "_PY_STRUCT_FLOAT_COERCE", 1);
  1915. #endif
  1916. }