blob: 2635af9db69597cb4254fd467b7ccfc82eddb4b8 [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 }
Xiang Zhangaad1caf2017-05-15 13:17:28 +0800542 *(unsigned char *)p = (unsigned char)x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000543 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;
Xiang Zhangaad1caf2017-05-15 13:17:28 +0800871 unsigned char *q = (unsigned char *)p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000872 if (get_long(v, &x) < 0)
873 return -1;
874 i = f->size;
875 if (i != SIZEOF_LONG) {
876 if ((i == 2) && (x < -32768 || x > 32767))
877 RANGE_ERROR(x, f, 0, 0xffffL);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000878#if (SIZEOF_LONG != 4)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000879 else if ((i == 4) && (x < -2147483648L || x > 2147483647L))
880 RANGE_ERROR(x, f, 0, 0xffffffffL);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000881#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 }
883 do {
Xiang Zhangaad1caf2017-05-15 13:17:28 +0800884 q[--i] = (unsigned char)(x & 0xffL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000885 x >>= 8;
886 } while (i > 0);
887 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000888}
889
890static int
891bp_uint(char *p, PyObject *v, const formatdef *f)
892{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000893 unsigned long x;
894 Py_ssize_t i;
Xiang Zhangaad1caf2017-05-15 13:17:28 +0800895 unsigned char *q = (unsigned char *)p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 if (get_ulong(v, &x) < 0)
897 return -1;
898 i = f->size;
899 if (i != SIZEOF_LONG) {
900 unsigned long maxint = 1;
901 maxint <<= (unsigned long)(i * 8);
902 if (x >= maxint)
903 RANGE_ERROR(x, f, 1, maxint - 1);
904 }
905 do {
Xiang Zhangaad1caf2017-05-15 13:17:28 +0800906 q[--i] = (unsigned char)(x & 0xffUL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 x >>= 8;
908 } while (i > 0);
909 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000910}
911
912static int
913bp_longlong(char *p, PyObject *v, const formatdef *f)
914{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000915 int res;
916 v = get_pylong(v);
917 if (v == NULL)
918 return -1;
919 res = _PyLong_AsByteArray((PyLongObject *)v,
920 (unsigned char *)p,
921 8,
922 0, /* little_endian */
923 1 /* signed */);
924 Py_DECREF(v);
925 return res;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000926}
927
928static int
929bp_ulonglong(char *p, PyObject *v, const formatdef *f)
930{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 int res;
932 v = get_pylong(v);
933 if (v == NULL)
934 return -1;
935 res = _PyLong_AsByteArray((PyLongObject *)v,
936 (unsigned char *)p,
937 8,
938 0, /* little_endian */
939 0 /* signed */);
940 Py_DECREF(v);
941 return res;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000942}
943
944static int
Mark Dickinson7c4e4092016-09-03 17:21:29 +0100945bp_halffloat(char *p, PyObject *v, const formatdef *f)
946{
947 return pack_halffloat(p, v, 0);
948}
949
950static int
Thomas Wouters477c8d52006-05-27 19:21:47 +0000951bp_float(char *p, PyObject *v, const formatdef *f)
952{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 double x = PyFloat_AsDouble(v);
954 if (x == -1 && PyErr_Occurred()) {
955 PyErr_SetString(StructError,
956 "required argument is not a float");
957 return -1;
958 }
959 return _PyFloat_Pack4(x, (unsigned char *)p, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000960}
961
962static int
963bp_double(char *p, PyObject *v, const formatdef *f)
964{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000965 double x = PyFloat_AsDouble(v);
966 if (x == -1 && PyErr_Occurred()) {
967 PyErr_SetString(StructError,
968 "required argument is not a float");
969 return -1;
970 }
971 return _PyFloat_Pack8(x, (unsigned char *)p, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000972}
973
Thomas Woutersb2137042007-02-01 18:02:27 +0000974static int
975bp_bool(char *p, PyObject *v, const formatdef *f)
976{
Mark Dickinsoneff5d852010-07-18 07:29:02 +0000977 int y;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 y = PyObject_IsTrue(v);
Benjamin Petersonde73c452010-07-07 18:54:59 +0000979 if (y < 0)
980 return -1;
Mark Dickinsoneff5d852010-07-18 07:29:02 +0000981 *p = (char)y;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 return 0;
Thomas Woutersb2137042007-02-01 18:02:27 +0000983}
984
Thomas Wouters477c8d52006-05-27 19:21:47 +0000985static formatdef bigendian_table[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 {'x', 1, 0, NULL},
987 {'b', 1, 0, nu_byte, np_byte},
988 {'B', 1, 0, nu_ubyte, np_ubyte},
989 {'c', 1, 0, nu_char, np_char},
990 {'s', 1, 0, NULL},
991 {'p', 1, 0, NULL},
992 {'h', 2, 0, bu_int, bp_int},
993 {'H', 2, 0, bu_uint, bp_uint},
994 {'i', 4, 0, bu_int, bp_int},
995 {'I', 4, 0, bu_uint, bp_uint},
996 {'l', 4, 0, bu_int, bp_int},
997 {'L', 4, 0, bu_uint, bp_uint},
998 {'q', 8, 0, bu_longlong, bp_longlong},
999 {'Q', 8, 0, bu_ulonglong, bp_ulonglong},
1000 {'?', 1, 0, bu_bool, bp_bool},
Mark Dickinson7c4e4092016-09-03 17:21:29 +01001001 {'e', 2, 0, bu_halffloat, bp_halffloat},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 {'f', 4, 0, bu_float, bp_float},
1003 {'d', 8, 0, bu_double, bp_double},
1004 {0}
Thomas Wouters477c8d52006-05-27 19:21:47 +00001005};
1006
1007/* Little-endian routines. *****************************************************/
1008
1009static PyObject *
1010lu_int(const char *p, const formatdef *f)
1011{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001012 long x = 0;
1013 Py_ssize_t i = f->size;
1014 const unsigned char *bytes = (const unsigned char *)p;
1015 do {
1016 x = (x<<8) | bytes[--i];
1017 } while (i > 0);
1018 /* Extend the sign bit. */
1019 if (SIZEOF_LONG > f->size)
1020 x |= -(x & (1L << ((8 * f->size) - 1)));
1021 return PyLong_FromLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001022}
1023
1024static PyObject *
1025lu_uint(const char *p, const formatdef *f)
1026{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027 unsigned long x = 0;
1028 Py_ssize_t i = f->size;
1029 const unsigned char *bytes = (const unsigned char *)p;
1030 do {
1031 x = (x<<8) | bytes[--i];
1032 } while (i > 0);
1033 if (x <= LONG_MAX)
1034 return PyLong_FromLong((long)x);
1035 return PyLong_FromUnsignedLong((long)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001036}
1037
1038static PyObject *
1039lu_longlong(const char *p, const formatdef *f)
1040{
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001041 long long x = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 Py_ssize_t i = f->size;
1043 const unsigned char *bytes = (const unsigned char *)p;
1044 do {
1045 x = (x<<8) | bytes[--i];
1046 } while (i > 0);
1047 /* Extend the sign bit. */
1048 if (SIZEOF_LONG_LONG > f->size)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001049 x |= -(x & ((long long)1 << ((8 * f->size) - 1)));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 if (x >= LONG_MIN && x <= LONG_MAX)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001051 return PyLong_FromLong(Py_SAFE_DOWNCAST(x, long long, long));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 return PyLong_FromLongLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001053}
1054
1055static PyObject *
1056lu_ulonglong(const char *p, const formatdef *f)
1057{
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001058 unsigned long long x = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001059 Py_ssize_t i = f->size;
1060 const unsigned char *bytes = (const unsigned char *)p;
1061 do {
1062 x = (x<<8) | bytes[--i];
1063 } while (i > 0);
1064 if (x <= LONG_MAX)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001065 return PyLong_FromLong(Py_SAFE_DOWNCAST(x, unsigned long long, long));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001066 return PyLong_FromUnsignedLongLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001067}
1068
1069static PyObject *
Mark Dickinson7c4e4092016-09-03 17:21:29 +01001070lu_halffloat(const char *p, const formatdef *f)
1071{
1072 return unpack_halffloat(p, 1);
1073}
1074
1075static PyObject *
Thomas Wouters477c8d52006-05-27 19:21:47 +00001076lu_float(const char *p, const formatdef *f)
1077{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 return unpack_float(p, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001079}
1080
1081static PyObject *
1082lu_double(const char *p, const formatdef *f)
1083{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 return unpack_double(p, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001085}
1086
1087static int
1088lp_int(char *p, PyObject *v, const formatdef *f)
1089{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001090 long x;
1091 Py_ssize_t i;
Xiang Zhangaad1caf2017-05-15 13:17:28 +08001092 unsigned char *q = (unsigned char *)p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001093 if (get_long(v, &x) < 0)
1094 return -1;
1095 i = f->size;
1096 if (i != SIZEOF_LONG) {
1097 if ((i == 2) && (x < -32768 || x > 32767))
1098 RANGE_ERROR(x, f, 0, 0xffffL);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001099#if (SIZEOF_LONG != 4)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001100 else if ((i == 4) && (x < -2147483648L || x > 2147483647L))
1101 RANGE_ERROR(x, f, 0, 0xffffffffL);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001102#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001103 }
1104 do {
Xiang Zhangaad1caf2017-05-15 13:17:28 +08001105 *q++ = (unsigned char)(x & 0xffL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 x >>= 8;
1107 } while (--i > 0);
1108 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001109}
1110
1111static int
1112lp_uint(char *p, PyObject *v, const formatdef *f)
1113{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001114 unsigned long x;
1115 Py_ssize_t i;
Xiang Zhangaad1caf2017-05-15 13:17:28 +08001116 unsigned char *q = (unsigned char *)p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001117 if (get_ulong(v, &x) < 0)
1118 return -1;
1119 i = f->size;
1120 if (i != SIZEOF_LONG) {
1121 unsigned long maxint = 1;
1122 maxint <<= (unsigned long)(i * 8);
1123 if (x >= maxint)
1124 RANGE_ERROR(x, f, 1, maxint - 1);
1125 }
1126 do {
Xiang Zhangaad1caf2017-05-15 13:17:28 +08001127 *q++ = (unsigned char)(x & 0xffUL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001128 x >>= 8;
1129 } while (--i > 0);
1130 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001131}
1132
1133static int
1134lp_longlong(char *p, PyObject *v, const formatdef *f)
1135{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136 int res;
1137 v = get_pylong(v);
1138 if (v == NULL)
1139 return -1;
1140 res = _PyLong_AsByteArray((PyLongObject*)v,
1141 (unsigned char *)p,
1142 8,
1143 1, /* little_endian */
1144 1 /* signed */);
1145 Py_DECREF(v);
1146 return res;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001147}
1148
1149static int
1150lp_ulonglong(char *p, PyObject *v, const formatdef *f)
1151{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001152 int res;
1153 v = get_pylong(v);
1154 if (v == NULL)
1155 return -1;
1156 res = _PyLong_AsByteArray((PyLongObject*)v,
1157 (unsigned char *)p,
1158 8,
1159 1, /* little_endian */
1160 0 /* signed */);
1161 Py_DECREF(v);
1162 return res;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001163}
1164
1165static int
Mark Dickinson7c4e4092016-09-03 17:21:29 +01001166lp_halffloat(char *p, PyObject *v, const formatdef *f)
1167{
1168 return pack_halffloat(p, v, 1);
1169}
1170
1171static int
Thomas Wouters477c8d52006-05-27 19:21:47 +00001172lp_float(char *p, PyObject *v, const formatdef *f)
1173{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001174 double x = PyFloat_AsDouble(v);
1175 if (x == -1 && PyErr_Occurred()) {
1176 PyErr_SetString(StructError,
1177 "required argument is not a float");
1178 return -1;
1179 }
1180 return _PyFloat_Pack4(x, (unsigned char *)p, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001181}
1182
1183static int
1184lp_double(char *p, PyObject *v, const formatdef *f)
1185{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001186 double x = PyFloat_AsDouble(v);
1187 if (x == -1 && PyErr_Occurred()) {
1188 PyErr_SetString(StructError,
1189 "required argument is not a float");
1190 return -1;
1191 }
1192 return _PyFloat_Pack8(x, (unsigned char *)p, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001193}
1194
1195static formatdef lilendian_table[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001196 {'x', 1, 0, NULL},
1197 {'b', 1, 0, nu_byte, np_byte},
1198 {'B', 1, 0, nu_ubyte, np_ubyte},
1199 {'c', 1, 0, nu_char, np_char},
1200 {'s', 1, 0, NULL},
1201 {'p', 1, 0, NULL},
1202 {'h', 2, 0, lu_int, lp_int},
1203 {'H', 2, 0, lu_uint, lp_uint},
1204 {'i', 4, 0, lu_int, lp_int},
1205 {'I', 4, 0, lu_uint, lp_uint},
1206 {'l', 4, 0, lu_int, lp_int},
1207 {'L', 4, 0, lu_uint, lp_uint},
1208 {'q', 8, 0, lu_longlong, lp_longlong},
1209 {'Q', 8, 0, lu_ulonglong, lp_ulonglong},
1210 {'?', 1, 0, bu_bool, bp_bool}, /* Std rep not endian dep,
1211 but potentially different from native rep -- reuse bx_bool funcs. */
Mark Dickinson7c4e4092016-09-03 17:21:29 +01001212 {'e', 2, 0, lu_halffloat, lp_halffloat},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 {'f', 4, 0, lu_float, lp_float},
1214 {'d', 8, 0, lu_double, lp_double},
1215 {0}
Thomas Wouters477c8d52006-05-27 19:21:47 +00001216};
1217
1218
1219static const formatdef *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001220whichtable(const char **pfmt)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001221{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001222 const char *fmt = (*pfmt)++; /* May be backed out of later */
1223 switch (*fmt) {
1224 case '<':
1225 return lilendian_table;
1226 case '>':
1227 case '!': /* Network byte order is big-endian */
1228 return bigendian_table;
Ezio Melotti42da6632011-03-15 05:18:48 +02001229 case '=': { /* Host byte order -- different from native in alignment! */
Christian Heimes743e0cd2012-10-17 23:52:17 +02001230#if PY_LITTLE_ENDIAN
1231 return lilendian_table;
1232#else
1233 return bigendian_table;
1234#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001235 }
1236 default:
1237 --*pfmt; /* Back out of pointer increment */
1238 /* Fall through */
1239 case '@':
1240 return native_table;
1241 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001242}
1243
1244
1245/* Get the table entry for a format code */
1246
1247static const formatdef *
1248getentry(int c, const formatdef *f)
1249{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001250 for (; f->format != '\0'; f++) {
1251 if (f->format == c) {
1252 return f;
1253 }
1254 }
1255 PyErr_SetString(StructError, "bad char in struct format");
1256 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001257}
1258
1259
Mark Dickinsonb72e6862010-06-11 19:50:30 +00001260/* Align a size according to a format code. Return -1 on overflow. */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001261
Mark Dickinsoneac0e682010-06-11 19:05:08 +00001262static Py_ssize_t
Thomas Wouters477c8d52006-05-27 19:21:47 +00001263align(Py_ssize_t size, char c, const formatdef *e)
1264{
Mark Dickinsonb72e6862010-06-11 19:50:30 +00001265 Py_ssize_t extra;
1266
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001267 if (e->format == c) {
Mark Dickinsonb72e6862010-06-11 19:50:30 +00001268 if (e->alignment && size > 0) {
1269 extra = (e->alignment - 1) - (size - 1) % (e->alignment);
1270 if (extra > PY_SSIZE_T_MAX - size)
1271 return -1;
1272 size += extra;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001273 }
1274 }
1275 return size;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001276}
1277
Antoine Pitrou9f146812013-04-27 00:20:04 +02001278/*
1279 * Struct object implementation.
1280 */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001281
1282/* calculate the size of a format string */
1283
1284static int
1285prepare_s(PyStructObject *self)
1286{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001287 const formatdef *f;
1288 const formatdef *e;
1289 formatcode *codes;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001290
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001291 const char *s;
1292 const char *fmt;
1293 char c;
Victor Stinner706768c2014-08-16 01:03:39 +02001294 Py_ssize_t size, len, num, itemsize;
1295 size_t ncodes;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001297 fmt = PyBytes_AS_STRING(self->s_format);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001298
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001299 f = whichtable(&fmt);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001301 s = fmt;
1302 size = 0;
1303 len = 0;
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001304 ncodes = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001305 while ((c = *s++) != '\0') {
Antoine Pitrou4de74572013-02-09 23:11:27 +01001306 if (Py_ISSPACE(Py_CHARMASK(c)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001307 continue;
1308 if ('0' <= c && c <= '9') {
1309 num = c - '0';
1310 while ('0' <= (c = *s++) && c <= '9') {
Mark Dickinsonab4096f2010-06-11 16:56:34 +00001311 /* overflow-safe version of
1312 if (num*10 + (c - '0') > PY_SSIZE_T_MAX) { ... } */
1313 if (num >= PY_SSIZE_T_MAX / 10 && (
1314 num > PY_SSIZE_T_MAX / 10 ||
Mark Dickinsonb72e6862010-06-11 19:50:30 +00001315 (c - '0') > PY_SSIZE_T_MAX % 10))
1316 goto overflow;
Mark Dickinsonab4096f2010-06-11 16:56:34 +00001317 num = num*10 + (c - '0');
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001318 }
Alexander Belopolsky177e8532010-06-11 16:04:59 +00001319 if (c == '\0') {
1320 PyErr_SetString(StructError,
1321 "repeat count given without format specifier");
1322 return -1;
1323 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001324 }
1325 else
1326 num = 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001328 e = getentry(c, f);
1329 if (e == NULL)
1330 return -1;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001332 switch (c) {
1333 case 's': /* fall through */
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001334 case 'p': len++; ncodes++; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001335 case 'x': break;
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001336 default: len += num; if (num) ncodes++; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001337 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001339 itemsize = e->size;
1340 size = align(size, c, e);
Mark Dickinsonb72e6862010-06-11 19:50:30 +00001341 if (size == -1)
1342 goto overflow;
1343
1344 /* if (size + num * itemsize > PY_SSIZE_T_MAX) { ... } */
1345 if (num > (PY_SSIZE_T_MAX - size) / itemsize)
1346 goto overflow;
1347 size += num * itemsize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001348 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001350 /* check for overflow */
Victor Stinner706768c2014-08-16 01:03:39 +02001351 if ((ncodes + 1) > ((size_t)PY_SSIZE_T_MAX / sizeof(formatcode))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001352 PyErr_NoMemory();
1353 return -1;
1354 }
Amaury Forgeot d'Arc35c86582008-06-17 21:11:29 +00001355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001356 self->s_size = size;
1357 self->s_len = len;
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001358 codes = PyMem_MALLOC((ncodes + 1) * sizeof(formatcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001359 if (codes == NULL) {
1360 PyErr_NoMemory();
1361 return -1;
1362 }
Mark Dickinsoncf28b952010-07-29 21:41:59 +00001363 /* Free any s_codes value left over from a previous initialization. */
1364 if (self->s_codes != NULL)
1365 PyMem_FREE(self->s_codes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001366 self->s_codes = codes;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001368 s = fmt;
1369 size = 0;
1370 while ((c = *s++) != '\0') {
Antoine Pitrou4de74572013-02-09 23:11:27 +01001371 if (Py_ISSPACE(Py_CHARMASK(c)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001372 continue;
1373 if ('0' <= c && c <= '9') {
1374 num = c - '0';
1375 while ('0' <= (c = *s++) && c <= '9')
1376 num = num*10 + (c - '0');
1377 if (c == '\0')
1378 break;
1379 }
1380 else
1381 num = 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001383 e = getentry(c, f);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001385 size = align(size, c, e);
1386 if (c == 's' || c == 'p') {
1387 codes->offset = size;
1388 codes->size = num;
1389 codes->fmtdef = e;
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001390 codes->repeat = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001391 codes++;
1392 size += num;
1393 } else if (c == 'x') {
1394 size += num;
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001395 } else if (num) {
1396 codes->offset = size;
1397 codes->size = e->size;
1398 codes->fmtdef = e;
1399 codes->repeat = num;
1400 codes++;
1401 size += e->size * num;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001402 }
1403 }
1404 codes->fmtdef = NULL;
1405 codes->offset = size;
1406 codes->size = 0;
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001407 codes->repeat = 0;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001408
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001409 return 0;
Mark Dickinsonb72e6862010-06-11 19:50:30 +00001410
1411 overflow:
1412 PyErr_SetString(StructError,
1413 "total struct size too long");
1414 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001415}
1416
1417static PyObject *
1418s_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1419{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001420 PyObject *self;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001422 assert(type != NULL && type->tp_alloc != NULL);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001424 self = type->tp_alloc(type, 0);
1425 if (self != NULL) {
1426 PyStructObject *s = (PyStructObject*)self;
1427 Py_INCREF(Py_None);
1428 s->s_format = Py_None;
1429 s->s_codes = NULL;
1430 s->s_size = -1;
1431 s->s_len = -1;
1432 }
1433 return self;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001434}
1435
1436static int
1437s_init(PyObject *self, PyObject *args, PyObject *kwds)
1438{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001439 PyStructObject *soself = (PyStructObject *)self;
1440 PyObject *o_format = NULL;
1441 int ret = 0;
1442 static char *kwlist[] = {"format", 0};
Thomas Wouters477c8d52006-05-27 19:21:47 +00001443
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001444 assert(PyStruct_Check(self));
Thomas Wouters477c8d52006-05-27 19:21:47 +00001445
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001446 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:Struct", kwlist,
1447 &o_format))
1448 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001450 if (PyUnicode_Check(o_format)) {
1451 o_format = PyUnicode_AsASCIIString(o_format);
1452 if (o_format == NULL)
1453 return -1;
1454 }
1455 /* XXX support buffer interface, too */
1456 else {
1457 Py_INCREF(o_format);
1458 }
Christian Heimesa34706f2008-01-04 03:06:10 +00001459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001460 if (!PyBytes_Check(o_format)) {
1461 Py_DECREF(o_format);
1462 PyErr_Format(PyExc_TypeError,
Victor Stinnerda9ec992010-12-28 13:26:42 +00001463 "Struct() argument 1 must be a bytes object, not %.200s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001464 Py_TYPE(o_format)->tp_name);
1465 return -1;
1466 }
Christian Heimesa34706f2008-01-04 03:06:10 +00001467
Serhiy Storchaka48842712016-04-06 09:45:48 +03001468 Py_XSETREF(soself->s_format, o_format);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001470 ret = prepare_s(soself);
1471 return ret;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001472}
1473
1474static void
1475s_dealloc(PyStructObject *s)
1476{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001477 if (s->weakreflist != NULL)
1478 PyObject_ClearWeakRefs((PyObject *)s);
1479 if (s->s_codes != NULL) {
1480 PyMem_FREE(s->s_codes);
1481 }
1482 Py_XDECREF(s->s_format);
1483 Py_TYPE(s)->tp_free((PyObject *)s);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001484}
1485
1486static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001487s_unpack_internal(PyStructObject *soself, const char *startfrom) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001488 formatcode *code;
1489 Py_ssize_t i = 0;
1490 PyObject *result = PyTuple_New(soself->s_len);
1491 if (result == NULL)
1492 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001494 for (code = soself->s_codes; code->fmtdef != NULL; code++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001495 const formatdef *e = code->fmtdef;
1496 const char *res = startfrom + code->offset;
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001497 Py_ssize_t j = code->repeat;
1498 while (j--) {
1499 PyObject *v;
1500 if (e->format == 's') {
1501 v = PyBytes_FromStringAndSize(res, code->size);
1502 } else if (e->format == 'p') {
1503 Py_ssize_t n = *(unsigned char*)res;
1504 if (n >= code->size)
1505 n = code->size - 1;
1506 v = PyBytes_FromStringAndSize(res + 1, n);
1507 } else {
1508 v = e->unpack(res, e);
1509 }
1510 if (v == NULL)
1511 goto fail;
1512 PyTuple_SET_ITEM(result, i++, v);
1513 res += code->size;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001514 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001515 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001517 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001518fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001519 Py_DECREF(result);
1520 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001521}
1522
1523
1524PyDoc_STRVAR(s_unpack__doc__,
Guido van Rossum913dd0b2007-04-13 03:33:53 +00001525"S.unpack(buffer) -> (v1, v2, ...)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00001526\n\
Mark Dickinsonaacfa952010-06-12 15:43:45 +00001527Return a tuple containing values unpacked according to the format\n\
Martin Panterb0309912016-04-15 23:03:54 +00001528string S.format. The buffer's size in bytes must be S.size. See\n\
1529help(struct) for more on format strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001530
1531static PyObject *
Guido van Rossum98297ee2007-11-06 21:34:58 +00001532s_unpack(PyObject *self, PyObject *input)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001533{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001534 Py_buffer vbuf;
1535 PyObject *result;
1536 PyStructObject *soself = (PyStructObject *)self;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001538 assert(PyStruct_Check(self));
1539 assert(soself->s_codes != NULL);
1540 if (PyObject_GetBuffer(input, &vbuf, PyBUF_SIMPLE) < 0)
1541 return NULL;
1542 if (vbuf.len != soself->s_size) {
1543 PyErr_Format(StructError,
Victor Stinnerda9ec992010-12-28 13:26:42 +00001544 "unpack requires a bytes object of length %zd",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001545 soself->s_size);
1546 PyBuffer_Release(&vbuf);
1547 return NULL;
1548 }
1549 result = s_unpack_internal(soself, vbuf.buf);
1550 PyBuffer_Release(&vbuf);
1551 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001552}
1553
1554PyDoc_STRVAR(s_unpack_from__doc__,
Mark Dickinsonc6f13962010-06-13 09:17:13 +00001555"S.unpack_from(buffer, offset=0) -> (v1, v2, ...)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00001556\n\
Mark Dickinsonaacfa952010-06-12 15:43:45 +00001557Return a tuple containing values unpacked according to the format\n\
Martin Panterb0309912016-04-15 23:03:54 +00001558string S.format. The buffer's size in bytes, minus offset, must be at\n\
1559least S.size. See help(struct) for more on format strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001560
1561static PyObject *
1562s_unpack_from(PyObject *self, PyObject *args, PyObject *kwds)
1563{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001564 static char *kwlist[] = {"buffer", "offset", 0};
Guido van Rossum98297ee2007-11-06 21:34:58 +00001565
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001566 PyObject *input;
1567 Py_ssize_t offset = 0;
1568 Py_buffer vbuf;
1569 PyObject *result;
1570 PyStructObject *soself = (PyStructObject *)self;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001572 assert(PyStruct_Check(self));
1573 assert(soself->s_codes != NULL);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001575 if (!PyArg_ParseTupleAndKeywords(args, kwds,
1576 "O|n:unpack_from", kwlist,
1577 &input, &offset))
1578 return NULL;
1579 if (PyObject_GetBuffer(input, &vbuf, PyBUF_SIMPLE) < 0)
1580 return NULL;
1581 if (offset < 0)
1582 offset += vbuf.len;
1583 if (offset < 0 || vbuf.len - offset < soself->s_size) {
1584 PyErr_Format(StructError,
1585 "unpack_from requires a buffer of at least %zd bytes",
1586 soself->s_size);
1587 PyBuffer_Release(&vbuf);
1588 return NULL;
1589 }
1590 result = s_unpack_internal(soself, (char*)vbuf.buf + offset);
1591 PyBuffer_Release(&vbuf);
1592 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001593}
1594
1595
Antoine Pitrou9f146812013-04-27 00:20:04 +02001596/* Unpack iterator type */
1597
1598typedef struct {
1599 PyObject_HEAD
1600 PyStructObject *so;
1601 Py_buffer buf;
1602 Py_ssize_t index;
1603} unpackiterobject;
1604
1605static void
1606unpackiter_dealloc(unpackiterobject *self)
1607{
1608 Py_XDECREF(self->so);
1609 PyBuffer_Release(&self->buf);
1610 PyObject_GC_Del(self);
1611}
1612
1613static int
1614unpackiter_traverse(unpackiterobject *self, visitproc visit, void *arg)
1615{
1616 Py_VISIT(self->so);
1617 Py_VISIT(self->buf.obj);
1618 return 0;
1619}
1620
1621static PyObject *
1622unpackiter_len(unpackiterobject *self)
1623{
1624 Py_ssize_t len;
1625 if (self->so == NULL)
1626 len = 0;
1627 else
1628 len = (self->buf.len - self->index) / self->so->s_size;
1629 return PyLong_FromSsize_t(len);
1630}
1631
1632static PyMethodDef unpackiter_methods[] = {
1633 {"__length_hint__", (PyCFunction) unpackiter_len, METH_NOARGS, NULL},
1634 {NULL, NULL} /* sentinel */
1635};
1636
1637static PyObject *
1638unpackiter_iternext(unpackiterobject *self)
1639{
1640 PyObject *result;
1641 if (self->so == NULL)
1642 return NULL;
1643 if (self->index >= self->buf.len) {
1644 /* Iterator exhausted */
1645 Py_CLEAR(self->so);
1646 PyBuffer_Release(&self->buf);
1647 return NULL;
1648 }
1649 assert(self->index + self->so->s_size <= self->buf.len);
1650 result = s_unpack_internal(self->so,
1651 (char*) self->buf.buf + self->index);
1652 self->index += self->so->s_size;
1653 return result;
1654}
1655
doko@ubuntu.com46c5deb2013-11-23 16:07:55 +01001656static PyTypeObject unpackiter_type = {
Antoine Pitrou9f146812013-04-27 00:20:04 +02001657 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1658 "unpack_iterator", /* tp_name */
1659 sizeof(unpackiterobject), /* tp_basicsize */
1660 0, /* tp_itemsize */
1661 (destructor)unpackiter_dealloc, /* tp_dealloc */
1662 0, /* tp_print */
1663 0, /* tp_getattr */
1664 0, /* tp_setattr */
1665 0, /* tp_reserved */
1666 0, /* tp_repr */
1667 0, /* tp_as_number */
1668 0, /* tp_as_sequence */
1669 0, /* tp_as_mapping */
1670 0, /* tp_hash */
1671 0, /* tp_call */
1672 0, /* tp_str */
1673 PyObject_GenericGetAttr, /* tp_getattro */
1674 0, /* tp_setattro */
1675 0, /* tp_as_buffer */
1676 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
1677 0, /* tp_doc */
1678 (traverseproc)unpackiter_traverse, /* tp_traverse */
1679 0, /* tp_clear */
1680 0, /* tp_richcompare */
1681 0, /* tp_weaklistoffset */
1682 PyObject_SelfIter, /* tp_iter */
1683 (iternextfunc)unpackiter_iternext, /* tp_iternext */
1684 unpackiter_methods /* tp_methods */
1685};
1686
1687PyDoc_STRVAR(s_iter_unpack__doc__,
1688"S.iter_unpack(buffer) -> iterator(v1, v2, ...)\n\
1689\n\
1690Return an iterator yielding tuples unpacked from the given bytes\n\
1691source, like a repeated invocation of unpack_from(). Requires\n\
1692that the bytes length be a multiple of the struct size.");
1693
1694static PyObject *
1695s_iter_unpack(PyObject *_so, PyObject *input)
1696{
1697 PyStructObject *so = (PyStructObject *) _so;
1698 unpackiterobject *self;
1699
1700 assert(PyStruct_Check(_so));
1701 assert(so->s_codes != NULL);
1702
1703 if (so->s_size == 0) {
1704 PyErr_Format(StructError,
1705 "cannot iteratively unpack with a struct of length 0");
1706 return NULL;
1707 }
1708
1709 self = (unpackiterobject *) PyType_GenericAlloc(&unpackiter_type, 0);
1710 if (self == NULL)
1711 return NULL;
1712
1713 if (PyObject_GetBuffer(input, &self->buf, PyBUF_SIMPLE) < 0) {
1714 Py_DECREF(self);
1715 return NULL;
1716 }
1717 if (self->buf.len % so->s_size != 0) {
1718 PyErr_Format(StructError,
1719 "iterative unpacking requires a bytes length "
1720 "multiple of %zd",
1721 so->s_size);
1722 Py_DECREF(self);
1723 return NULL;
1724 }
1725 Py_INCREF(so);
1726 self->so = so;
1727 self->index = 0;
1728 return (PyObject *) self;
1729}
1730
1731
Thomas Wouters477c8d52006-05-27 19:21:47 +00001732/*
1733 * Guts of the pack function.
1734 *
1735 * Takes a struct object, a tuple of arguments, and offset in that tuple of
1736 * argument for where to start processing the arguments for packing, and a
1737 * character buffer for writing the packed string. The caller must insure
1738 * that the buffer may contain the required length for packing the arguments.
1739 * 0 is returned on success, 1 is returned if there is an error.
1740 *
1741 */
1742static int
1743s_pack_internal(PyStructObject *soself, PyObject *args, int offset, char* buf)
1744{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001745 formatcode *code;
1746 /* XXX(nnorwitz): why does i need to be a local? can we use
1747 the offset parameter or do we need the wider width? */
1748 Py_ssize_t i;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001749
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001750 memset(buf, '\0', soself->s_size);
1751 i = offset;
1752 for (code = soself->s_codes; code->fmtdef != NULL; code++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001753 const formatdef *e = code->fmtdef;
1754 char *res = buf + code->offset;
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001755 Py_ssize_t j = code->repeat;
1756 while (j--) {
1757 PyObject *v = PyTuple_GET_ITEM(args, i++);
1758 if (e->format == 's') {
1759 Py_ssize_t n;
1760 int isstring;
1761 void *p;
1762 isstring = PyBytes_Check(v);
1763 if (!isstring && !PyByteArray_Check(v)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001764 PyErr_SetString(StructError,
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001765 "argument for 's' must be a bytes object");
1766 return -1;
1767 }
1768 if (isstring) {
1769 n = PyBytes_GET_SIZE(v);
1770 p = PyBytes_AS_STRING(v);
1771 }
1772 else {
1773 n = PyByteArray_GET_SIZE(v);
1774 p = PyByteArray_AS_STRING(v);
1775 }
1776 if (n > code->size)
1777 n = code->size;
1778 if (n > 0)
1779 memcpy(res, p, n);
1780 } else if (e->format == 'p') {
1781 Py_ssize_t n;
1782 int isstring;
1783 void *p;
1784 isstring = PyBytes_Check(v);
1785 if (!isstring && !PyByteArray_Check(v)) {
1786 PyErr_SetString(StructError,
1787 "argument for 'p' must be a bytes object");
1788 return -1;
1789 }
1790 if (isstring) {
1791 n = PyBytes_GET_SIZE(v);
1792 p = PyBytes_AS_STRING(v);
1793 }
1794 else {
1795 n = PyByteArray_GET_SIZE(v);
1796 p = PyByteArray_AS_STRING(v);
1797 }
1798 if (n > (code->size - 1))
1799 n = code->size - 1;
1800 if (n > 0)
1801 memcpy(res + 1, p, n);
1802 if (n > 255)
1803 n = 255;
1804 *res = Py_SAFE_DOWNCAST(n, Py_ssize_t, unsigned char);
1805 } else {
1806 if (e->pack(res, v, e) < 0) {
1807 if (PyLong_Check(v) && PyErr_ExceptionMatches(PyExc_OverflowError))
1808 PyErr_SetString(StructError,
Serhiy Storchaka46e1ce22013-08-27 20:17:03 +03001809 "int too large to convert");
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001810 return -1;
1811 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001812 }
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001813 res += code->size;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001814 }
1815 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001816
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001817 /* Success */
1818 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001819}
1820
1821
1822PyDoc_STRVAR(s_pack__doc__,
Benjamin Peterson4ae19462008-07-31 15:03:40 +00001823"S.pack(v1, v2, ...) -> bytes\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00001824\n\
Mark Dickinsonaacfa952010-06-12 15:43:45 +00001825Return a bytes object containing values v1, v2, ... packed according\n\
1826to the format string S.format. See help(struct) for more on format\n\
1827strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001828
1829static PyObject *
1830s_pack(PyObject *self, PyObject *args)
1831{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001832 PyStructObject *soself;
1833 PyObject *result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001834
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001835 /* Validate arguments. */
1836 soself = (PyStructObject *)self;
1837 assert(PyStruct_Check(self));
1838 assert(soself->s_codes != NULL);
1839 if (PyTuple_GET_SIZE(args) != soself->s_len)
1840 {
1841 PyErr_Format(StructError,
Petri Lehtinen92c28ca2012-10-29 21:16:57 +02001842 "pack expected %zd items for packing (got %zd)", soself->s_len, PyTuple_GET_SIZE(args));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001843 return NULL;
1844 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001845
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001846 /* Allocate a new string */
1847 result = PyBytes_FromStringAndSize((char *)NULL, soself->s_size);
1848 if (result == NULL)
1849 return NULL;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001850
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001851 /* Call the guts */
1852 if ( s_pack_internal(soself, args, 0, PyBytes_AS_STRING(result)) != 0 ) {
1853 Py_DECREF(result);
1854 return NULL;
1855 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001856
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001857 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001858}
1859
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001860PyDoc_STRVAR(s_pack_into__doc__,
1861"S.pack_into(buffer, offset, v1, v2, ...)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00001862\n\
Mark Dickinsonaacfa952010-06-12 15:43:45 +00001863Pack the values v1, v2, ... according to the format string S.format\n\
1864and write the packed bytes into the writable buffer buf starting at\n\
Mark Dickinsonfdb99f12010-06-12 16:30:53 +00001865offset. Note that the offset is a required argument. See\n\
Mark Dickinsonaacfa952010-06-12 15:43:45 +00001866help(struct) for more on format strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001867
1868static PyObject *
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001869s_pack_into(PyObject *self, PyObject *args)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001870{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001871 PyStructObject *soself;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001872 Py_buffer buffer;
1873 Py_ssize_t offset;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001874
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001875 /* Validate arguments. +1 is for the first arg as buffer. */
1876 soself = (PyStructObject *)self;
1877 assert(PyStruct_Check(self));
1878 assert(soself->s_codes != NULL);
1879 if (PyTuple_GET_SIZE(args) != (soself->s_len + 2))
1880 {
Petri Lehtinen92c28ca2012-10-29 21:16:57 +02001881 if (PyTuple_GET_SIZE(args) == 0) {
1882 PyErr_Format(StructError,
1883 "pack_into expected buffer argument");
1884 }
1885 else if (PyTuple_GET_SIZE(args) == 1) {
1886 PyErr_Format(StructError,
1887 "pack_into expected offset argument");
1888 }
1889 else {
1890 PyErr_Format(StructError,
1891 "pack_into expected %zd items for packing (got %zd)",
1892 soself->s_len, (PyTuple_GET_SIZE(args) - 2));
1893 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001894 return NULL;
1895 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001897 /* Extract a writable memory buffer from the first argument */
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001898 if (!PyArg_Parse(PyTuple_GET_ITEM(args, 0), "w*", &buffer))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001899 return NULL;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001900 assert(buffer.len >= 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001901
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001902 /* Extract the offset from the first argument */
1903 offset = PyNumber_AsSsize_t(PyTuple_GET_ITEM(args, 1), PyExc_IndexError);
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001904 if (offset == -1 && PyErr_Occurred()) {
1905 PyBuffer_Release(&buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001906 return NULL;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001907 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001908
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001909 /* Support negative offsets. */
1910 if (offset < 0)
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001911 offset += buffer.len;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001913 /* Check boundaries */
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001914 if (offset < 0 || (buffer.len - offset) < soself->s_size) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001915 PyErr_Format(StructError,
1916 "pack_into requires a buffer of at least %zd bytes",
1917 soself->s_size);
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001918 PyBuffer_Release(&buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001919 return NULL;
1920 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001922 /* Call the guts */
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001923 if (s_pack_internal(soself, args, 2, (char*)buffer.buf + offset) != 0) {
1924 PyBuffer_Release(&buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001925 return NULL;
1926 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001927
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001928 PyBuffer_Release(&buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001929 Py_RETURN_NONE;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001930}
1931
1932static PyObject *
1933s_get_format(PyStructObject *self, void *unused)
1934{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001935 Py_INCREF(self->s_format);
1936 return self->s_format;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001937}
1938
1939static PyObject *
1940s_get_size(PyStructObject *self, void *unused)
1941{
Christian Heimes217cfd12007-12-02 14:31:20 +00001942 return PyLong_FromSsize_t(self->s_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001943}
1944
Meador Ingeb14d8c92012-07-23 10:01:29 -05001945PyDoc_STRVAR(s_sizeof__doc__,
1946"S.__sizeof__() -> size of S in memory, in bytes");
1947
1948static PyObject *
Meador Inge90bc2dbc2012-07-28 22:16:39 -05001949s_sizeof(PyStructObject *self, void *unused)
Meador Ingeb14d8c92012-07-23 10:01:29 -05001950{
1951 Py_ssize_t size;
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001952 formatcode *code;
Meador Ingeb14d8c92012-07-23 10:01:29 -05001953
Serhiy Storchaka5c4064e2015-12-19 20:05:25 +02001954 size = _PyObject_SIZE(Py_TYPE(self)) + sizeof(formatcode);
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001955 for (code = self->s_codes; code->fmtdef != NULL; code++)
1956 size += sizeof(formatcode);
Meador Ingeb14d8c92012-07-23 10:01:29 -05001957 return PyLong_FromSsize_t(size);
1958}
1959
Thomas Wouters477c8d52006-05-27 19:21:47 +00001960/* List of functions */
1961
1962static struct PyMethodDef s_methods[] = {
Antoine Pitrou9f146812013-04-27 00:20:04 +02001963 {"iter_unpack", s_iter_unpack, METH_O, s_iter_unpack__doc__},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001964 {"pack", s_pack, METH_VARARGS, s_pack__doc__},
1965 {"pack_into", s_pack_into, METH_VARARGS, s_pack_into__doc__},
1966 {"unpack", s_unpack, METH_O, s_unpack__doc__},
1967 {"unpack_from", (PyCFunction)s_unpack_from, METH_VARARGS|METH_KEYWORDS,
1968 s_unpack_from__doc__},
Meador Ingeb14d8c92012-07-23 10:01:29 -05001969 {"__sizeof__", (PyCFunction)s_sizeof, METH_NOARGS, s_sizeof__doc__},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001970 {NULL, NULL} /* sentinel */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001971};
1972
Victor Stinnerda9ec992010-12-28 13:26:42 +00001973PyDoc_STRVAR(s__doc__,
Alexander Belopolsky0bd003a2010-06-12 19:36:28 +00001974"Struct(fmt) --> compiled struct object\n"
1975"\n"
1976"Return a new Struct object which writes and reads binary data according to\n"
1977"the format string fmt. See help(struct) for more on format strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001978
1979#define OFF(x) offsetof(PyStructObject, x)
1980
1981static PyGetSetDef s_getsetlist[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001982 {"format", (getter)s_get_format, (setter)NULL, "struct format string", NULL},
1983 {"size", (getter)s_get_size, (setter)NULL, "struct size in bytes", NULL},
1984 {NULL} /* sentinel */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001985};
1986
1987static
1988PyTypeObject PyStructType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001989 PyVarObject_HEAD_INIT(NULL, 0)
1990 "Struct",
1991 sizeof(PyStructObject),
1992 0,
1993 (destructor)s_dealloc, /* tp_dealloc */
1994 0, /* tp_print */
1995 0, /* tp_getattr */
1996 0, /* tp_setattr */
1997 0, /* tp_reserved */
1998 0, /* tp_repr */
1999 0, /* tp_as_number */
2000 0, /* tp_as_sequence */
2001 0, /* tp_as_mapping */
2002 0, /* tp_hash */
2003 0, /* tp_call */
2004 0, /* tp_str */
2005 PyObject_GenericGetAttr, /* tp_getattro */
2006 PyObject_GenericSetAttr, /* tp_setattro */
2007 0, /* tp_as_buffer */
2008 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
2009 s__doc__, /* tp_doc */
2010 0, /* tp_traverse */
2011 0, /* tp_clear */
2012 0, /* tp_richcompare */
2013 offsetof(PyStructObject, weakreflist), /* tp_weaklistoffset */
2014 0, /* tp_iter */
2015 0, /* tp_iternext */
2016 s_methods, /* tp_methods */
2017 NULL, /* tp_members */
2018 s_getsetlist, /* tp_getset */
2019 0, /* tp_base */
2020 0, /* tp_dict */
2021 0, /* tp_descr_get */
2022 0, /* tp_descr_set */
2023 0, /* tp_dictoffset */
2024 s_init, /* tp_init */
2025 PyType_GenericAlloc,/* tp_alloc */
2026 s_new, /* tp_new */
2027 PyObject_Del, /* tp_free */
Thomas Wouters477c8d52006-05-27 19:21:47 +00002028};
2029
Christian Heimesa34706f2008-01-04 03:06:10 +00002030
2031/* ---- Standalone functions ---- */
2032
2033#define MAXCACHE 100
2034static PyObject *cache = NULL;
2035
2036static PyObject *
2037cache_struct(PyObject *fmt)
2038{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002039 PyObject * s_object;
Christian Heimesa34706f2008-01-04 03:06:10 +00002040
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002041 if (cache == NULL) {
2042 cache = PyDict_New();
2043 if (cache == NULL)
2044 return NULL;
2045 }
Christian Heimesa34706f2008-01-04 03:06:10 +00002046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002047 s_object = PyDict_GetItem(cache, fmt);
2048 if (s_object != NULL) {
2049 Py_INCREF(s_object);
2050 return s_object;
2051 }
Christian Heimesa34706f2008-01-04 03:06:10 +00002052
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002053 s_object = PyObject_CallFunctionObjArgs((PyObject *)(&PyStructType), fmt, NULL);
2054 if (s_object != NULL) {
2055 if (PyDict_Size(cache) >= MAXCACHE)
2056 PyDict_Clear(cache);
2057 /* Attempt to cache the result */
2058 if (PyDict_SetItem(cache, fmt, s_object) == -1)
2059 PyErr_Clear();
2060 }
2061 return s_object;
Christian Heimesa34706f2008-01-04 03:06:10 +00002062}
2063
2064PyDoc_STRVAR(clearcache_doc,
2065"Clear the internal cache.");
2066
2067static PyObject *
2068clearcache(PyObject *self)
2069{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002070 Py_CLEAR(cache);
2071 Py_RETURN_NONE;
Christian Heimesa34706f2008-01-04 03:06:10 +00002072}
2073
2074PyDoc_STRVAR(calcsize_doc,
Mark Dickinsonaacfa952010-06-12 15:43:45 +00002075"calcsize(fmt) -> integer\n\
2076\n\
2077Return size in bytes of the struct described by the format string fmt.");
Christian Heimesa34706f2008-01-04 03:06:10 +00002078
2079static PyObject *
2080calcsize(PyObject *self, PyObject *fmt)
2081{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002082 Py_ssize_t n;
2083 PyObject *s_object = cache_struct(fmt);
2084 if (s_object == NULL)
2085 return NULL;
2086 n = ((PyStructObject *)s_object)->s_size;
2087 Py_DECREF(s_object);
2088 return PyLong_FromSsize_t(n);
Christian Heimesa34706f2008-01-04 03:06:10 +00002089}
2090
2091PyDoc_STRVAR(pack_doc,
Mark Dickinsonaacfa952010-06-12 15:43:45 +00002092"pack(fmt, v1, v2, ...) -> bytes\n\
2093\n\
Mark Dickinsonfdb99f12010-06-12 16:30:53 +00002094Return a bytes object containing the values v1, v2, ... packed according\n\
2095to the format string fmt. See help(struct) for more on format strings.");
Christian Heimesa34706f2008-01-04 03:06:10 +00002096
2097static PyObject *
2098pack(PyObject *self, PyObject *args)
2099{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002100 PyObject *s_object, *fmt, *newargs, *result;
2101 Py_ssize_t n = PyTuple_GET_SIZE(args);
Christian Heimesa34706f2008-01-04 03:06:10 +00002102
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002103 if (n == 0) {
2104 PyErr_SetString(PyExc_TypeError, "missing format argument");
2105 return NULL;
2106 }
2107 fmt = PyTuple_GET_ITEM(args, 0);
2108 newargs = PyTuple_GetSlice(args, 1, n);
2109 if (newargs == NULL)
2110 return NULL;
Christian Heimesa34706f2008-01-04 03:06:10 +00002111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002112 s_object = cache_struct(fmt);
2113 if (s_object == NULL) {
2114 Py_DECREF(newargs);
2115 return NULL;
2116 }
2117 result = s_pack(s_object, newargs);
2118 Py_DECREF(newargs);
2119 Py_DECREF(s_object);
2120 return result;
Christian Heimesa34706f2008-01-04 03:06:10 +00002121}
2122
2123PyDoc_STRVAR(pack_into_doc,
Mark Dickinsonaacfa952010-06-12 15:43:45 +00002124"pack_into(fmt, buffer, offset, v1, v2, ...)\n\
2125\n\
2126Pack the values v1, v2, ... according to the format string fmt and write\n\
2127the packed bytes into the writable buffer buf starting at offset. Note\n\
Mark Dickinsonfdb99f12010-06-12 16:30:53 +00002128that the offset is a required argument. See help(struct) for more\n\
Mark Dickinsonaacfa952010-06-12 15:43:45 +00002129on format strings.");
Christian Heimesa34706f2008-01-04 03:06:10 +00002130
2131static PyObject *
2132pack_into(PyObject *self, PyObject *args)
2133{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002134 PyObject *s_object, *fmt, *newargs, *result;
2135 Py_ssize_t n = PyTuple_GET_SIZE(args);
Christian Heimesa34706f2008-01-04 03:06:10 +00002136
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002137 if (n == 0) {
2138 PyErr_SetString(PyExc_TypeError, "missing format argument");
2139 return NULL;
2140 }
2141 fmt = PyTuple_GET_ITEM(args, 0);
2142 newargs = PyTuple_GetSlice(args, 1, n);
2143 if (newargs == NULL)
2144 return NULL;
Christian Heimesa34706f2008-01-04 03:06:10 +00002145
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002146 s_object = cache_struct(fmt);
2147 if (s_object == NULL) {
2148 Py_DECREF(newargs);
2149 return NULL;
2150 }
2151 result = s_pack_into(s_object, newargs);
2152 Py_DECREF(newargs);
2153 Py_DECREF(s_object);
2154 return result;
Christian Heimesa34706f2008-01-04 03:06:10 +00002155}
2156
2157PyDoc_STRVAR(unpack_doc,
Mark Dickinsonaacfa952010-06-12 15:43:45 +00002158"unpack(fmt, buffer) -> (v1, v2, ...)\n\
2159\n\
2160Return a tuple containing values unpacked according to the format string\n\
Martin Panterb0309912016-04-15 23:03:54 +00002161fmt. The buffer's size in bytes must be calcsize(fmt). See help(struct)\n\
2162for more on format strings.");
Christian Heimesa34706f2008-01-04 03:06:10 +00002163
2164static PyObject *
2165unpack(PyObject *self, PyObject *args)
2166{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002167 PyObject *s_object, *fmt, *inputstr, *result;
Christian Heimesa34706f2008-01-04 03:06:10 +00002168
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002169 if (!PyArg_UnpackTuple(args, "unpack", 2, 2, &fmt, &inputstr))
2170 return NULL;
Christian Heimesa34706f2008-01-04 03:06:10 +00002171
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002172 s_object = cache_struct(fmt);
2173 if (s_object == NULL)
2174 return NULL;
2175 result = s_unpack(s_object, inputstr);
2176 Py_DECREF(s_object);
2177 return result;
Christian Heimesa34706f2008-01-04 03:06:10 +00002178}
2179
2180PyDoc_STRVAR(unpack_from_doc,
Mark Dickinsonc6f13962010-06-13 09:17:13 +00002181"unpack_from(fmt, buffer, offset=0) -> (v1, v2, ...)\n\
Mark Dickinsonaacfa952010-06-12 15:43:45 +00002182\n\
2183Return a tuple containing values unpacked according to the format string\n\
Martin Panterb0309912016-04-15 23:03:54 +00002184fmt. The buffer's size, minus offset, must be at least calcsize(fmt).\n\
2185See help(struct) for more on format strings.");
Christian Heimesa34706f2008-01-04 03:06:10 +00002186
2187static PyObject *
2188unpack_from(PyObject *self, PyObject *args, PyObject *kwds)
2189{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002190 PyObject *s_object, *fmt, *newargs, *result;
2191 Py_ssize_t n = PyTuple_GET_SIZE(args);
Christian Heimesa34706f2008-01-04 03:06:10 +00002192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002193 if (n == 0) {
2194 PyErr_SetString(PyExc_TypeError, "missing format argument");
2195 return NULL;
2196 }
2197 fmt = PyTuple_GET_ITEM(args, 0);
2198 newargs = PyTuple_GetSlice(args, 1, n);
2199 if (newargs == NULL)
2200 return NULL;
Christian Heimesa34706f2008-01-04 03:06:10 +00002201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002202 s_object = cache_struct(fmt);
2203 if (s_object == NULL) {
2204 Py_DECREF(newargs);
2205 return NULL;
2206 }
2207 result = s_unpack_from(s_object, newargs, kwds);
2208 Py_DECREF(newargs);
2209 Py_DECREF(s_object);
2210 return result;
Christian Heimesa34706f2008-01-04 03:06:10 +00002211}
2212
Antoine Pitrou9f146812013-04-27 00:20:04 +02002213PyDoc_STRVAR(iter_unpack_doc,
2214"iter_unpack(fmt, buffer) -> iterator(v1, v2, ...)\n\
2215\n\
2216Return an iterator yielding tuples unpacked from the given bytes\n\
2217source according to the format string, like a repeated invocation of\n\
2218unpack_from(). Requires that the bytes length be a multiple of the\n\
2219format struct size.");
2220
2221static PyObject *
2222iter_unpack(PyObject *self, PyObject *args)
2223{
2224 PyObject *s_object, *fmt, *input, *result;
2225
2226 if (!PyArg_ParseTuple(args, "OO:iter_unpack", &fmt, &input))
2227 return NULL;
2228
2229 s_object = cache_struct(fmt);
2230 if (s_object == NULL)
2231 return NULL;
2232 result = s_iter_unpack(s_object, input);
2233 Py_DECREF(s_object);
2234 return result;
2235}
2236
Christian Heimesa34706f2008-01-04 03:06:10 +00002237static struct PyMethodDef module_functions[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002238 {"_clearcache", (PyCFunction)clearcache, METH_NOARGS, clearcache_doc},
2239 {"calcsize", calcsize, METH_O, calcsize_doc},
Antoine Pitrou9f146812013-04-27 00:20:04 +02002240 {"iter_unpack", iter_unpack, METH_VARARGS, iter_unpack_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002241 {"pack", pack, METH_VARARGS, pack_doc},
2242 {"pack_into", pack_into, METH_VARARGS, pack_into_doc},
2243 {"unpack", unpack, METH_VARARGS, unpack_doc},
2244 {"unpack_from", (PyCFunction)unpack_from,
2245 METH_VARARGS|METH_KEYWORDS, unpack_from_doc},
2246 {NULL, NULL} /* sentinel */
Christian Heimesa34706f2008-01-04 03:06:10 +00002247};
2248
2249
Thomas Wouters477c8d52006-05-27 19:21:47 +00002250/* Module initialization */
2251
Christian Heimesa34706f2008-01-04 03:06:10 +00002252PyDoc_STRVAR(module_doc,
2253"Functions to convert between Python values and C structs.\n\
Benjamin Peterson4ae19462008-07-31 15:03:40 +00002254Python bytes objects are used to hold the data representing the C struct\n\
Mark Dickinson40714af2009-10-08 15:59:20 +00002255and also as format strings (explained below) to describe the layout of data\n\
2256in the C struct.\n\
Christian Heimesa34706f2008-01-04 03:06:10 +00002257\n\
2258The optional first format char indicates byte order, size and alignment:\n\
Mark Dickinson40714af2009-10-08 15:59:20 +00002259 @: native order, size & alignment (default)\n\
2260 =: native order, std. size & alignment\n\
2261 <: little-endian, std. size & alignment\n\
2262 >: big-endian, std. size & alignment\n\
2263 !: same as >\n\
Christian Heimesa34706f2008-01-04 03:06:10 +00002264\n\
2265The remaining chars indicate types of args and must match exactly;\n\
2266these can be preceded by a decimal repeat count:\n\
2267 x: pad byte (no data); c:char; b:signed byte; B:unsigned byte;\n\
Mark Dickinson40714af2009-10-08 15:59:20 +00002268 ?: _Bool (requires C99; if not available, char is used instead)\n\
Christian Heimesa34706f2008-01-04 03:06:10 +00002269 h:short; H:unsigned short; i:int; I:unsigned int;\n\
Mark Dickinson7c4e4092016-09-03 17:21:29 +01002270 l:long; L:unsigned long; f:float; d:double; e:half-float.\n\
Christian Heimesa34706f2008-01-04 03:06:10 +00002271Special cases (preceding decimal count indicates length):\n\
2272 s:string (array of char); p: pascal string (with count byte).\n\
Antoine Pitrou45d9c912011-10-06 15:27:40 +02002273Special cases (only available in native format):\n\
2274 n:ssize_t; N:size_t;\n\
Christian Heimesa34706f2008-01-04 03:06:10 +00002275 P:an integer type that is wide enough to hold a pointer.\n\
2276Special case (not in native mode unless 'long long' in platform C):\n\
2277 q:long long; Q:unsigned long long\n\
2278Whitespace between formats is ignored.\n\
2279\n\
2280The variable struct.error is an exception raised on errors.\n");
2281
Martin v. Löwis1a214512008-06-11 05:26:20 +00002282
2283static struct PyModuleDef _structmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002284 PyModuleDef_HEAD_INIT,
2285 "_struct",
2286 module_doc,
2287 -1,
2288 module_functions,
2289 NULL,
2290 NULL,
2291 NULL,
2292 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002293};
2294
Thomas Wouters477c8d52006-05-27 19:21:47 +00002295PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002296PyInit__struct(void)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002297{
Mark Dickinson06817852010-06-12 09:25:13 +00002298 PyObject *m;
Christian Heimesa34706f2008-01-04 03:06:10 +00002299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002300 m = PyModule_Create(&_structmodule);
2301 if (m == NULL)
2302 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002304 Py_TYPE(&PyStructType) = &PyType_Type;
2305 if (PyType_Ready(&PyStructType) < 0)
2306 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002308 /* Check endian and swap in faster functions */
2309 {
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02002310 const formatdef *native = native_table;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002311 formatdef *other, *ptr;
Christian Heimes743e0cd2012-10-17 23:52:17 +02002312#if PY_LITTLE_ENDIAN
2313 other = lilendian_table;
2314#else
2315 other = bigendian_table;
2316#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002317 /* Scan through the native table, find a matching
2318 entry in the endian table and swap in the
2319 native implementations whenever possible
2320 (64-bit platforms may not have "standard" sizes) */
2321 while (native->format != '\0' && other->format != '\0') {
2322 ptr = other;
2323 while (ptr->format != '\0') {
2324 if (ptr->format == native->format) {
2325 /* Match faster when formats are
2326 listed in the same order */
2327 if (ptr == other)
2328 other++;
2329 /* Only use the trick if the
2330 size matches */
2331 if (ptr->size != native->size)
2332 break;
2333 /* Skip float and double, could be
2334 "unknown" float format */
2335 if (ptr->format == 'd' || ptr->format == 'f')
2336 break;
2337 ptr->pack = native->pack;
2338 ptr->unpack = native->unpack;
2339 break;
2340 }
2341 ptr++;
2342 }
2343 native++;
2344 }
2345 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002347 /* Add some symbolic constants to the module */
2348 if (StructError == NULL) {
2349 StructError = PyErr_NewException("struct.error", NULL, NULL);
2350 if (StructError == NULL)
2351 return NULL;
2352 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002353
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002354 Py_INCREF(StructError);
2355 PyModule_AddObject(m, "error", StructError);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002357 Py_INCREF((PyObject*)&PyStructType);
2358 PyModule_AddObject(m, "Struct", (PyObject*)&PyStructType);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002360 return m;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002361}