blob: a601f03ce75f4d5a1cf15c693cc196360c80ff6e [file] [log] [blame]
Benjamin Peterson4ae19462008-07-31 15:03:40 +00001/* struct module -- pack values into and (out of) bytes objects */
Thomas Wouters477c8d52006-05-27 19:21:47 +00002
3/* New version supporting byte order, alignment and size options,
4 character strings, and unsigned numbers */
5
6#define PY_SSIZE_T_CLEAN
7
8#include "Python.h"
Thomas Wouters477c8d52006-05-27 19:21:47 +00009#include "structmember.h"
10#include <ctype.h>
11
12static PyTypeObject PyStructType;
13
Thomas Wouters477c8d52006-05-27 19:21:47 +000014/* The translation function for each format character is table driven */
15typedef struct _formatdef {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000016 char format;
17 Py_ssize_t size;
18 Py_ssize_t alignment;
19 PyObject* (*unpack)(const char *,
20 const struct _formatdef *);
21 int (*pack)(char *, PyObject *,
22 const struct _formatdef *);
Thomas Wouters477c8d52006-05-27 19:21:47 +000023} formatdef;
24
25typedef struct _formatcode {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000026 const struct _formatdef *fmtdef;
27 Py_ssize_t offset;
28 Py_ssize_t size;
Serhiy Storchakafff61f22013-05-17 10:49:44 +030029 Py_ssize_t repeat;
Thomas Wouters477c8d52006-05-27 19:21:47 +000030} formatcode;
31
32/* Struct object interface */
33
34typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000035 PyObject_HEAD
36 Py_ssize_t s_size;
37 Py_ssize_t s_len;
38 formatcode *s_codes;
39 PyObject *s_format;
40 PyObject *weakreflist; /* List of weak references */
Thomas Wouters477c8d52006-05-27 19:21:47 +000041} PyStructObject;
42
43
44#define PyStruct_Check(op) PyObject_TypeCheck(op, &PyStructType)
Christian Heimes90aa7642007-12-19 02:45:37 +000045#define PyStruct_CheckExact(op) (Py_TYPE(op) == &PyStructType)
Thomas Wouters477c8d52006-05-27 19:21:47 +000046
47
48/* Exception */
49
50static PyObject *StructError;
51
52
53/* Define various structs to figure out the alignments of types */
54
55
56typedef struct { char c; short x; } st_short;
57typedef struct { char c; int x; } st_int;
58typedef struct { char c; long x; } st_long;
59typedef struct { char c; float x; } st_float;
60typedef struct { char c; double x; } st_double;
61typedef struct { char c; void *x; } st_void_p;
Antoine Pitrou45d9c912011-10-06 15:27:40 +020062typedef struct { char c; size_t x; } st_size_t;
Thomas Wouters477c8d52006-05-27 19:21:47 +000063
64#define SHORT_ALIGN (sizeof(st_short) - sizeof(short))
65#define INT_ALIGN (sizeof(st_int) - sizeof(int))
66#define LONG_ALIGN (sizeof(st_long) - sizeof(long))
67#define FLOAT_ALIGN (sizeof(st_float) - sizeof(float))
68#define DOUBLE_ALIGN (sizeof(st_double) - sizeof(double))
69#define VOID_P_ALIGN (sizeof(st_void_p) - sizeof(void *))
Antoine Pitrou45d9c912011-10-06 15:27:40 +020070#define SIZE_T_ALIGN (sizeof(st_size_t) - sizeof(size_t))
Thomas Wouters477c8d52006-05-27 19:21:47 +000071
72/* We can't support q and Q in native mode unless the compiler does;
73 in std mode, they're 8 bytes on all platforms. */
Benjamin Petersonaf580df2016-09-06 10:46:49 -070074typedef struct { char c; long long x; } s_long_long;
75#define LONG_LONG_ALIGN (sizeof(s_long_long) - sizeof(long long))
Thomas Wouters477c8d52006-05-27 19:21:47 +000076
Thomas Woutersb2137042007-02-01 18:02:27 +000077#ifdef HAVE_C99_BOOL
78#define BOOL_TYPE _Bool
79typedef struct { char c; _Bool x; } s_bool;
80#define BOOL_ALIGN (sizeof(s_bool) - sizeof(BOOL_TYPE))
81#else
82#define BOOL_TYPE char
83#define BOOL_ALIGN 0
84#endif
85
Thomas Wouters477c8d52006-05-27 19:21:47 +000086#ifdef __powerc
87#pragma options align=reset
88#endif
89
Mark Dickinson055a3fb2010-04-03 15:26:31 +000090/* Helper for integer format codes: converts an arbitrary Python object to a
91 PyLongObject if possible, otherwise fails. Caller should decref. */
Thomas Wouters477c8d52006-05-27 19:21:47 +000092
93static PyObject *
94get_pylong(PyObject *v)
95{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000096 assert(v != NULL);
97 if (!PyLong_Check(v)) {
98 /* Not an integer; try to use __index__ to convert. */
99 if (PyIndex_Check(v)) {
100 v = PyNumber_Index(v);
101 if (v == NULL)
102 return NULL;
103 }
104 else {
105 PyErr_SetString(StructError,
106 "required argument is not an integer");
107 return NULL;
108 }
109 }
110 else
111 Py_INCREF(v);
Mark Dickinsonea835e72009-04-19 20:40:33 +0000112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000113 assert(PyLong_Check(v));
114 return v;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000115}
116
Mark Dickinsonea835e72009-04-19 20:40:33 +0000117/* Helper routine to get a C long and raise the appropriate error if it isn't
118 one */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000119
120static int
121get_long(PyObject *v, long *p)
122{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000123 long x;
Mark Dickinsonea835e72009-04-19 20:40:33 +0000124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000125 v = get_pylong(v);
126 if (v == NULL)
127 return -1;
128 assert(PyLong_Check(v));
129 x = PyLong_AsLong(v);
130 Py_DECREF(v);
131 if (x == (long)-1 && PyErr_Occurred()) {
132 if (PyErr_ExceptionMatches(PyExc_OverflowError))
133 PyErr_SetString(StructError,
134 "argument out of range");
135 return -1;
136 }
137 *p = x;
138 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000139}
140
141
142/* Same, but handling unsigned long */
143
144static int
145get_ulong(PyObject *v, unsigned long *p)
146{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000147 unsigned long x;
Mark Dickinsonea835e72009-04-19 20:40:33 +0000148
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000149 v = get_pylong(v);
150 if (v == NULL)
151 return -1;
152 assert(PyLong_Check(v));
153 x = PyLong_AsUnsignedLong(v);
154 Py_DECREF(v);
155 if (x == (unsigned long)-1 && PyErr_Occurred()) {
156 if (PyErr_ExceptionMatches(PyExc_OverflowError))
157 PyErr_SetString(StructError,
158 "argument out of range");
159 return -1;
160 }
161 *p = x;
162 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000163}
164
Thomas Wouters477c8d52006-05-27 19:21:47 +0000165/* Same, but handling native long long. */
166
167static int
Benjamin Petersonaf580df2016-09-06 10:46:49 -0700168get_longlong(PyObject *v, long long *p)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000169{
Benjamin Petersonaf580df2016-09-06 10:46:49 -0700170 long long x;
Mark Dickinson055a3fb2010-04-03 15:26:31 +0000171
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000172 v = get_pylong(v);
173 if (v == NULL)
174 return -1;
175 assert(PyLong_Check(v));
176 x = PyLong_AsLongLong(v);
177 Py_DECREF(v);
Benjamin Petersonaf580df2016-09-06 10:46:49 -0700178 if (x == (long long)-1 && PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000179 if (PyErr_ExceptionMatches(PyExc_OverflowError))
180 PyErr_SetString(StructError,
181 "argument out of range");
182 return -1;
183 }
184 *p = x;
185 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000186}
187
188/* Same, but handling native unsigned long long. */
189
190static int
Benjamin Petersonaf580df2016-09-06 10:46:49 -0700191get_ulonglong(PyObject *v, unsigned long long *p)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000192{
Benjamin Petersonaf580df2016-09-06 10:46:49 -0700193 unsigned long long x;
Mark Dickinson055a3fb2010-04-03 15:26:31 +0000194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000195 v = get_pylong(v);
196 if (v == NULL)
197 return -1;
198 assert(PyLong_Check(v));
199 x = PyLong_AsUnsignedLongLong(v);
200 Py_DECREF(v);
Benjamin Petersonaf580df2016-09-06 10:46:49 -0700201 if (x == (unsigned long long)-1 && PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000202 if (PyErr_ExceptionMatches(PyExc_OverflowError))
203 PyErr_SetString(StructError,
204 "argument out of range");
205 return -1;
206 }
207 *p = x;
208 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000209}
210
Antoine Pitrou45d9c912011-10-06 15:27:40 +0200211/* Same, but handling Py_ssize_t */
212
213static int
214get_ssize_t(PyObject *v, Py_ssize_t *p)
215{
216 Py_ssize_t x;
217
218 v = get_pylong(v);
219 if (v == NULL)
220 return -1;
221 assert(PyLong_Check(v));
222 x = PyLong_AsSsize_t(v);
223 Py_DECREF(v);
224 if (x == (Py_ssize_t)-1 && PyErr_Occurred()) {
225 if (PyErr_ExceptionMatches(PyExc_OverflowError))
226 PyErr_SetString(StructError,
227 "argument out of range");
228 return -1;
229 }
230 *p = x;
231 return 0;
232}
233
234/* Same, but handling size_t */
235
236static int
237get_size_t(PyObject *v, size_t *p)
238{
239 size_t x;
240
241 v = get_pylong(v);
242 if (v == NULL)
243 return -1;
244 assert(PyLong_Check(v));
245 x = PyLong_AsSize_t(v);
246 Py_DECREF(v);
247 if (x == (size_t)-1 && PyErr_Occurred()) {
248 if (PyErr_ExceptionMatches(PyExc_OverflowError))
249 PyErr_SetString(StructError,
250 "argument out of range");
251 return -1;
252 }
253 *p = x;
254 return 0;
255}
256
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000257
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000258#define RANGE_ERROR(x, f, flag, mask) return _range_error(f, flag)
259
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000260
Thomas Wouters477c8d52006-05-27 19:21:47 +0000261/* Floating point helpers */
262
263static PyObject *
Mark Dickinson7c4e4092016-09-03 17:21:29 +0100264unpack_halffloat(const char *p, /* start of 2-byte string */
265 int le) /* true for little-endian, false for big-endian */
266{
267 double x;
268
269 x = _PyFloat_Unpack2((unsigned char *)p, le);
270 if (x == -1.0 && PyErr_Occurred()) {
271 return NULL;
272 }
273 return PyFloat_FromDouble(x);
274}
275
276static int
277pack_halffloat(char *p, /* start of 2-byte string */
278 PyObject *v, /* value to pack */
279 int le) /* true for little-endian, false for big-endian */
280{
281 double x = PyFloat_AsDouble(v);
282 if (x == -1.0 && PyErr_Occurred()) {
283 PyErr_SetString(StructError,
284 "required argument is not a float");
285 return -1;
286 }
287 return _PyFloat_Pack2(x, (unsigned char *)p, le);
288}
289
290static PyObject *
Thomas Wouters477c8d52006-05-27 19:21:47 +0000291unpack_float(const char *p, /* start of 4-byte string */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000292 int le) /* true for little-endian, false for big-endian */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000293{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000294 double x;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000296 x = _PyFloat_Unpack4((unsigned char *)p, le);
297 if (x == -1.0 && PyErr_Occurred())
298 return NULL;
299 return PyFloat_FromDouble(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000300}
301
302static PyObject *
303unpack_double(const char *p, /* start of 8-byte string */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000304 int le) /* true for little-endian, false for big-endian */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000305{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000306 double x;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000308 x = _PyFloat_Unpack8((unsigned char *)p, le);
309 if (x == -1.0 && PyErr_Occurred())
310 return NULL;
311 return PyFloat_FromDouble(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000312}
313
314/* Helper to format the range error exceptions */
315static int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000316_range_error(const formatdef *f, int is_unsigned)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000317{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000318 /* ulargest is the largest unsigned value with f->size bytes.
319 * Note that the simpler:
320 * ((size_t)1 << (f->size * 8)) - 1
321 * doesn't work when f->size == sizeof(size_t) because C doesn't
322 * define what happens when a left shift count is >= the number of
323 * bits in the integer being shifted; e.g., on some boxes it doesn't
324 * shift at all when they're equal.
325 */
326 const size_t ulargest = (size_t)-1 >> ((SIZEOF_SIZE_T - f->size)*8);
327 assert(f->size >= 1 && f->size <= SIZEOF_SIZE_T);
328 if (is_unsigned)
329 PyErr_Format(StructError,
330 "'%c' format requires 0 <= number <= %zu",
331 f->format,
332 ulargest);
333 else {
334 const Py_ssize_t largest = (Py_ssize_t)(ulargest >> 1);
335 PyErr_Format(StructError,
336 "'%c' format requires %zd <= number <= %zd",
337 f->format,
338 ~ largest,
339 largest);
340 }
Mark Dickinsonae681df2009-03-21 10:26:31 +0000341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000342 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000343}
344
345
346
347/* A large number of small routines follow, with names of the form
348
349 [bln][up]_TYPE
350
351 [bln] distiguishes among big-endian, little-endian and native.
352 [pu] distiguishes between pack (to struct) and unpack (from struct).
353 TYPE is one of char, byte, ubyte, etc.
354*/
355
356/* Native mode routines. ****************************************************/
357/* NOTE:
358 In all n[up]_<type> routines handling types larger than 1 byte, there is
359 *no* guarantee that the p pointer is properly aligned for each type,
360 therefore memcpy is called. An intermediate variable is used to
361 compensate for big-endian architectures.
362 Normally both the intermediate variable and the memcpy call will be
363 skipped by C optimisation in little-endian architectures (gcc >= 2.91
364 does this). */
365
366static PyObject *
367nu_char(const char *p, const formatdef *f)
368{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000369 return PyBytes_FromStringAndSize(p, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000370}
371
372static PyObject *
373nu_byte(const char *p, const formatdef *f)
374{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 return PyLong_FromLong((long) *(signed char *)p);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000376}
377
378static PyObject *
379nu_ubyte(const char *p, const formatdef *f)
380{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000381 return PyLong_FromLong((long) *(unsigned char *)p);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000382}
383
384static PyObject *
385nu_short(const char *p, const formatdef *f)
386{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000387 short x;
388 memcpy((char *)&x, p, sizeof x);
389 return PyLong_FromLong((long)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000390}
391
392static PyObject *
393nu_ushort(const char *p, const formatdef *f)
394{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000395 unsigned short x;
396 memcpy((char *)&x, p, sizeof x);
397 return PyLong_FromLong((long)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000398}
399
400static PyObject *
401nu_int(const char *p, const formatdef *f)
402{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000403 int x;
404 memcpy((char *)&x, p, sizeof x);
405 return PyLong_FromLong((long)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000406}
407
408static PyObject *
409nu_uint(const char *p, const formatdef *f)
410{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 unsigned int x;
412 memcpy((char *)&x, p, sizeof x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000413#if (SIZEOF_LONG > SIZEOF_INT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000414 return PyLong_FromLong((long)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000415#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000416 if (x <= ((unsigned int)LONG_MAX))
417 return PyLong_FromLong((long)x);
418 return PyLong_FromUnsignedLong((unsigned long)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000419#endif
420}
421
422static PyObject *
423nu_long(const char *p, const formatdef *f)
424{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425 long x;
426 memcpy((char *)&x, p, sizeof x);
427 return PyLong_FromLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000428}
429
430static PyObject *
431nu_ulong(const char *p, const formatdef *f)
432{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000433 unsigned long x;
434 memcpy((char *)&x, p, sizeof x);
435 if (x <= LONG_MAX)
436 return PyLong_FromLong((long)x);
437 return PyLong_FromUnsignedLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000438}
439
Antoine Pitrou45d9c912011-10-06 15:27:40 +0200440static PyObject *
441nu_ssize_t(const char *p, const formatdef *f)
442{
443 Py_ssize_t x;
444 memcpy((char *)&x, p, sizeof x);
445 return PyLong_FromSsize_t(x);
446}
447
448static PyObject *
449nu_size_t(const char *p, const formatdef *f)
450{
451 size_t x;
452 memcpy((char *)&x, p, sizeof x);
453 return PyLong_FromSize_t(x);
454}
455
456
Thomas Wouters477c8d52006-05-27 19:21:47 +0000457/* Native mode doesn't support q or Q unless the platform C supports
458 long long (or, on Windows, __int64). */
459
Thomas Wouters477c8d52006-05-27 19:21:47 +0000460static PyObject *
461nu_longlong(const char *p, const formatdef *f)
462{
Benjamin Petersonaf580df2016-09-06 10:46:49 -0700463 long long x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000464 memcpy((char *)&x, p, sizeof x);
465 if (x >= LONG_MIN && x <= LONG_MAX)
Benjamin Petersonaf580df2016-09-06 10:46:49 -0700466 return PyLong_FromLong(Py_SAFE_DOWNCAST(x, long long, long));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000467 return PyLong_FromLongLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000468}
469
470static PyObject *
471nu_ulonglong(const char *p, const formatdef *f)
472{
Benjamin Petersonaf580df2016-09-06 10:46:49 -0700473 unsigned long long x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 memcpy((char *)&x, p, sizeof x);
475 if (x <= LONG_MAX)
Benjamin Petersonaf580df2016-09-06 10:46:49 -0700476 return PyLong_FromLong(Py_SAFE_DOWNCAST(x, unsigned long long, long));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 return PyLong_FromUnsignedLongLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000478}
479
Thomas Wouters477c8d52006-05-27 19:21:47 +0000480static PyObject *
Thomas Woutersb2137042007-02-01 18:02:27 +0000481nu_bool(const char *p, const formatdef *f)
482{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 BOOL_TYPE x;
484 memcpy((char *)&x, p, sizeof x);
485 return PyBool_FromLong(x != 0);
Thomas Woutersb2137042007-02-01 18:02:27 +0000486}
487
488
489static PyObject *
Mark Dickinson7c4e4092016-09-03 17:21:29 +0100490nu_halffloat(const char *p, const formatdef *f)
491{
492#if PY_LITTLE_ENDIAN
493 return unpack_halffloat(p, 1);
494#else
495 return unpack_halffloat(p, 0);
496#endif
497}
498
499static PyObject *
Thomas Wouters477c8d52006-05-27 19:21:47 +0000500nu_float(const char *p, const formatdef *f)
501{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 float x;
503 memcpy((char *)&x, p, sizeof x);
504 return PyFloat_FromDouble((double)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000505}
506
507static PyObject *
508nu_double(const char *p, const formatdef *f)
509{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 double x;
511 memcpy((char *)&x, p, sizeof x);
512 return PyFloat_FromDouble(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000513}
514
515static PyObject *
516nu_void_p(const char *p, const formatdef *f)
517{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 void *x;
519 memcpy((char *)&x, p, sizeof x);
520 return PyLong_FromVoidPtr(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000521}
522
523static int
524np_byte(char *p, PyObject *v, const formatdef *f)
525{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 long x;
527 if (get_long(v, &x) < 0)
528 return -1;
529 if (x < -128 || x > 127){
530 PyErr_SetString(StructError,
531 "byte format requires -128 <= number <= 127");
532 return -1;
533 }
534 *p = (char)x;
535 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000536}
537
538static int
539np_ubyte(char *p, PyObject *v, const formatdef *f)
540{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000541 long x;
542 if (get_long(v, &x) < 0)
543 return -1;
544 if (x < 0 || x > 255){
545 PyErr_SetString(StructError,
546 "ubyte format requires 0 <= number <= 255");
547 return -1;
548 }
549 *p = (char)x;
550 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000551}
552
553static int
554np_char(char *p, PyObject *v, const formatdef *f)
555{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000556 if (!PyBytes_Check(v) || PyBytes_Size(v) != 1) {
557 PyErr_SetString(StructError,
Victor Stinnerda9ec992010-12-28 13:26:42 +0000558 "char format requires a bytes object of length 1");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 return -1;
560 }
561 *p = *PyBytes_AsString(v);
562 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000563}
564
565static int
566np_short(char *p, PyObject *v, const formatdef *f)
567{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000568 long x;
569 short y;
570 if (get_long(v, &x) < 0)
571 return -1;
572 if (x < SHRT_MIN || x > SHRT_MAX){
573 PyErr_SetString(StructError,
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200574 "short format requires " Py_STRINGIFY(SHRT_MIN)
575 " <= number <= " Py_STRINGIFY(SHRT_MAX));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000576 return -1;
577 }
578 y = (short)x;
579 memcpy(p, (char *)&y, sizeof y);
580 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000581}
582
583static int
584np_ushort(char *p, PyObject *v, const formatdef *f)
585{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000586 long x;
587 unsigned short y;
588 if (get_long(v, &x) < 0)
589 return -1;
590 if (x < 0 || x > USHRT_MAX){
591 PyErr_SetString(StructError,
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200592 "ushort format requires 0 <= number <= "
593 Py_STRINGIFY(USHRT_MAX));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 return -1;
595 }
596 y = (unsigned short)x;
597 memcpy(p, (char *)&y, sizeof y);
598 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000599}
600
601static int
602np_int(char *p, PyObject *v, const formatdef *f)
603{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000604 long x;
605 int y;
606 if (get_long(v, &x) < 0)
607 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000608#if (SIZEOF_LONG > SIZEOF_INT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 if ((x < ((long)INT_MIN)) || (x > ((long)INT_MAX)))
610 RANGE_ERROR(x, f, 0, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000611#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 y = (int)x;
613 memcpy(p, (char *)&y, sizeof y);
614 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000615}
616
617static int
618np_uint(char *p, PyObject *v, const formatdef *f)
619{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000620 unsigned long x;
621 unsigned int y;
622 if (get_ulong(v, &x) < 0)
623 return -1;
624 y = (unsigned int)x;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000625#if (SIZEOF_LONG > SIZEOF_INT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000626 if (x > ((unsigned long)UINT_MAX))
627 RANGE_ERROR(y, f, 1, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000628#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000629 memcpy(p, (char *)&y, sizeof y);
630 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000631}
632
633static int
634np_long(char *p, PyObject *v, const formatdef *f)
635{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 long x;
637 if (get_long(v, &x) < 0)
638 return -1;
639 memcpy(p, (char *)&x, sizeof x);
640 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000641}
642
643static int
644np_ulong(char *p, PyObject *v, const formatdef *f)
645{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 unsigned long x;
647 if (get_ulong(v, &x) < 0)
648 return -1;
649 memcpy(p, (char *)&x, sizeof x);
650 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000651}
652
Antoine Pitrou45d9c912011-10-06 15:27:40 +0200653static int
654np_ssize_t(char *p, PyObject *v, const formatdef *f)
655{
656 Py_ssize_t x;
657 if (get_ssize_t(v, &x) < 0)
658 return -1;
659 memcpy(p, (char *)&x, sizeof x);
660 return 0;
661}
662
663static int
664np_size_t(char *p, PyObject *v, const formatdef *f)
665{
666 size_t x;
667 if (get_size_t(v, &x) < 0)
668 return -1;
669 memcpy(p, (char *)&x, sizeof x);
670 return 0;
671}
672
Thomas Wouters477c8d52006-05-27 19:21:47 +0000673static int
674np_longlong(char *p, PyObject *v, const formatdef *f)
675{
Benjamin Petersonaf580df2016-09-06 10:46:49 -0700676 long long x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000677 if (get_longlong(v, &x) < 0)
678 return -1;
679 memcpy(p, (char *)&x, sizeof x);
680 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000681}
682
683static int
684np_ulonglong(char *p, PyObject *v, const formatdef *f)
685{
Benjamin Petersonaf580df2016-09-06 10:46:49 -0700686 unsigned long long x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000687 if (get_ulonglong(v, &x) < 0)
688 return -1;
689 memcpy(p, (char *)&x, sizeof x);
690 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000691}
Thomas Wouters477c8d52006-05-27 19:21:47 +0000692
Thomas Woutersb2137042007-02-01 18:02:27 +0000693
694static int
695np_bool(char *p, PyObject *v, const formatdef *f)
696{
Benjamin Petersonde73c452010-07-07 18:54:59 +0000697 int y;
698 BOOL_TYPE x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000699 y = PyObject_IsTrue(v);
Benjamin Petersonde73c452010-07-07 18:54:59 +0000700 if (y < 0)
701 return -1;
702 x = y;
703 memcpy(p, (char *)&x, sizeof x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000704 return 0;
Thomas Woutersb2137042007-02-01 18:02:27 +0000705}
706
Thomas Wouters477c8d52006-05-27 19:21:47 +0000707static int
Mark Dickinson7c4e4092016-09-03 17:21:29 +0100708np_halffloat(char *p, PyObject *v, const formatdef *f)
709{
710#if PY_LITTLE_ENDIAN
711 return pack_halffloat(p, v, 1);
712#else
713 return pack_halffloat(p, v, 0);
714#endif
715}
716
717static int
Thomas Wouters477c8d52006-05-27 19:21:47 +0000718np_float(char *p, PyObject *v, const formatdef *f)
719{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000720 float x = (float)PyFloat_AsDouble(v);
721 if (x == -1 && PyErr_Occurred()) {
722 PyErr_SetString(StructError,
723 "required argument is not a float");
724 return -1;
725 }
726 memcpy(p, (char *)&x, sizeof x);
727 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000728}
729
730static int
731np_double(char *p, PyObject *v, const formatdef *f)
732{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000733 double x = PyFloat_AsDouble(v);
734 if (x == -1 && PyErr_Occurred()) {
735 PyErr_SetString(StructError,
736 "required argument is not a float");
737 return -1;
738 }
739 memcpy(p, (char *)&x, sizeof(double));
740 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000741}
742
743static int
744np_void_p(char *p, PyObject *v, const formatdef *f)
745{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000746 void *x;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000747
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000748 v = get_pylong(v);
749 if (v == NULL)
750 return -1;
751 assert(PyLong_Check(v));
752 x = PyLong_AsVoidPtr(v);
753 Py_DECREF(v);
754 if (x == NULL && PyErr_Occurred())
755 return -1;
756 memcpy(p, (char *)&x, sizeof x);
757 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000758}
759
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200760static const formatdef native_table[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000761 {'x', sizeof(char), 0, NULL},
762 {'b', sizeof(char), 0, nu_byte, np_byte},
763 {'B', sizeof(char), 0, nu_ubyte, np_ubyte},
764 {'c', sizeof(char), 0, nu_char, np_char},
765 {'s', sizeof(char), 0, NULL},
766 {'p', sizeof(char), 0, NULL},
767 {'h', sizeof(short), SHORT_ALIGN, nu_short, np_short},
768 {'H', sizeof(short), SHORT_ALIGN, nu_ushort, np_ushort},
769 {'i', sizeof(int), INT_ALIGN, nu_int, np_int},
770 {'I', sizeof(int), INT_ALIGN, nu_uint, np_uint},
771 {'l', sizeof(long), LONG_ALIGN, nu_long, np_long},
772 {'L', sizeof(long), LONG_ALIGN, nu_ulong, np_ulong},
Antoine Pitrou45d9c912011-10-06 15:27:40 +0200773 {'n', sizeof(size_t), SIZE_T_ALIGN, nu_ssize_t, np_ssize_t},
774 {'N', sizeof(size_t), SIZE_T_ALIGN, nu_size_t, np_size_t},
Benjamin Petersonaf580df2016-09-06 10:46:49 -0700775 {'q', sizeof(long long), LONG_LONG_ALIGN, nu_longlong, np_longlong},
776 {'Q', sizeof(long long), LONG_LONG_ALIGN, nu_ulonglong,np_ulonglong},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000777 {'?', sizeof(BOOL_TYPE), BOOL_ALIGN, nu_bool, np_bool},
Mark Dickinson7c4e4092016-09-03 17:21:29 +0100778 {'e', sizeof(short), SHORT_ALIGN, nu_halffloat, np_halffloat},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 {'f', sizeof(float), FLOAT_ALIGN, nu_float, np_float},
780 {'d', sizeof(double), DOUBLE_ALIGN, nu_double, np_double},
781 {'P', sizeof(void *), VOID_P_ALIGN, nu_void_p, np_void_p},
782 {0}
Thomas Wouters477c8d52006-05-27 19:21:47 +0000783};
784
785/* Big-endian routines. *****************************************************/
786
787static PyObject *
788bu_int(const char *p, const formatdef *f)
789{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 long x = 0;
791 Py_ssize_t i = f->size;
792 const unsigned char *bytes = (const unsigned char *)p;
793 do {
794 x = (x<<8) | *bytes++;
795 } while (--i > 0);
796 /* Extend the sign bit. */
797 if (SIZEOF_LONG > f->size)
798 x |= -(x & (1L << ((8 * f->size) - 1)));
799 return PyLong_FromLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000800}
801
802static PyObject *
803bu_uint(const char *p, const formatdef *f)
804{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000805 unsigned long x = 0;
806 Py_ssize_t i = f->size;
807 const unsigned char *bytes = (const unsigned char *)p;
808 do {
809 x = (x<<8) | *bytes++;
810 } while (--i > 0);
811 if (x <= LONG_MAX)
812 return PyLong_FromLong((long)x);
813 return PyLong_FromUnsignedLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000814}
815
816static PyObject *
817bu_longlong(const char *p, const formatdef *f)
818{
Benjamin Petersonaf580df2016-09-06 10:46:49 -0700819 long long x = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000820 Py_ssize_t i = f->size;
821 const unsigned char *bytes = (const unsigned char *)p;
822 do {
823 x = (x<<8) | *bytes++;
824 } while (--i > 0);
825 /* Extend the sign bit. */
826 if (SIZEOF_LONG_LONG > f->size)
Benjamin Petersonaf580df2016-09-06 10:46:49 -0700827 x |= -(x & ((long long)1 << ((8 * f->size) - 1)));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000828 if (x >= LONG_MIN && x <= LONG_MAX)
Benjamin Petersonaf580df2016-09-06 10:46:49 -0700829 return PyLong_FromLong(Py_SAFE_DOWNCAST(x, long long, long));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 return PyLong_FromLongLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000831}
832
833static PyObject *
834bu_ulonglong(const char *p, const formatdef *f)
835{
Benjamin Petersonaf580df2016-09-06 10:46:49 -0700836 unsigned long long x = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000837 Py_ssize_t i = f->size;
838 const unsigned char *bytes = (const unsigned char *)p;
839 do {
840 x = (x<<8) | *bytes++;
841 } while (--i > 0);
842 if (x <= LONG_MAX)
Benjamin Petersonaf580df2016-09-06 10:46:49 -0700843 return PyLong_FromLong(Py_SAFE_DOWNCAST(x, unsigned long long, long));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000844 return PyLong_FromUnsignedLongLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000845}
846
847static PyObject *
Mark Dickinson7c4e4092016-09-03 17:21:29 +0100848bu_halffloat(const char *p, const formatdef *f)
849{
850 return unpack_halffloat(p, 0);
851}
852
853static PyObject *
Thomas Wouters477c8d52006-05-27 19:21:47 +0000854bu_float(const char *p, const formatdef *f)
855{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000856 return unpack_float(p, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000857}
858
859static PyObject *
860bu_double(const char *p, const formatdef *f)
861{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 return unpack_double(p, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000863}
864
Thomas Woutersb2137042007-02-01 18:02:27 +0000865static PyObject *
866bu_bool(const char *p, const formatdef *f)
867{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 char x;
869 memcpy((char *)&x, p, sizeof x);
870 return PyBool_FromLong(x != 0);
Thomas Woutersb2137042007-02-01 18:02:27 +0000871}
872
Thomas Wouters477c8d52006-05-27 19:21:47 +0000873static int
874bp_int(char *p, PyObject *v, const formatdef *f)
875{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000876 long x;
877 Py_ssize_t i;
878 if (get_long(v, &x) < 0)
879 return -1;
880 i = f->size;
881 if (i != SIZEOF_LONG) {
882 if ((i == 2) && (x < -32768 || x > 32767))
883 RANGE_ERROR(x, f, 0, 0xffffL);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000884#if (SIZEOF_LONG != 4)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000885 else if ((i == 4) && (x < -2147483648L || x > 2147483647L))
886 RANGE_ERROR(x, f, 0, 0xffffffffL);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000887#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000888 }
889 do {
890 p[--i] = (char)x;
891 x >>= 8;
892 } while (i > 0);
893 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000894}
895
896static int
897bp_uint(char *p, PyObject *v, const formatdef *f)
898{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000899 unsigned long x;
900 Py_ssize_t i;
901 if (get_ulong(v, &x) < 0)
902 return -1;
903 i = f->size;
904 if (i != SIZEOF_LONG) {
905 unsigned long maxint = 1;
906 maxint <<= (unsigned long)(i * 8);
907 if (x >= maxint)
908 RANGE_ERROR(x, f, 1, maxint - 1);
909 }
910 do {
911 p[--i] = (char)x;
912 x >>= 8;
913 } while (i > 0);
914 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000915}
916
917static int
918bp_longlong(char *p, PyObject *v, const formatdef *f)
919{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 int res;
921 v = get_pylong(v);
922 if (v == NULL)
923 return -1;
924 res = _PyLong_AsByteArray((PyLongObject *)v,
925 (unsigned char *)p,
926 8,
927 0, /* little_endian */
928 1 /* signed */);
929 Py_DECREF(v);
930 return res;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000931}
932
933static int
934bp_ulonglong(char *p, PyObject *v, const formatdef *f)
935{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 int res;
937 v = get_pylong(v);
938 if (v == NULL)
939 return -1;
940 res = _PyLong_AsByteArray((PyLongObject *)v,
941 (unsigned char *)p,
942 8,
943 0, /* little_endian */
944 0 /* signed */);
945 Py_DECREF(v);
946 return res;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000947}
948
949static int
Mark Dickinson7c4e4092016-09-03 17:21:29 +0100950bp_halffloat(char *p, PyObject *v, const formatdef *f)
951{
952 return pack_halffloat(p, v, 0);
953}
954
955static int
Thomas Wouters477c8d52006-05-27 19:21:47 +0000956bp_float(char *p, PyObject *v, const formatdef *f)
957{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000958 double x = PyFloat_AsDouble(v);
959 if (x == -1 && PyErr_Occurred()) {
960 PyErr_SetString(StructError,
961 "required argument is not a float");
962 return -1;
963 }
964 return _PyFloat_Pack4(x, (unsigned char *)p, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000965}
966
967static int
968bp_double(char *p, PyObject *v, const formatdef *f)
969{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000970 double x = PyFloat_AsDouble(v);
971 if (x == -1 && PyErr_Occurred()) {
972 PyErr_SetString(StructError,
973 "required argument is not a float");
974 return -1;
975 }
976 return _PyFloat_Pack8(x, (unsigned char *)p, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000977}
978
Thomas Woutersb2137042007-02-01 18:02:27 +0000979static int
980bp_bool(char *p, PyObject *v, const formatdef *f)
981{
Mark Dickinsoneff5d852010-07-18 07:29:02 +0000982 int y;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000983 y = PyObject_IsTrue(v);
Benjamin Petersonde73c452010-07-07 18:54:59 +0000984 if (y < 0)
985 return -1;
Mark Dickinsoneff5d852010-07-18 07:29:02 +0000986 *p = (char)y;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987 return 0;
Thomas Woutersb2137042007-02-01 18:02:27 +0000988}
989
Thomas Wouters477c8d52006-05-27 19:21:47 +0000990static formatdef bigendian_table[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 {'x', 1, 0, NULL},
992 {'b', 1, 0, nu_byte, np_byte},
993 {'B', 1, 0, nu_ubyte, np_ubyte},
994 {'c', 1, 0, nu_char, np_char},
995 {'s', 1, 0, NULL},
996 {'p', 1, 0, NULL},
997 {'h', 2, 0, bu_int, bp_int},
998 {'H', 2, 0, bu_uint, bp_uint},
999 {'i', 4, 0, bu_int, bp_int},
1000 {'I', 4, 0, bu_uint, bp_uint},
1001 {'l', 4, 0, bu_int, bp_int},
1002 {'L', 4, 0, bu_uint, bp_uint},
1003 {'q', 8, 0, bu_longlong, bp_longlong},
1004 {'Q', 8, 0, bu_ulonglong, bp_ulonglong},
1005 {'?', 1, 0, bu_bool, bp_bool},
Mark Dickinson7c4e4092016-09-03 17:21:29 +01001006 {'e', 2, 0, bu_halffloat, bp_halffloat},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001007 {'f', 4, 0, bu_float, bp_float},
1008 {'d', 8, 0, bu_double, bp_double},
1009 {0}
Thomas Wouters477c8d52006-05-27 19:21:47 +00001010};
1011
1012/* Little-endian routines. *****************************************************/
1013
1014static PyObject *
1015lu_int(const char *p, const formatdef *f)
1016{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 long x = 0;
1018 Py_ssize_t i = f->size;
1019 const unsigned char *bytes = (const unsigned char *)p;
1020 do {
1021 x = (x<<8) | bytes[--i];
1022 } while (i > 0);
1023 /* Extend the sign bit. */
1024 if (SIZEOF_LONG > f->size)
1025 x |= -(x & (1L << ((8 * f->size) - 1)));
1026 return PyLong_FromLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001027}
1028
1029static PyObject *
1030lu_uint(const char *p, const formatdef *f)
1031{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001032 unsigned long x = 0;
1033 Py_ssize_t i = f->size;
1034 const unsigned char *bytes = (const unsigned char *)p;
1035 do {
1036 x = (x<<8) | bytes[--i];
1037 } while (i > 0);
1038 if (x <= LONG_MAX)
1039 return PyLong_FromLong((long)x);
1040 return PyLong_FromUnsignedLong((long)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001041}
1042
1043static PyObject *
1044lu_longlong(const char *p, const formatdef *f)
1045{
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001046 long long x = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001047 Py_ssize_t i = f->size;
1048 const unsigned char *bytes = (const unsigned char *)p;
1049 do {
1050 x = (x<<8) | bytes[--i];
1051 } while (i > 0);
1052 /* Extend the sign bit. */
1053 if (SIZEOF_LONG_LONG > f->size)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001054 x |= -(x & ((long long)1 << ((8 * f->size) - 1)));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001055 if (x >= LONG_MIN && x <= LONG_MAX)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001056 return PyLong_FromLong(Py_SAFE_DOWNCAST(x, long long, long));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001057 return PyLong_FromLongLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001058}
1059
1060static PyObject *
1061lu_ulonglong(const char *p, const formatdef *f)
1062{
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001063 unsigned long long x = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001064 Py_ssize_t i = f->size;
1065 const unsigned char *bytes = (const unsigned char *)p;
1066 do {
1067 x = (x<<8) | bytes[--i];
1068 } while (i > 0);
1069 if (x <= LONG_MAX)
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001070 return PyLong_FromLong(Py_SAFE_DOWNCAST(x, unsigned long long, long));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 return PyLong_FromUnsignedLongLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001072}
1073
1074static PyObject *
Mark Dickinson7c4e4092016-09-03 17:21:29 +01001075lu_halffloat(const char *p, const formatdef *f)
1076{
1077 return unpack_halffloat(p, 1);
1078}
1079
1080static PyObject *
Thomas Wouters477c8d52006-05-27 19:21:47 +00001081lu_float(const char *p, const formatdef *f)
1082{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 return unpack_float(p, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001084}
1085
1086static PyObject *
1087lu_double(const char *p, const formatdef *f)
1088{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001089 return unpack_double(p, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001090}
1091
1092static int
1093lp_int(char *p, PyObject *v, const formatdef *f)
1094{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001095 long x;
1096 Py_ssize_t i;
1097 if (get_long(v, &x) < 0)
1098 return -1;
1099 i = f->size;
1100 if (i != SIZEOF_LONG) {
1101 if ((i == 2) && (x < -32768 || x > 32767))
1102 RANGE_ERROR(x, f, 0, 0xffffL);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001103#if (SIZEOF_LONG != 4)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001104 else if ((i == 4) && (x < -2147483648L || x > 2147483647L))
1105 RANGE_ERROR(x, f, 0, 0xffffffffL);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001106#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001107 }
1108 do {
1109 *p++ = (char)x;
1110 x >>= 8;
1111 } while (--i > 0);
1112 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001113}
1114
1115static int
1116lp_uint(char *p, PyObject *v, const formatdef *f)
1117{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001118 unsigned long x;
1119 Py_ssize_t i;
1120 if (get_ulong(v, &x) < 0)
1121 return -1;
1122 i = f->size;
1123 if (i != SIZEOF_LONG) {
1124 unsigned long maxint = 1;
1125 maxint <<= (unsigned long)(i * 8);
1126 if (x >= maxint)
1127 RANGE_ERROR(x, f, 1, maxint - 1);
1128 }
1129 do {
1130 *p++ = (char)x;
1131 x >>= 8;
1132 } while (--i > 0);
1133 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001134}
1135
1136static int
1137lp_longlong(char *p, PyObject *v, const formatdef *f)
1138{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001139 int res;
1140 v = get_pylong(v);
1141 if (v == NULL)
1142 return -1;
1143 res = _PyLong_AsByteArray((PyLongObject*)v,
1144 (unsigned char *)p,
1145 8,
1146 1, /* little_endian */
1147 1 /* signed */);
1148 Py_DECREF(v);
1149 return res;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001150}
1151
1152static int
1153lp_ulonglong(char *p, PyObject *v, const formatdef *f)
1154{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001155 int res;
1156 v = get_pylong(v);
1157 if (v == NULL)
1158 return -1;
1159 res = _PyLong_AsByteArray((PyLongObject*)v,
1160 (unsigned char *)p,
1161 8,
1162 1, /* little_endian */
1163 0 /* signed */);
1164 Py_DECREF(v);
1165 return res;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001166}
1167
1168static int
Mark Dickinson7c4e4092016-09-03 17:21:29 +01001169lp_halffloat(char *p, PyObject *v, const formatdef *f)
1170{
1171 return pack_halffloat(p, v, 1);
1172}
1173
1174static int
Thomas Wouters477c8d52006-05-27 19:21:47 +00001175lp_float(char *p, PyObject *v, const formatdef *f)
1176{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001177 double x = PyFloat_AsDouble(v);
1178 if (x == -1 && PyErr_Occurred()) {
1179 PyErr_SetString(StructError,
1180 "required argument is not a float");
1181 return -1;
1182 }
1183 return _PyFloat_Pack4(x, (unsigned char *)p, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001184}
1185
1186static int
1187lp_double(char *p, PyObject *v, const formatdef *f)
1188{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001189 double x = PyFloat_AsDouble(v);
1190 if (x == -1 && PyErr_Occurred()) {
1191 PyErr_SetString(StructError,
1192 "required argument is not a float");
1193 return -1;
1194 }
1195 return _PyFloat_Pack8(x, (unsigned char *)p, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001196}
1197
1198static formatdef lilendian_table[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001199 {'x', 1, 0, NULL},
1200 {'b', 1, 0, nu_byte, np_byte},
1201 {'B', 1, 0, nu_ubyte, np_ubyte},
1202 {'c', 1, 0, nu_char, np_char},
1203 {'s', 1, 0, NULL},
1204 {'p', 1, 0, NULL},
1205 {'h', 2, 0, lu_int, lp_int},
1206 {'H', 2, 0, lu_uint, lp_uint},
1207 {'i', 4, 0, lu_int, lp_int},
1208 {'I', 4, 0, lu_uint, lp_uint},
1209 {'l', 4, 0, lu_int, lp_int},
1210 {'L', 4, 0, lu_uint, lp_uint},
1211 {'q', 8, 0, lu_longlong, lp_longlong},
1212 {'Q', 8, 0, lu_ulonglong, lp_ulonglong},
1213 {'?', 1, 0, bu_bool, bp_bool}, /* Std rep not endian dep,
1214 but potentially different from native rep -- reuse bx_bool funcs. */
Mark Dickinson7c4e4092016-09-03 17:21:29 +01001215 {'e', 2, 0, lu_halffloat, lp_halffloat},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001216 {'f', 4, 0, lu_float, lp_float},
1217 {'d', 8, 0, lu_double, lp_double},
1218 {0}
Thomas Wouters477c8d52006-05-27 19:21:47 +00001219};
1220
1221
1222static const formatdef *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001223whichtable(const char **pfmt)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001224{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 const char *fmt = (*pfmt)++; /* May be backed out of later */
1226 switch (*fmt) {
1227 case '<':
1228 return lilendian_table;
1229 case '>':
1230 case '!': /* Network byte order is big-endian */
1231 return bigendian_table;
Ezio Melotti42da6632011-03-15 05:18:48 +02001232 case '=': { /* Host byte order -- different from native in alignment! */
Christian Heimes743e0cd2012-10-17 23:52:17 +02001233#if PY_LITTLE_ENDIAN
1234 return lilendian_table;
1235#else
1236 return bigendian_table;
1237#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001238 }
1239 default:
1240 --*pfmt; /* Back out of pointer increment */
1241 /* Fall through */
1242 case '@':
1243 return native_table;
1244 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001245}
1246
1247
1248/* Get the table entry for a format code */
1249
1250static const formatdef *
1251getentry(int c, const formatdef *f)
1252{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001253 for (; f->format != '\0'; f++) {
1254 if (f->format == c) {
1255 return f;
1256 }
1257 }
1258 PyErr_SetString(StructError, "bad char in struct format");
1259 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001260}
1261
1262
Mark Dickinsonb72e6862010-06-11 19:50:30 +00001263/* Align a size according to a format code. Return -1 on overflow. */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001264
Mark Dickinsoneac0e682010-06-11 19:05:08 +00001265static Py_ssize_t
Thomas Wouters477c8d52006-05-27 19:21:47 +00001266align(Py_ssize_t size, char c, const formatdef *e)
1267{
Mark Dickinsonb72e6862010-06-11 19:50:30 +00001268 Py_ssize_t extra;
1269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001270 if (e->format == c) {
Mark Dickinsonb72e6862010-06-11 19:50:30 +00001271 if (e->alignment && size > 0) {
1272 extra = (e->alignment - 1) - (size - 1) % (e->alignment);
1273 if (extra > PY_SSIZE_T_MAX - size)
1274 return -1;
1275 size += extra;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001276 }
1277 }
1278 return size;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001279}
1280
Antoine Pitrou9f146812013-04-27 00:20:04 +02001281/*
1282 * Struct object implementation.
1283 */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001284
1285/* calculate the size of a format string */
1286
1287static int
1288prepare_s(PyStructObject *self)
1289{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001290 const formatdef *f;
1291 const formatdef *e;
1292 formatcode *codes;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001294 const char *s;
1295 const char *fmt;
1296 char c;
Victor Stinner706768c2014-08-16 01:03:39 +02001297 Py_ssize_t size, len, num, itemsize;
1298 size_t ncodes;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001300 fmt = PyBytes_AS_STRING(self->s_format);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001301
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001302 f = whichtable(&fmt);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001304 s = fmt;
1305 size = 0;
1306 len = 0;
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001307 ncodes = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001308 while ((c = *s++) != '\0') {
Antoine Pitrou4de74572013-02-09 23:11:27 +01001309 if (Py_ISSPACE(Py_CHARMASK(c)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001310 continue;
1311 if ('0' <= c && c <= '9') {
1312 num = c - '0';
1313 while ('0' <= (c = *s++) && c <= '9') {
Mark Dickinsonab4096f2010-06-11 16:56:34 +00001314 /* overflow-safe version of
1315 if (num*10 + (c - '0') > PY_SSIZE_T_MAX) { ... } */
1316 if (num >= PY_SSIZE_T_MAX / 10 && (
1317 num > PY_SSIZE_T_MAX / 10 ||
Mark Dickinsonb72e6862010-06-11 19:50:30 +00001318 (c - '0') > PY_SSIZE_T_MAX % 10))
1319 goto overflow;
Mark Dickinsonab4096f2010-06-11 16:56:34 +00001320 num = num*10 + (c - '0');
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001321 }
Alexander Belopolsky177e8532010-06-11 16:04:59 +00001322 if (c == '\0') {
1323 PyErr_SetString(StructError,
1324 "repeat count given without format specifier");
1325 return -1;
1326 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001327 }
1328 else
1329 num = 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001331 e = getentry(c, f);
1332 if (e == NULL)
1333 return -1;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001335 switch (c) {
1336 case 's': /* fall through */
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001337 case 'p': len++; ncodes++; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001338 case 'x': break;
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001339 default: len += num; if (num) ncodes++; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001340 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001342 itemsize = e->size;
1343 size = align(size, c, e);
Mark Dickinsonb72e6862010-06-11 19:50:30 +00001344 if (size == -1)
1345 goto overflow;
1346
1347 /* if (size + num * itemsize > PY_SSIZE_T_MAX) { ... } */
1348 if (num > (PY_SSIZE_T_MAX - size) / itemsize)
1349 goto overflow;
1350 size += num * itemsize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001351 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001353 /* check for overflow */
Victor Stinner706768c2014-08-16 01:03:39 +02001354 if ((ncodes + 1) > ((size_t)PY_SSIZE_T_MAX / sizeof(formatcode))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001355 PyErr_NoMemory();
1356 return -1;
1357 }
Amaury Forgeot d'Arc35c86582008-06-17 21:11:29 +00001358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001359 self->s_size = size;
1360 self->s_len = len;
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001361 codes = PyMem_MALLOC((ncodes + 1) * sizeof(formatcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001362 if (codes == NULL) {
1363 PyErr_NoMemory();
1364 return -1;
1365 }
Mark Dickinsoncf28b952010-07-29 21:41:59 +00001366 /* Free any s_codes value left over from a previous initialization. */
1367 if (self->s_codes != NULL)
1368 PyMem_FREE(self->s_codes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001369 self->s_codes = codes;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001371 s = fmt;
1372 size = 0;
1373 while ((c = *s++) != '\0') {
Antoine Pitrou4de74572013-02-09 23:11:27 +01001374 if (Py_ISSPACE(Py_CHARMASK(c)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001375 continue;
1376 if ('0' <= c && c <= '9') {
1377 num = c - '0';
1378 while ('0' <= (c = *s++) && c <= '9')
1379 num = num*10 + (c - '0');
1380 if (c == '\0')
1381 break;
1382 }
1383 else
1384 num = 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001386 e = getentry(c, f);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001388 size = align(size, c, e);
1389 if (c == 's' || c == 'p') {
1390 codes->offset = size;
1391 codes->size = num;
1392 codes->fmtdef = e;
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001393 codes->repeat = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001394 codes++;
1395 size += num;
1396 } else if (c == 'x') {
1397 size += num;
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001398 } else if (num) {
1399 codes->offset = size;
1400 codes->size = e->size;
1401 codes->fmtdef = e;
1402 codes->repeat = num;
1403 codes++;
1404 size += e->size * num;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001405 }
1406 }
1407 codes->fmtdef = NULL;
1408 codes->offset = size;
1409 codes->size = 0;
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001410 codes->repeat = 0;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001412 return 0;
Mark Dickinsonb72e6862010-06-11 19:50:30 +00001413
1414 overflow:
1415 PyErr_SetString(StructError,
1416 "total struct size too long");
1417 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001418}
1419
1420static PyObject *
1421s_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1422{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001423 PyObject *self;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001425 assert(type != NULL && type->tp_alloc != NULL);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001426
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001427 self = type->tp_alloc(type, 0);
1428 if (self != NULL) {
1429 PyStructObject *s = (PyStructObject*)self;
1430 Py_INCREF(Py_None);
1431 s->s_format = Py_None;
1432 s->s_codes = NULL;
1433 s->s_size = -1;
1434 s->s_len = -1;
1435 }
1436 return self;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001437}
1438
1439static int
1440s_init(PyObject *self, PyObject *args, PyObject *kwds)
1441{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001442 PyStructObject *soself = (PyStructObject *)self;
1443 PyObject *o_format = NULL;
1444 int ret = 0;
1445 static char *kwlist[] = {"format", 0};
Thomas Wouters477c8d52006-05-27 19:21:47 +00001446
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001447 assert(PyStruct_Check(self));
Thomas Wouters477c8d52006-05-27 19:21:47 +00001448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001449 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:Struct", kwlist,
1450 &o_format))
1451 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001453 if (PyUnicode_Check(o_format)) {
1454 o_format = PyUnicode_AsASCIIString(o_format);
1455 if (o_format == NULL)
1456 return -1;
1457 }
1458 /* XXX support buffer interface, too */
1459 else {
1460 Py_INCREF(o_format);
1461 }
Christian Heimesa34706f2008-01-04 03:06:10 +00001462
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001463 if (!PyBytes_Check(o_format)) {
1464 Py_DECREF(o_format);
1465 PyErr_Format(PyExc_TypeError,
Victor Stinnerda9ec992010-12-28 13:26:42 +00001466 "Struct() argument 1 must be a bytes object, not %.200s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001467 Py_TYPE(o_format)->tp_name);
1468 return -1;
1469 }
Christian Heimesa34706f2008-01-04 03:06:10 +00001470
Serhiy Storchaka48842712016-04-06 09:45:48 +03001471 Py_XSETREF(soself->s_format, o_format);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001473 ret = prepare_s(soself);
1474 return ret;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001475}
1476
1477static void
1478s_dealloc(PyStructObject *s)
1479{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001480 if (s->weakreflist != NULL)
1481 PyObject_ClearWeakRefs((PyObject *)s);
1482 if (s->s_codes != NULL) {
1483 PyMem_FREE(s->s_codes);
1484 }
1485 Py_XDECREF(s->s_format);
1486 Py_TYPE(s)->tp_free((PyObject *)s);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001487}
1488
1489static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001490s_unpack_internal(PyStructObject *soself, const char *startfrom) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001491 formatcode *code;
1492 Py_ssize_t i = 0;
1493 PyObject *result = PyTuple_New(soself->s_len);
1494 if (result == NULL)
1495 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001497 for (code = soself->s_codes; code->fmtdef != NULL; code++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001498 const formatdef *e = code->fmtdef;
1499 const char *res = startfrom + code->offset;
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001500 Py_ssize_t j = code->repeat;
1501 while (j--) {
1502 PyObject *v;
1503 if (e->format == 's') {
1504 v = PyBytes_FromStringAndSize(res, code->size);
1505 } else if (e->format == 'p') {
1506 Py_ssize_t n = *(unsigned char*)res;
1507 if (n >= code->size)
1508 n = code->size - 1;
1509 v = PyBytes_FromStringAndSize(res + 1, n);
1510 } else {
1511 v = e->unpack(res, e);
1512 }
1513 if (v == NULL)
1514 goto fail;
1515 PyTuple_SET_ITEM(result, i++, v);
1516 res += code->size;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001517 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001518 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001520 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001521fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001522 Py_DECREF(result);
1523 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001524}
1525
1526
1527PyDoc_STRVAR(s_unpack__doc__,
Guido van Rossum913dd0b2007-04-13 03:33:53 +00001528"S.unpack(buffer) -> (v1, v2, ...)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00001529\n\
Mark Dickinsonaacfa952010-06-12 15:43:45 +00001530Return a tuple containing values unpacked according to the format\n\
Martin Panterb0309912016-04-15 23:03:54 +00001531string S.format. The buffer's size in bytes must be S.size. See\n\
1532help(struct) for more on format strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001533
1534static PyObject *
Guido van Rossum98297ee2007-11-06 21:34:58 +00001535s_unpack(PyObject *self, PyObject *input)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001536{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001537 Py_buffer vbuf;
1538 PyObject *result;
1539 PyStructObject *soself = (PyStructObject *)self;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001541 assert(PyStruct_Check(self));
1542 assert(soself->s_codes != NULL);
1543 if (PyObject_GetBuffer(input, &vbuf, PyBUF_SIMPLE) < 0)
1544 return NULL;
1545 if (vbuf.len != soself->s_size) {
1546 PyErr_Format(StructError,
Victor Stinnerda9ec992010-12-28 13:26:42 +00001547 "unpack requires a bytes object of length %zd",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001548 soself->s_size);
1549 PyBuffer_Release(&vbuf);
1550 return NULL;
1551 }
1552 result = s_unpack_internal(soself, vbuf.buf);
1553 PyBuffer_Release(&vbuf);
1554 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001555}
1556
1557PyDoc_STRVAR(s_unpack_from__doc__,
Mark Dickinsonc6f13962010-06-13 09:17:13 +00001558"S.unpack_from(buffer, offset=0) -> (v1, v2, ...)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00001559\n\
Mark Dickinsonaacfa952010-06-12 15:43:45 +00001560Return a tuple containing values unpacked according to the format\n\
Martin Panterb0309912016-04-15 23:03:54 +00001561string S.format. The buffer's size in bytes, minus offset, must be at\n\
1562least S.size. See help(struct) for more on format strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001563
1564static PyObject *
1565s_unpack_from(PyObject *self, PyObject *args, PyObject *kwds)
1566{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001567 static char *kwlist[] = {"buffer", "offset", 0};
Guido van Rossum98297ee2007-11-06 21:34:58 +00001568
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001569 PyObject *input;
1570 Py_ssize_t offset = 0;
1571 Py_buffer vbuf;
1572 PyObject *result;
1573 PyStructObject *soself = (PyStructObject *)self;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001575 assert(PyStruct_Check(self));
1576 assert(soself->s_codes != NULL);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001578 if (!PyArg_ParseTupleAndKeywords(args, kwds,
1579 "O|n:unpack_from", kwlist,
1580 &input, &offset))
1581 return NULL;
1582 if (PyObject_GetBuffer(input, &vbuf, PyBUF_SIMPLE) < 0)
1583 return NULL;
1584 if (offset < 0)
1585 offset += vbuf.len;
1586 if (offset < 0 || vbuf.len - offset < soself->s_size) {
1587 PyErr_Format(StructError,
1588 "unpack_from requires a buffer of at least %zd bytes",
1589 soself->s_size);
1590 PyBuffer_Release(&vbuf);
1591 return NULL;
1592 }
1593 result = s_unpack_internal(soself, (char*)vbuf.buf + offset);
1594 PyBuffer_Release(&vbuf);
1595 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001596}
1597
1598
Antoine Pitrou9f146812013-04-27 00:20:04 +02001599/* Unpack iterator type */
1600
1601typedef struct {
1602 PyObject_HEAD
1603 PyStructObject *so;
1604 Py_buffer buf;
1605 Py_ssize_t index;
1606} unpackiterobject;
1607
1608static void
1609unpackiter_dealloc(unpackiterobject *self)
1610{
1611 Py_XDECREF(self->so);
1612 PyBuffer_Release(&self->buf);
1613 PyObject_GC_Del(self);
1614}
1615
1616static int
1617unpackiter_traverse(unpackiterobject *self, visitproc visit, void *arg)
1618{
1619 Py_VISIT(self->so);
1620 Py_VISIT(self->buf.obj);
1621 return 0;
1622}
1623
1624static PyObject *
1625unpackiter_len(unpackiterobject *self)
1626{
1627 Py_ssize_t len;
1628 if (self->so == NULL)
1629 len = 0;
1630 else
1631 len = (self->buf.len - self->index) / self->so->s_size;
1632 return PyLong_FromSsize_t(len);
1633}
1634
1635static PyMethodDef unpackiter_methods[] = {
1636 {"__length_hint__", (PyCFunction) unpackiter_len, METH_NOARGS, NULL},
1637 {NULL, NULL} /* sentinel */
1638};
1639
1640static PyObject *
1641unpackiter_iternext(unpackiterobject *self)
1642{
1643 PyObject *result;
1644 if (self->so == NULL)
1645 return NULL;
1646 if (self->index >= self->buf.len) {
1647 /* Iterator exhausted */
1648 Py_CLEAR(self->so);
1649 PyBuffer_Release(&self->buf);
1650 return NULL;
1651 }
1652 assert(self->index + self->so->s_size <= self->buf.len);
1653 result = s_unpack_internal(self->so,
1654 (char*) self->buf.buf + self->index);
1655 self->index += self->so->s_size;
1656 return result;
1657}
1658
doko@ubuntu.com46c5deb2013-11-23 16:07:55 +01001659static PyTypeObject unpackiter_type = {
Antoine Pitrou9f146812013-04-27 00:20:04 +02001660 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1661 "unpack_iterator", /* tp_name */
1662 sizeof(unpackiterobject), /* tp_basicsize */
1663 0, /* tp_itemsize */
1664 (destructor)unpackiter_dealloc, /* tp_dealloc */
1665 0, /* tp_print */
1666 0, /* tp_getattr */
1667 0, /* tp_setattr */
1668 0, /* tp_reserved */
1669 0, /* tp_repr */
1670 0, /* tp_as_number */
1671 0, /* tp_as_sequence */
1672 0, /* tp_as_mapping */
1673 0, /* tp_hash */
1674 0, /* tp_call */
1675 0, /* tp_str */
1676 PyObject_GenericGetAttr, /* tp_getattro */
1677 0, /* tp_setattro */
1678 0, /* tp_as_buffer */
1679 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
1680 0, /* tp_doc */
1681 (traverseproc)unpackiter_traverse, /* tp_traverse */
1682 0, /* tp_clear */
1683 0, /* tp_richcompare */
1684 0, /* tp_weaklistoffset */
1685 PyObject_SelfIter, /* tp_iter */
1686 (iternextfunc)unpackiter_iternext, /* tp_iternext */
1687 unpackiter_methods /* tp_methods */
1688};
1689
1690PyDoc_STRVAR(s_iter_unpack__doc__,
1691"S.iter_unpack(buffer) -> iterator(v1, v2, ...)\n\
1692\n\
1693Return an iterator yielding tuples unpacked from the given bytes\n\
1694source, like a repeated invocation of unpack_from(). Requires\n\
1695that the bytes length be a multiple of the struct size.");
1696
1697static PyObject *
1698s_iter_unpack(PyObject *_so, PyObject *input)
1699{
1700 PyStructObject *so = (PyStructObject *) _so;
1701 unpackiterobject *self;
1702
1703 assert(PyStruct_Check(_so));
1704 assert(so->s_codes != NULL);
1705
1706 if (so->s_size == 0) {
1707 PyErr_Format(StructError,
1708 "cannot iteratively unpack with a struct of length 0");
1709 return NULL;
1710 }
1711
1712 self = (unpackiterobject *) PyType_GenericAlloc(&unpackiter_type, 0);
1713 if (self == NULL)
1714 return NULL;
1715
1716 if (PyObject_GetBuffer(input, &self->buf, PyBUF_SIMPLE) < 0) {
1717 Py_DECREF(self);
1718 return NULL;
1719 }
1720 if (self->buf.len % so->s_size != 0) {
1721 PyErr_Format(StructError,
1722 "iterative unpacking requires a bytes length "
1723 "multiple of %zd",
1724 so->s_size);
1725 Py_DECREF(self);
1726 return NULL;
1727 }
1728 Py_INCREF(so);
1729 self->so = so;
1730 self->index = 0;
1731 return (PyObject *) self;
1732}
1733
1734
Thomas Wouters477c8d52006-05-27 19:21:47 +00001735/*
1736 * Guts of the pack function.
1737 *
1738 * Takes a struct object, a tuple of arguments, and offset in that tuple of
1739 * argument for where to start processing the arguments for packing, and a
1740 * character buffer for writing the packed string. The caller must insure
1741 * that the buffer may contain the required length for packing the arguments.
1742 * 0 is returned on success, 1 is returned if there is an error.
1743 *
1744 */
1745static int
1746s_pack_internal(PyStructObject *soself, PyObject *args, int offset, char* buf)
1747{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001748 formatcode *code;
1749 /* XXX(nnorwitz): why does i need to be a local? can we use
1750 the offset parameter or do we need the wider width? */
1751 Py_ssize_t i;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001752
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001753 memset(buf, '\0', soself->s_size);
1754 i = offset;
1755 for (code = soself->s_codes; code->fmtdef != NULL; code++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001756 const formatdef *e = code->fmtdef;
1757 char *res = buf + code->offset;
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001758 Py_ssize_t j = code->repeat;
1759 while (j--) {
1760 PyObject *v = PyTuple_GET_ITEM(args, i++);
1761 if (e->format == 's') {
1762 Py_ssize_t n;
1763 int isstring;
1764 void *p;
1765 isstring = PyBytes_Check(v);
1766 if (!isstring && !PyByteArray_Check(v)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001767 PyErr_SetString(StructError,
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001768 "argument for 's' must be a bytes object");
1769 return -1;
1770 }
1771 if (isstring) {
1772 n = PyBytes_GET_SIZE(v);
1773 p = PyBytes_AS_STRING(v);
1774 }
1775 else {
1776 n = PyByteArray_GET_SIZE(v);
1777 p = PyByteArray_AS_STRING(v);
1778 }
1779 if (n > code->size)
1780 n = code->size;
1781 if (n > 0)
1782 memcpy(res, p, n);
1783 } else if (e->format == 'p') {
1784 Py_ssize_t n;
1785 int isstring;
1786 void *p;
1787 isstring = PyBytes_Check(v);
1788 if (!isstring && !PyByteArray_Check(v)) {
1789 PyErr_SetString(StructError,
1790 "argument for 'p' must be a bytes object");
1791 return -1;
1792 }
1793 if (isstring) {
1794 n = PyBytes_GET_SIZE(v);
1795 p = PyBytes_AS_STRING(v);
1796 }
1797 else {
1798 n = PyByteArray_GET_SIZE(v);
1799 p = PyByteArray_AS_STRING(v);
1800 }
1801 if (n > (code->size - 1))
1802 n = code->size - 1;
1803 if (n > 0)
1804 memcpy(res + 1, p, n);
1805 if (n > 255)
1806 n = 255;
1807 *res = Py_SAFE_DOWNCAST(n, Py_ssize_t, unsigned char);
1808 } else {
1809 if (e->pack(res, v, e) < 0) {
1810 if (PyLong_Check(v) && PyErr_ExceptionMatches(PyExc_OverflowError))
1811 PyErr_SetString(StructError,
Serhiy Storchaka46e1ce22013-08-27 20:17:03 +03001812 "int too large to convert");
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001813 return -1;
1814 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001815 }
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001816 res += code->size;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001817 }
1818 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001819
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001820 /* Success */
1821 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001822}
1823
1824
1825PyDoc_STRVAR(s_pack__doc__,
Benjamin Peterson4ae19462008-07-31 15:03:40 +00001826"S.pack(v1, v2, ...) -> bytes\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00001827\n\
Mark Dickinsonaacfa952010-06-12 15:43:45 +00001828Return a bytes object containing values v1, v2, ... packed according\n\
1829to the format string S.format. See help(struct) for more on format\n\
1830strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001831
1832static PyObject *
1833s_pack(PyObject *self, PyObject *args)
1834{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001835 PyStructObject *soself;
1836 PyObject *result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001838 /* Validate arguments. */
1839 soself = (PyStructObject *)self;
1840 assert(PyStruct_Check(self));
1841 assert(soself->s_codes != NULL);
1842 if (PyTuple_GET_SIZE(args) != soself->s_len)
1843 {
1844 PyErr_Format(StructError,
Petri Lehtinen92c28ca2012-10-29 21:16:57 +02001845 "pack expected %zd items for packing (got %zd)", soself->s_len, PyTuple_GET_SIZE(args));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001846 return NULL;
1847 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001849 /* Allocate a new string */
1850 result = PyBytes_FromStringAndSize((char *)NULL, soself->s_size);
1851 if (result == NULL)
1852 return NULL;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001853
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001854 /* Call the guts */
1855 if ( s_pack_internal(soself, args, 0, PyBytes_AS_STRING(result)) != 0 ) {
1856 Py_DECREF(result);
1857 return NULL;
1858 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001859
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001860 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001861}
1862
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001863PyDoc_STRVAR(s_pack_into__doc__,
1864"S.pack_into(buffer, offset, v1, v2, ...)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00001865\n\
Mark Dickinsonaacfa952010-06-12 15:43:45 +00001866Pack the values v1, v2, ... according to the format string S.format\n\
1867and write the packed bytes into the writable buffer buf starting at\n\
Mark Dickinsonfdb99f12010-06-12 16:30:53 +00001868offset. Note that the offset is a required argument. See\n\
Mark Dickinsonaacfa952010-06-12 15:43:45 +00001869help(struct) for more on format strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001870
1871static PyObject *
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001872s_pack_into(PyObject *self, PyObject *args)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001873{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001874 PyStructObject *soself;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001875 Py_buffer buffer;
1876 Py_ssize_t offset;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001878 /* Validate arguments. +1 is for the first arg as buffer. */
1879 soself = (PyStructObject *)self;
1880 assert(PyStruct_Check(self));
1881 assert(soself->s_codes != NULL);
1882 if (PyTuple_GET_SIZE(args) != (soself->s_len + 2))
1883 {
Petri Lehtinen92c28ca2012-10-29 21:16:57 +02001884 if (PyTuple_GET_SIZE(args) == 0) {
1885 PyErr_Format(StructError,
1886 "pack_into expected buffer argument");
1887 }
1888 else if (PyTuple_GET_SIZE(args) == 1) {
1889 PyErr_Format(StructError,
1890 "pack_into expected offset argument");
1891 }
1892 else {
1893 PyErr_Format(StructError,
1894 "pack_into expected %zd items for packing (got %zd)",
1895 soself->s_len, (PyTuple_GET_SIZE(args) - 2));
1896 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001897 return NULL;
1898 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001899
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001900 /* Extract a writable memory buffer from the first argument */
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001901 if (!PyArg_Parse(PyTuple_GET_ITEM(args, 0), "w*", &buffer))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001902 return NULL;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001903 assert(buffer.len >= 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001904
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001905 /* Extract the offset from the first argument */
1906 offset = PyNumber_AsSsize_t(PyTuple_GET_ITEM(args, 1), PyExc_IndexError);
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001907 if (offset == -1 && PyErr_Occurred()) {
1908 PyBuffer_Release(&buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001909 return NULL;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001910 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001911
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001912 /* Support negative offsets. */
1913 if (offset < 0)
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001914 offset += buffer.len;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001916 /* Check boundaries */
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001917 if (offset < 0 || (buffer.len - offset) < soself->s_size) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001918 PyErr_Format(StructError,
1919 "pack_into requires a buffer of at least %zd bytes",
1920 soself->s_size);
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001921 PyBuffer_Release(&buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001922 return NULL;
1923 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001925 /* Call the guts */
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001926 if (s_pack_internal(soself, args, 2, (char*)buffer.buf + offset) != 0) {
1927 PyBuffer_Release(&buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001928 return NULL;
1929 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001930
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001931 PyBuffer_Release(&buffer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001932 Py_RETURN_NONE;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001933}
1934
1935static PyObject *
1936s_get_format(PyStructObject *self, void *unused)
1937{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001938 Py_INCREF(self->s_format);
1939 return self->s_format;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001940}
1941
1942static PyObject *
1943s_get_size(PyStructObject *self, void *unused)
1944{
Christian Heimes217cfd12007-12-02 14:31:20 +00001945 return PyLong_FromSsize_t(self->s_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001946}
1947
Meador Ingeb14d8c92012-07-23 10:01:29 -05001948PyDoc_STRVAR(s_sizeof__doc__,
1949"S.__sizeof__() -> size of S in memory, in bytes");
1950
1951static PyObject *
Meador Inge90bc2dbc2012-07-28 22:16:39 -05001952s_sizeof(PyStructObject *self, void *unused)
Meador Ingeb14d8c92012-07-23 10:01:29 -05001953{
1954 Py_ssize_t size;
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001955 formatcode *code;
Meador Ingeb14d8c92012-07-23 10:01:29 -05001956
Serhiy Storchaka5c4064e2015-12-19 20:05:25 +02001957 size = _PyObject_SIZE(Py_TYPE(self)) + sizeof(formatcode);
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001958 for (code = self->s_codes; code->fmtdef != NULL; code++)
1959 size += sizeof(formatcode);
Meador Ingeb14d8c92012-07-23 10:01:29 -05001960 return PyLong_FromSsize_t(size);
1961}
1962
Thomas Wouters477c8d52006-05-27 19:21:47 +00001963/* List of functions */
1964
1965static struct PyMethodDef s_methods[] = {
Antoine Pitrou9f146812013-04-27 00:20:04 +02001966 {"iter_unpack", s_iter_unpack, METH_O, s_iter_unpack__doc__},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001967 {"pack", s_pack, METH_VARARGS, s_pack__doc__},
1968 {"pack_into", s_pack_into, METH_VARARGS, s_pack_into__doc__},
1969 {"unpack", s_unpack, METH_O, s_unpack__doc__},
1970 {"unpack_from", (PyCFunction)s_unpack_from, METH_VARARGS|METH_KEYWORDS,
1971 s_unpack_from__doc__},
Meador Ingeb14d8c92012-07-23 10:01:29 -05001972 {"__sizeof__", (PyCFunction)s_sizeof, METH_NOARGS, s_sizeof__doc__},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001973 {NULL, NULL} /* sentinel */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001974};
1975
Victor Stinnerda9ec992010-12-28 13:26:42 +00001976PyDoc_STRVAR(s__doc__,
Alexander Belopolsky0bd003a2010-06-12 19:36:28 +00001977"Struct(fmt) --> compiled struct object\n"
1978"\n"
1979"Return a new Struct object which writes and reads binary data according to\n"
1980"the format string fmt. See help(struct) for more on format strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001981
1982#define OFF(x) offsetof(PyStructObject, x)
1983
1984static PyGetSetDef s_getsetlist[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001985 {"format", (getter)s_get_format, (setter)NULL, "struct format string", NULL},
1986 {"size", (getter)s_get_size, (setter)NULL, "struct size in bytes", NULL},
1987 {NULL} /* sentinel */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001988};
1989
1990static
1991PyTypeObject PyStructType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001992 PyVarObject_HEAD_INIT(NULL, 0)
1993 "Struct",
1994 sizeof(PyStructObject),
1995 0,
1996 (destructor)s_dealloc, /* tp_dealloc */
1997 0, /* tp_print */
1998 0, /* tp_getattr */
1999 0, /* tp_setattr */
2000 0, /* tp_reserved */
2001 0, /* tp_repr */
2002 0, /* tp_as_number */
2003 0, /* tp_as_sequence */
2004 0, /* tp_as_mapping */
2005 0, /* tp_hash */
2006 0, /* tp_call */
2007 0, /* tp_str */
2008 PyObject_GenericGetAttr, /* tp_getattro */
2009 PyObject_GenericSetAttr, /* tp_setattro */
2010 0, /* tp_as_buffer */
2011 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
2012 s__doc__, /* tp_doc */
2013 0, /* tp_traverse */
2014 0, /* tp_clear */
2015 0, /* tp_richcompare */
2016 offsetof(PyStructObject, weakreflist), /* tp_weaklistoffset */
2017 0, /* tp_iter */
2018 0, /* tp_iternext */
2019 s_methods, /* tp_methods */
2020 NULL, /* tp_members */
2021 s_getsetlist, /* tp_getset */
2022 0, /* tp_base */
2023 0, /* tp_dict */
2024 0, /* tp_descr_get */
2025 0, /* tp_descr_set */
2026 0, /* tp_dictoffset */
2027 s_init, /* tp_init */
2028 PyType_GenericAlloc,/* tp_alloc */
2029 s_new, /* tp_new */
2030 PyObject_Del, /* tp_free */
Thomas Wouters477c8d52006-05-27 19:21:47 +00002031};
2032
Christian Heimesa34706f2008-01-04 03:06:10 +00002033
2034/* ---- Standalone functions ---- */
2035
2036#define MAXCACHE 100
2037static PyObject *cache = NULL;
2038
2039static PyObject *
2040cache_struct(PyObject *fmt)
2041{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002042 PyObject * s_object;
Christian Heimesa34706f2008-01-04 03:06:10 +00002043
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002044 if (cache == NULL) {
2045 cache = PyDict_New();
2046 if (cache == NULL)
2047 return NULL;
2048 }
Christian Heimesa34706f2008-01-04 03:06:10 +00002049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002050 s_object = PyDict_GetItem(cache, fmt);
2051 if (s_object != NULL) {
2052 Py_INCREF(s_object);
2053 return s_object;
2054 }
Christian Heimesa34706f2008-01-04 03:06:10 +00002055
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002056 s_object = PyObject_CallFunctionObjArgs((PyObject *)(&PyStructType), fmt, NULL);
2057 if (s_object != NULL) {
2058 if (PyDict_Size(cache) >= MAXCACHE)
2059 PyDict_Clear(cache);
2060 /* Attempt to cache the result */
2061 if (PyDict_SetItem(cache, fmt, s_object) == -1)
2062 PyErr_Clear();
2063 }
2064 return s_object;
Christian Heimesa34706f2008-01-04 03:06:10 +00002065}
2066
2067PyDoc_STRVAR(clearcache_doc,
2068"Clear the internal cache.");
2069
2070static PyObject *
2071clearcache(PyObject *self)
2072{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002073 Py_CLEAR(cache);
2074 Py_RETURN_NONE;
Christian Heimesa34706f2008-01-04 03:06:10 +00002075}
2076
2077PyDoc_STRVAR(calcsize_doc,
Mark Dickinsonaacfa952010-06-12 15:43:45 +00002078"calcsize(fmt) -> integer\n\
2079\n\
2080Return size in bytes of the struct described by the format string fmt.");
Christian Heimesa34706f2008-01-04 03:06:10 +00002081
2082static PyObject *
2083calcsize(PyObject *self, PyObject *fmt)
2084{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002085 Py_ssize_t n;
2086 PyObject *s_object = cache_struct(fmt);
2087 if (s_object == NULL)
2088 return NULL;
2089 n = ((PyStructObject *)s_object)->s_size;
2090 Py_DECREF(s_object);
2091 return PyLong_FromSsize_t(n);
Christian Heimesa34706f2008-01-04 03:06:10 +00002092}
2093
2094PyDoc_STRVAR(pack_doc,
Mark Dickinsonaacfa952010-06-12 15:43:45 +00002095"pack(fmt, v1, v2, ...) -> bytes\n\
2096\n\
Mark Dickinsonfdb99f12010-06-12 16:30:53 +00002097Return a bytes object containing the values v1, v2, ... packed according\n\
2098to the format string fmt. See help(struct) for more on format strings.");
Christian Heimesa34706f2008-01-04 03:06:10 +00002099
2100static PyObject *
2101pack(PyObject *self, PyObject *args)
2102{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002103 PyObject *s_object, *fmt, *newargs, *result;
2104 Py_ssize_t n = PyTuple_GET_SIZE(args);
Christian Heimesa34706f2008-01-04 03:06:10 +00002105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002106 if (n == 0) {
2107 PyErr_SetString(PyExc_TypeError, "missing format argument");
2108 return NULL;
2109 }
2110 fmt = PyTuple_GET_ITEM(args, 0);
2111 newargs = PyTuple_GetSlice(args, 1, n);
2112 if (newargs == NULL)
2113 return NULL;
Christian Heimesa34706f2008-01-04 03:06:10 +00002114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002115 s_object = cache_struct(fmt);
2116 if (s_object == NULL) {
2117 Py_DECREF(newargs);
2118 return NULL;
2119 }
2120 result = s_pack(s_object, newargs);
2121 Py_DECREF(newargs);
2122 Py_DECREF(s_object);
2123 return result;
Christian Heimesa34706f2008-01-04 03:06:10 +00002124}
2125
2126PyDoc_STRVAR(pack_into_doc,
Mark Dickinsonaacfa952010-06-12 15:43:45 +00002127"pack_into(fmt, buffer, offset, v1, v2, ...)\n\
2128\n\
2129Pack the values v1, v2, ... according to the format string fmt and write\n\
2130the packed bytes into the writable buffer buf starting at offset. Note\n\
Mark Dickinsonfdb99f12010-06-12 16:30:53 +00002131that the offset is a required argument. See help(struct) for more\n\
Mark Dickinsonaacfa952010-06-12 15:43:45 +00002132on format strings.");
Christian Heimesa34706f2008-01-04 03:06:10 +00002133
2134static PyObject *
2135pack_into(PyObject *self, PyObject *args)
2136{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002137 PyObject *s_object, *fmt, *newargs, *result;
2138 Py_ssize_t n = PyTuple_GET_SIZE(args);
Christian Heimesa34706f2008-01-04 03:06:10 +00002139
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002140 if (n == 0) {
2141 PyErr_SetString(PyExc_TypeError, "missing format argument");
2142 return NULL;
2143 }
2144 fmt = PyTuple_GET_ITEM(args, 0);
2145 newargs = PyTuple_GetSlice(args, 1, n);
2146 if (newargs == NULL)
2147 return NULL;
Christian Heimesa34706f2008-01-04 03:06:10 +00002148
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002149 s_object = cache_struct(fmt);
2150 if (s_object == NULL) {
2151 Py_DECREF(newargs);
2152 return NULL;
2153 }
2154 result = s_pack_into(s_object, newargs);
2155 Py_DECREF(newargs);
2156 Py_DECREF(s_object);
2157 return result;
Christian Heimesa34706f2008-01-04 03:06:10 +00002158}
2159
2160PyDoc_STRVAR(unpack_doc,
Mark Dickinsonaacfa952010-06-12 15:43:45 +00002161"unpack(fmt, buffer) -> (v1, v2, ...)\n\
2162\n\
2163Return a tuple containing values unpacked according to the format string\n\
Martin Panterb0309912016-04-15 23:03:54 +00002164fmt. The buffer's size in bytes must be calcsize(fmt). See help(struct)\n\
2165for more on format strings.");
Christian Heimesa34706f2008-01-04 03:06:10 +00002166
2167static PyObject *
2168unpack(PyObject *self, PyObject *args)
2169{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002170 PyObject *s_object, *fmt, *inputstr, *result;
Christian Heimesa34706f2008-01-04 03:06:10 +00002171
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002172 if (!PyArg_UnpackTuple(args, "unpack", 2, 2, &fmt, &inputstr))
2173 return NULL;
Christian Heimesa34706f2008-01-04 03:06:10 +00002174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002175 s_object = cache_struct(fmt);
2176 if (s_object == NULL)
2177 return NULL;
2178 result = s_unpack(s_object, inputstr);
2179 Py_DECREF(s_object);
2180 return result;
Christian Heimesa34706f2008-01-04 03:06:10 +00002181}
2182
2183PyDoc_STRVAR(unpack_from_doc,
Mark Dickinsonc6f13962010-06-13 09:17:13 +00002184"unpack_from(fmt, buffer, offset=0) -> (v1, v2, ...)\n\
Mark Dickinsonaacfa952010-06-12 15:43:45 +00002185\n\
2186Return a tuple containing values unpacked according to the format string\n\
Martin Panterb0309912016-04-15 23:03:54 +00002187fmt. The buffer's size, minus offset, must be at least calcsize(fmt).\n\
2188See help(struct) for more on format strings.");
Christian Heimesa34706f2008-01-04 03:06:10 +00002189
2190static PyObject *
2191unpack_from(PyObject *self, PyObject *args, PyObject *kwds)
2192{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002193 PyObject *s_object, *fmt, *newargs, *result;
2194 Py_ssize_t n = PyTuple_GET_SIZE(args);
Christian Heimesa34706f2008-01-04 03:06:10 +00002195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002196 if (n == 0) {
2197 PyErr_SetString(PyExc_TypeError, "missing format argument");
2198 return NULL;
2199 }
2200 fmt = PyTuple_GET_ITEM(args, 0);
2201 newargs = PyTuple_GetSlice(args, 1, n);
2202 if (newargs == NULL)
2203 return NULL;
Christian Heimesa34706f2008-01-04 03:06:10 +00002204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002205 s_object = cache_struct(fmt);
2206 if (s_object == NULL) {
2207 Py_DECREF(newargs);
2208 return NULL;
2209 }
2210 result = s_unpack_from(s_object, newargs, kwds);
2211 Py_DECREF(newargs);
2212 Py_DECREF(s_object);
2213 return result;
Christian Heimesa34706f2008-01-04 03:06:10 +00002214}
2215
Antoine Pitrou9f146812013-04-27 00:20:04 +02002216PyDoc_STRVAR(iter_unpack_doc,
2217"iter_unpack(fmt, buffer) -> iterator(v1, v2, ...)\n\
2218\n\
2219Return an iterator yielding tuples unpacked from the given bytes\n\
2220source according to the format string, like a repeated invocation of\n\
2221unpack_from(). Requires that the bytes length be a multiple of the\n\
2222format struct size.");
2223
2224static PyObject *
2225iter_unpack(PyObject *self, PyObject *args)
2226{
2227 PyObject *s_object, *fmt, *input, *result;
2228
2229 if (!PyArg_ParseTuple(args, "OO:iter_unpack", &fmt, &input))
2230 return NULL;
2231
2232 s_object = cache_struct(fmt);
2233 if (s_object == NULL)
2234 return NULL;
2235 result = s_iter_unpack(s_object, input);
2236 Py_DECREF(s_object);
2237 return result;
2238}
2239
Christian Heimesa34706f2008-01-04 03:06:10 +00002240static struct PyMethodDef module_functions[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002241 {"_clearcache", (PyCFunction)clearcache, METH_NOARGS, clearcache_doc},
2242 {"calcsize", calcsize, METH_O, calcsize_doc},
Antoine Pitrou9f146812013-04-27 00:20:04 +02002243 {"iter_unpack", iter_unpack, METH_VARARGS, iter_unpack_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002244 {"pack", pack, METH_VARARGS, pack_doc},
2245 {"pack_into", pack_into, METH_VARARGS, pack_into_doc},
2246 {"unpack", unpack, METH_VARARGS, unpack_doc},
2247 {"unpack_from", (PyCFunction)unpack_from,
2248 METH_VARARGS|METH_KEYWORDS, unpack_from_doc},
2249 {NULL, NULL} /* sentinel */
Christian Heimesa34706f2008-01-04 03:06:10 +00002250};
2251
2252
Thomas Wouters477c8d52006-05-27 19:21:47 +00002253/* Module initialization */
2254
Christian Heimesa34706f2008-01-04 03:06:10 +00002255PyDoc_STRVAR(module_doc,
2256"Functions to convert between Python values and C structs.\n\
Benjamin Peterson4ae19462008-07-31 15:03:40 +00002257Python bytes objects are used to hold the data representing the C struct\n\
Mark Dickinson40714af2009-10-08 15:59:20 +00002258and also as format strings (explained below) to describe the layout of data\n\
2259in the C struct.\n\
Christian Heimesa34706f2008-01-04 03:06:10 +00002260\n\
2261The optional first format char indicates byte order, size and alignment:\n\
Mark Dickinson40714af2009-10-08 15:59:20 +00002262 @: native order, size & alignment (default)\n\
2263 =: native order, std. size & alignment\n\
2264 <: little-endian, std. size & alignment\n\
2265 >: big-endian, std. size & alignment\n\
2266 !: same as >\n\
Christian Heimesa34706f2008-01-04 03:06:10 +00002267\n\
2268The remaining chars indicate types of args and must match exactly;\n\
2269these can be preceded by a decimal repeat count:\n\
2270 x: pad byte (no data); c:char; b:signed byte; B:unsigned byte;\n\
Mark Dickinson40714af2009-10-08 15:59:20 +00002271 ?: _Bool (requires C99; if not available, char is used instead)\n\
Christian Heimesa34706f2008-01-04 03:06:10 +00002272 h:short; H:unsigned short; i:int; I:unsigned int;\n\
Mark Dickinson7c4e4092016-09-03 17:21:29 +01002273 l:long; L:unsigned long; f:float; d:double; e:half-float.\n\
Christian Heimesa34706f2008-01-04 03:06:10 +00002274Special cases (preceding decimal count indicates length):\n\
2275 s:string (array of char); p: pascal string (with count byte).\n\
Antoine Pitrou45d9c912011-10-06 15:27:40 +02002276Special cases (only available in native format):\n\
2277 n:ssize_t; N:size_t;\n\
Christian Heimesa34706f2008-01-04 03:06:10 +00002278 P:an integer type that is wide enough to hold a pointer.\n\
2279Special case (not in native mode unless 'long long' in platform C):\n\
2280 q:long long; Q:unsigned long long\n\
2281Whitespace between formats is ignored.\n\
2282\n\
2283The variable struct.error is an exception raised on errors.\n");
2284
Martin v. Löwis1a214512008-06-11 05:26:20 +00002285
2286static struct PyModuleDef _structmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002287 PyModuleDef_HEAD_INIT,
2288 "_struct",
2289 module_doc,
2290 -1,
2291 module_functions,
2292 NULL,
2293 NULL,
2294 NULL,
2295 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002296};
2297
Thomas Wouters477c8d52006-05-27 19:21:47 +00002298PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002299PyInit__struct(void)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002300{
Mark Dickinson06817852010-06-12 09:25:13 +00002301 PyObject *m;
Christian Heimesa34706f2008-01-04 03:06:10 +00002302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002303 m = PyModule_Create(&_structmodule);
2304 if (m == NULL)
2305 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002307 Py_TYPE(&PyStructType) = &PyType_Type;
2308 if (PyType_Ready(&PyStructType) < 0)
2309 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002311 /* Check endian and swap in faster functions */
2312 {
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02002313 const formatdef *native = native_table;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002314 formatdef *other, *ptr;
Christian Heimes743e0cd2012-10-17 23:52:17 +02002315#if PY_LITTLE_ENDIAN
2316 other = lilendian_table;
2317#else
2318 other = bigendian_table;
2319#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002320 /* Scan through the native table, find a matching
2321 entry in the endian table and swap in the
2322 native implementations whenever possible
2323 (64-bit platforms may not have "standard" sizes) */
2324 while (native->format != '\0' && other->format != '\0') {
2325 ptr = other;
2326 while (ptr->format != '\0') {
2327 if (ptr->format == native->format) {
2328 /* Match faster when formats are
2329 listed in the same order */
2330 if (ptr == other)
2331 other++;
2332 /* Only use the trick if the
2333 size matches */
2334 if (ptr->size != native->size)
2335 break;
2336 /* Skip float and double, could be
2337 "unknown" float format */
2338 if (ptr->format == 'd' || ptr->format == 'f')
2339 break;
2340 ptr->pack = native->pack;
2341 ptr->unpack = native->unpack;
2342 break;
2343 }
2344 ptr++;
2345 }
2346 native++;
2347 }
2348 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002350 /* Add some symbolic constants to the module */
2351 if (StructError == NULL) {
2352 StructError = PyErr_NewException("struct.error", NULL, NULL);
2353 if (StructError == NULL)
2354 return NULL;
2355 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002357 Py_INCREF(StructError);
2358 PyModule_AddObject(m, "error", StructError);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002360 Py_INCREF((PyObject*)&PyStructType);
2361 PyModule_AddObject(m, "Struct", (PyObject*)&PyStructType);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002363 return m;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002364}