blob: d000df20514f1050c858ff8a6c7009e87acebfca [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 {
17 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 *);
24} formatdef;
25
26typedef struct _formatcode {
27 const struct _formatdef *fmtdef;
28 Py_ssize_t offset;
29 Py_ssize_t size;
30} formatcode;
31
32/* Struct object interface */
33
34typedef struct {
35 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 */
41} 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{
Thomas Wouters477c8d52006-05-27 19:21:47 +000098 assert(v != NULL);
Mark Dickinsonea835e72009-04-19 20:40:33 +000099 if (!PyLong_Check(v)) {
Mark Dickinsonc5935772010-04-03 15:54:36 +0000100 /* 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 if (!PyLong_Check(v)) {
106 PyErr_SetString(PyExc_TypeError,
107 "__index__ method "
108 "returned non-integer");
109 return NULL;
110 }
111 }
112 else {
113 PyErr_SetString(StructError,
114 "required argument is not an integer");
115 return NULL;
116 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000117 }
Mark Dickinsonc5935772010-04-03 15:54:36 +0000118 else
119 Py_INCREF(v);
Mark Dickinsonea835e72009-04-19 20:40:33 +0000120
Mark Dickinsonea835e72009-04-19 20:40:33 +0000121 return v;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000122}
123
Mark Dickinsonea835e72009-04-19 20:40:33 +0000124/* Helper routine to get a C long and raise the appropriate error if it isn't
125 one */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000126
127static int
128get_long(PyObject *v, long *p)
129{
Mark Dickinsonea835e72009-04-19 20:40:33 +0000130 long x;
131
Mark Dickinson055a3fb2010-04-03 15:26:31 +0000132 v = get_pylong(v);
133 if (v == NULL)
Mark Dickinsonea835e72009-04-19 20:40:33 +0000134 return -1;
Mark Dickinson055a3fb2010-04-03 15:26:31 +0000135 assert(PyLong_Check(v));
Mark Dickinsonea835e72009-04-19 20:40:33 +0000136 x = PyLong_AsLong(v);
Mark Dickinson055a3fb2010-04-03 15:26:31 +0000137 Py_DECREF(v);
138 if (x == (long)-1 && PyErr_Occurred()) {
Mark Dickinsonea835e72009-04-19 20:40:33 +0000139 if (PyErr_ExceptionMatches(PyExc_OverflowError))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000140 PyErr_SetString(StructError,
Mark Dickinsonea835e72009-04-19 20:40:33 +0000141 "argument out of range");
Thomas Wouters477c8d52006-05-27 19:21:47 +0000142 return -1;
143 }
144 *p = x;
145 return 0;
146}
147
148
149/* Same, but handling unsigned long */
150
151static int
152get_ulong(PyObject *v, unsigned long *p)
153{
Mark Dickinsonea835e72009-04-19 20:40:33 +0000154 unsigned long x;
155
Mark Dickinson055a3fb2010-04-03 15:26:31 +0000156 v = get_pylong(v);
157 if (v == NULL)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000158 return -1;
Mark Dickinson055a3fb2010-04-03 15:26:31 +0000159 assert(PyLong_Check(v));
Mark Dickinsonea835e72009-04-19 20:40:33 +0000160 x = PyLong_AsUnsignedLong(v);
Benjamin Peterson04e8bcb2010-04-03 23:56:48 +0000161 Py_DECREF(v);
Mark Dickinsonea835e72009-04-19 20:40:33 +0000162 if (x == (unsigned long)-1 && PyErr_Occurred()) {
163 if (PyErr_ExceptionMatches(PyExc_OverflowError))
164 PyErr_SetString(StructError,
165 "argument out of range");
166 return -1;
167 }
168 *p = x;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000169 return 0;
170}
171
172#ifdef HAVE_LONG_LONG
173
174/* Same, but handling native long long. */
175
176static int
177get_longlong(PyObject *v, PY_LONG_LONG *p)
178{
179 PY_LONG_LONG x;
Mark Dickinson055a3fb2010-04-03 15:26:31 +0000180
181 v = get_pylong(v);
182 if (v == NULL)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000183 return -1;
Mark Dickinson055a3fb2010-04-03 15:26:31 +0000184 assert(PyLong_Check(v));
Thomas Wouters477c8d52006-05-27 19:21:47 +0000185 x = PyLong_AsLongLong(v);
Benjamin Peterson04e8bcb2010-04-03 23:56:48 +0000186 Py_DECREF(v);
Mark Dickinson055a3fb2010-04-03 15:26:31 +0000187 if (x == (PY_LONG_LONG)-1 && PyErr_Occurred()) {
Mark Dickinsonea835e72009-04-19 20:40:33 +0000188 if (PyErr_ExceptionMatches(PyExc_OverflowError))
189 PyErr_SetString(StructError,
190 "argument out of range");
Thomas Wouters477c8d52006-05-27 19:21:47 +0000191 return -1;
Mark Dickinsonea835e72009-04-19 20:40:33 +0000192 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000193 *p = x;
194 return 0;
195}
196
197/* Same, but handling native unsigned long long. */
198
199static int
200get_ulonglong(PyObject *v, unsigned PY_LONG_LONG *p)
201{
202 unsigned PY_LONG_LONG x;
Mark Dickinson055a3fb2010-04-03 15:26:31 +0000203
204 v = get_pylong(v);
205 if (v == NULL)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000206 return -1;
Mark Dickinson055a3fb2010-04-03 15:26:31 +0000207 assert(PyLong_Check(v));
Thomas Wouters477c8d52006-05-27 19:21:47 +0000208 x = PyLong_AsUnsignedLongLong(v);
Benjamin Peterson04e8bcb2010-04-03 23:56:48 +0000209 Py_DECREF(v);
Mark Dickinson055a3fb2010-04-03 15:26:31 +0000210 if (x == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred()) {
Mark Dickinsonea835e72009-04-19 20:40:33 +0000211 if (PyErr_ExceptionMatches(PyExc_OverflowError))
212 PyErr_SetString(StructError,
213 "argument out of range");
Thomas Wouters477c8d52006-05-27 19:21:47 +0000214 return -1;
Mark Dickinsonea835e72009-04-19 20:40:33 +0000215 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000216 *p = x;
217 return 0;
218}
219
220#endif
221
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000222
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000223#define RANGE_ERROR(x, f, flag, mask) return _range_error(f, flag)
224
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000225
Thomas Wouters477c8d52006-05-27 19:21:47 +0000226/* Floating point helpers */
227
228static PyObject *
229unpack_float(const char *p, /* start of 4-byte string */
230 int le) /* true for little-endian, false for big-endian */
231{
232 double x;
233
234 x = _PyFloat_Unpack4((unsigned char *)p, le);
235 if (x == -1.0 && PyErr_Occurred())
236 return NULL;
237 return PyFloat_FromDouble(x);
238}
239
240static PyObject *
241unpack_double(const char *p, /* start of 8-byte string */
242 int le) /* true for little-endian, false for big-endian */
243{
244 double x;
245
246 x = _PyFloat_Unpack8((unsigned char *)p, le);
247 if (x == -1.0 && PyErr_Occurred())
248 return NULL;
249 return PyFloat_FromDouble(x);
250}
251
252/* Helper to format the range error exceptions */
253static int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000254_range_error(const formatdef *f, int is_unsigned)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000255{
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000256 /* ulargest is the largest unsigned value with f->size bytes.
257 * Note that the simpler:
258 * ((size_t)1 << (f->size * 8)) - 1
259 * doesn't work when f->size == sizeof(size_t) because C doesn't
260 * define what happens when a left shift count is >= the number of
261 * bits in the integer being shifted; e.g., on some boxes it doesn't
262 * shift at all when they're equal.
263 */
264 const size_t ulargest = (size_t)-1 >> ((SIZEOF_SIZE_T - f->size)*8);
265 assert(f->size >= 1 && f->size <= SIZEOF_SIZE_T);
266 if (is_unsigned)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000267 PyErr_Format(StructError,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000268 "'%c' format requires 0 <= number <= %zu",
269 f->format,
270 ulargest);
271 else {
272 const Py_ssize_t largest = (Py_ssize_t)(ulargest >> 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000273 PyErr_Format(StructError,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000274 "'%c' format requires %zd <= number <= %zd",
275 f->format,
276 ~ largest,
Thomas Wouters477c8d52006-05-27 19:21:47 +0000277 largest);
278 }
Mark Dickinsonae681df2009-03-21 10:26:31 +0000279
Thomas Wouters477c8d52006-05-27 19:21:47 +0000280 return -1;
281}
282
283
284
285/* A large number of small routines follow, with names of the form
286
287 [bln][up]_TYPE
288
289 [bln] distiguishes among big-endian, little-endian and native.
290 [pu] distiguishes between pack (to struct) and unpack (from struct).
291 TYPE is one of char, byte, ubyte, etc.
292*/
293
294/* Native mode routines. ****************************************************/
295/* NOTE:
296 In all n[up]_<type> routines handling types larger than 1 byte, there is
297 *no* guarantee that the p pointer is properly aligned for each type,
298 therefore memcpy is called. An intermediate variable is used to
299 compensate for big-endian architectures.
300 Normally both the intermediate variable and the memcpy call will be
301 skipped by C optimisation in little-endian architectures (gcc >= 2.91
302 does this). */
303
304static PyObject *
305nu_char(const char *p, const formatdef *f)
306{
Christian Heimes72b710a2008-05-26 13:28:38 +0000307 return PyBytes_FromStringAndSize(p, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000308}
309
310static PyObject *
311nu_byte(const char *p, const formatdef *f)
312{
Christian Heimes217cfd12007-12-02 14:31:20 +0000313 return PyLong_FromLong((long) *(signed char *)p);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000314}
315
316static PyObject *
317nu_ubyte(const char *p, const formatdef *f)
318{
Christian Heimes217cfd12007-12-02 14:31:20 +0000319 return PyLong_FromLong((long) *(unsigned char *)p);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000320}
321
322static PyObject *
323nu_short(const char *p, const formatdef *f)
324{
325 short x;
326 memcpy((char *)&x, p, sizeof x);
Christian Heimes217cfd12007-12-02 14:31:20 +0000327 return PyLong_FromLong((long)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000328}
329
330static PyObject *
331nu_ushort(const char *p, const formatdef *f)
332{
333 unsigned short x;
334 memcpy((char *)&x, p, sizeof x);
Christian Heimes217cfd12007-12-02 14:31:20 +0000335 return PyLong_FromLong((long)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000336}
337
338static PyObject *
339nu_int(const char *p, const formatdef *f)
340{
341 int x;
342 memcpy((char *)&x, p, sizeof x);
Christian Heimes217cfd12007-12-02 14:31:20 +0000343 return PyLong_FromLong((long)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000344}
345
346static PyObject *
347nu_uint(const char *p, const formatdef *f)
348{
349 unsigned int x;
350 memcpy((char *)&x, p, sizeof x);
351#if (SIZEOF_LONG > SIZEOF_INT)
Christian Heimes217cfd12007-12-02 14:31:20 +0000352 return PyLong_FromLong((long)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000353#else
354 if (x <= ((unsigned int)LONG_MAX))
Christian Heimes217cfd12007-12-02 14:31:20 +0000355 return PyLong_FromLong((long)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000356 return PyLong_FromUnsignedLong((unsigned long)x);
357#endif
358}
359
360static PyObject *
361nu_long(const char *p, const formatdef *f)
362{
363 long x;
364 memcpy((char *)&x, p, sizeof x);
Christian Heimes217cfd12007-12-02 14:31:20 +0000365 return PyLong_FromLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000366}
367
368static PyObject *
369nu_ulong(const char *p, const formatdef *f)
370{
371 unsigned long x;
372 memcpy((char *)&x, p, sizeof x);
373 if (x <= LONG_MAX)
Christian Heimes217cfd12007-12-02 14:31:20 +0000374 return PyLong_FromLong((long)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000375 return PyLong_FromUnsignedLong(x);
376}
377
378/* Native mode doesn't support q or Q unless the platform C supports
379 long long (or, on Windows, __int64). */
380
381#ifdef HAVE_LONG_LONG
382
383static PyObject *
384nu_longlong(const char *p, const formatdef *f)
385{
386 PY_LONG_LONG x;
387 memcpy((char *)&x, p, sizeof x);
388 if (x >= LONG_MIN && x <= LONG_MAX)
Christian Heimes217cfd12007-12-02 14:31:20 +0000389 return PyLong_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long));
Thomas Wouters477c8d52006-05-27 19:21:47 +0000390 return PyLong_FromLongLong(x);
391}
392
393static PyObject *
394nu_ulonglong(const char *p, const formatdef *f)
395{
396 unsigned PY_LONG_LONG x;
397 memcpy((char *)&x, p, sizeof x);
398 if (x <= LONG_MAX)
Christian Heimes217cfd12007-12-02 14:31:20 +0000399 return PyLong_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long));
Thomas Wouters477c8d52006-05-27 19:21:47 +0000400 return PyLong_FromUnsignedLongLong(x);
401}
402
403#endif
404
405static PyObject *
Thomas Woutersb2137042007-02-01 18:02:27 +0000406nu_bool(const char *p, const formatdef *f)
407{
408 BOOL_TYPE x;
409 memcpy((char *)&x, p, sizeof x);
410 return PyBool_FromLong(x != 0);
411}
412
413
414static PyObject *
Thomas Wouters477c8d52006-05-27 19:21:47 +0000415nu_float(const char *p, const formatdef *f)
416{
417 float x;
418 memcpy((char *)&x, p, sizeof x);
419 return PyFloat_FromDouble((double)x);
420}
421
422static PyObject *
423nu_double(const char *p, const formatdef *f)
424{
425 double x;
426 memcpy((char *)&x, p, sizeof x);
427 return PyFloat_FromDouble(x);
428}
429
430static PyObject *
431nu_void_p(const char *p, const formatdef *f)
432{
433 void *x;
434 memcpy((char *)&x, p, sizeof x);
435 return PyLong_FromVoidPtr(x);
436}
437
438static int
439np_byte(char *p, PyObject *v, const formatdef *f)
440{
441 long x;
442 if (get_long(v, &x) < 0)
443 return -1;
444 if (x < -128 || x > 127){
445 PyErr_SetString(StructError,
446 "byte format requires -128 <= number <= 127");
447 return -1;
448 }
449 *p = (char)x;
450 return 0;
451}
452
453static int
454np_ubyte(char *p, PyObject *v, const formatdef *f)
455{
456 long x;
457 if (get_long(v, &x) < 0)
458 return -1;
459 if (x < 0 || x > 255){
460 PyErr_SetString(StructError,
461 "ubyte format requires 0 <= number <= 255");
462 return -1;
463 }
464 *p = (char)x;
465 return 0;
466}
467
468static int
469np_char(char *p, PyObject *v, const formatdef *f)
470{
Guido van Rossume625fd52007-05-27 09:19:04 +0000471 if (PyUnicode_Check(v)) {
472 v = _PyUnicode_AsDefaultEncodedString(v, NULL);
473 if (v == NULL)
474 return -1;
475 }
Christian Heimes72b710a2008-05-26 13:28:38 +0000476 if (!PyBytes_Check(v) || PyBytes_Size(v) != 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +0000477 PyErr_SetString(StructError,
Benjamin Peterson4ae19462008-07-31 15:03:40 +0000478 "char format requires bytes or string of length 1");
Thomas Wouters477c8d52006-05-27 19:21:47 +0000479 return -1;
480 }
Christian Heimes72b710a2008-05-26 13:28:38 +0000481 *p = *PyBytes_AsString(v);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000482 return 0;
483}
484
485static int
486np_short(char *p, PyObject *v, const formatdef *f)
487{
488 long x;
489 short y;
490 if (get_long(v, &x) < 0)
491 return -1;
492 if (x < SHRT_MIN || x > SHRT_MAX){
493 PyErr_SetString(StructError,
494 "short format requires " STRINGIFY(SHRT_MIN)
495 " <= number <= " STRINGIFY(SHRT_MAX));
496 return -1;
497 }
498 y = (short)x;
499 memcpy(p, (char *)&y, sizeof y);
500 return 0;
501}
502
503static int
504np_ushort(char *p, PyObject *v, const formatdef *f)
505{
506 long x;
507 unsigned short y;
508 if (get_long(v, &x) < 0)
509 return -1;
510 if (x < 0 || x > USHRT_MAX){
511 PyErr_SetString(StructError,
Mark Dickinsond99620d2009-07-07 10:21:03 +0000512 "ushort format requires 0 <= number <= " STRINGIFY(USHRT_MAX));
Thomas Wouters477c8d52006-05-27 19:21:47 +0000513 return -1;
514 }
515 y = (unsigned short)x;
516 memcpy(p, (char *)&y, sizeof y);
517 return 0;
518}
519
520static int
521np_int(char *p, PyObject *v, const formatdef *f)
522{
523 long x;
524 int y;
525 if (get_long(v, &x) < 0)
526 return -1;
527#if (SIZEOF_LONG > SIZEOF_INT)
528 if ((x < ((long)INT_MIN)) || (x > ((long)INT_MAX)))
Georg Brandlb1441c72009-01-03 22:33:39 +0000529 RANGE_ERROR(x, f, 0, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000530#endif
531 y = (int)x;
532 memcpy(p, (char *)&y, sizeof y);
533 return 0;
534}
535
536static int
537np_uint(char *p, PyObject *v, const formatdef *f)
538{
539 unsigned long x;
540 unsigned int y;
Mark Dickinsonae681df2009-03-21 10:26:31 +0000541 if (get_ulong(v, &x) < 0)
Georg Brandlb1441c72009-01-03 22:33:39 +0000542 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000543 y = (unsigned int)x;
544#if (SIZEOF_LONG > SIZEOF_INT)
545 if (x > ((unsigned long)UINT_MAX))
Georg Brandlb1441c72009-01-03 22:33:39 +0000546 RANGE_ERROR(y, f, 1, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000547#endif
548 memcpy(p, (char *)&y, sizeof y);
549 return 0;
550}
551
552static int
553np_long(char *p, PyObject *v, const formatdef *f)
554{
555 long x;
556 if (get_long(v, &x) < 0)
557 return -1;
558 memcpy(p, (char *)&x, sizeof x);
559 return 0;
560}
561
562static int
563np_ulong(char *p, PyObject *v, const formatdef *f)
564{
565 unsigned long x;
Mark Dickinsonae681df2009-03-21 10:26:31 +0000566 if (get_ulong(v, &x) < 0)
Georg Brandlb1441c72009-01-03 22:33:39 +0000567 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000568 memcpy(p, (char *)&x, sizeof x);
569 return 0;
570}
571
572#ifdef HAVE_LONG_LONG
573
574static int
575np_longlong(char *p, PyObject *v, const formatdef *f)
576{
577 PY_LONG_LONG x;
578 if (get_longlong(v, &x) < 0)
579 return -1;
580 memcpy(p, (char *)&x, sizeof x);
581 return 0;
582}
583
584static int
585np_ulonglong(char *p, PyObject *v, const formatdef *f)
586{
587 unsigned PY_LONG_LONG x;
588 if (get_ulonglong(v, &x) < 0)
589 return -1;
590 memcpy(p, (char *)&x, sizeof x);
591 return 0;
592}
593#endif
594
Thomas Woutersb2137042007-02-01 18:02:27 +0000595
596static int
597np_bool(char *p, PyObject *v, const formatdef *f)
598{
599 BOOL_TYPE y;
600 y = PyObject_IsTrue(v);
601 memcpy(p, (char *)&y, sizeof y);
602 return 0;
603}
604
Thomas Wouters477c8d52006-05-27 19:21:47 +0000605static int
606np_float(char *p, PyObject *v, const formatdef *f)
607{
608 float x = (float)PyFloat_AsDouble(v);
609 if (x == -1 && PyErr_Occurred()) {
610 PyErr_SetString(StructError,
611 "required argument is not a float");
612 return -1;
613 }
614 memcpy(p, (char *)&x, sizeof x);
615 return 0;
616}
617
618static int
619np_double(char *p, PyObject *v, const formatdef *f)
620{
621 double x = PyFloat_AsDouble(v);
622 if (x == -1 && PyErr_Occurred()) {
623 PyErr_SetString(StructError,
624 "required argument is not a float");
625 return -1;
626 }
627 memcpy(p, (char *)&x, sizeof(double));
628 return 0;
629}
630
631static int
632np_void_p(char *p, PyObject *v, const formatdef *f)
633{
634 void *x;
635
636 v = get_pylong(v);
637 if (v == NULL)
638 return -1;
639 assert(PyLong_Check(v));
640 x = PyLong_AsVoidPtr(v);
641 Py_DECREF(v);
642 if (x == NULL && PyErr_Occurred())
643 return -1;
644 memcpy(p, (char *)&x, sizeof x);
645 return 0;
646}
647
648static formatdef native_table[] = {
649 {'x', sizeof(char), 0, NULL},
650 {'b', sizeof(char), 0, nu_byte, np_byte},
651 {'B', sizeof(char), 0, nu_ubyte, np_ubyte},
652 {'c', sizeof(char), 0, nu_char, np_char},
653 {'s', sizeof(char), 0, NULL},
654 {'p', sizeof(char), 0, NULL},
655 {'h', sizeof(short), SHORT_ALIGN, nu_short, np_short},
656 {'H', sizeof(short), SHORT_ALIGN, nu_ushort, np_ushort},
657 {'i', sizeof(int), INT_ALIGN, nu_int, np_int},
658 {'I', sizeof(int), INT_ALIGN, nu_uint, np_uint},
659 {'l', sizeof(long), LONG_ALIGN, nu_long, np_long},
660 {'L', sizeof(long), LONG_ALIGN, nu_ulong, np_ulong},
661#ifdef HAVE_LONG_LONG
662 {'q', sizeof(PY_LONG_LONG), LONG_LONG_ALIGN, nu_longlong, np_longlong},
663 {'Q', sizeof(PY_LONG_LONG), LONG_LONG_ALIGN, nu_ulonglong,np_ulonglong},
664#endif
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000665 {'?', sizeof(BOOL_TYPE), BOOL_ALIGN, nu_bool, np_bool},
Thomas Wouters477c8d52006-05-27 19:21:47 +0000666 {'f', sizeof(float), FLOAT_ALIGN, nu_float, np_float},
667 {'d', sizeof(double), DOUBLE_ALIGN, nu_double, np_double},
668 {'P', sizeof(void *), VOID_P_ALIGN, nu_void_p, np_void_p},
669 {0}
670};
671
672/* Big-endian routines. *****************************************************/
673
674static PyObject *
675bu_int(const char *p, const formatdef *f)
676{
677 long x = 0;
678 Py_ssize_t i = f->size;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000679 const unsigned char *bytes = (const unsigned char *)p;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000680 do {
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000681 x = (x<<8) | *bytes++;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000682 } while (--i > 0);
683 /* Extend the sign bit. */
684 if (SIZEOF_LONG > f->size)
685 x |= -(x & (1L << ((8 * f->size) - 1)));
Christian Heimes217cfd12007-12-02 14:31:20 +0000686 return PyLong_FromLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000687}
688
689static PyObject *
690bu_uint(const char *p, const formatdef *f)
691{
692 unsigned long x = 0;
693 Py_ssize_t i = f->size;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000694 const unsigned char *bytes = (const unsigned char *)p;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000695 do {
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000696 x = (x<<8) | *bytes++;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000697 } while (--i > 0);
698 if (x <= LONG_MAX)
Christian Heimes217cfd12007-12-02 14:31:20 +0000699 return PyLong_FromLong((long)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000700 return PyLong_FromUnsignedLong(x);
701}
702
703static PyObject *
704bu_longlong(const char *p, const formatdef *f)
705{
706#ifdef HAVE_LONG_LONG
707 PY_LONG_LONG x = 0;
708 Py_ssize_t i = f->size;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000709 const unsigned char *bytes = (const unsigned char *)p;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000710 do {
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000711 x = (x<<8) | *bytes++;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000712 } while (--i > 0);
713 /* Extend the sign bit. */
714 if (SIZEOF_LONG_LONG > f->size)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000715 x |= -(x & ((PY_LONG_LONG)1 << ((8 * f->size) - 1)));
Thomas Wouters477c8d52006-05-27 19:21:47 +0000716 if (x >= LONG_MIN && x <= LONG_MAX)
Christian Heimes217cfd12007-12-02 14:31:20 +0000717 return PyLong_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long));
Thomas Wouters477c8d52006-05-27 19:21:47 +0000718 return PyLong_FromLongLong(x);
719#else
720 return _PyLong_FromByteArray((const unsigned char *)p,
721 8,
722 0, /* little-endian */
723 1 /* signed */);
724#endif
725}
726
727static PyObject *
728bu_ulonglong(const char *p, const formatdef *f)
729{
730#ifdef HAVE_LONG_LONG
731 unsigned PY_LONG_LONG x = 0;
732 Py_ssize_t i = f->size;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000733 const unsigned char *bytes = (const unsigned char *)p;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000734 do {
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000735 x = (x<<8) | *bytes++;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000736 } while (--i > 0);
737 if (x <= LONG_MAX)
Christian Heimes217cfd12007-12-02 14:31:20 +0000738 return PyLong_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long));
Thomas Wouters477c8d52006-05-27 19:21:47 +0000739 return PyLong_FromUnsignedLongLong(x);
740#else
741 return _PyLong_FromByteArray((const unsigned char *)p,
742 8,
743 0, /* little-endian */
744 0 /* signed */);
745#endif
746}
747
748static PyObject *
749bu_float(const char *p, const formatdef *f)
750{
751 return unpack_float(p, 0);
752}
753
754static PyObject *
755bu_double(const char *p, const formatdef *f)
756{
757 return unpack_double(p, 0);
758}
759
Thomas Woutersb2137042007-02-01 18:02:27 +0000760static PyObject *
761bu_bool(const char *p, const formatdef *f)
762{
763 char x;
764 memcpy((char *)&x, p, sizeof x);
765 return PyBool_FromLong(x != 0);
766}
767
Thomas Wouters477c8d52006-05-27 19:21:47 +0000768static int
769bp_int(char *p, PyObject *v, const formatdef *f)
770{
771 long x;
772 Py_ssize_t i;
Mark Dickinsonae681df2009-03-21 10:26:31 +0000773 if (get_long(v, &x) < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000774 return -1;
775 i = f->size;
776 if (i != SIZEOF_LONG) {
777 if ((i == 2) && (x < -32768 || x > 32767))
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000778 RANGE_ERROR(x, f, 0, 0xffffL);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000779#if (SIZEOF_LONG != 4)
780 else if ((i == 4) && (x < -2147483648L || x > 2147483647L))
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000781 RANGE_ERROR(x, f, 0, 0xffffffffL);
782#endif
Thomas Wouters477c8d52006-05-27 19:21:47 +0000783 }
784 do {
785 p[--i] = (char)x;
786 x >>= 8;
787 } while (i > 0);
788 return 0;
789}
790
791static int
792bp_uint(char *p, PyObject *v, const formatdef *f)
793{
794 unsigned long x;
795 Py_ssize_t i;
Mark Dickinsonae681df2009-03-21 10:26:31 +0000796 if (get_ulong(v, &x) < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000797 return -1;
798 i = f->size;
799 if (i != SIZEOF_LONG) {
800 unsigned long maxint = 1;
801 maxint <<= (unsigned long)(i * 8);
802 if (x >= maxint)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000803 RANGE_ERROR(x, f, 1, maxint - 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000804 }
805 do {
806 p[--i] = (char)x;
807 x >>= 8;
808 } while (i > 0);
809 return 0;
810}
811
812static int
813bp_longlong(char *p, PyObject *v, const formatdef *f)
814{
815 int res;
816 v = get_pylong(v);
817 if (v == NULL)
818 return -1;
819 res = _PyLong_AsByteArray((PyLongObject *)v,
820 (unsigned char *)p,
821 8,
822 0, /* little_endian */
823 1 /* signed */);
824 Py_DECREF(v);
825 return res;
826}
827
828static int
829bp_ulonglong(char *p, PyObject *v, const formatdef *f)
830{
831 int res;
832 v = get_pylong(v);
833 if (v == NULL)
834 return -1;
835 res = _PyLong_AsByteArray((PyLongObject *)v,
836 (unsigned char *)p,
837 8,
838 0, /* little_endian */
839 0 /* signed */);
840 Py_DECREF(v);
841 return res;
842}
843
844static int
845bp_float(char *p, PyObject *v, const formatdef *f)
846{
847 double x = PyFloat_AsDouble(v);
848 if (x == -1 && PyErr_Occurred()) {
849 PyErr_SetString(StructError,
850 "required argument is not a float");
851 return -1;
852 }
853 return _PyFloat_Pack4(x, (unsigned char *)p, 0);
854}
855
856static int
857bp_double(char *p, PyObject *v, const formatdef *f)
858{
859 double x = PyFloat_AsDouble(v);
860 if (x == -1 && PyErr_Occurred()) {
861 PyErr_SetString(StructError,
862 "required argument is not a float");
863 return -1;
864 }
865 return _PyFloat_Pack8(x, (unsigned char *)p, 0);
866}
867
Thomas Woutersb2137042007-02-01 18:02:27 +0000868static int
869bp_bool(char *p, PyObject *v, const formatdef *f)
870{
871 char y;
872 y = PyObject_IsTrue(v);
873 memcpy(p, (char *)&y, sizeof y);
874 return 0;
875}
876
Thomas Wouters477c8d52006-05-27 19:21:47 +0000877static formatdef bigendian_table[] = {
878 {'x', 1, 0, NULL},
879 {'b', 1, 0, nu_byte, np_byte},
880 {'B', 1, 0, nu_ubyte, np_ubyte},
881 {'c', 1, 0, nu_char, np_char},
882 {'s', 1, 0, NULL},
883 {'p', 1, 0, NULL},
884 {'h', 2, 0, bu_int, bp_int},
885 {'H', 2, 0, bu_uint, bp_uint},
886 {'i', 4, 0, bu_int, bp_int},
887 {'I', 4, 0, bu_uint, bp_uint},
888 {'l', 4, 0, bu_int, bp_int},
889 {'L', 4, 0, bu_uint, bp_uint},
890 {'q', 8, 0, bu_longlong, bp_longlong},
891 {'Q', 8, 0, bu_ulonglong, bp_ulonglong},
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000892 {'?', 1, 0, bu_bool, bp_bool},
Thomas Wouters477c8d52006-05-27 19:21:47 +0000893 {'f', 4, 0, bu_float, bp_float},
894 {'d', 8, 0, bu_double, bp_double},
895 {0}
896};
897
898/* Little-endian routines. *****************************************************/
899
900static PyObject *
901lu_int(const char *p, const formatdef *f)
902{
903 long x = 0;
904 Py_ssize_t i = f->size;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000905 const unsigned char *bytes = (const unsigned char *)p;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000906 do {
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000907 x = (x<<8) | bytes[--i];
Thomas Wouters477c8d52006-05-27 19:21:47 +0000908 } while (i > 0);
909 /* Extend the sign bit. */
910 if (SIZEOF_LONG > f->size)
911 x |= -(x & (1L << ((8 * f->size) - 1)));
Christian Heimes217cfd12007-12-02 14:31:20 +0000912 return PyLong_FromLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000913}
914
915static PyObject *
916lu_uint(const char *p, const formatdef *f)
917{
918 unsigned long x = 0;
919 Py_ssize_t i = f->size;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000920 const unsigned char *bytes = (const unsigned char *)p;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000921 do {
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000922 x = (x<<8) | bytes[--i];
Thomas Wouters477c8d52006-05-27 19:21:47 +0000923 } while (i > 0);
924 if (x <= LONG_MAX)
Christian Heimes217cfd12007-12-02 14:31:20 +0000925 return PyLong_FromLong((long)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000926 return PyLong_FromUnsignedLong((long)x);
927}
928
929static PyObject *
930lu_longlong(const char *p, const formatdef *f)
931{
932#ifdef HAVE_LONG_LONG
933 PY_LONG_LONG x = 0;
934 Py_ssize_t i = f->size;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000935 const unsigned char *bytes = (const unsigned char *)p;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000936 do {
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000937 x = (x<<8) | bytes[--i];
Thomas Wouters477c8d52006-05-27 19:21:47 +0000938 } while (i > 0);
939 /* Extend the sign bit. */
940 if (SIZEOF_LONG_LONG > f->size)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000941 x |= -(x & ((PY_LONG_LONG)1 << ((8 * f->size) - 1)));
Thomas Wouters477c8d52006-05-27 19:21:47 +0000942 if (x >= LONG_MIN && x <= LONG_MAX)
Christian Heimes217cfd12007-12-02 14:31:20 +0000943 return PyLong_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long));
Thomas Wouters477c8d52006-05-27 19:21:47 +0000944 return PyLong_FromLongLong(x);
945#else
946 return _PyLong_FromByteArray((const unsigned char *)p,
947 8,
948 1, /* little-endian */
949 1 /* signed */);
950#endif
951}
952
953static PyObject *
954lu_ulonglong(const char *p, const formatdef *f)
955{
956#ifdef HAVE_LONG_LONG
957 unsigned PY_LONG_LONG x = 0;
958 Py_ssize_t i = f->size;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000959 const unsigned char *bytes = (const unsigned char *)p;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000960 do {
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000961 x = (x<<8) | bytes[--i];
Thomas Wouters477c8d52006-05-27 19:21:47 +0000962 } while (i > 0);
963 if (x <= LONG_MAX)
Christian Heimes217cfd12007-12-02 14:31:20 +0000964 return PyLong_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long));
Thomas Wouters477c8d52006-05-27 19:21:47 +0000965 return PyLong_FromUnsignedLongLong(x);
966#else
967 return _PyLong_FromByteArray((const unsigned char *)p,
968 8,
969 1, /* little-endian */
970 0 /* signed */);
971#endif
972}
973
974static PyObject *
975lu_float(const char *p, const formatdef *f)
976{
977 return unpack_float(p, 1);
978}
979
980static PyObject *
981lu_double(const char *p, const formatdef *f)
982{
983 return unpack_double(p, 1);
984}
985
986static int
987lp_int(char *p, PyObject *v, const formatdef *f)
988{
989 long x;
990 Py_ssize_t i;
Mark Dickinsonae681df2009-03-21 10:26:31 +0000991 if (get_long(v, &x) < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000992 return -1;
993 i = f->size;
994 if (i != SIZEOF_LONG) {
995 if ((i == 2) && (x < -32768 || x > 32767))
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000996 RANGE_ERROR(x, f, 0, 0xffffL);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000997#if (SIZEOF_LONG != 4)
998 else if ((i == 4) && (x < -2147483648L || x > 2147483647L))
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000999 RANGE_ERROR(x, f, 0, 0xffffffffL);
1000#endif
Thomas Wouters477c8d52006-05-27 19:21:47 +00001001 }
1002 do {
1003 *p++ = (char)x;
1004 x >>= 8;
1005 } while (--i > 0);
1006 return 0;
1007}
1008
1009static int
1010lp_uint(char *p, PyObject *v, const formatdef *f)
1011{
1012 unsigned long x;
1013 Py_ssize_t i;
Mark Dickinsonae681df2009-03-21 10:26:31 +00001014 if (get_ulong(v, &x) < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001015 return -1;
1016 i = f->size;
1017 if (i != SIZEOF_LONG) {
1018 unsigned long maxint = 1;
1019 maxint <<= (unsigned long)(i * 8);
1020 if (x >= maxint)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001021 RANGE_ERROR(x, f, 1, maxint - 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001022 }
1023 do {
1024 *p++ = (char)x;
1025 x >>= 8;
1026 } while (--i > 0);
1027 return 0;
1028}
1029
1030static int
1031lp_longlong(char *p, PyObject *v, const formatdef *f)
1032{
1033 int res;
1034 v = get_pylong(v);
1035 if (v == NULL)
1036 return -1;
1037 res = _PyLong_AsByteArray((PyLongObject*)v,
1038 (unsigned char *)p,
1039 8,
1040 1, /* little_endian */
1041 1 /* signed */);
1042 Py_DECREF(v);
1043 return res;
1044}
1045
1046static int
1047lp_ulonglong(char *p, PyObject *v, const formatdef *f)
1048{
1049 int res;
1050 v = get_pylong(v);
1051 if (v == NULL)
1052 return -1;
1053 res = _PyLong_AsByteArray((PyLongObject*)v,
1054 (unsigned char *)p,
1055 8,
1056 1, /* little_endian */
1057 0 /* signed */);
1058 Py_DECREF(v);
1059 return res;
1060}
1061
1062static int
1063lp_float(char *p, PyObject *v, const formatdef *f)
1064{
1065 double x = PyFloat_AsDouble(v);
1066 if (x == -1 && PyErr_Occurred()) {
1067 PyErr_SetString(StructError,
1068 "required argument is not a float");
1069 return -1;
1070 }
1071 return _PyFloat_Pack4(x, (unsigned char *)p, 1);
1072}
1073
1074static int
1075lp_double(char *p, PyObject *v, const formatdef *f)
1076{
1077 double x = PyFloat_AsDouble(v);
1078 if (x == -1 && PyErr_Occurred()) {
1079 PyErr_SetString(StructError,
1080 "required argument is not a float");
1081 return -1;
1082 }
1083 return _PyFloat_Pack8(x, (unsigned char *)p, 1);
1084}
1085
1086static formatdef lilendian_table[] = {
1087 {'x', 1, 0, NULL},
1088 {'b', 1, 0, nu_byte, np_byte},
1089 {'B', 1, 0, nu_ubyte, np_ubyte},
1090 {'c', 1, 0, nu_char, np_char},
1091 {'s', 1, 0, NULL},
1092 {'p', 1, 0, NULL},
1093 {'h', 2, 0, lu_int, lp_int},
1094 {'H', 2, 0, lu_uint, lp_uint},
1095 {'i', 4, 0, lu_int, lp_int},
1096 {'I', 4, 0, lu_uint, lp_uint},
1097 {'l', 4, 0, lu_int, lp_int},
1098 {'L', 4, 0, lu_uint, lp_uint},
1099 {'q', 8, 0, lu_longlong, lp_longlong},
1100 {'Q', 8, 0, lu_ulonglong, lp_ulonglong},
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001101 {'?', 1, 0, bu_bool, bp_bool}, /* Std rep not endian dep,
Thomas Woutersb2137042007-02-01 18:02:27 +00001102 but potentially different from native rep -- reuse bx_bool funcs. */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001103 {'f', 4, 0, lu_float, lp_float},
1104 {'d', 8, 0, lu_double, lp_double},
1105 {0}
1106};
1107
1108
1109static const formatdef *
1110whichtable(char **pfmt)
1111{
1112 const char *fmt = (*pfmt)++; /* May be backed out of later */
1113 switch (*fmt) {
1114 case '<':
1115 return lilendian_table;
1116 case '>':
1117 case '!': /* Network byte order is big-endian */
1118 return bigendian_table;
1119 case '=': { /* Host byte order -- different from native in aligment! */
1120 int n = 1;
1121 char *p = (char *) &n;
1122 if (*p == 1)
1123 return lilendian_table;
1124 else
1125 return bigendian_table;
1126 }
1127 default:
1128 --*pfmt; /* Back out of pointer increment */
1129 /* Fall through */
1130 case '@':
1131 return native_table;
1132 }
1133}
1134
1135
1136/* Get the table entry for a format code */
1137
1138static const formatdef *
1139getentry(int c, const formatdef *f)
1140{
1141 for (; f->format != '\0'; f++) {
1142 if (f->format == c) {
1143 return f;
1144 }
1145 }
1146 PyErr_SetString(StructError, "bad char in struct format");
1147 return NULL;
1148}
1149
1150
1151/* Align a size according to a format code */
1152
1153static int
1154align(Py_ssize_t size, char c, const formatdef *e)
1155{
1156 if (e->format == c) {
1157 if (e->alignment) {
1158 size = ((size + e->alignment - 1)
1159 / e->alignment)
1160 * e->alignment;
1161 }
1162 }
1163 return size;
1164}
1165
1166
1167/* calculate the size of a format string */
1168
1169static int
1170prepare_s(PyStructObject *self)
1171{
1172 const formatdef *f;
1173 const formatdef *e;
1174 formatcode *codes;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001175
Thomas Wouters477c8d52006-05-27 19:21:47 +00001176 const char *s;
1177 const char *fmt;
1178 char c;
1179 Py_ssize_t size, len, num, itemsize, x;
1180
Christian Heimes72b710a2008-05-26 13:28:38 +00001181 fmt = PyBytes_AS_STRING(self->s_format);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001182
1183 f = whichtable((char **)&fmt);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001184
Thomas Wouters477c8d52006-05-27 19:21:47 +00001185 s = fmt;
1186 size = 0;
1187 len = 0;
1188 while ((c = *s++) != '\0') {
1189 if (isspace(Py_CHARMASK(c)))
1190 continue;
1191 if ('0' <= c && c <= '9') {
1192 num = c - '0';
1193 while ('0' <= (c = *s++) && c <= '9') {
1194 x = num*10 + (c - '0');
1195 if (x/10 != num) {
1196 PyErr_SetString(
1197 StructError,
1198 "overflow in item count");
1199 return -1;
1200 }
1201 num = x;
1202 }
1203 if (c == '\0')
1204 break;
1205 }
1206 else
1207 num = 1;
1208
1209 e = getentry(c, f);
1210 if (e == NULL)
1211 return -1;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001212
Thomas Wouters477c8d52006-05-27 19:21:47 +00001213 switch (c) {
1214 case 's': /* fall through */
1215 case 'p': len++; break;
1216 case 'x': break;
1217 default: len += num; break;
1218 }
1219
1220 itemsize = e->size;
1221 size = align(size, c, e);
1222 x = num * itemsize;
1223 size += x;
1224 if (x/itemsize != num || size < 0) {
1225 PyErr_SetString(StructError,
1226 "total struct size too long");
1227 return -1;
1228 }
1229 }
1230
Amaury Forgeot d'Arc35c86582008-06-17 21:11:29 +00001231 /* check for overflow */
1232 if ((len + 1) > (PY_SSIZE_T_MAX / sizeof(formatcode))) {
1233 PyErr_NoMemory();
1234 return -1;
1235 }
1236
Thomas Wouters477c8d52006-05-27 19:21:47 +00001237 self->s_size = size;
1238 self->s_len = len;
1239 codes = PyMem_MALLOC((len + 1) * sizeof(formatcode));
1240 if (codes == NULL) {
1241 PyErr_NoMemory();
1242 return -1;
1243 }
1244 self->s_codes = codes;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001245
Thomas Wouters477c8d52006-05-27 19:21:47 +00001246 s = fmt;
1247 size = 0;
1248 while ((c = *s++) != '\0') {
1249 if (isspace(Py_CHARMASK(c)))
1250 continue;
1251 if ('0' <= c && c <= '9') {
1252 num = c - '0';
1253 while ('0' <= (c = *s++) && c <= '9')
1254 num = num*10 + (c - '0');
1255 if (c == '\0')
1256 break;
1257 }
1258 else
1259 num = 1;
1260
1261 e = getentry(c, f);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001262
Thomas Wouters477c8d52006-05-27 19:21:47 +00001263 size = align(size, c, e);
1264 if (c == 's' || c == 'p') {
1265 codes->offset = size;
1266 codes->size = num;
1267 codes->fmtdef = e;
1268 codes++;
1269 size += num;
1270 } else if (c == 'x') {
1271 size += num;
1272 } else {
1273 while (--num >= 0) {
1274 codes->offset = size;
1275 codes->size = e->size;
1276 codes->fmtdef = e;
1277 codes++;
1278 size += e->size;
1279 }
1280 }
1281 }
1282 codes->fmtdef = NULL;
1283 codes->offset = size;
1284 codes->size = 0;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001285
Thomas Wouters477c8d52006-05-27 19:21:47 +00001286 return 0;
1287}
1288
1289static PyObject *
1290s_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1291{
1292 PyObject *self;
1293
1294 assert(type != NULL && type->tp_alloc != NULL);
1295
1296 self = type->tp_alloc(type, 0);
1297 if (self != NULL) {
1298 PyStructObject *s = (PyStructObject*)self;
1299 Py_INCREF(Py_None);
1300 s->s_format = Py_None;
1301 s->s_codes = NULL;
1302 s->s_size = -1;
1303 s->s_len = -1;
1304 }
1305 return self;
1306}
1307
1308static int
1309s_init(PyObject *self, PyObject *args, PyObject *kwds)
1310{
1311 PyStructObject *soself = (PyStructObject *)self;
1312 PyObject *o_format = NULL;
1313 int ret = 0;
1314 static char *kwlist[] = {"format", 0};
1315
1316 assert(PyStruct_Check(self));
1317
Christian Heimesa34706f2008-01-04 03:06:10 +00001318 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:Struct", kwlist,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001319 &o_format))
1320 return -1;
1321
Christian Heimesa34706f2008-01-04 03:06:10 +00001322 if (PyUnicode_Check(o_format)) {
1323 o_format = PyUnicode_AsASCIIString(o_format);
1324 if (o_format == NULL)
1325 return -1;
1326 }
1327 /* XXX support buffer interface, too */
1328 else {
1329 Py_INCREF(o_format);
1330 }
1331
Christian Heimes72b710a2008-05-26 13:28:38 +00001332 if (!PyBytes_Check(o_format)) {
Christian Heimesa34706f2008-01-04 03:06:10 +00001333 Py_DECREF(o_format);
1334 PyErr_Format(PyExc_TypeError,
1335 "Struct() argument 1 must be bytes, not %.200s",
1336 Py_TYPE(o_format)->tp_name);
1337 return -1;
1338 }
1339
Christian Heimes18c66892008-02-17 13:31:39 +00001340 Py_CLEAR(soself->s_format);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001341 soself->s_format = o_format;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001342
Thomas Wouters477c8d52006-05-27 19:21:47 +00001343 ret = prepare_s(soself);
1344 return ret;
1345}
1346
1347static void
1348s_dealloc(PyStructObject *s)
1349{
1350 if (s->weakreflist != NULL)
1351 PyObject_ClearWeakRefs((PyObject *)s);
1352 if (s->s_codes != NULL) {
1353 PyMem_FREE(s->s_codes);
1354 }
1355 Py_XDECREF(s->s_format);
Christian Heimes90aa7642007-12-19 02:45:37 +00001356 Py_TYPE(s)->tp_free((PyObject *)s);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001357}
1358
1359static PyObject *
1360s_unpack_internal(PyStructObject *soself, char *startfrom) {
1361 formatcode *code;
1362 Py_ssize_t i = 0;
1363 PyObject *result = PyTuple_New(soself->s_len);
1364 if (result == NULL)
1365 return NULL;
1366
1367 for (code = soself->s_codes; code->fmtdef != NULL; code++) {
1368 PyObject *v;
1369 const formatdef *e = code->fmtdef;
1370 const char *res = startfrom + code->offset;
1371 if (e->format == 's') {
Christian Heimes72b710a2008-05-26 13:28:38 +00001372 v = PyBytes_FromStringAndSize(res, code->size);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001373 } else if (e->format == 'p') {
1374 Py_ssize_t n = *(unsigned char*)res;
1375 if (n >= code->size)
1376 n = code->size - 1;
Christian Heimes72b710a2008-05-26 13:28:38 +00001377 v = PyBytes_FromStringAndSize(res + 1, n);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001378 } else {
1379 v = e->unpack(res, e);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001380 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001381 if (v == NULL)
1382 goto fail;
1383 PyTuple_SET_ITEM(result, i++, v);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001384 }
1385
1386 return result;
1387fail:
1388 Py_DECREF(result);
1389 return NULL;
1390}
1391
1392
1393PyDoc_STRVAR(s_unpack__doc__,
Guido van Rossum913dd0b2007-04-13 03:33:53 +00001394"S.unpack(buffer) -> (v1, v2, ...)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00001395\n\
1396Return tuple containing values unpacked according to this Struct's format.\n\
Guido van Rossum913dd0b2007-04-13 03:33:53 +00001397Requires len(buffer) == self.size. See struct.__doc__ for more on format\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00001398strings.");
1399
1400static PyObject *
Guido van Rossum98297ee2007-11-06 21:34:58 +00001401s_unpack(PyObject *self, PyObject *input)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001402{
Guido van Rossum98297ee2007-11-06 21:34:58 +00001403 Py_buffer vbuf;
1404 PyObject *result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001405 PyStructObject *soself = (PyStructObject *)self;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001406
Thomas Wouters477c8d52006-05-27 19:21:47 +00001407 assert(PyStruct_Check(self));
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001408 assert(soself->s_codes != NULL);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001409 if (PyObject_GetBuffer(input, &vbuf, PyBUF_SIMPLE) < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001410 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001411 if (vbuf.len != soself->s_size) {
1412 PyErr_Format(StructError,
1413 "unpack requires a bytes argument of length %zd",
1414 soself->s_size);
Martin v. Löwis423be952008-08-13 15:53:07 +00001415 PyBuffer_Release(&vbuf);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001416 return NULL;
1417 }
1418 result = s_unpack_internal(soself, vbuf.buf);
Martin v. Löwis423be952008-08-13 15:53:07 +00001419 PyBuffer_Release(&vbuf);
Guido van Rossumd8faa362007-04-27 19:54:29 +00001420 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001421}
1422
1423PyDoc_STRVAR(s_unpack_from__doc__,
1424"S.unpack_from(buffer[, offset]) -> (v1, v2, ...)\n\
1425\n\
1426Return tuple containing values unpacked according to this Struct's format.\n\
1427Unlike unpack, unpack_from can unpack values from any object supporting\n\
1428the buffer API, not just str. Requires len(buffer[offset:]) >= self.size.\n\
1429See struct.__doc__ for more on format strings.");
1430
1431static PyObject *
1432s_unpack_from(PyObject *self, PyObject *args, PyObject *kwds)
1433{
1434 static char *kwlist[] = {"buffer", "offset", 0};
Guido van Rossum98297ee2007-11-06 21:34:58 +00001435
1436 PyObject *input;
1437 Py_ssize_t offset = 0;
1438 Py_buffer vbuf;
1439 PyObject *result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001440 PyStructObject *soself = (PyStructObject *)self;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001441
Thomas Wouters477c8d52006-05-27 19:21:47 +00001442 assert(PyStruct_Check(self));
1443 assert(soself->s_codes != NULL);
1444
Guido van Rossum98297ee2007-11-06 21:34:58 +00001445 if (!PyArg_ParseTupleAndKeywords(args, kwds,
1446 "O|n:unpack_from", kwlist,
1447 &input, &offset))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001448 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001449 if (PyObject_GetBuffer(input, &vbuf, PyBUF_SIMPLE) < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001450 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001451 if (offset < 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00001452 offset += vbuf.len;
1453 if (offset < 0 || vbuf.len - offset < soself->s_size) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001454 PyErr_Format(StructError,
1455 "unpack_from requires a buffer of at least %zd bytes",
1456 soself->s_size);
Martin v. Löwis423be952008-08-13 15:53:07 +00001457 PyBuffer_Release(&vbuf);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001458 return NULL;
1459 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00001460 result = s_unpack_internal(soself, (char*)vbuf.buf + offset);
Martin v. Löwis423be952008-08-13 15:53:07 +00001461 PyBuffer_Release(&vbuf);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001462 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001463}
1464
1465
1466/*
1467 * Guts of the pack function.
1468 *
1469 * Takes a struct object, a tuple of arguments, and offset in that tuple of
1470 * argument for where to start processing the arguments for packing, and a
1471 * character buffer for writing the packed string. The caller must insure
1472 * that the buffer may contain the required length for packing the arguments.
1473 * 0 is returned on success, 1 is returned if there is an error.
1474 *
1475 */
1476static int
1477s_pack_internal(PyStructObject *soself, PyObject *args, int offset, char* buf)
1478{
1479 formatcode *code;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001480 /* XXX(nnorwitz): why does i need to be a local? can we use
1481 the offset parameter or do we need the wider width? */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001482 Py_ssize_t i;
1483
1484 memset(buf, '\0', soself->s_size);
1485 i = offset;
1486 for (code = soself->s_codes; code->fmtdef != NULL; code++) {
1487 Py_ssize_t n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001488 PyObject *v = PyTuple_GET_ITEM(args, i++);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001489 const formatdef *e = code->fmtdef;
1490 char *res = buf + code->offset;
1491 if (e->format == 's') {
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001492 int isstring;
1493 void *p;
1494 if (PyUnicode_Check(v)) {
1495 v = _PyUnicode_AsDefaultEncodedString(v, NULL);
1496 if (v == NULL)
1497 return -1;
1498 }
Christian Heimes72b710a2008-05-26 13:28:38 +00001499 isstring = PyBytes_Check(v);
Christian Heimes9c4756e2008-05-26 13:22:05 +00001500 if (!isstring && !PyByteArray_Check(v)) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001501 PyErr_SetString(StructError,
Benjamin Peterson4ae19462008-07-31 15:03:40 +00001502 "argument for 's' must be a bytes or string");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001503 return -1;
1504 }
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001505 if (isstring) {
Christian Heimes72b710a2008-05-26 13:28:38 +00001506 n = PyBytes_GET_SIZE(v);
1507 p = PyBytes_AS_STRING(v);
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001508 }
1509 else {
Christian Heimes9c4756e2008-05-26 13:22:05 +00001510 n = PyByteArray_GET_SIZE(v);
1511 p = PyByteArray_AS_STRING(v);
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001512 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001513 if (n > code->size)
1514 n = code->size;
1515 if (n > 0)
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001516 memcpy(res, p, n);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001517 } else if (e->format == 'p') {
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001518 int isstring;
1519 void *p;
1520 if (PyUnicode_Check(v)) {
1521 v = _PyUnicode_AsDefaultEncodedString(v, NULL);
1522 if (v == NULL)
1523 return -1;
1524 }
Christian Heimes72b710a2008-05-26 13:28:38 +00001525 isstring = PyBytes_Check(v);
Christian Heimes9c4756e2008-05-26 13:22:05 +00001526 if (!isstring && !PyByteArray_Check(v)) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001527 PyErr_SetString(StructError,
Benjamin Peterson4ae19462008-07-31 15:03:40 +00001528 "argument for 'p' must be a bytes or string");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001529 return -1;
1530 }
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001531 if (isstring) {
Christian Heimes72b710a2008-05-26 13:28:38 +00001532 n = PyBytes_GET_SIZE(v);
1533 p = PyBytes_AS_STRING(v);
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001534 }
1535 else {
Christian Heimes9c4756e2008-05-26 13:22:05 +00001536 n = PyByteArray_GET_SIZE(v);
1537 p = PyByteArray_AS_STRING(v);
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001538 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001539 if (n > (code->size - 1))
1540 n = code->size - 1;
1541 if (n > 0)
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001542 memcpy(res + 1, p, n);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001543 if (n > 255)
1544 n = 255;
1545 *res = Py_SAFE_DOWNCAST(n, Py_ssize_t, unsigned char);
1546 } else {
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001547 if (e->pack(res, v, e) < 0) {
1548 if (PyLong_Check(v) && PyErr_ExceptionMatches(PyExc_OverflowError))
1549 PyErr_SetString(StructError,
1550 "long too large to convert to int");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001551 return -1;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001552 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001553 }
1554 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001555
Thomas Wouters477c8d52006-05-27 19:21:47 +00001556 /* Success */
1557 return 0;
1558}
1559
1560
1561PyDoc_STRVAR(s_pack__doc__,
Benjamin Peterson4ae19462008-07-31 15:03:40 +00001562"S.pack(v1, v2, ...) -> bytes\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00001563\n\
Benjamin Peterson4ae19462008-07-31 15:03:40 +00001564Return a bytes containing values v1, v2, ... packed according to this\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00001565Struct's format. See struct.__doc__ for more on format strings.");
1566
1567static PyObject *
1568s_pack(PyObject *self, PyObject *args)
1569{
1570 PyStructObject *soself;
1571 PyObject *result;
1572
1573 /* Validate arguments. */
1574 soself = (PyStructObject *)self;
1575 assert(PyStruct_Check(self));
1576 assert(soself->s_codes != NULL);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001577 if (PyTuple_GET_SIZE(args) != soself->s_len)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001578 {
1579 PyErr_Format(StructError,
1580 "pack requires exactly %zd arguments", soself->s_len);
1581 return NULL;
1582 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001583
Thomas Wouters477c8d52006-05-27 19:21:47 +00001584 /* Allocate a new string */
Christian Heimes72b710a2008-05-26 13:28:38 +00001585 result = PyBytes_FromStringAndSize((char *)NULL, soself->s_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001586 if (result == NULL)
1587 return NULL;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001588
Thomas Wouters477c8d52006-05-27 19:21:47 +00001589 /* Call the guts */
Christian Heimes72b710a2008-05-26 13:28:38 +00001590 if ( s_pack_internal(soself, args, 0, PyBytes_AS_STRING(result)) != 0 ) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001591 Py_DECREF(result);
1592 return NULL;
1593 }
1594
1595 return result;
1596}
1597
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001598PyDoc_STRVAR(s_pack_into__doc__,
1599"S.pack_into(buffer, offset, v1, v2, ...)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00001600\n\
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001601Pack the values v1, v2, ... according to this Struct's format, write \n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00001602the packed bytes into the writable buffer buf starting at offset. Note\n\
1603that the offset is not an optional argument. See struct.__doc__ for \n\
1604more on format strings.");
1605
1606static PyObject *
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001607s_pack_into(PyObject *self, PyObject *args)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001608{
1609 PyStructObject *soself;
1610 char *buffer;
1611 Py_ssize_t buffer_len, offset;
1612
1613 /* Validate arguments. +1 is for the first arg as buffer. */
1614 soself = (PyStructObject *)self;
1615 assert(PyStruct_Check(self));
1616 assert(soself->s_codes != NULL);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001617 if (PyTuple_GET_SIZE(args) != (soself->s_len + 2))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001618 {
1619 PyErr_Format(StructError,
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001620 "pack_into requires exactly %zd arguments",
Thomas Wouters477c8d52006-05-27 19:21:47 +00001621 (soself->s_len + 2));
1622 return NULL;
1623 }
1624
1625 /* Extract a writable memory buffer from the first argument */
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001626 if ( PyObject_AsWriteBuffer(PyTuple_GET_ITEM(args, 0),
1627 (void**)&buffer, &buffer_len) == -1 ) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001628 return NULL;
1629 }
1630 assert( buffer_len >= 0 );
1631
1632 /* Extract the offset from the first argument */
Georg Brandl75c3d6f2009-02-13 11:01:07 +00001633 offset = PyNumber_AsSsize_t(PyTuple_GET_ITEM(args, 1), PyExc_IndexError);
Benjamin Petersona8a93042008-09-30 02:18:09 +00001634 if (offset == -1 && PyErr_Occurred())
1635 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001636
1637 /* Support negative offsets. */
1638 if (offset < 0)
1639 offset += buffer_len;
1640
1641 /* Check boundaries */
1642 if (offset < 0 || (buffer_len - offset) < soself->s_size) {
1643 PyErr_Format(StructError,
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001644 "pack_into requires a buffer of at least %zd bytes",
Thomas Wouters477c8d52006-05-27 19:21:47 +00001645 soself->s_size);
1646 return NULL;
1647 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001648
Thomas Wouters477c8d52006-05-27 19:21:47 +00001649 /* Call the guts */
1650 if ( s_pack_internal(soself, args, 2, buffer + offset) != 0 ) {
1651 return NULL;
1652 }
1653
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001654 Py_RETURN_NONE;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001655}
1656
1657static PyObject *
1658s_get_format(PyStructObject *self, void *unused)
1659{
1660 Py_INCREF(self->s_format);
1661 return self->s_format;
1662}
1663
1664static PyObject *
1665s_get_size(PyStructObject *self, void *unused)
1666{
Christian Heimes217cfd12007-12-02 14:31:20 +00001667 return PyLong_FromSsize_t(self->s_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001668}
1669
1670/* List of functions */
1671
1672static struct PyMethodDef s_methods[] = {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001673 {"pack", s_pack, METH_VARARGS, s_pack__doc__},
1674 {"pack_into", s_pack_into, METH_VARARGS, s_pack_into__doc__},
1675 {"unpack", s_unpack, METH_O, s_unpack__doc__},
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001676 {"unpack_from", (PyCFunction)s_unpack_from, METH_VARARGS|METH_KEYWORDS,
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001677 s_unpack_from__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +00001678 {NULL, NULL} /* sentinel */
1679};
1680
1681PyDoc_STRVAR(s__doc__, "Compiled struct object");
1682
1683#define OFF(x) offsetof(PyStructObject, x)
1684
1685static PyGetSetDef s_getsetlist[] = {
1686 {"format", (getter)s_get_format, (setter)NULL, "struct format string", NULL},
1687 {"size", (getter)s_get_size, (setter)NULL, "struct size in bytes", NULL},
1688 {NULL} /* sentinel */
1689};
1690
1691static
1692PyTypeObject PyStructType = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001693 PyVarObject_HEAD_INIT(NULL, 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001694 "Struct",
1695 sizeof(PyStructObject),
1696 0,
1697 (destructor)s_dealloc, /* tp_dealloc */
1698 0, /* tp_print */
1699 0, /* tp_getattr */
1700 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00001701 0, /* tp_reserved */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001702 0, /* tp_repr */
1703 0, /* tp_as_number */
1704 0, /* tp_as_sequence */
1705 0, /* tp_as_mapping */
1706 0, /* tp_hash */
1707 0, /* tp_call */
1708 0, /* tp_str */
1709 PyObject_GenericGetAttr, /* tp_getattro */
1710 PyObject_GenericSetAttr, /* tp_setattro */
1711 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00001712 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001713 s__doc__, /* tp_doc */
1714 0, /* tp_traverse */
1715 0, /* tp_clear */
1716 0, /* tp_richcompare */
1717 offsetof(PyStructObject, weakreflist), /* tp_weaklistoffset */
1718 0, /* tp_iter */
1719 0, /* tp_iternext */
1720 s_methods, /* tp_methods */
1721 NULL, /* tp_members */
1722 s_getsetlist, /* tp_getset */
1723 0, /* tp_base */
1724 0, /* tp_dict */
1725 0, /* tp_descr_get */
1726 0, /* tp_descr_set */
1727 0, /* tp_dictoffset */
1728 s_init, /* tp_init */
1729 PyType_GenericAlloc,/* tp_alloc */
1730 s_new, /* tp_new */
1731 PyObject_Del, /* tp_free */
1732};
1733
Christian Heimesa34706f2008-01-04 03:06:10 +00001734
1735/* ---- Standalone functions ---- */
1736
1737#define MAXCACHE 100
1738static PyObject *cache = NULL;
1739
1740static PyObject *
1741cache_struct(PyObject *fmt)
1742{
1743 PyObject * s_object;
1744
1745 if (cache == NULL) {
1746 cache = PyDict_New();
1747 if (cache == NULL)
1748 return NULL;
1749 }
1750
1751 s_object = PyDict_GetItem(cache, fmt);
1752 if (s_object != NULL) {
1753 Py_INCREF(s_object);
1754 return s_object;
1755 }
1756
1757 s_object = PyObject_CallFunctionObjArgs((PyObject *)(&PyStructType), fmt, NULL);
1758 if (s_object != NULL) {
1759 if (PyDict_Size(cache) >= MAXCACHE)
1760 PyDict_Clear(cache);
1761 /* Attempt to cache the result */
1762 if (PyDict_SetItem(cache, fmt, s_object) == -1)
1763 PyErr_Clear();
1764 }
1765 return s_object;
1766}
1767
1768PyDoc_STRVAR(clearcache_doc,
1769"Clear the internal cache.");
1770
1771static PyObject *
1772clearcache(PyObject *self)
1773{
Christian Heimes679db4a2008-01-18 09:56:22 +00001774 Py_CLEAR(cache);
Christian Heimesa34706f2008-01-04 03:06:10 +00001775 Py_RETURN_NONE;
1776}
1777
1778PyDoc_STRVAR(calcsize_doc,
1779"Return size of C struct described by format string fmt.");
1780
1781static PyObject *
1782calcsize(PyObject *self, PyObject *fmt)
1783{
1784 Py_ssize_t n;
1785 PyObject *s_object = cache_struct(fmt);
1786 if (s_object == NULL)
1787 return NULL;
1788 n = ((PyStructObject *)s_object)->s_size;
1789 Py_DECREF(s_object);
1790 return PyLong_FromSsize_t(n);
1791}
1792
1793PyDoc_STRVAR(pack_doc,
Benjamin Peterson4ae19462008-07-31 15:03:40 +00001794"Return bytes containing values v1, v2, ... packed according to fmt.");
Christian Heimesa34706f2008-01-04 03:06:10 +00001795
1796static PyObject *
1797pack(PyObject *self, PyObject *args)
1798{
1799 PyObject *s_object, *fmt, *newargs, *result;
1800 Py_ssize_t n = PyTuple_GET_SIZE(args);
1801
1802 if (n == 0) {
1803 PyErr_SetString(PyExc_TypeError, "missing format argument");
1804 return NULL;
1805 }
1806 fmt = PyTuple_GET_ITEM(args, 0);
1807 newargs = PyTuple_GetSlice(args, 1, n);
1808 if (newargs == NULL)
1809 return NULL;
1810
1811 s_object = cache_struct(fmt);
1812 if (s_object == NULL) {
1813 Py_DECREF(newargs);
1814 return NULL;
1815 }
1816 result = s_pack(s_object, newargs);
1817 Py_DECREF(newargs);
1818 Py_DECREF(s_object);
1819 return result;
1820}
1821
1822PyDoc_STRVAR(pack_into_doc,
1823"Pack the values v1, v2, ... according to fmt.\n\
1824Write the packed bytes into the writable buffer buf starting at offset.");
1825
1826static PyObject *
1827pack_into(PyObject *self, PyObject *args)
1828{
1829 PyObject *s_object, *fmt, *newargs, *result;
1830 Py_ssize_t n = PyTuple_GET_SIZE(args);
1831
1832 if (n == 0) {
1833 PyErr_SetString(PyExc_TypeError, "missing format argument");
1834 return NULL;
1835 }
1836 fmt = PyTuple_GET_ITEM(args, 0);
1837 newargs = PyTuple_GetSlice(args, 1, n);
1838 if (newargs == NULL)
1839 return NULL;
1840
1841 s_object = cache_struct(fmt);
1842 if (s_object == NULL) {
1843 Py_DECREF(newargs);
1844 return NULL;
1845 }
1846 result = s_pack_into(s_object, newargs);
1847 Py_DECREF(newargs);
1848 Py_DECREF(s_object);
1849 return result;
1850}
1851
1852PyDoc_STRVAR(unpack_doc,
Benjamin Peterson4ae19462008-07-31 15:03:40 +00001853"Unpack the bytes containing packed C structure data, according to fmt.\n\
1854Requires len(bytes) == calcsize(fmt).");
Christian Heimesa34706f2008-01-04 03:06:10 +00001855
1856static PyObject *
1857unpack(PyObject *self, PyObject *args)
1858{
1859 PyObject *s_object, *fmt, *inputstr, *result;
1860
1861 if (!PyArg_UnpackTuple(args, "unpack", 2, 2, &fmt, &inputstr))
1862 return NULL;
1863
1864 s_object = cache_struct(fmt);
1865 if (s_object == NULL)
1866 return NULL;
1867 result = s_unpack(s_object, inputstr);
1868 Py_DECREF(s_object);
1869 return result;
1870}
1871
1872PyDoc_STRVAR(unpack_from_doc,
1873"Unpack the buffer, containing packed C structure data, according to\n\
1874fmt, starting at offset. Requires len(buffer[offset:]) >= calcsize(fmt).");
1875
1876static PyObject *
1877unpack_from(PyObject *self, PyObject *args, PyObject *kwds)
1878{
1879 PyObject *s_object, *fmt, *newargs, *result;
1880 Py_ssize_t n = PyTuple_GET_SIZE(args);
1881
1882 if (n == 0) {
1883 PyErr_SetString(PyExc_TypeError, "missing format argument");
1884 return NULL;
1885 }
1886 fmt = PyTuple_GET_ITEM(args, 0);
1887 newargs = PyTuple_GetSlice(args, 1, n);
1888 if (newargs == NULL)
1889 return NULL;
1890
1891 s_object = cache_struct(fmt);
1892 if (s_object == NULL) {
1893 Py_DECREF(newargs);
1894 return NULL;
1895 }
1896 result = s_unpack_from(s_object, newargs, kwds);
1897 Py_DECREF(newargs);
1898 Py_DECREF(s_object);
1899 return result;
1900}
1901
1902static struct PyMethodDef module_functions[] = {
1903 {"_clearcache", (PyCFunction)clearcache, METH_NOARGS, clearcache_doc},
1904 {"calcsize", calcsize, METH_O, calcsize_doc},
1905 {"pack", pack, METH_VARARGS, pack_doc},
1906 {"pack_into", pack_into, METH_VARARGS, pack_into_doc},
1907 {"unpack", unpack, METH_VARARGS, unpack_doc},
1908 {"unpack_from", (PyCFunction)unpack_from,
1909 METH_VARARGS|METH_KEYWORDS, unpack_from_doc},
1910 {NULL, NULL} /* sentinel */
1911};
1912
1913
Thomas Wouters477c8d52006-05-27 19:21:47 +00001914/* Module initialization */
1915
Christian Heimesa34706f2008-01-04 03:06:10 +00001916PyDoc_STRVAR(module_doc,
1917"Functions to convert between Python values and C structs.\n\
Benjamin Peterson4ae19462008-07-31 15:03:40 +00001918Python bytes objects are used to hold the data representing the C struct\n\
Mark Dickinson40714af2009-10-08 15:59:20 +00001919and also as format strings (explained below) to describe the layout of data\n\
1920in the C struct.\n\
Christian Heimesa34706f2008-01-04 03:06:10 +00001921\n\
1922The optional first format char indicates byte order, size and alignment:\n\
Mark Dickinson40714af2009-10-08 15:59:20 +00001923 @: native order, size & alignment (default)\n\
1924 =: native order, std. size & alignment\n\
1925 <: little-endian, std. size & alignment\n\
1926 >: big-endian, std. size & alignment\n\
1927 !: same as >\n\
Christian Heimesa34706f2008-01-04 03:06:10 +00001928\n\
1929The remaining chars indicate types of args and must match exactly;\n\
1930these can be preceded by a decimal repeat count:\n\
1931 x: pad byte (no data); c:char; b:signed byte; B:unsigned byte;\n\
Mark Dickinson40714af2009-10-08 15:59:20 +00001932 ?: _Bool (requires C99; if not available, char is used instead)\n\
Christian Heimesa34706f2008-01-04 03:06:10 +00001933 h:short; H:unsigned short; i:int; I:unsigned int;\n\
1934 l:long; L:unsigned long; f:float; d:double.\n\
1935Special cases (preceding decimal count indicates length):\n\
1936 s:string (array of char); p: pascal string (with count byte).\n\
1937Special case (only available in native format):\n\
1938 P:an integer type that is wide enough to hold a pointer.\n\
1939Special case (not in native mode unless 'long long' in platform C):\n\
1940 q:long long; Q:unsigned long long\n\
1941Whitespace between formats is ignored.\n\
1942\n\
1943The variable struct.error is an exception raised on errors.\n");
1944
Martin v. Löwis1a214512008-06-11 05:26:20 +00001945
1946static struct PyModuleDef _structmodule = {
1947 PyModuleDef_HEAD_INIT,
1948 "_struct",
1949 module_doc,
1950 -1,
1951 module_functions,
1952 NULL,
1953 NULL,
1954 NULL,
1955 NULL
1956};
1957
Thomas Wouters477c8d52006-05-27 19:21:47 +00001958PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001959PyInit__struct(void)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001960{
Christian Heimesa34706f2008-01-04 03:06:10 +00001961 PyObject *ver, *m;
1962
Mark Dickinsonea835e72009-04-19 20:40:33 +00001963 ver = PyBytes_FromString("0.3");
Christian Heimesa34706f2008-01-04 03:06:10 +00001964 if (ver == NULL)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001965 return NULL;
Christian Heimesa34706f2008-01-04 03:06:10 +00001966
Martin v. Löwis1a214512008-06-11 05:26:20 +00001967 m = PyModule_Create(&_structmodule);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001968 if (m == NULL)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001969 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001970
Christian Heimes90aa7642007-12-19 02:45:37 +00001971 Py_TYPE(&PyStructType) = &PyType_Type;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001972 if (PyType_Ready(&PyStructType) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001973 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001974
1975 /* Check endian and swap in faster functions */
1976 {
1977 int one = 1;
1978 formatdef *native = native_table;
1979 formatdef *other, *ptr;
1980 if ((int)*(unsigned char*)&one)
1981 other = lilendian_table;
1982 else
1983 other = bigendian_table;
1984 /* Scan through the native table, find a matching
1985 entry in the endian table and swap in the
1986 native implementations whenever possible
1987 (64-bit platforms may not have "standard" sizes) */
1988 while (native->format != '\0' && other->format != '\0') {
1989 ptr = other;
1990 while (ptr->format != '\0') {
1991 if (ptr->format == native->format) {
1992 /* Match faster when formats are
1993 listed in the same order */
1994 if (ptr == other)
1995 other++;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001996 /* Only use the trick if the
Thomas Wouters477c8d52006-05-27 19:21:47 +00001997 size matches */
1998 if (ptr->size != native->size)
1999 break;
2000 /* Skip float and double, could be
2001 "unknown" float format */
2002 if (ptr->format == 'd' || ptr->format == 'f')
2003 break;
2004 ptr->pack = native->pack;
2005 ptr->unpack = native->unpack;
2006 break;
2007 }
2008 ptr++;
2009 }
2010 native++;
2011 }
2012 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002013
Thomas Wouters477c8d52006-05-27 19:21:47 +00002014 /* Add some symbolic constants to the module */
2015 if (StructError == NULL) {
2016 StructError = PyErr_NewException("struct.error", NULL, NULL);
2017 if (StructError == NULL)
Martin v. Löwis1a214512008-06-11 05:26:20 +00002018 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002019 }
2020
2021 Py_INCREF(StructError);
2022 PyModule_AddObject(m, "error", StructError);
2023
2024 Py_INCREF((PyObject*)&PyStructType);
2025 PyModule_AddObject(m, "Struct", (PyObject*)&PyStructType);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002026
Christian Heimesa34706f2008-01-04 03:06:10 +00002027 PyModule_AddObject(m, "__version__", ver);
2028
Martin v. Löwis1a214512008-06-11 05:26:20 +00002029 return m;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002030}