blob: 0a09fd8a82ff1916c3c6edef5d61ba396e664011 [file] [log] [blame]
Benjamin Peterson4ae19462008-07-31 15:03:40 +00001/* struct module -- pack values into and (out of) bytes objects */
Thomas Wouters477c8d52006-05-27 19:21:47 +00002
3/* New version supporting byte order, alignment and size options,
4 character strings, and unsigned numbers */
5
6#define PY_SSIZE_T_CLEAN
7
8#include "Python.h"
Thomas Wouters477c8d52006-05-27 19:21:47 +00009#include "structmember.h"
10#include <ctype.h>
11
12static PyTypeObject PyStructType;
13
Thomas Wouters477c8d52006-05-27 19:21:47 +000014/* The translation function for each format character is table driven */
15typedef struct _formatdef {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000016 char format;
17 Py_ssize_t size;
18 Py_ssize_t alignment;
19 PyObject* (*unpack)(const char *,
20 const struct _formatdef *);
21 int (*pack)(char *, PyObject *,
22 const struct _formatdef *);
Thomas Wouters477c8d52006-05-27 19:21:47 +000023} formatdef;
24
25typedef struct _formatcode {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000026 const struct _formatdef *fmtdef;
27 Py_ssize_t offset;
28 Py_ssize_t size;
Thomas Wouters477c8d52006-05-27 19:21:47 +000029} formatcode;
30
31/* Struct object interface */
32
33typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000034 PyObject_HEAD
35 Py_ssize_t s_size;
36 Py_ssize_t s_len;
37 formatcode *s_codes;
38 PyObject *s_format;
39 PyObject *weakreflist; /* List of weak references */
Thomas Wouters477c8d52006-05-27 19:21:47 +000040} PyStructObject;
41
42
43#define PyStruct_Check(op) PyObject_TypeCheck(op, &PyStructType)
Christian Heimes90aa7642007-12-19 02:45:37 +000044#define PyStruct_CheckExact(op) (Py_TYPE(op) == &PyStructType)
Thomas Wouters477c8d52006-05-27 19:21:47 +000045
46
47/* Exception */
48
49static PyObject *StructError;
50
51
52/* Define various structs to figure out the alignments of types */
53
54
55typedef struct { char c; short x; } st_short;
56typedef struct { char c; int x; } st_int;
57typedef struct { char c; long x; } st_long;
58typedef struct { char c; float x; } st_float;
59typedef struct { char c; double x; } st_double;
60typedef struct { char c; void *x; } st_void_p;
61
62#define SHORT_ALIGN (sizeof(st_short) - sizeof(short))
63#define INT_ALIGN (sizeof(st_int) - sizeof(int))
64#define LONG_ALIGN (sizeof(st_long) - sizeof(long))
65#define FLOAT_ALIGN (sizeof(st_float) - sizeof(float))
66#define DOUBLE_ALIGN (sizeof(st_double) - sizeof(double))
67#define VOID_P_ALIGN (sizeof(st_void_p) - sizeof(void *))
68
69/* We can't support q and Q in native mode unless the compiler does;
70 in std mode, they're 8 bytes on all platforms. */
71#ifdef HAVE_LONG_LONG
72typedef struct { char c; PY_LONG_LONG x; } s_long_long;
73#define LONG_LONG_ALIGN (sizeof(s_long_long) - sizeof(PY_LONG_LONG))
74#endif
75
Thomas Woutersb2137042007-02-01 18:02:27 +000076#ifdef HAVE_C99_BOOL
77#define BOOL_TYPE _Bool
78typedef struct { char c; _Bool x; } s_bool;
79#define BOOL_ALIGN (sizeof(s_bool) - sizeof(BOOL_TYPE))
80#else
81#define BOOL_TYPE char
82#define BOOL_ALIGN 0
83#endif
84
Thomas Wouters477c8d52006-05-27 19:21:47 +000085#define STRINGIFY(x) #x
86
87#ifdef __powerc
88#pragma options align=reset
89#endif
90
Mark Dickinson055a3fb2010-04-03 15:26:31 +000091/* Helper for integer format codes: converts an arbitrary Python object to a
92 PyLongObject if possible, otherwise fails. Caller should decref. */
Thomas Wouters477c8d52006-05-27 19:21:47 +000093
94static PyObject *
95get_pylong(PyObject *v)
96{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000097 assert(v != NULL);
98 if (!PyLong_Check(v)) {
99 /* Not an integer; try to use __index__ to convert. */
100 if (PyIndex_Check(v)) {
101 v = PyNumber_Index(v);
102 if (v == NULL)
103 return NULL;
104 }
105 else {
106 PyErr_SetString(StructError,
107 "required argument is not an integer");
108 return NULL;
109 }
110 }
111 else
112 Py_INCREF(v);
Mark Dickinsonea835e72009-04-19 20:40:33 +0000113
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000114 assert(PyLong_Check(v));
115 return v;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000116}
117
Mark Dickinsonea835e72009-04-19 20:40:33 +0000118/* Helper routine to get a C long and raise the appropriate error if it isn't
119 one */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000120
121static int
122get_long(PyObject *v, long *p)
123{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000124 long x;
Mark Dickinsonea835e72009-04-19 20:40:33 +0000125
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000126 v = get_pylong(v);
127 if (v == NULL)
128 return -1;
129 assert(PyLong_Check(v));
130 x = PyLong_AsLong(v);
131 Py_DECREF(v);
132 if (x == (long)-1 && PyErr_Occurred()) {
133 if (PyErr_ExceptionMatches(PyExc_OverflowError))
134 PyErr_SetString(StructError,
135 "argument out of range");
136 return -1;
137 }
138 *p = x;
139 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000140}
141
142
143/* Same, but handling unsigned long */
144
145static int
146get_ulong(PyObject *v, unsigned long *p)
147{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000148 unsigned long x;
Mark Dickinsonea835e72009-04-19 20:40:33 +0000149
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000150 v = get_pylong(v);
151 if (v == NULL)
152 return -1;
153 assert(PyLong_Check(v));
154 x = PyLong_AsUnsignedLong(v);
155 Py_DECREF(v);
156 if (x == (unsigned long)-1 && PyErr_Occurred()) {
157 if (PyErr_ExceptionMatches(PyExc_OverflowError))
158 PyErr_SetString(StructError,
159 "argument out of range");
160 return -1;
161 }
162 *p = x;
163 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000164}
165
166#ifdef HAVE_LONG_LONG
167
168/* Same, but handling native long long. */
169
170static int
171get_longlong(PyObject *v, PY_LONG_LONG *p)
172{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000173 PY_LONG_LONG x;
Mark Dickinson055a3fb2010-04-03 15:26:31 +0000174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175 v = get_pylong(v);
176 if (v == NULL)
177 return -1;
178 assert(PyLong_Check(v));
179 x = PyLong_AsLongLong(v);
180 Py_DECREF(v);
181 if (x == (PY_LONG_LONG)-1 && PyErr_Occurred()) {
182 if (PyErr_ExceptionMatches(PyExc_OverflowError))
183 PyErr_SetString(StructError,
184 "argument out of range");
185 return -1;
186 }
187 *p = x;
188 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000189}
190
191/* Same, but handling native unsigned long long. */
192
193static int
194get_ulonglong(PyObject *v, unsigned PY_LONG_LONG *p)
195{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000196 unsigned PY_LONG_LONG x;
Mark Dickinson055a3fb2010-04-03 15:26:31 +0000197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000198 v = get_pylong(v);
199 if (v == NULL)
200 return -1;
201 assert(PyLong_Check(v));
202 x = PyLong_AsUnsignedLongLong(v);
203 Py_DECREF(v);
204 if (x == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred()) {
205 if (PyErr_ExceptionMatches(PyExc_OverflowError))
206 PyErr_SetString(StructError,
207 "argument out of range");
208 return -1;
209 }
210 *p = x;
211 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000212}
213
214#endif
215
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000216
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000217#define RANGE_ERROR(x, f, flag, mask) return _range_error(f, flag)
218
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000219
Thomas Wouters477c8d52006-05-27 19:21:47 +0000220/* Floating point helpers */
221
222static PyObject *
223unpack_float(const char *p, /* start of 4-byte string */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000224 int le) /* true for little-endian, false for big-endian */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000225{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000226 double x;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000227
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000228 x = _PyFloat_Unpack4((unsigned char *)p, le);
229 if (x == -1.0 && PyErr_Occurred())
230 return NULL;
231 return PyFloat_FromDouble(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000232}
233
234static PyObject *
235unpack_double(const char *p, /* start of 8-byte string */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000236 int le) /* true for little-endian, false for big-endian */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000237{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000238 double x;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000240 x = _PyFloat_Unpack8((unsigned char *)p, le);
241 if (x == -1.0 && PyErr_Occurred())
242 return NULL;
243 return PyFloat_FromDouble(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000244}
245
246/* Helper to format the range error exceptions */
247static int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000248_range_error(const formatdef *f, int is_unsigned)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000249{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000250 /* ulargest is the largest unsigned value with f->size bytes.
251 * Note that the simpler:
252 * ((size_t)1 << (f->size * 8)) - 1
253 * doesn't work when f->size == sizeof(size_t) because C doesn't
254 * define what happens when a left shift count is >= the number of
255 * bits in the integer being shifted; e.g., on some boxes it doesn't
256 * shift at all when they're equal.
257 */
258 const size_t ulargest = (size_t)-1 >> ((SIZEOF_SIZE_T - f->size)*8);
259 assert(f->size >= 1 && f->size <= SIZEOF_SIZE_T);
260 if (is_unsigned)
261 PyErr_Format(StructError,
262 "'%c' format requires 0 <= number <= %zu",
263 f->format,
264 ulargest);
265 else {
266 const Py_ssize_t largest = (Py_ssize_t)(ulargest >> 1);
267 PyErr_Format(StructError,
268 "'%c' format requires %zd <= number <= %zd",
269 f->format,
270 ~ largest,
271 largest);
272 }
Mark Dickinsonae681df2009-03-21 10:26:31 +0000273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000274 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000275}
276
277
278
279/* A large number of small routines follow, with names of the form
280
281 [bln][up]_TYPE
282
283 [bln] distiguishes among big-endian, little-endian and native.
284 [pu] distiguishes between pack (to struct) and unpack (from struct).
285 TYPE is one of char, byte, ubyte, etc.
286*/
287
288/* Native mode routines. ****************************************************/
289/* NOTE:
290 In all n[up]_<type> routines handling types larger than 1 byte, there is
291 *no* guarantee that the p pointer is properly aligned for each type,
292 therefore memcpy is called. An intermediate variable is used to
293 compensate for big-endian architectures.
294 Normally both the intermediate variable and the memcpy call will be
295 skipped by C optimisation in little-endian architectures (gcc >= 2.91
296 does this). */
297
298static PyObject *
299nu_char(const char *p, const formatdef *f)
300{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000301 return PyBytes_FromStringAndSize(p, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000302}
303
304static PyObject *
305nu_byte(const char *p, const formatdef *f)
306{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000307 return PyLong_FromLong((long) *(signed char *)p);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000308}
309
310static PyObject *
311nu_ubyte(const char *p, const formatdef *f)
312{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000313 return PyLong_FromLong((long) *(unsigned char *)p);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000314}
315
316static PyObject *
317nu_short(const char *p, const formatdef *f)
318{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000319 short x;
320 memcpy((char *)&x, p, sizeof x);
321 return PyLong_FromLong((long)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000322}
323
324static PyObject *
325nu_ushort(const char *p, const formatdef *f)
326{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000327 unsigned short x;
328 memcpy((char *)&x, p, sizeof x);
329 return PyLong_FromLong((long)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000330}
331
332static PyObject *
333nu_int(const char *p, const formatdef *f)
334{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000335 int x;
336 memcpy((char *)&x, p, sizeof x);
337 return PyLong_FromLong((long)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000338}
339
340static PyObject *
341nu_uint(const char *p, const formatdef *f)
342{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000343 unsigned int x;
344 memcpy((char *)&x, p, sizeof x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000345#if (SIZEOF_LONG > SIZEOF_INT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000346 return PyLong_FromLong((long)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000347#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000348 if (x <= ((unsigned int)LONG_MAX))
349 return PyLong_FromLong((long)x);
350 return PyLong_FromUnsignedLong((unsigned long)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000351#endif
352}
353
354static PyObject *
355nu_long(const char *p, const formatdef *f)
356{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000357 long x;
358 memcpy((char *)&x, p, sizeof x);
359 return PyLong_FromLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000360}
361
362static PyObject *
363nu_ulong(const char *p, const formatdef *f)
364{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000365 unsigned long x;
366 memcpy((char *)&x, p, sizeof x);
367 if (x <= LONG_MAX)
368 return PyLong_FromLong((long)x);
369 return PyLong_FromUnsignedLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000370}
371
372/* Native mode doesn't support q or Q unless the platform C supports
373 long long (or, on Windows, __int64). */
374
375#ifdef HAVE_LONG_LONG
376
377static PyObject *
378nu_longlong(const char *p, const formatdef *f)
379{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000380 PY_LONG_LONG x;
381 memcpy((char *)&x, p, sizeof x);
382 if (x >= LONG_MIN && x <= LONG_MAX)
383 return PyLong_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long));
384 return PyLong_FromLongLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000385}
386
387static PyObject *
388nu_ulonglong(const char *p, const formatdef *f)
389{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000390 unsigned PY_LONG_LONG x;
391 memcpy((char *)&x, p, sizeof x);
392 if (x <= LONG_MAX)
393 return PyLong_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long));
394 return PyLong_FromUnsignedLongLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000395}
396
397#endif
398
399static PyObject *
Thomas Woutersb2137042007-02-01 18:02:27 +0000400nu_bool(const char *p, const formatdef *f)
401{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000402 BOOL_TYPE x;
403 memcpy((char *)&x, p, sizeof x);
404 return PyBool_FromLong(x != 0);
Thomas Woutersb2137042007-02-01 18:02:27 +0000405}
406
407
408static PyObject *
Thomas Wouters477c8d52006-05-27 19:21:47 +0000409nu_float(const char *p, const formatdef *f)
410{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 float x;
412 memcpy((char *)&x, p, sizeof x);
413 return PyFloat_FromDouble((double)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000414}
415
416static PyObject *
417nu_double(const char *p, const formatdef *f)
418{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000419 double x;
420 memcpy((char *)&x, p, sizeof x);
421 return PyFloat_FromDouble(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000422}
423
424static PyObject *
425nu_void_p(const char *p, const formatdef *f)
426{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000427 void *x;
428 memcpy((char *)&x, p, sizeof x);
429 return PyLong_FromVoidPtr(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000430}
431
432static int
433np_byte(char *p, PyObject *v, const formatdef *f)
434{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000435 long x;
436 if (get_long(v, &x) < 0)
437 return -1;
438 if (x < -128 || x > 127){
439 PyErr_SetString(StructError,
440 "byte format requires -128 <= number <= 127");
441 return -1;
442 }
443 *p = (char)x;
444 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000445}
446
447static int
448np_ubyte(char *p, PyObject *v, const formatdef *f)
449{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000450 long x;
451 if (get_long(v, &x) < 0)
452 return -1;
453 if (x < 0 || x > 255){
454 PyErr_SetString(StructError,
455 "ubyte format requires 0 <= number <= 255");
456 return -1;
457 }
458 *p = (char)x;
459 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000460}
461
462static int
463np_char(char *p, PyObject *v, const formatdef *f)
464{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000465 if (!PyBytes_Check(v) || PyBytes_Size(v) != 1) {
466 PyErr_SetString(StructError,
Victor Stinnerda9ec992010-12-28 13:26:42 +0000467 "char format requires a bytes object of length 1");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000468 return -1;
469 }
470 *p = *PyBytes_AsString(v);
471 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000472}
473
474static int
475np_short(char *p, PyObject *v, const formatdef *f)
476{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 long x;
478 short y;
479 if (get_long(v, &x) < 0)
480 return -1;
481 if (x < SHRT_MIN || x > SHRT_MAX){
482 PyErr_SetString(StructError,
483 "short format requires " STRINGIFY(SHRT_MIN)
484 " <= number <= " STRINGIFY(SHRT_MAX));
485 return -1;
486 }
487 y = (short)x;
488 memcpy(p, (char *)&y, sizeof y);
489 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000490}
491
492static int
493np_ushort(char *p, PyObject *v, const formatdef *f)
494{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000495 long x;
496 unsigned short y;
497 if (get_long(v, &x) < 0)
498 return -1;
499 if (x < 0 || x > USHRT_MAX){
500 PyErr_SetString(StructError,
501 "ushort format requires 0 <= number <= " STRINGIFY(USHRT_MAX));
502 return -1;
503 }
504 y = (unsigned short)x;
505 memcpy(p, (char *)&y, sizeof y);
506 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000507}
508
509static int
510np_int(char *p, PyObject *v, const formatdef *f)
511{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 long x;
513 int y;
514 if (get_long(v, &x) < 0)
515 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000516#if (SIZEOF_LONG > SIZEOF_INT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 if ((x < ((long)INT_MIN)) || (x > ((long)INT_MAX)))
518 RANGE_ERROR(x, f, 0, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000519#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000520 y = (int)x;
521 memcpy(p, (char *)&y, sizeof y);
522 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000523}
524
525static int
526np_uint(char *p, PyObject *v, const formatdef *f)
527{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000528 unsigned long x;
529 unsigned int y;
530 if (get_ulong(v, &x) < 0)
531 return -1;
532 y = (unsigned int)x;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000533#if (SIZEOF_LONG > SIZEOF_INT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 if (x > ((unsigned long)UINT_MAX))
535 RANGE_ERROR(y, f, 1, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000536#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000537 memcpy(p, (char *)&y, sizeof y);
538 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000539}
540
541static int
542np_long(char *p, PyObject *v, const formatdef *f)
543{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000544 long x;
545 if (get_long(v, &x) < 0)
546 return -1;
547 memcpy(p, (char *)&x, sizeof x);
548 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000549}
550
551static int
552np_ulong(char *p, PyObject *v, const formatdef *f)
553{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000554 unsigned long x;
555 if (get_ulong(v, &x) < 0)
556 return -1;
557 memcpy(p, (char *)&x, sizeof x);
558 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000559}
560
561#ifdef HAVE_LONG_LONG
562
563static int
564np_longlong(char *p, PyObject *v, const formatdef *f)
565{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000566 PY_LONG_LONG x;
567 if (get_longlong(v, &x) < 0)
568 return -1;
569 memcpy(p, (char *)&x, sizeof x);
570 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000571}
572
573static int
574np_ulonglong(char *p, PyObject *v, const formatdef *f)
575{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000576 unsigned PY_LONG_LONG x;
577 if (get_ulonglong(v, &x) < 0)
578 return -1;
579 memcpy(p, (char *)&x, sizeof x);
580 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000581}
582#endif
583
Thomas Woutersb2137042007-02-01 18:02:27 +0000584
585static int
586np_bool(char *p, PyObject *v, const formatdef *f)
587{
Benjamin Petersonde73c452010-07-07 18:54:59 +0000588 int y;
589 BOOL_TYPE x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000590 y = PyObject_IsTrue(v);
Benjamin Petersonde73c452010-07-07 18:54:59 +0000591 if (y < 0)
592 return -1;
593 x = y;
594 memcpy(p, (char *)&x, sizeof x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 return 0;
Thomas Woutersb2137042007-02-01 18:02:27 +0000596}
597
Thomas Wouters477c8d52006-05-27 19:21:47 +0000598static int
599np_float(char *p, PyObject *v, const formatdef *f)
600{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000601 float x = (float)PyFloat_AsDouble(v);
602 if (x == -1 && PyErr_Occurred()) {
603 PyErr_SetString(StructError,
604 "required argument is not a float");
605 return -1;
606 }
607 memcpy(p, (char *)&x, sizeof x);
608 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000609}
610
611static int
612np_double(char *p, PyObject *v, const formatdef *f)
613{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000614 double x = PyFloat_AsDouble(v);
615 if (x == -1 && PyErr_Occurred()) {
616 PyErr_SetString(StructError,
617 "required argument is not a float");
618 return -1;
619 }
620 memcpy(p, (char *)&x, sizeof(double));
621 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000622}
623
624static int
625np_void_p(char *p, PyObject *v, const formatdef *f)
626{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 void *x;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000628
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000629 v = get_pylong(v);
630 if (v == NULL)
631 return -1;
632 assert(PyLong_Check(v));
633 x = PyLong_AsVoidPtr(v);
634 Py_DECREF(v);
635 if (x == NULL && PyErr_Occurred())
636 return -1;
637 memcpy(p, (char *)&x, sizeof x);
638 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000639}
640
641static formatdef native_table[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 {'x', sizeof(char), 0, NULL},
643 {'b', sizeof(char), 0, nu_byte, np_byte},
644 {'B', sizeof(char), 0, nu_ubyte, np_ubyte},
645 {'c', sizeof(char), 0, nu_char, np_char},
646 {'s', sizeof(char), 0, NULL},
647 {'p', sizeof(char), 0, NULL},
648 {'h', sizeof(short), SHORT_ALIGN, nu_short, np_short},
649 {'H', sizeof(short), SHORT_ALIGN, nu_ushort, np_ushort},
650 {'i', sizeof(int), INT_ALIGN, nu_int, np_int},
651 {'I', sizeof(int), INT_ALIGN, nu_uint, np_uint},
652 {'l', sizeof(long), LONG_ALIGN, nu_long, np_long},
653 {'L', sizeof(long), LONG_ALIGN, nu_ulong, np_ulong},
Thomas Wouters477c8d52006-05-27 19:21:47 +0000654#ifdef HAVE_LONG_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000655 {'q', sizeof(PY_LONG_LONG), LONG_LONG_ALIGN, nu_longlong, np_longlong},
656 {'Q', sizeof(PY_LONG_LONG), LONG_LONG_ALIGN, nu_ulonglong,np_ulonglong},
Thomas Wouters477c8d52006-05-27 19:21:47 +0000657#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000658 {'?', sizeof(BOOL_TYPE), BOOL_ALIGN, nu_bool, np_bool},
659 {'f', sizeof(float), FLOAT_ALIGN, nu_float, np_float},
660 {'d', sizeof(double), DOUBLE_ALIGN, nu_double, np_double},
661 {'P', sizeof(void *), VOID_P_ALIGN, nu_void_p, np_void_p},
662 {0}
Thomas Wouters477c8d52006-05-27 19:21:47 +0000663};
664
665/* Big-endian routines. *****************************************************/
666
667static PyObject *
668bu_int(const char *p, const formatdef *f)
669{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 long x = 0;
671 Py_ssize_t i = f->size;
672 const unsigned char *bytes = (const unsigned char *)p;
673 do {
674 x = (x<<8) | *bytes++;
675 } while (--i > 0);
676 /* Extend the sign bit. */
677 if (SIZEOF_LONG > f->size)
678 x |= -(x & (1L << ((8 * f->size) - 1)));
679 return PyLong_FromLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000680}
681
682static PyObject *
683bu_uint(const char *p, const formatdef *f)
684{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000685 unsigned long x = 0;
686 Py_ssize_t i = f->size;
687 const unsigned char *bytes = (const unsigned char *)p;
688 do {
689 x = (x<<8) | *bytes++;
690 } while (--i > 0);
691 if (x <= LONG_MAX)
692 return PyLong_FromLong((long)x);
693 return PyLong_FromUnsignedLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000694}
695
696static PyObject *
697bu_longlong(const char *p, const formatdef *f)
698{
699#ifdef HAVE_LONG_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000700 PY_LONG_LONG x = 0;
701 Py_ssize_t i = f->size;
702 const unsigned char *bytes = (const unsigned char *)p;
703 do {
704 x = (x<<8) | *bytes++;
705 } while (--i > 0);
706 /* Extend the sign bit. */
707 if (SIZEOF_LONG_LONG > f->size)
708 x |= -(x & ((PY_LONG_LONG)1 << ((8 * f->size) - 1)));
709 if (x >= LONG_MIN && x <= LONG_MAX)
710 return PyLong_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long));
711 return PyLong_FromLongLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000712#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000713 return _PyLong_FromByteArray((const unsigned char *)p,
714 8,
715 0, /* little-endian */
716 1 /* signed */);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000717#endif
718}
719
720static PyObject *
721bu_ulonglong(const char *p, const formatdef *f)
722{
723#ifdef HAVE_LONG_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000724 unsigned PY_LONG_LONG x = 0;
725 Py_ssize_t i = f->size;
726 const unsigned char *bytes = (const unsigned char *)p;
727 do {
728 x = (x<<8) | *bytes++;
729 } while (--i > 0);
730 if (x <= LONG_MAX)
731 return PyLong_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long));
732 return PyLong_FromUnsignedLongLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000733#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000734 return _PyLong_FromByteArray((const unsigned char *)p,
735 8,
736 0, /* little-endian */
737 0 /* signed */);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000738#endif
739}
740
741static PyObject *
742bu_float(const char *p, const formatdef *f)
743{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000744 return unpack_float(p, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000745}
746
747static PyObject *
748bu_double(const char *p, const formatdef *f)
749{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000750 return unpack_double(p, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000751}
752
Thomas Woutersb2137042007-02-01 18:02:27 +0000753static PyObject *
754bu_bool(const char *p, const formatdef *f)
755{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 char x;
757 memcpy((char *)&x, p, sizeof x);
758 return PyBool_FromLong(x != 0);
Thomas Woutersb2137042007-02-01 18:02:27 +0000759}
760
Thomas Wouters477c8d52006-05-27 19:21:47 +0000761static int
762bp_int(char *p, PyObject *v, const formatdef *f)
763{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000764 long x;
765 Py_ssize_t i;
766 if (get_long(v, &x) < 0)
767 return -1;
768 i = f->size;
769 if (i != SIZEOF_LONG) {
770 if ((i == 2) && (x < -32768 || x > 32767))
771 RANGE_ERROR(x, f, 0, 0xffffL);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000772#if (SIZEOF_LONG != 4)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000773 else if ((i == 4) && (x < -2147483648L || x > 2147483647L))
774 RANGE_ERROR(x, f, 0, 0xffffffffL);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000775#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000776 }
777 do {
778 p[--i] = (char)x;
779 x >>= 8;
780 } while (i > 0);
781 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000782}
783
784static int
785bp_uint(char *p, PyObject *v, const formatdef *f)
786{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 unsigned long x;
788 Py_ssize_t i;
789 if (get_ulong(v, &x) < 0)
790 return -1;
791 i = f->size;
792 if (i != SIZEOF_LONG) {
793 unsigned long maxint = 1;
794 maxint <<= (unsigned long)(i * 8);
795 if (x >= maxint)
796 RANGE_ERROR(x, f, 1, maxint - 1);
797 }
798 do {
799 p[--i] = (char)x;
800 x >>= 8;
801 } while (i > 0);
802 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000803}
804
805static int
806bp_longlong(char *p, PyObject *v, const formatdef *f)
807{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 int res;
809 v = get_pylong(v);
810 if (v == NULL)
811 return -1;
812 res = _PyLong_AsByteArray((PyLongObject *)v,
813 (unsigned char *)p,
814 8,
815 0, /* little_endian */
816 1 /* signed */);
817 Py_DECREF(v);
818 return res;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000819}
820
821static int
822bp_ulonglong(char *p, PyObject *v, const formatdef *f)
823{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000824 int res;
825 v = get_pylong(v);
826 if (v == NULL)
827 return -1;
828 res = _PyLong_AsByteArray((PyLongObject *)v,
829 (unsigned char *)p,
830 8,
831 0, /* little_endian */
832 0 /* signed */);
833 Py_DECREF(v);
834 return res;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000835}
836
837static int
838bp_float(char *p, PyObject *v, const formatdef *f)
839{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000840 double x = PyFloat_AsDouble(v);
841 if (x == -1 && PyErr_Occurred()) {
842 PyErr_SetString(StructError,
843 "required argument is not a float");
844 return -1;
845 }
846 return _PyFloat_Pack4(x, (unsigned char *)p, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000847}
848
849static int
850bp_double(char *p, PyObject *v, const formatdef *f)
851{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000852 double x = PyFloat_AsDouble(v);
853 if (x == -1 && PyErr_Occurred()) {
854 PyErr_SetString(StructError,
855 "required argument is not a float");
856 return -1;
857 }
858 return _PyFloat_Pack8(x, (unsigned char *)p, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000859}
860
Thomas Woutersb2137042007-02-01 18:02:27 +0000861static int
862bp_bool(char *p, PyObject *v, const formatdef *f)
863{
Mark Dickinsoneff5d852010-07-18 07:29:02 +0000864 int y;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000865 y = PyObject_IsTrue(v);
Benjamin Petersonde73c452010-07-07 18:54:59 +0000866 if (y < 0)
867 return -1;
Mark Dickinsoneff5d852010-07-18 07:29:02 +0000868 *p = (char)y;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000869 return 0;
Thomas Woutersb2137042007-02-01 18:02:27 +0000870}
871
Thomas Wouters477c8d52006-05-27 19:21:47 +0000872static formatdef bigendian_table[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000873 {'x', 1, 0, NULL},
874 {'b', 1, 0, nu_byte, np_byte},
875 {'B', 1, 0, nu_ubyte, np_ubyte},
876 {'c', 1, 0, nu_char, np_char},
877 {'s', 1, 0, NULL},
878 {'p', 1, 0, NULL},
879 {'h', 2, 0, bu_int, bp_int},
880 {'H', 2, 0, bu_uint, bp_uint},
881 {'i', 4, 0, bu_int, bp_int},
882 {'I', 4, 0, bu_uint, bp_uint},
883 {'l', 4, 0, bu_int, bp_int},
884 {'L', 4, 0, bu_uint, bp_uint},
885 {'q', 8, 0, bu_longlong, bp_longlong},
886 {'Q', 8, 0, bu_ulonglong, bp_ulonglong},
887 {'?', 1, 0, bu_bool, bp_bool},
888 {'f', 4, 0, bu_float, bp_float},
889 {'d', 8, 0, bu_double, bp_double},
890 {0}
Thomas Wouters477c8d52006-05-27 19:21:47 +0000891};
892
893/* Little-endian routines. *****************************************************/
894
895static PyObject *
896lu_int(const char *p, const formatdef *f)
897{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000898 long x = 0;
899 Py_ssize_t i = f->size;
900 const unsigned char *bytes = (const unsigned char *)p;
901 do {
902 x = (x<<8) | bytes[--i];
903 } while (i > 0);
904 /* Extend the sign bit. */
905 if (SIZEOF_LONG > f->size)
906 x |= -(x & (1L << ((8 * f->size) - 1)));
907 return PyLong_FromLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000908}
909
910static PyObject *
911lu_uint(const char *p, const formatdef *f)
912{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 unsigned long x = 0;
914 Py_ssize_t i = f->size;
915 const unsigned char *bytes = (const unsigned char *)p;
916 do {
917 x = (x<<8) | bytes[--i];
918 } while (i > 0);
919 if (x <= LONG_MAX)
920 return PyLong_FromLong((long)x);
921 return PyLong_FromUnsignedLong((long)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000922}
923
924static PyObject *
925lu_longlong(const char *p, const formatdef *f)
926{
927#ifdef HAVE_LONG_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 PY_LONG_LONG x = 0;
929 Py_ssize_t i = f->size;
930 const unsigned char *bytes = (const unsigned char *)p;
931 do {
932 x = (x<<8) | bytes[--i];
933 } while (i > 0);
934 /* Extend the sign bit. */
935 if (SIZEOF_LONG_LONG > f->size)
936 x |= -(x & ((PY_LONG_LONG)1 << ((8 * f->size) - 1)));
937 if (x >= LONG_MIN && x <= LONG_MAX)
938 return PyLong_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long));
939 return PyLong_FromLongLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000940#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 return _PyLong_FromByteArray((const unsigned char *)p,
942 8,
943 1, /* little-endian */
944 1 /* signed */);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000945#endif
946}
947
948static PyObject *
949lu_ulonglong(const char *p, const formatdef *f)
950{
951#ifdef HAVE_LONG_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 unsigned PY_LONG_LONG x = 0;
953 Py_ssize_t i = f->size;
954 const unsigned char *bytes = (const unsigned char *)p;
955 do {
956 x = (x<<8) | bytes[--i];
957 } while (i > 0);
958 if (x <= LONG_MAX)
959 return PyLong_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long));
960 return PyLong_FromUnsignedLongLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000961#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000962 return _PyLong_FromByteArray((const unsigned char *)p,
963 8,
964 1, /* little-endian */
965 0 /* signed */);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000966#endif
967}
968
969static PyObject *
970lu_float(const char *p, const formatdef *f)
971{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 return unpack_float(p, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000973}
974
975static PyObject *
976lu_double(const char *p, const formatdef *f)
977{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 return unpack_double(p, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000979}
980
981static int
982lp_int(char *p, PyObject *v, const formatdef *f)
983{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000984 long x;
985 Py_ssize_t i;
986 if (get_long(v, &x) < 0)
987 return -1;
988 i = f->size;
989 if (i != SIZEOF_LONG) {
990 if ((i == 2) && (x < -32768 || x > 32767))
991 RANGE_ERROR(x, f, 0, 0xffffL);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000992#if (SIZEOF_LONG != 4)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 else if ((i == 4) && (x < -2147483648L || x > 2147483647L))
994 RANGE_ERROR(x, f, 0, 0xffffffffL);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000995#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000996 }
997 do {
998 *p++ = (char)x;
999 x >>= 8;
1000 } while (--i > 0);
1001 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001002}
1003
1004static int
1005lp_uint(char *p, PyObject *v, const formatdef *f)
1006{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001007 unsigned long x;
1008 Py_ssize_t i;
1009 if (get_ulong(v, &x) < 0)
1010 return -1;
1011 i = f->size;
1012 if (i != SIZEOF_LONG) {
1013 unsigned long maxint = 1;
1014 maxint <<= (unsigned long)(i * 8);
1015 if (x >= maxint)
1016 RANGE_ERROR(x, f, 1, maxint - 1);
1017 }
1018 do {
1019 *p++ = (char)x;
1020 x >>= 8;
1021 } while (--i > 0);
1022 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001023}
1024
1025static int
1026lp_longlong(char *p, PyObject *v, const formatdef *f)
1027{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 int res;
1029 v = get_pylong(v);
1030 if (v == NULL)
1031 return -1;
1032 res = _PyLong_AsByteArray((PyLongObject*)v,
1033 (unsigned char *)p,
1034 8,
1035 1, /* little_endian */
1036 1 /* signed */);
1037 Py_DECREF(v);
1038 return res;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001039}
1040
1041static int
1042lp_ulonglong(char *p, PyObject *v, const formatdef *f)
1043{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 int res;
1045 v = get_pylong(v);
1046 if (v == NULL)
1047 return -1;
1048 res = _PyLong_AsByteArray((PyLongObject*)v,
1049 (unsigned char *)p,
1050 8,
1051 1, /* little_endian */
1052 0 /* signed */);
1053 Py_DECREF(v);
1054 return res;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001055}
1056
1057static int
1058lp_float(char *p, PyObject *v, const formatdef *f)
1059{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001060 double x = PyFloat_AsDouble(v);
1061 if (x == -1 && PyErr_Occurred()) {
1062 PyErr_SetString(StructError,
1063 "required argument is not a float");
1064 return -1;
1065 }
1066 return _PyFloat_Pack4(x, (unsigned char *)p, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001067}
1068
1069static int
1070lp_double(char *p, PyObject *v, const formatdef *f)
1071{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001072 double x = PyFloat_AsDouble(v);
1073 if (x == -1 && PyErr_Occurred()) {
1074 PyErr_SetString(StructError,
1075 "required argument is not a float");
1076 return -1;
1077 }
1078 return _PyFloat_Pack8(x, (unsigned char *)p, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001079}
1080
1081static formatdef lilendian_table[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 {'x', 1, 0, NULL},
1083 {'b', 1, 0, nu_byte, np_byte},
1084 {'B', 1, 0, nu_ubyte, np_ubyte},
1085 {'c', 1, 0, nu_char, np_char},
1086 {'s', 1, 0, NULL},
1087 {'p', 1, 0, NULL},
1088 {'h', 2, 0, lu_int, lp_int},
1089 {'H', 2, 0, lu_uint, lp_uint},
1090 {'i', 4, 0, lu_int, lp_int},
1091 {'I', 4, 0, lu_uint, lp_uint},
1092 {'l', 4, 0, lu_int, lp_int},
1093 {'L', 4, 0, lu_uint, lp_uint},
1094 {'q', 8, 0, lu_longlong, lp_longlong},
1095 {'Q', 8, 0, lu_ulonglong, lp_ulonglong},
1096 {'?', 1, 0, bu_bool, bp_bool}, /* Std rep not endian dep,
1097 but potentially different from native rep -- reuse bx_bool funcs. */
1098 {'f', 4, 0, lu_float, lp_float},
1099 {'d', 8, 0, lu_double, lp_double},
1100 {0}
Thomas Wouters477c8d52006-05-27 19:21:47 +00001101};
1102
1103
1104static const formatdef *
1105whichtable(char **pfmt)
1106{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001107 const char *fmt = (*pfmt)++; /* May be backed out of later */
1108 switch (*fmt) {
1109 case '<':
1110 return lilendian_table;
1111 case '>':
1112 case '!': /* Network byte order is big-endian */
1113 return bigendian_table;
Ezio Melotti42da6632011-03-15 05:18:48 +02001114 case '=': { /* Host byte order -- different from native in alignment! */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 int n = 1;
1116 char *p = (char *) &n;
1117 if (*p == 1)
1118 return lilendian_table;
1119 else
1120 return bigendian_table;
1121 }
1122 default:
1123 --*pfmt; /* Back out of pointer increment */
1124 /* Fall through */
1125 case '@':
1126 return native_table;
1127 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001128}
1129
1130
1131/* Get the table entry for a format code */
1132
1133static const formatdef *
1134getentry(int c, const formatdef *f)
1135{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136 for (; f->format != '\0'; f++) {
1137 if (f->format == c) {
1138 return f;
1139 }
1140 }
1141 PyErr_SetString(StructError, "bad char in struct format");
1142 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001143}
1144
1145
Mark Dickinsonb72e6862010-06-11 19:50:30 +00001146/* Align a size according to a format code. Return -1 on overflow. */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001147
Mark Dickinsoneac0e682010-06-11 19:05:08 +00001148static Py_ssize_t
Thomas Wouters477c8d52006-05-27 19:21:47 +00001149align(Py_ssize_t size, char c, const formatdef *e)
1150{
Mark Dickinsonb72e6862010-06-11 19:50:30 +00001151 Py_ssize_t extra;
1152
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001153 if (e->format == c) {
Mark Dickinsonb72e6862010-06-11 19:50:30 +00001154 if (e->alignment && size > 0) {
1155 extra = (e->alignment - 1) - (size - 1) % (e->alignment);
1156 if (extra > PY_SSIZE_T_MAX - size)
1157 return -1;
1158 size += extra;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001159 }
1160 }
1161 return size;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001162}
1163
1164
1165/* calculate the size of a format string */
1166
1167static int
1168prepare_s(PyStructObject *self)
1169{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001170 const formatdef *f;
1171 const formatdef *e;
1172 formatcode *codes;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001174 const char *s;
1175 const char *fmt;
1176 char c;
Mark Dickinsonb72e6862010-06-11 19:50:30 +00001177 Py_ssize_t size, len, num, itemsize;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001179 fmt = PyBytes_AS_STRING(self->s_format);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001180
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001181 f = whichtable((char **)&fmt);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001182
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 s = fmt;
1184 size = 0;
1185 len = 0;
1186 while ((c = *s++) != '\0') {
1187 if (isspace(Py_CHARMASK(c)))
1188 continue;
1189 if ('0' <= c && c <= '9') {
1190 num = c - '0';
1191 while ('0' <= (c = *s++) && c <= '9') {
Mark Dickinsonab4096f2010-06-11 16:56:34 +00001192 /* overflow-safe version of
1193 if (num*10 + (c - '0') > PY_SSIZE_T_MAX) { ... } */
1194 if (num >= PY_SSIZE_T_MAX / 10 && (
1195 num > PY_SSIZE_T_MAX / 10 ||
Mark Dickinsonb72e6862010-06-11 19:50:30 +00001196 (c - '0') > PY_SSIZE_T_MAX % 10))
1197 goto overflow;
Mark Dickinsonab4096f2010-06-11 16:56:34 +00001198 num = num*10 + (c - '0');
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001199 }
Alexander Belopolsky177e8532010-06-11 16:04:59 +00001200 if (c == '\0') {
1201 PyErr_SetString(StructError,
1202 "repeat count given without format specifier");
1203 return -1;
1204 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001205 }
1206 else
1207 num = 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001209 e = getentry(c, f);
1210 if (e == NULL)
1211 return -1;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 switch (c) {
1214 case 's': /* fall through */
1215 case 'p': len++; break;
1216 case 'x': break;
1217 default: len += num; break;
1218 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001220 itemsize = e->size;
1221 size = align(size, c, e);
Mark Dickinsonb72e6862010-06-11 19:50:30 +00001222 if (size == -1)
1223 goto overflow;
1224
1225 /* if (size + num * itemsize > PY_SSIZE_T_MAX) { ... } */
1226 if (num > (PY_SSIZE_T_MAX - size) / itemsize)
1227 goto overflow;
1228 size += num * itemsize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001229 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001231 /* check for overflow */
1232 if ((len + 1) > (PY_SSIZE_T_MAX / sizeof(formatcode))) {
1233 PyErr_NoMemory();
1234 return -1;
1235 }
Amaury Forgeot d'Arc35c86582008-06-17 21:11:29 +00001236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001237 self->s_size = size;
1238 self->s_len = len;
1239 codes = PyMem_MALLOC((len + 1) * sizeof(formatcode));
1240 if (codes == NULL) {
1241 PyErr_NoMemory();
1242 return -1;
1243 }
Mark Dickinsoncf28b952010-07-29 21:41:59 +00001244 /* Free any s_codes value left over from a previous initialization. */
1245 if (self->s_codes != NULL)
1246 PyMem_FREE(self->s_codes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001247 self->s_codes = codes;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001249 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;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001264 e = getentry(c, f);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001265
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001266 size = align(size, c, e);
1267 if (c == 's' || c == 'p') {
1268 codes->offset = size;
1269 codes->size = num;
1270 codes->fmtdef = e;
1271 codes++;
1272 size += num;
1273 } else if (c == 'x') {
1274 size += num;
1275 } else {
1276 while (--num >= 0) {
1277 codes->offset = size;
1278 codes->size = e->size;
1279 codes->fmtdef = e;
1280 codes++;
1281 size += e->size;
1282 }
1283 }
1284 }
1285 codes->fmtdef = NULL;
1286 codes->offset = size;
1287 codes->size = 0;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001289 return 0;
Mark Dickinsonb72e6862010-06-11 19:50:30 +00001290
1291 overflow:
1292 PyErr_SetString(StructError,
1293 "total struct size too long");
1294 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001295}
1296
1297static PyObject *
1298s_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1299{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001300 PyObject *self;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001302 assert(type != NULL && type->tp_alloc != NULL);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001304 self = type->tp_alloc(type, 0);
1305 if (self != NULL) {
1306 PyStructObject *s = (PyStructObject*)self;
1307 Py_INCREF(Py_None);
1308 s->s_format = Py_None;
1309 s->s_codes = NULL;
1310 s->s_size = -1;
1311 s->s_len = -1;
1312 }
1313 return self;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001314}
1315
1316static int
1317s_init(PyObject *self, PyObject *args, PyObject *kwds)
1318{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001319 PyStructObject *soself = (PyStructObject *)self;
1320 PyObject *o_format = NULL;
1321 int ret = 0;
1322 static char *kwlist[] = {"format", 0};
Thomas Wouters477c8d52006-05-27 19:21:47 +00001323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001324 assert(PyStruct_Check(self));
Thomas Wouters477c8d52006-05-27 19:21:47 +00001325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001326 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:Struct", kwlist,
1327 &o_format))
1328 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001330 if (PyUnicode_Check(o_format)) {
1331 o_format = PyUnicode_AsASCIIString(o_format);
1332 if (o_format == NULL)
1333 return -1;
1334 }
1335 /* XXX support buffer interface, too */
1336 else {
1337 Py_INCREF(o_format);
1338 }
Christian Heimesa34706f2008-01-04 03:06:10 +00001339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001340 if (!PyBytes_Check(o_format)) {
1341 Py_DECREF(o_format);
1342 PyErr_Format(PyExc_TypeError,
Victor Stinnerda9ec992010-12-28 13:26:42 +00001343 "Struct() argument 1 must be a bytes object, not %.200s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001344 Py_TYPE(o_format)->tp_name);
1345 return -1;
1346 }
Christian Heimesa34706f2008-01-04 03:06:10 +00001347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001348 Py_CLEAR(soself->s_format);
1349 soself->s_format = o_format;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001351 ret = prepare_s(soself);
1352 return ret;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001353}
1354
1355static void
1356s_dealloc(PyStructObject *s)
1357{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001358 if (s->weakreflist != NULL)
1359 PyObject_ClearWeakRefs((PyObject *)s);
1360 if (s->s_codes != NULL) {
1361 PyMem_FREE(s->s_codes);
1362 }
1363 Py_XDECREF(s->s_format);
1364 Py_TYPE(s)->tp_free((PyObject *)s);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001365}
1366
1367static PyObject *
1368s_unpack_internal(PyStructObject *soself, char *startfrom) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001369 formatcode *code;
1370 Py_ssize_t i = 0;
1371 PyObject *result = PyTuple_New(soself->s_len);
1372 if (result == NULL)
1373 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001375 for (code = soself->s_codes; code->fmtdef != NULL; code++) {
1376 PyObject *v;
1377 const formatdef *e = code->fmtdef;
1378 const char *res = startfrom + code->offset;
1379 if (e->format == 's') {
1380 v = PyBytes_FromStringAndSize(res, code->size);
1381 } else if (e->format == 'p') {
1382 Py_ssize_t n = *(unsigned char*)res;
1383 if (n >= code->size)
1384 n = code->size - 1;
1385 v = PyBytes_FromStringAndSize(res + 1, n);
1386 } else {
1387 v = e->unpack(res, e);
1388 }
1389 if (v == NULL)
1390 goto fail;
1391 PyTuple_SET_ITEM(result, i++, v);
1392 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001394 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001395fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001396 Py_DECREF(result);
1397 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001398}
1399
1400
1401PyDoc_STRVAR(s_unpack__doc__,
Guido van Rossum913dd0b2007-04-13 03:33:53 +00001402"S.unpack(buffer) -> (v1, v2, ...)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00001403\n\
Mark Dickinsonaacfa952010-06-12 15:43:45 +00001404Return a tuple containing values unpacked according to the format\n\
1405string S.format. Requires len(buffer) == S.size. See help(struct)\n\
1406for more on format strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001407
1408static PyObject *
Guido van Rossum98297ee2007-11-06 21:34:58 +00001409s_unpack(PyObject *self, PyObject *input)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001410{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001411 Py_buffer vbuf;
1412 PyObject *result;
1413 PyStructObject *soself = (PyStructObject *)self;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001415 assert(PyStruct_Check(self));
1416 assert(soself->s_codes != NULL);
1417 if (PyObject_GetBuffer(input, &vbuf, PyBUF_SIMPLE) < 0)
1418 return NULL;
1419 if (vbuf.len != soself->s_size) {
1420 PyErr_Format(StructError,
Victor Stinnerda9ec992010-12-28 13:26:42 +00001421 "unpack requires a bytes object of length %zd",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001422 soself->s_size);
1423 PyBuffer_Release(&vbuf);
1424 return NULL;
1425 }
1426 result = s_unpack_internal(soself, vbuf.buf);
1427 PyBuffer_Release(&vbuf);
1428 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001429}
1430
1431PyDoc_STRVAR(s_unpack_from__doc__,
Mark Dickinsonc6f13962010-06-13 09:17:13 +00001432"S.unpack_from(buffer, offset=0) -> (v1, v2, ...)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00001433\n\
Mark Dickinsonaacfa952010-06-12 15:43:45 +00001434Return a tuple containing values unpacked according to the format\n\
1435string S.format. Requires len(buffer[offset:]) >= S.size. See\n\
1436help(struct) for more on format strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001437
1438static PyObject *
1439s_unpack_from(PyObject *self, PyObject *args, PyObject *kwds)
1440{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001441 static char *kwlist[] = {"buffer", "offset", 0};
Guido van Rossum98297ee2007-11-06 21:34:58 +00001442
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001443 PyObject *input;
1444 Py_ssize_t offset = 0;
1445 Py_buffer vbuf;
1446 PyObject *result;
1447 PyStructObject *soself = (PyStructObject *)self;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001449 assert(PyStruct_Check(self));
1450 assert(soself->s_codes != NULL);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001451
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001452 if (!PyArg_ParseTupleAndKeywords(args, kwds,
1453 "O|n:unpack_from", kwlist,
1454 &input, &offset))
1455 return NULL;
1456 if (PyObject_GetBuffer(input, &vbuf, PyBUF_SIMPLE) < 0)
1457 return NULL;
1458 if (offset < 0)
1459 offset += vbuf.len;
1460 if (offset < 0 || vbuf.len - offset < soself->s_size) {
1461 PyErr_Format(StructError,
1462 "unpack_from requires a buffer of at least %zd bytes",
1463 soself->s_size);
1464 PyBuffer_Release(&vbuf);
1465 return NULL;
1466 }
1467 result = s_unpack_internal(soself, (char*)vbuf.buf + offset);
1468 PyBuffer_Release(&vbuf);
1469 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001470}
1471
1472
1473/*
1474 * Guts of the pack function.
1475 *
1476 * Takes a struct object, a tuple of arguments, and offset in that tuple of
1477 * argument for where to start processing the arguments for packing, and a
1478 * character buffer for writing the packed string. The caller must insure
1479 * that the buffer may contain the required length for packing the arguments.
1480 * 0 is returned on success, 1 is returned if there is an error.
1481 *
1482 */
1483static int
1484s_pack_internal(PyStructObject *soself, PyObject *args, int offset, char* buf)
1485{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001486 formatcode *code;
1487 /* XXX(nnorwitz): why does i need to be a local? can we use
1488 the offset parameter or do we need the wider width? */
1489 Py_ssize_t i;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001490
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001491 memset(buf, '\0', soself->s_size);
1492 i = offset;
1493 for (code = soself->s_codes; code->fmtdef != NULL; code++) {
1494 Py_ssize_t n;
1495 PyObject *v = PyTuple_GET_ITEM(args, i++);
1496 const formatdef *e = code->fmtdef;
1497 char *res = buf + code->offset;
1498 if (e->format == 's') {
1499 int isstring;
1500 void *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001501 isstring = PyBytes_Check(v);
1502 if (!isstring && !PyByteArray_Check(v)) {
1503 PyErr_SetString(StructError,
Victor Stinnerda9ec992010-12-28 13:26:42 +00001504 "argument for 's' must be a bytes object");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001505 return -1;
1506 }
1507 if (isstring) {
1508 n = PyBytes_GET_SIZE(v);
1509 p = PyBytes_AS_STRING(v);
1510 }
1511 else {
1512 n = PyByteArray_GET_SIZE(v);
1513 p = PyByteArray_AS_STRING(v);
1514 }
1515 if (n > code->size)
1516 n = code->size;
1517 if (n > 0)
1518 memcpy(res, p, n);
1519 } else if (e->format == 'p') {
1520 int isstring;
1521 void *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001522 isstring = PyBytes_Check(v);
1523 if (!isstring && !PyByteArray_Check(v)) {
1524 PyErr_SetString(StructError,
Victor Stinnerda9ec992010-12-28 13:26:42 +00001525 "argument for 'p' must be a bytes object");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001526 return -1;
1527 }
1528 if (isstring) {
1529 n = PyBytes_GET_SIZE(v);
1530 p = PyBytes_AS_STRING(v);
1531 }
1532 else {
1533 n = PyByteArray_GET_SIZE(v);
1534 p = PyByteArray_AS_STRING(v);
1535 }
1536 if (n > (code->size - 1))
1537 n = code->size - 1;
1538 if (n > 0)
1539 memcpy(res + 1, p, n);
1540 if (n > 255)
1541 n = 255;
1542 *res = Py_SAFE_DOWNCAST(n, Py_ssize_t, unsigned char);
1543 } else {
1544 if (e->pack(res, v, e) < 0) {
1545 if (PyLong_Check(v) && PyErr_ExceptionMatches(PyExc_OverflowError))
1546 PyErr_SetString(StructError,
1547 "long too large to convert to int");
1548 return -1;
1549 }
1550 }
1551 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001553 /* Success */
1554 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001555}
1556
1557
1558PyDoc_STRVAR(s_pack__doc__,
Benjamin Peterson4ae19462008-07-31 15:03:40 +00001559"S.pack(v1, v2, ...) -> bytes\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00001560\n\
Mark Dickinsonaacfa952010-06-12 15:43:45 +00001561Return a bytes object containing values v1, v2, ... packed according\n\
1562to the format string S.format. See help(struct) for more on format\n\
1563strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001564
1565static PyObject *
1566s_pack(PyObject *self, PyObject *args)
1567{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001568 PyStructObject *soself;
1569 PyObject *result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001571 /* Validate arguments. */
1572 soself = (PyStructObject *)self;
1573 assert(PyStruct_Check(self));
1574 assert(soself->s_codes != NULL);
1575 if (PyTuple_GET_SIZE(args) != soself->s_len)
1576 {
1577 PyErr_Format(StructError,
1578 "pack requires exactly %zd arguments", soself->s_len);
1579 return NULL;
1580 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001581
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001582 /* Allocate a new string */
1583 result = PyBytes_FromStringAndSize((char *)NULL, soself->s_size);
1584 if (result == NULL)
1585 return NULL;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001586
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001587 /* Call the guts */
1588 if ( s_pack_internal(soself, args, 0, PyBytes_AS_STRING(result)) != 0 ) {
1589 Py_DECREF(result);
1590 return NULL;
1591 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001593 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001594}
1595
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001596PyDoc_STRVAR(s_pack_into__doc__,
1597"S.pack_into(buffer, offset, v1, v2, ...)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00001598\n\
Mark Dickinsonaacfa952010-06-12 15:43:45 +00001599Pack the values v1, v2, ... according to the format string S.format\n\
1600and write the packed bytes into the writable buffer buf starting at\n\
Mark Dickinsonfdb99f12010-06-12 16:30:53 +00001601offset. Note that the offset is a required argument. See\n\
Mark Dickinsonaacfa952010-06-12 15:43:45 +00001602help(struct) for more on format strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001603
1604static PyObject *
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001605s_pack_into(PyObject *self, PyObject *args)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001606{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001607 PyStructObject *soself;
1608 char *buffer;
1609 Py_ssize_t buffer_len, offset;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001610
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001611 /* Validate arguments. +1 is for the first arg as buffer. */
1612 soself = (PyStructObject *)self;
1613 assert(PyStruct_Check(self));
1614 assert(soself->s_codes != NULL);
1615 if (PyTuple_GET_SIZE(args) != (soself->s_len + 2))
1616 {
1617 PyErr_Format(StructError,
1618 "pack_into requires exactly %zd arguments",
1619 (soself->s_len + 2));
1620 return NULL;
1621 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001622
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001623 /* Extract a writable memory buffer from the first argument */
1624 if ( PyObject_AsWriteBuffer(PyTuple_GET_ITEM(args, 0),
1625 (void**)&buffer, &buffer_len) == -1 ) {
1626 return NULL;
1627 }
1628 assert( buffer_len >= 0 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00001629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001630 /* Extract the offset from the first argument */
1631 offset = PyNumber_AsSsize_t(PyTuple_GET_ITEM(args, 1), PyExc_IndexError);
1632 if (offset == -1 && PyErr_Occurred())
1633 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001635 /* Support negative offsets. */
1636 if (offset < 0)
1637 offset += buffer_len;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001639 /* Check boundaries */
1640 if (offset < 0 || (buffer_len - offset) < soself->s_size) {
1641 PyErr_Format(StructError,
1642 "pack_into requires a buffer of at least %zd bytes",
1643 soself->s_size);
1644 return NULL;
1645 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001647 /* Call the guts */
1648 if ( s_pack_internal(soself, args, 2, buffer + offset) != 0 ) {
1649 return NULL;
1650 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001652 Py_RETURN_NONE;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001653}
1654
1655static PyObject *
1656s_get_format(PyStructObject *self, void *unused)
1657{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001658 Py_INCREF(self->s_format);
1659 return self->s_format;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001660}
1661
1662static PyObject *
1663s_get_size(PyStructObject *self, void *unused)
1664{
Christian Heimes217cfd12007-12-02 14:31:20 +00001665 return PyLong_FromSsize_t(self->s_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001666}
1667
Meador Ingeb14d8c92012-07-23 10:01:29 -05001668PyDoc_STRVAR(s_sizeof__doc__,
1669"S.__sizeof__() -> size of S in memory, in bytes");
1670
1671static PyObject *
1672s_sizeof(PyStructObject *self)
1673{
1674 Py_ssize_t size;
1675 formatcode *code;
1676
1677 size = sizeof(PyStructObject) + sizeof(formatcode);
1678 for (code = self->s_codes; code->fmtdef != NULL; code++) {
1679 size += sizeof(formatcode);
1680 }
1681 return PyLong_FromSsize_t(size);
1682}
1683
Thomas Wouters477c8d52006-05-27 19:21:47 +00001684/* List of functions */
1685
1686static struct PyMethodDef s_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001687 {"pack", s_pack, METH_VARARGS, s_pack__doc__},
1688 {"pack_into", s_pack_into, METH_VARARGS, s_pack_into__doc__},
1689 {"unpack", s_unpack, METH_O, s_unpack__doc__},
1690 {"unpack_from", (PyCFunction)s_unpack_from, METH_VARARGS|METH_KEYWORDS,
1691 s_unpack_from__doc__},
Meador Ingeb14d8c92012-07-23 10:01:29 -05001692 {"__sizeof__", (PyCFunction)s_sizeof, METH_NOARGS, s_sizeof__doc__},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001693 {NULL, NULL} /* sentinel */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001694};
1695
Victor Stinnerda9ec992010-12-28 13:26:42 +00001696PyDoc_STRVAR(s__doc__,
Alexander Belopolsky0bd003a2010-06-12 19:36:28 +00001697"Struct(fmt) --> compiled struct object\n"
1698"\n"
1699"Return a new Struct object which writes and reads binary data according to\n"
1700"the format string fmt. See help(struct) for more on format strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001701
1702#define OFF(x) offsetof(PyStructObject, x)
1703
1704static PyGetSetDef s_getsetlist[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001705 {"format", (getter)s_get_format, (setter)NULL, "struct format string", NULL},
1706 {"size", (getter)s_get_size, (setter)NULL, "struct size in bytes", NULL},
1707 {NULL} /* sentinel */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001708};
1709
1710static
1711PyTypeObject PyStructType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001712 PyVarObject_HEAD_INIT(NULL, 0)
1713 "Struct",
1714 sizeof(PyStructObject),
1715 0,
1716 (destructor)s_dealloc, /* tp_dealloc */
1717 0, /* tp_print */
1718 0, /* tp_getattr */
1719 0, /* tp_setattr */
1720 0, /* tp_reserved */
1721 0, /* tp_repr */
1722 0, /* tp_as_number */
1723 0, /* tp_as_sequence */
1724 0, /* tp_as_mapping */
1725 0, /* tp_hash */
1726 0, /* tp_call */
1727 0, /* tp_str */
1728 PyObject_GenericGetAttr, /* tp_getattro */
1729 PyObject_GenericSetAttr, /* tp_setattro */
1730 0, /* tp_as_buffer */
1731 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1732 s__doc__, /* tp_doc */
1733 0, /* tp_traverse */
1734 0, /* tp_clear */
1735 0, /* tp_richcompare */
1736 offsetof(PyStructObject, weakreflist), /* tp_weaklistoffset */
1737 0, /* tp_iter */
1738 0, /* tp_iternext */
1739 s_methods, /* tp_methods */
1740 NULL, /* tp_members */
1741 s_getsetlist, /* tp_getset */
1742 0, /* tp_base */
1743 0, /* tp_dict */
1744 0, /* tp_descr_get */
1745 0, /* tp_descr_set */
1746 0, /* tp_dictoffset */
1747 s_init, /* tp_init */
1748 PyType_GenericAlloc,/* tp_alloc */
1749 s_new, /* tp_new */
1750 PyObject_Del, /* tp_free */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001751};
1752
Christian Heimesa34706f2008-01-04 03:06:10 +00001753
1754/* ---- Standalone functions ---- */
1755
1756#define MAXCACHE 100
1757static PyObject *cache = NULL;
1758
1759static PyObject *
1760cache_struct(PyObject *fmt)
1761{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001762 PyObject * s_object;
Christian Heimesa34706f2008-01-04 03:06:10 +00001763
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001764 if (cache == NULL) {
1765 cache = PyDict_New();
1766 if (cache == NULL)
1767 return NULL;
1768 }
Christian Heimesa34706f2008-01-04 03:06:10 +00001769
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001770 s_object = PyDict_GetItem(cache, fmt);
1771 if (s_object != NULL) {
1772 Py_INCREF(s_object);
1773 return s_object;
1774 }
Christian Heimesa34706f2008-01-04 03:06:10 +00001775
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001776 s_object = PyObject_CallFunctionObjArgs((PyObject *)(&PyStructType), fmt, NULL);
1777 if (s_object != NULL) {
1778 if (PyDict_Size(cache) >= MAXCACHE)
1779 PyDict_Clear(cache);
1780 /* Attempt to cache the result */
1781 if (PyDict_SetItem(cache, fmt, s_object) == -1)
1782 PyErr_Clear();
1783 }
1784 return s_object;
Christian Heimesa34706f2008-01-04 03:06:10 +00001785}
1786
1787PyDoc_STRVAR(clearcache_doc,
1788"Clear the internal cache.");
1789
1790static PyObject *
1791clearcache(PyObject *self)
1792{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001793 Py_CLEAR(cache);
1794 Py_RETURN_NONE;
Christian Heimesa34706f2008-01-04 03:06:10 +00001795}
1796
1797PyDoc_STRVAR(calcsize_doc,
Mark Dickinsonaacfa952010-06-12 15:43:45 +00001798"calcsize(fmt) -> integer\n\
1799\n\
1800Return size in bytes of the struct described by the format string fmt.");
Christian Heimesa34706f2008-01-04 03:06:10 +00001801
1802static PyObject *
1803calcsize(PyObject *self, PyObject *fmt)
1804{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001805 Py_ssize_t n;
1806 PyObject *s_object = cache_struct(fmt);
1807 if (s_object == NULL)
1808 return NULL;
1809 n = ((PyStructObject *)s_object)->s_size;
1810 Py_DECREF(s_object);
1811 return PyLong_FromSsize_t(n);
Christian Heimesa34706f2008-01-04 03:06:10 +00001812}
1813
1814PyDoc_STRVAR(pack_doc,
Mark Dickinsonaacfa952010-06-12 15:43:45 +00001815"pack(fmt, v1, v2, ...) -> bytes\n\
1816\n\
Mark Dickinsonfdb99f12010-06-12 16:30:53 +00001817Return a bytes object containing the values v1, v2, ... packed according\n\
1818to the format string fmt. See help(struct) for more on format strings.");
Christian Heimesa34706f2008-01-04 03:06:10 +00001819
1820static PyObject *
1821pack(PyObject *self, PyObject *args)
1822{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001823 PyObject *s_object, *fmt, *newargs, *result;
1824 Py_ssize_t n = PyTuple_GET_SIZE(args);
Christian Heimesa34706f2008-01-04 03:06:10 +00001825
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001826 if (n == 0) {
1827 PyErr_SetString(PyExc_TypeError, "missing format argument");
1828 return NULL;
1829 }
1830 fmt = PyTuple_GET_ITEM(args, 0);
1831 newargs = PyTuple_GetSlice(args, 1, n);
1832 if (newargs == NULL)
1833 return NULL;
Christian Heimesa34706f2008-01-04 03:06:10 +00001834
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001835 s_object = cache_struct(fmt);
1836 if (s_object == NULL) {
1837 Py_DECREF(newargs);
1838 return NULL;
1839 }
1840 result = s_pack(s_object, newargs);
1841 Py_DECREF(newargs);
1842 Py_DECREF(s_object);
1843 return result;
Christian Heimesa34706f2008-01-04 03:06:10 +00001844}
1845
1846PyDoc_STRVAR(pack_into_doc,
Mark Dickinsonaacfa952010-06-12 15:43:45 +00001847"pack_into(fmt, buffer, offset, v1, v2, ...)\n\
1848\n\
1849Pack the values v1, v2, ... according to the format string fmt and write\n\
1850the packed bytes into the writable buffer buf starting at offset. Note\n\
Mark Dickinsonfdb99f12010-06-12 16:30:53 +00001851that the offset is a required argument. See help(struct) for more\n\
Mark Dickinsonaacfa952010-06-12 15:43:45 +00001852on format strings.");
Christian Heimesa34706f2008-01-04 03:06:10 +00001853
1854static PyObject *
1855pack_into(PyObject *self, PyObject *args)
1856{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001857 PyObject *s_object, *fmt, *newargs, *result;
1858 Py_ssize_t n = PyTuple_GET_SIZE(args);
Christian Heimesa34706f2008-01-04 03:06:10 +00001859
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001860 if (n == 0) {
1861 PyErr_SetString(PyExc_TypeError, "missing format argument");
1862 return NULL;
1863 }
1864 fmt = PyTuple_GET_ITEM(args, 0);
1865 newargs = PyTuple_GetSlice(args, 1, n);
1866 if (newargs == NULL)
1867 return NULL;
Christian Heimesa34706f2008-01-04 03:06:10 +00001868
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001869 s_object = cache_struct(fmt);
1870 if (s_object == NULL) {
1871 Py_DECREF(newargs);
1872 return NULL;
1873 }
1874 result = s_pack_into(s_object, newargs);
1875 Py_DECREF(newargs);
1876 Py_DECREF(s_object);
1877 return result;
Christian Heimesa34706f2008-01-04 03:06:10 +00001878}
1879
1880PyDoc_STRVAR(unpack_doc,
Mark Dickinsonaacfa952010-06-12 15:43:45 +00001881"unpack(fmt, buffer) -> (v1, v2, ...)\n\
1882\n\
1883Return a tuple containing values unpacked according to the format string\n\
1884fmt. Requires len(buffer) == calcsize(fmt). See help(struct) for more\n\
1885on format strings.");
Christian Heimesa34706f2008-01-04 03:06:10 +00001886
1887static PyObject *
1888unpack(PyObject *self, PyObject *args)
1889{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001890 PyObject *s_object, *fmt, *inputstr, *result;
Christian Heimesa34706f2008-01-04 03:06:10 +00001891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001892 if (!PyArg_UnpackTuple(args, "unpack", 2, 2, &fmt, &inputstr))
1893 return NULL;
Christian Heimesa34706f2008-01-04 03:06:10 +00001894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001895 s_object = cache_struct(fmt);
1896 if (s_object == NULL)
1897 return NULL;
1898 result = s_unpack(s_object, inputstr);
1899 Py_DECREF(s_object);
1900 return result;
Christian Heimesa34706f2008-01-04 03:06:10 +00001901}
1902
1903PyDoc_STRVAR(unpack_from_doc,
Mark Dickinsonc6f13962010-06-13 09:17:13 +00001904"unpack_from(fmt, buffer, offset=0) -> (v1, v2, ...)\n\
Mark Dickinsonaacfa952010-06-12 15:43:45 +00001905\n\
1906Return a tuple containing values unpacked according to the format string\n\
1907fmt. Requires len(buffer[offset:]) >= calcsize(fmt). See help(struct)\n\
1908for more on format strings.");
Christian Heimesa34706f2008-01-04 03:06:10 +00001909
1910static PyObject *
1911unpack_from(PyObject *self, PyObject *args, PyObject *kwds)
1912{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001913 PyObject *s_object, *fmt, *newargs, *result;
1914 Py_ssize_t n = PyTuple_GET_SIZE(args);
Christian Heimesa34706f2008-01-04 03:06:10 +00001915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001916 if (n == 0) {
1917 PyErr_SetString(PyExc_TypeError, "missing format argument");
1918 return NULL;
1919 }
1920 fmt = PyTuple_GET_ITEM(args, 0);
1921 newargs = PyTuple_GetSlice(args, 1, n);
1922 if (newargs == NULL)
1923 return NULL;
Christian Heimesa34706f2008-01-04 03:06:10 +00001924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001925 s_object = cache_struct(fmt);
1926 if (s_object == NULL) {
1927 Py_DECREF(newargs);
1928 return NULL;
1929 }
1930 result = s_unpack_from(s_object, newargs, kwds);
1931 Py_DECREF(newargs);
1932 Py_DECREF(s_object);
1933 return result;
Christian Heimesa34706f2008-01-04 03:06:10 +00001934}
1935
1936static struct PyMethodDef module_functions[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001937 {"_clearcache", (PyCFunction)clearcache, METH_NOARGS, clearcache_doc},
1938 {"calcsize", calcsize, METH_O, calcsize_doc},
1939 {"pack", pack, METH_VARARGS, pack_doc},
1940 {"pack_into", pack_into, METH_VARARGS, pack_into_doc},
1941 {"unpack", unpack, METH_VARARGS, unpack_doc},
1942 {"unpack_from", (PyCFunction)unpack_from,
1943 METH_VARARGS|METH_KEYWORDS, unpack_from_doc},
1944 {NULL, NULL} /* sentinel */
Christian Heimesa34706f2008-01-04 03:06:10 +00001945};
1946
1947
Thomas Wouters477c8d52006-05-27 19:21:47 +00001948/* Module initialization */
1949
Christian Heimesa34706f2008-01-04 03:06:10 +00001950PyDoc_STRVAR(module_doc,
1951"Functions to convert between Python values and C structs.\n\
Benjamin Peterson4ae19462008-07-31 15:03:40 +00001952Python bytes objects are used to hold the data representing the C struct\n\
Mark Dickinson40714af2009-10-08 15:59:20 +00001953and also as format strings (explained below) to describe the layout of data\n\
1954in the C struct.\n\
Christian Heimesa34706f2008-01-04 03:06:10 +00001955\n\
1956The optional first format char indicates byte order, size and alignment:\n\
Mark Dickinson40714af2009-10-08 15:59:20 +00001957 @: native order, size & alignment (default)\n\
1958 =: native order, std. size & alignment\n\
1959 <: little-endian, std. size & alignment\n\
1960 >: big-endian, std. size & alignment\n\
1961 !: same as >\n\
Christian Heimesa34706f2008-01-04 03:06:10 +00001962\n\
1963The remaining chars indicate types of args and must match exactly;\n\
1964these can be preceded by a decimal repeat count:\n\
1965 x: pad byte (no data); c:char; b:signed byte; B:unsigned byte;\n\
Mark Dickinson40714af2009-10-08 15:59:20 +00001966 ?: _Bool (requires C99; if not available, char is used instead)\n\
Christian Heimesa34706f2008-01-04 03:06:10 +00001967 h:short; H:unsigned short; i:int; I:unsigned int;\n\
1968 l:long; L:unsigned long; f:float; d:double.\n\
1969Special cases (preceding decimal count indicates length):\n\
1970 s:string (array of char); p: pascal string (with count byte).\n\
1971Special case (only available in native format):\n\
1972 P:an integer type that is wide enough to hold a pointer.\n\
1973Special case (not in native mode unless 'long long' in platform C):\n\
1974 q:long long; Q:unsigned long long\n\
1975Whitespace between formats is ignored.\n\
1976\n\
1977The variable struct.error is an exception raised on errors.\n");
1978
Martin v. Löwis1a214512008-06-11 05:26:20 +00001979
1980static struct PyModuleDef _structmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001981 PyModuleDef_HEAD_INIT,
1982 "_struct",
1983 module_doc,
1984 -1,
1985 module_functions,
1986 NULL,
1987 NULL,
1988 NULL,
1989 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001990};
1991
Thomas Wouters477c8d52006-05-27 19:21:47 +00001992PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001993PyInit__struct(void)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001994{
Mark Dickinson06817852010-06-12 09:25:13 +00001995 PyObject *m;
Christian Heimesa34706f2008-01-04 03:06:10 +00001996
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001997 m = PyModule_Create(&_structmodule);
1998 if (m == NULL)
1999 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002001 Py_TYPE(&PyStructType) = &PyType_Type;
2002 if (PyType_Ready(&PyStructType) < 0)
2003 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002004
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002005 /* Check endian and swap in faster functions */
2006 {
2007 int one = 1;
2008 formatdef *native = native_table;
2009 formatdef *other, *ptr;
2010 if ((int)*(unsigned char*)&one)
2011 other = lilendian_table;
2012 else
2013 other = bigendian_table;
2014 /* Scan through the native table, find a matching
2015 entry in the endian table and swap in the
2016 native implementations whenever possible
2017 (64-bit platforms may not have "standard" sizes) */
2018 while (native->format != '\0' && other->format != '\0') {
2019 ptr = other;
2020 while (ptr->format != '\0') {
2021 if (ptr->format == native->format) {
2022 /* Match faster when formats are
2023 listed in the same order */
2024 if (ptr == other)
2025 other++;
2026 /* Only use the trick if the
2027 size matches */
2028 if (ptr->size != native->size)
2029 break;
2030 /* Skip float and double, could be
2031 "unknown" float format */
2032 if (ptr->format == 'd' || ptr->format == 'f')
2033 break;
2034 ptr->pack = native->pack;
2035 ptr->unpack = native->unpack;
2036 break;
2037 }
2038 ptr++;
2039 }
2040 native++;
2041 }
2042 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002043
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002044 /* Add some symbolic constants to the module */
2045 if (StructError == NULL) {
2046 StructError = PyErr_NewException("struct.error", NULL, NULL);
2047 if (StructError == NULL)
2048 return NULL;
2049 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002051 Py_INCREF(StructError);
2052 PyModule_AddObject(m, "error", StructError);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002054 Py_INCREF((PyObject*)&PyStructType);
2055 PyModule_AddObject(m, "Struct", (PyObject*)&PyStructType);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002056
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002057 return m;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002058}