blob: 2dec4ed6d74b24bc3a6ca78c8c22a7887b833a6f [file] [log] [blame]
Benjamin Peterson4ae19462008-07-31 15:03:40 +00001/* struct module -- pack values into and (out of) bytes objects */
Thomas Wouters477c8d52006-05-27 19:21:47 +00002
3/* New version supporting byte order, alignment and size options,
4 character strings, and unsigned numbers */
5
6#define PY_SSIZE_T_CLEAN
7
8#include "Python.h"
Thomas Wouters477c8d52006-05-27 19:21:47 +00009#include "structmember.h"
10#include <ctype.h>
11
12static PyTypeObject PyStructType;
13
Thomas Wouters477c8d52006-05-27 19:21:47 +000014/* The translation function for each format character is table driven */
15typedef struct _formatdef {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000016 char format;
17 Py_ssize_t size;
18 Py_ssize_t alignment;
19 PyObject* (*unpack)(const char *,
20 const struct _formatdef *);
21 int (*pack)(char *, PyObject *,
22 const struct _formatdef *);
Thomas Wouters477c8d52006-05-27 19:21:47 +000023} formatdef;
24
25typedef struct _formatcode {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000026 const struct _formatdef *fmtdef;
27 Py_ssize_t offset;
28 Py_ssize_t size;
Thomas Wouters477c8d52006-05-27 19:21:47 +000029} formatcode;
30
31/* Struct object interface */
32
33typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000034 PyObject_HEAD
35 Py_ssize_t s_size;
36 Py_ssize_t s_len;
37 formatcode *s_codes;
38 PyObject *s_format;
39 PyObject *weakreflist; /* List of weak references */
Thomas Wouters477c8d52006-05-27 19:21:47 +000040} PyStructObject;
41
42
43#define PyStruct_Check(op) PyObject_TypeCheck(op, &PyStructType)
Christian Heimes90aa7642007-12-19 02:45:37 +000044#define PyStruct_CheckExact(op) (Py_TYPE(op) == &PyStructType)
Thomas Wouters477c8d52006-05-27 19:21:47 +000045
46
47/* Exception */
48
49static PyObject *StructError;
50
51
52/* Define various structs to figure out the alignments of types */
53
54
55typedef struct { char c; short x; } st_short;
56typedef struct { char c; int x; } st_int;
57typedef struct { char c; long x; } st_long;
58typedef struct { char c; float x; } st_float;
59typedef struct { char c; double x; } st_double;
60typedef struct { char c; void *x; } st_void_p;
Antoine Pitrou45d9c912011-10-06 15:27:40 +020061typedef struct { char c; size_t x; } st_size_t;
Thomas Wouters477c8d52006-05-27 19:21:47 +000062
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 *))
Antoine Pitrou45d9c912011-10-06 15:27:40 +020069#define SIZE_T_ALIGN (sizeof(st_size_t) - sizeof(size_t))
Thomas Wouters477c8d52006-05-27 19:21:47 +000070
71/* We can't support q and Q in native mode unless the compiler does;
72 in std mode, they're 8 bytes on all platforms. */
73#ifdef HAVE_LONG_LONG
74typedef struct { char c; PY_LONG_LONG x; } s_long_long;
75#define LONG_LONG_ALIGN (sizeof(s_long_long) - sizeof(PY_LONG_LONG))
76#endif
77
Thomas Woutersb2137042007-02-01 18:02:27 +000078#ifdef HAVE_C99_BOOL
79#define BOOL_TYPE _Bool
80typedef struct { char c; _Bool x; } s_bool;
81#define BOOL_ALIGN (sizeof(s_bool) - sizeof(BOOL_TYPE))
82#else
83#define BOOL_TYPE char
84#define BOOL_ALIGN 0
85#endif
86
Thomas Wouters477c8d52006-05-27 19:21:47 +000087#define STRINGIFY(x) #x
88
89#ifdef __powerc
90#pragma options align=reset
91#endif
92
Mark Dickinson055a3fb2010-04-03 15:26:31 +000093/* Helper for integer format codes: converts an arbitrary Python object to a
94 PyLongObject if possible, otherwise fails. Caller should decref. */
Thomas Wouters477c8d52006-05-27 19:21:47 +000095
96static PyObject *
97get_pylong(PyObject *v)
98{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000099 assert(v != NULL);
100 if (!PyLong_Check(v)) {
101 /* Not an integer; try to use __index__ to convert. */
102 if (PyIndex_Check(v)) {
103 v = PyNumber_Index(v);
104 if (v == NULL)
105 return NULL;
106 }
107 else {
108 PyErr_SetString(StructError,
109 "required argument is not an integer");
110 return NULL;
111 }
112 }
113 else
114 Py_INCREF(v);
Mark Dickinsonea835e72009-04-19 20:40:33 +0000115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000116 assert(PyLong_Check(v));
117 return v;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000118}
119
Mark Dickinsonea835e72009-04-19 20:40:33 +0000120/* Helper routine to get a C long and raise the appropriate error if it isn't
121 one */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000122
123static int
124get_long(PyObject *v, long *p)
125{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000126 long x;
Mark Dickinsonea835e72009-04-19 20:40:33 +0000127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000128 v = get_pylong(v);
129 if (v == NULL)
130 return -1;
131 assert(PyLong_Check(v));
132 x = PyLong_AsLong(v);
133 Py_DECREF(v);
134 if (x == (long)-1 && PyErr_Occurred()) {
135 if (PyErr_ExceptionMatches(PyExc_OverflowError))
136 PyErr_SetString(StructError,
137 "argument out of range");
138 return -1;
139 }
140 *p = x;
141 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000142}
143
144
145/* Same, but handling unsigned long */
146
147static int
148get_ulong(PyObject *v, unsigned long *p)
149{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000150 unsigned long x;
Mark Dickinsonea835e72009-04-19 20:40:33 +0000151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000152 v = get_pylong(v);
153 if (v == NULL)
154 return -1;
155 assert(PyLong_Check(v));
156 x = PyLong_AsUnsignedLong(v);
157 Py_DECREF(v);
158 if (x == (unsigned long)-1 && PyErr_Occurred()) {
159 if (PyErr_ExceptionMatches(PyExc_OverflowError))
160 PyErr_SetString(StructError,
161 "argument out of range");
162 return -1;
163 }
164 *p = x;
165 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000166}
167
168#ifdef HAVE_LONG_LONG
169
170/* Same, but handling native long long. */
171
172static int
173get_longlong(PyObject *v, PY_LONG_LONG *p)
174{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175 PY_LONG_LONG x;
Mark Dickinson055a3fb2010-04-03 15:26:31 +0000176
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000177 v = get_pylong(v);
178 if (v == NULL)
179 return -1;
180 assert(PyLong_Check(v));
181 x = PyLong_AsLongLong(v);
182 Py_DECREF(v);
183 if (x == (PY_LONG_LONG)-1 && PyErr_Occurred()) {
184 if (PyErr_ExceptionMatches(PyExc_OverflowError))
185 PyErr_SetString(StructError,
186 "argument out of range");
187 return -1;
188 }
189 *p = x;
190 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000191}
192
193/* Same, but handling native unsigned long long. */
194
195static int
196get_ulonglong(PyObject *v, unsigned PY_LONG_LONG *p)
197{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000198 unsigned PY_LONG_LONG x;
Mark Dickinson055a3fb2010-04-03 15:26:31 +0000199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000200 v = get_pylong(v);
201 if (v == NULL)
202 return -1;
203 assert(PyLong_Check(v));
204 x = PyLong_AsUnsignedLongLong(v);
205 Py_DECREF(v);
206 if (x == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred()) {
207 if (PyErr_ExceptionMatches(PyExc_OverflowError))
208 PyErr_SetString(StructError,
209 "argument out of range");
210 return -1;
211 }
212 *p = x;
213 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000214}
215
216#endif
217
Antoine Pitrou45d9c912011-10-06 15:27:40 +0200218/* Same, but handling Py_ssize_t */
219
220static int
221get_ssize_t(PyObject *v, Py_ssize_t *p)
222{
223 Py_ssize_t x;
224
225 v = get_pylong(v);
226 if (v == NULL)
227 return -1;
228 assert(PyLong_Check(v));
229 x = PyLong_AsSsize_t(v);
230 Py_DECREF(v);
231 if (x == (Py_ssize_t)-1 && PyErr_Occurred()) {
232 if (PyErr_ExceptionMatches(PyExc_OverflowError))
233 PyErr_SetString(StructError,
234 "argument out of range");
235 return -1;
236 }
237 *p = x;
238 return 0;
239}
240
241/* Same, but handling size_t */
242
243static int
244get_size_t(PyObject *v, size_t *p)
245{
246 size_t x;
247
248 v = get_pylong(v);
249 if (v == NULL)
250 return -1;
251 assert(PyLong_Check(v));
252 x = PyLong_AsSize_t(v);
253 Py_DECREF(v);
254 if (x == (size_t)-1 && PyErr_Occurred()) {
255 if (PyErr_ExceptionMatches(PyExc_OverflowError))
256 PyErr_SetString(StructError,
257 "argument out of range");
258 return -1;
259 }
260 *p = x;
261 return 0;
262}
263
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000264
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000265#define RANGE_ERROR(x, f, flag, mask) return _range_error(f, flag)
266
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000267
Thomas Wouters477c8d52006-05-27 19:21:47 +0000268/* Floating point helpers */
269
270static PyObject *
271unpack_float(const char *p, /* start of 4-byte string */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000272 int le) /* true for little-endian, false for big-endian */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000273{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000274 double x;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000276 x = _PyFloat_Unpack4((unsigned char *)p, le);
277 if (x == -1.0 && PyErr_Occurred())
278 return NULL;
279 return PyFloat_FromDouble(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000280}
281
282static PyObject *
283unpack_double(const char *p, /* start of 8-byte string */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000284 int le) /* true for little-endian, false for big-endian */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000285{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 double x;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000288 x = _PyFloat_Unpack8((unsigned char *)p, le);
289 if (x == -1.0 && PyErr_Occurred())
290 return NULL;
291 return PyFloat_FromDouble(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000292}
293
294/* Helper to format the range error exceptions */
295static int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000296_range_error(const formatdef *f, int is_unsigned)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000297{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000298 /* ulargest is the largest unsigned value with f->size bytes.
299 * Note that the simpler:
300 * ((size_t)1 << (f->size * 8)) - 1
301 * doesn't work when f->size == sizeof(size_t) because C doesn't
302 * define what happens when a left shift count is >= the number of
303 * bits in the integer being shifted; e.g., on some boxes it doesn't
304 * shift at all when they're equal.
305 */
306 const size_t ulargest = (size_t)-1 >> ((SIZEOF_SIZE_T - f->size)*8);
307 assert(f->size >= 1 && f->size <= SIZEOF_SIZE_T);
308 if (is_unsigned)
309 PyErr_Format(StructError,
310 "'%c' format requires 0 <= number <= %zu",
311 f->format,
312 ulargest);
313 else {
314 const Py_ssize_t largest = (Py_ssize_t)(ulargest >> 1);
315 PyErr_Format(StructError,
316 "'%c' format requires %zd <= number <= %zd",
317 f->format,
318 ~ largest,
319 largest);
320 }
Mark Dickinsonae681df2009-03-21 10:26:31 +0000321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000322 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000323}
324
325
326
327/* A large number of small routines follow, with names of the form
328
329 [bln][up]_TYPE
330
331 [bln] distiguishes among big-endian, little-endian and native.
332 [pu] distiguishes between pack (to struct) and unpack (from struct).
333 TYPE is one of char, byte, ubyte, etc.
334*/
335
336/* Native mode routines. ****************************************************/
337/* NOTE:
338 In all n[up]_<type> routines handling types larger than 1 byte, there is
339 *no* guarantee that the p pointer is properly aligned for each type,
340 therefore memcpy is called. An intermediate variable is used to
341 compensate for big-endian architectures.
342 Normally both the intermediate variable and the memcpy call will be
343 skipped by C optimisation in little-endian architectures (gcc >= 2.91
344 does this). */
345
346static PyObject *
347nu_char(const char *p, const formatdef *f)
348{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000349 return PyBytes_FromStringAndSize(p, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000350}
351
352static PyObject *
353nu_byte(const char *p, const formatdef *f)
354{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000355 return PyLong_FromLong((long) *(signed char *)p);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000356}
357
358static PyObject *
359nu_ubyte(const char *p, const formatdef *f)
360{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000361 return PyLong_FromLong((long) *(unsigned char *)p);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000362}
363
364static PyObject *
365nu_short(const char *p, const formatdef *f)
366{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000367 short x;
368 memcpy((char *)&x, p, sizeof x);
369 return PyLong_FromLong((long)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000370}
371
372static PyObject *
373nu_ushort(const char *p, const formatdef *f)
374{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 unsigned short x;
376 memcpy((char *)&x, p, sizeof x);
377 return PyLong_FromLong((long)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000378}
379
380static PyObject *
381nu_int(const char *p, const formatdef *f)
382{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000383 int x;
384 memcpy((char *)&x, p, sizeof x);
385 return PyLong_FromLong((long)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000386}
387
388static PyObject *
389nu_uint(const char *p, const formatdef *f)
390{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000391 unsigned int x;
392 memcpy((char *)&x, p, sizeof x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000393#if (SIZEOF_LONG > SIZEOF_INT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000394 return PyLong_FromLong((long)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000395#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000396 if (x <= ((unsigned int)LONG_MAX))
397 return PyLong_FromLong((long)x);
398 return PyLong_FromUnsignedLong((unsigned long)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000399#endif
400}
401
402static PyObject *
403nu_long(const char *p, const formatdef *f)
404{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000405 long x;
406 memcpy((char *)&x, p, sizeof x);
407 return PyLong_FromLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000408}
409
410static PyObject *
411nu_ulong(const char *p, const formatdef *f)
412{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000413 unsigned long x;
414 memcpy((char *)&x, p, sizeof x);
415 if (x <= LONG_MAX)
416 return PyLong_FromLong((long)x);
417 return PyLong_FromUnsignedLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000418}
419
Antoine Pitrou45d9c912011-10-06 15:27:40 +0200420static PyObject *
421nu_ssize_t(const char *p, const formatdef *f)
422{
423 Py_ssize_t x;
424 memcpy((char *)&x, p, sizeof x);
425 return PyLong_FromSsize_t(x);
426}
427
428static PyObject *
429nu_size_t(const char *p, const formatdef *f)
430{
431 size_t x;
432 memcpy((char *)&x, p, sizeof x);
433 return PyLong_FromSize_t(x);
434}
435
436
Thomas Wouters477c8d52006-05-27 19:21:47 +0000437/* Native mode doesn't support q or Q unless the platform C supports
438 long long (or, on Windows, __int64). */
439
440#ifdef HAVE_LONG_LONG
441
442static PyObject *
443nu_longlong(const char *p, const formatdef *f)
444{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000445 PY_LONG_LONG x;
446 memcpy((char *)&x, p, sizeof x);
447 if (x >= LONG_MIN && x <= LONG_MAX)
448 return PyLong_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long));
449 return PyLong_FromLongLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000450}
451
452static PyObject *
453nu_ulonglong(const char *p, const formatdef *f)
454{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000455 unsigned PY_LONG_LONG x;
456 memcpy((char *)&x, p, sizeof x);
457 if (x <= LONG_MAX)
458 return PyLong_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long));
459 return PyLong_FromUnsignedLongLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000460}
461
462#endif
463
464static PyObject *
Thomas Woutersb2137042007-02-01 18:02:27 +0000465nu_bool(const char *p, const formatdef *f)
466{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000467 BOOL_TYPE x;
468 memcpy((char *)&x, p, sizeof x);
469 return PyBool_FromLong(x != 0);
Thomas Woutersb2137042007-02-01 18:02:27 +0000470}
471
472
473static PyObject *
Thomas Wouters477c8d52006-05-27 19:21:47 +0000474nu_float(const char *p, const formatdef *f)
475{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 float x;
477 memcpy((char *)&x, p, sizeof x);
478 return PyFloat_FromDouble((double)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000479}
480
481static PyObject *
482nu_double(const char *p, const formatdef *f)
483{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 double x;
485 memcpy((char *)&x, p, sizeof x);
486 return PyFloat_FromDouble(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000487}
488
489static PyObject *
490nu_void_p(const char *p, const formatdef *f)
491{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 void *x;
493 memcpy((char *)&x, p, sizeof x);
494 return PyLong_FromVoidPtr(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000495}
496
497static int
498np_byte(char *p, PyObject *v, const formatdef *f)
499{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 long x;
501 if (get_long(v, &x) < 0)
502 return -1;
503 if (x < -128 || x > 127){
504 PyErr_SetString(StructError,
505 "byte format requires -128 <= number <= 127");
506 return -1;
507 }
508 *p = (char)x;
509 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000510}
511
512static int
513np_ubyte(char *p, PyObject *v, const formatdef *f)
514{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000515 long x;
516 if (get_long(v, &x) < 0)
517 return -1;
518 if (x < 0 || x > 255){
519 PyErr_SetString(StructError,
520 "ubyte format requires 0 <= number <= 255");
521 return -1;
522 }
523 *p = (char)x;
524 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000525}
526
527static int
528np_char(char *p, PyObject *v, const formatdef *f)
529{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 if (!PyBytes_Check(v) || PyBytes_Size(v) != 1) {
531 PyErr_SetString(StructError,
Victor Stinnerda9ec992010-12-28 13:26:42 +0000532 "char format requires a bytes object of length 1");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000533 return -1;
534 }
535 *p = *PyBytes_AsString(v);
536 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000537}
538
539static int
540np_short(char *p, PyObject *v, const formatdef *f)
541{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000542 long x;
543 short y;
544 if (get_long(v, &x) < 0)
545 return -1;
546 if (x < SHRT_MIN || x > SHRT_MAX){
547 PyErr_SetString(StructError,
548 "short format requires " STRINGIFY(SHRT_MIN)
549 " <= number <= " STRINGIFY(SHRT_MAX));
550 return -1;
551 }
552 y = (short)x;
553 memcpy(p, (char *)&y, sizeof y);
554 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000555}
556
557static int
558np_ushort(char *p, PyObject *v, const formatdef *f)
559{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 long x;
561 unsigned short y;
562 if (get_long(v, &x) < 0)
563 return -1;
564 if (x < 0 || x > USHRT_MAX){
565 PyErr_SetString(StructError,
566 "ushort format requires 0 <= number <= " STRINGIFY(USHRT_MAX));
567 return -1;
568 }
569 y = (unsigned short)x;
570 memcpy(p, (char *)&y, sizeof y);
571 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000572}
573
574static int
575np_int(char *p, PyObject *v, const formatdef *f)
576{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577 long x;
578 int y;
579 if (get_long(v, &x) < 0)
580 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000581#if (SIZEOF_LONG > SIZEOF_INT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000582 if ((x < ((long)INT_MIN)) || (x > ((long)INT_MAX)))
583 RANGE_ERROR(x, f, 0, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000584#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000585 y = (int)x;
586 memcpy(p, (char *)&y, sizeof y);
587 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000588}
589
590static int
591np_uint(char *p, PyObject *v, const formatdef *f)
592{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000593 unsigned long x;
594 unsigned int y;
595 if (get_ulong(v, &x) < 0)
596 return -1;
597 y = (unsigned int)x;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000598#if (SIZEOF_LONG > SIZEOF_INT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000599 if (x > ((unsigned long)UINT_MAX))
600 RANGE_ERROR(y, f, 1, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000601#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000602 memcpy(p, (char *)&y, sizeof y);
603 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000604}
605
606static int
607np_long(char *p, PyObject *v, const formatdef *f)
608{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 long x;
610 if (get_long(v, &x) < 0)
611 return -1;
612 memcpy(p, (char *)&x, sizeof x);
613 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000614}
615
616static int
617np_ulong(char *p, PyObject *v, const formatdef *f)
618{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 unsigned long x;
620 if (get_ulong(v, &x) < 0)
621 return -1;
622 memcpy(p, (char *)&x, sizeof x);
623 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000624}
625
Antoine Pitrou45d9c912011-10-06 15:27:40 +0200626static int
627np_ssize_t(char *p, PyObject *v, const formatdef *f)
628{
629 Py_ssize_t x;
630 if (get_ssize_t(v, &x) < 0)
631 return -1;
632 memcpy(p, (char *)&x, sizeof x);
633 return 0;
634}
635
636static int
637np_size_t(char *p, PyObject *v, const formatdef *f)
638{
639 size_t x;
640 if (get_size_t(v, &x) < 0)
641 return -1;
642 memcpy(p, (char *)&x, sizeof x);
643 return 0;
644}
645
Thomas Wouters477c8d52006-05-27 19:21:47 +0000646#ifdef HAVE_LONG_LONG
647
648static int
649np_longlong(char *p, PyObject *v, const formatdef *f)
650{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000651 PY_LONG_LONG x;
652 if (get_longlong(v, &x) < 0)
653 return -1;
654 memcpy(p, (char *)&x, sizeof x);
655 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000656}
657
658static int
659np_ulonglong(char *p, PyObject *v, const formatdef *f)
660{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 unsigned PY_LONG_LONG x;
662 if (get_ulonglong(v, &x) < 0)
663 return -1;
664 memcpy(p, (char *)&x, sizeof x);
665 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000666}
667#endif
668
Thomas Woutersb2137042007-02-01 18:02:27 +0000669
670static int
671np_bool(char *p, PyObject *v, const formatdef *f)
672{
Benjamin Petersonde73c452010-07-07 18:54:59 +0000673 int y;
674 BOOL_TYPE x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000675 y = PyObject_IsTrue(v);
Benjamin Petersonde73c452010-07-07 18:54:59 +0000676 if (y < 0)
677 return -1;
678 x = y;
679 memcpy(p, (char *)&x, sizeof x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000680 return 0;
Thomas Woutersb2137042007-02-01 18:02:27 +0000681}
682
Thomas Wouters477c8d52006-05-27 19:21:47 +0000683static int
684np_float(char *p, PyObject *v, const formatdef *f)
685{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000686 float x = (float)PyFloat_AsDouble(v);
687 if (x == -1 && PyErr_Occurred()) {
688 PyErr_SetString(StructError,
689 "required argument is not a float");
690 return -1;
691 }
692 memcpy(p, (char *)&x, sizeof x);
693 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000694}
695
696static int
697np_double(char *p, PyObject *v, const formatdef *f)
698{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000699 double x = PyFloat_AsDouble(v);
700 if (x == -1 && PyErr_Occurred()) {
701 PyErr_SetString(StructError,
702 "required argument is not a float");
703 return -1;
704 }
705 memcpy(p, (char *)&x, sizeof(double));
706 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000707}
708
709static int
710np_void_p(char *p, PyObject *v, const formatdef *f)
711{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000712 void *x;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 v = get_pylong(v);
715 if (v == NULL)
716 return -1;
717 assert(PyLong_Check(v));
718 x = PyLong_AsVoidPtr(v);
719 Py_DECREF(v);
720 if (x == NULL && PyErr_Occurred())
721 return -1;
722 memcpy(p, (char *)&x, sizeof x);
723 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000724}
725
726static formatdef native_table[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000727 {'x', sizeof(char), 0, NULL},
728 {'b', sizeof(char), 0, nu_byte, np_byte},
729 {'B', sizeof(char), 0, nu_ubyte, np_ubyte},
730 {'c', sizeof(char), 0, nu_char, np_char},
731 {'s', sizeof(char), 0, NULL},
732 {'p', sizeof(char), 0, NULL},
733 {'h', sizeof(short), SHORT_ALIGN, nu_short, np_short},
734 {'H', sizeof(short), SHORT_ALIGN, nu_ushort, np_ushort},
735 {'i', sizeof(int), INT_ALIGN, nu_int, np_int},
736 {'I', sizeof(int), INT_ALIGN, nu_uint, np_uint},
737 {'l', sizeof(long), LONG_ALIGN, nu_long, np_long},
738 {'L', sizeof(long), LONG_ALIGN, nu_ulong, np_ulong},
Antoine Pitrou45d9c912011-10-06 15:27:40 +0200739 {'n', sizeof(size_t), SIZE_T_ALIGN, nu_ssize_t, np_ssize_t},
740 {'N', sizeof(size_t), SIZE_T_ALIGN, nu_size_t, np_size_t},
Thomas Wouters477c8d52006-05-27 19:21:47 +0000741#ifdef HAVE_LONG_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000742 {'q', sizeof(PY_LONG_LONG), LONG_LONG_ALIGN, nu_longlong, np_longlong},
743 {'Q', sizeof(PY_LONG_LONG), LONG_LONG_ALIGN, nu_ulonglong,np_ulonglong},
Thomas Wouters477c8d52006-05-27 19:21:47 +0000744#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000745 {'?', sizeof(BOOL_TYPE), BOOL_ALIGN, nu_bool, np_bool},
746 {'f', sizeof(float), FLOAT_ALIGN, nu_float, np_float},
747 {'d', sizeof(double), DOUBLE_ALIGN, nu_double, np_double},
748 {'P', sizeof(void *), VOID_P_ALIGN, nu_void_p, np_void_p},
749 {0}
Thomas Wouters477c8d52006-05-27 19:21:47 +0000750};
751
752/* Big-endian routines. *****************************************************/
753
754static PyObject *
755bu_int(const char *p, const formatdef *f)
756{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000757 long x = 0;
758 Py_ssize_t i = f->size;
759 const unsigned char *bytes = (const unsigned char *)p;
760 do {
761 x = (x<<8) | *bytes++;
762 } while (--i > 0);
763 /* Extend the sign bit. */
764 if (SIZEOF_LONG > f->size)
765 x |= -(x & (1L << ((8 * f->size) - 1)));
766 return PyLong_FromLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000767}
768
769static PyObject *
770bu_uint(const char *p, const formatdef *f)
771{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000772 unsigned long x = 0;
773 Py_ssize_t i = f->size;
774 const unsigned char *bytes = (const unsigned char *)p;
775 do {
776 x = (x<<8) | *bytes++;
777 } while (--i > 0);
778 if (x <= LONG_MAX)
779 return PyLong_FromLong((long)x);
780 return PyLong_FromUnsignedLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000781}
782
783static PyObject *
784bu_longlong(const char *p, const formatdef *f)
785{
786#ifdef HAVE_LONG_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 PY_LONG_LONG x = 0;
788 Py_ssize_t i = f->size;
789 const unsigned char *bytes = (const unsigned char *)p;
790 do {
791 x = (x<<8) | *bytes++;
792 } while (--i > 0);
793 /* Extend the sign bit. */
794 if (SIZEOF_LONG_LONG > f->size)
795 x |= -(x & ((PY_LONG_LONG)1 << ((8 * f->size) - 1)));
796 if (x >= LONG_MIN && x <= LONG_MAX)
797 return PyLong_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long));
798 return PyLong_FromLongLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000799#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000800 return _PyLong_FromByteArray((const unsigned char *)p,
801 8,
802 0, /* little-endian */
803 1 /* signed */);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000804#endif
805}
806
807static PyObject *
808bu_ulonglong(const char *p, const formatdef *f)
809{
810#ifdef HAVE_LONG_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000811 unsigned PY_LONG_LONG x = 0;
812 Py_ssize_t i = f->size;
813 const unsigned char *bytes = (const unsigned char *)p;
814 do {
815 x = (x<<8) | *bytes++;
816 } while (--i > 0);
817 if (x <= LONG_MAX)
818 return PyLong_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long));
819 return PyLong_FromUnsignedLongLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000820#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000821 return _PyLong_FromByteArray((const unsigned char *)p,
822 8,
823 0, /* little-endian */
824 0 /* signed */);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000825#endif
826}
827
828static PyObject *
829bu_float(const char *p, const formatdef *f)
830{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000831 return unpack_float(p, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000832}
833
834static PyObject *
835bu_double(const char *p, const formatdef *f)
836{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000837 return unpack_double(p, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000838}
839
Thomas Woutersb2137042007-02-01 18:02:27 +0000840static PyObject *
841bu_bool(const char *p, const formatdef *f)
842{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000843 char x;
844 memcpy((char *)&x, p, sizeof x);
845 return PyBool_FromLong(x != 0);
Thomas Woutersb2137042007-02-01 18:02:27 +0000846}
847
Thomas Wouters477c8d52006-05-27 19:21:47 +0000848static int
849bp_int(char *p, PyObject *v, const formatdef *f)
850{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000851 long x;
852 Py_ssize_t i;
853 if (get_long(v, &x) < 0)
854 return -1;
855 i = f->size;
856 if (i != SIZEOF_LONG) {
857 if ((i == 2) && (x < -32768 || x > 32767))
858 RANGE_ERROR(x, f, 0, 0xffffL);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000859#if (SIZEOF_LONG != 4)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000860 else if ((i == 4) && (x < -2147483648L || x > 2147483647L))
861 RANGE_ERROR(x, f, 0, 0xffffffffL);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000862#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000863 }
864 do {
865 p[--i] = (char)x;
866 x >>= 8;
867 } while (i > 0);
868 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000869}
870
871static int
872bp_uint(char *p, PyObject *v, const formatdef *f)
873{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000874 unsigned long x;
875 Py_ssize_t i;
876 if (get_ulong(v, &x) < 0)
877 return -1;
878 i = f->size;
879 if (i != SIZEOF_LONG) {
880 unsigned long maxint = 1;
881 maxint <<= (unsigned long)(i * 8);
882 if (x >= maxint)
883 RANGE_ERROR(x, f, 1, maxint - 1);
884 }
885 do {
886 p[--i] = (char)x;
887 x >>= 8;
888 } while (i > 0);
889 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000890}
891
892static int
893bp_longlong(char *p, PyObject *v, const formatdef *f)
894{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000895 int res;
896 v = get_pylong(v);
897 if (v == NULL)
898 return -1;
899 res = _PyLong_AsByteArray((PyLongObject *)v,
900 (unsigned char *)p,
901 8,
902 0, /* little_endian */
903 1 /* signed */);
904 Py_DECREF(v);
905 return res;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000906}
907
908static int
909bp_ulonglong(char *p, PyObject *v, const formatdef *f)
910{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000911 int res;
912 v = get_pylong(v);
913 if (v == NULL)
914 return -1;
915 res = _PyLong_AsByteArray((PyLongObject *)v,
916 (unsigned char *)p,
917 8,
918 0, /* little_endian */
919 0 /* signed */);
920 Py_DECREF(v);
921 return res;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000922}
923
924static int
925bp_float(char *p, PyObject *v, const formatdef *f)
926{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000927 double x = PyFloat_AsDouble(v);
928 if (x == -1 && PyErr_Occurred()) {
929 PyErr_SetString(StructError,
930 "required argument is not a float");
931 return -1;
932 }
933 return _PyFloat_Pack4(x, (unsigned char *)p, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000934}
935
936static int
937bp_double(char *p, PyObject *v, const formatdef *f)
938{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 double x = PyFloat_AsDouble(v);
940 if (x == -1 && PyErr_Occurred()) {
941 PyErr_SetString(StructError,
942 "required argument is not a float");
943 return -1;
944 }
945 return _PyFloat_Pack8(x, (unsigned char *)p, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000946}
947
Thomas Woutersb2137042007-02-01 18:02:27 +0000948static int
949bp_bool(char *p, PyObject *v, const formatdef *f)
950{
Mark Dickinsoneff5d852010-07-18 07:29:02 +0000951 int y;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 y = PyObject_IsTrue(v);
Benjamin Petersonde73c452010-07-07 18:54:59 +0000953 if (y < 0)
954 return -1;
Mark Dickinsoneff5d852010-07-18 07:29:02 +0000955 *p = (char)y;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000956 return 0;
Thomas Woutersb2137042007-02-01 18:02:27 +0000957}
958
Thomas Wouters477c8d52006-05-27 19:21:47 +0000959static formatdef bigendian_table[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 {'x', 1, 0, NULL},
961 {'b', 1, 0, nu_byte, np_byte},
962 {'B', 1, 0, nu_ubyte, np_ubyte},
963 {'c', 1, 0, nu_char, np_char},
964 {'s', 1, 0, NULL},
965 {'p', 1, 0, NULL},
966 {'h', 2, 0, bu_int, bp_int},
967 {'H', 2, 0, bu_uint, bp_uint},
968 {'i', 4, 0, bu_int, bp_int},
969 {'I', 4, 0, bu_uint, bp_uint},
970 {'l', 4, 0, bu_int, bp_int},
971 {'L', 4, 0, bu_uint, bp_uint},
972 {'q', 8, 0, bu_longlong, bp_longlong},
973 {'Q', 8, 0, bu_ulonglong, bp_ulonglong},
974 {'?', 1, 0, bu_bool, bp_bool},
975 {'f', 4, 0, bu_float, bp_float},
976 {'d', 8, 0, bu_double, bp_double},
977 {0}
Thomas Wouters477c8d52006-05-27 19:21:47 +0000978};
979
980/* Little-endian routines. *****************************************************/
981
982static PyObject *
983lu_int(const char *p, const formatdef *f)
984{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000985 long x = 0;
986 Py_ssize_t i = f->size;
987 const unsigned char *bytes = (const unsigned char *)p;
988 do {
989 x = (x<<8) | bytes[--i];
990 } while (i > 0);
991 /* Extend the sign bit. */
992 if (SIZEOF_LONG > f->size)
993 x |= -(x & (1L << ((8 * f->size) - 1)));
994 return PyLong_FromLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000995}
996
997static PyObject *
998lu_uint(const char *p, const formatdef *f)
999{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001000 unsigned long x = 0;
1001 Py_ssize_t i = f->size;
1002 const unsigned char *bytes = (const unsigned char *)p;
1003 do {
1004 x = (x<<8) | bytes[--i];
1005 } while (i > 0);
1006 if (x <= LONG_MAX)
1007 return PyLong_FromLong((long)x);
1008 return PyLong_FromUnsignedLong((long)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001009}
1010
1011static PyObject *
1012lu_longlong(const char *p, const formatdef *f)
1013{
1014#ifdef HAVE_LONG_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 PY_LONG_LONG x = 0;
1016 Py_ssize_t i = f->size;
1017 const unsigned char *bytes = (const unsigned char *)p;
1018 do {
1019 x = (x<<8) | bytes[--i];
1020 } while (i > 0);
1021 /* Extend the sign bit. */
1022 if (SIZEOF_LONG_LONG > f->size)
1023 x |= -(x & ((PY_LONG_LONG)1 << ((8 * f->size) - 1)));
1024 if (x >= LONG_MIN && x <= LONG_MAX)
1025 return PyLong_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long));
1026 return PyLong_FromLongLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001027#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 return _PyLong_FromByteArray((const unsigned char *)p,
1029 8,
1030 1, /* little-endian */
1031 1 /* signed */);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001032#endif
1033}
1034
1035static PyObject *
1036lu_ulonglong(const char *p, const formatdef *f)
1037{
1038#ifdef HAVE_LONG_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001039 unsigned PY_LONG_LONG x = 0;
1040 Py_ssize_t i = f->size;
1041 const unsigned char *bytes = (const unsigned char *)p;
1042 do {
1043 x = (x<<8) | bytes[--i];
1044 } while (i > 0);
1045 if (x <= LONG_MAX)
1046 return PyLong_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long));
1047 return PyLong_FromUnsignedLongLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001048#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049 return _PyLong_FromByteArray((const unsigned char *)p,
1050 8,
1051 1, /* little-endian */
1052 0 /* signed */);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001053#endif
1054}
1055
1056static PyObject *
1057lu_float(const char *p, const formatdef *f)
1058{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001059 return unpack_float(p, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001060}
1061
1062static PyObject *
1063lu_double(const char *p, const formatdef *f)
1064{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001065 return unpack_double(p, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001066}
1067
1068static int
1069lp_int(char *p, PyObject *v, const formatdef *f)
1070{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 long x;
1072 Py_ssize_t i;
1073 if (get_long(v, &x) < 0)
1074 return -1;
1075 i = f->size;
1076 if (i != SIZEOF_LONG) {
1077 if ((i == 2) && (x < -32768 || x > 32767))
1078 RANGE_ERROR(x, f, 0, 0xffffL);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001079#if (SIZEOF_LONG != 4)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001080 else if ((i == 4) && (x < -2147483648L || x > 2147483647L))
1081 RANGE_ERROR(x, f, 0, 0xffffffffL);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001082#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 }
1084 do {
1085 *p++ = (char)x;
1086 x >>= 8;
1087 } while (--i > 0);
1088 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001089}
1090
1091static int
1092lp_uint(char *p, PyObject *v, const formatdef *f)
1093{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001094 unsigned long x;
1095 Py_ssize_t i;
1096 if (get_ulong(v, &x) < 0)
1097 return -1;
1098 i = f->size;
1099 if (i != SIZEOF_LONG) {
1100 unsigned long maxint = 1;
1101 maxint <<= (unsigned long)(i * 8);
1102 if (x >= maxint)
1103 RANGE_ERROR(x, f, 1, maxint - 1);
1104 }
1105 do {
1106 *p++ = (char)x;
1107 x >>= 8;
1108 } while (--i > 0);
1109 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001110}
1111
1112static int
1113lp_longlong(char *p, PyObject *v, const formatdef *f)
1114{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 int res;
1116 v = get_pylong(v);
1117 if (v == NULL)
1118 return -1;
1119 res = _PyLong_AsByteArray((PyLongObject*)v,
1120 (unsigned char *)p,
1121 8,
1122 1, /* little_endian */
1123 1 /* signed */);
1124 Py_DECREF(v);
1125 return res;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001126}
1127
1128static int
1129lp_ulonglong(char *p, PyObject *v, const formatdef *f)
1130{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001131 int res;
1132 v = get_pylong(v);
1133 if (v == NULL)
1134 return -1;
1135 res = _PyLong_AsByteArray((PyLongObject*)v,
1136 (unsigned char *)p,
1137 8,
1138 1, /* little_endian */
1139 0 /* signed */);
1140 Py_DECREF(v);
1141 return res;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001142}
1143
1144static int
1145lp_float(char *p, PyObject *v, const formatdef *f)
1146{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001147 double x = PyFloat_AsDouble(v);
1148 if (x == -1 && PyErr_Occurred()) {
1149 PyErr_SetString(StructError,
1150 "required argument is not a float");
1151 return -1;
1152 }
1153 return _PyFloat_Pack4(x, (unsigned char *)p, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001154}
1155
1156static int
1157lp_double(char *p, PyObject *v, const formatdef *f)
1158{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001159 double x = PyFloat_AsDouble(v);
1160 if (x == -1 && PyErr_Occurred()) {
1161 PyErr_SetString(StructError,
1162 "required argument is not a float");
1163 return -1;
1164 }
1165 return _PyFloat_Pack8(x, (unsigned char *)p, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001166}
1167
1168static formatdef lilendian_table[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001169 {'x', 1, 0, NULL},
1170 {'b', 1, 0, nu_byte, np_byte},
1171 {'B', 1, 0, nu_ubyte, np_ubyte},
1172 {'c', 1, 0, nu_char, np_char},
1173 {'s', 1, 0, NULL},
1174 {'p', 1, 0, NULL},
1175 {'h', 2, 0, lu_int, lp_int},
1176 {'H', 2, 0, lu_uint, lp_uint},
1177 {'i', 4, 0, lu_int, lp_int},
1178 {'I', 4, 0, lu_uint, lp_uint},
1179 {'l', 4, 0, lu_int, lp_int},
1180 {'L', 4, 0, lu_uint, lp_uint},
1181 {'q', 8, 0, lu_longlong, lp_longlong},
1182 {'Q', 8, 0, lu_ulonglong, lp_ulonglong},
1183 {'?', 1, 0, bu_bool, bp_bool}, /* Std rep not endian dep,
1184 but potentially different from native rep -- reuse bx_bool funcs. */
1185 {'f', 4, 0, lu_float, lp_float},
1186 {'d', 8, 0, lu_double, lp_double},
1187 {0}
Thomas Wouters477c8d52006-05-27 19:21:47 +00001188};
1189
1190
1191static const formatdef *
1192whichtable(char **pfmt)
1193{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 const char *fmt = (*pfmt)++; /* May be backed out of later */
1195 switch (*fmt) {
1196 case '<':
1197 return lilendian_table;
1198 case '>':
1199 case '!': /* Network byte order is big-endian */
1200 return bigendian_table;
Ezio Melotti42da6632011-03-15 05:18:48 +02001201 case '=': { /* Host byte order -- different from native in alignment! */
Christian Heimes743e0cd2012-10-17 23:52:17 +02001202#if PY_LITTLE_ENDIAN
1203 return lilendian_table;
1204#else
1205 return bigendian_table;
1206#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001207 }
1208 default:
1209 --*pfmt; /* Back out of pointer increment */
1210 /* Fall through */
1211 case '@':
1212 return native_table;
1213 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001214}
1215
1216
1217/* Get the table entry for a format code */
1218
1219static const formatdef *
1220getentry(int c, const formatdef *f)
1221{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001222 for (; f->format != '\0'; f++) {
1223 if (f->format == c) {
1224 return f;
1225 }
1226 }
1227 PyErr_SetString(StructError, "bad char in struct format");
1228 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001229}
1230
1231
Mark Dickinsonb72e6862010-06-11 19:50:30 +00001232/* Align a size according to a format code. Return -1 on overflow. */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001233
Mark Dickinsoneac0e682010-06-11 19:05:08 +00001234static Py_ssize_t
Thomas Wouters477c8d52006-05-27 19:21:47 +00001235align(Py_ssize_t size, char c, const formatdef *e)
1236{
Mark Dickinsonb72e6862010-06-11 19:50:30 +00001237 Py_ssize_t extra;
1238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001239 if (e->format == c) {
Mark Dickinsonb72e6862010-06-11 19:50:30 +00001240 if (e->alignment && size > 0) {
1241 extra = (e->alignment - 1) - (size - 1) % (e->alignment);
1242 if (extra > PY_SSIZE_T_MAX - size)
1243 return -1;
1244 size += extra;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001245 }
1246 }
1247 return size;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001248}
1249
Antoine Pitrou9f146812013-04-27 00:20:04 +02001250/*
1251 * Struct object implementation.
1252 */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001253
1254/* calculate the size of a format string */
1255
1256static int
1257prepare_s(PyStructObject *self)
1258{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001259 const formatdef *f;
1260 const formatdef *e;
1261 formatcode *codes;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 const char *s;
1264 const char *fmt;
1265 char c;
Mark Dickinsonb72e6862010-06-11 19:50:30 +00001266 Py_ssize_t size, len, num, itemsize;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001267
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001268 fmt = PyBytes_AS_STRING(self->s_format);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001270 f = whichtable((char **)&fmt);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 s = fmt;
1273 size = 0;
1274 len = 0;
1275 while ((c = *s++) != '\0') {
Antoine Pitrou4de74572013-02-09 23:11:27 +01001276 if (Py_ISSPACE(Py_CHARMASK(c)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001277 continue;
1278 if ('0' <= c && c <= '9') {
1279 num = c - '0';
1280 while ('0' <= (c = *s++) && c <= '9') {
Mark Dickinsonab4096f2010-06-11 16:56:34 +00001281 /* overflow-safe version of
1282 if (num*10 + (c - '0') > PY_SSIZE_T_MAX) { ... } */
1283 if (num >= PY_SSIZE_T_MAX / 10 && (
1284 num > PY_SSIZE_T_MAX / 10 ||
Mark Dickinsonb72e6862010-06-11 19:50:30 +00001285 (c - '0') > PY_SSIZE_T_MAX % 10))
1286 goto overflow;
Mark Dickinsonab4096f2010-06-11 16:56:34 +00001287 num = num*10 + (c - '0');
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001288 }
Alexander Belopolsky177e8532010-06-11 16:04:59 +00001289 if (c == '\0') {
1290 PyErr_SetString(StructError,
1291 "repeat count given without format specifier");
1292 return -1;
1293 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001294 }
1295 else
1296 num = 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001298 e = getentry(c, f);
1299 if (e == NULL)
1300 return -1;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001302 switch (c) {
1303 case 's': /* fall through */
1304 case 'p': len++; break;
1305 case 'x': break;
1306 default: len += num; break;
1307 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001309 itemsize = e->size;
1310 size = align(size, c, e);
Mark Dickinsonb72e6862010-06-11 19:50:30 +00001311 if (size == -1)
1312 goto overflow;
1313
1314 /* if (size + num * itemsize > PY_SSIZE_T_MAX) { ... } */
1315 if (num > (PY_SSIZE_T_MAX - size) / itemsize)
1316 goto overflow;
1317 size += num * itemsize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001318 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001320 /* check for overflow */
1321 if ((len + 1) > (PY_SSIZE_T_MAX / sizeof(formatcode))) {
1322 PyErr_NoMemory();
1323 return -1;
1324 }
Amaury Forgeot d'Arc35c86582008-06-17 21:11:29 +00001325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001326 self->s_size = size;
1327 self->s_len = len;
1328 codes = PyMem_MALLOC((len + 1) * sizeof(formatcode));
1329 if (codes == NULL) {
1330 PyErr_NoMemory();
1331 return -1;
1332 }
Mark Dickinsoncf28b952010-07-29 21:41:59 +00001333 /* Free any s_codes value left over from a previous initialization. */
1334 if (self->s_codes != NULL)
1335 PyMem_FREE(self->s_codes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001336 self->s_codes = codes;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001338 s = fmt;
1339 size = 0;
1340 while ((c = *s++) != '\0') {
Antoine Pitrou4de74572013-02-09 23:11:27 +01001341 if (Py_ISSPACE(Py_CHARMASK(c)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001342 continue;
1343 if ('0' <= c && c <= '9') {
1344 num = c - '0';
1345 while ('0' <= (c = *s++) && c <= '9')
1346 num = num*10 + (c - '0');
1347 if (c == '\0')
1348 break;
1349 }
1350 else
1351 num = 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001353 e = getentry(c, f);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001355 size = align(size, c, e);
1356 if (c == 's' || c == 'p') {
1357 codes->offset = size;
1358 codes->size = num;
1359 codes->fmtdef = e;
1360 codes++;
1361 size += num;
1362 } else if (c == 'x') {
1363 size += num;
1364 } else {
1365 while (--num >= 0) {
1366 codes->offset = size;
1367 codes->size = e->size;
1368 codes->fmtdef = e;
1369 codes++;
1370 size += e->size;
1371 }
1372 }
1373 }
1374 codes->fmtdef = NULL;
1375 codes->offset = size;
1376 codes->size = 0;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001378 return 0;
Mark Dickinsonb72e6862010-06-11 19:50:30 +00001379
1380 overflow:
1381 PyErr_SetString(StructError,
1382 "total struct size too long");
1383 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001384}
1385
1386static PyObject *
1387s_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1388{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001389 PyObject *self;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001391 assert(type != NULL && type->tp_alloc != NULL);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001393 self = type->tp_alloc(type, 0);
1394 if (self != NULL) {
1395 PyStructObject *s = (PyStructObject*)self;
1396 Py_INCREF(Py_None);
1397 s->s_format = Py_None;
1398 s->s_codes = NULL;
1399 s->s_size = -1;
1400 s->s_len = -1;
1401 }
1402 return self;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001403}
1404
1405static int
1406s_init(PyObject *self, PyObject *args, PyObject *kwds)
1407{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001408 PyStructObject *soself = (PyStructObject *)self;
1409 PyObject *o_format = NULL;
1410 int ret = 0;
1411 static char *kwlist[] = {"format", 0};
Thomas Wouters477c8d52006-05-27 19:21:47 +00001412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001413 assert(PyStruct_Check(self));
Thomas Wouters477c8d52006-05-27 19:21:47 +00001414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001415 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:Struct", kwlist,
1416 &o_format))
1417 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001418
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001419 if (PyUnicode_Check(o_format)) {
1420 o_format = PyUnicode_AsASCIIString(o_format);
1421 if (o_format == NULL)
1422 return -1;
1423 }
1424 /* XXX support buffer interface, too */
1425 else {
1426 Py_INCREF(o_format);
1427 }
Christian Heimesa34706f2008-01-04 03:06:10 +00001428
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001429 if (!PyBytes_Check(o_format)) {
1430 Py_DECREF(o_format);
1431 PyErr_Format(PyExc_TypeError,
Victor Stinnerda9ec992010-12-28 13:26:42 +00001432 "Struct() argument 1 must be a bytes object, not %.200s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001433 Py_TYPE(o_format)->tp_name);
1434 return -1;
1435 }
Christian Heimesa34706f2008-01-04 03:06:10 +00001436
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001437 Py_CLEAR(soself->s_format);
1438 soself->s_format = o_format;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001440 ret = prepare_s(soself);
1441 return ret;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001442}
1443
1444static void
1445s_dealloc(PyStructObject *s)
1446{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001447 if (s->weakreflist != NULL)
1448 PyObject_ClearWeakRefs((PyObject *)s);
1449 if (s->s_codes != NULL) {
1450 PyMem_FREE(s->s_codes);
1451 }
1452 Py_XDECREF(s->s_format);
1453 Py_TYPE(s)->tp_free((PyObject *)s);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001454}
1455
1456static PyObject *
1457s_unpack_internal(PyStructObject *soself, char *startfrom) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001458 formatcode *code;
1459 Py_ssize_t i = 0;
1460 PyObject *result = PyTuple_New(soself->s_len);
1461 if (result == NULL)
1462 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001463
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001464 for (code = soself->s_codes; code->fmtdef != NULL; code++) {
1465 PyObject *v;
1466 const formatdef *e = code->fmtdef;
1467 const char *res = startfrom + code->offset;
1468 if (e->format == 's') {
1469 v = PyBytes_FromStringAndSize(res, code->size);
1470 } else if (e->format == 'p') {
1471 Py_ssize_t n = *(unsigned char*)res;
1472 if (n >= code->size)
1473 n = code->size - 1;
1474 v = PyBytes_FromStringAndSize(res + 1, n);
1475 } else {
1476 v = e->unpack(res, e);
1477 }
1478 if (v == NULL)
1479 goto fail;
1480 PyTuple_SET_ITEM(result, i++, v);
1481 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001483 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001484fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001485 Py_DECREF(result);
1486 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001487}
1488
1489
1490PyDoc_STRVAR(s_unpack__doc__,
Guido van Rossum913dd0b2007-04-13 03:33:53 +00001491"S.unpack(buffer) -> (v1, v2, ...)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00001492\n\
Mark Dickinsonaacfa952010-06-12 15:43:45 +00001493Return a tuple containing values unpacked according to the format\n\
1494string S.format. Requires len(buffer) == S.size. See help(struct)\n\
1495for more on format strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001496
1497static PyObject *
Guido van Rossum98297ee2007-11-06 21:34:58 +00001498s_unpack(PyObject *self, PyObject *input)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001499{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001500 Py_buffer vbuf;
1501 PyObject *result;
1502 PyStructObject *soself = (PyStructObject *)self;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001504 assert(PyStruct_Check(self));
1505 assert(soself->s_codes != NULL);
1506 if (PyObject_GetBuffer(input, &vbuf, PyBUF_SIMPLE) < 0)
1507 return NULL;
1508 if (vbuf.len != soself->s_size) {
1509 PyErr_Format(StructError,
Victor Stinnerda9ec992010-12-28 13:26:42 +00001510 "unpack requires a bytes object of length %zd",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001511 soself->s_size);
1512 PyBuffer_Release(&vbuf);
1513 return NULL;
1514 }
1515 result = s_unpack_internal(soself, vbuf.buf);
1516 PyBuffer_Release(&vbuf);
1517 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001518}
1519
1520PyDoc_STRVAR(s_unpack_from__doc__,
Mark Dickinsonc6f13962010-06-13 09:17:13 +00001521"S.unpack_from(buffer, offset=0) -> (v1, v2, ...)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00001522\n\
Mark Dickinsonaacfa952010-06-12 15:43:45 +00001523Return a tuple containing values unpacked according to the format\n\
1524string S.format. Requires len(buffer[offset:]) >= S.size. See\n\
1525help(struct) for more on format strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001526
1527static PyObject *
1528s_unpack_from(PyObject *self, PyObject *args, PyObject *kwds)
1529{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001530 static char *kwlist[] = {"buffer", "offset", 0};
Guido van Rossum98297ee2007-11-06 21:34:58 +00001531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001532 PyObject *input;
1533 Py_ssize_t offset = 0;
1534 Py_buffer vbuf;
1535 PyObject *result;
1536 PyStructObject *soself = (PyStructObject *)self;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001538 assert(PyStruct_Check(self));
1539 assert(soself->s_codes != NULL);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001541 if (!PyArg_ParseTupleAndKeywords(args, kwds,
1542 "O|n:unpack_from", kwlist,
1543 &input, &offset))
1544 return NULL;
1545 if (PyObject_GetBuffer(input, &vbuf, PyBUF_SIMPLE) < 0)
1546 return NULL;
1547 if (offset < 0)
1548 offset += vbuf.len;
1549 if (offset < 0 || vbuf.len - offset < soself->s_size) {
1550 PyErr_Format(StructError,
1551 "unpack_from requires a buffer of at least %zd bytes",
1552 soself->s_size);
1553 PyBuffer_Release(&vbuf);
1554 return NULL;
1555 }
1556 result = s_unpack_internal(soself, (char*)vbuf.buf + offset);
1557 PyBuffer_Release(&vbuf);
1558 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001559}
1560
1561
Antoine Pitrou9f146812013-04-27 00:20:04 +02001562/* Unpack iterator type */
1563
1564typedef struct {
1565 PyObject_HEAD
1566 PyStructObject *so;
1567 Py_buffer buf;
1568 Py_ssize_t index;
1569} unpackiterobject;
1570
1571static void
1572unpackiter_dealloc(unpackiterobject *self)
1573{
1574 Py_XDECREF(self->so);
1575 PyBuffer_Release(&self->buf);
1576 PyObject_GC_Del(self);
1577}
1578
1579static int
1580unpackiter_traverse(unpackiterobject *self, visitproc visit, void *arg)
1581{
1582 Py_VISIT(self->so);
1583 Py_VISIT(self->buf.obj);
1584 return 0;
1585}
1586
1587static PyObject *
1588unpackiter_len(unpackiterobject *self)
1589{
1590 Py_ssize_t len;
1591 if (self->so == NULL)
1592 len = 0;
1593 else
1594 len = (self->buf.len - self->index) / self->so->s_size;
1595 return PyLong_FromSsize_t(len);
1596}
1597
1598static PyMethodDef unpackiter_methods[] = {
1599 {"__length_hint__", (PyCFunction) unpackiter_len, METH_NOARGS, NULL},
1600 {NULL, NULL} /* sentinel */
1601};
1602
1603static PyObject *
1604unpackiter_iternext(unpackiterobject *self)
1605{
1606 PyObject *result;
1607 if (self->so == NULL)
1608 return NULL;
1609 if (self->index >= self->buf.len) {
1610 /* Iterator exhausted */
1611 Py_CLEAR(self->so);
1612 PyBuffer_Release(&self->buf);
1613 return NULL;
1614 }
1615 assert(self->index + self->so->s_size <= self->buf.len);
1616 result = s_unpack_internal(self->so,
1617 (char*) self->buf.buf + self->index);
1618 self->index += self->so->s_size;
1619 return result;
1620}
1621
1622PyTypeObject unpackiter_type = {
1623 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1624 "unpack_iterator", /* tp_name */
1625 sizeof(unpackiterobject), /* tp_basicsize */
1626 0, /* tp_itemsize */
1627 (destructor)unpackiter_dealloc, /* tp_dealloc */
1628 0, /* tp_print */
1629 0, /* tp_getattr */
1630 0, /* tp_setattr */
1631 0, /* tp_reserved */
1632 0, /* tp_repr */
1633 0, /* tp_as_number */
1634 0, /* tp_as_sequence */
1635 0, /* tp_as_mapping */
1636 0, /* tp_hash */
1637 0, /* tp_call */
1638 0, /* tp_str */
1639 PyObject_GenericGetAttr, /* tp_getattro */
1640 0, /* tp_setattro */
1641 0, /* tp_as_buffer */
1642 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
1643 0, /* tp_doc */
1644 (traverseproc)unpackiter_traverse, /* tp_traverse */
1645 0, /* tp_clear */
1646 0, /* tp_richcompare */
1647 0, /* tp_weaklistoffset */
1648 PyObject_SelfIter, /* tp_iter */
1649 (iternextfunc)unpackiter_iternext, /* tp_iternext */
1650 unpackiter_methods /* tp_methods */
1651};
1652
1653PyDoc_STRVAR(s_iter_unpack__doc__,
1654"S.iter_unpack(buffer) -> iterator(v1, v2, ...)\n\
1655\n\
1656Return an iterator yielding tuples unpacked from the given bytes\n\
1657source, like a repeated invocation of unpack_from(). Requires\n\
1658that the bytes length be a multiple of the struct size.");
1659
1660static PyObject *
1661s_iter_unpack(PyObject *_so, PyObject *input)
1662{
1663 PyStructObject *so = (PyStructObject *) _so;
1664 unpackiterobject *self;
1665
1666 assert(PyStruct_Check(_so));
1667 assert(so->s_codes != NULL);
1668
1669 if (so->s_size == 0) {
1670 PyErr_Format(StructError,
1671 "cannot iteratively unpack with a struct of length 0");
1672 return NULL;
1673 }
1674
1675 self = (unpackiterobject *) PyType_GenericAlloc(&unpackiter_type, 0);
1676 if (self == NULL)
1677 return NULL;
1678
1679 if (PyObject_GetBuffer(input, &self->buf, PyBUF_SIMPLE) < 0) {
1680 Py_DECREF(self);
1681 return NULL;
1682 }
1683 if (self->buf.len % so->s_size != 0) {
1684 PyErr_Format(StructError,
1685 "iterative unpacking requires a bytes length "
1686 "multiple of %zd",
1687 so->s_size);
1688 Py_DECREF(self);
1689 return NULL;
1690 }
1691 Py_INCREF(so);
1692 self->so = so;
1693 self->index = 0;
1694 return (PyObject *) self;
1695}
1696
1697
Thomas Wouters477c8d52006-05-27 19:21:47 +00001698/*
1699 * Guts of the pack function.
1700 *
1701 * Takes a struct object, a tuple of arguments, and offset in that tuple of
1702 * argument for where to start processing the arguments for packing, and a
1703 * character buffer for writing the packed string. The caller must insure
1704 * that the buffer may contain the required length for packing the arguments.
1705 * 0 is returned on success, 1 is returned if there is an error.
1706 *
1707 */
1708static int
1709s_pack_internal(PyStructObject *soself, PyObject *args, int offset, char* buf)
1710{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001711 formatcode *code;
1712 /* XXX(nnorwitz): why does i need to be a local? can we use
1713 the offset parameter or do we need the wider width? */
1714 Py_ssize_t i;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001715
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001716 memset(buf, '\0', soself->s_size);
1717 i = offset;
1718 for (code = soself->s_codes; code->fmtdef != NULL; code++) {
1719 Py_ssize_t n;
1720 PyObject *v = PyTuple_GET_ITEM(args, i++);
1721 const formatdef *e = code->fmtdef;
1722 char *res = buf + code->offset;
1723 if (e->format == 's') {
1724 int isstring;
1725 void *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001726 isstring = PyBytes_Check(v);
1727 if (!isstring && !PyByteArray_Check(v)) {
1728 PyErr_SetString(StructError,
Victor Stinnerda9ec992010-12-28 13:26:42 +00001729 "argument for 's' must be a bytes object");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001730 return -1;
1731 }
1732 if (isstring) {
1733 n = PyBytes_GET_SIZE(v);
1734 p = PyBytes_AS_STRING(v);
1735 }
1736 else {
1737 n = PyByteArray_GET_SIZE(v);
1738 p = PyByteArray_AS_STRING(v);
1739 }
1740 if (n > code->size)
1741 n = code->size;
1742 if (n > 0)
1743 memcpy(res, p, n);
1744 } else if (e->format == 'p') {
1745 int isstring;
1746 void *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001747 isstring = PyBytes_Check(v);
1748 if (!isstring && !PyByteArray_Check(v)) {
1749 PyErr_SetString(StructError,
Victor Stinnerda9ec992010-12-28 13:26:42 +00001750 "argument for 'p' must be a bytes object");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001751 return -1;
1752 }
1753 if (isstring) {
1754 n = PyBytes_GET_SIZE(v);
1755 p = PyBytes_AS_STRING(v);
1756 }
1757 else {
1758 n = PyByteArray_GET_SIZE(v);
1759 p = PyByteArray_AS_STRING(v);
1760 }
1761 if (n > (code->size - 1))
1762 n = code->size - 1;
1763 if (n > 0)
1764 memcpy(res + 1, p, n);
1765 if (n > 255)
1766 n = 255;
1767 *res = Py_SAFE_DOWNCAST(n, Py_ssize_t, unsigned char);
1768 } else {
1769 if (e->pack(res, v, e) < 0) {
1770 if (PyLong_Check(v) && PyErr_ExceptionMatches(PyExc_OverflowError))
1771 PyErr_SetString(StructError,
1772 "long too large to convert to int");
1773 return -1;
1774 }
1775 }
1776 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001777
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001778 /* Success */
1779 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001780}
1781
1782
1783PyDoc_STRVAR(s_pack__doc__,
Benjamin Peterson4ae19462008-07-31 15:03:40 +00001784"S.pack(v1, v2, ...) -> bytes\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00001785\n\
Mark Dickinsonaacfa952010-06-12 15:43:45 +00001786Return a bytes object containing values v1, v2, ... packed according\n\
1787to the format string S.format. See help(struct) for more on format\n\
1788strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001789
1790static PyObject *
1791s_pack(PyObject *self, PyObject *args)
1792{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001793 PyStructObject *soself;
1794 PyObject *result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001796 /* Validate arguments. */
1797 soself = (PyStructObject *)self;
1798 assert(PyStruct_Check(self));
1799 assert(soself->s_codes != NULL);
1800 if (PyTuple_GET_SIZE(args) != soself->s_len)
1801 {
1802 PyErr_Format(StructError,
Petri Lehtinen92c28ca2012-10-29 21:16:57 +02001803 "pack expected %zd items for packing (got %zd)", soself->s_len, PyTuple_GET_SIZE(args));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001804 return NULL;
1805 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001807 /* Allocate a new string */
1808 result = PyBytes_FromStringAndSize((char *)NULL, soself->s_size);
1809 if (result == NULL)
1810 return NULL;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001811
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001812 /* Call the guts */
1813 if ( s_pack_internal(soself, args, 0, PyBytes_AS_STRING(result)) != 0 ) {
1814 Py_DECREF(result);
1815 return NULL;
1816 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001817
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001818 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001819}
1820
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001821PyDoc_STRVAR(s_pack_into__doc__,
1822"S.pack_into(buffer, offset, v1, v2, ...)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00001823\n\
Mark Dickinsonaacfa952010-06-12 15:43:45 +00001824Pack the values v1, v2, ... according to the format string S.format\n\
1825and write the packed bytes into the writable buffer buf starting at\n\
Mark Dickinsonfdb99f12010-06-12 16:30:53 +00001826offset. Note that the offset is a required argument. See\n\
Mark Dickinsonaacfa952010-06-12 15:43:45 +00001827help(struct) for more on format strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001828
1829static PyObject *
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001830s_pack_into(PyObject *self, PyObject *args)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001831{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001832 PyStructObject *soself;
1833 char *buffer;
1834 Py_ssize_t buffer_len, offset;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001836 /* Validate arguments. +1 is for the first arg as buffer. */
1837 soself = (PyStructObject *)self;
1838 assert(PyStruct_Check(self));
1839 assert(soself->s_codes != NULL);
1840 if (PyTuple_GET_SIZE(args) != (soself->s_len + 2))
1841 {
Petri Lehtinen92c28ca2012-10-29 21:16:57 +02001842 if (PyTuple_GET_SIZE(args) == 0) {
1843 PyErr_Format(StructError,
1844 "pack_into expected buffer argument");
1845 }
1846 else if (PyTuple_GET_SIZE(args) == 1) {
1847 PyErr_Format(StructError,
1848 "pack_into expected offset argument");
1849 }
1850 else {
1851 PyErr_Format(StructError,
1852 "pack_into expected %zd items for packing (got %zd)",
1853 soself->s_len, (PyTuple_GET_SIZE(args) - 2));
1854 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001855 return NULL;
1856 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001858 /* Extract a writable memory buffer from the first argument */
1859 if ( PyObject_AsWriteBuffer(PyTuple_GET_ITEM(args, 0),
1860 (void**)&buffer, &buffer_len) == -1 ) {
1861 return NULL;
1862 }
1863 assert( buffer_len >= 0 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00001864
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001865 /* Extract the offset from the first argument */
1866 offset = PyNumber_AsSsize_t(PyTuple_GET_ITEM(args, 1), PyExc_IndexError);
1867 if (offset == -1 && PyErr_Occurred())
1868 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001870 /* Support negative offsets. */
1871 if (offset < 0)
1872 offset += buffer_len;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001874 /* Check boundaries */
1875 if (offset < 0 || (buffer_len - offset) < soself->s_size) {
1876 PyErr_Format(StructError,
1877 "pack_into requires a buffer of at least %zd bytes",
1878 soself->s_size);
1879 return NULL;
1880 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001882 /* Call the guts */
1883 if ( s_pack_internal(soself, args, 2, buffer + offset) != 0 ) {
1884 return NULL;
1885 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001886
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001887 Py_RETURN_NONE;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001888}
1889
1890static PyObject *
1891s_get_format(PyStructObject *self, void *unused)
1892{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001893 Py_INCREF(self->s_format);
1894 return self->s_format;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001895}
1896
1897static PyObject *
1898s_get_size(PyStructObject *self, void *unused)
1899{
Christian Heimes217cfd12007-12-02 14:31:20 +00001900 return PyLong_FromSsize_t(self->s_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001901}
1902
Meador Ingeb14d8c92012-07-23 10:01:29 -05001903PyDoc_STRVAR(s_sizeof__doc__,
1904"S.__sizeof__() -> size of S in memory, in bytes");
1905
1906static PyObject *
Meador Inge90bc2dbc2012-07-28 22:16:39 -05001907s_sizeof(PyStructObject *self, void *unused)
Meador Ingeb14d8c92012-07-23 10:01:29 -05001908{
1909 Py_ssize_t size;
Meador Ingeb14d8c92012-07-23 10:01:29 -05001910
Meador Inge90bc2dbc2012-07-28 22:16:39 -05001911 size = sizeof(PyStructObject) + sizeof(formatcode) * (self->s_len + 1);
Meador Ingeb14d8c92012-07-23 10:01:29 -05001912 return PyLong_FromSsize_t(size);
1913}
1914
Thomas Wouters477c8d52006-05-27 19:21:47 +00001915/* List of functions */
1916
1917static struct PyMethodDef s_methods[] = {
Antoine Pitrou9f146812013-04-27 00:20:04 +02001918 {"iter_unpack", s_iter_unpack, METH_O, s_iter_unpack__doc__},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001919 {"pack", s_pack, METH_VARARGS, s_pack__doc__},
1920 {"pack_into", s_pack_into, METH_VARARGS, s_pack_into__doc__},
1921 {"unpack", s_unpack, METH_O, s_unpack__doc__},
1922 {"unpack_from", (PyCFunction)s_unpack_from, METH_VARARGS|METH_KEYWORDS,
1923 s_unpack_from__doc__},
Meador Ingeb14d8c92012-07-23 10:01:29 -05001924 {"__sizeof__", (PyCFunction)s_sizeof, METH_NOARGS, s_sizeof__doc__},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001925 {NULL, NULL} /* sentinel */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001926};
1927
Victor Stinnerda9ec992010-12-28 13:26:42 +00001928PyDoc_STRVAR(s__doc__,
Alexander Belopolsky0bd003a2010-06-12 19:36:28 +00001929"Struct(fmt) --> compiled struct object\n"
1930"\n"
1931"Return a new Struct object which writes and reads binary data according to\n"
1932"the format string fmt. See help(struct) for more on format strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001933
1934#define OFF(x) offsetof(PyStructObject, x)
1935
1936static PyGetSetDef s_getsetlist[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001937 {"format", (getter)s_get_format, (setter)NULL, "struct format string", NULL},
1938 {"size", (getter)s_get_size, (setter)NULL, "struct size in bytes", NULL},
1939 {NULL} /* sentinel */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001940};
1941
1942static
1943PyTypeObject PyStructType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001944 PyVarObject_HEAD_INIT(NULL, 0)
1945 "Struct",
1946 sizeof(PyStructObject),
1947 0,
1948 (destructor)s_dealloc, /* tp_dealloc */
1949 0, /* tp_print */
1950 0, /* tp_getattr */
1951 0, /* tp_setattr */
1952 0, /* tp_reserved */
1953 0, /* tp_repr */
1954 0, /* tp_as_number */
1955 0, /* tp_as_sequence */
1956 0, /* tp_as_mapping */
1957 0, /* tp_hash */
1958 0, /* tp_call */
1959 0, /* tp_str */
1960 PyObject_GenericGetAttr, /* tp_getattro */
1961 PyObject_GenericSetAttr, /* tp_setattro */
1962 0, /* tp_as_buffer */
1963 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1964 s__doc__, /* tp_doc */
1965 0, /* tp_traverse */
1966 0, /* tp_clear */
1967 0, /* tp_richcompare */
1968 offsetof(PyStructObject, weakreflist), /* tp_weaklistoffset */
1969 0, /* tp_iter */
1970 0, /* tp_iternext */
1971 s_methods, /* tp_methods */
1972 NULL, /* tp_members */
1973 s_getsetlist, /* tp_getset */
1974 0, /* tp_base */
1975 0, /* tp_dict */
1976 0, /* tp_descr_get */
1977 0, /* tp_descr_set */
1978 0, /* tp_dictoffset */
1979 s_init, /* tp_init */
1980 PyType_GenericAlloc,/* tp_alloc */
1981 s_new, /* tp_new */
1982 PyObject_Del, /* tp_free */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001983};
1984
Christian Heimesa34706f2008-01-04 03:06:10 +00001985
1986/* ---- Standalone functions ---- */
1987
1988#define MAXCACHE 100
1989static PyObject *cache = NULL;
1990
1991static PyObject *
1992cache_struct(PyObject *fmt)
1993{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001994 PyObject * s_object;
Christian Heimesa34706f2008-01-04 03:06:10 +00001995
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001996 if (cache == NULL) {
1997 cache = PyDict_New();
1998 if (cache == NULL)
1999 return NULL;
2000 }
Christian Heimesa34706f2008-01-04 03:06:10 +00002001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002002 s_object = PyDict_GetItem(cache, fmt);
2003 if (s_object != NULL) {
2004 Py_INCREF(s_object);
2005 return s_object;
2006 }
Christian Heimesa34706f2008-01-04 03:06:10 +00002007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002008 s_object = PyObject_CallFunctionObjArgs((PyObject *)(&PyStructType), fmt, NULL);
2009 if (s_object != NULL) {
2010 if (PyDict_Size(cache) >= MAXCACHE)
2011 PyDict_Clear(cache);
2012 /* Attempt to cache the result */
2013 if (PyDict_SetItem(cache, fmt, s_object) == -1)
2014 PyErr_Clear();
2015 }
2016 return s_object;
Christian Heimesa34706f2008-01-04 03:06:10 +00002017}
2018
2019PyDoc_STRVAR(clearcache_doc,
2020"Clear the internal cache.");
2021
2022static PyObject *
2023clearcache(PyObject *self)
2024{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002025 Py_CLEAR(cache);
2026 Py_RETURN_NONE;
Christian Heimesa34706f2008-01-04 03:06:10 +00002027}
2028
2029PyDoc_STRVAR(calcsize_doc,
Mark Dickinsonaacfa952010-06-12 15:43:45 +00002030"calcsize(fmt) -> integer\n\
2031\n\
2032Return size in bytes of the struct described by the format string fmt.");
Christian Heimesa34706f2008-01-04 03:06:10 +00002033
2034static PyObject *
2035calcsize(PyObject *self, PyObject *fmt)
2036{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002037 Py_ssize_t n;
2038 PyObject *s_object = cache_struct(fmt);
2039 if (s_object == NULL)
2040 return NULL;
2041 n = ((PyStructObject *)s_object)->s_size;
2042 Py_DECREF(s_object);
2043 return PyLong_FromSsize_t(n);
Christian Heimesa34706f2008-01-04 03:06:10 +00002044}
2045
2046PyDoc_STRVAR(pack_doc,
Mark Dickinsonaacfa952010-06-12 15:43:45 +00002047"pack(fmt, v1, v2, ...) -> bytes\n\
2048\n\
Mark Dickinsonfdb99f12010-06-12 16:30:53 +00002049Return a bytes object containing the values v1, v2, ... packed according\n\
2050to the format string fmt. See help(struct) for more on format strings.");
Christian Heimesa34706f2008-01-04 03:06:10 +00002051
2052static PyObject *
2053pack(PyObject *self, PyObject *args)
2054{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002055 PyObject *s_object, *fmt, *newargs, *result;
2056 Py_ssize_t n = PyTuple_GET_SIZE(args);
Christian Heimesa34706f2008-01-04 03:06:10 +00002057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002058 if (n == 0) {
2059 PyErr_SetString(PyExc_TypeError, "missing format argument");
2060 return NULL;
2061 }
2062 fmt = PyTuple_GET_ITEM(args, 0);
2063 newargs = PyTuple_GetSlice(args, 1, n);
2064 if (newargs == NULL)
2065 return NULL;
Christian Heimesa34706f2008-01-04 03:06:10 +00002066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002067 s_object = cache_struct(fmt);
2068 if (s_object == NULL) {
2069 Py_DECREF(newargs);
2070 return NULL;
2071 }
2072 result = s_pack(s_object, newargs);
2073 Py_DECREF(newargs);
2074 Py_DECREF(s_object);
2075 return result;
Christian Heimesa34706f2008-01-04 03:06:10 +00002076}
2077
2078PyDoc_STRVAR(pack_into_doc,
Mark Dickinsonaacfa952010-06-12 15:43:45 +00002079"pack_into(fmt, buffer, offset, v1, v2, ...)\n\
2080\n\
2081Pack the values v1, v2, ... according to the format string fmt and write\n\
2082the packed bytes into the writable buffer buf starting at offset. Note\n\
Mark Dickinsonfdb99f12010-06-12 16:30:53 +00002083that the offset is a required argument. See help(struct) for more\n\
Mark Dickinsonaacfa952010-06-12 15:43:45 +00002084on format strings.");
Christian Heimesa34706f2008-01-04 03:06:10 +00002085
2086static PyObject *
2087pack_into(PyObject *self, PyObject *args)
2088{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002089 PyObject *s_object, *fmt, *newargs, *result;
2090 Py_ssize_t n = PyTuple_GET_SIZE(args);
Christian Heimesa34706f2008-01-04 03:06:10 +00002091
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002092 if (n == 0) {
2093 PyErr_SetString(PyExc_TypeError, "missing format argument");
2094 return NULL;
2095 }
2096 fmt = PyTuple_GET_ITEM(args, 0);
2097 newargs = PyTuple_GetSlice(args, 1, n);
2098 if (newargs == NULL)
2099 return NULL;
Christian Heimesa34706f2008-01-04 03:06:10 +00002100
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002101 s_object = cache_struct(fmt);
2102 if (s_object == NULL) {
2103 Py_DECREF(newargs);
2104 return NULL;
2105 }
2106 result = s_pack_into(s_object, newargs);
2107 Py_DECREF(newargs);
2108 Py_DECREF(s_object);
2109 return result;
Christian Heimesa34706f2008-01-04 03:06:10 +00002110}
2111
2112PyDoc_STRVAR(unpack_doc,
Mark Dickinsonaacfa952010-06-12 15:43:45 +00002113"unpack(fmt, buffer) -> (v1, v2, ...)\n\
2114\n\
2115Return a tuple containing values unpacked according to the format string\n\
2116fmt. Requires len(buffer) == calcsize(fmt). See help(struct) for more\n\
2117on format strings.");
Christian Heimesa34706f2008-01-04 03:06:10 +00002118
2119static PyObject *
2120unpack(PyObject *self, PyObject *args)
2121{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002122 PyObject *s_object, *fmt, *inputstr, *result;
Christian Heimesa34706f2008-01-04 03:06:10 +00002123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002124 if (!PyArg_UnpackTuple(args, "unpack", 2, 2, &fmt, &inputstr))
2125 return NULL;
Christian Heimesa34706f2008-01-04 03:06:10 +00002126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002127 s_object = cache_struct(fmt);
2128 if (s_object == NULL)
2129 return NULL;
2130 result = s_unpack(s_object, inputstr);
2131 Py_DECREF(s_object);
2132 return result;
Christian Heimesa34706f2008-01-04 03:06:10 +00002133}
2134
2135PyDoc_STRVAR(unpack_from_doc,
Mark Dickinsonc6f13962010-06-13 09:17:13 +00002136"unpack_from(fmt, buffer, offset=0) -> (v1, v2, ...)\n\
Mark Dickinsonaacfa952010-06-12 15:43:45 +00002137\n\
2138Return a tuple containing values unpacked according to the format string\n\
2139fmt. Requires len(buffer[offset:]) >= calcsize(fmt). See help(struct)\n\
2140for more on format strings.");
Christian Heimesa34706f2008-01-04 03:06:10 +00002141
2142static PyObject *
2143unpack_from(PyObject *self, PyObject *args, PyObject *kwds)
2144{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002145 PyObject *s_object, *fmt, *newargs, *result;
2146 Py_ssize_t n = PyTuple_GET_SIZE(args);
Christian Heimesa34706f2008-01-04 03:06:10 +00002147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002148 if (n == 0) {
2149 PyErr_SetString(PyExc_TypeError, "missing format argument");
2150 return NULL;
2151 }
2152 fmt = PyTuple_GET_ITEM(args, 0);
2153 newargs = PyTuple_GetSlice(args, 1, n);
2154 if (newargs == NULL)
2155 return NULL;
Christian Heimesa34706f2008-01-04 03:06:10 +00002156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002157 s_object = cache_struct(fmt);
2158 if (s_object == NULL) {
2159 Py_DECREF(newargs);
2160 return NULL;
2161 }
2162 result = s_unpack_from(s_object, newargs, kwds);
2163 Py_DECREF(newargs);
2164 Py_DECREF(s_object);
2165 return result;
Christian Heimesa34706f2008-01-04 03:06:10 +00002166}
2167
Antoine Pitrou9f146812013-04-27 00:20:04 +02002168PyDoc_STRVAR(iter_unpack_doc,
2169"iter_unpack(fmt, buffer) -> iterator(v1, v2, ...)\n\
2170\n\
2171Return an iterator yielding tuples unpacked from the given bytes\n\
2172source according to the format string, like a repeated invocation of\n\
2173unpack_from(). Requires that the bytes length be a multiple of the\n\
2174format struct size.");
2175
2176static PyObject *
2177iter_unpack(PyObject *self, PyObject *args)
2178{
2179 PyObject *s_object, *fmt, *input, *result;
2180
2181 if (!PyArg_ParseTuple(args, "OO:iter_unpack", &fmt, &input))
2182 return NULL;
2183
2184 s_object = cache_struct(fmt);
2185 if (s_object == NULL)
2186 return NULL;
2187 result = s_iter_unpack(s_object, input);
2188 Py_DECREF(s_object);
2189 return result;
2190}
2191
Christian Heimesa34706f2008-01-04 03:06:10 +00002192static struct PyMethodDef module_functions[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002193 {"_clearcache", (PyCFunction)clearcache, METH_NOARGS, clearcache_doc},
2194 {"calcsize", calcsize, METH_O, calcsize_doc},
Antoine Pitrou9f146812013-04-27 00:20:04 +02002195 {"iter_unpack", iter_unpack, METH_VARARGS, iter_unpack_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002196 {"pack", pack, METH_VARARGS, pack_doc},
2197 {"pack_into", pack_into, METH_VARARGS, pack_into_doc},
2198 {"unpack", unpack, METH_VARARGS, unpack_doc},
2199 {"unpack_from", (PyCFunction)unpack_from,
2200 METH_VARARGS|METH_KEYWORDS, unpack_from_doc},
2201 {NULL, NULL} /* sentinel */
Christian Heimesa34706f2008-01-04 03:06:10 +00002202};
2203
2204
Thomas Wouters477c8d52006-05-27 19:21:47 +00002205/* Module initialization */
2206
Christian Heimesa34706f2008-01-04 03:06:10 +00002207PyDoc_STRVAR(module_doc,
2208"Functions to convert between Python values and C structs.\n\
Benjamin Peterson4ae19462008-07-31 15:03:40 +00002209Python bytes objects are used to hold the data representing the C struct\n\
Mark Dickinson40714af2009-10-08 15:59:20 +00002210and also as format strings (explained below) to describe the layout of data\n\
2211in the C struct.\n\
Christian Heimesa34706f2008-01-04 03:06:10 +00002212\n\
2213The optional first format char indicates byte order, size and alignment:\n\
Mark Dickinson40714af2009-10-08 15:59:20 +00002214 @: native order, size & alignment (default)\n\
2215 =: native order, std. size & alignment\n\
2216 <: little-endian, std. size & alignment\n\
2217 >: big-endian, std. size & alignment\n\
2218 !: same as >\n\
Christian Heimesa34706f2008-01-04 03:06:10 +00002219\n\
2220The remaining chars indicate types of args and must match exactly;\n\
2221these can be preceded by a decimal repeat count:\n\
2222 x: pad byte (no data); c:char; b:signed byte; B:unsigned byte;\n\
Mark Dickinson40714af2009-10-08 15:59:20 +00002223 ?: _Bool (requires C99; if not available, char is used instead)\n\
Christian Heimesa34706f2008-01-04 03:06:10 +00002224 h:short; H:unsigned short; i:int; I:unsigned int;\n\
2225 l:long; L:unsigned long; f:float; d:double.\n\
2226Special cases (preceding decimal count indicates length):\n\
2227 s:string (array of char); p: pascal string (with count byte).\n\
Antoine Pitrou45d9c912011-10-06 15:27:40 +02002228Special cases (only available in native format):\n\
2229 n:ssize_t; N:size_t;\n\
Christian Heimesa34706f2008-01-04 03:06:10 +00002230 P:an integer type that is wide enough to hold a pointer.\n\
2231Special case (not in native mode unless 'long long' in platform C):\n\
2232 q:long long; Q:unsigned long long\n\
2233Whitespace between formats is ignored.\n\
2234\n\
2235The variable struct.error is an exception raised on errors.\n");
2236
Martin v. Löwis1a214512008-06-11 05:26:20 +00002237
2238static struct PyModuleDef _structmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002239 PyModuleDef_HEAD_INIT,
2240 "_struct",
2241 module_doc,
2242 -1,
2243 module_functions,
2244 NULL,
2245 NULL,
2246 NULL,
2247 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002248};
2249
Thomas Wouters477c8d52006-05-27 19:21:47 +00002250PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002251PyInit__struct(void)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002252{
Mark Dickinson06817852010-06-12 09:25:13 +00002253 PyObject *m;
Christian Heimesa34706f2008-01-04 03:06:10 +00002254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002255 m = PyModule_Create(&_structmodule);
2256 if (m == NULL)
2257 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002259 Py_TYPE(&PyStructType) = &PyType_Type;
2260 if (PyType_Ready(&PyStructType) < 0)
2261 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002263 /* Check endian and swap in faster functions */
2264 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002265 formatdef *native = native_table;
2266 formatdef *other, *ptr;
Christian Heimes743e0cd2012-10-17 23:52:17 +02002267#if PY_LITTLE_ENDIAN
2268 other = lilendian_table;
2269#else
2270 other = bigendian_table;
2271#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002272 /* Scan through the native table, find a matching
2273 entry in the endian table and swap in the
2274 native implementations whenever possible
2275 (64-bit platforms may not have "standard" sizes) */
2276 while (native->format != '\0' && other->format != '\0') {
2277 ptr = other;
2278 while (ptr->format != '\0') {
2279 if (ptr->format == native->format) {
2280 /* Match faster when formats are
2281 listed in the same order */
2282 if (ptr == other)
2283 other++;
2284 /* Only use the trick if the
2285 size matches */
2286 if (ptr->size != native->size)
2287 break;
2288 /* Skip float and double, could be
2289 "unknown" float format */
2290 if (ptr->format == 'd' || ptr->format == 'f')
2291 break;
2292 ptr->pack = native->pack;
2293 ptr->unpack = native->unpack;
2294 break;
2295 }
2296 ptr++;
2297 }
2298 native++;
2299 }
2300 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002302 /* Add some symbolic constants to the module */
2303 if (StructError == NULL) {
2304 StructError = PyErr_NewException("struct.error", NULL, NULL);
2305 if (StructError == NULL)
2306 return NULL;
2307 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002309 Py_INCREF(StructError);
2310 PyModule_AddObject(m, "error", StructError);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002312 Py_INCREF((PyObject*)&PyStructType);
2313 PyModule_AddObject(m, "Struct", (PyObject*)&PyStructType);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002315 return m;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002316}