blob: 4941fc8c8272f9a59d960f669448ccb98bce8063 [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;
Serhiy Storchakafff61f22013-05-17 10:49:44 +030029 Py_ssize_t repeat;
Thomas Wouters477c8d52006-05-27 19:21:47 +000030} formatcode;
31
32/* Struct object interface */
33
34typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000035 PyObject_HEAD
36 Py_ssize_t s_size;
37 Py_ssize_t s_len;
38 formatcode *s_codes;
39 PyObject *s_format;
40 PyObject *weakreflist; /* List of weak references */
Thomas Wouters477c8d52006-05-27 19:21:47 +000041} PyStructObject;
42
43
44#define PyStruct_Check(op) PyObject_TypeCheck(op, &PyStructType)
Christian Heimes90aa7642007-12-19 02:45:37 +000045#define PyStruct_CheckExact(op) (Py_TYPE(op) == &PyStructType)
Thomas Wouters477c8d52006-05-27 19:21:47 +000046
47
48/* Exception */
49
50static PyObject *StructError;
51
52
53/* Define various structs to figure out the alignments of types */
54
55
56typedef struct { char c; short x; } st_short;
57typedef struct { char c; int x; } st_int;
58typedef struct { char c; long x; } st_long;
59typedef struct { char c; float x; } st_float;
60typedef struct { char c; double x; } st_double;
61typedef struct { char c; void *x; } st_void_p;
Antoine Pitrou45d9c912011-10-06 15:27:40 +020062typedef struct { char c; size_t x; } st_size_t;
Thomas Wouters477c8d52006-05-27 19:21:47 +000063
64#define SHORT_ALIGN (sizeof(st_short) - sizeof(short))
65#define INT_ALIGN (sizeof(st_int) - sizeof(int))
66#define LONG_ALIGN (sizeof(st_long) - sizeof(long))
67#define FLOAT_ALIGN (sizeof(st_float) - sizeof(float))
68#define DOUBLE_ALIGN (sizeof(st_double) - sizeof(double))
69#define VOID_P_ALIGN (sizeof(st_void_p) - sizeof(void *))
Antoine Pitrou45d9c912011-10-06 15:27:40 +020070#define SIZE_T_ALIGN (sizeof(st_size_t) - sizeof(size_t))
Thomas Wouters477c8d52006-05-27 19:21:47 +000071
72/* We can't support q and Q in native mode unless the compiler does;
73 in std mode, they're 8 bytes on all platforms. */
74#ifdef HAVE_LONG_LONG
75typedef struct { char c; PY_LONG_LONG x; } s_long_long;
76#define LONG_LONG_ALIGN (sizeof(s_long_long) - sizeof(PY_LONG_LONG))
77#endif
78
Thomas Woutersb2137042007-02-01 18:02:27 +000079#ifdef HAVE_C99_BOOL
80#define BOOL_TYPE _Bool
81typedef struct { char c; _Bool x; } s_bool;
82#define BOOL_ALIGN (sizeof(s_bool) - sizeof(BOOL_TYPE))
83#else
84#define BOOL_TYPE char
85#define BOOL_ALIGN 0
86#endif
87
Thomas Wouters477c8d52006-05-27 19:21:47 +000088#ifdef __powerc
89#pragma options align=reset
90#endif
91
Mark Dickinson055a3fb2010-04-03 15:26:31 +000092/* Helper for integer format codes: converts an arbitrary Python object to a
93 PyLongObject if possible, otherwise fails. Caller should decref. */
Thomas Wouters477c8d52006-05-27 19:21:47 +000094
95static PyObject *
96get_pylong(PyObject *v)
97{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000098 assert(v != NULL);
99 if (!PyLong_Check(v)) {
100 /* Not an integer; try to use __index__ to convert. */
101 if (PyIndex_Check(v)) {
102 v = PyNumber_Index(v);
103 if (v == NULL)
104 return NULL;
105 }
106 else {
107 PyErr_SetString(StructError,
108 "required argument is not an integer");
109 return NULL;
110 }
111 }
112 else
113 Py_INCREF(v);
Mark Dickinsonea835e72009-04-19 20:40:33 +0000114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000115 assert(PyLong_Check(v));
116 return v;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000117}
118
Mark Dickinsonea835e72009-04-19 20:40:33 +0000119/* Helper routine to get a C long and raise the appropriate error if it isn't
120 one */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000121
122static int
123get_long(PyObject *v, long *p)
124{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000125 long x;
Mark Dickinsonea835e72009-04-19 20:40:33 +0000126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000127 v = get_pylong(v);
128 if (v == NULL)
129 return -1;
130 assert(PyLong_Check(v));
131 x = PyLong_AsLong(v);
132 Py_DECREF(v);
133 if (x == (long)-1 && PyErr_Occurred()) {
134 if (PyErr_ExceptionMatches(PyExc_OverflowError))
135 PyErr_SetString(StructError,
136 "argument out of range");
137 return -1;
138 }
139 *p = x;
140 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000141}
142
143
144/* Same, but handling unsigned long */
145
146static int
147get_ulong(PyObject *v, unsigned long *p)
148{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000149 unsigned long x;
Mark Dickinsonea835e72009-04-19 20:40:33 +0000150
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000151 v = get_pylong(v);
152 if (v == NULL)
153 return -1;
154 assert(PyLong_Check(v));
155 x = PyLong_AsUnsignedLong(v);
156 Py_DECREF(v);
157 if (x == (unsigned long)-1 && PyErr_Occurred()) {
158 if (PyErr_ExceptionMatches(PyExc_OverflowError))
159 PyErr_SetString(StructError,
160 "argument out of range");
161 return -1;
162 }
163 *p = x;
164 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000165}
166
167#ifdef HAVE_LONG_LONG
168
169/* Same, but handling native long long. */
170
171static int
172get_longlong(PyObject *v, PY_LONG_LONG *p)
173{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000174 PY_LONG_LONG x;
Mark Dickinson055a3fb2010-04-03 15:26:31 +0000175
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000176 v = get_pylong(v);
177 if (v == NULL)
178 return -1;
179 assert(PyLong_Check(v));
180 x = PyLong_AsLongLong(v);
181 Py_DECREF(v);
182 if (x == (PY_LONG_LONG)-1 && PyErr_Occurred()) {
183 if (PyErr_ExceptionMatches(PyExc_OverflowError))
184 PyErr_SetString(StructError,
185 "argument out of range");
186 return -1;
187 }
188 *p = x;
189 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000190}
191
192/* Same, but handling native unsigned long long. */
193
194static int
195get_ulonglong(PyObject *v, unsigned PY_LONG_LONG *p)
196{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000197 unsigned PY_LONG_LONG x;
Mark Dickinson055a3fb2010-04-03 15:26:31 +0000198
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000199 v = get_pylong(v);
200 if (v == NULL)
201 return -1;
202 assert(PyLong_Check(v));
203 x = PyLong_AsUnsignedLongLong(v);
204 Py_DECREF(v);
205 if (x == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred()) {
206 if (PyErr_ExceptionMatches(PyExc_OverflowError))
207 PyErr_SetString(StructError,
208 "argument out of range");
209 return -1;
210 }
211 *p = x;
212 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000213}
214
215#endif
216
Antoine Pitrou45d9c912011-10-06 15:27:40 +0200217/* Same, but handling Py_ssize_t */
218
219static int
220get_ssize_t(PyObject *v, Py_ssize_t *p)
221{
222 Py_ssize_t x;
223
224 v = get_pylong(v);
225 if (v == NULL)
226 return -1;
227 assert(PyLong_Check(v));
228 x = PyLong_AsSsize_t(v);
229 Py_DECREF(v);
230 if (x == (Py_ssize_t)-1 && PyErr_Occurred()) {
231 if (PyErr_ExceptionMatches(PyExc_OverflowError))
232 PyErr_SetString(StructError,
233 "argument out of range");
234 return -1;
235 }
236 *p = x;
237 return 0;
238}
239
240/* Same, but handling size_t */
241
242static int
243get_size_t(PyObject *v, size_t *p)
244{
245 size_t x;
246
247 v = get_pylong(v);
248 if (v == NULL)
249 return -1;
250 assert(PyLong_Check(v));
251 x = PyLong_AsSize_t(v);
252 Py_DECREF(v);
253 if (x == (size_t)-1 && PyErr_Occurred()) {
254 if (PyErr_ExceptionMatches(PyExc_OverflowError))
255 PyErr_SetString(StructError,
256 "argument out of range");
257 return -1;
258 }
259 *p = x;
260 return 0;
261}
262
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000263
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000264#define RANGE_ERROR(x, f, flag, mask) return _range_error(f, flag)
265
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000266
Thomas Wouters477c8d52006-05-27 19:21:47 +0000267/* Floating point helpers */
268
269static PyObject *
270unpack_float(const char *p, /* start of 4-byte string */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000271 int le) /* true for little-endian, false for big-endian */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000272{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000273 double x;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000275 x = _PyFloat_Unpack4((unsigned char *)p, le);
276 if (x == -1.0 && PyErr_Occurred())
277 return NULL;
278 return PyFloat_FromDouble(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000279}
280
281static PyObject *
282unpack_double(const char *p, /* start of 8-byte string */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000283 int le) /* true for little-endian, false for big-endian */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000284{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000285 double x;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000287 x = _PyFloat_Unpack8((unsigned char *)p, le);
288 if (x == -1.0 && PyErr_Occurred())
289 return NULL;
290 return PyFloat_FromDouble(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000291}
292
293/* Helper to format the range error exceptions */
294static int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000295_range_error(const formatdef *f, int is_unsigned)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000296{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000297 /* ulargest is the largest unsigned value with f->size bytes.
298 * Note that the simpler:
299 * ((size_t)1 << (f->size * 8)) - 1
300 * doesn't work when f->size == sizeof(size_t) because C doesn't
301 * define what happens when a left shift count is >= the number of
302 * bits in the integer being shifted; e.g., on some boxes it doesn't
303 * shift at all when they're equal.
304 */
305 const size_t ulargest = (size_t)-1 >> ((SIZEOF_SIZE_T - f->size)*8);
306 assert(f->size >= 1 && f->size <= SIZEOF_SIZE_T);
307 if (is_unsigned)
308 PyErr_Format(StructError,
309 "'%c' format requires 0 <= number <= %zu",
310 f->format,
311 ulargest);
312 else {
313 const Py_ssize_t largest = (Py_ssize_t)(ulargest >> 1);
314 PyErr_Format(StructError,
315 "'%c' format requires %zd <= number <= %zd",
316 f->format,
317 ~ largest,
318 largest);
319 }
Mark Dickinsonae681df2009-03-21 10:26:31 +0000320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000321 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000322}
323
324
325
326/* A large number of small routines follow, with names of the form
327
328 [bln][up]_TYPE
329
330 [bln] distiguishes among big-endian, little-endian and native.
331 [pu] distiguishes between pack (to struct) and unpack (from struct).
332 TYPE is one of char, byte, ubyte, etc.
333*/
334
335/* Native mode routines. ****************************************************/
336/* NOTE:
337 In all n[up]_<type> routines handling types larger than 1 byte, there is
338 *no* guarantee that the p pointer is properly aligned for each type,
339 therefore memcpy is called. An intermediate variable is used to
340 compensate for big-endian architectures.
341 Normally both the intermediate variable and the memcpy call will be
342 skipped by C optimisation in little-endian architectures (gcc >= 2.91
343 does this). */
344
345static PyObject *
346nu_char(const char *p, const formatdef *f)
347{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000348 return PyBytes_FromStringAndSize(p, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000349}
350
351static PyObject *
352nu_byte(const char *p, const formatdef *f)
353{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000354 return PyLong_FromLong((long) *(signed char *)p);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000355}
356
357static PyObject *
358nu_ubyte(const char *p, const formatdef *f)
359{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000360 return PyLong_FromLong((long) *(unsigned char *)p);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000361}
362
363static PyObject *
364nu_short(const char *p, const formatdef *f)
365{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000366 short x;
367 memcpy((char *)&x, p, sizeof x);
368 return PyLong_FromLong((long)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000369}
370
371static PyObject *
372nu_ushort(const char *p, const formatdef *f)
373{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000374 unsigned short x;
375 memcpy((char *)&x, p, sizeof x);
376 return PyLong_FromLong((long)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000377}
378
379static PyObject *
380nu_int(const char *p, const formatdef *f)
381{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000382 int x;
383 memcpy((char *)&x, p, sizeof x);
384 return PyLong_FromLong((long)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000385}
386
387static PyObject *
388nu_uint(const char *p, const formatdef *f)
389{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000390 unsigned int x;
391 memcpy((char *)&x, p, sizeof x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000392#if (SIZEOF_LONG > SIZEOF_INT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000393 return PyLong_FromLong((long)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000394#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000395 if (x <= ((unsigned int)LONG_MAX))
396 return PyLong_FromLong((long)x);
397 return PyLong_FromUnsignedLong((unsigned long)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000398#endif
399}
400
401static PyObject *
402nu_long(const char *p, const formatdef *f)
403{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000404 long x;
405 memcpy((char *)&x, p, sizeof x);
406 return PyLong_FromLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000407}
408
409static PyObject *
410nu_ulong(const char *p, const formatdef *f)
411{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000412 unsigned long x;
413 memcpy((char *)&x, p, sizeof x);
414 if (x <= LONG_MAX)
415 return PyLong_FromLong((long)x);
416 return PyLong_FromUnsignedLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000417}
418
Antoine Pitrou45d9c912011-10-06 15:27:40 +0200419static PyObject *
420nu_ssize_t(const char *p, const formatdef *f)
421{
422 Py_ssize_t x;
423 memcpy((char *)&x, p, sizeof x);
424 return PyLong_FromSsize_t(x);
425}
426
427static PyObject *
428nu_size_t(const char *p, const formatdef *f)
429{
430 size_t x;
431 memcpy((char *)&x, p, sizeof x);
432 return PyLong_FromSize_t(x);
433}
434
435
Thomas Wouters477c8d52006-05-27 19:21:47 +0000436/* Native mode doesn't support q or Q unless the platform C supports
437 long long (or, on Windows, __int64). */
438
439#ifdef HAVE_LONG_LONG
440
441static PyObject *
442nu_longlong(const char *p, const formatdef *f)
443{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000444 PY_LONG_LONG x;
445 memcpy((char *)&x, p, sizeof x);
446 if (x >= LONG_MIN && x <= LONG_MAX)
447 return PyLong_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long));
448 return PyLong_FromLongLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000449}
450
451static PyObject *
452nu_ulonglong(const char *p, const formatdef *f)
453{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000454 unsigned PY_LONG_LONG x;
455 memcpy((char *)&x, p, sizeof x);
456 if (x <= LONG_MAX)
457 return PyLong_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long));
458 return PyLong_FromUnsignedLongLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000459}
460
461#endif
462
463static PyObject *
Thomas Woutersb2137042007-02-01 18:02:27 +0000464nu_bool(const char *p, const formatdef *f)
465{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000466 BOOL_TYPE x;
467 memcpy((char *)&x, p, sizeof x);
468 return PyBool_FromLong(x != 0);
Thomas Woutersb2137042007-02-01 18:02:27 +0000469}
470
471
472static PyObject *
Thomas Wouters477c8d52006-05-27 19:21:47 +0000473nu_float(const char *p, const formatdef *f)
474{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000475 float x;
476 memcpy((char *)&x, p, sizeof x);
477 return PyFloat_FromDouble((double)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000478}
479
480static PyObject *
481nu_double(const char *p, const formatdef *f)
482{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 double x;
484 memcpy((char *)&x, p, sizeof x);
485 return PyFloat_FromDouble(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000486}
487
488static PyObject *
489nu_void_p(const char *p, const formatdef *f)
490{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000491 void *x;
492 memcpy((char *)&x, p, sizeof x);
493 return PyLong_FromVoidPtr(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000494}
495
496static int
497np_byte(char *p, PyObject *v, const formatdef *f)
498{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000499 long x;
500 if (get_long(v, &x) < 0)
501 return -1;
502 if (x < -128 || x > 127){
503 PyErr_SetString(StructError,
504 "byte format requires -128 <= number <= 127");
505 return -1;
506 }
507 *p = (char)x;
508 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000509}
510
511static int
512np_ubyte(char *p, PyObject *v, const formatdef *f)
513{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000514 long x;
515 if (get_long(v, &x) < 0)
516 return -1;
517 if (x < 0 || x > 255){
518 PyErr_SetString(StructError,
519 "ubyte format requires 0 <= number <= 255");
520 return -1;
521 }
522 *p = (char)x;
523 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000524}
525
526static int
527np_char(char *p, PyObject *v, const formatdef *f)
528{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000529 if (!PyBytes_Check(v) || PyBytes_Size(v) != 1) {
530 PyErr_SetString(StructError,
Victor Stinnerda9ec992010-12-28 13:26:42 +0000531 "char format requires a bytes object of length 1");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532 return -1;
533 }
534 *p = *PyBytes_AsString(v);
535 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000536}
537
538static int
539np_short(char *p, PyObject *v, const formatdef *f)
540{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000541 long x;
542 short y;
543 if (get_long(v, &x) < 0)
544 return -1;
545 if (x < SHRT_MIN || x > SHRT_MAX){
546 PyErr_SetString(StructError,
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200547 "short format requires " Py_STRINGIFY(SHRT_MIN)
548 " <= number <= " Py_STRINGIFY(SHRT_MAX));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000549 return -1;
550 }
551 y = (short)x;
552 memcpy(p, (char *)&y, sizeof y);
553 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000554}
555
556static int
557np_ushort(char *p, PyObject *v, const formatdef *f)
558{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 long x;
560 unsigned short y;
561 if (get_long(v, &x) < 0)
562 return -1;
563 if (x < 0 || x > USHRT_MAX){
564 PyErr_SetString(StructError,
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200565 "ushort format requires 0 <= number <= "
566 Py_STRINGIFY(USHRT_MAX));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000567 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;
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001266 Py_ssize_t size, len, ncodes, 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;
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001275 ncodes = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001276 while ((c = *s++) != '\0') {
Antoine Pitrou4de74572013-02-09 23:11:27 +01001277 if (Py_ISSPACE(Py_CHARMASK(c)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001278 continue;
1279 if ('0' <= c && c <= '9') {
1280 num = c - '0';
1281 while ('0' <= (c = *s++) && c <= '9') {
Mark Dickinsonab4096f2010-06-11 16:56:34 +00001282 /* overflow-safe version of
1283 if (num*10 + (c - '0') > PY_SSIZE_T_MAX) { ... } */
1284 if (num >= PY_SSIZE_T_MAX / 10 && (
1285 num > PY_SSIZE_T_MAX / 10 ||
Mark Dickinsonb72e6862010-06-11 19:50:30 +00001286 (c - '0') > PY_SSIZE_T_MAX % 10))
1287 goto overflow;
Mark Dickinsonab4096f2010-06-11 16:56:34 +00001288 num = num*10 + (c - '0');
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001289 }
Alexander Belopolsky177e8532010-06-11 16:04:59 +00001290 if (c == '\0') {
1291 PyErr_SetString(StructError,
1292 "repeat count given without format specifier");
1293 return -1;
1294 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001295 }
1296 else
1297 num = 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001299 e = getentry(c, f);
1300 if (e == NULL)
1301 return -1;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001303 switch (c) {
1304 case 's': /* fall through */
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001305 case 'p': len++; ncodes++; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001306 case 'x': break;
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001307 default: len += num; if (num) ncodes++; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001308 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001310 itemsize = e->size;
1311 size = align(size, c, e);
Mark Dickinsonb72e6862010-06-11 19:50:30 +00001312 if (size == -1)
1313 goto overflow;
1314
1315 /* if (size + num * itemsize > PY_SSIZE_T_MAX) { ... } */
1316 if (num > (PY_SSIZE_T_MAX - size) / itemsize)
1317 goto overflow;
1318 size += num * itemsize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001319 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001321 /* check for overflow */
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001322 if ((ncodes + 1) > (PY_SSIZE_T_MAX / sizeof(formatcode))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001323 PyErr_NoMemory();
1324 return -1;
1325 }
Amaury Forgeot d'Arc35c86582008-06-17 21:11:29 +00001326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001327 self->s_size = size;
1328 self->s_len = len;
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001329 codes = PyMem_MALLOC((ncodes + 1) * sizeof(formatcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001330 if (codes == NULL) {
1331 PyErr_NoMemory();
1332 return -1;
1333 }
Mark Dickinsoncf28b952010-07-29 21:41:59 +00001334 /* Free any s_codes value left over from a previous initialization. */
1335 if (self->s_codes != NULL)
1336 PyMem_FREE(self->s_codes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001337 self->s_codes = codes;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001339 s = fmt;
1340 size = 0;
1341 while ((c = *s++) != '\0') {
Antoine Pitrou4de74572013-02-09 23:11:27 +01001342 if (Py_ISSPACE(Py_CHARMASK(c)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001343 continue;
1344 if ('0' <= c && c <= '9') {
1345 num = c - '0';
1346 while ('0' <= (c = *s++) && c <= '9')
1347 num = num*10 + (c - '0');
1348 if (c == '\0')
1349 break;
1350 }
1351 else
1352 num = 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001353
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001354 e = getentry(c, f);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001356 size = align(size, c, e);
1357 if (c == 's' || c == 'p') {
1358 codes->offset = size;
1359 codes->size = num;
1360 codes->fmtdef = e;
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001361 codes->repeat = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001362 codes++;
1363 size += num;
1364 } else if (c == 'x') {
1365 size += num;
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001366 } else if (num) {
1367 codes->offset = size;
1368 codes->size = e->size;
1369 codes->fmtdef = e;
1370 codes->repeat = num;
1371 codes++;
1372 size += e->size * num;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001373 }
1374 }
1375 codes->fmtdef = NULL;
1376 codes->offset = size;
1377 codes->size = 0;
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001378 codes->repeat = 0;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001380 return 0;
Mark Dickinsonb72e6862010-06-11 19:50:30 +00001381
1382 overflow:
1383 PyErr_SetString(StructError,
1384 "total struct size too long");
1385 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001386}
1387
1388static PyObject *
1389s_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1390{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001391 PyObject *self;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001393 assert(type != NULL && type->tp_alloc != NULL);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001395 self = type->tp_alloc(type, 0);
1396 if (self != NULL) {
1397 PyStructObject *s = (PyStructObject*)self;
1398 Py_INCREF(Py_None);
1399 s->s_format = Py_None;
1400 s->s_codes = NULL;
1401 s->s_size = -1;
1402 s->s_len = -1;
1403 }
1404 return self;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001405}
1406
1407static int
1408s_init(PyObject *self, PyObject *args, PyObject *kwds)
1409{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 PyStructObject *soself = (PyStructObject *)self;
1411 PyObject *o_format = NULL;
1412 int ret = 0;
1413 static char *kwlist[] = {"format", 0};
Thomas Wouters477c8d52006-05-27 19:21:47 +00001414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001415 assert(PyStruct_Check(self));
Thomas Wouters477c8d52006-05-27 19:21:47 +00001416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001417 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:Struct", kwlist,
1418 &o_format))
1419 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001420
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001421 if (PyUnicode_Check(o_format)) {
1422 o_format = PyUnicode_AsASCIIString(o_format);
1423 if (o_format == NULL)
1424 return -1;
1425 }
1426 /* XXX support buffer interface, too */
1427 else {
1428 Py_INCREF(o_format);
1429 }
Christian Heimesa34706f2008-01-04 03:06:10 +00001430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001431 if (!PyBytes_Check(o_format)) {
1432 Py_DECREF(o_format);
1433 PyErr_Format(PyExc_TypeError,
Victor Stinnerda9ec992010-12-28 13:26:42 +00001434 "Struct() argument 1 must be a bytes object, not %.200s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001435 Py_TYPE(o_format)->tp_name);
1436 return -1;
1437 }
Christian Heimesa34706f2008-01-04 03:06:10 +00001438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001439 Py_CLEAR(soself->s_format);
1440 soself->s_format = o_format;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001442 ret = prepare_s(soself);
1443 return ret;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001444}
1445
1446static void
1447s_dealloc(PyStructObject *s)
1448{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001449 if (s->weakreflist != NULL)
1450 PyObject_ClearWeakRefs((PyObject *)s);
1451 if (s->s_codes != NULL) {
1452 PyMem_FREE(s->s_codes);
1453 }
1454 Py_XDECREF(s->s_format);
1455 Py_TYPE(s)->tp_free((PyObject *)s);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001456}
1457
1458static PyObject *
1459s_unpack_internal(PyStructObject *soself, char *startfrom) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001460 formatcode *code;
1461 Py_ssize_t i = 0;
1462 PyObject *result = PyTuple_New(soself->s_len);
1463 if (result == NULL)
1464 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001466 for (code = soself->s_codes; code->fmtdef != NULL; code++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001467 const formatdef *e = code->fmtdef;
1468 const char *res = startfrom + code->offset;
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001469 Py_ssize_t j = code->repeat;
1470 while (j--) {
1471 PyObject *v;
1472 if (e->format == 's') {
1473 v = PyBytes_FromStringAndSize(res, code->size);
1474 } else if (e->format == 'p') {
1475 Py_ssize_t n = *(unsigned char*)res;
1476 if (n >= code->size)
1477 n = code->size - 1;
1478 v = PyBytes_FromStringAndSize(res + 1, n);
1479 } else {
1480 v = e->unpack(res, e);
1481 }
1482 if (v == NULL)
1483 goto fail;
1484 PyTuple_SET_ITEM(result, i++, v);
1485 res += code->size;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001486 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001487 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001489 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001490fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001491 Py_DECREF(result);
1492 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001493}
1494
1495
1496PyDoc_STRVAR(s_unpack__doc__,
Guido van Rossum913dd0b2007-04-13 03:33:53 +00001497"S.unpack(buffer) -> (v1, v2, ...)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00001498\n\
Mark Dickinsonaacfa952010-06-12 15:43:45 +00001499Return a tuple containing values unpacked according to the format\n\
1500string S.format. Requires len(buffer) == S.size. See help(struct)\n\
1501for more on format strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001502
1503static PyObject *
Guido van Rossum98297ee2007-11-06 21:34:58 +00001504s_unpack(PyObject *self, PyObject *input)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001505{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001506 Py_buffer vbuf;
1507 PyObject *result;
1508 PyStructObject *soself = (PyStructObject *)self;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001510 assert(PyStruct_Check(self));
1511 assert(soself->s_codes != NULL);
1512 if (PyObject_GetBuffer(input, &vbuf, PyBUF_SIMPLE) < 0)
1513 return NULL;
1514 if (vbuf.len != soself->s_size) {
1515 PyErr_Format(StructError,
Victor Stinnerda9ec992010-12-28 13:26:42 +00001516 "unpack requires a bytes object of length %zd",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001517 soself->s_size);
1518 PyBuffer_Release(&vbuf);
1519 return NULL;
1520 }
1521 result = s_unpack_internal(soself, vbuf.buf);
1522 PyBuffer_Release(&vbuf);
1523 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001524}
1525
1526PyDoc_STRVAR(s_unpack_from__doc__,
Mark Dickinsonc6f13962010-06-13 09:17:13 +00001527"S.unpack_from(buffer, offset=0) -> (v1, v2, ...)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00001528\n\
Mark Dickinsonaacfa952010-06-12 15:43:45 +00001529Return a tuple containing values unpacked according to the format\n\
1530string S.format. Requires len(buffer[offset:]) >= S.size. See\n\
1531help(struct) for more on format strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001532
1533static PyObject *
1534s_unpack_from(PyObject *self, PyObject *args, PyObject *kwds)
1535{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001536 static char *kwlist[] = {"buffer", "offset", 0};
Guido van Rossum98297ee2007-11-06 21:34:58 +00001537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001538 PyObject *input;
1539 Py_ssize_t offset = 0;
1540 Py_buffer vbuf;
1541 PyObject *result;
1542 PyStructObject *soself = (PyStructObject *)self;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001543
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001544 assert(PyStruct_Check(self));
1545 assert(soself->s_codes != NULL);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001547 if (!PyArg_ParseTupleAndKeywords(args, kwds,
1548 "O|n:unpack_from", kwlist,
1549 &input, &offset))
1550 return NULL;
1551 if (PyObject_GetBuffer(input, &vbuf, PyBUF_SIMPLE) < 0)
1552 return NULL;
1553 if (offset < 0)
1554 offset += vbuf.len;
1555 if (offset < 0 || vbuf.len - offset < soself->s_size) {
1556 PyErr_Format(StructError,
1557 "unpack_from requires a buffer of at least %zd bytes",
1558 soself->s_size);
1559 PyBuffer_Release(&vbuf);
1560 return NULL;
1561 }
1562 result = s_unpack_internal(soself, (char*)vbuf.buf + offset);
1563 PyBuffer_Release(&vbuf);
1564 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001565}
1566
1567
Antoine Pitrou9f146812013-04-27 00:20:04 +02001568/* Unpack iterator type */
1569
1570typedef struct {
1571 PyObject_HEAD
1572 PyStructObject *so;
1573 Py_buffer buf;
1574 Py_ssize_t index;
1575} unpackiterobject;
1576
1577static void
1578unpackiter_dealloc(unpackiterobject *self)
1579{
1580 Py_XDECREF(self->so);
1581 PyBuffer_Release(&self->buf);
1582 PyObject_GC_Del(self);
1583}
1584
1585static int
1586unpackiter_traverse(unpackiterobject *self, visitproc visit, void *arg)
1587{
1588 Py_VISIT(self->so);
1589 Py_VISIT(self->buf.obj);
1590 return 0;
1591}
1592
1593static PyObject *
1594unpackiter_len(unpackiterobject *self)
1595{
1596 Py_ssize_t len;
1597 if (self->so == NULL)
1598 len = 0;
1599 else
1600 len = (self->buf.len - self->index) / self->so->s_size;
1601 return PyLong_FromSsize_t(len);
1602}
1603
1604static PyMethodDef unpackiter_methods[] = {
1605 {"__length_hint__", (PyCFunction) unpackiter_len, METH_NOARGS, NULL},
1606 {NULL, NULL} /* sentinel */
1607};
1608
1609static PyObject *
1610unpackiter_iternext(unpackiterobject *self)
1611{
1612 PyObject *result;
1613 if (self->so == NULL)
1614 return NULL;
1615 if (self->index >= self->buf.len) {
1616 /* Iterator exhausted */
1617 Py_CLEAR(self->so);
1618 PyBuffer_Release(&self->buf);
1619 return NULL;
1620 }
1621 assert(self->index + self->so->s_size <= self->buf.len);
1622 result = s_unpack_internal(self->so,
1623 (char*) self->buf.buf + self->index);
1624 self->index += self->so->s_size;
1625 return result;
1626}
1627
doko@ubuntu.com46c5deb2013-11-23 16:07:55 +01001628static PyTypeObject unpackiter_type = {
Antoine Pitrou9f146812013-04-27 00:20:04 +02001629 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1630 "unpack_iterator", /* tp_name */
1631 sizeof(unpackiterobject), /* tp_basicsize */
1632 0, /* tp_itemsize */
1633 (destructor)unpackiter_dealloc, /* tp_dealloc */
1634 0, /* tp_print */
1635 0, /* tp_getattr */
1636 0, /* tp_setattr */
1637 0, /* tp_reserved */
1638 0, /* tp_repr */
1639 0, /* tp_as_number */
1640 0, /* tp_as_sequence */
1641 0, /* tp_as_mapping */
1642 0, /* tp_hash */
1643 0, /* tp_call */
1644 0, /* tp_str */
1645 PyObject_GenericGetAttr, /* tp_getattro */
1646 0, /* tp_setattro */
1647 0, /* tp_as_buffer */
1648 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
1649 0, /* tp_doc */
1650 (traverseproc)unpackiter_traverse, /* tp_traverse */
1651 0, /* tp_clear */
1652 0, /* tp_richcompare */
1653 0, /* tp_weaklistoffset */
1654 PyObject_SelfIter, /* tp_iter */
1655 (iternextfunc)unpackiter_iternext, /* tp_iternext */
1656 unpackiter_methods /* tp_methods */
1657};
1658
1659PyDoc_STRVAR(s_iter_unpack__doc__,
1660"S.iter_unpack(buffer) -> iterator(v1, v2, ...)\n\
1661\n\
1662Return an iterator yielding tuples unpacked from the given bytes\n\
1663source, like a repeated invocation of unpack_from(). Requires\n\
1664that the bytes length be a multiple of the struct size.");
1665
1666static PyObject *
1667s_iter_unpack(PyObject *_so, PyObject *input)
1668{
1669 PyStructObject *so = (PyStructObject *) _so;
1670 unpackiterobject *self;
1671
1672 assert(PyStruct_Check(_so));
1673 assert(so->s_codes != NULL);
1674
1675 if (so->s_size == 0) {
1676 PyErr_Format(StructError,
1677 "cannot iteratively unpack with a struct of length 0");
1678 return NULL;
1679 }
1680
1681 self = (unpackiterobject *) PyType_GenericAlloc(&unpackiter_type, 0);
1682 if (self == NULL)
1683 return NULL;
1684
1685 if (PyObject_GetBuffer(input, &self->buf, PyBUF_SIMPLE) < 0) {
1686 Py_DECREF(self);
1687 return NULL;
1688 }
1689 if (self->buf.len % so->s_size != 0) {
1690 PyErr_Format(StructError,
1691 "iterative unpacking requires a bytes length "
1692 "multiple of %zd",
1693 so->s_size);
1694 Py_DECREF(self);
1695 return NULL;
1696 }
1697 Py_INCREF(so);
1698 self->so = so;
1699 self->index = 0;
1700 return (PyObject *) self;
1701}
1702
1703
Thomas Wouters477c8d52006-05-27 19:21:47 +00001704/*
1705 * Guts of the pack function.
1706 *
1707 * Takes a struct object, a tuple of arguments, and offset in that tuple of
1708 * argument for where to start processing the arguments for packing, and a
1709 * character buffer for writing the packed string. The caller must insure
1710 * that the buffer may contain the required length for packing the arguments.
1711 * 0 is returned on success, 1 is returned if there is an error.
1712 *
1713 */
1714static int
1715s_pack_internal(PyStructObject *soself, PyObject *args, int offset, char* buf)
1716{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001717 formatcode *code;
1718 /* XXX(nnorwitz): why does i need to be a local? can we use
1719 the offset parameter or do we need the wider width? */
1720 Py_ssize_t i;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001721
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001722 memset(buf, '\0', soself->s_size);
1723 i = offset;
1724 for (code = soself->s_codes; code->fmtdef != NULL; code++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001725 const formatdef *e = code->fmtdef;
1726 char *res = buf + code->offset;
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001727 Py_ssize_t j = code->repeat;
1728 while (j--) {
1729 PyObject *v = PyTuple_GET_ITEM(args, i++);
1730 if (e->format == 's') {
1731 Py_ssize_t n;
1732 int isstring;
1733 void *p;
1734 isstring = PyBytes_Check(v);
1735 if (!isstring && !PyByteArray_Check(v)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001736 PyErr_SetString(StructError,
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001737 "argument for 's' must be a bytes object");
1738 return -1;
1739 }
1740 if (isstring) {
1741 n = PyBytes_GET_SIZE(v);
1742 p = PyBytes_AS_STRING(v);
1743 }
1744 else {
1745 n = PyByteArray_GET_SIZE(v);
1746 p = PyByteArray_AS_STRING(v);
1747 }
1748 if (n > code->size)
1749 n = code->size;
1750 if (n > 0)
1751 memcpy(res, p, n);
1752 } else if (e->format == 'p') {
1753 Py_ssize_t n;
1754 int isstring;
1755 void *p;
1756 isstring = PyBytes_Check(v);
1757 if (!isstring && !PyByteArray_Check(v)) {
1758 PyErr_SetString(StructError,
1759 "argument for 'p' must be a bytes object");
1760 return -1;
1761 }
1762 if (isstring) {
1763 n = PyBytes_GET_SIZE(v);
1764 p = PyBytes_AS_STRING(v);
1765 }
1766 else {
1767 n = PyByteArray_GET_SIZE(v);
1768 p = PyByteArray_AS_STRING(v);
1769 }
1770 if (n > (code->size - 1))
1771 n = code->size - 1;
1772 if (n > 0)
1773 memcpy(res + 1, p, n);
1774 if (n > 255)
1775 n = 255;
1776 *res = Py_SAFE_DOWNCAST(n, Py_ssize_t, unsigned char);
1777 } else {
1778 if (e->pack(res, v, e) < 0) {
1779 if (PyLong_Check(v) && PyErr_ExceptionMatches(PyExc_OverflowError))
1780 PyErr_SetString(StructError,
Serhiy Storchaka46e1ce22013-08-27 20:17:03 +03001781 "int too large to convert");
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001782 return -1;
1783 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001784 }
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001785 res += code->size;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001786 }
1787 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001789 /* Success */
1790 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001791}
1792
1793
1794PyDoc_STRVAR(s_pack__doc__,
Benjamin Peterson4ae19462008-07-31 15:03:40 +00001795"S.pack(v1, v2, ...) -> bytes\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00001796\n\
Mark Dickinsonaacfa952010-06-12 15:43:45 +00001797Return a bytes object containing values v1, v2, ... packed according\n\
1798to the format string S.format. See help(struct) for more on format\n\
1799strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001800
1801static PyObject *
1802s_pack(PyObject *self, PyObject *args)
1803{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001804 PyStructObject *soself;
1805 PyObject *result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001807 /* Validate arguments. */
1808 soself = (PyStructObject *)self;
1809 assert(PyStruct_Check(self));
1810 assert(soself->s_codes != NULL);
1811 if (PyTuple_GET_SIZE(args) != soself->s_len)
1812 {
1813 PyErr_Format(StructError,
Petri Lehtinen92c28ca2012-10-29 21:16:57 +02001814 "pack expected %zd items for packing (got %zd)", soself->s_len, PyTuple_GET_SIZE(args));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001815 return NULL;
1816 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001817
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001818 /* Allocate a new string */
1819 result = PyBytes_FromStringAndSize((char *)NULL, soself->s_size);
1820 if (result == NULL)
1821 return NULL;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001823 /* Call the guts */
1824 if ( s_pack_internal(soself, args, 0, PyBytes_AS_STRING(result)) != 0 ) {
1825 Py_DECREF(result);
1826 return NULL;
1827 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001828
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001829 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001830}
1831
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001832PyDoc_STRVAR(s_pack_into__doc__,
1833"S.pack_into(buffer, offset, v1, v2, ...)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00001834\n\
Mark Dickinsonaacfa952010-06-12 15:43:45 +00001835Pack the values v1, v2, ... according to the format string S.format\n\
1836and write the packed bytes into the writable buffer buf starting at\n\
Mark Dickinsonfdb99f12010-06-12 16:30:53 +00001837offset. Note that the offset is a required argument. See\n\
Mark Dickinsonaacfa952010-06-12 15:43:45 +00001838help(struct) for more on format strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001839
1840static PyObject *
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001841s_pack_into(PyObject *self, PyObject *args)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001842{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001843 PyStructObject *soself;
1844 char *buffer;
1845 Py_ssize_t buffer_len, offset;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001846
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001847 /* Validate arguments. +1 is for the first arg as buffer. */
1848 soself = (PyStructObject *)self;
1849 assert(PyStruct_Check(self));
1850 assert(soself->s_codes != NULL);
1851 if (PyTuple_GET_SIZE(args) != (soself->s_len + 2))
1852 {
Petri Lehtinen92c28ca2012-10-29 21:16:57 +02001853 if (PyTuple_GET_SIZE(args) == 0) {
1854 PyErr_Format(StructError,
1855 "pack_into expected buffer argument");
1856 }
1857 else if (PyTuple_GET_SIZE(args) == 1) {
1858 PyErr_Format(StructError,
1859 "pack_into expected offset argument");
1860 }
1861 else {
1862 PyErr_Format(StructError,
1863 "pack_into expected %zd items for packing (got %zd)",
1864 soself->s_len, (PyTuple_GET_SIZE(args) - 2));
1865 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001866 return NULL;
1867 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001868
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001869 /* Extract a writable memory buffer from the first argument */
1870 if ( PyObject_AsWriteBuffer(PyTuple_GET_ITEM(args, 0),
1871 (void**)&buffer, &buffer_len) == -1 ) {
1872 return NULL;
1873 }
1874 assert( buffer_len >= 0 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00001875
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001876 /* Extract the offset from the first argument */
1877 offset = PyNumber_AsSsize_t(PyTuple_GET_ITEM(args, 1), PyExc_IndexError);
1878 if (offset == -1 && PyErr_Occurred())
1879 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001880
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001881 /* Support negative offsets. */
1882 if (offset < 0)
1883 offset += buffer_len;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001885 /* Check boundaries */
1886 if (offset < 0 || (buffer_len - offset) < soself->s_size) {
1887 PyErr_Format(StructError,
1888 "pack_into requires a buffer of at least %zd bytes",
1889 soself->s_size);
1890 return NULL;
1891 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001893 /* Call the guts */
1894 if ( s_pack_internal(soself, args, 2, buffer + offset) != 0 ) {
1895 return NULL;
1896 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001898 Py_RETURN_NONE;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001899}
1900
1901static PyObject *
1902s_get_format(PyStructObject *self, void *unused)
1903{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001904 Py_INCREF(self->s_format);
1905 return self->s_format;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001906}
1907
1908static PyObject *
1909s_get_size(PyStructObject *self, void *unused)
1910{
Christian Heimes217cfd12007-12-02 14:31:20 +00001911 return PyLong_FromSsize_t(self->s_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001912}
1913
Meador Ingeb14d8c92012-07-23 10:01:29 -05001914PyDoc_STRVAR(s_sizeof__doc__,
1915"S.__sizeof__() -> size of S in memory, in bytes");
1916
1917static PyObject *
Meador Inge90bc2dbc2012-07-28 22:16:39 -05001918s_sizeof(PyStructObject *self, void *unused)
Meador Ingeb14d8c92012-07-23 10:01:29 -05001919{
1920 Py_ssize_t size;
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001921 formatcode *code;
Meador Ingeb14d8c92012-07-23 10:01:29 -05001922
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001923 size = sizeof(PyStructObject) + sizeof(formatcode);
1924 for (code = self->s_codes; code->fmtdef != NULL; code++)
1925 size += sizeof(formatcode);
Meador Ingeb14d8c92012-07-23 10:01:29 -05001926 return PyLong_FromSsize_t(size);
1927}
1928
Thomas Wouters477c8d52006-05-27 19:21:47 +00001929/* List of functions */
1930
1931static struct PyMethodDef s_methods[] = {
Antoine Pitrou9f146812013-04-27 00:20:04 +02001932 {"iter_unpack", s_iter_unpack, METH_O, s_iter_unpack__doc__},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001933 {"pack", s_pack, METH_VARARGS, s_pack__doc__},
1934 {"pack_into", s_pack_into, METH_VARARGS, s_pack_into__doc__},
1935 {"unpack", s_unpack, METH_O, s_unpack__doc__},
1936 {"unpack_from", (PyCFunction)s_unpack_from, METH_VARARGS|METH_KEYWORDS,
1937 s_unpack_from__doc__},
Meador Ingeb14d8c92012-07-23 10:01:29 -05001938 {"__sizeof__", (PyCFunction)s_sizeof, METH_NOARGS, s_sizeof__doc__},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001939 {NULL, NULL} /* sentinel */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001940};
1941
Victor Stinnerda9ec992010-12-28 13:26:42 +00001942PyDoc_STRVAR(s__doc__,
Alexander Belopolsky0bd003a2010-06-12 19:36:28 +00001943"Struct(fmt) --> compiled struct object\n"
1944"\n"
1945"Return a new Struct object which writes and reads binary data according to\n"
1946"the format string fmt. See help(struct) for more on format strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001947
1948#define OFF(x) offsetof(PyStructObject, x)
1949
1950static PyGetSetDef s_getsetlist[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001951 {"format", (getter)s_get_format, (setter)NULL, "struct format string", NULL},
1952 {"size", (getter)s_get_size, (setter)NULL, "struct size in bytes", NULL},
1953 {NULL} /* sentinel */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001954};
1955
1956static
1957PyTypeObject PyStructType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001958 PyVarObject_HEAD_INIT(NULL, 0)
1959 "Struct",
1960 sizeof(PyStructObject),
1961 0,
1962 (destructor)s_dealloc, /* tp_dealloc */
1963 0, /* tp_print */
1964 0, /* tp_getattr */
1965 0, /* tp_setattr */
1966 0, /* tp_reserved */
1967 0, /* tp_repr */
1968 0, /* tp_as_number */
1969 0, /* tp_as_sequence */
1970 0, /* tp_as_mapping */
1971 0, /* tp_hash */
1972 0, /* tp_call */
1973 0, /* tp_str */
1974 PyObject_GenericGetAttr, /* tp_getattro */
1975 PyObject_GenericSetAttr, /* tp_setattro */
1976 0, /* tp_as_buffer */
1977 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1978 s__doc__, /* tp_doc */
1979 0, /* tp_traverse */
1980 0, /* tp_clear */
1981 0, /* tp_richcompare */
1982 offsetof(PyStructObject, weakreflist), /* tp_weaklistoffset */
1983 0, /* tp_iter */
1984 0, /* tp_iternext */
1985 s_methods, /* tp_methods */
1986 NULL, /* tp_members */
1987 s_getsetlist, /* tp_getset */
1988 0, /* tp_base */
1989 0, /* tp_dict */
1990 0, /* tp_descr_get */
1991 0, /* tp_descr_set */
1992 0, /* tp_dictoffset */
1993 s_init, /* tp_init */
1994 PyType_GenericAlloc,/* tp_alloc */
1995 s_new, /* tp_new */
1996 PyObject_Del, /* tp_free */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001997};
1998
Christian Heimesa34706f2008-01-04 03:06:10 +00001999
2000/* ---- Standalone functions ---- */
2001
2002#define MAXCACHE 100
2003static PyObject *cache = NULL;
2004
2005static PyObject *
2006cache_struct(PyObject *fmt)
2007{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002008 PyObject * s_object;
Christian Heimesa34706f2008-01-04 03:06:10 +00002009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002010 if (cache == NULL) {
2011 cache = PyDict_New();
2012 if (cache == NULL)
2013 return NULL;
2014 }
Christian Heimesa34706f2008-01-04 03:06:10 +00002015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002016 s_object = PyDict_GetItem(cache, fmt);
2017 if (s_object != NULL) {
2018 Py_INCREF(s_object);
2019 return s_object;
2020 }
Christian Heimesa34706f2008-01-04 03:06:10 +00002021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002022 s_object = PyObject_CallFunctionObjArgs((PyObject *)(&PyStructType), fmt, NULL);
2023 if (s_object != NULL) {
2024 if (PyDict_Size(cache) >= MAXCACHE)
2025 PyDict_Clear(cache);
2026 /* Attempt to cache the result */
2027 if (PyDict_SetItem(cache, fmt, s_object) == -1)
2028 PyErr_Clear();
2029 }
2030 return s_object;
Christian Heimesa34706f2008-01-04 03:06:10 +00002031}
2032
2033PyDoc_STRVAR(clearcache_doc,
2034"Clear the internal cache.");
2035
2036static PyObject *
2037clearcache(PyObject *self)
2038{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002039 Py_CLEAR(cache);
2040 Py_RETURN_NONE;
Christian Heimesa34706f2008-01-04 03:06:10 +00002041}
2042
2043PyDoc_STRVAR(calcsize_doc,
Mark Dickinsonaacfa952010-06-12 15:43:45 +00002044"calcsize(fmt) -> integer\n\
2045\n\
2046Return size in bytes of the struct described by the format string fmt.");
Christian Heimesa34706f2008-01-04 03:06:10 +00002047
2048static PyObject *
2049calcsize(PyObject *self, PyObject *fmt)
2050{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002051 Py_ssize_t n;
2052 PyObject *s_object = cache_struct(fmt);
2053 if (s_object == NULL)
2054 return NULL;
2055 n = ((PyStructObject *)s_object)->s_size;
2056 Py_DECREF(s_object);
2057 return PyLong_FromSsize_t(n);
Christian Heimesa34706f2008-01-04 03:06:10 +00002058}
2059
2060PyDoc_STRVAR(pack_doc,
Mark Dickinsonaacfa952010-06-12 15:43:45 +00002061"pack(fmt, v1, v2, ...) -> bytes\n\
2062\n\
Mark Dickinsonfdb99f12010-06-12 16:30:53 +00002063Return a bytes object containing the values v1, v2, ... packed according\n\
2064to the format string fmt. See help(struct) for more on format strings.");
Christian Heimesa34706f2008-01-04 03:06:10 +00002065
2066static PyObject *
2067pack(PyObject *self, PyObject *args)
2068{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002069 PyObject *s_object, *fmt, *newargs, *result;
2070 Py_ssize_t n = PyTuple_GET_SIZE(args);
Christian Heimesa34706f2008-01-04 03:06:10 +00002071
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002072 if (n == 0) {
2073 PyErr_SetString(PyExc_TypeError, "missing format argument");
2074 return NULL;
2075 }
2076 fmt = PyTuple_GET_ITEM(args, 0);
2077 newargs = PyTuple_GetSlice(args, 1, n);
2078 if (newargs == NULL)
2079 return NULL;
Christian Heimesa34706f2008-01-04 03:06:10 +00002080
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002081 s_object = cache_struct(fmt);
2082 if (s_object == NULL) {
2083 Py_DECREF(newargs);
2084 return NULL;
2085 }
2086 result = s_pack(s_object, newargs);
2087 Py_DECREF(newargs);
2088 Py_DECREF(s_object);
2089 return result;
Christian Heimesa34706f2008-01-04 03:06:10 +00002090}
2091
2092PyDoc_STRVAR(pack_into_doc,
Mark Dickinsonaacfa952010-06-12 15:43:45 +00002093"pack_into(fmt, buffer, offset, v1, v2, ...)\n\
2094\n\
2095Pack the values v1, v2, ... according to the format string fmt and write\n\
2096the packed bytes into the writable buffer buf starting at offset. Note\n\
Mark Dickinsonfdb99f12010-06-12 16:30:53 +00002097that the offset is a required argument. See help(struct) for more\n\
Mark Dickinsonaacfa952010-06-12 15:43:45 +00002098on format strings.");
Christian Heimesa34706f2008-01-04 03:06:10 +00002099
2100static PyObject *
2101pack_into(PyObject *self, PyObject *args)
2102{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002103 PyObject *s_object, *fmt, *newargs, *result;
2104 Py_ssize_t n = PyTuple_GET_SIZE(args);
Christian Heimesa34706f2008-01-04 03:06:10 +00002105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002106 if (n == 0) {
2107 PyErr_SetString(PyExc_TypeError, "missing format argument");
2108 return NULL;
2109 }
2110 fmt = PyTuple_GET_ITEM(args, 0);
2111 newargs = PyTuple_GetSlice(args, 1, n);
2112 if (newargs == NULL)
2113 return NULL;
Christian Heimesa34706f2008-01-04 03:06:10 +00002114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002115 s_object = cache_struct(fmt);
2116 if (s_object == NULL) {
2117 Py_DECREF(newargs);
2118 return NULL;
2119 }
2120 result = s_pack_into(s_object, newargs);
2121 Py_DECREF(newargs);
2122 Py_DECREF(s_object);
2123 return result;
Christian Heimesa34706f2008-01-04 03:06:10 +00002124}
2125
2126PyDoc_STRVAR(unpack_doc,
Mark Dickinsonaacfa952010-06-12 15:43:45 +00002127"unpack(fmt, buffer) -> (v1, v2, ...)\n\
2128\n\
2129Return a tuple containing values unpacked according to the format string\n\
2130fmt. Requires len(buffer) == calcsize(fmt). See help(struct) for more\n\
2131on format strings.");
Christian Heimesa34706f2008-01-04 03:06:10 +00002132
2133static PyObject *
2134unpack(PyObject *self, PyObject *args)
2135{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002136 PyObject *s_object, *fmt, *inputstr, *result;
Christian Heimesa34706f2008-01-04 03:06:10 +00002137
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002138 if (!PyArg_UnpackTuple(args, "unpack", 2, 2, &fmt, &inputstr))
2139 return NULL;
Christian Heimesa34706f2008-01-04 03:06:10 +00002140
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 s_object = cache_struct(fmt);
2142 if (s_object == NULL)
2143 return NULL;
2144 result = s_unpack(s_object, inputstr);
2145 Py_DECREF(s_object);
2146 return result;
Christian Heimesa34706f2008-01-04 03:06:10 +00002147}
2148
2149PyDoc_STRVAR(unpack_from_doc,
Mark Dickinsonc6f13962010-06-13 09:17:13 +00002150"unpack_from(fmt, buffer, offset=0) -> (v1, v2, ...)\n\
Mark Dickinsonaacfa952010-06-12 15:43:45 +00002151\n\
2152Return a tuple containing values unpacked according to the format string\n\
2153fmt. Requires len(buffer[offset:]) >= calcsize(fmt). See help(struct)\n\
2154for more on format strings.");
Christian Heimesa34706f2008-01-04 03:06:10 +00002155
2156static PyObject *
2157unpack_from(PyObject *self, PyObject *args, PyObject *kwds)
2158{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002159 PyObject *s_object, *fmt, *newargs, *result;
2160 Py_ssize_t n = PyTuple_GET_SIZE(args);
Christian Heimesa34706f2008-01-04 03:06:10 +00002161
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002162 if (n == 0) {
2163 PyErr_SetString(PyExc_TypeError, "missing format argument");
2164 return NULL;
2165 }
2166 fmt = PyTuple_GET_ITEM(args, 0);
2167 newargs = PyTuple_GetSlice(args, 1, n);
2168 if (newargs == NULL)
2169 return NULL;
Christian Heimesa34706f2008-01-04 03:06:10 +00002170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002171 s_object = cache_struct(fmt);
2172 if (s_object == NULL) {
2173 Py_DECREF(newargs);
2174 return NULL;
2175 }
2176 result = s_unpack_from(s_object, newargs, kwds);
2177 Py_DECREF(newargs);
2178 Py_DECREF(s_object);
2179 return result;
Christian Heimesa34706f2008-01-04 03:06:10 +00002180}
2181
Antoine Pitrou9f146812013-04-27 00:20:04 +02002182PyDoc_STRVAR(iter_unpack_doc,
2183"iter_unpack(fmt, buffer) -> iterator(v1, v2, ...)\n\
2184\n\
2185Return an iterator yielding tuples unpacked from the given bytes\n\
2186source according to the format string, like a repeated invocation of\n\
2187unpack_from(). Requires that the bytes length be a multiple of the\n\
2188format struct size.");
2189
2190static PyObject *
2191iter_unpack(PyObject *self, PyObject *args)
2192{
2193 PyObject *s_object, *fmt, *input, *result;
2194
2195 if (!PyArg_ParseTuple(args, "OO:iter_unpack", &fmt, &input))
2196 return NULL;
2197
2198 s_object = cache_struct(fmt);
2199 if (s_object == NULL)
2200 return NULL;
2201 result = s_iter_unpack(s_object, input);
2202 Py_DECREF(s_object);
2203 return result;
2204}
2205
Christian Heimesa34706f2008-01-04 03:06:10 +00002206static struct PyMethodDef module_functions[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002207 {"_clearcache", (PyCFunction)clearcache, METH_NOARGS, clearcache_doc},
2208 {"calcsize", calcsize, METH_O, calcsize_doc},
Antoine Pitrou9f146812013-04-27 00:20:04 +02002209 {"iter_unpack", iter_unpack, METH_VARARGS, iter_unpack_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002210 {"pack", pack, METH_VARARGS, pack_doc},
2211 {"pack_into", pack_into, METH_VARARGS, pack_into_doc},
2212 {"unpack", unpack, METH_VARARGS, unpack_doc},
2213 {"unpack_from", (PyCFunction)unpack_from,
2214 METH_VARARGS|METH_KEYWORDS, unpack_from_doc},
2215 {NULL, NULL} /* sentinel */
Christian Heimesa34706f2008-01-04 03:06:10 +00002216};
2217
2218
Thomas Wouters477c8d52006-05-27 19:21:47 +00002219/* Module initialization */
2220
Christian Heimesa34706f2008-01-04 03:06:10 +00002221PyDoc_STRVAR(module_doc,
2222"Functions to convert between Python values and C structs.\n\
Benjamin Peterson4ae19462008-07-31 15:03:40 +00002223Python bytes objects are used to hold the data representing the C struct\n\
Mark Dickinson40714af2009-10-08 15:59:20 +00002224and also as format strings (explained below) to describe the layout of data\n\
2225in the C struct.\n\
Christian Heimesa34706f2008-01-04 03:06:10 +00002226\n\
2227The optional first format char indicates byte order, size and alignment:\n\
Mark Dickinson40714af2009-10-08 15:59:20 +00002228 @: native order, size & alignment (default)\n\
2229 =: native order, std. size & alignment\n\
2230 <: little-endian, std. size & alignment\n\
2231 >: big-endian, std. size & alignment\n\
2232 !: same as >\n\
Christian Heimesa34706f2008-01-04 03:06:10 +00002233\n\
2234The remaining chars indicate types of args and must match exactly;\n\
2235these can be preceded by a decimal repeat count:\n\
2236 x: pad byte (no data); c:char; b:signed byte; B:unsigned byte;\n\
Mark Dickinson40714af2009-10-08 15:59:20 +00002237 ?: _Bool (requires C99; if not available, char is used instead)\n\
Christian Heimesa34706f2008-01-04 03:06:10 +00002238 h:short; H:unsigned short; i:int; I:unsigned int;\n\
2239 l:long; L:unsigned long; f:float; d:double.\n\
2240Special cases (preceding decimal count indicates length):\n\
2241 s:string (array of char); p: pascal string (with count byte).\n\
Antoine Pitrou45d9c912011-10-06 15:27:40 +02002242Special cases (only available in native format):\n\
2243 n:ssize_t; N:size_t;\n\
Christian Heimesa34706f2008-01-04 03:06:10 +00002244 P:an integer type that is wide enough to hold a pointer.\n\
2245Special case (not in native mode unless 'long long' in platform C):\n\
2246 q:long long; Q:unsigned long long\n\
2247Whitespace between formats is ignored.\n\
2248\n\
2249The variable struct.error is an exception raised on errors.\n");
2250
Martin v. Löwis1a214512008-06-11 05:26:20 +00002251
2252static struct PyModuleDef _structmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002253 PyModuleDef_HEAD_INIT,
2254 "_struct",
2255 module_doc,
2256 -1,
2257 module_functions,
2258 NULL,
2259 NULL,
2260 NULL,
2261 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002262};
2263
Thomas Wouters477c8d52006-05-27 19:21:47 +00002264PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002265PyInit__struct(void)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002266{
Mark Dickinson06817852010-06-12 09:25:13 +00002267 PyObject *m;
Christian Heimesa34706f2008-01-04 03:06:10 +00002268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002269 m = PyModule_Create(&_structmodule);
2270 if (m == NULL)
2271 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002273 Py_TYPE(&PyStructType) = &PyType_Type;
2274 if (PyType_Ready(&PyStructType) < 0)
2275 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002277 /* Check endian and swap in faster functions */
2278 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002279 formatdef *native = native_table;
2280 formatdef *other, *ptr;
Christian Heimes743e0cd2012-10-17 23:52:17 +02002281#if PY_LITTLE_ENDIAN
2282 other = lilendian_table;
2283#else
2284 other = bigendian_table;
2285#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002286 /* Scan through the native table, find a matching
2287 entry in the endian table and swap in the
2288 native implementations whenever possible
2289 (64-bit platforms may not have "standard" sizes) */
2290 while (native->format != '\0' && other->format != '\0') {
2291 ptr = other;
2292 while (ptr->format != '\0') {
2293 if (ptr->format == native->format) {
2294 /* Match faster when formats are
2295 listed in the same order */
2296 if (ptr == other)
2297 other++;
2298 /* Only use the trick if the
2299 size matches */
2300 if (ptr->size != native->size)
2301 break;
2302 /* Skip float and double, could be
2303 "unknown" float format */
2304 if (ptr->format == 'd' || ptr->format == 'f')
2305 break;
2306 ptr->pack = native->pack;
2307 ptr->unpack = native->unpack;
2308 break;
2309 }
2310 ptr++;
2311 }
2312 native++;
2313 }
2314 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002316 /* Add some symbolic constants to the module */
2317 if (StructError == NULL) {
2318 StructError = PyErr_NewException("struct.error", NULL, NULL);
2319 if (StructError == NULL)
2320 return NULL;
2321 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002323 Py_INCREF(StructError);
2324 PyModule_AddObject(m, "error", StructError);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002326 Py_INCREF((PyObject*)&PyStructType);
2327 PyModule_AddObject(m, "Struct", (PyObject*)&PyStructType);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002329 return m;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002330}