blob: 2e594e8f783d490acb42ea3ee94fcb3e0e40ed8a [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"
9#include "structseq.h"
10#include "structmember.h"
11#include <ctype.h>
12
13static PyTypeObject PyStructType;
14
Thomas Wouters477c8d52006-05-27 19:21:47 +000015/* The translation function for each format character is table driven */
16typedef struct _formatdef {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000017 char format;
18 Py_ssize_t size;
19 Py_ssize_t alignment;
20 PyObject* (*unpack)(const char *,
21 const struct _formatdef *);
22 int (*pack)(char *, PyObject *,
23 const struct _formatdef *);
Thomas Wouters477c8d52006-05-27 19:21:47 +000024} formatdef;
25
26typedef struct _formatcode {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000027 const struct _formatdef *fmtdef;
28 Py_ssize_t offset;
29 Py_ssize_t size;
Thomas Wouters477c8d52006-05-27 19:21:47 +000030} formatcode;
31
32/* Struct object interface */
33
34typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000035 PyObject_HEAD
36 Py_ssize_t s_size;
37 Py_ssize_t s_len;
38 formatcode *s_codes;
39 PyObject *s_format;
40 PyObject *weakreflist; /* List of weak references */
Thomas Wouters477c8d52006-05-27 19:21:47 +000041} PyStructObject;
42
43
44#define PyStruct_Check(op) PyObject_TypeCheck(op, &PyStructType)
Christian Heimes90aa7642007-12-19 02:45:37 +000045#define PyStruct_CheckExact(op) (Py_TYPE(op) == &PyStructType)
Thomas Wouters477c8d52006-05-27 19:21:47 +000046
47
48/* Exception */
49
50static PyObject *StructError;
51
52
53/* Define various structs to figure out the alignments of types */
54
55
56typedef struct { char c; short x; } st_short;
57typedef struct { char c; int x; } st_int;
58typedef struct { char c; long x; } st_long;
59typedef struct { char c; float x; } st_float;
60typedef struct { char c; double x; } st_double;
61typedef struct { char c; void *x; } st_void_p;
62
63#define SHORT_ALIGN (sizeof(st_short) - sizeof(short))
64#define INT_ALIGN (sizeof(st_int) - sizeof(int))
65#define LONG_ALIGN (sizeof(st_long) - sizeof(long))
66#define FLOAT_ALIGN (sizeof(st_float) - sizeof(float))
67#define DOUBLE_ALIGN (sizeof(st_double) - sizeof(double))
68#define VOID_P_ALIGN (sizeof(st_void_p) - sizeof(void *))
69
70/* We can't support q and Q in native mode unless the compiler does;
71 in std mode, they're 8 bytes on all platforms. */
72#ifdef HAVE_LONG_LONG
73typedef struct { char c; PY_LONG_LONG x; } s_long_long;
74#define LONG_LONG_ALIGN (sizeof(s_long_long) - sizeof(PY_LONG_LONG))
75#endif
76
Thomas Woutersb2137042007-02-01 18:02:27 +000077#ifdef HAVE_C99_BOOL
78#define BOOL_TYPE _Bool
79typedef struct { char c; _Bool x; } s_bool;
80#define BOOL_ALIGN (sizeof(s_bool) - sizeof(BOOL_TYPE))
81#else
82#define BOOL_TYPE char
83#define BOOL_ALIGN 0
84#endif
85
Thomas Wouters477c8d52006-05-27 19:21:47 +000086#define STRINGIFY(x) #x
87
88#ifdef __powerc
89#pragma options align=reset
90#endif
91
Mark Dickinson055a3fb2010-04-03 15:26:31 +000092/* Helper for integer format codes: converts an arbitrary Python object to a
93 PyLongObject if possible, otherwise fails. Caller should decref. */
Thomas Wouters477c8d52006-05-27 19:21:47 +000094
95static PyObject *
96get_pylong(PyObject *v)
97{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000098 assert(v != NULL);
99 if (!PyLong_Check(v)) {
100 /* Not an integer; try to use __index__ to convert. */
101 if (PyIndex_Check(v)) {
102 v = PyNumber_Index(v);
103 if (v == NULL)
104 return NULL;
105 }
106 else {
107 PyErr_SetString(StructError,
108 "required argument is not an integer");
109 return NULL;
110 }
111 }
112 else
113 Py_INCREF(v);
Mark Dickinsonea835e72009-04-19 20:40:33 +0000114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000115 assert(PyLong_Check(v));
116 return v;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000117}
118
Mark Dickinsonea835e72009-04-19 20:40:33 +0000119/* Helper routine to get a C long and raise the appropriate error if it isn't
120 one */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000121
122static int
123get_long(PyObject *v, long *p)
124{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000125 long x;
Mark Dickinsonea835e72009-04-19 20:40:33 +0000126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000127 v = get_pylong(v);
128 if (v == NULL)
129 return -1;
130 assert(PyLong_Check(v));
131 x = PyLong_AsLong(v);
132 Py_DECREF(v);
133 if (x == (long)-1 && PyErr_Occurred()) {
134 if (PyErr_ExceptionMatches(PyExc_OverflowError))
135 PyErr_SetString(StructError,
136 "argument out of range");
137 return -1;
138 }
139 *p = x;
140 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000141}
142
143
144/* Same, but handling unsigned long */
145
146static int
147get_ulong(PyObject *v, unsigned long *p)
148{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000149 unsigned long x;
Mark Dickinsonea835e72009-04-19 20:40:33 +0000150
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000151 v = get_pylong(v);
152 if (v == NULL)
153 return -1;
154 assert(PyLong_Check(v));
155 x = PyLong_AsUnsignedLong(v);
156 Py_DECREF(v);
157 if (x == (unsigned long)-1 && PyErr_Occurred()) {
158 if (PyErr_ExceptionMatches(PyExc_OverflowError))
159 PyErr_SetString(StructError,
160 "argument out of range");
161 return -1;
162 }
163 *p = x;
164 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000165}
166
167#ifdef HAVE_LONG_LONG
168
169/* Same, but handling native long long. */
170
171static int
172get_longlong(PyObject *v, PY_LONG_LONG *p)
173{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000174 PY_LONG_LONG x;
Mark Dickinson055a3fb2010-04-03 15:26:31 +0000175
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000176 v = get_pylong(v);
177 if (v == NULL)
178 return -1;
179 assert(PyLong_Check(v));
180 x = PyLong_AsLongLong(v);
181 Py_DECREF(v);
182 if (x == (PY_LONG_LONG)-1 && PyErr_Occurred()) {
183 if (PyErr_ExceptionMatches(PyExc_OverflowError))
184 PyErr_SetString(StructError,
185 "argument out of range");
186 return -1;
187 }
188 *p = x;
189 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000190}
191
192/* Same, but handling native unsigned long long. */
193
194static int
195get_ulonglong(PyObject *v, unsigned PY_LONG_LONG *p)
196{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000197 unsigned PY_LONG_LONG x;
Mark Dickinson055a3fb2010-04-03 15:26:31 +0000198
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000199 v = get_pylong(v);
200 if (v == NULL)
201 return -1;
202 assert(PyLong_Check(v));
203 x = PyLong_AsUnsignedLongLong(v);
204 Py_DECREF(v);
205 if (x == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred()) {
206 if (PyErr_ExceptionMatches(PyExc_OverflowError))
207 PyErr_SetString(StructError,
208 "argument out of range");
209 return -1;
210 }
211 *p = x;
212 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000213}
214
215#endif
216
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000217
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000218#define RANGE_ERROR(x, f, flag, mask) return _range_error(f, flag)
219
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000220
Thomas Wouters477c8d52006-05-27 19:21:47 +0000221/* Floating point helpers */
222
223static PyObject *
224unpack_float(const char *p, /* start of 4-byte string */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000225 int le) /* true for little-endian, false for big-endian */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000226{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000227 double x;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000229 x = _PyFloat_Unpack4((unsigned char *)p, le);
230 if (x == -1.0 && PyErr_Occurred())
231 return NULL;
232 return PyFloat_FromDouble(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000233}
234
235static PyObject *
236unpack_double(const char *p, /* start of 8-byte string */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000237 int le) /* true for little-endian, false for big-endian */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000238{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000239 double x;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000241 x = _PyFloat_Unpack8((unsigned char *)p, le);
242 if (x == -1.0 && PyErr_Occurred())
243 return NULL;
244 return PyFloat_FromDouble(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000245}
246
247/* Helper to format the range error exceptions */
248static int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000249_range_error(const formatdef *f, int is_unsigned)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000250{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000251 /* ulargest is the largest unsigned value with f->size bytes.
252 * Note that the simpler:
253 * ((size_t)1 << (f->size * 8)) - 1
254 * doesn't work when f->size == sizeof(size_t) because C doesn't
255 * define what happens when a left shift count is >= the number of
256 * bits in the integer being shifted; e.g., on some boxes it doesn't
257 * shift at all when they're equal.
258 */
259 const size_t ulargest = (size_t)-1 >> ((SIZEOF_SIZE_T - f->size)*8);
260 assert(f->size >= 1 && f->size <= SIZEOF_SIZE_T);
261 if (is_unsigned)
262 PyErr_Format(StructError,
263 "'%c' format requires 0 <= number <= %zu",
264 f->format,
265 ulargest);
266 else {
267 const Py_ssize_t largest = (Py_ssize_t)(ulargest >> 1);
268 PyErr_Format(StructError,
269 "'%c' format requires %zd <= number <= %zd",
270 f->format,
271 ~ largest,
272 largest);
273 }
Mark Dickinsonae681df2009-03-21 10:26:31 +0000274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000275 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000276}
277
278
279
280/* A large number of small routines follow, with names of the form
281
282 [bln][up]_TYPE
283
284 [bln] distiguishes among big-endian, little-endian and native.
285 [pu] distiguishes between pack (to struct) and unpack (from struct).
286 TYPE is one of char, byte, ubyte, etc.
287*/
288
289/* Native mode routines. ****************************************************/
290/* NOTE:
291 In all n[up]_<type> routines handling types larger than 1 byte, there is
292 *no* guarantee that the p pointer is properly aligned for each type,
293 therefore memcpy is called. An intermediate variable is used to
294 compensate for big-endian architectures.
295 Normally both the intermediate variable and the memcpy call will be
296 skipped by C optimisation in little-endian architectures (gcc >= 2.91
297 does this). */
298
299static PyObject *
300nu_char(const char *p, const formatdef *f)
301{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000302 return PyBytes_FromStringAndSize(p, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000303}
304
305static PyObject *
306nu_byte(const char *p, const formatdef *f)
307{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000308 return PyLong_FromLong((long) *(signed char *)p);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000309}
310
311static PyObject *
312nu_ubyte(const char *p, const formatdef *f)
313{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000314 return PyLong_FromLong((long) *(unsigned char *)p);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000315}
316
317static PyObject *
318nu_short(const char *p, const formatdef *f)
319{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000320 short x;
321 memcpy((char *)&x, p, sizeof x);
322 return PyLong_FromLong((long)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000323}
324
325static PyObject *
326nu_ushort(const char *p, const formatdef *f)
327{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000328 unsigned short x;
329 memcpy((char *)&x, p, sizeof x);
330 return PyLong_FromLong((long)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000331}
332
333static PyObject *
334nu_int(const char *p, const formatdef *f)
335{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000336 int x;
337 memcpy((char *)&x, p, sizeof x);
338 return PyLong_FromLong((long)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000339}
340
341static PyObject *
342nu_uint(const char *p, const formatdef *f)
343{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000344 unsigned int x;
345 memcpy((char *)&x, p, sizeof x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000346#if (SIZEOF_LONG > SIZEOF_INT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000347 return PyLong_FromLong((long)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000348#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000349 if (x <= ((unsigned int)LONG_MAX))
350 return PyLong_FromLong((long)x);
351 return PyLong_FromUnsignedLong((unsigned long)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000352#endif
353}
354
355static PyObject *
356nu_long(const char *p, const formatdef *f)
357{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000358 long x;
359 memcpy((char *)&x, p, sizeof x);
360 return PyLong_FromLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000361}
362
363static PyObject *
364nu_ulong(const char *p, const formatdef *f)
365{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000366 unsigned long x;
367 memcpy((char *)&x, p, sizeof x);
368 if (x <= LONG_MAX)
369 return PyLong_FromLong((long)x);
370 return PyLong_FromUnsignedLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000371}
372
373/* Native mode doesn't support q or Q unless the platform C supports
374 long long (or, on Windows, __int64). */
375
376#ifdef HAVE_LONG_LONG
377
378static PyObject *
379nu_longlong(const char *p, const formatdef *f)
380{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000381 PY_LONG_LONG x;
382 memcpy((char *)&x, p, sizeof x);
383 if (x >= LONG_MIN && x <= LONG_MAX)
384 return PyLong_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long));
385 return PyLong_FromLongLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000386}
387
388static PyObject *
389nu_ulonglong(const char *p, const formatdef *f)
390{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000391 unsigned PY_LONG_LONG x;
392 memcpy((char *)&x, p, sizeof x);
393 if (x <= LONG_MAX)
394 return PyLong_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long));
395 return PyLong_FromUnsignedLongLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000396}
397
398#endif
399
400static PyObject *
Thomas Woutersb2137042007-02-01 18:02:27 +0000401nu_bool(const char *p, const formatdef *f)
402{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000403 BOOL_TYPE x;
404 memcpy((char *)&x, p, sizeof x);
405 return PyBool_FromLong(x != 0);
Thomas Woutersb2137042007-02-01 18:02:27 +0000406}
407
408
409static PyObject *
Thomas Wouters477c8d52006-05-27 19:21:47 +0000410nu_float(const char *p, const formatdef *f)
411{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000412 float x;
413 memcpy((char *)&x, p, sizeof x);
414 return PyFloat_FromDouble((double)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000415}
416
417static PyObject *
418nu_double(const char *p, const formatdef *f)
419{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 double x;
421 memcpy((char *)&x, p, sizeof x);
422 return PyFloat_FromDouble(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000423}
424
425static PyObject *
426nu_void_p(const char *p, const formatdef *f)
427{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000428 void *x;
429 memcpy((char *)&x, p, sizeof x);
430 return PyLong_FromVoidPtr(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000431}
432
433static int
434np_byte(char *p, PyObject *v, const formatdef *f)
435{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000436 long x;
437 if (get_long(v, &x) < 0)
438 return -1;
439 if (x < -128 || x > 127){
440 PyErr_SetString(StructError,
441 "byte format requires -128 <= number <= 127");
442 return -1;
443 }
444 *p = (char)x;
445 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000446}
447
448static int
449np_ubyte(char *p, PyObject *v, const formatdef *f)
450{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000451 long x;
452 if (get_long(v, &x) < 0)
453 return -1;
454 if (x < 0 || x > 255){
455 PyErr_SetString(StructError,
456 "ubyte format requires 0 <= number <= 255");
457 return -1;
458 }
459 *p = (char)x;
460 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000461}
462
463static int
464np_char(char *p, PyObject *v, const formatdef *f)
465{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000466 if (PyUnicode_Check(v)) {
467 v = _PyUnicode_AsDefaultEncodedString(v, NULL);
468 if (v == NULL)
469 return -1;
470 }
471 if (!PyBytes_Check(v) || PyBytes_Size(v) != 1) {
472 PyErr_SetString(StructError,
473 "char format requires bytes or string of length 1");
474 return -1;
475 }
476 *p = *PyBytes_AsString(v);
477 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000478}
479
480static int
481np_short(char *p, PyObject *v, const formatdef *f)
482{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 long x;
484 short y;
485 if (get_long(v, &x) < 0)
486 return -1;
487 if (x < SHRT_MIN || x > SHRT_MAX){
488 PyErr_SetString(StructError,
489 "short format requires " STRINGIFY(SHRT_MIN)
490 " <= number <= " STRINGIFY(SHRT_MAX));
491 return -1;
492 }
493 y = (short)x;
494 memcpy(p, (char *)&y, sizeof y);
495 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000496}
497
498static int
499np_ushort(char *p, PyObject *v, const formatdef *f)
500{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 long x;
502 unsigned short y;
503 if (get_long(v, &x) < 0)
504 return -1;
505 if (x < 0 || x > USHRT_MAX){
506 PyErr_SetString(StructError,
507 "ushort format requires 0 <= number <= " STRINGIFY(USHRT_MAX));
508 return -1;
509 }
510 y = (unsigned short)x;
511 memcpy(p, (char *)&y, sizeof y);
512 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000513}
514
515static int
516np_int(char *p, PyObject *v, const formatdef *f)
517{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 long x;
519 int y;
520 if (get_long(v, &x) < 0)
521 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000522#if (SIZEOF_LONG > SIZEOF_INT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000523 if ((x < ((long)INT_MIN)) || (x > ((long)INT_MAX)))
524 RANGE_ERROR(x, f, 0, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000525#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 y = (int)x;
527 memcpy(p, (char *)&y, sizeof y);
528 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000529}
530
531static int
532np_uint(char *p, PyObject *v, const formatdef *f)
533{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 unsigned long x;
535 unsigned int y;
536 if (get_ulong(v, &x) < 0)
537 return -1;
538 y = (unsigned int)x;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000539#if (SIZEOF_LONG > SIZEOF_INT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000540 if (x > ((unsigned long)UINT_MAX))
541 RANGE_ERROR(y, f, 1, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000542#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000543 memcpy(p, (char *)&y, sizeof y);
544 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000545}
546
547static int
548np_long(char *p, PyObject *v, const formatdef *f)
549{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000550 long x;
551 if (get_long(v, &x) < 0)
552 return -1;
553 memcpy(p, (char *)&x, sizeof x);
554 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000555}
556
557static int
558np_ulong(char *p, PyObject *v, const formatdef *f)
559{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 unsigned long x;
561 if (get_ulong(v, &x) < 0)
562 return -1;
563 memcpy(p, (char *)&x, sizeof x);
564 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000565}
566
567#ifdef HAVE_LONG_LONG
568
569static int
570np_longlong(char *p, PyObject *v, const formatdef *f)
571{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000572 PY_LONG_LONG x;
573 if (get_longlong(v, &x) < 0)
574 return -1;
575 memcpy(p, (char *)&x, sizeof x);
576 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000577}
578
579static int
580np_ulonglong(char *p, PyObject *v, const formatdef *f)
581{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000582 unsigned PY_LONG_LONG x;
583 if (get_ulonglong(v, &x) < 0)
584 return -1;
585 memcpy(p, (char *)&x, sizeof x);
586 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000587}
588#endif
589
Thomas Woutersb2137042007-02-01 18:02:27 +0000590
591static int
592np_bool(char *p, PyObject *v, const formatdef *f)
593{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 BOOL_TYPE y;
595 y = PyObject_IsTrue(v);
596 memcpy(p, (char *)&y, sizeof y);
597 return 0;
Thomas Woutersb2137042007-02-01 18:02:27 +0000598}
599
Thomas Wouters477c8d52006-05-27 19:21:47 +0000600static int
601np_float(char *p, PyObject *v, const formatdef *f)
602{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000603 float x = (float)PyFloat_AsDouble(v);
604 if (x == -1 && PyErr_Occurred()) {
605 PyErr_SetString(StructError,
606 "required argument is not a float");
607 return -1;
608 }
609 memcpy(p, (char *)&x, sizeof x);
610 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000611}
612
613static int
614np_double(char *p, PyObject *v, const formatdef *f)
615{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000616 double x = PyFloat_AsDouble(v);
617 if (x == -1 && PyErr_Occurred()) {
618 PyErr_SetString(StructError,
619 "required argument is not a float");
620 return -1;
621 }
622 memcpy(p, (char *)&x, sizeof(double));
623 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000624}
625
626static int
627np_void_p(char *p, PyObject *v, const formatdef *f)
628{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000629 void *x;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000631 v = get_pylong(v);
632 if (v == NULL)
633 return -1;
634 assert(PyLong_Check(v));
635 x = PyLong_AsVoidPtr(v);
636 Py_DECREF(v);
637 if (x == NULL && PyErr_Occurred())
638 return -1;
639 memcpy(p, (char *)&x, sizeof x);
640 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000641}
642
643static formatdef native_table[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 {'x', sizeof(char), 0, NULL},
645 {'b', sizeof(char), 0, nu_byte, np_byte},
646 {'B', sizeof(char), 0, nu_ubyte, np_ubyte},
647 {'c', sizeof(char), 0, nu_char, np_char},
648 {'s', sizeof(char), 0, NULL},
649 {'p', sizeof(char), 0, NULL},
650 {'h', sizeof(short), SHORT_ALIGN, nu_short, np_short},
651 {'H', sizeof(short), SHORT_ALIGN, nu_ushort, np_ushort},
652 {'i', sizeof(int), INT_ALIGN, nu_int, np_int},
653 {'I', sizeof(int), INT_ALIGN, nu_uint, np_uint},
654 {'l', sizeof(long), LONG_ALIGN, nu_long, np_long},
655 {'L', sizeof(long), LONG_ALIGN, nu_ulong, np_ulong},
Thomas Wouters477c8d52006-05-27 19:21:47 +0000656#ifdef HAVE_LONG_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000657 {'q', sizeof(PY_LONG_LONG), LONG_LONG_ALIGN, nu_longlong, np_longlong},
658 {'Q', sizeof(PY_LONG_LONG), LONG_LONG_ALIGN, nu_ulonglong,np_ulonglong},
Thomas Wouters477c8d52006-05-27 19:21:47 +0000659#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000660 {'?', sizeof(BOOL_TYPE), BOOL_ALIGN, nu_bool, np_bool},
661 {'f', sizeof(float), FLOAT_ALIGN, nu_float, np_float},
662 {'d', sizeof(double), DOUBLE_ALIGN, nu_double, np_double},
663 {'P', sizeof(void *), VOID_P_ALIGN, nu_void_p, np_void_p},
664 {0}
Thomas Wouters477c8d52006-05-27 19:21:47 +0000665};
666
667/* Big-endian routines. *****************************************************/
668
669static PyObject *
670bu_int(const char *p, const formatdef *f)
671{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000672 long x = 0;
673 Py_ssize_t i = f->size;
674 const unsigned char *bytes = (const unsigned char *)p;
675 do {
676 x = (x<<8) | *bytes++;
677 } while (--i > 0);
678 /* Extend the sign bit. */
679 if (SIZEOF_LONG > f->size)
680 x |= -(x & (1L << ((8 * f->size) - 1)));
681 return PyLong_FromLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000682}
683
684static PyObject *
685bu_uint(const char *p, const formatdef *f)
686{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000687 unsigned long x = 0;
688 Py_ssize_t i = f->size;
689 const unsigned char *bytes = (const unsigned char *)p;
690 do {
691 x = (x<<8) | *bytes++;
692 } while (--i > 0);
693 if (x <= LONG_MAX)
694 return PyLong_FromLong((long)x);
695 return PyLong_FromUnsignedLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000696}
697
698static PyObject *
699bu_longlong(const char *p, const formatdef *f)
700{
701#ifdef HAVE_LONG_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000702 PY_LONG_LONG x = 0;
703 Py_ssize_t i = f->size;
704 const unsigned char *bytes = (const unsigned char *)p;
705 do {
706 x = (x<<8) | *bytes++;
707 } while (--i > 0);
708 /* Extend the sign bit. */
709 if (SIZEOF_LONG_LONG > f->size)
710 x |= -(x & ((PY_LONG_LONG)1 << ((8 * f->size) - 1)));
711 if (x >= LONG_MIN && x <= LONG_MAX)
712 return PyLong_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long));
713 return PyLong_FromLongLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000714#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 return _PyLong_FromByteArray((const unsigned char *)p,
716 8,
717 0, /* little-endian */
718 1 /* signed */);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000719#endif
720}
721
722static PyObject *
723bu_ulonglong(const char *p, const formatdef *f)
724{
725#ifdef HAVE_LONG_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000726 unsigned PY_LONG_LONG x = 0;
727 Py_ssize_t i = f->size;
728 const unsigned char *bytes = (const unsigned char *)p;
729 do {
730 x = (x<<8) | *bytes++;
731 } while (--i > 0);
732 if (x <= LONG_MAX)
733 return PyLong_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long));
734 return PyLong_FromUnsignedLongLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000735#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 return _PyLong_FromByteArray((const unsigned char *)p,
737 8,
738 0, /* little-endian */
739 0 /* signed */);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000740#endif
741}
742
743static PyObject *
744bu_float(const char *p, const formatdef *f)
745{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000746 return unpack_float(p, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000747}
748
749static PyObject *
750bu_double(const char *p, const formatdef *f)
751{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000752 return unpack_double(p, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000753}
754
Thomas Woutersb2137042007-02-01 18:02:27 +0000755static PyObject *
756bu_bool(const char *p, const formatdef *f)
757{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 char x;
759 memcpy((char *)&x, p, sizeof x);
760 return PyBool_FromLong(x != 0);
Thomas Woutersb2137042007-02-01 18:02:27 +0000761}
762
Thomas Wouters477c8d52006-05-27 19:21:47 +0000763static int
764bp_int(char *p, PyObject *v, const formatdef *f)
765{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000766 long x;
767 Py_ssize_t i;
768 if (get_long(v, &x) < 0)
769 return -1;
770 i = f->size;
771 if (i != SIZEOF_LONG) {
772 if ((i == 2) && (x < -32768 || x > 32767))
773 RANGE_ERROR(x, f, 0, 0xffffL);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000774#if (SIZEOF_LONG != 4)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000775 else if ((i == 4) && (x < -2147483648L || x > 2147483647L))
776 RANGE_ERROR(x, f, 0, 0xffffffffL);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000777#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 }
779 do {
780 p[--i] = (char)x;
781 x >>= 8;
782 } while (i > 0);
783 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000784}
785
786static int
787bp_uint(char *p, PyObject *v, const formatdef *f)
788{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 unsigned long x;
790 Py_ssize_t i;
791 if (get_ulong(v, &x) < 0)
792 return -1;
793 i = f->size;
794 if (i != SIZEOF_LONG) {
795 unsigned long maxint = 1;
796 maxint <<= (unsigned long)(i * 8);
797 if (x >= maxint)
798 RANGE_ERROR(x, f, 1, maxint - 1);
799 }
800 do {
801 p[--i] = (char)x;
802 x >>= 8;
803 } while (i > 0);
804 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000805}
806
807static int
808bp_longlong(char *p, PyObject *v, const formatdef *f)
809{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000810 int res;
811 v = get_pylong(v);
812 if (v == NULL)
813 return -1;
814 res = _PyLong_AsByteArray((PyLongObject *)v,
815 (unsigned char *)p,
816 8,
817 0, /* little_endian */
818 1 /* signed */);
819 Py_DECREF(v);
820 return res;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000821}
822
823static int
824bp_ulonglong(char *p, PyObject *v, const formatdef *f)
825{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000826 int res;
827 v = get_pylong(v);
828 if (v == NULL)
829 return -1;
830 res = _PyLong_AsByteArray((PyLongObject *)v,
831 (unsigned char *)p,
832 8,
833 0, /* little_endian */
834 0 /* signed */);
835 Py_DECREF(v);
836 return res;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000837}
838
839static int
840bp_float(char *p, PyObject *v, const formatdef *f)
841{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000842 double x = PyFloat_AsDouble(v);
843 if (x == -1 && PyErr_Occurred()) {
844 PyErr_SetString(StructError,
845 "required argument is not a float");
846 return -1;
847 }
848 return _PyFloat_Pack4(x, (unsigned char *)p, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000849}
850
851static int
852bp_double(char *p, PyObject *v, const formatdef *f)
853{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000854 double x = PyFloat_AsDouble(v);
855 if (x == -1 && PyErr_Occurred()) {
856 PyErr_SetString(StructError,
857 "required argument is not a float");
858 return -1;
859 }
860 return _PyFloat_Pack8(x, (unsigned char *)p, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000861}
862
Thomas Woutersb2137042007-02-01 18:02:27 +0000863static int
864bp_bool(char *p, PyObject *v, const formatdef *f)
865{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000866 char y;
867 y = PyObject_IsTrue(v);
868 memcpy(p, (char *)&y, sizeof y);
869 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;
1114 case '=': { /* Host byte order -- different from native in aligment! */
1115 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
1146/* Align a size according to a format code */
1147
1148static int
1149align(Py_ssize_t size, char c, const formatdef *e)
1150{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001151 if (e->format == c) {
1152 if (e->alignment) {
1153 size = ((size + e->alignment - 1)
1154 / e->alignment)
1155 * e->alignment;
1156 }
1157 }
1158 return size;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001159}
1160
1161
1162/* calculate the size of a format string */
1163
1164static int
1165prepare_s(PyStructObject *self)
1166{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001167 const formatdef *f;
1168 const formatdef *e;
1169 formatcode *codes;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001171 const char *s;
1172 const char *fmt;
1173 char c;
1174 Py_ssize_t size, len, num, itemsize, x;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001175
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001176 fmt = PyBytes_AS_STRING(self->s_format);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001178 f = whichtable((char **)&fmt);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001179
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001180 s = fmt;
1181 size = 0;
1182 len = 0;
1183 while ((c = *s++) != '\0') {
1184 if (isspace(Py_CHARMASK(c)))
1185 continue;
1186 if ('0' <= c && c <= '9') {
1187 num = c - '0';
1188 while ('0' <= (c = *s++) && c <= '9') {
1189 x = num*10 + (c - '0');
1190 if (x/10 != num) {
1191 PyErr_SetString(
1192 StructError,
1193 "overflow in item count");
1194 return -1;
1195 }
1196 num = x;
1197 }
Alexander Belopolsky177e8532010-06-11 16:04:59 +00001198 if (c == '\0') {
1199 PyErr_SetString(StructError,
1200 "repeat count given without format specifier");
1201 return -1;
1202 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001203 }
1204 else
1205 num = 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001206
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001207 e = getentry(c, f);
1208 if (e == NULL)
1209 return -1;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001211 switch (c) {
1212 case 's': /* fall through */
1213 case 'p': len++; break;
1214 case 'x': break;
1215 default: len += num; break;
1216 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001218 itemsize = e->size;
1219 size = align(size, c, e);
1220 x = num * itemsize;
1221 size += x;
1222 if (x/itemsize != num || size < 0) {
1223 PyErr_SetString(StructError,
1224 "total struct size too long");
1225 return -1;
1226 }
1227 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001229 /* check for overflow */
1230 if ((len + 1) > (PY_SSIZE_T_MAX / sizeof(formatcode))) {
1231 PyErr_NoMemory();
1232 return -1;
1233 }
Amaury Forgeot d'Arc35c86582008-06-17 21:11:29 +00001234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001235 self->s_size = size;
1236 self->s_len = len;
1237 codes = PyMem_MALLOC((len + 1) * sizeof(formatcode));
1238 if (codes == NULL) {
1239 PyErr_NoMemory();
1240 return -1;
1241 }
1242 self->s_codes = codes;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001244 s = fmt;
1245 size = 0;
1246 while ((c = *s++) != '\0') {
1247 if (isspace(Py_CHARMASK(c)))
1248 continue;
1249 if ('0' <= c && c <= '9') {
1250 num = c - '0';
1251 while ('0' <= (c = *s++) && c <= '9')
1252 num = num*10 + (c - '0');
1253 if (c == '\0')
1254 break;
1255 }
1256 else
1257 num = 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001259 e = getentry(c, f);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001261 size = align(size, c, e);
1262 if (c == 's' || c == 'p') {
1263 codes->offset = size;
1264 codes->size = num;
1265 codes->fmtdef = e;
1266 codes++;
1267 size += num;
1268 } else if (c == 'x') {
1269 size += num;
1270 } else {
1271 while (--num >= 0) {
1272 codes->offset = size;
1273 codes->size = e->size;
1274 codes->fmtdef = e;
1275 codes++;
1276 size += e->size;
1277 }
1278 }
1279 }
1280 codes->fmtdef = NULL;
1281 codes->offset = size;
1282 codes->size = 0;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001284 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001285}
1286
1287static PyObject *
1288s_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1289{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001290 PyObject *self;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001292 assert(type != NULL && type->tp_alloc != NULL);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001294 self = type->tp_alloc(type, 0);
1295 if (self != NULL) {
1296 PyStructObject *s = (PyStructObject*)self;
1297 Py_INCREF(Py_None);
1298 s->s_format = Py_None;
1299 s->s_codes = NULL;
1300 s->s_size = -1;
1301 s->s_len = -1;
1302 }
1303 return self;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001304}
1305
1306static int
1307s_init(PyObject *self, PyObject *args, PyObject *kwds)
1308{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001309 PyStructObject *soself = (PyStructObject *)self;
1310 PyObject *o_format = NULL;
1311 int ret = 0;
1312 static char *kwlist[] = {"format", 0};
Thomas Wouters477c8d52006-05-27 19:21:47 +00001313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001314 assert(PyStruct_Check(self));
Thomas Wouters477c8d52006-05-27 19:21:47 +00001315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001316 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:Struct", kwlist,
1317 &o_format))
1318 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001320 if (PyUnicode_Check(o_format)) {
1321 o_format = PyUnicode_AsASCIIString(o_format);
1322 if (o_format == NULL)
1323 return -1;
1324 }
1325 /* XXX support buffer interface, too */
1326 else {
1327 Py_INCREF(o_format);
1328 }
Christian Heimesa34706f2008-01-04 03:06:10 +00001329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001330 if (!PyBytes_Check(o_format)) {
1331 Py_DECREF(o_format);
1332 PyErr_Format(PyExc_TypeError,
1333 "Struct() argument 1 must be bytes, not %.200s",
1334 Py_TYPE(o_format)->tp_name);
1335 return -1;
1336 }
Christian Heimesa34706f2008-01-04 03:06:10 +00001337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001338 Py_CLEAR(soself->s_format);
1339 soself->s_format = o_format;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001341 ret = prepare_s(soself);
1342 return ret;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001343}
1344
1345static void
1346s_dealloc(PyStructObject *s)
1347{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001348 if (s->weakreflist != NULL)
1349 PyObject_ClearWeakRefs((PyObject *)s);
1350 if (s->s_codes != NULL) {
1351 PyMem_FREE(s->s_codes);
1352 }
1353 Py_XDECREF(s->s_format);
1354 Py_TYPE(s)->tp_free((PyObject *)s);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001355}
1356
1357static PyObject *
1358s_unpack_internal(PyStructObject *soself, char *startfrom) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001359 formatcode *code;
1360 Py_ssize_t i = 0;
1361 PyObject *result = PyTuple_New(soself->s_len);
1362 if (result == NULL)
1363 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001365 for (code = soself->s_codes; code->fmtdef != NULL; code++) {
1366 PyObject *v;
1367 const formatdef *e = code->fmtdef;
1368 const char *res = startfrom + code->offset;
1369 if (e->format == 's') {
1370 v = PyBytes_FromStringAndSize(res, code->size);
1371 } else if (e->format == 'p') {
1372 Py_ssize_t n = *(unsigned char*)res;
1373 if (n >= code->size)
1374 n = code->size - 1;
1375 v = PyBytes_FromStringAndSize(res + 1, n);
1376 } else {
1377 v = e->unpack(res, e);
1378 }
1379 if (v == NULL)
1380 goto fail;
1381 PyTuple_SET_ITEM(result, i++, v);
1382 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001384 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001385fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001386 Py_DECREF(result);
1387 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001388}
1389
1390
1391PyDoc_STRVAR(s_unpack__doc__,
Guido van Rossum913dd0b2007-04-13 03:33:53 +00001392"S.unpack(buffer) -> (v1, v2, ...)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00001393\n\
1394Return tuple containing values unpacked according to this Struct's format.\n\
Guido van Rossum913dd0b2007-04-13 03:33:53 +00001395Requires len(buffer) == self.size. See struct.__doc__ for more on format\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00001396strings.");
1397
1398static PyObject *
Guido van Rossum98297ee2007-11-06 21:34:58 +00001399s_unpack(PyObject *self, PyObject *input)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001400{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001401 Py_buffer vbuf;
1402 PyObject *result;
1403 PyStructObject *soself = (PyStructObject *)self;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001404
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001405 assert(PyStruct_Check(self));
1406 assert(soself->s_codes != NULL);
1407 if (PyObject_GetBuffer(input, &vbuf, PyBUF_SIMPLE) < 0)
1408 return NULL;
1409 if (vbuf.len != soself->s_size) {
1410 PyErr_Format(StructError,
1411 "unpack requires a bytes argument of length %zd",
1412 soself->s_size);
1413 PyBuffer_Release(&vbuf);
1414 return NULL;
1415 }
1416 result = s_unpack_internal(soself, vbuf.buf);
1417 PyBuffer_Release(&vbuf);
1418 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001419}
1420
1421PyDoc_STRVAR(s_unpack_from__doc__,
1422"S.unpack_from(buffer[, offset]) -> (v1, v2, ...)\n\
1423\n\
1424Return tuple containing values unpacked according to this Struct's format.\n\
1425Unlike unpack, unpack_from can unpack values from any object supporting\n\
1426the buffer API, not just str. Requires len(buffer[offset:]) >= self.size.\n\
1427See struct.__doc__ for more on format strings.");
1428
1429static PyObject *
1430s_unpack_from(PyObject *self, PyObject *args, PyObject *kwds)
1431{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001432 static char *kwlist[] = {"buffer", "offset", 0};
Guido van Rossum98297ee2007-11-06 21:34:58 +00001433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001434 PyObject *input;
1435 Py_ssize_t offset = 0;
1436 Py_buffer vbuf;
1437 PyObject *result;
1438 PyStructObject *soself = (PyStructObject *)self;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001440 assert(PyStruct_Check(self));
1441 assert(soself->s_codes != NULL);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001442
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001443 if (!PyArg_ParseTupleAndKeywords(args, kwds,
1444 "O|n:unpack_from", kwlist,
1445 &input, &offset))
1446 return NULL;
1447 if (PyObject_GetBuffer(input, &vbuf, PyBUF_SIMPLE) < 0)
1448 return NULL;
1449 if (offset < 0)
1450 offset += vbuf.len;
1451 if (offset < 0 || vbuf.len - offset < soself->s_size) {
1452 PyErr_Format(StructError,
1453 "unpack_from requires a buffer of at least %zd bytes",
1454 soself->s_size);
1455 PyBuffer_Release(&vbuf);
1456 return NULL;
1457 }
1458 result = s_unpack_internal(soself, (char*)vbuf.buf + offset);
1459 PyBuffer_Release(&vbuf);
1460 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001461}
1462
1463
1464/*
1465 * Guts of the pack function.
1466 *
1467 * Takes a struct object, a tuple of arguments, and offset in that tuple of
1468 * argument for where to start processing the arguments for packing, and a
1469 * character buffer for writing the packed string. The caller must insure
1470 * that the buffer may contain the required length for packing the arguments.
1471 * 0 is returned on success, 1 is returned if there is an error.
1472 *
1473 */
1474static int
1475s_pack_internal(PyStructObject *soself, PyObject *args, int offset, char* buf)
1476{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001477 formatcode *code;
1478 /* XXX(nnorwitz): why does i need to be a local? can we use
1479 the offset parameter or do we need the wider width? */
1480 Py_ssize_t i;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001481
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001482 memset(buf, '\0', soself->s_size);
1483 i = offset;
1484 for (code = soself->s_codes; code->fmtdef != NULL; code++) {
1485 Py_ssize_t n;
1486 PyObject *v = PyTuple_GET_ITEM(args, i++);
1487 const formatdef *e = code->fmtdef;
1488 char *res = buf + code->offset;
1489 if (e->format == 's') {
1490 int isstring;
1491 void *p;
1492 if (PyUnicode_Check(v)) {
1493 v = _PyUnicode_AsDefaultEncodedString(v, NULL);
1494 if (v == NULL)
1495 return -1;
1496 }
1497 isstring = PyBytes_Check(v);
1498 if (!isstring && !PyByteArray_Check(v)) {
1499 PyErr_SetString(StructError,
1500 "argument for 's' must be a bytes or string");
1501 return -1;
1502 }
1503 if (isstring) {
1504 n = PyBytes_GET_SIZE(v);
1505 p = PyBytes_AS_STRING(v);
1506 }
1507 else {
1508 n = PyByteArray_GET_SIZE(v);
1509 p = PyByteArray_AS_STRING(v);
1510 }
1511 if (n > code->size)
1512 n = code->size;
1513 if (n > 0)
1514 memcpy(res, p, n);
1515 } else if (e->format == 'p') {
1516 int isstring;
1517 void *p;
1518 if (PyUnicode_Check(v)) {
1519 v = _PyUnicode_AsDefaultEncodedString(v, NULL);
1520 if (v == NULL)
1521 return -1;
1522 }
1523 isstring = PyBytes_Check(v);
1524 if (!isstring && !PyByteArray_Check(v)) {
1525 PyErr_SetString(StructError,
1526 "argument for 'p' must be a bytes or string");
1527 return -1;
1528 }
1529 if (isstring) {
1530 n = PyBytes_GET_SIZE(v);
1531 p = PyBytes_AS_STRING(v);
1532 }
1533 else {
1534 n = PyByteArray_GET_SIZE(v);
1535 p = PyByteArray_AS_STRING(v);
1536 }
1537 if (n > (code->size - 1))
1538 n = code->size - 1;
1539 if (n > 0)
1540 memcpy(res + 1, p, n);
1541 if (n > 255)
1542 n = 255;
1543 *res = Py_SAFE_DOWNCAST(n, Py_ssize_t, unsigned char);
1544 } else {
1545 if (e->pack(res, v, e) < 0) {
1546 if (PyLong_Check(v) && PyErr_ExceptionMatches(PyExc_OverflowError))
1547 PyErr_SetString(StructError,
1548 "long too large to convert to int");
1549 return -1;
1550 }
1551 }
1552 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001553
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001554 /* Success */
1555 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001556}
1557
1558
1559PyDoc_STRVAR(s_pack__doc__,
Benjamin Peterson4ae19462008-07-31 15:03:40 +00001560"S.pack(v1, v2, ...) -> bytes\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00001561\n\
Benjamin Peterson4ae19462008-07-31 15:03:40 +00001562Return a bytes containing values v1, v2, ... packed according to this\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00001563Struct's format. See struct.__doc__ for more on format strings.");
1564
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\
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001599Pack the values v1, v2, ... according to this Struct's format, write \n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00001600the packed bytes into the writable buffer buf starting at offset. Note\n\
1601that the offset is not an optional argument. See struct.__doc__ for \n\
1602more on format strings.");
1603
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
1668/* List of functions */
1669
1670static struct PyMethodDef s_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001671 {"pack", s_pack, METH_VARARGS, s_pack__doc__},
1672 {"pack_into", s_pack_into, METH_VARARGS, s_pack_into__doc__},
1673 {"unpack", s_unpack, METH_O, s_unpack__doc__},
1674 {"unpack_from", (PyCFunction)s_unpack_from, METH_VARARGS|METH_KEYWORDS,
1675 s_unpack_from__doc__},
1676 {NULL, NULL} /* sentinel */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001677};
1678
1679PyDoc_STRVAR(s__doc__, "Compiled struct object");
1680
1681#define OFF(x) offsetof(PyStructObject, x)
1682
1683static PyGetSetDef s_getsetlist[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001684 {"format", (getter)s_get_format, (setter)NULL, "struct format string", NULL},
1685 {"size", (getter)s_get_size, (setter)NULL, "struct size in bytes", NULL},
1686 {NULL} /* sentinel */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001687};
1688
1689static
1690PyTypeObject PyStructType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001691 PyVarObject_HEAD_INIT(NULL, 0)
1692 "Struct",
1693 sizeof(PyStructObject),
1694 0,
1695 (destructor)s_dealloc, /* tp_dealloc */
1696 0, /* tp_print */
1697 0, /* tp_getattr */
1698 0, /* tp_setattr */
1699 0, /* tp_reserved */
1700 0, /* tp_repr */
1701 0, /* tp_as_number */
1702 0, /* tp_as_sequence */
1703 0, /* tp_as_mapping */
1704 0, /* tp_hash */
1705 0, /* tp_call */
1706 0, /* tp_str */
1707 PyObject_GenericGetAttr, /* tp_getattro */
1708 PyObject_GenericSetAttr, /* tp_setattro */
1709 0, /* tp_as_buffer */
1710 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1711 s__doc__, /* tp_doc */
1712 0, /* tp_traverse */
1713 0, /* tp_clear */
1714 0, /* tp_richcompare */
1715 offsetof(PyStructObject, weakreflist), /* tp_weaklistoffset */
1716 0, /* tp_iter */
1717 0, /* tp_iternext */
1718 s_methods, /* tp_methods */
1719 NULL, /* tp_members */
1720 s_getsetlist, /* tp_getset */
1721 0, /* tp_base */
1722 0, /* tp_dict */
1723 0, /* tp_descr_get */
1724 0, /* tp_descr_set */
1725 0, /* tp_dictoffset */
1726 s_init, /* tp_init */
1727 PyType_GenericAlloc,/* tp_alloc */
1728 s_new, /* tp_new */
1729 PyObject_Del, /* tp_free */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001730};
1731
Christian Heimesa34706f2008-01-04 03:06:10 +00001732
1733/* ---- Standalone functions ---- */
1734
1735#define MAXCACHE 100
1736static PyObject *cache = NULL;
1737
1738static PyObject *
1739cache_struct(PyObject *fmt)
1740{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001741 PyObject * s_object;
Christian Heimesa34706f2008-01-04 03:06:10 +00001742
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001743 if (cache == NULL) {
1744 cache = PyDict_New();
1745 if (cache == NULL)
1746 return NULL;
1747 }
Christian Heimesa34706f2008-01-04 03:06:10 +00001748
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001749 s_object = PyDict_GetItem(cache, fmt);
1750 if (s_object != NULL) {
1751 Py_INCREF(s_object);
1752 return s_object;
1753 }
Christian Heimesa34706f2008-01-04 03:06:10 +00001754
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001755 s_object = PyObject_CallFunctionObjArgs((PyObject *)(&PyStructType), fmt, NULL);
1756 if (s_object != NULL) {
1757 if (PyDict_Size(cache) >= MAXCACHE)
1758 PyDict_Clear(cache);
1759 /* Attempt to cache the result */
1760 if (PyDict_SetItem(cache, fmt, s_object) == -1)
1761 PyErr_Clear();
1762 }
1763 return s_object;
Christian Heimesa34706f2008-01-04 03:06:10 +00001764}
1765
1766PyDoc_STRVAR(clearcache_doc,
1767"Clear the internal cache.");
1768
1769static PyObject *
1770clearcache(PyObject *self)
1771{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001772 Py_CLEAR(cache);
1773 Py_RETURN_NONE;
Christian Heimesa34706f2008-01-04 03:06:10 +00001774}
1775
1776PyDoc_STRVAR(calcsize_doc,
1777"Return size of C struct described by format string fmt.");
1778
1779static PyObject *
1780calcsize(PyObject *self, PyObject *fmt)
1781{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001782 Py_ssize_t n;
1783 PyObject *s_object = cache_struct(fmt);
1784 if (s_object == NULL)
1785 return NULL;
1786 n = ((PyStructObject *)s_object)->s_size;
1787 Py_DECREF(s_object);
1788 return PyLong_FromSsize_t(n);
Christian Heimesa34706f2008-01-04 03:06:10 +00001789}
1790
1791PyDoc_STRVAR(pack_doc,
Benjamin Peterson4ae19462008-07-31 15:03:40 +00001792"Return bytes containing values v1, v2, ... packed according to fmt.");
Christian Heimesa34706f2008-01-04 03:06:10 +00001793
1794static PyObject *
1795pack(PyObject *self, PyObject *args)
1796{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001797 PyObject *s_object, *fmt, *newargs, *result;
1798 Py_ssize_t n = PyTuple_GET_SIZE(args);
Christian Heimesa34706f2008-01-04 03:06:10 +00001799
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001800 if (n == 0) {
1801 PyErr_SetString(PyExc_TypeError, "missing format argument");
1802 return NULL;
1803 }
1804 fmt = PyTuple_GET_ITEM(args, 0);
1805 newargs = PyTuple_GetSlice(args, 1, n);
1806 if (newargs == NULL)
1807 return NULL;
Christian Heimesa34706f2008-01-04 03:06:10 +00001808
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001809 s_object = cache_struct(fmt);
1810 if (s_object == NULL) {
1811 Py_DECREF(newargs);
1812 return NULL;
1813 }
1814 result = s_pack(s_object, newargs);
1815 Py_DECREF(newargs);
1816 Py_DECREF(s_object);
1817 return result;
Christian Heimesa34706f2008-01-04 03:06:10 +00001818}
1819
1820PyDoc_STRVAR(pack_into_doc,
1821"Pack the values v1, v2, ... according to fmt.\n\
1822Write the packed bytes into the writable buffer buf starting at offset.");
1823
1824static PyObject *
1825pack_into(PyObject *self, PyObject *args)
1826{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001827 PyObject *s_object, *fmt, *newargs, *result;
1828 Py_ssize_t n = PyTuple_GET_SIZE(args);
Christian Heimesa34706f2008-01-04 03:06:10 +00001829
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001830 if (n == 0) {
1831 PyErr_SetString(PyExc_TypeError, "missing format argument");
1832 return NULL;
1833 }
1834 fmt = PyTuple_GET_ITEM(args, 0);
1835 newargs = PyTuple_GetSlice(args, 1, n);
1836 if (newargs == NULL)
1837 return NULL;
Christian Heimesa34706f2008-01-04 03:06:10 +00001838
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001839 s_object = cache_struct(fmt);
1840 if (s_object == NULL) {
1841 Py_DECREF(newargs);
1842 return NULL;
1843 }
1844 result = s_pack_into(s_object, newargs);
1845 Py_DECREF(newargs);
1846 Py_DECREF(s_object);
1847 return result;
Christian Heimesa34706f2008-01-04 03:06:10 +00001848}
1849
1850PyDoc_STRVAR(unpack_doc,
Benjamin Peterson4ae19462008-07-31 15:03:40 +00001851"Unpack the bytes containing packed C structure data, according to fmt.\n\
1852Requires len(bytes) == calcsize(fmt).");
Christian Heimesa34706f2008-01-04 03:06:10 +00001853
1854static PyObject *
1855unpack(PyObject *self, PyObject *args)
1856{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001857 PyObject *s_object, *fmt, *inputstr, *result;
Christian Heimesa34706f2008-01-04 03:06:10 +00001858
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001859 if (!PyArg_UnpackTuple(args, "unpack", 2, 2, &fmt, &inputstr))
1860 return NULL;
Christian Heimesa34706f2008-01-04 03:06:10 +00001861
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001862 s_object = cache_struct(fmt);
1863 if (s_object == NULL)
1864 return NULL;
1865 result = s_unpack(s_object, inputstr);
1866 Py_DECREF(s_object);
1867 return result;
Christian Heimesa34706f2008-01-04 03:06:10 +00001868}
1869
1870PyDoc_STRVAR(unpack_from_doc,
1871"Unpack the buffer, containing packed C structure data, according to\n\
1872fmt, starting at offset. Requires len(buffer[offset:]) >= calcsize(fmt).");
1873
1874static PyObject *
1875unpack_from(PyObject *self, PyObject *args, PyObject *kwds)
1876{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001877 PyObject *s_object, *fmt, *newargs, *result;
1878 Py_ssize_t n = PyTuple_GET_SIZE(args);
Christian Heimesa34706f2008-01-04 03:06:10 +00001879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001880 if (n == 0) {
1881 PyErr_SetString(PyExc_TypeError, "missing format argument");
1882 return NULL;
1883 }
1884 fmt = PyTuple_GET_ITEM(args, 0);
1885 newargs = PyTuple_GetSlice(args, 1, n);
1886 if (newargs == NULL)
1887 return NULL;
Christian Heimesa34706f2008-01-04 03:06:10 +00001888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001889 s_object = cache_struct(fmt);
1890 if (s_object == NULL) {
1891 Py_DECREF(newargs);
1892 return NULL;
1893 }
1894 result = s_unpack_from(s_object, newargs, kwds);
1895 Py_DECREF(newargs);
1896 Py_DECREF(s_object);
1897 return result;
Christian Heimesa34706f2008-01-04 03:06:10 +00001898}
1899
1900static struct PyMethodDef module_functions[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001901 {"_clearcache", (PyCFunction)clearcache, METH_NOARGS, clearcache_doc},
1902 {"calcsize", calcsize, METH_O, calcsize_doc},
1903 {"pack", pack, METH_VARARGS, pack_doc},
1904 {"pack_into", pack_into, METH_VARARGS, pack_into_doc},
1905 {"unpack", unpack, METH_VARARGS, unpack_doc},
1906 {"unpack_from", (PyCFunction)unpack_from,
1907 METH_VARARGS|METH_KEYWORDS, unpack_from_doc},
1908 {NULL, NULL} /* sentinel */
Christian Heimesa34706f2008-01-04 03:06:10 +00001909};
1910
1911
Thomas Wouters477c8d52006-05-27 19:21:47 +00001912/* Module initialization */
1913
Christian Heimesa34706f2008-01-04 03:06:10 +00001914PyDoc_STRVAR(module_doc,
1915"Functions to convert between Python values and C structs.\n\
Benjamin Peterson4ae19462008-07-31 15:03:40 +00001916Python bytes objects are used to hold the data representing the C struct\n\
Mark Dickinson40714af2009-10-08 15:59:20 +00001917and also as format strings (explained below) to describe the layout of data\n\
1918in the C struct.\n\
Christian Heimesa34706f2008-01-04 03:06:10 +00001919\n\
1920The optional first format char indicates byte order, size and alignment:\n\
Mark Dickinson40714af2009-10-08 15:59:20 +00001921 @: native order, size & alignment (default)\n\
1922 =: native order, std. size & alignment\n\
1923 <: little-endian, std. size & alignment\n\
1924 >: big-endian, std. size & alignment\n\
1925 !: same as >\n\
Christian Heimesa34706f2008-01-04 03:06:10 +00001926\n\
1927The remaining chars indicate types of args and must match exactly;\n\
1928these can be preceded by a decimal repeat count:\n\
1929 x: pad byte (no data); c:char; b:signed byte; B:unsigned byte;\n\
Mark Dickinson40714af2009-10-08 15:59:20 +00001930 ?: _Bool (requires C99; if not available, char is used instead)\n\
Christian Heimesa34706f2008-01-04 03:06:10 +00001931 h:short; H:unsigned short; i:int; I:unsigned int;\n\
1932 l:long; L:unsigned long; f:float; d:double.\n\
1933Special cases (preceding decimal count indicates length):\n\
1934 s:string (array of char); p: pascal string (with count byte).\n\
1935Special case (only available in native format):\n\
1936 P:an integer type that is wide enough to hold a pointer.\n\
1937Special case (not in native mode unless 'long long' in platform C):\n\
1938 q:long long; Q:unsigned long long\n\
1939Whitespace between formats is ignored.\n\
1940\n\
1941The variable struct.error is an exception raised on errors.\n");
1942
Martin v. Löwis1a214512008-06-11 05:26:20 +00001943
1944static struct PyModuleDef _structmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001945 PyModuleDef_HEAD_INIT,
1946 "_struct",
1947 module_doc,
1948 -1,
1949 module_functions,
1950 NULL,
1951 NULL,
1952 NULL,
1953 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001954};
1955
Thomas Wouters477c8d52006-05-27 19:21:47 +00001956PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001957PyInit__struct(void)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001958{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001959 PyObject *ver, *m;
Christian Heimesa34706f2008-01-04 03:06:10 +00001960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001961 ver = PyBytes_FromString("0.3");
1962 if (ver == NULL)
1963 return NULL;
Christian Heimesa34706f2008-01-04 03:06:10 +00001964
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001965 m = PyModule_Create(&_structmodule);
1966 if (m == NULL)
1967 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001969 Py_TYPE(&PyStructType) = &PyType_Type;
1970 if (PyType_Ready(&PyStructType) < 0)
1971 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001972
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001973 /* Check endian and swap in faster functions */
1974 {
1975 int one = 1;
1976 formatdef *native = native_table;
1977 formatdef *other, *ptr;
1978 if ((int)*(unsigned char*)&one)
1979 other = lilendian_table;
1980 else
1981 other = bigendian_table;
1982 /* Scan through the native table, find a matching
1983 entry in the endian table and swap in the
1984 native implementations whenever possible
1985 (64-bit platforms may not have "standard" sizes) */
1986 while (native->format != '\0' && other->format != '\0') {
1987 ptr = other;
1988 while (ptr->format != '\0') {
1989 if (ptr->format == native->format) {
1990 /* Match faster when formats are
1991 listed in the same order */
1992 if (ptr == other)
1993 other++;
1994 /* Only use the trick if the
1995 size matches */
1996 if (ptr->size != native->size)
1997 break;
1998 /* Skip float and double, could be
1999 "unknown" float format */
2000 if (ptr->format == 'd' || ptr->format == 'f')
2001 break;
2002 ptr->pack = native->pack;
2003 ptr->unpack = native->unpack;
2004 break;
2005 }
2006 ptr++;
2007 }
2008 native++;
2009 }
2010 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002012 /* Add some symbolic constants to the module */
2013 if (StructError == NULL) {
2014 StructError = PyErr_NewException("struct.error", NULL, NULL);
2015 if (StructError == NULL)
2016 return NULL;
2017 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002019 Py_INCREF(StructError);
2020 PyModule_AddObject(m, "error", StructError);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002022 Py_INCREF((PyObject*)&PyStructType);
2023 PyModule_AddObject(m, "Struct", (PyObject*)&PyStructType);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002024
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002025 PyModule_AddObject(m, "__version__", ver);
Christian Heimesa34706f2008-01-04 03:06:10 +00002026
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002027 return m;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002028}