blob: 796d1682f094f1498bc3d18c5942d785294d22da [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;
Benjamin Petersona9296e72016-09-07 11:06:17 -070063typedef struct { char c; _Bool x; } st_bool;
Thomas Wouters477c8d52006-05-27 19:21:47 +000064
65#define SHORT_ALIGN (sizeof(st_short) - sizeof(short))
66#define INT_ALIGN (sizeof(st_int) - sizeof(int))
67#define LONG_ALIGN (sizeof(st_long) - sizeof(long))
68#define FLOAT_ALIGN (sizeof(st_float) - sizeof(float))
69#define DOUBLE_ALIGN (sizeof(st_double) - sizeof(double))
70#define VOID_P_ALIGN (sizeof(st_void_p) - sizeof(void *))
Antoine Pitrou45d9c912011-10-06 15:27:40 +020071#define SIZE_T_ALIGN (sizeof(st_size_t) - sizeof(size_t))
Benjamin Petersona9296e72016-09-07 11:06:17 -070072#define BOOL_ALIGN (sizeof(st_bool) - sizeof(_Bool))
Thomas Wouters477c8d52006-05-27 19:21:47 +000073
74/* We can't support q and Q in native mode unless the compiler does;
75 in std mode, they're 8 bytes on all platforms. */
Benjamin Petersonaf580df2016-09-06 10:46:49 -070076typedef struct { char c; long long x; } s_long_long;
77#define LONG_LONG_ALIGN (sizeof(s_long_long) - sizeof(long long))
Thomas Wouters477c8d52006-05-27 19:21:47 +000078
Thomas Wouters477c8d52006-05-27 19:21:47 +000079#ifdef __powerc
80#pragma options align=reset
81#endif
82
Mark Dickinson055a3fb2010-04-03 15:26:31 +000083/* Helper for integer format codes: converts an arbitrary Python object to a
84 PyLongObject if possible, otherwise fails. Caller should decref. */
Thomas Wouters477c8d52006-05-27 19:21:47 +000085
86static PyObject *
87get_pylong(PyObject *v)
88{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000089 assert(v != NULL);
90 if (!PyLong_Check(v)) {
91 /* Not an integer; try to use __index__ to convert. */
92 if (PyIndex_Check(v)) {
93 v = PyNumber_Index(v);
94 if (v == NULL)
95 return NULL;
96 }
97 else {
98 PyErr_SetString(StructError,
99 "required argument is not an integer");
100 return NULL;
101 }
102 }
103 else
104 Py_INCREF(v);
Mark Dickinsonea835e72009-04-19 20:40:33 +0000105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000106 assert(PyLong_Check(v));
107 return v;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000108}
109
Mark Dickinsonea835e72009-04-19 20:40:33 +0000110/* Helper routine to get a C long and raise the appropriate error if it isn't
111 one */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000112
113static int
114get_long(PyObject *v, long *p)
115{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000116 long x;
Mark Dickinsonea835e72009-04-19 20:40:33 +0000117
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000118 v = get_pylong(v);
119 if (v == NULL)
120 return -1;
121 assert(PyLong_Check(v));
122 x = PyLong_AsLong(v);
123 Py_DECREF(v);
124 if (x == (long)-1 && PyErr_Occurred()) {
125 if (PyErr_ExceptionMatches(PyExc_OverflowError))
126 PyErr_SetString(StructError,
127 "argument out of range");
128 return -1;
129 }
130 *p = x;
131 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000132}
133
134
135/* Same, but handling unsigned long */
136
137static int
138get_ulong(PyObject *v, unsigned long *p)
139{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000140 unsigned long x;
Mark Dickinsonea835e72009-04-19 20:40:33 +0000141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000142 v = get_pylong(v);
143 if (v == NULL)
144 return -1;
145 assert(PyLong_Check(v));
146 x = PyLong_AsUnsignedLong(v);
147 Py_DECREF(v);
148 if (x == (unsigned long)-1 && PyErr_Occurred()) {
149 if (PyErr_ExceptionMatches(PyExc_OverflowError))
150 PyErr_SetString(StructError,
151 "argument out of range");
152 return -1;
153 }
154 *p = x;
155 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000156}
157
Thomas Wouters477c8d52006-05-27 19:21:47 +0000158/* Same, but handling native long long. */
159
160static int
Benjamin Petersonaf580df2016-09-06 10:46:49 -0700161get_longlong(PyObject *v, long long *p)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000162{
Benjamin Petersonaf580df2016-09-06 10:46:49 -0700163 long long x;
Mark Dickinson055a3fb2010-04-03 15:26:31 +0000164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000165 v = get_pylong(v);
166 if (v == NULL)
167 return -1;
168 assert(PyLong_Check(v));
169 x = PyLong_AsLongLong(v);
170 Py_DECREF(v);
Benjamin Petersonaf580df2016-09-06 10:46:49 -0700171 if (x == (long long)-1 && PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000172 if (PyErr_ExceptionMatches(PyExc_OverflowError))
173 PyErr_SetString(StructError,
174 "argument out of range");
175 return -1;
176 }
177 *p = x;
178 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000179}
180
181/* Same, but handling native unsigned long long. */
182
183static int
Benjamin Petersonaf580df2016-09-06 10:46:49 -0700184get_ulonglong(PyObject *v, unsigned long long *p)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000185{
Benjamin Petersonaf580df2016-09-06 10:46:49 -0700186 unsigned long long x;
Mark Dickinson055a3fb2010-04-03 15:26:31 +0000187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000188 v = get_pylong(v);
189 if (v == NULL)
190 return -1;
191 assert(PyLong_Check(v));
192 x = PyLong_AsUnsignedLongLong(v);
193 Py_DECREF(v);
Benjamin Petersonaf580df2016-09-06 10:46:49 -0700194 if (x == (unsigned long long)-1 && PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000195 if (PyErr_ExceptionMatches(PyExc_OverflowError))
196 PyErr_SetString(StructError,
197 "argument out of range");
198 return -1;
199 }
200 *p = x;
201 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000202}
203
Antoine Pitrou45d9c912011-10-06 15:27:40 +0200204/* Same, but handling Py_ssize_t */
205
206static int
207get_ssize_t(PyObject *v, Py_ssize_t *p)
208{
209 Py_ssize_t x;
210
211 v = get_pylong(v);
212 if (v == NULL)
213 return -1;
214 assert(PyLong_Check(v));
215 x = PyLong_AsSsize_t(v);
216 Py_DECREF(v);
217 if (x == (Py_ssize_t)-1 && PyErr_Occurred()) {
218 if (PyErr_ExceptionMatches(PyExc_OverflowError))
219 PyErr_SetString(StructError,
220 "argument out of range");
221 return -1;
222 }
223 *p = x;
224 return 0;
225}
226
227/* Same, but handling size_t */
228
229static int
230get_size_t(PyObject *v, size_t *p)
231{
232 size_t x;
233
234 v = get_pylong(v);
235 if (v == NULL)
236 return -1;
237 assert(PyLong_Check(v));
238 x = PyLong_AsSize_t(v);
239 Py_DECREF(v);
240 if (x == (size_t)-1 && PyErr_Occurred()) {
241 if (PyErr_ExceptionMatches(PyExc_OverflowError))
242 PyErr_SetString(StructError,
243 "argument out of range");
244 return -1;
245 }
246 *p = x;
247 return 0;
248}
249
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000250
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000251#define RANGE_ERROR(x, f, flag, mask) return _range_error(f, flag)
252
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000253
Thomas Wouters477c8d52006-05-27 19:21:47 +0000254/* Floating point helpers */
255
256static PyObject *
Mark Dickinson7c4e4092016-09-03 17:21:29 +0100257unpack_halffloat(const char *p, /* start of 2-byte string */
258 int le) /* true for little-endian, false for big-endian */
259{
260 double x;
261
262 x = _PyFloat_Unpack2((unsigned char *)p, le);
263 if (x == -1.0 && PyErr_Occurred()) {
264 return NULL;
265 }
266 return PyFloat_FromDouble(x);
267}
268
269static int
270pack_halffloat(char *p, /* start of 2-byte string */
271 PyObject *v, /* value to pack */
272 int le) /* true for little-endian, false for big-endian */
273{
274 double x = PyFloat_AsDouble(v);
275 if (x == -1.0 && PyErr_Occurred()) {
276 PyErr_SetString(StructError,
277 "required argument is not a float");
278 return -1;
279 }
280 return _PyFloat_Pack2(x, (unsigned char *)p, le);
281}
282
283static PyObject *
Thomas Wouters477c8d52006-05-27 19:21:47 +0000284unpack_float(const char *p, /* start of 4-byte string */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000285 int le) /* true for little-endian, false for big-endian */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000286{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000287 double x;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000289 x = _PyFloat_Unpack4((unsigned char *)p, le);
290 if (x == -1.0 && PyErr_Occurred())
291 return NULL;
292 return PyFloat_FromDouble(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000293}
294
295static PyObject *
296unpack_double(const char *p, /* start of 8-byte string */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000297 int le) /* true for little-endian, false for big-endian */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000298{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000299 double x;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000301 x = _PyFloat_Unpack8((unsigned char *)p, le);
302 if (x == -1.0 && PyErr_Occurred())
303 return NULL;
304 return PyFloat_FromDouble(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000305}
306
307/* Helper to format the range error exceptions */
308static int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000309_range_error(const formatdef *f, int is_unsigned)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000310{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000311 /* ulargest is the largest unsigned value with f->size bytes.
312 * Note that the simpler:
313 * ((size_t)1 << (f->size * 8)) - 1
314 * doesn't work when f->size == sizeof(size_t) because C doesn't
315 * define what happens when a left shift count is >= the number of
316 * bits in the integer being shifted; e.g., on some boxes it doesn't
317 * shift at all when they're equal.
318 */
319 const size_t ulargest = (size_t)-1 >> ((SIZEOF_SIZE_T - f->size)*8);
320 assert(f->size >= 1 && f->size <= SIZEOF_SIZE_T);
321 if (is_unsigned)
322 PyErr_Format(StructError,
323 "'%c' format requires 0 <= number <= %zu",
324 f->format,
325 ulargest);
326 else {
327 const Py_ssize_t largest = (Py_ssize_t)(ulargest >> 1);
328 PyErr_Format(StructError,
329 "'%c' format requires %zd <= number <= %zd",
330 f->format,
331 ~ largest,
332 largest);
333 }
Mark Dickinsonae681df2009-03-21 10:26:31 +0000334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000335 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000336}
337
338
339
340/* A large number of small routines follow, with names of the form
341
342 [bln][up]_TYPE
343
344 [bln] distiguishes among big-endian, little-endian and native.
345 [pu] distiguishes between pack (to struct) and unpack (from struct).
346 TYPE is one of char, byte, ubyte, etc.
347*/
348
349/* Native mode routines. ****************************************************/
350/* NOTE:
351 In all n[up]_<type> routines handling types larger than 1 byte, there is
352 *no* guarantee that the p pointer is properly aligned for each type,
353 therefore memcpy is called. An intermediate variable is used to
354 compensate for big-endian architectures.
355 Normally both the intermediate variable and the memcpy call will be
356 skipped by C optimisation in little-endian architectures (gcc >= 2.91
357 does this). */
358
359static PyObject *
360nu_char(const char *p, const formatdef *f)
361{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000362 return PyBytes_FromStringAndSize(p, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000363}
364
365static PyObject *
366nu_byte(const char *p, const formatdef *f)
367{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000368 return PyLong_FromLong((long) *(signed char *)p);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000369}
370
371static PyObject *
372nu_ubyte(const char *p, const formatdef *f)
373{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000374 return PyLong_FromLong((long) *(unsigned char *)p);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000375}
376
377static PyObject *
378nu_short(const char *p, const formatdef *f)
379{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000380 short x;
381 memcpy((char *)&x, p, sizeof x);
382 return PyLong_FromLong((long)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000383}
384
385static PyObject *
386nu_ushort(const char *p, const formatdef *f)
387{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000388 unsigned short x;
389 memcpy((char *)&x, p, sizeof x);
390 return PyLong_FromLong((long)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000391}
392
393static PyObject *
394nu_int(const char *p, const formatdef *f)
395{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000396 int x;
397 memcpy((char *)&x, p, sizeof x);
398 return PyLong_FromLong((long)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000399}
400
401static PyObject *
402nu_uint(const char *p, const formatdef *f)
403{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000404 unsigned int x;
405 memcpy((char *)&x, p, sizeof x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000406#if (SIZEOF_LONG > SIZEOF_INT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000407 return PyLong_FromLong((long)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000408#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000409 if (x <= ((unsigned int)LONG_MAX))
410 return PyLong_FromLong((long)x);
411 return PyLong_FromUnsignedLong((unsigned long)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000412#endif
413}
414
415static PyObject *
416nu_long(const char *p, const formatdef *f)
417{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000418 long x;
419 memcpy((char *)&x, p, sizeof x);
420 return PyLong_FromLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000421}
422
423static PyObject *
424nu_ulong(const char *p, const formatdef *f)
425{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000426 unsigned long x;
427 memcpy((char *)&x, p, sizeof x);
428 if (x <= LONG_MAX)
429 return PyLong_FromLong((long)x);
430 return PyLong_FromUnsignedLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000431}
432
Antoine Pitrou45d9c912011-10-06 15:27:40 +0200433static PyObject *
434nu_ssize_t(const char *p, const formatdef *f)
435{
436 Py_ssize_t x;
437 memcpy((char *)&x, p, sizeof x);
438 return PyLong_FromSsize_t(x);
439}
440
441static PyObject *
442nu_size_t(const char *p, const formatdef *f)
443{
444 size_t x;
445 memcpy((char *)&x, p, sizeof x);
446 return PyLong_FromSize_t(x);
447}
448
449
Thomas Wouters477c8d52006-05-27 19:21:47 +0000450/* Native mode doesn't support q or Q unless the platform C supports
451 long long (or, on Windows, __int64). */
452
Thomas Wouters477c8d52006-05-27 19:21:47 +0000453static PyObject *
454nu_longlong(const char *p, const formatdef *f)
455{
Benjamin Petersonaf580df2016-09-06 10:46:49 -0700456 long long x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000457 memcpy((char *)&x, p, sizeof x);
458 if (x >= LONG_MIN && x <= LONG_MAX)
Benjamin Petersonaf580df2016-09-06 10:46:49 -0700459 return PyLong_FromLong(Py_SAFE_DOWNCAST(x, long long, long));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 return PyLong_FromLongLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000461}
462
463static PyObject *
464nu_ulonglong(const char *p, const formatdef *f)
465{
Benjamin Petersonaf580df2016-09-06 10:46:49 -0700466 unsigned long long x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000467 memcpy((char *)&x, p, sizeof x);
468 if (x <= LONG_MAX)
Benjamin Petersonaf580df2016-09-06 10:46:49 -0700469 return PyLong_FromLong(Py_SAFE_DOWNCAST(x, unsigned long long, long));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000470 return PyLong_FromUnsignedLongLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000471}
472
Thomas Wouters477c8d52006-05-27 19:21:47 +0000473static PyObject *
Thomas Woutersb2137042007-02-01 18:02:27 +0000474nu_bool(const char *p, const formatdef *f)
475{
Benjamin Petersona9296e72016-09-07 11:06:17 -0700476 _Bool x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 memcpy((char *)&x, p, sizeof x);
478 return PyBool_FromLong(x != 0);
Thomas Woutersb2137042007-02-01 18:02:27 +0000479}
480
481
482static PyObject *
Mark Dickinson7c4e4092016-09-03 17:21:29 +0100483nu_halffloat(const char *p, const formatdef *f)
484{
485#if PY_LITTLE_ENDIAN
486 return unpack_halffloat(p, 1);
487#else
488 return unpack_halffloat(p, 0);
Benjamin Petersone2e792d2016-09-19 22:17:16 -0700489#endif
Mark Dickinson7c4e4092016-09-03 17:21:29 +0100490}
491
492static PyObject *
Thomas Wouters477c8d52006-05-27 19:21:47 +0000493nu_float(const char *p, const formatdef *f)
494{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000495 float x;
496 memcpy((char *)&x, p, sizeof x);
497 return PyFloat_FromDouble((double)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000498}
499
500static PyObject *
501nu_double(const char *p, const formatdef *f)
502{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000503 double x;
504 memcpy((char *)&x, p, sizeof x);
505 return PyFloat_FromDouble(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000506}
507
508static PyObject *
509nu_void_p(const char *p, const formatdef *f)
510{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 void *x;
512 memcpy((char *)&x, p, sizeof x);
513 return PyLong_FromVoidPtr(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000514}
515
516static int
517np_byte(char *p, PyObject *v, const formatdef *f)
518{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 long x;
520 if (get_long(v, &x) < 0)
521 return -1;
522 if (x < -128 || x > 127){
523 PyErr_SetString(StructError,
524 "byte format requires -128 <= number <= 127");
525 return -1;
526 }
527 *p = (char)x;
528 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000529}
530
531static int
532np_ubyte(char *p, PyObject *v, const formatdef *f)
533{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 long x;
535 if (get_long(v, &x) < 0)
536 return -1;
537 if (x < 0 || x > 255){
538 PyErr_SetString(StructError,
539 "ubyte format requires 0 <= number <= 255");
540 return -1;
541 }
542 *p = (char)x;
543 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000544}
545
546static int
547np_char(char *p, PyObject *v, const formatdef *f)
548{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000549 if (!PyBytes_Check(v) || PyBytes_Size(v) != 1) {
550 PyErr_SetString(StructError,
Victor Stinnerda9ec992010-12-28 13:26:42 +0000551 "char format requires a bytes object of length 1");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000552 return -1;
553 }
554 *p = *PyBytes_AsString(v);
555 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000556}
557
558static int
559np_short(char *p, PyObject *v, const formatdef *f)
560{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561 long x;
562 short y;
563 if (get_long(v, &x) < 0)
564 return -1;
565 if (x < SHRT_MIN || x > SHRT_MAX){
566 PyErr_SetString(StructError,
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200567 "short format requires " Py_STRINGIFY(SHRT_MIN)
568 " <= number <= " Py_STRINGIFY(SHRT_MAX));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000569 return -1;
570 }
571 y = (short)x;
572 memcpy(p, (char *)&y, sizeof y);
573 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000574}
575
576static int
577np_ushort(char *p, PyObject *v, const formatdef *f)
578{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000579 long x;
580 unsigned short y;
581 if (get_long(v, &x) < 0)
582 return -1;
583 if (x < 0 || x > USHRT_MAX){
584 PyErr_SetString(StructError,
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200585 "ushort format requires 0 <= number <= "
586 Py_STRINGIFY(USHRT_MAX));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000587 return -1;
588 }
589 y = (unsigned short)x;
590 memcpy(p, (char *)&y, sizeof y);
591 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000592}
593
594static int
595np_int(char *p, PyObject *v, const formatdef *f)
596{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000597 long x;
598 int y;
599 if (get_long(v, &x) < 0)
600 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000601#if (SIZEOF_LONG > SIZEOF_INT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000602 if ((x < ((long)INT_MIN)) || (x > ((long)INT_MAX)))
603 RANGE_ERROR(x, f, 0, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000604#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000605 y = (int)x;
606 memcpy(p, (char *)&y, sizeof y);
607 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000608}
609
610static int
611np_uint(char *p, PyObject *v, const formatdef *f)
612{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000613 unsigned long x;
614 unsigned int y;
615 if (get_ulong(v, &x) < 0)
616 return -1;
617 y = (unsigned int)x;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000618#if (SIZEOF_LONG > SIZEOF_INT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 if (x > ((unsigned long)UINT_MAX))
620 RANGE_ERROR(y, f, 1, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000621#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 memcpy(p, (char *)&y, sizeof y);
623 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000624}
625
626static int
627np_long(char *p, PyObject *v, const formatdef *f)
628{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000629 long x;
630 if (get_long(v, &x) < 0)
631 return -1;
632 memcpy(p, (char *)&x, sizeof x);
633 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000634}
635
636static int
637np_ulong(char *p, PyObject *v, const formatdef *f)
638{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000639 unsigned long x;
640 if (get_ulong(v, &x) < 0)
641 return -1;
642 memcpy(p, (char *)&x, sizeof x);
643 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000644}
645
Antoine Pitrou45d9c912011-10-06 15:27:40 +0200646static int
647np_ssize_t(char *p, PyObject *v, const formatdef *f)
648{
649 Py_ssize_t x;
650 if (get_ssize_t(v, &x) < 0)
651 return -1;
652 memcpy(p, (char *)&x, sizeof x);
653 return 0;
654}
655
656static int
657np_size_t(char *p, PyObject *v, const formatdef *f)
658{
659 size_t x;
660 if (get_size_t(v, &x) < 0)
661 return -1;
662 memcpy(p, (char *)&x, sizeof x);
663 return 0;
664}
665
Thomas Wouters477c8d52006-05-27 19:21:47 +0000666static int
667np_longlong(char *p, PyObject *v, const formatdef *f)
668{
Benjamin Petersonaf580df2016-09-06 10:46:49 -0700669 long long x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 if (get_longlong(v, &x) < 0)
671 return -1;
672 memcpy(p, (char *)&x, sizeof x);
673 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000674}
675
676static int
677np_ulonglong(char *p, PyObject *v, const formatdef *f)
678{
Benjamin Petersonaf580df2016-09-06 10:46:49 -0700679 unsigned long long x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000680 if (get_ulonglong(v, &x) < 0)
681 return -1;
682 memcpy(p, (char *)&x, sizeof x);
683 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000684}
Thomas Wouters477c8d52006-05-27 19:21:47 +0000685
Thomas Woutersb2137042007-02-01 18:02:27 +0000686
687static int
688np_bool(char *p, PyObject *v, const formatdef *f)
689{
Benjamin Petersonde73c452010-07-07 18:54:59 +0000690 int y;
Benjamin Petersona9296e72016-09-07 11:06:17 -0700691 _Bool x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000692 y = PyObject_IsTrue(v);
Benjamin Petersonde73c452010-07-07 18:54:59 +0000693 if (y < 0)
694 return -1;
695 x = y;
696 memcpy(p, (char *)&x, sizeof x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000697 return 0;
Thomas Woutersb2137042007-02-01 18:02:27 +0000698}
699
Thomas Wouters477c8d52006-05-27 19:21:47 +0000700static int
Mark Dickinson7c4e4092016-09-03 17:21:29 +0100701np_halffloat(char *p, PyObject *v, const formatdef *f)
702{
703#if PY_LITTLE_ENDIAN
704 return pack_halffloat(p, v, 1);
705#else
706 return pack_halffloat(p, v, 0);
707#endif
708}
709
710static int
Thomas Wouters477c8d52006-05-27 19:21:47 +0000711np_float(char *p, PyObject *v, const formatdef *f)
712{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000713 float x = (float)PyFloat_AsDouble(v);
714 if (x == -1 && PyErr_Occurred()) {
715 PyErr_SetString(StructError,
716 "required argument is not a float");
717 return -1;
718 }
719 memcpy(p, (char *)&x, sizeof x);
720 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000721}
722
723static int
724np_double(char *p, PyObject *v, const formatdef *f)
725{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000726 double x = PyFloat_AsDouble(v);
727 if (x == -1 && PyErr_Occurred()) {
728 PyErr_SetString(StructError,
729 "required argument is not a float");
730 return -1;
731 }
732 memcpy(p, (char *)&x, sizeof(double));
733 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000734}
735
736static int
737np_void_p(char *p, PyObject *v, const formatdef *f)
738{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 void *x;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000740
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000741 v = get_pylong(v);
742 if (v == NULL)
743 return -1;
744 assert(PyLong_Check(v));
745 x = PyLong_AsVoidPtr(v);
746 Py_DECREF(v);
747 if (x == NULL && PyErr_Occurred())
748 return -1;
749 memcpy(p, (char *)&x, sizeof x);
750 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000751}
752
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200753static const formatdef native_table[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000754 {'x', sizeof(char), 0, NULL},
755 {'b', sizeof(char), 0, nu_byte, np_byte},
756 {'B', sizeof(char), 0, nu_ubyte, np_ubyte},
757 {'c', sizeof(char), 0, nu_char, np_char},
758 {'s', sizeof(char), 0, NULL},
759 {'p', sizeof(char), 0, NULL},
760 {'h', sizeof(short), SHORT_ALIGN, nu_short, np_short},
761 {'H', sizeof(short), SHORT_ALIGN, nu_ushort, np_ushort},
762 {'i', sizeof(int), INT_ALIGN, nu_int, np_int},
763 {'I', sizeof(int), INT_ALIGN, nu_uint, np_uint},
764 {'l', sizeof(long), LONG_ALIGN, nu_long, np_long},
765 {'L', sizeof(long), LONG_ALIGN, nu_ulong, np_ulong},
Antoine Pitrou45d9c912011-10-06 15:27:40 +0200766 {'n', sizeof(size_t), SIZE_T_ALIGN, nu_ssize_t, np_ssize_t},
767 {'N', sizeof(size_t), SIZE_T_ALIGN, nu_size_t, np_size_t},
Benjamin Petersonaf580df2016-09-06 10:46:49 -0700768 {'q', sizeof(long long), LONG_LONG_ALIGN, nu_longlong, np_longlong},
769 {'Q', sizeof(long long), LONG_LONG_ALIGN, nu_ulonglong,np_ulonglong},
Benjamin Petersona9296e72016-09-07 11:06:17 -0700770 {'?', sizeof(_Bool), BOOL_ALIGN, nu_bool, np_bool},
Mark Dickinson7c4e4092016-09-03 17:21:29 +0100771 {'e', sizeof(short), SHORT_ALIGN, nu_halffloat, np_halffloat},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000772 {'f', sizeof(float), FLOAT_ALIGN, nu_float, np_float},
773 {'d', sizeof(double), DOUBLE_ALIGN, nu_double, np_double},
774 {'P', sizeof(void *), VOID_P_ALIGN, nu_void_p, np_void_p},
775 {0}
Thomas Wouters477c8d52006-05-27 19:21:47 +0000776};
777
778/* Big-endian routines. *****************************************************/
779
780static PyObject *
781bu_int(const char *p, const formatdef *f)
782{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000783 long x = 0;
784 Py_ssize_t i = f->size;
785 const unsigned char *bytes = (const unsigned char *)p;
786 do {
787 x = (x<<8) | *bytes++;
788 } while (--i > 0);
789 /* Extend the sign bit. */
790 if (SIZEOF_LONG > f->size)
791 x |= -(x & (1L << ((8 * f->size) - 1)));
792 return PyLong_FromLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000793}
794
795static PyObject *
796bu_uint(const char *p, const formatdef *f)
797{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000798 unsigned long x = 0;
799 Py_ssize_t i = f->size;
800 const unsigned char *bytes = (const unsigned char *)p;
801 do {
802 x = (x<<8) | *bytes++;
803 } while (--i > 0);
804 if (x <= LONG_MAX)
805 return PyLong_FromLong((long)x);
806 return PyLong_FromUnsignedLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000807}
808
809static PyObject *
810bu_longlong(const char *p, const formatdef *f)
811{
Benjamin Petersonaf580df2016-09-06 10:46:49 -0700812 long long x = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000813 Py_ssize_t i = f->size;
814 const unsigned char *bytes = (const unsigned char *)p;
815 do {
816 x = (x<<8) | *bytes++;
817 } while (--i > 0);
818 /* Extend the sign bit. */
819 if (SIZEOF_LONG_LONG > f->size)
Benjamin Petersonaf580df2016-09-06 10:46:49 -0700820 x |= -(x & ((long long)1 << ((8 * f->size) - 1)));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000821 if (x >= LONG_MIN && x <= LONG_MAX)
Benjamin Petersonaf580df2016-09-06 10:46:49 -0700822 return PyLong_FromLong(Py_SAFE_DOWNCAST(x, long long, long));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 return PyLong_FromLongLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000824}
825
826static PyObject *
827bu_ulonglong(const char *p, const formatdef *f)
828{
Benjamin Petersonaf580df2016-09-06 10:46:49 -0700829 unsigned long long x = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 Py_ssize_t i = f->size;
831 const unsigned char *bytes = (const unsigned char *)p;
832 do {
833 x = (x<<8) | *bytes++;
834 } while (--i > 0);
835 if (x <= LONG_MAX)
Benjamin Petersonaf580df2016-09-06 10:46:49 -0700836 return PyLong_FromLong(Py_SAFE_DOWNCAST(x, unsigned long long, long));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000837 return PyLong_FromUnsignedLongLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000838}
839
840static PyObject *
Mark Dickinson7c4e4092016-09-03 17:21:29 +0100841bu_halffloat(const char *p, const formatdef *f)
842{
843 return unpack_halffloat(p, 0);
844}
845
846static PyObject *
Thomas Wouters477c8d52006-05-27 19:21:47 +0000847bu_float(const char *p, const formatdef *f)
848{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 return unpack_float(p, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000850}
851
852static PyObject *
853bu_double(const char *p, const formatdef *f)
854{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 return unpack_double(p, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000856}
857
Thomas Woutersb2137042007-02-01 18:02:27 +0000858static PyObject *
859bu_bool(const char *p, const formatdef *f)
860{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000861 char x;
862 memcpy((char *)&x, p, sizeof x);
863 return PyBool_FromLong(x != 0);
Thomas Woutersb2137042007-02-01 18:02:27 +0000864}
865
Thomas Wouters477c8d52006-05-27 19:21:47 +0000866static int
867bp_int(char *p, PyObject *v, const formatdef *f)
868{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000869 long x;
870 Py_ssize_t i;
871 if (get_long(v, &x) < 0)
872 return -1;
873 i = f->size;
874 if (i != SIZEOF_LONG) {
875 if ((i == 2) && (x < -32768 || x > 32767))
876 RANGE_ERROR(x, f, 0, 0xffffL);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000877#if (SIZEOF_LONG != 4)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000878 else if ((i == 4) && (x < -2147483648L || x > 2147483647L))
879 RANGE_ERROR(x, f, 0, 0xffffffffL);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000880#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 }
882 do {
883 p[--i] = (char)x;
884 x >>= 8;
885 } while (i > 0);
886 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000887}
888
889static int
890bp_uint(char *p, PyObject *v, const formatdef *f)
891{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000892 unsigned long x;
893 Py_ssize_t i;
894 if (get_ulong(v, &x) < 0)
895 return -1;
896 i = f->size;
897 if (i != SIZEOF_LONG) {
898 unsigned long maxint = 1;
899 maxint <<= (unsigned long)(i * 8);
900 if (x >= maxint)
901 RANGE_ERROR(x, f, 1, maxint - 1);
902 }
903 do {
904 p[--i] = (char)x;
905 x >>= 8;
906 } while (i > 0);
907 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000908}
909
910static int
911bp_longlong(char *p, PyObject *v, const formatdef *f)
912{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 int res;
914 v = get_pylong(v);
915 if (v == NULL)
916 return -1;
917 res = _PyLong_AsByteArray((PyLongObject *)v,
918 (unsigned char *)p,
919 8,
920 0, /* little_endian */
921 1 /* signed */);
922 Py_DECREF(v);
923 return res;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000924}
925
926static int
927bp_ulonglong(char *p, PyObject *v, const formatdef *f)
928{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000929 int res;
930 v = get_pylong(v);
931 if (v == NULL)
932 return -1;
933 res = _PyLong_AsByteArray((PyLongObject *)v,
934 (unsigned char *)p,
935 8,
936 0, /* little_endian */
937 0 /* signed */);
938 Py_DECREF(v);
939 return res;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000940}
941
942static int
Mark Dickinson7c4e4092016-09-03 17:21:29 +0100943bp_halffloat(char *p, PyObject *v, const formatdef *f)
944{
945 return pack_halffloat(p, v, 0);
946}
947
948static int
Thomas Wouters477c8d52006-05-27 19:21:47 +0000949bp_float(char *p, PyObject *v, const formatdef *f)
950{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000951 double x = PyFloat_AsDouble(v);
952 if (x == -1 && PyErr_Occurred()) {
953 PyErr_SetString(StructError,
954 "required argument is not a float");
955 return -1;
956 }
957 return _PyFloat_Pack4(x, (unsigned char *)p, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000958}
959
960static int
961bp_double(char *p, PyObject *v, const formatdef *f)
962{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000963 double x = PyFloat_AsDouble(v);
964 if (x == -1 && PyErr_Occurred()) {
965 PyErr_SetString(StructError,
966 "required argument is not a float");
967 return -1;
968 }
969 return _PyFloat_Pack8(x, (unsigned char *)p, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000970}
971
Thomas Woutersb2137042007-02-01 18:02:27 +0000972static int
973bp_bool(char *p, PyObject *v, const formatdef *f)
974{
Mark Dickinsoneff5d852010-07-18 07:29:02 +0000975 int y;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000976 y = PyObject_IsTrue(v);
Benjamin Petersonde73c452010-07-07 18:54:59 +0000977 if (y < 0)
978 return -1;
Mark Dickinsoneff5d852010-07-18 07:29:02 +0000979 *p = (char)y;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000980 return 0;
Thomas Woutersb2137042007-02-01 18:02:27 +0000981}
982
Thomas Wouters477c8d52006-05-27 19:21:47 +0000983static formatdef bigendian_table[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000984 {'x', 1, 0, NULL},
985 {'b', 1, 0, nu_byte, np_byte},
986 {'B', 1, 0, nu_ubyte, np_ubyte},
987 {'c', 1, 0, nu_char, np_char},
988 {'s', 1, 0, NULL},
989 {'p', 1, 0, NULL},
990 {'h', 2, 0, bu_int, bp_int},
991 {'H', 2, 0, bu_uint, bp_uint},
992 {'i', 4, 0, bu_int, bp_int},
993 {'I', 4, 0, bu_uint, bp_uint},
994 {'l', 4, 0, bu_int, bp_int},
995 {'L', 4, 0, bu_uint, bp_uint},
996 {'q', 8, 0, bu_longlong, bp_longlong},
997 {'Q', 8, 0, bu_ulonglong, bp_ulonglong},
998 {'?', 1, 0, bu_bool, bp_bool},
Mark Dickinson7c4e4092016-09-03 17:21:29 +0100999 {'e', 2, 0, bu_halffloat, bp_halffloat},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001000 {'f', 4, 0, bu_float, bp_float},
1001 {'d', 8, 0, bu_double, bp_double},
1002 {0}
Thomas Wouters477c8d52006-05-27 19:21:47 +00001003};
1004
1005/* Little-endian routines. *****************************************************/
1006
1007static PyObject *
1008lu_int(const char *p, const formatdef *f)
1009{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001010 long x = 0;
1011 Py_ssize_t i = f->size;
1012 const unsigned char *bytes = (const unsigned char *)p;
1013 do {
1014 x = (x<<8) | bytes[--i];
1015 } while (i > 0);
1016 /* Extend the sign bit. */
1017 if (SIZEOF_LONG > f->size)
1018 x |= -(x & (1L << ((8 * f->size) - 1)));
1019 return PyLong_FromLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001020}
1021
1022static PyObject *
1023lu_uint(const char *p, const formatdef *f)
1024{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001025 unsigned long x = 0;
1026 Py_ssize_t i = f->size;
1027 const unsigned char *bytes = (const unsigned char *)p;
1028 do {
1029 x = (x<<8) | bytes[--i];
1030 } while (i > 0);
1031 if (x <= LONG_MAX)
1032 return PyLong_FromLong((long)x);
1033 return PyLong_FromUnsignedLong((long)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001034}
1035
1036static PyObject *
1037lu_longlong(const char *p, const formatdef *f)
1038{
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001039 long long x = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 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 /* Extend the sign bit. */
1046 if (SIZEOF_LONG_LONG > f->size)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001047 x |= -(x & ((long long)1 << ((8 * f->size) - 1)));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 if (x >= LONG_MIN && x <= LONG_MAX)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001049 return PyLong_FromLong(Py_SAFE_DOWNCAST(x, long long, long));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 return PyLong_FromLongLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001051}
1052
1053static PyObject *
1054lu_ulonglong(const char *p, const formatdef *f)
1055{
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001056 unsigned long long x = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001057 Py_ssize_t i = f->size;
1058 const unsigned char *bytes = (const unsigned char *)p;
1059 do {
1060 x = (x<<8) | bytes[--i];
1061 } while (i > 0);
1062 if (x <= LONG_MAX)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001063 return PyLong_FromLong(Py_SAFE_DOWNCAST(x, unsigned long long, long));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001064 return PyLong_FromUnsignedLongLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001065}
1066
1067static PyObject *
Mark Dickinson7c4e4092016-09-03 17:21:29 +01001068lu_halffloat(const char *p, const formatdef *f)
1069{
1070 return unpack_halffloat(p, 1);
1071}
1072
1073static PyObject *
Thomas Wouters477c8d52006-05-27 19:21:47 +00001074lu_float(const char *p, const formatdef *f)
1075{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001076 return unpack_float(p, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001077}
1078
1079static PyObject *
1080lu_double(const char *p, const formatdef *f)
1081{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 return unpack_double(p, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001083}
1084
1085static int
1086lp_int(char *p, PyObject *v, const formatdef *f)
1087{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001088 long x;
1089 Py_ssize_t i;
1090 if (get_long(v, &x) < 0)
1091 return -1;
1092 i = f->size;
1093 if (i != SIZEOF_LONG) {
1094 if ((i == 2) && (x < -32768 || x > 32767))
1095 RANGE_ERROR(x, f, 0, 0xffffL);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001096#if (SIZEOF_LONG != 4)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001097 else if ((i == 4) && (x < -2147483648L || x > 2147483647L))
1098 RANGE_ERROR(x, f, 0, 0xffffffffL);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001099#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001100 }
1101 do {
1102 *p++ = (char)x;
1103 x >>= 8;
1104 } while (--i > 0);
1105 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001106}
1107
1108static int
1109lp_uint(char *p, PyObject *v, const formatdef *f)
1110{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001111 unsigned long x;
1112 Py_ssize_t i;
1113 if (get_ulong(v, &x) < 0)
1114 return -1;
1115 i = f->size;
1116 if (i != SIZEOF_LONG) {
1117 unsigned long maxint = 1;
1118 maxint <<= (unsigned long)(i * 8);
1119 if (x >= maxint)
1120 RANGE_ERROR(x, f, 1, maxint - 1);
1121 }
1122 do {
1123 *p++ = (char)x;
1124 x >>= 8;
1125 } while (--i > 0);
1126 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001127}
1128
1129static int
1130lp_longlong(char *p, PyObject *v, const formatdef *f)
1131{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001132 int res;
1133 v = get_pylong(v);
1134 if (v == NULL)
1135 return -1;
1136 res = _PyLong_AsByteArray((PyLongObject*)v,
1137 (unsigned char *)p,
1138 8,
1139 1, /* little_endian */
1140 1 /* signed */);
1141 Py_DECREF(v);
1142 return res;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001143}
1144
1145static int
1146lp_ulonglong(char *p, PyObject *v, const formatdef *f)
1147{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001148 int res;
1149 v = get_pylong(v);
1150 if (v == NULL)
1151 return -1;
1152 res = _PyLong_AsByteArray((PyLongObject*)v,
1153 (unsigned char *)p,
1154 8,
1155 1, /* little_endian */
1156 0 /* signed */);
1157 Py_DECREF(v);
1158 return res;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001159}
1160
1161static int
Mark Dickinson7c4e4092016-09-03 17:21:29 +01001162lp_halffloat(char *p, PyObject *v, const formatdef *f)
1163{
1164 return pack_halffloat(p, v, 1);
1165}
1166
1167static int
Thomas Wouters477c8d52006-05-27 19:21:47 +00001168lp_float(char *p, PyObject *v, const formatdef *f)
1169{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001170 double x = PyFloat_AsDouble(v);
1171 if (x == -1 && PyErr_Occurred()) {
1172 PyErr_SetString(StructError,
1173 "required argument is not a float");
1174 return -1;
1175 }
1176 return _PyFloat_Pack4(x, (unsigned char *)p, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001177}
1178
1179static int
1180lp_double(char *p, PyObject *v, const formatdef *f)
1181{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 double x = PyFloat_AsDouble(v);
1183 if (x == -1 && PyErr_Occurred()) {
1184 PyErr_SetString(StructError,
1185 "required argument is not a float");
1186 return -1;
1187 }
1188 return _PyFloat_Pack8(x, (unsigned char *)p, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001189}
1190
1191static formatdef lilendian_table[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001192 {'x', 1, 0, NULL},
1193 {'b', 1, 0, nu_byte, np_byte},
1194 {'B', 1, 0, nu_ubyte, np_ubyte},
1195 {'c', 1, 0, nu_char, np_char},
1196 {'s', 1, 0, NULL},
1197 {'p', 1, 0, NULL},
1198 {'h', 2, 0, lu_int, lp_int},
1199 {'H', 2, 0, lu_uint, lp_uint},
1200 {'i', 4, 0, lu_int, lp_int},
1201 {'I', 4, 0, lu_uint, lp_uint},
1202 {'l', 4, 0, lu_int, lp_int},
1203 {'L', 4, 0, lu_uint, lp_uint},
1204 {'q', 8, 0, lu_longlong, lp_longlong},
1205 {'Q', 8, 0, lu_ulonglong, lp_ulonglong},
1206 {'?', 1, 0, bu_bool, bp_bool}, /* Std rep not endian dep,
1207 but potentially different from native rep -- reuse bx_bool funcs. */
Mark Dickinson7c4e4092016-09-03 17:21:29 +01001208 {'e', 2, 0, lu_halffloat, lp_halffloat},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001209 {'f', 4, 0, lu_float, lp_float},
1210 {'d', 8, 0, lu_double, lp_double},
1211 {0}
Thomas Wouters477c8d52006-05-27 19:21:47 +00001212};
1213
1214
1215static const formatdef *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001216whichtable(const char **pfmt)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001217{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001218 const char *fmt = (*pfmt)++; /* May be backed out of later */
1219 switch (*fmt) {
1220 case '<':
1221 return lilendian_table;
1222 case '>':
1223 case '!': /* Network byte order is big-endian */
1224 return bigendian_table;
Ezio Melotti42da6632011-03-15 05:18:48 +02001225 case '=': { /* Host byte order -- different from native in alignment! */
Christian Heimes743e0cd2012-10-17 23:52:17 +02001226#if PY_LITTLE_ENDIAN
1227 return lilendian_table;
1228#else
1229 return bigendian_table;
1230#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001231 }
1232 default:
1233 --*pfmt; /* Back out of pointer increment */
1234 /* Fall through */
1235 case '@':
1236 return native_table;
1237 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001238}
1239
1240
1241/* Get the table entry for a format code */
1242
1243static const formatdef *
1244getentry(int c, const formatdef *f)
1245{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001246 for (; f->format != '\0'; f++) {
1247 if (f->format == c) {
1248 return f;
1249 }
1250 }
1251 PyErr_SetString(StructError, "bad char in struct format");
1252 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001253}
1254
1255
Mark Dickinsonb72e6862010-06-11 19:50:30 +00001256/* Align a size according to a format code. Return -1 on overflow. */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001257
Mark Dickinsoneac0e682010-06-11 19:05:08 +00001258static Py_ssize_t
Thomas Wouters477c8d52006-05-27 19:21:47 +00001259align(Py_ssize_t size, char c, const formatdef *e)
1260{
Mark Dickinsonb72e6862010-06-11 19:50:30 +00001261 Py_ssize_t extra;
1262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 if (e->format == c) {
Mark Dickinsonb72e6862010-06-11 19:50:30 +00001264 if (e->alignment && size > 0) {
1265 extra = (e->alignment - 1) - (size - 1) % (e->alignment);
1266 if (extra > PY_SSIZE_T_MAX - size)
1267 return -1;
1268 size += extra;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001269 }
1270 }
1271 return size;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001272}
1273
Antoine Pitrou9f146812013-04-27 00:20:04 +02001274/*
1275 * Struct object implementation.
1276 */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001277
1278/* calculate the size of a format string */
1279
1280static int
1281prepare_s(PyStructObject *self)
1282{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001283 const formatdef *f;
1284 const formatdef *e;
1285 formatcode *codes;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001287 const char *s;
1288 const char *fmt;
1289 char c;
Victor Stinner706768c2014-08-16 01:03:39 +02001290 Py_ssize_t size, len, num, itemsize;
1291 size_t ncodes;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001293 fmt = PyBytes_AS_STRING(self->s_format);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001294
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001295 f = whichtable(&fmt);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001297 s = fmt;
1298 size = 0;
1299 len = 0;
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001300 ncodes = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001301 while ((c = *s++) != '\0') {
Antoine Pitrou4de74572013-02-09 23:11:27 +01001302 if (Py_ISSPACE(Py_CHARMASK(c)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001303 continue;
1304 if ('0' <= c && c <= '9') {
1305 num = c - '0';
1306 while ('0' <= (c = *s++) && c <= '9') {
Mark Dickinsonab4096f2010-06-11 16:56:34 +00001307 /* overflow-safe version of
1308 if (num*10 + (c - '0') > PY_SSIZE_T_MAX) { ... } */
1309 if (num >= PY_SSIZE_T_MAX / 10 && (
1310 num > PY_SSIZE_T_MAX / 10 ||
Mark Dickinsonb72e6862010-06-11 19:50:30 +00001311 (c - '0') > PY_SSIZE_T_MAX % 10))
1312 goto overflow;
Mark Dickinsonab4096f2010-06-11 16:56:34 +00001313 num = num*10 + (c - '0');
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001314 }
Alexander Belopolsky177e8532010-06-11 16:04:59 +00001315 if (c == '\0') {
1316 PyErr_SetString(StructError,
1317 "repeat count given without format specifier");
1318 return -1;
1319 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001320 }
1321 else
1322 num = 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001324 e = getentry(c, f);
1325 if (e == NULL)
1326 return -1;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001328 switch (c) {
1329 case 's': /* fall through */
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001330 case 'p': len++; ncodes++; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001331 case 'x': break;
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001332 default: len += num; if (num) ncodes++; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001333 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001335 itemsize = e->size;
1336 size = align(size, c, e);
Mark Dickinsonb72e6862010-06-11 19:50:30 +00001337 if (size == -1)
1338 goto overflow;
1339
1340 /* if (size + num * itemsize > PY_SSIZE_T_MAX) { ... } */
1341 if (num > (PY_SSIZE_T_MAX - size) / itemsize)
1342 goto overflow;
1343 size += num * itemsize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001344 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001346 /* check for overflow */
Victor Stinner706768c2014-08-16 01:03:39 +02001347 if ((ncodes + 1) > ((size_t)PY_SSIZE_T_MAX / sizeof(formatcode))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001348 PyErr_NoMemory();
1349 return -1;
1350 }
Amaury Forgeot d'Arc35c86582008-06-17 21:11:29 +00001351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001352 self->s_size = size;
1353 self->s_len = len;
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001354 codes = PyMem_MALLOC((ncodes + 1) * sizeof(formatcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001355 if (codes == NULL) {
1356 PyErr_NoMemory();
1357 return -1;
1358 }
Mark Dickinsoncf28b952010-07-29 21:41:59 +00001359 /* Free any s_codes value left over from a previous initialization. */
1360 if (self->s_codes != NULL)
1361 PyMem_FREE(self->s_codes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001362 self->s_codes = codes;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001364 s = fmt;
1365 size = 0;
1366 while ((c = *s++) != '\0') {
Antoine Pitrou4de74572013-02-09 23:11:27 +01001367 if (Py_ISSPACE(Py_CHARMASK(c)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001368 continue;
1369 if ('0' <= c && c <= '9') {
1370 num = c - '0';
1371 while ('0' <= (c = *s++) && c <= '9')
1372 num = num*10 + (c - '0');
1373 if (c == '\0')
1374 break;
1375 }
1376 else
1377 num = 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001379 e = getentry(c, f);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001381 size = align(size, c, e);
1382 if (c == 's' || c == 'p') {
1383 codes->offset = size;
1384 codes->size = num;
1385 codes->fmtdef = e;
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001386 codes->repeat = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001387 codes++;
1388 size += num;
1389 } else if (c == 'x') {
1390 size += num;
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001391 } else if (num) {
1392 codes->offset = size;
1393 codes->size = e->size;
1394 codes->fmtdef = e;
1395 codes->repeat = num;
1396 codes++;
1397 size += e->size * num;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001398 }
1399 }
1400 codes->fmtdef = NULL;
1401 codes->offset = size;
1402 codes->size = 0;
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001403 codes->repeat = 0;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001404
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001405 return 0;
Mark Dickinsonb72e6862010-06-11 19:50:30 +00001406
1407 overflow:
1408 PyErr_SetString(StructError,
1409 "total struct size too long");
1410 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001411}
1412
1413static PyObject *
1414s_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1415{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001416 PyObject *self;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001418 assert(type != NULL && type->tp_alloc != NULL);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001419
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001420 self = type->tp_alloc(type, 0);
1421 if (self != NULL) {
1422 PyStructObject *s = (PyStructObject*)self;
1423 Py_INCREF(Py_None);
1424 s->s_format = Py_None;
1425 s->s_codes = NULL;
1426 s->s_size = -1;
1427 s->s_len = -1;
1428 }
1429 return self;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001430}
1431
1432static int
1433s_init(PyObject *self, PyObject *args, PyObject *kwds)
1434{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001435 PyStructObject *soself = (PyStructObject *)self;
1436 PyObject *o_format = NULL;
1437 int ret = 0;
1438 static char *kwlist[] = {"format", 0};
Thomas Wouters477c8d52006-05-27 19:21:47 +00001439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001440 assert(PyStruct_Check(self));
Thomas Wouters477c8d52006-05-27 19:21:47 +00001441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001442 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:Struct", kwlist,
1443 &o_format))
1444 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001445
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001446 if (PyUnicode_Check(o_format)) {
1447 o_format = PyUnicode_AsASCIIString(o_format);
1448 if (o_format == NULL)
1449 return -1;
1450 }
1451 /* XXX support buffer interface, too */
1452 else {
1453 Py_INCREF(o_format);
1454 }
Christian Heimesa34706f2008-01-04 03:06:10 +00001455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001456 if (!PyBytes_Check(o_format)) {
1457 Py_DECREF(o_format);
1458 PyErr_Format(PyExc_TypeError,
Victor Stinnerda9ec992010-12-28 13:26:42 +00001459 "Struct() argument 1 must be a bytes object, not %.200s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001460 Py_TYPE(o_format)->tp_name);
1461 return -1;
1462 }
Christian Heimesa34706f2008-01-04 03:06:10 +00001463
Serhiy Storchaka48842712016-04-06 09:45:48 +03001464 Py_XSETREF(soself->s_format, o_format);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001466 ret = prepare_s(soself);
1467 return ret;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001468}
1469
1470static void
1471s_dealloc(PyStructObject *s)
1472{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001473 if (s->weakreflist != NULL)
1474 PyObject_ClearWeakRefs((PyObject *)s);
1475 if (s->s_codes != NULL) {
1476 PyMem_FREE(s->s_codes);
1477 }
1478 Py_XDECREF(s->s_format);
1479 Py_TYPE(s)->tp_free((PyObject *)s);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001480}
1481
1482static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001483s_unpack_internal(PyStructObject *soself, const char *startfrom) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001484 formatcode *code;
1485 Py_ssize_t i = 0;
1486 PyObject *result = PyTuple_New(soself->s_len);
1487 if (result == NULL)
1488 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001490 for (code = soself->s_codes; code->fmtdef != NULL; code++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001491 const formatdef *e = code->fmtdef;
1492 const char *res = startfrom + code->offset;
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001493 Py_ssize_t j = code->repeat;
1494 while (j--) {
1495 PyObject *v;
1496 if (e->format == 's') {
1497 v = PyBytes_FromStringAndSize(res, code->size);
1498 } else if (e->format == 'p') {
1499 Py_ssize_t n = *(unsigned char*)res;
1500 if (n >= code->size)
1501 n = code->size - 1;
1502 v = PyBytes_FromStringAndSize(res + 1, n);
1503 } else {
1504 v = e->unpack(res, e);
1505 }
1506 if (v == NULL)
1507 goto fail;
1508 PyTuple_SET_ITEM(result, i++, v);
1509 res += code->size;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001510 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001511 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001513 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001514fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001515 Py_DECREF(result);
1516 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001517}
1518
1519
1520PyDoc_STRVAR(s_unpack__doc__,
Guido van Rossum913dd0b2007-04-13 03:33:53 +00001521"S.unpack(buffer) -> (v1, v2, ...)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00001522\n\
Mark Dickinsonaacfa952010-06-12 15:43:45 +00001523Return a tuple containing values unpacked according to the format\n\
Martin Panterb0309912016-04-15 23:03:54 +00001524string S.format. The buffer's size in bytes must be S.size. See\n\
1525help(struct) for more on format strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001526
1527static PyObject *
Guido van Rossum98297ee2007-11-06 21:34:58 +00001528s_unpack(PyObject *self, PyObject *input)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001529{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001530 Py_buffer vbuf;
1531 PyObject *result;
1532 PyStructObject *soself = (PyStructObject *)self;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001534 assert(PyStruct_Check(self));
1535 assert(soself->s_codes != NULL);
1536 if (PyObject_GetBuffer(input, &vbuf, PyBUF_SIMPLE) < 0)
1537 return NULL;
1538 if (vbuf.len != soself->s_size) {
1539 PyErr_Format(StructError,
Victor Stinnerda9ec992010-12-28 13:26:42 +00001540 "unpack requires a bytes object of length %zd",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001541 soself->s_size);
1542 PyBuffer_Release(&vbuf);
1543 return NULL;
1544 }
1545 result = s_unpack_internal(soself, vbuf.buf);
1546 PyBuffer_Release(&vbuf);
1547 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001548}
1549
1550PyDoc_STRVAR(s_unpack_from__doc__,
Mark Dickinsonc6f13962010-06-13 09:17:13 +00001551"S.unpack_from(buffer, offset=0) -> (v1, v2, ...)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00001552\n\
Mark Dickinsonaacfa952010-06-12 15:43:45 +00001553Return a tuple containing values unpacked according to the format\n\
Martin Panterb0309912016-04-15 23:03:54 +00001554string S.format. The buffer's size in bytes, minus offset, must be at\n\
1555least S.size. See help(struct) for more on format strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001556
1557static PyObject *
1558s_unpack_from(PyObject *self, PyObject *args, PyObject *kwds)
1559{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001560 static char *kwlist[] = {"buffer", "offset", 0};
Guido van Rossum98297ee2007-11-06 21:34:58 +00001561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001562 PyObject *input;
1563 Py_ssize_t offset = 0;
1564 Py_buffer vbuf;
1565 PyObject *result;
1566 PyStructObject *soself = (PyStructObject *)self;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001568 assert(PyStruct_Check(self));
1569 assert(soself->s_codes != NULL);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001571 if (!PyArg_ParseTupleAndKeywords(args, kwds,
1572 "O|n:unpack_from", kwlist,
1573 &input, &offset))
1574 return NULL;
1575 if (PyObject_GetBuffer(input, &vbuf, PyBUF_SIMPLE) < 0)
1576 return NULL;
1577 if (offset < 0)
1578 offset += vbuf.len;
1579 if (offset < 0 || vbuf.len - offset < soself->s_size) {
1580 PyErr_Format(StructError,
1581 "unpack_from requires a buffer of at least %zd bytes",
1582 soself->s_size);
1583 PyBuffer_Release(&vbuf);
1584 return NULL;
1585 }
1586 result = s_unpack_internal(soself, (char*)vbuf.buf + offset);
1587 PyBuffer_Release(&vbuf);
1588 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001589}
1590
1591
Antoine Pitrou9f146812013-04-27 00:20:04 +02001592/* Unpack iterator type */
1593
1594typedef struct {
1595 PyObject_HEAD
1596 PyStructObject *so;
1597 Py_buffer buf;
1598 Py_ssize_t index;
1599} unpackiterobject;
1600
1601static void
1602unpackiter_dealloc(unpackiterobject *self)
1603{
1604 Py_XDECREF(self->so);
1605 PyBuffer_Release(&self->buf);
1606 PyObject_GC_Del(self);
1607}
1608
1609static int
1610unpackiter_traverse(unpackiterobject *self, visitproc visit, void *arg)
1611{
1612 Py_VISIT(self->so);
1613 Py_VISIT(self->buf.obj);
1614 return 0;
1615}
1616
1617static PyObject *
1618unpackiter_len(unpackiterobject *self)
1619{
1620 Py_ssize_t len;
1621 if (self->so == NULL)
1622 len = 0;
1623 else
1624 len = (self->buf.len - self->index) / self->so->s_size;
1625 return PyLong_FromSsize_t(len);
1626}
1627
1628static PyMethodDef unpackiter_methods[] = {
1629 {"__length_hint__", (PyCFunction) unpackiter_len, METH_NOARGS, NULL},
1630 {NULL, NULL} /* sentinel */
1631};
1632
1633static PyObject *
1634unpackiter_iternext(unpackiterobject *self)
1635{
1636 PyObject *result;
1637 if (self->so == NULL)
1638 return NULL;
1639 if (self->index >= self->buf.len) {
1640 /* Iterator exhausted */
1641 Py_CLEAR(self->so);
1642 PyBuffer_Release(&self->buf);
1643 return NULL;
1644 }
1645 assert(self->index + self->so->s_size <= self->buf.len);
1646 result = s_unpack_internal(self->so,
1647 (char*) self->buf.buf + self->index);
1648 self->index += self->so->s_size;
1649 return result;
1650}
1651
doko@ubuntu.com46c5deb2013-11-23 16:07:55 +01001652static PyTypeObject unpackiter_type = {
Antoine Pitrou9f146812013-04-27 00:20:04 +02001653 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1654 "unpack_iterator", /* tp_name */
1655 sizeof(unpackiterobject), /* tp_basicsize */
1656 0, /* tp_itemsize */
1657 (destructor)unpackiter_dealloc, /* tp_dealloc */
1658 0, /* tp_print */
1659 0, /* tp_getattr */
1660 0, /* tp_setattr */
1661 0, /* tp_reserved */
1662 0, /* tp_repr */
1663 0, /* tp_as_number */
1664 0, /* tp_as_sequence */
1665 0, /* tp_as_mapping */
1666 0, /* tp_hash */
1667 0, /* tp_call */
1668 0, /* tp_str */
1669 PyObject_GenericGetAttr, /* tp_getattro */
1670 0, /* tp_setattro */
1671 0, /* tp_as_buffer */
1672 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
1673 0, /* tp_doc */
1674 (traverseproc)unpackiter_traverse, /* tp_traverse */
1675 0, /* tp_clear */
1676 0, /* tp_richcompare */
1677 0, /* tp_weaklistoffset */
1678 PyObject_SelfIter, /* tp_iter */
1679 (iternextfunc)unpackiter_iternext, /* tp_iternext */
1680 unpackiter_methods /* tp_methods */
1681};
1682
1683PyDoc_STRVAR(s_iter_unpack__doc__,
1684"S.iter_unpack(buffer) -> iterator(v1, v2, ...)\n\
1685\n\
1686Return an iterator yielding tuples unpacked from the given bytes\n\
1687source, like a repeated invocation of unpack_from(). Requires\n\
1688that the bytes length be a multiple of the struct size.");
1689
1690static PyObject *
1691s_iter_unpack(PyObject *_so, PyObject *input)
1692{
1693 PyStructObject *so = (PyStructObject *) _so;
1694 unpackiterobject *self;
1695
1696 assert(PyStruct_Check(_so));
1697 assert(so->s_codes != NULL);
1698
1699 if (so->s_size == 0) {
1700 PyErr_Format(StructError,
1701 "cannot iteratively unpack with a struct of length 0");
1702 return NULL;
1703 }
1704
1705 self = (unpackiterobject *) PyType_GenericAlloc(&unpackiter_type, 0);
1706 if (self == NULL)
1707 return NULL;
1708
1709 if (PyObject_GetBuffer(input, &self->buf, PyBUF_SIMPLE) < 0) {
1710 Py_DECREF(self);
1711 return NULL;
1712 }
1713 if (self->buf.len % so->s_size != 0) {
1714 PyErr_Format(StructError,
1715 "iterative unpacking requires a bytes length "
1716 "multiple of %zd",
1717 so->s_size);
1718 Py_DECREF(self);
1719 return NULL;
1720 }
1721 Py_INCREF(so);
1722 self->so = so;
1723 self->index = 0;
1724 return (PyObject *) self;
1725}
1726
1727
Thomas Wouters477c8d52006-05-27 19:21:47 +00001728/*
1729 * Guts of the pack function.
1730 *
1731 * Takes a struct object, a tuple of arguments, and offset in that tuple of
1732 * argument for where to start processing the arguments for packing, and a
1733 * character buffer for writing the packed string. The caller must insure
1734 * that the buffer may contain the required length for packing the arguments.
1735 * 0 is returned on success, 1 is returned if there is an error.
1736 *
1737 */
1738static int
1739s_pack_internal(PyStructObject *soself, PyObject *args, int offset, char* buf)
1740{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001741 formatcode *code;
1742 /* XXX(nnorwitz): why does i need to be a local? can we use
1743 the offset parameter or do we need the wider width? */
1744 Py_ssize_t i;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001745
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001746 memset(buf, '\0', soself->s_size);
1747 i = offset;
1748 for (code = soself->s_codes; code->fmtdef != NULL; code++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001749 const formatdef *e = code->fmtdef;
1750 char *res = buf + code->offset;
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001751 Py_ssize_t j = code->repeat;
1752 while (j--) {
1753 PyObject *v = PyTuple_GET_ITEM(args, i++);
1754 if (e->format == 's') {
1755 Py_ssize_t n;
1756 int isstring;
1757 void *p;
1758 isstring = PyBytes_Check(v);
1759 if (!isstring && !PyByteArray_Check(v)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001760 PyErr_SetString(StructError,
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001761 "argument for 's' must be a bytes object");
1762 return -1;
1763 }
1764 if (isstring) {
1765 n = PyBytes_GET_SIZE(v);
1766 p = PyBytes_AS_STRING(v);
1767 }
1768 else {
1769 n = PyByteArray_GET_SIZE(v);
1770 p = PyByteArray_AS_STRING(v);
1771 }
1772 if (n > code->size)
1773 n = code->size;
1774 if (n > 0)
1775 memcpy(res, p, n);
1776 } else if (e->format == 'p') {
1777 Py_ssize_t n;
1778 int isstring;
1779 void *p;
1780 isstring = PyBytes_Check(v);
1781 if (!isstring && !PyByteArray_Check(v)) {
1782 PyErr_SetString(StructError,
1783 "argument for 'p' must be a bytes object");
1784 return -1;
1785 }
1786 if (isstring) {
1787 n = PyBytes_GET_SIZE(v);
1788 p = PyBytes_AS_STRING(v);
1789 }
1790 else {
1791 n = PyByteArray_GET_SIZE(v);
1792 p = PyByteArray_AS_STRING(v);
1793 }
1794 if (n > (code->size - 1))
1795 n = code->size - 1;
1796 if (n > 0)
1797 memcpy(res + 1, p, n);
1798 if (n > 255)
1799 n = 255;
1800 *res = Py_SAFE_DOWNCAST(n, Py_ssize_t, unsigned char);
1801 } else {
1802 if (e->pack(res, v, e) < 0) {
1803 if (PyLong_Check(v) && PyErr_ExceptionMatches(PyExc_OverflowError))
1804 PyErr_SetString(StructError,
Serhiy Storchaka46e1ce22013-08-27 20:17:03 +03001805 "int too large to convert");
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001806 return -1;
1807 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001808 }
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001809 res += code->size;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001810 }
1811 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001812
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001813 /* Success */
1814 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001815}
1816
1817
1818PyDoc_STRVAR(s_pack__doc__,
Benjamin Peterson4ae19462008-07-31 15:03:40 +00001819"S.pack(v1, v2, ...) -> bytes\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00001820\n\
Mark Dickinsonaacfa952010-06-12 15:43:45 +00001821Return a bytes object containing values v1, v2, ... packed according\n\
1822to the format string S.format. See help(struct) for more on format\n\
1823strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001824
1825static PyObject *
1826s_pack(PyObject *self, PyObject *args)
1827{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001828 PyStructObject *soself;
1829 PyObject *result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001830
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001831 /* Validate arguments. */
1832 soself = (PyStructObject *)self;
1833 assert(PyStruct_Check(self));
1834 assert(soself->s_codes != NULL);
1835 if (PyTuple_GET_SIZE(args) != soself->s_len)
1836 {
1837 PyErr_Format(StructError,
Petri Lehtinen92c28ca2012-10-29 21:16:57 +02001838 "pack expected %zd items for packing (got %zd)", soself->s_len, PyTuple_GET_SIZE(args));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001839 return NULL;
1840 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001841
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001842 /* Allocate a new string */
1843 result = PyBytes_FromStringAndSize((char *)NULL, soself->s_size);
1844 if (result == NULL)
1845 return NULL;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001846
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001847 /* Call the guts */
1848 if ( s_pack_internal(soself, args, 0, PyBytes_AS_STRING(result)) != 0 ) {
1849 Py_DECREF(result);
1850 return NULL;
1851 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001853 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001854}
1855
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001856PyDoc_STRVAR(s_pack_into__doc__,
1857"S.pack_into(buffer, offset, v1, v2, ...)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00001858\n\
Mark Dickinsonaacfa952010-06-12 15:43:45 +00001859Pack the values v1, v2, ... according to the format string S.format\n\
1860and write the packed bytes into the writable buffer buf starting at\n\
Mark Dickinsonfdb99f12010-06-12 16:30:53 +00001861offset. Note that the offset is a required argument. See\n\
Mark Dickinsonaacfa952010-06-12 15:43:45 +00001862help(struct) for more on format strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001863
1864static PyObject *
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001865s_pack_into(PyObject *self, PyObject *args)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001866{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001867 PyStructObject *soself;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001868 Py_buffer buffer;
1869 Py_ssize_t offset;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001870
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001871 /* Validate arguments. +1 is for the first arg as buffer. */
1872 soself = (PyStructObject *)self;
1873 assert(PyStruct_Check(self));
1874 assert(soself->s_codes != NULL);
1875 if (PyTuple_GET_SIZE(args) != (soself->s_len + 2))
1876 {
Petri Lehtinen92c28ca2012-10-29 21:16:57 +02001877 if (PyTuple_GET_SIZE(args) == 0) {
1878 PyErr_Format(StructError,
1879 "pack_into expected buffer argument");
1880 }
1881 else if (PyTuple_GET_SIZE(args) == 1) {
1882 PyErr_Format(StructError,
1883 "pack_into expected offset argument");
1884 }
1885 else {
1886 PyErr_Format(StructError,
1887 "pack_into expected %zd items for packing (got %zd)",
1888 soself->s_len, (PyTuple_GET_SIZE(args) - 2));
1889 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001890 return NULL;
1891 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001893 /* Extract a writable memory buffer from the first argument */
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001894 if (!PyArg_Parse(PyTuple_GET_ITEM(args, 0), "w*", &buffer))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001895 return NULL;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001896 assert(buffer.len >= 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001898 /* Extract the offset from the first argument */
1899 offset = PyNumber_AsSsize_t(PyTuple_GET_ITEM(args, 1), PyExc_IndexError);
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001900 if (offset == -1 && PyErr_Occurred()) {
1901 PyBuffer_Release(&buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001902 return NULL;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001903 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001904
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001905 /* Support negative offsets. */
1906 if (offset < 0)
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001907 offset += buffer.len;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001908
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001909 /* Check boundaries */
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001910 if (offset < 0 || (buffer.len - offset) < soself->s_size) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001911 PyErr_Format(StructError,
1912 "pack_into requires a buffer of at least %zd bytes",
1913 soself->s_size);
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001914 PyBuffer_Release(&buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001915 return NULL;
1916 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001918 /* Call the guts */
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001919 if (s_pack_internal(soself, args, 2, (char*)buffer.buf + offset) != 0) {
1920 PyBuffer_Release(&buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001921 return NULL;
1922 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001923
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001924 PyBuffer_Release(&buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001925 Py_RETURN_NONE;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001926}
1927
1928static PyObject *
1929s_get_format(PyStructObject *self, void *unused)
1930{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001931 Py_INCREF(self->s_format);
1932 return self->s_format;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001933}
1934
1935static PyObject *
1936s_get_size(PyStructObject *self, void *unused)
1937{
Christian Heimes217cfd12007-12-02 14:31:20 +00001938 return PyLong_FromSsize_t(self->s_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001939}
1940
Meador Ingeb14d8c92012-07-23 10:01:29 -05001941PyDoc_STRVAR(s_sizeof__doc__,
1942"S.__sizeof__() -> size of S in memory, in bytes");
1943
1944static PyObject *
Meador Inge90bc2dbc2012-07-28 22:16:39 -05001945s_sizeof(PyStructObject *self, void *unused)
Meador Ingeb14d8c92012-07-23 10:01:29 -05001946{
1947 Py_ssize_t size;
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001948 formatcode *code;
Meador Ingeb14d8c92012-07-23 10:01:29 -05001949
Serhiy Storchaka5c4064e2015-12-19 20:05:25 +02001950 size = _PyObject_SIZE(Py_TYPE(self)) + sizeof(formatcode);
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001951 for (code = self->s_codes; code->fmtdef != NULL; code++)
1952 size += sizeof(formatcode);
Meador Ingeb14d8c92012-07-23 10:01:29 -05001953 return PyLong_FromSsize_t(size);
1954}
1955
Thomas Wouters477c8d52006-05-27 19:21:47 +00001956/* List of functions */
1957
1958static struct PyMethodDef s_methods[] = {
Antoine Pitrou9f146812013-04-27 00:20:04 +02001959 {"iter_unpack", s_iter_unpack, METH_O, s_iter_unpack__doc__},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001960 {"pack", s_pack, METH_VARARGS, s_pack__doc__},
1961 {"pack_into", s_pack_into, METH_VARARGS, s_pack_into__doc__},
1962 {"unpack", s_unpack, METH_O, s_unpack__doc__},
1963 {"unpack_from", (PyCFunction)s_unpack_from, METH_VARARGS|METH_KEYWORDS,
1964 s_unpack_from__doc__},
Meador Ingeb14d8c92012-07-23 10:01:29 -05001965 {"__sizeof__", (PyCFunction)s_sizeof, METH_NOARGS, s_sizeof__doc__},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001966 {NULL, NULL} /* sentinel */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001967};
1968
Victor Stinnerda9ec992010-12-28 13:26:42 +00001969PyDoc_STRVAR(s__doc__,
Alexander Belopolsky0bd003a2010-06-12 19:36:28 +00001970"Struct(fmt) --> compiled struct object\n"
1971"\n"
1972"Return a new Struct object which writes and reads binary data according to\n"
1973"the format string fmt. See help(struct) for more on format strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001974
1975#define OFF(x) offsetof(PyStructObject, x)
1976
1977static PyGetSetDef s_getsetlist[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001978 {"format", (getter)s_get_format, (setter)NULL, "struct format string", NULL},
1979 {"size", (getter)s_get_size, (setter)NULL, "struct size in bytes", NULL},
1980 {NULL} /* sentinel */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001981};
1982
1983static
1984PyTypeObject PyStructType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001985 PyVarObject_HEAD_INIT(NULL, 0)
1986 "Struct",
1987 sizeof(PyStructObject),
1988 0,
1989 (destructor)s_dealloc, /* tp_dealloc */
1990 0, /* tp_print */
1991 0, /* tp_getattr */
1992 0, /* tp_setattr */
1993 0, /* tp_reserved */
1994 0, /* tp_repr */
1995 0, /* tp_as_number */
1996 0, /* tp_as_sequence */
1997 0, /* tp_as_mapping */
1998 0, /* tp_hash */
1999 0, /* tp_call */
2000 0, /* tp_str */
2001 PyObject_GenericGetAttr, /* tp_getattro */
2002 PyObject_GenericSetAttr, /* tp_setattro */
2003 0, /* tp_as_buffer */
2004 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
2005 s__doc__, /* tp_doc */
2006 0, /* tp_traverse */
2007 0, /* tp_clear */
2008 0, /* tp_richcompare */
2009 offsetof(PyStructObject, weakreflist), /* tp_weaklistoffset */
2010 0, /* tp_iter */
2011 0, /* tp_iternext */
2012 s_methods, /* tp_methods */
2013 NULL, /* tp_members */
2014 s_getsetlist, /* tp_getset */
2015 0, /* tp_base */
2016 0, /* tp_dict */
2017 0, /* tp_descr_get */
2018 0, /* tp_descr_set */
2019 0, /* tp_dictoffset */
2020 s_init, /* tp_init */
2021 PyType_GenericAlloc,/* tp_alloc */
2022 s_new, /* tp_new */
2023 PyObject_Del, /* tp_free */
Thomas Wouters477c8d52006-05-27 19:21:47 +00002024};
2025
Christian Heimesa34706f2008-01-04 03:06:10 +00002026
2027/* ---- Standalone functions ---- */
2028
2029#define MAXCACHE 100
2030static PyObject *cache = NULL;
2031
2032static PyObject *
2033cache_struct(PyObject *fmt)
2034{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002035 PyObject * s_object;
Christian Heimesa34706f2008-01-04 03:06:10 +00002036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002037 if (cache == NULL) {
2038 cache = PyDict_New();
2039 if (cache == NULL)
2040 return NULL;
2041 }
Christian Heimesa34706f2008-01-04 03:06:10 +00002042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002043 s_object = PyDict_GetItem(cache, fmt);
2044 if (s_object != NULL) {
2045 Py_INCREF(s_object);
2046 return s_object;
2047 }
Christian Heimesa34706f2008-01-04 03:06:10 +00002048
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002049 s_object = PyObject_CallFunctionObjArgs((PyObject *)(&PyStructType), fmt, NULL);
2050 if (s_object != NULL) {
2051 if (PyDict_Size(cache) >= MAXCACHE)
2052 PyDict_Clear(cache);
2053 /* Attempt to cache the result */
2054 if (PyDict_SetItem(cache, fmt, s_object) == -1)
2055 PyErr_Clear();
2056 }
2057 return s_object;
Christian Heimesa34706f2008-01-04 03:06:10 +00002058}
2059
2060PyDoc_STRVAR(clearcache_doc,
2061"Clear the internal cache.");
2062
2063static PyObject *
2064clearcache(PyObject *self)
2065{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002066 Py_CLEAR(cache);
2067 Py_RETURN_NONE;
Christian Heimesa34706f2008-01-04 03:06:10 +00002068}
2069
2070PyDoc_STRVAR(calcsize_doc,
Mark Dickinsonaacfa952010-06-12 15:43:45 +00002071"calcsize(fmt) -> integer\n\
2072\n\
2073Return size in bytes of the struct described by the format string fmt.");
Christian Heimesa34706f2008-01-04 03:06:10 +00002074
2075static PyObject *
2076calcsize(PyObject *self, PyObject *fmt)
2077{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002078 Py_ssize_t n;
2079 PyObject *s_object = cache_struct(fmt);
2080 if (s_object == NULL)
2081 return NULL;
2082 n = ((PyStructObject *)s_object)->s_size;
2083 Py_DECREF(s_object);
2084 return PyLong_FromSsize_t(n);
Christian Heimesa34706f2008-01-04 03:06:10 +00002085}
2086
2087PyDoc_STRVAR(pack_doc,
Mark Dickinsonaacfa952010-06-12 15:43:45 +00002088"pack(fmt, v1, v2, ...) -> bytes\n\
2089\n\
Mark Dickinsonfdb99f12010-06-12 16:30:53 +00002090Return a bytes object containing the values v1, v2, ... packed according\n\
2091to the format string fmt. See help(struct) for more on format strings.");
Christian Heimesa34706f2008-01-04 03:06:10 +00002092
2093static PyObject *
2094pack(PyObject *self, PyObject *args)
2095{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002096 PyObject *s_object, *fmt, *newargs, *result;
2097 Py_ssize_t n = PyTuple_GET_SIZE(args);
Christian Heimesa34706f2008-01-04 03:06:10 +00002098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002099 if (n == 0) {
2100 PyErr_SetString(PyExc_TypeError, "missing format argument");
2101 return NULL;
2102 }
2103 fmt = PyTuple_GET_ITEM(args, 0);
2104 newargs = PyTuple_GetSlice(args, 1, n);
2105 if (newargs == NULL)
2106 return NULL;
Christian Heimesa34706f2008-01-04 03:06:10 +00002107
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002108 s_object = cache_struct(fmt);
2109 if (s_object == NULL) {
2110 Py_DECREF(newargs);
2111 return NULL;
2112 }
2113 result = s_pack(s_object, newargs);
2114 Py_DECREF(newargs);
2115 Py_DECREF(s_object);
2116 return result;
Christian Heimesa34706f2008-01-04 03:06:10 +00002117}
2118
2119PyDoc_STRVAR(pack_into_doc,
Mark Dickinsonaacfa952010-06-12 15:43:45 +00002120"pack_into(fmt, buffer, offset, v1, v2, ...)\n\
2121\n\
2122Pack the values v1, v2, ... according to the format string fmt and write\n\
2123the packed bytes into the writable buffer buf starting at offset. Note\n\
Mark Dickinsonfdb99f12010-06-12 16:30:53 +00002124that the offset is a required argument. See help(struct) for more\n\
Mark Dickinsonaacfa952010-06-12 15:43:45 +00002125on format strings.");
Christian Heimesa34706f2008-01-04 03:06:10 +00002126
2127static PyObject *
2128pack_into(PyObject *self, PyObject *args)
2129{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002130 PyObject *s_object, *fmt, *newargs, *result;
2131 Py_ssize_t n = PyTuple_GET_SIZE(args);
Christian Heimesa34706f2008-01-04 03:06:10 +00002132
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002133 if (n == 0) {
2134 PyErr_SetString(PyExc_TypeError, "missing format argument");
2135 return NULL;
2136 }
2137 fmt = PyTuple_GET_ITEM(args, 0);
2138 newargs = PyTuple_GetSlice(args, 1, n);
2139 if (newargs == NULL)
2140 return NULL;
Christian Heimesa34706f2008-01-04 03:06:10 +00002141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002142 s_object = cache_struct(fmt);
2143 if (s_object == NULL) {
2144 Py_DECREF(newargs);
2145 return NULL;
2146 }
2147 result = s_pack_into(s_object, newargs);
2148 Py_DECREF(newargs);
2149 Py_DECREF(s_object);
2150 return result;
Christian Heimesa34706f2008-01-04 03:06:10 +00002151}
2152
2153PyDoc_STRVAR(unpack_doc,
Mark Dickinsonaacfa952010-06-12 15:43:45 +00002154"unpack(fmt, buffer) -> (v1, v2, ...)\n\
2155\n\
2156Return a tuple containing values unpacked according to the format string\n\
Martin Panterb0309912016-04-15 23:03:54 +00002157fmt. The buffer's size in bytes must be calcsize(fmt). See help(struct)\n\
2158for more on format strings.");
Christian Heimesa34706f2008-01-04 03:06:10 +00002159
2160static PyObject *
2161unpack(PyObject *self, PyObject *args)
2162{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002163 PyObject *s_object, *fmt, *inputstr, *result;
Christian Heimesa34706f2008-01-04 03:06:10 +00002164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002165 if (!PyArg_UnpackTuple(args, "unpack", 2, 2, &fmt, &inputstr))
2166 return NULL;
Christian Heimesa34706f2008-01-04 03:06:10 +00002167
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002168 s_object = cache_struct(fmt);
2169 if (s_object == NULL)
2170 return NULL;
2171 result = s_unpack(s_object, inputstr);
2172 Py_DECREF(s_object);
2173 return result;
Christian Heimesa34706f2008-01-04 03:06:10 +00002174}
2175
2176PyDoc_STRVAR(unpack_from_doc,
Mark Dickinsonc6f13962010-06-13 09:17:13 +00002177"unpack_from(fmt, buffer, offset=0) -> (v1, v2, ...)\n\
Mark Dickinsonaacfa952010-06-12 15:43:45 +00002178\n\
2179Return a tuple containing values unpacked according to the format string\n\
Martin Panterb0309912016-04-15 23:03:54 +00002180fmt. The buffer's size, minus offset, must be at least calcsize(fmt).\n\
2181See help(struct) for more on format strings.");
Christian Heimesa34706f2008-01-04 03:06:10 +00002182
2183static PyObject *
2184unpack_from(PyObject *self, PyObject *args, PyObject *kwds)
2185{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002186 PyObject *s_object, *fmt, *newargs, *result;
2187 Py_ssize_t n = PyTuple_GET_SIZE(args);
Christian Heimesa34706f2008-01-04 03:06:10 +00002188
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002189 if (n == 0) {
2190 PyErr_SetString(PyExc_TypeError, "missing format argument");
2191 return NULL;
2192 }
2193 fmt = PyTuple_GET_ITEM(args, 0);
2194 newargs = PyTuple_GetSlice(args, 1, n);
2195 if (newargs == NULL)
2196 return NULL;
Christian Heimesa34706f2008-01-04 03:06:10 +00002197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002198 s_object = cache_struct(fmt);
2199 if (s_object == NULL) {
2200 Py_DECREF(newargs);
2201 return NULL;
2202 }
2203 result = s_unpack_from(s_object, newargs, kwds);
2204 Py_DECREF(newargs);
2205 Py_DECREF(s_object);
2206 return result;
Christian Heimesa34706f2008-01-04 03:06:10 +00002207}
2208
Antoine Pitrou9f146812013-04-27 00:20:04 +02002209PyDoc_STRVAR(iter_unpack_doc,
2210"iter_unpack(fmt, buffer) -> iterator(v1, v2, ...)\n\
2211\n\
2212Return an iterator yielding tuples unpacked from the given bytes\n\
2213source according to the format string, like a repeated invocation of\n\
2214unpack_from(). Requires that the bytes length be a multiple of the\n\
2215format struct size.");
2216
2217static PyObject *
2218iter_unpack(PyObject *self, PyObject *args)
2219{
2220 PyObject *s_object, *fmt, *input, *result;
2221
2222 if (!PyArg_ParseTuple(args, "OO:iter_unpack", &fmt, &input))
2223 return NULL;
2224
2225 s_object = cache_struct(fmt);
2226 if (s_object == NULL)
2227 return NULL;
2228 result = s_iter_unpack(s_object, input);
2229 Py_DECREF(s_object);
2230 return result;
2231}
2232
Christian Heimesa34706f2008-01-04 03:06:10 +00002233static struct PyMethodDef module_functions[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002234 {"_clearcache", (PyCFunction)clearcache, METH_NOARGS, clearcache_doc},
2235 {"calcsize", calcsize, METH_O, calcsize_doc},
Antoine Pitrou9f146812013-04-27 00:20:04 +02002236 {"iter_unpack", iter_unpack, METH_VARARGS, iter_unpack_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002237 {"pack", pack, METH_VARARGS, pack_doc},
2238 {"pack_into", pack_into, METH_VARARGS, pack_into_doc},
2239 {"unpack", unpack, METH_VARARGS, unpack_doc},
2240 {"unpack_from", (PyCFunction)unpack_from,
2241 METH_VARARGS|METH_KEYWORDS, unpack_from_doc},
2242 {NULL, NULL} /* sentinel */
Christian Heimesa34706f2008-01-04 03:06:10 +00002243};
2244
2245
Thomas Wouters477c8d52006-05-27 19:21:47 +00002246/* Module initialization */
2247
Christian Heimesa34706f2008-01-04 03:06:10 +00002248PyDoc_STRVAR(module_doc,
2249"Functions to convert between Python values and C structs.\n\
Benjamin Peterson4ae19462008-07-31 15:03:40 +00002250Python bytes objects are used to hold the data representing the C struct\n\
Mark Dickinson40714af2009-10-08 15:59:20 +00002251and also as format strings (explained below) to describe the layout of data\n\
2252in the C struct.\n\
Christian Heimesa34706f2008-01-04 03:06:10 +00002253\n\
2254The optional first format char indicates byte order, size and alignment:\n\
Mark Dickinson40714af2009-10-08 15:59:20 +00002255 @: native order, size & alignment (default)\n\
2256 =: native order, std. size & alignment\n\
2257 <: little-endian, std. size & alignment\n\
2258 >: big-endian, std. size & alignment\n\
2259 !: same as >\n\
Christian Heimesa34706f2008-01-04 03:06:10 +00002260\n\
2261The remaining chars indicate types of args and must match exactly;\n\
2262these can be preceded by a decimal repeat count:\n\
2263 x: pad byte (no data); c:char; b:signed byte; B:unsigned byte;\n\
Mark Dickinson40714af2009-10-08 15:59:20 +00002264 ?: _Bool (requires C99; if not available, char is used instead)\n\
Christian Heimesa34706f2008-01-04 03:06:10 +00002265 h:short; H:unsigned short; i:int; I:unsigned int;\n\
Mark Dickinson7c4e4092016-09-03 17:21:29 +01002266 l:long; L:unsigned long; f:float; d:double; e:half-float.\n\
Christian Heimesa34706f2008-01-04 03:06:10 +00002267Special cases (preceding decimal count indicates length):\n\
2268 s:string (array of char); p: pascal string (with count byte).\n\
Antoine Pitrou45d9c912011-10-06 15:27:40 +02002269Special cases (only available in native format):\n\
2270 n:ssize_t; N:size_t;\n\
Christian Heimesa34706f2008-01-04 03:06:10 +00002271 P:an integer type that is wide enough to hold a pointer.\n\
2272Special case (not in native mode unless 'long long' in platform C):\n\
2273 q:long long; Q:unsigned long long\n\
2274Whitespace between formats is ignored.\n\
2275\n\
2276The variable struct.error is an exception raised on errors.\n");
2277
Martin v. Löwis1a214512008-06-11 05:26:20 +00002278
2279static struct PyModuleDef _structmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002280 PyModuleDef_HEAD_INIT,
2281 "_struct",
2282 module_doc,
2283 -1,
2284 module_functions,
2285 NULL,
2286 NULL,
2287 NULL,
2288 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002289};
2290
Thomas Wouters477c8d52006-05-27 19:21:47 +00002291PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002292PyInit__struct(void)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002293{
Mark Dickinson06817852010-06-12 09:25:13 +00002294 PyObject *m;
Christian Heimesa34706f2008-01-04 03:06:10 +00002295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002296 m = PyModule_Create(&_structmodule);
2297 if (m == NULL)
2298 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002300 Py_TYPE(&PyStructType) = &PyType_Type;
2301 if (PyType_Ready(&PyStructType) < 0)
2302 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002304 /* Check endian and swap in faster functions */
2305 {
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02002306 const formatdef *native = native_table;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002307 formatdef *other, *ptr;
Christian Heimes743e0cd2012-10-17 23:52:17 +02002308#if PY_LITTLE_ENDIAN
2309 other = lilendian_table;
2310#else
2311 other = bigendian_table;
2312#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002313 /* Scan through the native table, find a matching
2314 entry in the endian table and swap in the
2315 native implementations whenever possible
2316 (64-bit platforms may not have "standard" sizes) */
2317 while (native->format != '\0' && other->format != '\0') {
2318 ptr = other;
2319 while (ptr->format != '\0') {
2320 if (ptr->format == native->format) {
2321 /* Match faster when formats are
2322 listed in the same order */
2323 if (ptr == other)
2324 other++;
2325 /* Only use the trick if the
2326 size matches */
2327 if (ptr->size != native->size)
2328 break;
2329 /* Skip float and double, could be
2330 "unknown" float format */
2331 if (ptr->format == 'd' || ptr->format == 'f')
2332 break;
2333 ptr->pack = native->pack;
2334 ptr->unpack = native->unpack;
2335 break;
2336 }
2337 ptr++;
2338 }
2339 native++;
2340 }
2341 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002343 /* Add some symbolic constants to the module */
2344 if (StructError == NULL) {
2345 StructError = PyErr_NewException("struct.error", NULL, NULL);
2346 if (StructError == NULL)
2347 return NULL;
2348 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002350 Py_INCREF(StructError);
2351 PyModule_AddObject(m, "error", StructError);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002353 Py_INCREF((PyObject*)&PyStructType);
2354 PyModule_AddObject(m, "Struct", (PyObject*)&PyStructType);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002356 return m;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002357}