blob: e05fb730ef60427efe890eb8e80a75b4e9f8f033 [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') {
Mark Dickinsonab4096f2010-06-11 16:56:34 +00001189 /* overflow-safe version of
1190 if (num*10 + (c - '0') > PY_SSIZE_T_MAX) { ... } */
1191 if (num >= PY_SSIZE_T_MAX / 10 && (
1192 num > PY_SSIZE_T_MAX / 10 ||
1193 (c - '0') > PY_SSIZE_T_MAX % 10)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 PyErr_SetString(
1195 StructError,
1196 "overflow in item count");
1197 return -1;
1198 }
Mark Dickinsonab4096f2010-06-11 16:56:34 +00001199 num = num*10 + (c - '0');
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001200 }
Alexander Belopolsky177e8532010-06-11 16:04:59 +00001201 if (c == '\0') {
1202 PyErr_SetString(StructError,
1203 "repeat count given without format specifier");
1204 return -1;
1205 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001206 }
1207 else
1208 num = 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001210 e = getentry(c, f);
1211 if (e == NULL)
1212 return -1;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001214 switch (c) {
1215 case 's': /* fall through */
1216 case 'p': len++; break;
1217 case 'x': break;
1218 default: len += num; break;
1219 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001221 itemsize = e->size;
1222 size = align(size, c, e);
1223 x = num * itemsize;
1224 size += x;
1225 if (x/itemsize != num || size < 0) {
1226 PyErr_SetString(StructError,
1227 "total struct size too long");
1228 return -1;
1229 }
1230 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001232 /* check for overflow */
1233 if ((len + 1) > (PY_SSIZE_T_MAX / sizeof(formatcode))) {
1234 PyErr_NoMemory();
1235 return -1;
1236 }
Amaury Forgeot d'Arc35c86582008-06-17 21:11:29 +00001237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001238 self->s_size = size;
1239 self->s_len = len;
1240 codes = PyMem_MALLOC((len + 1) * sizeof(formatcode));
1241 if (codes == NULL) {
1242 PyErr_NoMemory();
1243 return -1;
1244 }
1245 self->s_codes = codes;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001247 s = fmt;
1248 size = 0;
1249 while ((c = *s++) != '\0') {
1250 if (isspace(Py_CHARMASK(c)))
1251 continue;
1252 if ('0' <= c && c <= '9') {
1253 num = c - '0';
1254 while ('0' <= (c = *s++) && c <= '9')
1255 num = num*10 + (c - '0');
1256 if (c == '\0')
1257 break;
1258 }
1259 else
1260 num = 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001261
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001262 e = getentry(c, f);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001264 size = align(size, c, e);
1265 if (c == 's' || c == 'p') {
1266 codes->offset = size;
1267 codes->size = num;
1268 codes->fmtdef = e;
1269 codes++;
1270 size += num;
1271 } else if (c == 'x') {
1272 size += num;
1273 } else {
1274 while (--num >= 0) {
1275 codes->offset = size;
1276 codes->size = e->size;
1277 codes->fmtdef = e;
1278 codes++;
1279 size += e->size;
1280 }
1281 }
1282 }
1283 codes->fmtdef = NULL;
1284 codes->offset = size;
1285 codes->size = 0;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001287 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001288}
1289
1290static PyObject *
1291s_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1292{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001293 PyObject *self;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001295 assert(type != NULL && type->tp_alloc != NULL);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001297 self = type->tp_alloc(type, 0);
1298 if (self != NULL) {
1299 PyStructObject *s = (PyStructObject*)self;
1300 Py_INCREF(Py_None);
1301 s->s_format = Py_None;
1302 s->s_codes = NULL;
1303 s->s_size = -1;
1304 s->s_len = -1;
1305 }
1306 return self;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001307}
1308
1309static int
1310s_init(PyObject *self, PyObject *args, PyObject *kwds)
1311{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001312 PyStructObject *soself = (PyStructObject *)self;
1313 PyObject *o_format = NULL;
1314 int ret = 0;
1315 static char *kwlist[] = {"format", 0};
Thomas Wouters477c8d52006-05-27 19:21:47 +00001316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001317 assert(PyStruct_Check(self));
Thomas Wouters477c8d52006-05-27 19:21:47 +00001318
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001319 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:Struct", kwlist,
1320 &o_format))
1321 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001323 if (PyUnicode_Check(o_format)) {
1324 o_format = PyUnicode_AsASCIIString(o_format);
1325 if (o_format == NULL)
1326 return -1;
1327 }
1328 /* XXX support buffer interface, too */
1329 else {
1330 Py_INCREF(o_format);
1331 }
Christian Heimesa34706f2008-01-04 03:06:10 +00001332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001333 if (!PyBytes_Check(o_format)) {
1334 Py_DECREF(o_format);
1335 PyErr_Format(PyExc_TypeError,
1336 "Struct() argument 1 must be bytes, not %.200s",
1337 Py_TYPE(o_format)->tp_name);
1338 return -1;
1339 }
Christian Heimesa34706f2008-01-04 03:06:10 +00001340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001341 Py_CLEAR(soself->s_format);
1342 soself->s_format = o_format;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001344 ret = prepare_s(soself);
1345 return ret;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001346}
1347
1348static void
1349s_dealloc(PyStructObject *s)
1350{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001351 if (s->weakreflist != NULL)
1352 PyObject_ClearWeakRefs((PyObject *)s);
1353 if (s->s_codes != NULL) {
1354 PyMem_FREE(s->s_codes);
1355 }
1356 Py_XDECREF(s->s_format);
1357 Py_TYPE(s)->tp_free((PyObject *)s);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001358}
1359
1360static PyObject *
1361s_unpack_internal(PyStructObject *soself, char *startfrom) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001362 formatcode *code;
1363 Py_ssize_t i = 0;
1364 PyObject *result = PyTuple_New(soself->s_len);
1365 if (result == NULL)
1366 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001368 for (code = soself->s_codes; code->fmtdef != NULL; code++) {
1369 PyObject *v;
1370 const formatdef *e = code->fmtdef;
1371 const char *res = startfrom + code->offset;
1372 if (e->format == 's') {
1373 v = PyBytes_FromStringAndSize(res, code->size);
1374 } else if (e->format == 'p') {
1375 Py_ssize_t n = *(unsigned char*)res;
1376 if (n >= code->size)
1377 n = code->size - 1;
1378 v = PyBytes_FromStringAndSize(res + 1, n);
1379 } else {
1380 v = e->unpack(res, e);
1381 }
1382 if (v == NULL)
1383 goto fail;
1384 PyTuple_SET_ITEM(result, i++, v);
1385 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001387 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001388fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001389 Py_DECREF(result);
1390 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001391}
1392
1393
1394PyDoc_STRVAR(s_unpack__doc__,
Guido van Rossum913dd0b2007-04-13 03:33:53 +00001395"S.unpack(buffer) -> (v1, v2, ...)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00001396\n\
1397Return tuple containing values unpacked according to this Struct's format.\n\
Guido van Rossum913dd0b2007-04-13 03:33:53 +00001398Requires len(buffer) == self.size. See struct.__doc__ for more on format\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00001399strings.");
1400
1401static PyObject *
Guido van Rossum98297ee2007-11-06 21:34:58 +00001402s_unpack(PyObject *self, PyObject *input)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001403{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001404 Py_buffer vbuf;
1405 PyObject *result;
1406 PyStructObject *soself = (PyStructObject *)self;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001407
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001408 assert(PyStruct_Check(self));
1409 assert(soself->s_codes != NULL);
1410 if (PyObject_GetBuffer(input, &vbuf, PyBUF_SIMPLE) < 0)
1411 return NULL;
1412 if (vbuf.len != soself->s_size) {
1413 PyErr_Format(StructError,
1414 "unpack requires a bytes argument of length %zd",
1415 soself->s_size);
1416 PyBuffer_Release(&vbuf);
1417 return NULL;
1418 }
1419 result = s_unpack_internal(soself, vbuf.buf);
1420 PyBuffer_Release(&vbuf);
1421 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001422}
1423
1424PyDoc_STRVAR(s_unpack_from__doc__,
1425"S.unpack_from(buffer[, offset]) -> (v1, v2, ...)\n\
1426\n\
1427Return tuple containing values unpacked according to this Struct's format.\n\
1428Unlike unpack, unpack_from can unpack values from any object supporting\n\
1429the buffer API, not just str. Requires len(buffer[offset:]) >= self.size.\n\
1430See struct.__doc__ for more on format strings.");
1431
1432static PyObject *
1433s_unpack_from(PyObject *self, PyObject *args, PyObject *kwds)
1434{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001435 static char *kwlist[] = {"buffer", "offset", 0};
Guido van Rossum98297ee2007-11-06 21:34:58 +00001436
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001437 PyObject *input;
1438 Py_ssize_t offset = 0;
1439 Py_buffer vbuf;
1440 PyObject *result;
1441 PyStructObject *soself = (PyStructObject *)self;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001442
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001443 assert(PyStruct_Check(self));
1444 assert(soself->s_codes != NULL);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001445
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001446 if (!PyArg_ParseTupleAndKeywords(args, kwds,
1447 "O|n:unpack_from", kwlist,
1448 &input, &offset))
1449 return NULL;
1450 if (PyObject_GetBuffer(input, &vbuf, PyBUF_SIMPLE) < 0)
1451 return NULL;
1452 if (offset < 0)
1453 offset += vbuf.len;
1454 if (offset < 0 || vbuf.len - offset < soself->s_size) {
1455 PyErr_Format(StructError,
1456 "unpack_from requires a buffer of at least %zd bytes",
1457 soself->s_size);
1458 PyBuffer_Release(&vbuf);
1459 return NULL;
1460 }
1461 result = s_unpack_internal(soself, (char*)vbuf.buf + offset);
1462 PyBuffer_Release(&vbuf);
1463 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001464}
1465
1466
1467/*
1468 * Guts of the pack function.
1469 *
1470 * Takes a struct object, a tuple of arguments, and offset in that tuple of
1471 * argument for where to start processing the arguments for packing, and a
1472 * character buffer for writing the packed string. The caller must insure
1473 * that the buffer may contain the required length for packing the arguments.
1474 * 0 is returned on success, 1 is returned if there is an error.
1475 *
1476 */
1477static int
1478s_pack_internal(PyStructObject *soself, PyObject *args, int offset, char* buf)
1479{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001480 formatcode *code;
1481 /* XXX(nnorwitz): why does i need to be a local? can we use
1482 the offset parameter or do we need the wider width? */
1483 Py_ssize_t i;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001485 memset(buf, '\0', soself->s_size);
1486 i = offset;
1487 for (code = soself->s_codes; code->fmtdef != NULL; code++) {
1488 Py_ssize_t n;
1489 PyObject *v = PyTuple_GET_ITEM(args, i++);
1490 const formatdef *e = code->fmtdef;
1491 char *res = buf + code->offset;
1492 if (e->format == 's') {
1493 int isstring;
1494 void *p;
1495 if (PyUnicode_Check(v)) {
1496 v = _PyUnicode_AsDefaultEncodedString(v, NULL);
1497 if (v == NULL)
1498 return -1;
1499 }
1500 isstring = PyBytes_Check(v);
1501 if (!isstring && !PyByteArray_Check(v)) {
1502 PyErr_SetString(StructError,
1503 "argument for 's' must be a bytes or string");
1504 return -1;
1505 }
1506 if (isstring) {
1507 n = PyBytes_GET_SIZE(v);
1508 p = PyBytes_AS_STRING(v);
1509 }
1510 else {
1511 n = PyByteArray_GET_SIZE(v);
1512 p = PyByteArray_AS_STRING(v);
1513 }
1514 if (n > code->size)
1515 n = code->size;
1516 if (n > 0)
1517 memcpy(res, p, n);
1518 } else if (e->format == 'p') {
1519 int isstring;
1520 void *p;
1521 if (PyUnicode_Check(v)) {
1522 v = _PyUnicode_AsDefaultEncodedString(v, NULL);
1523 if (v == NULL)
1524 return -1;
1525 }
1526 isstring = PyBytes_Check(v);
1527 if (!isstring && !PyByteArray_Check(v)) {
1528 PyErr_SetString(StructError,
1529 "argument for 'p' must be a bytes or string");
1530 return -1;
1531 }
1532 if (isstring) {
1533 n = PyBytes_GET_SIZE(v);
1534 p = PyBytes_AS_STRING(v);
1535 }
1536 else {
1537 n = PyByteArray_GET_SIZE(v);
1538 p = PyByteArray_AS_STRING(v);
1539 }
1540 if (n > (code->size - 1))
1541 n = code->size - 1;
1542 if (n > 0)
1543 memcpy(res + 1, p, n);
1544 if (n > 255)
1545 n = 255;
1546 *res = Py_SAFE_DOWNCAST(n, Py_ssize_t, unsigned char);
1547 } else {
1548 if (e->pack(res, v, e) < 0) {
1549 if (PyLong_Check(v) && PyErr_ExceptionMatches(PyExc_OverflowError))
1550 PyErr_SetString(StructError,
1551 "long too large to convert to int");
1552 return -1;
1553 }
1554 }
1555 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001556
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001557 /* Success */
1558 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001559}
1560
1561
1562PyDoc_STRVAR(s_pack__doc__,
Benjamin Peterson4ae19462008-07-31 15:03:40 +00001563"S.pack(v1, v2, ...) -> bytes\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00001564\n\
Benjamin Peterson4ae19462008-07-31 15:03:40 +00001565Return a bytes containing values v1, v2, ... packed according to this\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00001566Struct's format. See struct.__doc__ for more on format strings.");
1567
1568static PyObject *
1569s_pack(PyObject *self, PyObject *args)
1570{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001571 PyStructObject *soself;
1572 PyObject *result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001573
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001574 /* Validate arguments. */
1575 soself = (PyStructObject *)self;
1576 assert(PyStruct_Check(self));
1577 assert(soself->s_codes != NULL);
1578 if (PyTuple_GET_SIZE(args) != soself->s_len)
1579 {
1580 PyErr_Format(StructError,
1581 "pack requires exactly %zd arguments", soself->s_len);
1582 return NULL;
1583 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001585 /* Allocate a new string */
1586 result = PyBytes_FromStringAndSize((char *)NULL, soself->s_size);
1587 if (result == NULL)
1588 return NULL;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001590 /* Call the guts */
1591 if ( s_pack_internal(soself, args, 0, PyBytes_AS_STRING(result)) != 0 ) {
1592 Py_DECREF(result);
1593 return NULL;
1594 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001596 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001597}
1598
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001599PyDoc_STRVAR(s_pack_into__doc__,
1600"S.pack_into(buffer, offset, v1, v2, ...)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00001601\n\
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001602Pack the values v1, v2, ... according to this Struct's format, write \n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00001603the packed bytes into the writable buffer buf starting at offset. Note\n\
1604that the offset is not an optional argument. See struct.__doc__ for \n\
1605more on format strings.");
1606
1607static PyObject *
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001608s_pack_into(PyObject *self, PyObject *args)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001609{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001610 PyStructObject *soself;
1611 char *buffer;
1612 Py_ssize_t buffer_len, offset;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001614 /* Validate arguments. +1 is for the first arg as buffer. */
1615 soself = (PyStructObject *)self;
1616 assert(PyStruct_Check(self));
1617 assert(soself->s_codes != NULL);
1618 if (PyTuple_GET_SIZE(args) != (soself->s_len + 2))
1619 {
1620 PyErr_Format(StructError,
1621 "pack_into requires exactly %zd arguments",
1622 (soself->s_len + 2));
1623 return NULL;
1624 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001626 /* Extract a writable memory buffer from the first argument */
1627 if ( PyObject_AsWriteBuffer(PyTuple_GET_ITEM(args, 0),
1628 (void**)&buffer, &buffer_len) == -1 ) {
1629 return NULL;
1630 }
1631 assert( buffer_len >= 0 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00001632
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001633 /* Extract the offset from the first argument */
1634 offset = PyNumber_AsSsize_t(PyTuple_GET_ITEM(args, 1), PyExc_IndexError);
1635 if (offset == -1 && PyErr_Occurred())
1636 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001637
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001638 /* Support negative offsets. */
1639 if (offset < 0)
1640 offset += buffer_len;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001642 /* Check boundaries */
1643 if (offset < 0 || (buffer_len - offset) < soself->s_size) {
1644 PyErr_Format(StructError,
1645 "pack_into requires a buffer of at least %zd bytes",
1646 soself->s_size);
1647 return NULL;
1648 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001649
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001650 /* Call the guts */
1651 if ( s_pack_internal(soself, args, 2, buffer + offset) != 0 ) {
1652 return NULL;
1653 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001655 Py_RETURN_NONE;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001656}
1657
1658static PyObject *
1659s_get_format(PyStructObject *self, void *unused)
1660{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001661 Py_INCREF(self->s_format);
1662 return self->s_format;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001663}
1664
1665static PyObject *
1666s_get_size(PyStructObject *self, void *unused)
1667{
Christian Heimes217cfd12007-12-02 14:31:20 +00001668 return PyLong_FromSsize_t(self->s_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001669}
1670
1671/* List of functions */
1672
1673static struct PyMethodDef s_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001674 {"pack", s_pack, METH_VARARGS, s_pack__doc__},
1675 {"pack_into", s_pack_into, METH_VARARGS, s_pack_into__doc__},
1676 {"unpack", s_unpack, METH_O, s_unpack__doc__},
1677 {"unpack_from", (PyCFunction)s_unpack_from, METH_VARARGS|METH_KEYWORDS,
1678 s_unpack_from__doc__},
1679 {NULL, NULL} /* sentinel */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001680};
1681
1682PyDoc_STRVAR(s__doc__, "Compiled struct object");
1683
1684#define OFF(x) offsetof(PyStructObject, x)
1685
1686static PyGetSetDef s_getsetlist[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001687 {"format", (getter)s_get_format, (setter)NULL, "struct format string", NULL},
1688 {"size", (getter)s_get_size, (setter)NULL, "struct size in bytes", NULL},
1689 {NULL} /* sentinel */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001690};
1691
1692static
1693PyTypeObject PyStructType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001694 PyVarObject_HEAD_INIT(NULL, 0)
1695 "Struct",
1696 sizeof(PyStructObject),
1697 0,
1698 (destructor)s_dealloc, /* tp_dealloc */
1699 0, /* tp_print */
1700 0, /* tp_getattr */
1701 0, /* tp_setattr */
1702 0, /* tp_reserved */
1703 0, /* tp_repr */
1704 0, /* tp_as_number */
1705 0, /* tp_as_sequence */
1706 0, /* tp_as_mapping */
1707 0, /* tp_hash */
1708 0, /* tp_call */
1709 0, /* tp_str */
1710 PyObject_GenericGetAttr, /* tp_getattro */
1711 PyObject_GenericSetAttr, /* tp_setattro */
1712 0, /* tp_as_buffer */
1713 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1714 s__doc__, /* tp_doc */
1715 0, /* tp_traverse */
1716 0, /* tp_clear */
1717 0, /* tp_richcompare */
1718 offsetof(PyStructObject, weakreflist), /* tp_weaklistoffset */
1719 0, /* tp_iter */
1720 0, /* tp_iternext */
1721 s_methods, /* tp_methods */
1722 NULL, /* tp_members */
1723 s_getsetlist, /* tp_getset */
1724 0, /* tp_base */
1725 0, /* tp_dict */
1726 0, /* tp_descr_get */
1727 0, /* tp_descr_set */
1728 0, /* tp_dictoffset */
1729 s_init, /* tp_init */
1730 PyType_GenericAlloc,/* tp_alloc */
1731 s_new, /* tp_new */
1732 PyObject_Del, /* tp_free */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001733};
1734
Christian Heimesa34706f2008-01-04 03:06:10 +00001735
1736/* ---- Standalone functions ---- */
1737
1738#define MAXCACHE 100
1739static PyObject *cache = NULL;
1740
1741static PyObject *
1742cache_struct(PyObject *fmt)
1743{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001744 PyObject * s_object;
Christian Heimesa34706f2008-01-04 03:06:10 +00001745
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001746 if (cache == NULL) {
1747 cache = PyDict_New();
1748 if (cache == NULL)
1749 return NULL;
1750 }
Christian Heimesa34706f2008-01-04 03:06:10 +00001751
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001752 s_object = PyDict_GetItem(cache, fmt);
1753 if (s_object != NULL) {
1754 Py_INCREF(s_object);
1755 return s_object;
1756 }
Christian Heimesa34706f2008-01-04 03:06:10 +00001757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001758 s_object = PyObject_CallFunctionObjArgs((PyObject *)(&PyStructType), fmt, NULL);
1759 if (s_object != NULL) {
1760 if (PyDict_Size(cache) >= MAXCACHE)
1761 PyDict_Clear(cache);
1762 /* Attempt to cache the result */
1763 if (PyDict_SetItem(cache, fmt, s_object) == -1)
1764 PyErr_Clear();
1765 }
1766 return s_object;
Christian Heimesa34706f2008-01-04 03:06:10 +00001767}
1768
1769PyDoc_STRVAR(clearcache_doc,
1770"Clear the internal cache.");
1771
1772static PyObject *
1773clearcache(PyObject *self)
1774{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001775 Py_CLEAR(cache);
1776 Py_RETURN_NONE;
Christian Heimesa34706f2008-01-04 03:06:10 +00001777}
1778
1779PyDoc_STRVAR(calcsize_doc,
1780"Return size of C struct described by format string fmt.");
1781
1782static PyObject *
1783calcsize(PyObject *self, PyObject *fmt)
1784{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001785 Py_ssize_t n;
1786 PyObject *s_object = cache_struct(fmt);
1787 if (s_object == NULL)
1788 return NULL;
1789 n = ((PyStructObject *)s_object)->s_size;
1790 Py_DECREF(s_object);
1791 return PyLong_FromSsize_t(n);
Christian Heimesa34706f2008-01-04 03:06:10 +00001792}
1793
1794PyDoc_STRVAR(pack_doc,
Benjamin Peterson4ae19462008-07-31 15:03:40 +00001795"Return bytes containing values v1, v2, ... packed according to fmt.");
Christian Heimesa34706f2008-01-04 03:06:10 +00001796
1797static PyObject *
1798pack(PyObject *self, PyObject *args)
1799{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001800 PyObject *s_object, *fmt, *newargs, *result;
1801 Py_ssize_t n = PyTuple_GET_SIZE(args);
Christian Heimesa34706f2008-01-04 03:06:10 +00001802
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001803 if (n == 0) {
1804 PyErr_SetString(PyExc_TypeError, "missing format argument");
1805 return NULL;
1806 }
1807 fmt = PyTuple_GET_ITEM(args, 0);
1808 newargs = PyTuple_GetSlice(args, 1, n);
1809 if (newargs == NULL)
1810 return NULL;
Christian Heimesa34706f2008-01-04 03:06:10 +00001811
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001812 s_object = cache_struct(fmt);
1813 if (s_object == NULL) {
1814 Py_DECREF(newargs);
1815 return NULL;
1816 }
1817 result = s_pack(s_object, newargs);
1818 Py_DECREF(newargs);
1819 Py_DECREF(s_object);
1820 return result;
Christian Heimesa34706f2008-01-04 03:06:10 +00001821}
1822
1823PyDoc_STRVAR(pack_into_doc,
1824"Pack the values v1, v2, ... according to fmt.\n\
1825Write the packed bytes into the writable buffer buf starting at offset.");
1826
1827static PyObject *
1828pack_into(PyObject *self, PyObject *args)
1829{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001830 PyObject *s_object, *fmt, *newargs, *result;
1831 Py_ssize_t n = PyTuple_GET_SIZE(args);
Christian Heimesa34706f2008-01-04 03:06:10 +00001832
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001833 if (n == 0) {
1834 PyErr_SetString(PyExc_TypeError, "missing format argument");
1835 return NULL;
1836 }
1837 fmt = PyTuple_GET_ITEM(args, 0);
1838 newargs = PyTuple_GetSlice(args, 1, n);
1839 if (newargs == NULL)
1840 return NULL;
Christian Heimesa34706f2008-01-04 03:06:10 +00001841
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001842 s_object = cache_struct(fmt);
1843 if (s_object == NULL) {
1844 Py_DECREF(newargs);
1845 return NULL;
1846 }
1847 result = s_pack_into(s_object, newargs);
1848 Py_DECREF(newargs);
1849 Py_DECREF(s_object);
1850 return result;
Christian Heimesa34706f2008-01-04 03:06:10 +00001851}
1852
1853PyDoc_STRVAR(unpack_doc,
Benjamin Peterson4ae19462008-07-31 15:03:40 +00001854"Unpack the bytes containing packed C structure data, according to fmt.\n\
1855Requires len(bytes) == calcsize(fmt).");
Christian Heimesa34706f2008-01-04 03:06:10 +00001856
1857static PyObject *
1858unpack(PyObject *self, PyObject *args)
1859{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001860 PyObject *s_object, *fmt, *inputstr, *result;
Christian Heimesa34706f2008-01-04 03:06:10 +00001861
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001862 if (!PyArg_UnpackTuple(args, "unpack", 2, 2, &fmt, &inputstr))
1863 return NULL;
Christian Heimesa34706f2008-01-04 03:06:10 +00001864
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001865 s_object = cache_struct(fmt);
1866 if (s_object == NULL)
1867 return NULL;
1868 result = s_unpack(s_object, inputstr);
1869 Py_DECREF(s_object);
1870 return result;
Christian Heimesa34706f2008-01-04 03:06:10 +00001871}
1872
1873PyDoc_STRVAR(unpack_from_doc,
1874"Unpack the buffer, containing packed C structure data, according to\n\
1875fmt, starting at offset. Requires len(buffer[offset:]) >= calcsize(fmt).");
1876
1877static PyObject *
1878unpack_from(PyObject *self, PyObject *args, PyObject *kwds)
1879{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001880 PyObject *s_object, *fmt, *newargs, *result;
1881 Py_ssize_t n = PyTuple_GET_SIZE(args);
Christian Heimesa34706f2008-01-04 03:06:10 +00001882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001883 if (n == 0) {
1884 PyErr_SetString(PyExc_TypeError, "missing format argument");
1885 return NULL;
1886 }
1887 fmt = PyTuple_GET_ITEM(args, 0);
1888 newargs = PyTuple_GetSlice(args, 1, n);
1889 if (newargs == NULL)
1890 return NULL;
Christian Heimesa34706f2008-01-04 03:06:10 +00001891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001892 s_object = cache_struct(fmt);
1893 if (s_object == NULL) {
1894 Py_DECREF(newargs);
1895 return NULL;
1896 }
1897 result = s_unpack_from(s_object, newargs, kwds);
1898 Py_DECREF(newargs);
1899 Py_DECREF(s_object);
1900 return result;
Christian Heimesa34706f2008-01-04 03:06:10 +00001901}
1902
1903static struct PyMethodDef module_functions[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001904 {"_clearcache", (PyCFunction)clearcache, METH_NOARGS, clearcache_doc},
1905 {"calcsize", calcsize, METH_O, calcsize_doc},
1906 {"pack", pack, METH_VARARGS, pack_doc},
1907 {"pack_into", pack_into, METH_VARARGS, pack_into_doc},
1908 {"unpack", unpack, METH_VARARGS, unpack_doc},
1909 {"unpack_from", (PyCFunction)unpack_from,
1910 METH_VARARGS|METH_KEYWORDS, unpack_from_doc},
1911 {NULL, NULL} /* sentinel */
Christian Heimesa34706f2008-01-04 03:06:10 +00001912};
1913
1914
Thomas Wouters477c8d52006-05-27 19:21:47 +00001915/* Module initialization */
1916
Christian Heimesa34706f2008-01-04 03:06:10 +00001917PyDoc_STRVAR(module_doc,
1918"Functions to convert between Python values and C structs.\n\
Benjamin Peterson4ae19462008-07-31 15:03:40 +00001919Python bytes objects are used to hold the data representing the C struct\n\
Mark Dickinson40714af2009-10-08 15:59:20 +00001920and also as format strings (explained below) to describe the layout of data\n\
1921in the C struct.\n\
Christian Heimesa34706f2008-01-04 03:06:10 +00001922\n\
1923The optional first format char indicates byte order, size and alignment:\n\
Mark Dickinson40714af2009-10-08 15:59:20 +00001924 @: native order, size & alignment (default)\n\
1925 =: native order, std. size & alignment\n\
1926 <: little-endian, std. size & alignment\n\
1927 >: big-endian, std. size & alignment\n\
1928 !: same as >\n\
Christian Heimesa34706f2008-01-04 03:06:10 +00001929\n\
1930The remaining chars indicate types of args and must match exactly;\n\
1931these can be preceded by a decimal repeat count:\n\
1932 x: pad byte (no data); c:char; b:signed byte; B:unsigned byte;\n\
Mark Dickinson40714af2009-10-08 15:59:20 +00001933 ?: _Bool (requires C99; if not available, char is used instead)\n\
Christian Heimesa34706f2008-01-04 03:06:10 +00001934 h:short; H:unsigned short; i:int; I:unsigned int;\n\
1935 l:long; L:unsigned long; f:float; d:double.\n\
1936Special cases (preceding decimal count indicates length):\n\
1937 s:string (array of char); p: pascal string (with count byte).\n\
1938Special case (only available in native format):\n\
1939 P:an integer type that is wide enough to hold a pointer.\n\
1940Special case (not in native mode unless 'long long' in platform C):\n\
1941 q:long long; Q:unsigned long long\n\
1942Whitespace between formats is ignored.\n\
1943\n\
1944The variable struct.error is an exception raised on errors.\n");
1945
Martin v. Löwis1a214512008-06-11 05:26:20 +00001946
1947static struct PyModuleDef _structmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001948 PyModuleDef_HEAD_INIT,
1949 "_struct",
1950 module_doc,
1951 -1,
1952 module_functions,
1953 NULL,
1954 NULL,
1955 NULL,
1956 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001957};
1958
Thomas Wouters477c8d52006-05-27 19:21:47 +00001959PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001960PyInit__struct(void)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001961{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001962 PyObject *ver, *m;
Christian Heimesa34706f2008-01-04 03:06:10 +00001963
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001964 ver = PyBytes_FromString("0.3");
1965 if (ver == NULL)
1966 return NULL;
Christian Heimesa34706f2008-01-04 03:06:10 +00001967
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001968 m = PyModule_Create(&_structmodule);
1969 if (m == NULL)
1970 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001971
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001972 Py_TYPE(&PyStructType) = &PyType_Type;
1973 if (PyType_Ready(&PyStructType) < 0)
1974 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001975
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001976 /* Check endian and swap in faster functions */
1977 {
1978 int one = 1;
1979 formatdef *native = native_table;
1980 formatdef *other, *ptr;
1981 if ((int)*(unsigned char*)&one)
1982 other = lilendian_table;
1983 else
1984 other = bigendian_table;
1985 /* Scan through the native table, find a matching
1986 entry in the endian table and swap in the
1987 native implementations whenever possible
1988 (64-bit platforms may not have "standard" sizes) */
1989 while (native->format != '\0' && other->format != '\0') {
1990 ptr = other;
1991 while (ptr->format != '\0') {
1992 if (ptr->format == native->format) {
1993 /* Match faster when formats are
1994 listed in the same order */
1995 if (ptr == other)
1996 other++;
1997 /* Only use the trick if the
1998 size matches */
1999 if (ptr->size != native->size)
2000 break;
2001 /* Skip float and double, could be
2002 "unknown" float format */
2003 if (ptr->format == 'd' || ptr->format == 'f')
2004 break;
2005 ptr->pack = native->pack;
2006 ptr->unpack = native->unpack;
2007 break;
2008 }
2009 ptr++;
2010 }
2011 native++;
2012 }
2013 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002015 /* Add some symbolic constants to the module */
2016 if (StructError == NULL) {
2017 StructError = PyErr_NewException("struct.error", NULL, NULL);
2018 if (StructError == NULL)
2019 return NULL;
2020 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002022 Py_INCREF(StructError);
2023 PyModule_AddObject(m, "error", StructError);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002024
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002025 Py_INCREF((PyObject*)&PyStructType);
2026 PyModule_AddObject(m, "Struct", (PyObject*)&PyStructType);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002028 PyModule_AddObject(m, "__version__", ver);
Christian Heimesa34706f2008-01-04 03:06:10 +00002029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002030 return m;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002031}