blob: 2bcd492a290f5e6a0f090958967eb524dfbf8f9b [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 *
Mark Dickinson7c4e4092016-09-03 17:21:29 +0100270unpack_halffloat(const char *p, /* start of 2-byte string */
271 int le) /* true for little-endian, false for big-endian */
272{
273 double x;
274
275 x = _PyFloat_Unpack2((unsigned char *)p, le);
276 if (x == -1.0 && PyErr_Occurred()) {
277 return NULL;
278 }
279 return PyFloat_FromDouble(x);
280}
281
282static int
283pack_halffloat(char *p, /* start of 2-byte string */
284 PyObject *v, /* value to pack */
285 int le) /* true for little-endian, false for big-endian */
286{
287 double x = PyFloat_AsDouble(v);
288 if (x == -1.0 && PyErr_Occurred()) {
289 PyErr_SetString(StructError,
290 "required argument is not a float");
291 return -1;
292 }
293 return _PyFloat_Pack2(x, (unsigned char *)p, le);
294}
295
296static PyObject *
Thomas Wouters477c8d52006-05-27 19:21:47 +0000297unpack_float(const char *p, /* start of 4-byte string */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000298 int le) /* true for little-endian, false for big-endian */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000299{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000300 double x;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000302 x = _PyFloat_Unpack4((unsigned char *)p, le);
303 if (x == -1.0 && PyErr_Occurred())
304 return NULL;
305 return PyFloat_FromDouble(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000306}
307
308static PyObject *
309unpack_double(const char *p, /* start of 8-byte string */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000310 int le) /* true for little-endian, false for big-endian */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000311{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000312 double x;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000314 x = _PyFloat_Unpack8((unsigned char *)p, le);
315 if (x == -1.0 && PyErr_Occurred())
316 return NULL;
317 return PyFloat_FromDouble(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000318}
319
320/* Helper to format the range error exceptions */
321static int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000322_range_error(const formatdef *f, int is_unsigned)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000323{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000324 /* ulargest is the largest unsigned value with f->size bytes.
325 * Note that the simpler:
326 * ((size_t)1 << (f->size * 8)) - 1
327 * doesn't work when f->size == sizeof(size_t) because C doesn't
328 * define what happens when a left shift count is >= the number of
329 * bits in the integer being shifted; e.g., on some boxes it doesn't
330 * shift at all when they're equal.
331 */
332 const size_t ulargest = (size_t)-1 >> ((SIZEOF_SIZE_T - f->size)*8);
333 assert(f->size >= 1 && f->size <= SIZEOF_SIZE_T);
334 if (is_unsigned)
335 PyErr_Format(StructError,
336 "'%c' format requires 0 <= number <= %zu",
337 f->format,
338 ulargest);
339 else {
340 const Py_ssize_t largest = (Py_ssize_t)(ulargest >> 1);
341 PyErr_Format(StructError,
342 "'%c' format requires %zd <= number <= %zd",
343 f->format,
344 ~ largest,
345 largest);
346 }
Mark Dickinsonae681df2009-03-21 10:26:31 +0000347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000348 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000349}
350
351
352
353/* A large number of small routines follow, with names of the form
354
355 [bln][up]_TYPE
356
357 [bln] distiguishes among big-endian, little-endian and native.
358 [pu] distiguishes between pack (to struct) and unpack (from struct).
359 TYPE is one of char, byte, ubyte, etc.
360*/
361
362/* Native mode routines. ****************************************************/
363/* NOTE:
364 In all n[up]_<type> routines handling types larger than 1 byte, there is
365 *no* guarantee that the p pointer is properly aligned for each type,
366 therefore memcpy is called. An intermediate variable is used to
367 compensate for big-endian architectures.
368 Normally both the intermediate variable and the memcpy call will be
369 skipped by C optimisation in little-endian architectures (gcc >= 2.91
370 does this). */
371
372static PyObject *
373nu_char(const char *p, const formatdef *f)
374{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 return PyBytes_FromStringAndSize(p, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000376}
377
378static PyObject *
379nu_byte(const char *p, const formatdef *f)
380{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000381 return PyLong_FromLong((long) *(signed char *)p);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000382}
383
384static PyObject *
385nu_ubyte(const char *p, const formatdef *f)
386{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000387 return PyLong_FromLong((long) *(unsigned char *)p);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000388}
389
390static PyObject *
391nu_short(const char *p, const formatdef *f)
392{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000393 short x;
394 memcpy((char *)&x, p, sizeof x);
395 return PyLong_FromLong((long)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000396}
397
398static PyObject *
399nu_ushort(const char *p, const formatdef *f)
400{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000401 unsigned short x;
402 memcpy((char *)&x, p, sizeof x);
403 return PyLong_FromLong((long)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000404}
405
406static PyObject *
407nu_int(const char *p, const formatdef *f)
408{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000409 int x;
410 memcpy((char *)&x, p, sizeof x);
411 return PyLong_FromLong((long)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000412}
413
414static PyObject *
415nu_uint(const char *p, const formatdef *f)
416{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417 unsigned int x;
418 memcpy((char *)&x, p, sizeof x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000419#if (SIZEOF_LONG > SIZEOF_INT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 return PyLong_FromLong((long)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000421#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000422 if (x <= ((unsigned int)LONG_MAX))
423 return PyLong_FromLong((long)x);
424 return PyLong_FromUnsignedLong((unsigned long)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000425#endif
426}
427
428static PyObject *
429nu_long(const char *p, const formatdef *f)
430{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 long x;
432 memcpy((char *)&x, p, sizeof x);
433 return PyLong_FromLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000434}
435
436static PyObject *
437nu_ulong(const char *p, const formatdef *f)
438{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000439 unsigned long x;
440 memcpy((char *)&x, p, sizeof x);
441 if (x <= LONG_MAX)
442 return PyLong_FromLong((long)x);
443 return PyLong_FromUnsignedLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000444}
445
Antoine Pitrou45d9c912011-10-06 15:27:40 +0200446static PyObject *
447nu_ssize_t(const char *p, const formatdef *f)
448{
449 Py_ssize_t x;
450 memcpy((char *)&x, p, sizeof x);
451 return PyLong_FromSsize_t(x);
452}
453
454static PyObject *
455nu_size_t(const char *p, const formatdef *f)
456{
457 size_t x;
458 memcpy((char *)&x, p, sizeof x);
459 return PyLong_FromSize_t(x);
460}
461
462
Thomas Wouters477c8d52006-05-27 19:21:47 +0000463/* Native mode doesn't support q or Q unless the platform C supports
464 long long (or, on Windows, __int64). */
465
466#ifdef HAVE_LONG_LONG
467
468static PyObject *
469nu_longlong(const char *p, const formatdef *f)
470{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 PY_LONG_LONG x;
472 memcpy((char *)&x, p, sizeof x);
473 if (x >= LONG_MIN && x <= LONG_MAX)
474 return PyLong_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long));
475 return PyLong_FromLongLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000476}
477
478static PyObject *
479nu_ulonglong(const char *p, const formatdef *f)
480{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000481 unsigned PY_LONG_LONG x;
482 memcpy((char *)&x, p, sizeof x);
483 if (x <= LONG_MAX)
484 return PyLong_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long));
485 return PyLong_FromUnsignedLongLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000486}
487
488#endif
489
490static PyObject *
Thomas Woutersb2137042007-02-01 18:02:27 +0000491nu_bool(const char *p, const formatdef *f)
492{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 BOOL_TYPE x;
494 memcpy((char *)&x, p, sizeof x);
495 return PyBool_FromLong(x != 0);
Thomas Woutersb2137042007-02-01 18:02:27 +0000496}
497
498
499static PyObject *
Mark Dickinson7c4e4092016-09-03 17:21:29 +0100500nu_halffloat(const char *p, const formatdef *f)
501{
502#if PY_LITTLE_ENDIAN
503 return unpack_halffloat(p, 1);
504#else
505 return unpack_halffloat(p, 0);
506#endif
507}
508
509static PyObject *
Thomas Wouters477c8d52006-05-27 19:21:47 +0000510nu_float(const char *p, const formatdef *f)
511{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 float x;
513 memcpy((char *)&x, p, sizeof x);
514 return PyFloat_FromDouble((double)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000515}
516
517static PyObject *
518nu_double(const char *p, const formatdef *f)
519{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000520 double x;
521 memcpy((char *)&x, p, sizeof x);
522 return PyFloat_FromDouble(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000523}
524
525static PyObject *
526nu_void_p(const char *p, const formatdef *f)
527{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000528 void *x;
529 memcpy((char *)&x, p, sizeof x);
530 return PyLong_FromVoidPtr(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000531}
532
533static int
534np_byte(char *p, PyObject *v, const formatdef *f)
535{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000536 long x;
537 if (get_long(v, &x) < 0)
538 return -1;
539 if (x < -128 || x > 127){
540 PyErr_SetString(StructError,
541 "byte format requires -128 <= number <= 127");
542 return -1;
543 }
544 *p = (char)x;
545 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000546}
547
548static int
549np_ubyte(char *p, PyObject *v, const formatdef *f)
550{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 long x;
552 if (get_long(v, &x) < 0)
553 return -1;
554 if (x < 0 || x > 255){
555 PyErr_SetString(StructError,
556 "ubyte format requires 0 <= number <= 255");
557 return -1;
558 }
559 *p = (char)x;
560 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000561}
562
563static int
564np_char(char *p, PyObject *v, const formatdef *f)
565{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000566 if (!PyBytes_Check(v) || PyBytes_Size(v) != 1) {
567 PyErr_SetString(StructError,
Victor Stinnerda9ec992010-12-28 13:26:42 +0000568 "char format requires a bytes object of length 1");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000569 return -1;
570 }
571 *p = *PyBytes_AsString(v);
572 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000573}
574
575static int
576np_short(char *p, PyObject *v, const formatdef *f)
577{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000578 long x;
579 short y;
580 if (get_long(v, &x) < 0)
581 return -1;
582 if (x < SHRT_MIN || x > SHRT_MAX){
583 PyErr_SetString(StructError,
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200584 "short format requires " Py_STRINGIFY(SHRT_MIN)
585 " <= number <= " Py_STRINGIFY(SHRT_MAX));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000586 return -1;
587 }
588 y = (short)x;
589 memcpy(p, (char *)&y, sizeof y);
590 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000591}
592
593static int
594np_ushort(char *p, PyObject *v, const formatdef *f)
595{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596 long x;
597 unsigned short y;
598 if (get_long(v, &x) < 0)
599 return -1;
600 if (x < 0 || x > USHRT_MAX){
601 PyErr_SetString(StructError,
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200602 "ushort format requires 0 <= number <= "
603 Py_STRINGIFY(USHRT_MAX));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000604 return -1;
605 }
606 y = (unsigned short)x;
607 memcpy(p, (char *)&y, sizeof y);
608 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000609}
610
611static int
612np_int(char *p, PyObject *v, const formatdef *f)
613{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000614 long x;
615 int y;
616 if (get_long(v, &x) < 0)
617 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000618#if (SIZEOF_LONG > SIZEOF_INT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 if ((x < ((long)INT_MIN)) || (x > ((long)INT_MAX)))
620 RANGE_ERROR(x, f, 0, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000621#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 y = (int)x;
623 memcpy(p, (char *)&y, sizeof y);
624 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000625}
626
627static int
628np_uint(char *p, PyObject *v, const formatdef *f)
629{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 unsigned long x;
631 unsigned int y;
632 if (get_ulong(v, &x) < 0)
633 return -1;
634 y = (unsigned int)x;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000635#if (SIZEOF_LONG > SIZEOF_INT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 if (x > ((unsigned long)UINT_MAX))
637 RANGE_ERROR(y, f, 1, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000638#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000639 memcpy(p, (char *)&y, sizeof y);
640 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000641}
642
643static int
644np_long(char *p, PyObject *v, const formatdef *f)
645{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 long x;
647 if (get_long(v, &x) < 0)
648 return -1;
649 memcpy(p, (char *)&x, sizeof x);
650 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000651}
652
653static int
654np_ulong(char *p, PyObject *v, const formatdef *f)
655{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000656 unsigned long x;
657 if (get_ulong(v, &x) < 0)
658 return -1;
659 memcpy(p, (char *)&x, sizeof x);
660 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000661}
662
Antoine Pitrou45d9c912011-10-06 15:27:40 +0200663static int
664np_ssize_t(char *p, PyObject *v, const formatdef *f)
665{
666 Py_ssize_t x;
667 if (get_ssize_t(v, &x) < 0)
668 return -1;
669 memcpy(p, (char *)&x, sizeof x);
670 return 0;
671}
672
673static int
674np_size_t(char *p, PyObject *v, const formatdef *f)
675{
676 size_t x;
677 if (get_size_t(v, &x) < 0)
678 return -1;
679 memcpy(p, (char *)&x, sizeof x);
680 return 0;
681}
682
Thomas Wouters477c8d52006-05-27 19:21:47 +0000683#ifdef HAVE_LONG_LONG
684
685static int
686np_longlong(char *p, PyObject *v, const formatdef *f)
687{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000688 PY_LONG_LONG x;
689 if (get_longlong(v, &x) < 0)
690 return -1;
691 memcpy(p, (char *)&x, sizeof x);
692 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000693}
694
695static int
696np_ulonglong(char *p, PyObject *v, const formatdef *f)
697{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000698 unsigned PY_LONG_LONG x;
699 if (get_ulonglong(v, &x) < 0)
700 return -1;
701 memcpy(p, (char *)&x, sizeof x);
702 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000703}
704#endif
705
Thomas Woutersb2137042007-02-01 18:02:27 +0000706
707static int
708np_bool(char *p, PyObject *v, const formatdef *f)
709{
Benjamin Petersonde73c452010-07-07 18:54:59 +0000710 int y;
711 BOOL_TYPE x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000712 y = PyObject_IsTrue(v);
Benjamin Petersonde73c452010-07-07 18:54:59 +0000713 if (y < 0)
714 return -1;
715 x = y;
716 memcpy(p, (char *)&x, sizeof x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000717 return 0;
Thomas Woutersb2137042007-02-01 18:02:27 +0000718}
719
Thomas Wouters477c8d52006-05-27 19:21:47 +0000720static int
Mark Dickinson7c4e4092016-09-03 17:21:29 +0100721np_halffloat(char *p, PyObject *v, const formatdef *f)
722{
723#if PY_LITTLE_ENDIAN
724 return pack_halffloat(p, v, 1);
725#else
726 return pack_halffloat(p, v, 0);
727#endif
728}
729
730static int
Thomas Wouters477c8d52006-05-27 19:21:47 +0000731np_float(char *p, PyObject *v, const formatdef *f)
732{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000733 float x = (float)PyFloat_AsDouble(v);
734 if (x == -1 && PyErr_Occurred()) {
735 PyErr_SetString(StructError,
736 "required argument is not a float");
737 return -1;
738 }
739 memcpy(p, (char *)&x, sizeof x);
740 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000741}
742
743static int
744np_double(char *p, PyObject *v, const formatdef *f)
745{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000746 double x = PyFloat_AsDouble(v);
747 if (x == -1 && PyErr_Occurred()) {
748 PyErr_SetString(StructError,
749 "required argument is not a float");
750 return -1;
751 }
752 memcpy(p, (char *)&x, sizeof(double));
753 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000754}
755
756static int
757np_void_p(char *p, PyObject *v, const formatdef *f)
758{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000759 void *x;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000760
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000761 v = get_pylong(v);
762 if (v == NULL)
763 return -1;
764 assert(PyLong_Check(v));
765 x = PyLong_AsVoidPtr(v);
766 Py_DECREF(v);
767 if (x == NULL && PyErr_Occurred())
768 return -1;
769 memcpy(p, (char *)&x, sizeof x);
770 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000771}
772
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200773static const formatdef native_table[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000774 {'x', sizeof(char), 0, NULL},
775 {'b', sizeof(char), 0, nu_byte, np_byte},
776 {'B', sizeof(char), 0, nu_ubyte, np_ubyte},
777 {'c', sizeof(char), 0, nu_char, np_char},
778 {'s', sizeof(char), 0, NULL},
779 {'p', sizeof(char), 0, NULL},
780 {'h', sizeof(short), SHORT_ALIGN, nu_short, np_short},
781 {'H', sizeof(short), SHORT_ALIGN, nu_ushort, np_ushort},
782 {'i', sizeof(int), INT_ALIGN, nu_int, np_int},
783 {'I', sizeof(int), INT_ALIGN, nu_uint, np_uint},
784 {'l', sizeof(long), LONG_ALIGN, nu_long, np_long},
785 {'L', sizeof(long), LONG_ALIGN, nu_ulong, np_ulong},
Antoine Pitrou45d9c912011-10-06 15:27:40 +0200786 {'n', sizeof(size_t), SIZE_T_ALIGN, nu_ssize_t, np_ssize_t},
787 {'N', sizeof(size_t), SIZE_T_ALIGN, nu_size_t, np_size_t},
Thomas Wouters477c8d52006-05-27 19:21:47 +0000788#ifdef HAVE_LONG_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 {'q', sizeof(PY_LONG_LONG), LONG_LONG_ALIGN, nu_longlong, np_longlong},
790 {'Q', sizeof(PY_LONG_LONG), LONG_LONG_ALIGN, nu_ulonglong,np_ulonglong},
Thomas Wouters477c8d52006-05-27 19:21:47 +0000791#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000792 {'?', sizeof(BOOL_TYPE), BOOL_ALIGN, nu_bool, np_bool},
Mark Dickinson7c4e4092016-09-03 17:21:29 +0100793 {'e', sizeof(short), SHORT_ALIGN, nu_halffloat, np_halffloat},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000794 {'f', sizeof(float), FLOAT_ALIGN, nu_float, np_float},
795 {'d', sizeof(double), DOUBLE_ALIGN, nu_double, np_double},
796 {'P', sizeof(void *), VOID_P_ALIGN, nu_void_p, np_void_p},
797 {0}
Thomas Wouters477c8d52006-05-27 19:21:47 +0000798};
799
800/* Big-endian routines. *****************************************************/
801
802static PyObject *
803bu_int(const char *p, const formatdef *f)
804{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000805 long x = 0;
806 Py_ssize_t i = f->size;
807 const unsigned char *bytes = (const unsigned char *)p;
808 do {
809 x = (x<<8) | *bytes++;
810 } while (--i > 0);
811 /* Extend the sign bit. */
812 if (SIZEOF_LONG > f->size)
813 x |= -(x & (1L << ((8 * f->size) - 1)));
814 return PyLong_FromLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000815}
816
817static PyObject *
818bu_uint(const char *p, const formatdef *f)
819{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000820 unsigned long x = 0;
821 Py_ssize_t i = f->size;
822 const unsigned char *bytes = (const unsigned char *)p;
823 do {
824 x = (x<<8) | *bytes++;
825 } while (--i > 0);
826 if (x <= LONG_MAX)
827 return PyLong_FromLong((long)x);
828 return PyLong_FromUnsignedLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000829}
830
831static PyObject *
832bu_longlong(const char *p, const formatdef *f)
833{
834#ifdef HAVE_LONG_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 PY_LONG_LONG x = 0;
836 Py_ssize_t i = f->size;
837 const unsigned char *bytes = (const unsigned char *)p;
838 do {
839 x = (x<<8) | *bytes++;
840 } while (--i > 0);
841 /* Extend the sign bit. */
842 if (SIZEOF_LONG_LONG > f->size)
843 x |= -(x & ((PY_LONG_LONG)1 << ((8 * f->size) - 1)));
844 if (x >= LONG_MIN && x <= LONG_MAX)
845 return PyLong_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long));
846 return PyLong_FromLongLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000847#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 return _PyLong_FromByteArray((const unsigned char *)p,
849 8,
850 0, /* little-endian */
851 1 /* signed */);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000852#endif
853}
854
855static PyObject *
856bu_ulonglong(const char *p, const formatdef *f)
857{
858#ifdef HAVE_LONG_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 unsigned PY_LONG_LONG x = 0;
860 Py_ssize_t i = f->size;
861 const unsigned char *bytes = (const unsigned char *)p;
862 do {
863 x = (x<<8) | *bytes++;
864 } while (--i > 0);
865 if (x <= LONG_MAX)
866 return PyLong_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long));
867 return PyLong_FromUnsignedLongLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000868#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000869 return _PyLong_FromByteArray((const unsigned char *)p,
870 8,
871 0, /* little-endian */
872 0 /* signed */);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000873#endif
874}
875
876static PyObject *
Mark Dickinson7c4e4092016-09-03 17:21:29 +0100877bu_halffloat(const char *p, const formatdef *f)
878{
879 return unpack_halffloat(p, 0);
880}
881
882static PyObject *
Thomas Wouters477c8d52006-05-27 19:21:47 +0000883bu_float(const char *p, const formatdef *f)
884{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000885 return unpack_float(p, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000886}
887
888static PyObject *
889bu_double(const char *p, const formatdef *f)
890{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000891 return unpack_double(p, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000892}
893
Thomas Woutersb2137042007-02-01 18:02:27 +0000894static PyObject *
895bu_bool(const char *p, const formatdef *f)
896{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000897 char x;
898 memcpy((char *)&x, p, sizeof x);
899 return PyBool_FromLong(x != 0);
Thomas Woutersb2137042007-02-01 18:02:27 +0000900}
901
Thomas Wouters477c8d52006-05-27 19:21:47 +0000902static int
903bp_int(char *p, PyObject *v, const formatdef *f)
904{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000905 long x;
906 Py_ssize_t i;
907 if (get_long(v, &x) < 0)
908 return -1;
909 i = f->size;
910 if (i != SIZEOF_LONG) {
911 if ((i == 2) && (x < -32768 || x > 32767))
912 RANGE_ERROR(x, f, 0, 0xffffL);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000913#if (SIZEOF_LONG != 4)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 else if ((i == 4) && (x < -2147483648L || x > 2147483647L))
915 RANGE_ERROR(x, f, 0, 0xffffffffL);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000916#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000917 }
918 do {
919 p[--i] = (char)x;
920 x >>= 8;
921 } while (i > 0);
922 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000923}
924
925static int
926bp_uint(char *p, PyObject *v, const formatdef *f)
927{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 unsigned long x;
929 Py_ssize_t i;
930 if (get_ulong(v, &x) < 0)
931 return -1;
932 i = f->size;
933 if (i != SIZEOF_LONG) {
934 unsigned long maxint = 1;
935 maxint <<= (unsigned long)(i * 8);
936 if (x >= maxint)
937 RANGE_ERROR(x, f, 1, maxint - 1);
938 }
939 do {
940 p[--i] = (char)x;
941 x >>= 8;
942 } while (i > 0);
943 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000944}
945
946static int
947bp_longlong(char *p, PyObject *v, const formatdef *f)
948{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 int res;
950 v = get_pylong(v);
951 if (v == NULL)
952 return -1;
953 res = _PyLong_AsByteArray((PyLongObject *)v,
954 (unsigned char *)p,
955 8,
956 0, /* little_endian */
957 1 /* signed */);
958 Py_DECREF(v);
959 return res;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000960}
961
962static int
963bp_ulonglong(char *p, PyObject *v, const formatdef *f)
964{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000965 int res;
966 v = get_pylong(v);
967 if (v == NULL)
968 return -1;
969 res = _PyLong_AsByteArray((PyLongObject *)v,
970 (unsigned char *)p,
971 8,
972 0, /* little_endian */
973 0 /* signed */);
974 Py_DECREF(v);
975 return res;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000976}
977
978static int
Mark Dickinson7c4e4092016-09-03 17:21:29 +0100979bp_halffloat(char *p, PyObject *v, const formatdef *f)
980{
981 return pack_halffloat(p, v, 0);
982}
983
984static int
Thomas Wouters477c8d52006-05-27 19:21:47 +0000985bp_float(char *p, PyObject *v, const formatdef *f)
986{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987 double x = PyFloat_AsDouble(v);
988 if (x == -1 && PyErr_Occurred()) {
989 PyErr_SetString(StructError,
990 "required argument is not a float");
991 return -1;
992 }
993 return _PyFloat_Pack4(x, (unsigned char *)p, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000994}
995
996static int
997bp_double(char *p, PyObject *v, const formatdef *f)
998{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 double x = PyFloat_AsDouble(v);
1000 if (x == -1 && PyErr_Occurred()) {
1001 PyErr_SetString(StructError,
1002 "required argument is not a float");
1003 return -1;
1004 }
1005 return _PyFloat_Pack8(x, (unsigned char *)p, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001006}
1007
Thomas Woutersb2137042007-02-01 18:02:27 +00001008static int
1009bp_bool(char *p, PyObject *v, const formatdef *f)
1010{
Mark Dickinsoneff5d852010-07-18 07:29:02 +00001011 int y;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001012 y = PyObject_IsTrue(v);
Benjamin Petersonde73c452010-07-07 18:54:59 +00001013 if (y < 0)
1014 return -1;
Mark Dickinsoneff5d852010-07-18 07:29:02 +00001015 *p = (char)y;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 return 0;
Thomas Woutersb2137042007-02-01 18:02:27 +00001017}
1018
Thomas Wouters477c8d52006-05-27 19:21:47 +00001019static formatdef bigendian_table[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 {'x', 1, 0, NULL},
1021 {'b', 1, 0, nu_byte, np_byte},
1022 {'B', 1, 0, nu_ubyte, np_ubyte},
1023 {'c', 1, 0, nu_char, np_char},
1024 {'s', 1, 0, NULL},
1025 {'p', 1, 0, NULL},
1026 {'h', 2, 0, bu_int, bp_int},
1027 {'H', 2, 0, bu_uint, bp_uint},
1028 {'i', 4, 0, bu_int, bp_int},
1029 {'I', 4, 0, bu_uint, bp_uint},
1030 {'l', 4, 0, bu_int, bp_int},
1031 {'L', 4, 0, bu_uint, bp_uint},
1032 {'q', 8, 0, bu_longlong, bp_longlong},
1033 {'Q', 8, 0, bu_ulonglong, bp_ulonglong},
1034 {'?', 1, 0, bu_bool, bp_bool},
Mark Dickinson7c4e4092016-09-03 17:21:29 +01001035 {'e', 2, 0, bu_halffloat, bp_halffloat},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001036 {'f', 4, 0, bu_float, bp_float},
1037 {'d', 8, 0, bu_double, bp_double},
1038 {0}
Thomas Wouters477c8d52006-05-27 19:21:47 +00001039};
1040
1041/* Little-endian routines. *****************************************************/
1042
1043static PyObject *
1044lu_int(const char *p, const formatdef *f)
1045{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 long x = 0;
1047 Py_ssize_t i = f->size;
1048 const unsigned char *bytes = (const unsigned char *)p;
1049 do {
1050 x = (x<<8) | bytes[--i];
1051 } while (i > 0);
1052 /* Extend the sign bit. */
1053 if (SIZEOF_LONG > f->size)
1054 x |= -(x & (1L << ((8 * f->size) - 1)));
1055 return PyLong_FromLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001056}
1057
1058static PyObject *
1059lu_uint(const char *p, const formatdef *f)
1060{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001061 unsigned long x = 0;
1062 Py_ssize_t i = f->size;
1063 const unsigned char *bytes = (const unsigned char *)p;
1064 do {
1065 x = (x<<8) | bytes[--i];
1066 } while (i > 0);
1067 if (x <= LONG_MAX)
1068 return PyLong_FromLong((long)x);
1069 return PyLong_FromUnsignedLong((long)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001070}
1071
1072static PyObject *
1073lu_longlong(const char *p, const formatdef *f)
1074{
1075#ifdef HAVE_LONG_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001076 PY_LONG_LONG x = 0;
1077 Py_ssize_t i = f->size;
1078 const unsigned char *bytes = (const unsigned char *)p;
1079 do {
1080 x = (x<<8) | bytes[--i];
1081 } while (i > 0);
1082 /* Extend the sign bit. */
1083 if (SIZEOF_LONG_LONG > f->size)
1084 x |= -(x & ((PY_LONG_LONG)1 << ((8 * f->size) - 1)));
1085 if (x >= LONG_MIN && x <= LONG_MAX)
1086 return PyLong_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long));
1087 return PyLong_FromLongLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001088#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001089 return _PyLong_FromByteArray((const unsigned char *)p,
1090 8,
1091 1, /* little-endian */
1092 1 /* signed */);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001093#endif
1094}
1095
1096static PyObject *
1097lu_ulonglong(const char *p, const formatdef *f)
1098{
1099#ifdef HAVE_LONG_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001100 unsigned PY_LONG_LONG x = 0;
1101 Py_ssize_t i = f->size;
1102 const unsigned char *bytes = (const unsigned char *)p;
1103 do {
1104 x = (x<<8) | bytes[--i];
1105 } while (i > 0);
1106 if (x <= LONG_MAX)
1107 return PyLong_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long));
1108 return PyLong_FromUnsignedLongLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001109#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001110 return _PyLong_FromByteArray((const unsigned char *)p,
1111 8,
1112 1, /* little-endian */
1113 0 /* signed */);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001114#endif
1115}
1116
1117static PyObject *
Mark Dickinson7c4e4092016-09-03 17:21:29 +01001118lu_halffloat(const char *p, const formatdef *f)
1119{
1120 return unpack_halffloat(p, 1);
1121}
1122
1123static PyObject *
Thomas Wouters477c8d52006-05-27 19:21:47 +00001124lu_float(const char *p, const formatdef *f)
1125{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 return unpack_float(p, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001127}
1128
1129static PyObject *
1130lu_double(const char *p, const formatdef *f)
1131{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001132 return unpack_double(p, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001133}
1134
1135static int
1136lp_int(char *p, PyObject *v, const formatdef *f)
1137{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001138 long x;
1139 Py_ssize_t i;
1140 if (get_long(v, &x) < 0)
1141 return -1;
1142 i = f->size;
1143 if (i != SIZEOF_LONG) {
1144 if ((i == 2) && (x < -32768 || x > 32767))
1145 RANGE_ERROR(x, f, 0, 0xffffL);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001146#if (SIZEOF_LONG != 4)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001147 else if ((i == 4) && (x < -2147483648L || x > 2147483647L))
1148 RANGE_ERROR(x, f, 0, 0xffffffffL);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001149#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001150 }
1151 do {
1152 *p++ = (char)x;
1153 x >>= 8;
1154 } while (--i > 0);
1155 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001156}
1157
1158static int
1159lp_uint(char *p, PyObject *v, const formatdef *f)
1160{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001161 unsigned long x;
1162 Py_ssize_t i;
1163 if (get_ulong(v, &x) < 0)
1164 return -1;
1165 i = f->size;
1166 if (i != SIZEOF_LONG) {
1167 unsigned long maxint = 1;
1168 maxint <<= (unsigned long)(i * 8);
1169 if (x >= maxint)
1170 RANGE_ERROR(x, f, 1, maxint - 1);
1171 }
1172 do {
1173 *p++ = (char)x;
1174 x >>= 8;
1175 } while (--i > 0);
1176 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001177}
1178
1179static int
1180lp_longlong(char *p, PyObject *v, const formatdef *f)
1181{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 int res;
1183 v = get_pylong(v);
1184 if (v == NULL)
1185 return -1;
1186 res = _PyLong_AsByteArray((PyLongObject*)v,
1187 (unsigned char *)p,
1188 8,
1189 1, /* little_endian */
1190 1 /* signed */);
1191 Py_DECREF(v);
1192 return res;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001193}
1194
1195static int
1196lp_ulonglong(char *p, PyObject *v, const formatdef *f)
1197{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001198 int res;
1199 v = get_pylong(v);
1200 if (v == NULL)
1201 return -1;
1202 res = _PyLong_AsByteArray((PyLongObject*)v,
1203 (unsigned char *)p,
1204 8,
1205 1, /* little_endian */
1206 0 /* signed */);
1207 Py_DECREF(v);
1208 return res;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001209}
1210
1211static int
Mark Dickinson7c4e4092016-09-03 17:21:29 +01001212lp_halffloat(char *p, PyObject *v, const formatdef *f)
1213{
1214 return pack_halffloat(p, v, 1);
1215}
1216
1217static int
Thomas Wouters477c8d52006-05-27 19:21:47 +00001218lp_float(char *p, PyObject *v, const formatdef *f)
1219{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001220 double x = PyFloat_AsDouble(v);
1221 if (x == -1 && PyErr_Occurred()) {
1222 PyErr_SetString(StructError,
1223 "required argument is not a float");
1224 return -1;
1225 }
1226 return _PyFloat_Pack4(x, (unsigned char *)p, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001227}
1228
1229static int
1230lp_double(char *p, PyObject *v, const formatdef *f)
1231{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001232 double x = PyFloat_AsDouble(v);
1233 if (x == -1 && PyErr_Occurred()) {
1234 PyErr_SetString(StructError,
1235 "required argument is not a float");
1236 return -1;
1237 }
1238 return _PyFloat_Pack8(x, (unsigned char *)p, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001239}
1240
1241static formatdef lilendian_table[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001242 {'x', 1, 0, NULL},
1243 {'b', 1, 0, nu_byte, np_byte},
1244 {'B', 1, 0, nu_ubyte, np_ubyte},
1245 {'c', 1, 0, nu_char, np_char},
1246 {'s', 1, 0, NULL},
1247 {'p', 1, 0, NULL},
1248 {'h', 2, 0, lu_int, lp_int},
1249 {'H', 2, 0, lu_uint, lp_uint},
1250 {'i', 4, 0, lu_int, lp_int},
1251 {'I', 4, 0, lu_uint, lp_uint},
1252 {'l', 4, 0, lu_int, lp_int},
1253 {'L', 4, 0, lu_uint, lp_uint},
1254 {'q', 8, 0, lu_longlong, lp_longlong},
1255 {'Q', 8, 0, lu_ulonglong, lp_ulonglong},
1256 {'?', 1, 0, bu_bool, bp_bool}, /* Std rep not endian dep,
1257 but potentially different from native rep -- reuse bx_bool funcs. */
Mark Dickinson7c4e4092016-09-03 17:21:29 +01001258 {'e', 2, 0, lu_halffloat, lp_halffloat},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001259 {'f', 4, 0, lu_float, lp_float},
1260 {'d', 8, 0, lu_double, lp_double},
1261 {0}
Thomas Wouters477c8d52006-05-27 19:21:47 +00001262};
1263
1264
1265static const formatdef *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001266whichtable(const char **pfmt)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001267{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001268 const char *fmt = (*pfmt)++; /* May be backed out of later */
1269 switch (*fmt) {
1270 case '<':
1271 return lilendian_table;
1272 case '>':
1273 case '!': /* Network byte order is big-endian */
1274 return bigendian_table;
Ezio Melotti42da6632011-03-15 05:18:48 +02001275 case '=': { /* Host byte order -- different from native in alignment! */
Christian Heimes743e0cd2012-10-17 23:52:17 +02001276#if PY_LITTLE_ENDIAN
1277 return lilendian_table;
1278#else
1279 return bigendian_table;
1280#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001281 }
1282 default:
1283 --*pfmt; /* Back out of pointer increment */
1284 /* Fall through */
1285 case '@':
1286 return native_table;
1287 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001288}
1289
1290
1291/* Get the table entry for a format code */
1292
1293static const formatdef *
1294getentry(int c, const formatdef *f)
1295{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001296 for (; f->format != '\0'; f++) {
1297 if (f->format == c) {
1298 return f;
1299 }
1300 }
1301 PyErr_SetString(StructError, "bad char in struct format");
1302 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001303}
1304
1305
Mark Dickinsonb72e6862010-06-11 19:50:30 +00001306/* Align a size according to a format code. Return -1 on overflow. */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001307
Mark Dickinsoneac0e682010-06-11 19:05:08 +00001308static Py_ssize_t
Thomas Wouters477c8d52006-05-27 19:21:47 +00001309align(Py_ssize_t size, char c, const formatdef *e)
1310{
Mark Dickinsonb72e6862010-06-11 19:50:30 +00001311 Py_ssize_t extra;
1312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001313 if (e->format == c) {
Mark Dickinsonb72e6862010-06-11 19:50:30 +00001314 if (e->alignment && size > 0) {
1315 extra = (e->alignment - 1) - (size - 1) % (e->alignment);
1316 if (extra > PY_SSIZE_T_MAX - size)
1317 return -1;
1318 size += extra;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001319 }
1320 }
1321 return size;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001322}
1323
Antoine Pitrou9f146812013-04-27 00:20:04 +02001324/*
1325 * Struct object implementation.
1326 */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001327
1328/* calculate the size of a format string */
1329
1330static int
1331prepare_s(PyStructObject *self)
1332{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001333 const formatdef *f;
1334 const formatdef *e;
1335 formatcode *codes;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001336
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001337 const char *s;
1338 const char *fmt;
1339 char c;
Victor Stinner706768c2014-08-16 01:03:39 +02001340 Py_ssize_t size, len, num, itemsize;
1341 size_t ncodes;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001343 fmt = PyBytes_AS_STRING(self->s_format);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001344
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001345 f = whichtable(&fmt);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001347 s = fmt;
1348 size = 0;
1349 len = 0;
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001350 ncodes = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001351 while ((c = *s++) != '\0') {
Antoine Pitrou4de74572013-02-09 23:11:27 +01001352 if (Py_ISSPACE(Py_CHARMASK(c)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001353 continue;
1354 if ('0' <= c && c <= '9') {
1355 num = c - '0';
1356 while ('0' <= (c = *s++) && c <= '9') {
Mark Dickinsonab4096f2010-06-11 16:56:34 +00001357 /* overflow-safe version of
1358 if (num*10 + (c - '0') > PY_SSIZE_T_MAX) { ... } */
1359 if (num >= PY_SSIZE_T_MAX / 10 && (
1360 num > PY_SSIZE_T_MAX / 10 ||
Mark Dickinsonb72e6862010-06-11 19:50:30 +00001361 (c - '0') > PY_SSIZE_T_MAX % 10))
1362 goto overflow;
Mark Dickinsonab4096f2010-06-11 16:56:34 +00001363 num = num*10 + (c - '0');
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001364 }
Alexander Belopolsky177e8532010-06-11 16:04:59 +00001365 if (c == '\0') {
1366 PyErr_SetString(StructError,
1367 "repeat count given without format specifier");
1368 return -1;
1369 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001370 }
1371 else
1372 num = 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001374 e = getentry(c, f);
1375 if (e == NULL)
1376 return -1;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001378 switch (c) {
1379 case 's': /* fall through */
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001380 case 'p': len++; ncodes++; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001381 case 'x': break;
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001382 default: len += num; if (num) ncodes++; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001383 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001385 itemsize = e->size;
1386 size = align(size, c, e);
Mark Dickinsonb72e6862010-06-11 19:50:30 +00001387 if (size == -1)
1388 goto overflow;
1389
1390 /* if (size + num * itemsize > PY_SSIZE_T_MAX) { ... } */
1391 if (num > (PY_SSIZE_T_MAX - size) / itemsize)
1392 goto overflow;
1393 size += num * itemsize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001394 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001396 /* check for overflow */
Victor Stinner706768c2014-08-16 01:03:39 +02001397 if ((ncodes + 1) > ((size_t)PY_SSIZE_T_MAX / sizeof(formatcode))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001398 PyErr_NoMemory();
1399 return -1;
1400 }
Amaury Forgeot d'Arc35c86582008-06-17 21:11:29 +00001401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001402 self->s_size = size;
1403 self->s_len = len;
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001404 codes = PyMem_MALLOC((ncodes + 1) * sizeof(formatcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001405 if (codes == NULL) {
1406 PyErr_NoMemory();
1407 return -1;
1408 }
Mark Dickinsoncf28b952010-07-29 21:41:59 +00001409 /* Free any s_codes value left over from a previous initialization. */
1410 if (self->s_codes != NULL)
1411 PyMem_FREE(self->s_codes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001412 self->s_codes = codes;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001413
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001414 s = fmt;
1415 size = 0;
1416 while ((c = *s++) != '\0') {
Antoine Pitrou4de74572013-02-09 23:11:27 +01001417 if (Py_ISSPACE(Py_CHARMASK(c)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001418 continue;
1419 if ('0' <= c && c <= '9') {
1420 num = c - '0';
1421 while ('0' <= (c = *s++) && c <= '9')
1422 num = num*10 + (c - '0');
1423 if (c == '\0')
1424 break;
1425 }
1426 else
1427 num = 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001428
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001429 e = getentry(c, f);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001431 size = align(size, c, e);
1432 if (c == 's' || c == 'p') {
1433 codes->offset = size;
1434 codes->size = num;
1435 codes->fmtdef = e;
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001436 codes->repeat = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001437 codes++;
1438 size += num;
1439 } else if (c == 'x') {
1440 size += num;
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001441 } else if (num) {
1442 codes->offset = size;
1443 codes->size = e->size;
1444 codes->fmtdef = e;
1445 codes->repeat = num;
1446 codes++;
1447 size += e->size * num;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001448 }
1449 }
1450 codes->fmtdef = NULL;
1451 codes->offset = size;
1452 codes->size = 0;
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001453 codes->repeat = 0;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001454
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001455 return 0;
Mark Dickinsonb72e6862010-06-11 19:50:30 +00001456
1457 overflow:
1458 PyErr_SetString(StructError,
1459 "total struct size too long");
1460 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001461}
1462
1463static PyObject *
1464s_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1465{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001466 PyObject *self;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001467
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001468 assert(type != NULL && type->tp_alloc != NULL);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001470 self = type->tp_alloc(type, 0);
1471 if (self != NULL) {
1472 PyStructObject *s = (PyStructObject*)self;
1473 Py_INCREF(Py_None);
1474 s->s_format = Py_None;
1475 s->s_codes = NULL;
1476 s->s_size = -1;
1477 s->s_len = -1;
1478 }
1479 return self;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001480}
1481
1482static int
1483s_init(PyObject *self, PyObject *args, PyObject *kwds)
1484{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001485 PyStructObject *soself = (PyStructObject *)self;
1486 PyObject *o_format = NULL;
1487 int ret = 0;
1488 static char *kwlist[] = {"format", 0};
Thomas Wouters477c8d52006-05-27 19:21:47 +00001489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001490 assert(PyStruct_Check(self));
Thomas Wouters477c8d52006-05-27 19:21:47 +00001491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001492 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:Struct", kwlist,
1493 &o_format))
1494 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001496 if (PyUnicode_Check(o_format)) {
1497 o_format = PyUnicode_AsASCIIString(o_format);
1498 if (o_format == NULL)
1499 return -1;
1500 }
1501 /* XXX support buffer interface, too */
1502 else {
1503 Py_INCREF(o_format);
1504 }
Christian Heimesa34706f2008-01-04 03:06:10 +00001505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001506 if (!PyBytes_Check(o_format)) {
1507 Py_DECREF(o_format);
1508 PyErr_Format(PyExc_TypeError,
Victor Stinnerda9ec992010-12-28 13:26:42 +00001509 "Struct() argument 1 must be a bytes object, not %.200s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001510 Py_TYPE(o_format)->tp_name);
1511 return -1;
1512 }
Christian Heimesa34706f2008-01-04 03:06:10 +00001513
Serhiy Storchaka48842712016-04-06 09:45:48 +03001514 Py_XSETREF(soself->s_format, o_format);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001516 ret = prepare_s(soself);
1517 return ret;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001518}
1519
1520static void
1521s_dealloc(PyStructObject *s)
1522{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001523 if (s->weakreflist != NULL)
1524 PyObject_ClearWeakRefs((PyObject *)s);
1525 if (s->s_codes != NULL) {
1526 PyMem_FREE(s->s_codes);
1527 }
1528 Py_XDECREF(s->s_format);
1529 Py_TYPE(s)->tp_free((PyObject *)s);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001530}
1531
1532static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001533s_unpack_internal(PyStructObject *soself, const char *startfrom) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001534 formatcode *code;
1535 Py_ssize_t i = 0;
1536 PyObject *result = PyTuple_New(soself->s_len);
1537 if (result == NULL)
1538 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001540 for (code = soself->s_codes; code->fmtdef != NULL; code++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001541 const formatdef *e = code->fmtdef;
1542 const char *res = startfrom + code->offset;
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001543 Py_ssize_t j = code->repeat;
1544 while (j--) {
1545 PyObject *v;
1546 if (e->format == 's') {
1547 v = PyBytes_FromStringAndSize(res, code->size);
1548 } else if (e->format == 'p') {
1549 Py_ssize_t n = *(unsigned char*)res;
1550 if (n >= code->size)
1551 n = code->size - 1;
1552 v = PyBytes_FromStringAndSize(res + 1, n);
1553 } else {
1554 v = e->unpack(res, e);
1555 }
1556 if (v == NULL)
1557 goto fail;
1558 PyTuple_SET_ITEM(result, i++, v);
1559 res += code->size;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001560 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001561 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001563 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001564fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001565 Py_DECREF(result);
1566 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001567}
1568
1569
1570PyDoc_STRVAR(s_unpack__doc__,
Guido van Rossum913dd0b2007-04-13 03:33:53 +00001571"S.unpack(buffer) -> (v1, v2, ...)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00001572\n\
Mark Dickinsonaacfa952010-06-12 15:43:45 +00001573Return a tuple containing values unpacked according to the format\n\
Martin Panterb0309912016-04-15 23:03:54 +00001574string S.format. The buffer's size in bytes must be S.size. See\n\
1575help(struct) for more on format strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001576
1577static PyObject *
Guido van Rossum98297ee2007-11-06 21:34:58 +00001578s_unpack(PyObject *self, PyObject *input)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001579{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001580 Py_buffer vbuf;
1581 PyObject *result;
1582 PyStructObject *soself = (PyStructObject *)self;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001584 assert(PyStruct_Check(self));
1585 assert(soself->s_codes != NULL);
1586 if (PyObject_GetBuffer(input, &vbuf, PyBUF_SIMPLE) < 0)
1587 return NULL;
1588 if (vbuf.len != soself->s_size) {
1589 PyErr_Format(StructError,
Victor Stinnerda9ec992010-12-28 13:26:42 +00001590 "unpack requires a bytes object of length %zd",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001591 soself->s_size);
1592 PyBuffer_Release(&vbuf);
1593 return NULL;
1594 }
1595 result = s_unpack_internal(soself, vbuf.buf);
1596 PyBuffer_Release(&vbuf);
1597 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001598}
1599
1600PyDoc_STRVAR(s_unpack_from__doc__,
Mark Dickinsonc6f13962010-06-13 09:17:13 +00001601"S.unpack_from(buffer, offset=0) -> (v1, v2, ...)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00001602\n\
Mark Dickinsonaacfa952010-06-12 15:43:45 +00001603Return a tuple containing values unpacked according to the format\n\
Martin Panterb0309912016-04-15 23:03:54 +00001604string S.format. The buffer's size in bytes, minus offset, must be at\n\
1605least S.size. See help(struct) for more on format strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001606
1607static PyObject *
1608s_unpack_from(PyObject *self, PyObject *args, PyObject *kwds)
1609{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001610 static char *kwlist[] = {"buffer", "offset", 0};
Guido van Rossum98297ee2007-11-06 21:34:58 +00001611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001612 PyObject *input;
1613 Py_ssize_t offset = 0;
1614 Py_buffer vbuf;
1615 PyObject *result;
1616 PyStructObject *soself = (PyStructObject *)self;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001618 assert(PyStruct_Check(self));
1619 assert(soself->s_codes != NULL);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001621 if (!PyArg_ParseTupleAndKeywords(args, kwds,
1622 "O|n:unpack_from", kwlist,
1623 &input, &offset))
1624 return NULL;
1625 if (PyObject_GetBuffer(input, &vbuf, PyBUF_SIMPLE) < 0)
1626 return NULL;
1627 if (offset < 0)
1628 offset += vbuf.len;
1629 if (offset < 0 || vbuf.len - offset < soself->s_size) {
1630 PyErr_Format(StructError,
1631 "unpack_from requires a buffer of at least %zd bytes",
1632 soself->s_size);
1633 PyBuffer_Release(&vbuf);
1634 return NULL;
1635 }
1636 result = s_unpack_internal(soself, (char*)vbuf.buf + offset);
1637 PyBuffer_Release(&vbuf);
1638 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001639}
1640
1641
Antoine Pitrou9f146812013-04-27 00:20:04 +02001642/* Unpack iterator type */
1643
1644typedef struct {
1645 PyObject_HEAD
1646 PyStructObject *so;
1647 Py_buffer buf;
1648 Py_ssize_t index;
1649} unpackiterobject;
1650
1651static void
1652unpackiter_dealloc(unpackiterobject *self)
1653{
1654 Py_XDECREF(self->so);
1655 PyBuffer_Release(&self->buf);
1656 PyObject_GC_Del(self);
1657}
1658
1659static int
1660unpackiter_traverse(unpackiterobject *self, visitproc visit, void *arg)
1661{
1662 Py_VISIT(self->so);
1663 Py_VISIT(self->buf.obj);
1664 return 0;
1665}
1666
1667static PyObject *
1668unpackiter_len(unpackiterobject *self)
1669{
1670 Py_ssize_t len;
1671 if (self->so == NULL)
1672 len = 0;
1673 else
1674 len = (self->buf.len - self->index) / self->so->s_size;
1675 return PyLong_FromSsize_t(len);
1676}
1677
1678static PyMethodDef unpackiter_methods[] = {
1679 {"__length_hint__", (PyCFunction) unpackiter_len, METH_NOARGS, NULL},
1680 {NULL, NULL} /* sentinel */
1681};
1682
1683static PyObject *
1684unpackiter_iternext(unpackiterobject *self)
1685{
1686 PyObject *result;
1687 if (self->so == NULL)
1688 return NULL;
1689 if (self->index >= self->buf.len) {
1690 /* Iterator exhausted */
1691 Py_CLEAR(self->so);
1692 PyBuffer_Release(&self->buf);
1693 return NULL;
1694 }
1695 assert(self->index + self->so->s_size <= self->buf.len);
1696 result = s_unpack_internal(self->so,
1697 (char*) self->buf.buf + self->index);
1698 self->index += self->so->s_size;
1699 return result;
1700}
1701
doko@ubuntu.com46c5deb2013-11-23 16:07:55 +01001702static PyTypeObject unpackiter_type = {
Antoine Pitrou9f146812013-04-27 00:20:04 +02001703 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1704 "unpack_iterator", /* tp_name */
1705 sizeof(unpackiterobject), /* tp_basicsize */
1706 0, /* tp_itemsize */
1707 (destructor)unpackiter_dealloc, /* tp_dealloc */
1708 0, /* tp_print */
1709 0, /* tp_getattr */
1710 0, /* tp_setattr */
1711 0, /* tp_reserved */
1712 0, /* tp_repr */
1713 0, /* tp_as_number */
1714 0, /* tp_as_sequence */
1715 0, /* tp_as_mapping */
1716 0, /* tp_hash */
1717 0, /* tp_call */
1718 0, /* tp_str */
1719 PyObject_GenericGetAttr, /* tp_getattro */
1720 0, /* tp_setattro */
1721 0, /* tp_as_buffer */
1722 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
1723 0, /* tp_doc */
1724 (traverseproc)unpackiter_traverse, /* tp_traverse */
1725 0, /* tp_clear */
1726 0, /* tp_richcompare */
1727 0, /* tp_weaklistoffset */
1728 PyObject_SelfIter, /* tp_iter */
1729 (iternextfunc)unpackiter_iternext, /* tp_iternext */
1730 unpackiter_methods /* tp_methods */
1731};
1732
1733PyDoc_STRVAR(s_iter_unpack__doc__,
1734"S.iter_unpack(buffer) -> iterator(v1, v2, ...)\n\
1735\n\
1736Return an iterator yielding tuples unpacked from the given bytes\n\
1737source, like a repeated invocation of unpack_from(). Requires\n\
1738that the bytes length be a multiple of the struct size.");
1739
1740static PyObject *
1741s_iter_unpack(PyObject *_so, PyObject *input)
1742{
1743 PyStructObject *so = (PyStructObject *) _so;
1744 unpackiterobject *self;
1745
1746 assert(PyStruct_Check(_so));
1747 assert(so->s_codes != NULL);
1748
1749 if (so->s_size == 0) {
1750 PyErr_Format(StructError,
1751 "cannot iteratively unpack with a struct of length 0");
1752 return NULL;
1753 }
1754
1755 self = (unpackiterobject *) PyType_GenericAlloc(&unpackiter_type, 0);
1756 if (self == NULL)
1757 return NULL;
1758
1759 if (PyObject_GetBuffer(input, &self->buf, PyBUF_SIMPLE) < 0) {
1760 Py_DECREF(self);
1761 return NULL;
1762 }
1763 if (self->buf.len % so->s_size != 0) {
1764 PyErr_Format(StructError,
1765 "iterative unpacking requires a bytes length "
1766 "multiple of %zd",
1767 so->s_size);
1768 Py_DECREF(self);
1769 return NULL;
1770 }
1771 Py_INCREF(so);
1772 self->so = so;
1773 self->index = 0;
1774 return (PyObject *) self;
1775}
1776
1777
Thomas Wouters477c8d52006-05-27 19:21:47 +00001778/*
1779 * Guts of the pack function.
1780 *
1781 * Takes a struct object, a tuple of arguments, and offset in that tuple of
1782 * argument for where to start processing the arguments for packing, and a
1783 * character buffer for writing the packed string. The caller must insure
1784 * that the buffer may contain the required length for packing the arguments.
1785 * 0 is returned on success, 1 is returned if there is an error.
1786 *
1787 */
1788static int
1789s_pack_internal(PyStructObject *soself, PyObject *args, int offset, char* buf)
1790{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001791 formatcode *code;
1792 /* XXX(nnorwitz): why does i need to be a local? can we use
1793 the offset parameter or do we need the wider width? */
1794 Py_ssize_t i;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001796 memset(buf, '\0', soself->s_size);
1797 i = offset;
1798 for (code = soself->s_codes; code->fmtdef != NULL; code++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001799 const formatdef *e = code->fmtdef;
1800 char *res = buf + code->offset;
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001801 Py_ssize_t j = code->repeat;
1802 while (j--) {
1803 PyObject *v = PyTuple_GET_ITEM(args, i++);
1804 if (e->format == 's') {
1805 Py_ssize_t n;
1806 int isstring;
1807 void *p;
1808 isstring = PyBytes_Check(v);
1809 if (!isstring && !PyByteArray_Check(v)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001810 PyErr_SetString(StructError,
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001811 "argument for 's' must be a bytes object");
1812 return -1;
1813 }
1814 if (isstring) {
1815 n = PyBytes_GET_SIZE(v);
1816 p = PyBytes_AS_STRING(v);
1817 }
1818 else {
1819 n = PyByteArray_GET_SIZE(v);
1820 p = PyByteArray_AS_STRING(v);
1821 }
1822 if (n > code->size)
1823 n = code->size;
1824 if (n > 0)
1825 memcpy(res, p, n);
1826 } else if (e->format == 'p') {
1827 Py_ssize_t n;
1828 int isstring;
1829 void *p;
1830 isstring = PyBytes_Check(v);
1831 if (!isstring && !PyByteArray_Check(v)) {
1832 PyErr_SetString(StructError,
1833 "argument for 'p' must be a bytes object");
1834 return -1;
1835 }
1836 if (isstring) {
1837 n = PyBytes_GET_SIZE(v);
1838 p = PyBytes_AS_STRING(v);
1839 }
1840 else {
1841 n = PyByteArray_GET_SIZE(v);
1842 p = PyByteArray_AS_STRING(v);
1843 }
1844 if (n > (code->size - 1))
1845 n = code->size - 1;
1846 if (n > 0)
1847 memcpy(res + 1, p, n);
1848 if (n > 255)
1849 n = 255;
1850 *res = Py_SAFE_DOWNCAST(n, Py_ssize_t, unsigned char);
1851 } else {
1852 if (e->pack(res, v, e) < 0) {
1853 if (PyLong_Check(v) && PyErr_ExceptionMatches(PyExc_OverflowError))
1854 PyErr_SetString(StructError,
Serhiy Storchaka46e1ce22013-08-27 20:17:03 +03001855 "int too large to convert");
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001856 return -1;
1857 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001858 }
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001859 res += code->size;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001860 }
1861 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001862
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001863 /* Success */
1864 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001865}
1866
1867
1868PyDoc_STRVAR(s_pack__doc__,
Benjamin Peterson4ae19462008-07-31 15:03:40 +00001869"S.pack(v1, v2, ...) -> bytes\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00001870\n\
Mark Dickinsonaacfa952010-06-12 15:43:45 +00001871Return a bytes object containing values v1, v2, ... packed according\n\
1872to the format string S.format. See help(struct) for more on format\n\
1873strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001874
1875static PyObject *
1876s_pack(PyObject *self, PyObject *args)
1877{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001878 PyStructObject *soself;
1879 PyObject *result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001880
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001881 /* Validate arguments. */
1882 soself = (PyStructObject *)self;
1883 assert(PyStruct_Check(self));
1884 assert(soself->s_codes != NULL);
1885 if (PyTuple_GET_SIZE(args) != soself->s_len)
1886 {
1887 PyErr_Format(StructError,
Petri Lehtinen92c28ca2012-10-29 21:16:57 +02001888 "pack expected %zd items for packing (got %zd)", soself->s_len, PyTuple_GET_SIZE(args));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001889 return NULL;
1890 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001892 /* Allocate a new string */
1893 result = PyBytes_FromStringAndSize((char *)NULL, soself->s_size);
1894 if (result == NULL)
1895 return NULL;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001897 /* Call the guts */
1898 if ( s_pack_internal(soself, args, 0, PyBytes_AS_STRING(result)) != 0 ) {
1899 Py_DECREF(result);
1900 return NULL;
1901 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001903 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001904}
1905
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001906PyDoc_STRVAR(s_pack_into__doc__,
1907"S.pack_into(buffer, offset, v1, v2, ...)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00001908\n\
Mark Dickinsonaacfa952010-06-12 15:43:45 +00001909Pack the values v1, v2, ... according to the format string S.format\n\
1910and write the packed bytes into the writable buffer buf starting at\n\
Mark Dickinsonfdb99f12010-06-12 16:30:53 +00001911offset. Note that the offset is a required argument. See\n\
Mark Dickinsonaacfa952010-06-12 15:43:45 +00001912help(struct) for more on format strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001913
1914static PyObject *
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001915s_pack_into(PyObject *self, PyObject *args)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001916{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001917 PyStructObject *soself;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001918 Py_buffer buffer;
1919 Py_ssize_t offset;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001920
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001921 /* Validate arguments. +1 is for the first arg as buffer. */
1922 soself = (PyStructObject *)self;
1923 assert(PyStruct_Check(self));
1924 assert(soself->s_codes != NULL);
1925 if (PyTuple_GET_SIZE(args) != (soself->s_len + 2))
1926 {
Petri Lehtinen92c28ca2012-10-29 21:16:57 +02001927 if (PyTuple_GET_SIZE(args) == 0) {
1928 PyErr_Format(StructError,
1929 "pack_into expected buffer argument");
1930 }
1931 else if (PyTuple_GET_SIZE(args) == 1) {
1932 PyErr_Format(StructError,
1933 "pack_into expected offset argument");
1934 }
1935 else {
1936 PyErr_Format(StructError,
1937 "pack_into expected %zd items for packing (got %zd)",
1938 soself->s_len, (PyTuple_GET_SIZE(args) - 2));
1939 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001940 return NULL;
1941 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001943 /* Extract a writable memory buffer from the first argument */
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001944 if (!PyArg_Parse(PyTuple_GET_ITEM(args, 0), "w*", &buffer))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001945 return NULL;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001946 assert(buffer.len >= 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001947
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001948 /* Extract the offset from the first argument */
1949 offset = PyNumber_AsSsize_t(PyTuple_GET_ITEM(args, 1), PyExc_IndexError);
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001950 if (offset == -1 && PyErr_Occurred()) {
1951 PyBuffer_Release(&buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001952 return NULL;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001953 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001955 /* Support negative offsets. */
1956 if (offset < 0)
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001957 offset += buffer.len;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001958
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001959 /* Check boundaries */
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001960 if (offset < 0 || (buffer.len - offset) < soself->s_size) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001961 PyErr_Format(StructError,
1962 "pack_into requires a buffer of at least %zd bytes",
1963 soself->s_size);
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001964 PyBuffer_Release(&buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001965 return NULL;
1966 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001967
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001968 /* Call the guts */
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001969 if (s_pack_internal(soself, args, 2, (char*)buffer.buf + offset) != 0) {
1970 PyBuffer_Release(&buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001971 return NULL;
1972 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001973
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001974 PyBuffer_Release(&buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001975 Py_RETURN_NONE;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001976}
1977
1978static PyObject *
1979s_get_format(PyStructObject *self, void *unused)
1980{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001981 Py_INCREF(self->s_format);
1982 return self->s_format;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001983}
1984
1985static PyObject *
1986s_get_size(PyStructObject *self, void *unused)
1987{
Christian Heimes217cfd12007-12-02 14:31:20 +00001988 return PyLong_FromSsize_t(self->s_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001989}
1990
Meador Ingeb14d8c92012-07-23 10:01:29 -05001991PyDoc_STRVAR(s_sizeof__doc__,
1992"S.__sizeof__() -> size of S in memory, in bytes");
1993
1994static PyObject *
Meador Inge90bc2dbc2012-07-28 22:16:39 -05001995s_sizeof(PyStructObject *self, void *unused)
Meador Ingeb14d8c92012-07-23 10:01:29 -05001996{
1997 Py_ssize_t size;
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001998 formatcode *code;
Meador Ingeb14d8c92012-07-23 10:01:29 -05001999
Serhiy Storchaka5c4064e2015-12-19 20:05:25 +02002000 size = _PyObject_SIZE(Py_TYPE(self)) + sizeof(formatcode);
Serhiy Storchakafff61f22013-05-17 10:49:44 +03002001 for (code = self->s_codes; code->fmtdef != NULL; code++)
2002 size += sizeof(formatcode);
Meador Ingeb14d8c92012-07-23 10:01:29 -05002003 return PyLong_FromSsize_t(size);
2004}
2005
Thomas Wouters477c8d52006-05-27 19:21:47 +00002006/* List of functions */
2007
2008static struct PyMethodDef s_methods[] = {
Antoine Pitrou9f146812013-04-27 00:20:04 +02002009 {"iter_unpack", s_iter_unpack, METH_O, s_iter_unpack__doc__},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002010 {"pack", s_pack, METH_VARARGS, s_pack__doc__},
2011 {"pack_into", s_pack_into, METH_VARARGS, s_pack_into__doc__},
2012 {"unpack", s_unpack, METH_O, s_unpack__doc__},
2013 {"unpack_from", (PyCFunction)s_unpack_from, METH_VARARGS|METH_KEYWORDS,
2014 s_unpack_from__doc__},
Meador Ingeb14d8c92012-07-23 10:01:29 -05002015 {"__sizeof__", (PyCFunction)s_sizeof, METH_NOARGS, s_sizeof__doc__},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002016 {NULL, NULL} /* sentinel */
Thomas Wouters477c8d52006-05-27 19:21:47 +00002017};
2018
Victor Stinnerda9ec992010-12-28 13:26:42 +00002019PyDoc_STRVAR(s__doc__,
Alexander Belopolsky0bd003a2010-06-12 19:36:28 +00002020"Struct(fmt) --> compiled struct object\n"
2021"\n"
2022"Return a new Struct object which writes and reads binary data according to\n"
2023"the format string fmt. See help(struct) for more on format strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00002024
2025#define OFF(x) offsetof(PyStructObject, x)
2026
2027static PyGetSetDef s_getsetlist[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002028 {"format", (getter)s_get_format, (setter)NULL, "struct format string", NULL},
2029 {"size", (getter)s_get_size, (setter)NULL, "struct size in bytes", NULL},
2030 {NULL} /* sentinel */
Thomas Wouters477c8d52006-05-27 19:21:47 +00002031};
2032
2033static
2034PyTypeObject PyStructType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002035 PyVarObject_HEAD_INIT(NULL, 0)
2036 "Struct",
2037 sizeof(PyStructObject),
2038 0,
2039 (destructor)s_dealloc, /* tp_dealloc */
2040 0, /* tp_print */
2041 0, /* tp_getattr */
2042 0, /* tp_setattr */
2043 0, /* tp_reserved */
2044 0, /* tp_repr */
2045 0, /* tp_as_number */
2046 0, /* tp_as_sequence */
2047 0, /* tp_as_mapping */
2048 0, /* tp_hash */
2049 0, /* tp_call */
2050 0, /* tp_str */
2051 PyObject_GenericGetAttr, /* tp_getattro */
2052 PyObject_GenericSetAttr, /* tp_setattro */
2053 0, /* tp_as_buffer */
2054 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
2055 s__doc__, /* tp_doc */
2056 0, /* tp_traverse */
2057 0, /* tp_clear */
2058 0, /* tp_richcompare */
2059 offsetof(PyStructObject, weakreflist), /* tp_weaklistoffset */
2060 0, /* tp_iter */
2061 0, /* tp_iternext */
2062 s_methods, /* tp_methods */
2063 NULL, /* tp_members */
2064 s_getsetlist, /* tp_getset */
2065 0, /* tp_base */
2066 0, /* tp_dict */
2067 0, /* tp_descr_get */
2068 0, /* tp_descr_set */
2069 0, /* tp_dictoffset */
2070 s_init, /* tp_init */
2071 PyType_GenericAlloc,/* tp_alloc */
2072 s_new, /* tp_new */
2073 PyObject_Del, /* tp_free */
Thomas Wouters477c8d52006-05-27 19:21:47 +00002074};
2075
Christian Heimesa34706f2008-01-04 03:06:10 +00002076
2077/* ---- Standalone functions ---- */
2078
2079#define MAXCACHE 100
2080static PyObject *cache = NULL;
2081
2082static PyObject *
2083cache_struct(PyObject *fmt)
2084{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002085 PyObject * s_object;
Christian Heimesa34706f2008-01-04 03:06:10 +00002086
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002087 if (cache == NULL) {
2088 cache = PyDict_New();
2089 if (cache == NULL)
2090 return NULL;
2091 }
Christian Heimesa34706f2008-01-04 03:06:10 +00002092
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002093 s_object = PyDict_GetItem(cache, fmt);
2094 if (s_object != NULL) {
2095 Py_INCREF(s_object);
2096 return s_object;
2097 }
Christian Heimesa34706f2008-01-04 03:06:10 +00002098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002099 s_object = PyObject_CallFunctionObjArgs((PyObject *)(&PyStructType), fmt, NULL);
2100 if (s_object != NULL) {
2101 if (PyDict_Size(cache) >= MAXCACHE)
2102 PyDict_Clear(cache);
2103 /* Attempt to cache the result */
2104 if (PyDict_SetItem(cache, fmt, s_object) == -1)
2105 PyErr_Clear();
2106 }
2107 return s_object;
Christian Heimesa34706f2008-01-04 03:06:10 +00002108}
2109
2110PyDoc_STRVAR(clearcache_doc,
2111"Clear the internal cache.");
2112
2113static PyObject *
2114clearcache(PyObject *self)
2115{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002116 Py_CLEAR(cache);
2117 Py_RETURN_NONE;
Christian Heimesa34706f2008-01-04 03:06:10 +00002118}
2119
2120PyDoc_STRVAR(calcsize_doc,
Mark Dickinsonaacfa952010-06-12 15:43:45 +00002121"calcsize(fmt) -> integer\n\
2122\n\
2123Return size in bytes of the struct described by the format string fmt.");
Christian Heimesa34706f2008-01-04 03:06:10 +00002124
2125static PyObject *
2126calcsize(PyObject *self, PyObject *fmt)
2127{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002128 Py_ssize_t n;
2129 PyObject *s_object = cache_struct(fmt);
2130 if (s_object == NULL)
2131 return NULL;
2132 n = ((PyStructObject *)s_object)->s_size;
2133 Py_DECREF(s_object);
2134 return PyLong_FromSsize_t(n);
Christian Heimesa34706f2008-01-04 03:06:10 +00002135}
2136
2137PyDoc_STRVAR(pack_doc,
Mark Dickinsonaacfa952010-06-12 15:43:45 +00002138"pack(fmt, v1, v2, ...) -> bytes\n\
2139\n\
Mark Dickinsonfdb99f12010-06-12 16:30:53 +00002140Return a bytes object containing the values v1, v2, ... packed according\n\
2141to the format string fmt. See help(struct) for more on format strings.");
Christian Heimesa34706f2008-01-04 03:06:10 +00002142
2143static PyObject *
2144pack(PyObject *self, PyObject *args)
2145{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002146 PyObject *s_object, *fmt, *newargs, *result;
2147 Py_ssize_t n = PyTuple_GET_SIZE(args);
Christian Heimesa34706f2008-01-04 03:06:10 +00002148
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002149 if (n == 0) {
2150 PyErr_SetString(PyExc_TypeError, "missing format argument");
2151 return NULL;
2152 }
2153 fmt = PyTuple_GET_ITEM(args, 0);
2154 newargs = PyTuple_GetSlice(args, 1, n);
2155 if (newargs == NULL)
2156 return NULL;
Christian Heimesa34706f2008-01-04 03:06:10 +00002157
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002158 s_object = cache_struct(fmt);
2159 if (s_object == NULL) {
2160 Py_DECREF(newargs);
2161 return NULL;
2162 }
2163 result = s_pack(s_object, newargs);
2164 Py_DECREF(newargs);
2165 Py_DECREF(s_object);
2166 return result;
Christian Heimesa34706f2008-01-04 03:06:10 +00002167}
2168
2169PyDoc_STRVAR(pack_into_doc,
Mark Dickinsonaacfa952010-06-12 15:43:45 +00002170"pack_into(fmt, buffer, offset, v1, v2, ...)\n\
2171\n\
2172Pack the values v1, v2, ... according to the format string fmt and write\n\
2173the packed bytes into the writable buffer buf starting at offset. Note\n\
Mark Dickinsonfdb99f12010-06-12 16:30:53 +00002174that the offset is a required argument. See help(struct) for more\n\
Mark Dickinsonaacfa952010-06-12 15:43:45 +00002175on format strings.");
Christian Heimesa34706f2008-01-04 03:06:10 +00002176
2177static PyObject *
2178pack_into(PyObject *self, PyObject *args)
2179{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002180 PyObject *s_object, *fmt, *newargs, *result;
2181 Py_ssize_t n = PyTuple_GET_SIZE(args);
Christian Heimesa34706f2008-01-04 03:06:10 +00002182
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002183 if (n == 0) {
2184 PyErr_SetString(PyExc_TypeError, "missing format argument");
2185 return NULL;
2186 }
2187 fmt = PyTuple_GET_ITEM(args, 0);
2188 newargs = PyTuple_GetSlice(args, 1, n);
2189 if (newargs == NULL)
2190 return NULL;
Christian Heimesa34706f2008-01-04 03:06:10 +00002191
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002192 s_object = cache_struct(fmt);
2193 if (s_object == NULL) {
2194 Py_DECREF(newargs);
2195 return NULL;
2196 }
2197 result = s_pack_into(s_object, newargs);
2198 Py_DECREF(newargs);
2199 Py_DECREF(s_object);
2200 return result;
Christian Heimesa34706f2008-01-04 03:06:10 +00002201}
2202
2203PyDoc_STRVAR(unpack_doc,
Mark Dickinsonaacfa952010-06-12 15:43:45 +00002204"unpack(fmt, buffer) -> (v1, v2, ...)\n\
2205\n\
2206Return a tuple containing values unpacked according to the format string\n\
Martin Panterb0309912016-04-15 23:03:54 +00002207fmt. The buffer's size in bytes must be calcsize(fmt). See help(struct)\n\
2208for more on format strings.");
Christian Heimesa34706f2008-01-04 03:06:10 +00002209
2210static PyObject *
2211unpack(PyObject *self, PyObject *args)
2212{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002213 PyObject *s_object, *fmt, *inputstr, *result;
Christian Heimesa34706f2008-01-04 03:06:10 +00002214
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002215 if (!PyArg_UnpackTuple(args, "unpack", 2, 2, &fmt, &inputstr))
2216 return NULL;
Christian Heimesa34706f2008-01-04 03:06:10 +00002217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002218 s_object = cache_struct(fmt);
2219 if (s_object == NULL)
2220 return NULL;
2221 result = s_unpack(s_object, inputstr);
2222 Py_DECREF(s_object);
2223 return result;
Christian Heimesa34706f2008-01-04 03:06:10 +00002224}
2225
2226PyDoc_STRVAR(unpack_from_doc,
Mark Dickinsonc6f13962010-06-13 09:17:13 +00002227"unpack_from(fmt, buffer, offset=0) -> (v1, v2, ...)\n\
Mark Dickinsonaacfa952010-06-12 15:43:45 +00002228\n\
2229Return a tuple containing values unpacked according to the format string\n\
Martin Panterb0309912016-04-15 23:03:54 +00002230fmt. The buffer's size, minus offset, must be at least calcsize(fmt).\n\
2231See help(struct) for more on format strings.");
Christian Heimesa34706f2008-01-04 03:06:10 +00002232
2233static PyObject *
2234unpack_from(PyObject *self, PyObject *args, PyObject *kwds)
2235{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002236 PyObject *s_object, *fmt, *newargs, *result;
2237 Py_ssize_t n = PyTuple_GET_SIZE(args);
Christian Heimesa34706f2008-01-04 03:06:10 +00002238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002239 if (n == 0) {
2240 PyErr_SetString(PyExc_TypeError, "missing format argument");
2241 return NULL;
2242 }
2243 fmt = PyTuple_GET_ITEM(args, 0);
2244 newargs = PyTuple_GetSlice(args, 1, n);
2245 if (newargs == NULL)
2246 return NULL;
Christian Heimesa34706f2008-01-04 03:06:10 +00002247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002248 s_object = cache_struct(fmt);
2249 if (s_object == NULL) {
2250 Py_DECREF(newargs);
2251 return NULL;
2252 }
2253 result = s_unpack_from(s_object, newargs, kwds);
2254 Py_DECREF(newargs);
2255 Py_DECREF(s_object);
2256 return result;
Christian Heimesa34706f2008-01-04 03:06:10 +00002257}
2258
Antoine Pitrou9f146812013-04-27 00:20:04 +02002259PyDoc_STRVAR(iter_unpack_doc,
2260"iter_unpack(fmt, buffer) -> iterator(v1, v2, ...)\n\
2261\n\
2262Return an iterator yielding tuples unpacked from the given bytes\n\
2263source according to the format string, like a repeated invocation of\n\
2264unpack_from(). Requires that the bytes length be a multiple of the\n\
2265format struct size.");
2266
2267static PyObject *
2268iter_unpack(PyObject *self, PyObject *args)
2269{
2270 PyObject *s_object, *fmt, *input, *result;
2271
2272 if (!PyArg_ParseTuple(args, "OO:iter_unpack", &fmt, &input))
2273 return NULL;
2274
2275 s_object = cache_struct(fmt);
2276 if (s_object == NULL)
2277 return NULL;
2278 result = s_iter_unpack(s_object, input);
2279 Py_DECREF(s_object);
2280 return result;
2281}
2282
Christian Heimesa34706f2008-01-04 03:06:10 +00002283static struct PyMethodDef module_functions[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002284 {"_clearcache", (PyCFunction)clearcache, METH_NOARGS, clearcache_doc},
2285 {"calcsize", calcsize, METH_O, calcsize_doc},
Antoine Pitrou9f146812013-04-27 00:20:04 +02002286 {"iter_unpack", iter_unpack, METH_VARARGS, iter_unpack_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002287 {"pack", pack, METH_VARARGS, pack_doc},
2288 {"pack_into", pack_into, METH_VARARGS, pack_into_doc},
2289 {"unpack", unpack, METH_VARARGS, unpack_doc},
2290 {"unpack_from", (PyCFunction)unpack_from,
2291 METH_VARARGS|METH_KEYWORDS, unpack_from_doc},
2292 {NULL, NULL} /* sentinel */
Christian Heimesa34706f2008-01-04 03:06:10 +00002293};
2294
2295
Thomas Wouters477c8d52006-05-27 19:21:47 +00002296/* Module initialization */
2297
Christian Heimesa34706f2008-01-04 03:06:10 +00002298PyDoc_STRVAR(module_doc,
2299"Functions to convert between Python values and C structs.\n\
Benjamin Peterson4ae19462008-07-31 15:03:40 +00002300Python bytes objects are used to hold the data representing the C struct\n\
Mark Dickinson40714af2009-10-08 15:59:20 +00002301and also as format strings (explained below) to describe the layout of data\n\
2302in the C struct.\n\
Christian Heimesa34706f2008-01-04 03:06:10 +00002303\n\
2304The optional first format char indicates byte order, size and alignment:\n\
Mark Dickinson40714af2009-10-08 15:59:20 +00002305 @: native order, size & alignment (default)\n\
2306 =: native order, std. size & alignment\n\
2307 <: little-endian, std. size & alignment\n\
2308 >: big-endian, std. size & alignment\n\
2309 !: same as >\n\
Christian Heimesa34706f2008-01-04 03:06:10 +00002310\n\
2311The remaining chars indicate types of args and must match exactly;\n\
2312these can be preceded by a decimal repeat count:\n\
2313 x: pad byte (no data); c:char; b:signed byte; B:unsigned byte;\n\
Mark Dickinson40714af2009-10-08 15:59:20 +00002314 ?: _Bool (requires C99; if not available, char is used instead)\n\
Christian Heimesa34706f2008-01-04 03:06:10 +00002315 h:short; H:unsigned short; i:int; I:unsigned int;\n\
Mark Dickinson7c4e4092016-09-03 17:21:29 +01002316 l:long; L:unsigned long; f:float; d:double; e:half-float.\n\
Christian Heimesa34706f2008-01-04 03:06:10 +00002317Special cases (preceding decimal count indicates length):\n\
2318 s:string (array of char); p: pascal string (with count byte).\n\
Antoine Pitrou45d9c912011-10-06 15:27:40 +02002319Special cases (only available in native format):\n\
2320 n:ssize_t; N:size_t;\n\
Christian Heimesa34706f2008-01-04 03:06:10 +00002321 P:an integer type that is wide enough to hold a pointer.\n\
2322Special case (not in native mode unless 'long long' in platform C):\n\
2323 q:long long; Q:unsigned long long\n\
2324Whitespace between formats is ignored.\n\
2325\n\
2326The variable struct.error is an exception raised on errors.\n");
2327
Martin v. Löwis1a214512008-06-11 05:26:20 +00002328
2329static struct PyModuleDef _structmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002330 PyModuleDef_HEAD_INIT,
2331 "_struct",
2332 module_doc,
2333 -1,
2334 module_functions,
2335 NULL,
2336 NULL,
2337 NULL,
2338 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002339};
2340
Thomas Wouters477c8d52006-05-27 19:21:47 +00002341PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002342PyInit__struct(void)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002343{
Mark Dickinson06817852010-06-12 09:25:13 +00002344 PyObject *m;
Christian Heimesa34706f2008-01-04 03:06:10 +00002345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002346 m = PyModule_Create(&_structmodule);
2347 if (m == NULL)
2348 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002350 Py_TYPE(&PyStructType) = &PyType_Type;
2351 if (PyType_Ready(&PyStructType) < 0)
2352 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002353
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002354 /* Check endian and swap in faster functions */
2355 {
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02002356 const formatdef *native = native_table;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002357 formatdef *other, *ptr;
Christian Heimes743e0cd2012-10-17 23:52:17 +02002358#if PY_LITTLE_ENDIAN
2359 other = lilendian_table;
2360#else
2361 other = bigendian_table;
2362#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002363 /* Scan through the native table, find a matching
2364 entry in the endian table and swap in the
2365 native implementations whenever possible
2366 (64-bit platforms may not have "standard" sizes) */
2367 while (native->format != '\0' && other->format != '\0') {
2368 ptr = other;
2369 while (ptr->format != '\0') {
2370 if (ptr->format == native->format) {
2371 /* Match faster when formats are
2372 listed in the same order */
2373 if (ptr == other)
2374 other++;
2375 /* Only use the trick if the
2376 size matches */
2377 if (ptr->size != native->size)
2378 break;
2379 /* Skip float and double, could be
2380 "unknown" float format */
2381 if (ptr->format == 'd' || ptr->format == 'f')
2382 break;
2383 ptr->pack = native->pack;
2384 ptr->unpack = native->unpack;
2385 break;
2386 }
2387 ptr++;
2388 }
2389 native++;
2390 }
2391 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002393 /* Add some symbolic constants to the module */
2394 if (StructError == NULL) {
2395 StructError = PyErr_NewException("struct.error", NULL, NULL);
2396 if (StructError == NULL)
2397 return NULL;
2398 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002400 Py_INCREF(StructError);
2401 PyModule_AddObject(m, "error", StructError);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002403 Py_INCREF((PyObject*)&PyStructType);
2404 PyModule_AddObject(m, "Struct", (PyObject*)&PyStructType);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002405
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002406 return m;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002407}