blob: 1de94e406e18c50e4b02928e79b98c47ca9a8077 [file] [log] [blame]
Benjamin Peterson4ae19462008-07-31 15:03:40 +00001/* struct module -- pack values into and (out of) bytes objects */
Thomas Wouters477c8d52006-05-27 19:21:47 +00002
3/* New version supporting byte order, alignment and size options,
4 character strings, and unsigned numbers */
5
6#define PY_SSIZE_T_CLEAN
7
8#include "Python.h"
Thomas Wouters477c8d52006-05-27 19:21:47 +00009#include "structmember.h"
10#include <ctype.h>
11
12static PyTypeObject PyStructType;
13
Thomas Wouters477c8d52006-05-27 19:21:47 +000014/* The translation function for each format character is table driven */
15typedef struct _formatdef {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000016 char format;
17 Py_ssize_t size;
18 Py_ssize_t alignment;
19 PyObject* (*unpack)(const char *,
20 const struct _formatdef *);
21 int (*pack)(char *, PyObject *,
22 const struct _formatdef *);
Thomas Wouters477c8d52006-05-27 19:21:47 +000023} formatdef;
24
25typedef struct _formatcode {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000026 const struct _formatdef *fmtdef;
27 Py_ssize_t offset;
28 Py_ssize_t size;
Serhiy Storchakafff61f22013-05-17 10:49:44 +030029 Py_ssize_t repeat;
Thomas Wouters477c8d52006-05-27 19:21:47 +000030} formatcode;
31
32/* Struct object interface */
33
34typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000035 PyObject_HEAD
36 Py_ssize_t s_size;
37 Py_ssize_t s_len;
38 formatcode *s_codes;
39 PyObject *s_format;
40 PyObject *weakreflist; /* List of weak references */
Thomas Wouters477c8d52006-05-27 19:21:47 +000041} PyStructObject;
42
43
44#define PyStruct_Check(op) PyObject_TypeCheck(op, &PyStructType)
Christian Heimes90aa7642007-12-19 02:45:37 +000045#define PyStruct_CheckExact(op) (Py_TYPE(op) == &PyStructType)
Thomas Wouters477c8d52006-05-27 19:21:47 +000046
47
48/* Exception */
49
50static PyObject *StructError;
51
52
53/* Define various structs to figure out the alignments of types */
54
55
56typedef struct { char c; short x; } st_short;
57typedef struct { char c; int x; } st_int;
58typedef struct { char c; long x; } st_long;
59typedef struct { char c; float x; } st_float;
60typedef struct { char c; double x; } st_double;
61typedef struct { char c; void *x; } st_void_p;
Antoine Pitrou45d9c912011-10-06 15:27:40 +020062typedef struct { char c; size_t x; } st_size_t;
Thomas Wouters477c8d52006-05-27 19:21:47 +000063
64#define SHORT_ALIGN (sizeof(st_short) - sizeof(short))
65#define INT_ALIGN (sizeof(st_int) - sizeof(int))
66#define LONG_ALIGN (sizeof(st_long) - sizeof(long))
67#define FLOAT_ALIGN (sizeof(st_float) - sizeof(float))
68#define DOUBLE_ALIGN (sizeof(st_double) - sizeof(double))
69#define VOID_P_ALIGN (sizeof(st_void_p) - sizeof(void *))
Antoine Pitrou45d9c912011-10-06 15:27:40 +020070#define SIZE_T_ALIGN (sizeof(st_size_t) - sizeof(size_t))
Thomas Wouters477c8d52006-05-27 19:21:47 +000071
72/* We can't support q and Q in native mode unless the compiler does;
73 in std mode, they're 8 bytes on all platforms. */
74#ifdef HAVE_LONG_LONG
75typedef struct { char c; PY_LONG_LONG x; } s_long_long;
76#define LONG_LONG_ALIGN (sizeof(s_long_long) - sizeof(PY_LONG_LONG))
77#endif
78
Thomas Woutersb2137042007-02-01 18:02:27 +000079#ifdef HAVE_C99_BOOL
80#define BOOL_TYPE _Bool
81typedef struct { char c; _Bool x; } s_bool;
82#define BOOL_ALIGN (sizeof(s_bool) - sizeof(BOOL_TYPE))
83#else
84#define BOOL_TYPE char
85#define BOOL_ALIGN 0
86#endif
87
Thomas Wouters477c8d52006-05-27 19:21:47 +000088#define STRINGIFY(x) #x
89
90#ifdef __powerc
91#pragma options align=reset
92#endif
93
Mark Dickinson055a3fb2010-04-03 15:26:31 +000094/* Helper for integer format codes: converts an arbitrary Python object to a
95 PyLongObject if possible, otherwise fails. Caller should decref. */
Thomas Wouters477c8d52006-05-27 19:21:47 +000096
97static PyObject *
98get_pylong(PyObject *v)
99{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000100 assert(v != NULL);
101 if (!PyLong_Check(v)) {
102 /* Not an integer; try to use __index__ to convert. */
103 if (PyIndex_Check(v)) {
104 v = PyNumber_Index(v);
105 if (v == NULL)
106 return NULL;
107 }
108 else {
109 PyErr_SetString(StructError,
110 "required argument is not an integer");
111 return NULL;
112 }
113 }
114 else
115 Py_INCREF(v);
Mark Dickinsonea835e72009-04-19 20:40:33 +0000116
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000117 assert(PyLong_Check(v));
118 return v;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000119}
120
Mark Dickinsonea835e72009-04-19 20:40:33 +0000121/* Helper routine to get a C long and raise the appropriate error if it isn't
122 one */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000123
124static int
125get_long(PyObject *v, long *p)
126{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000127 long x;
Mark Dickinsonea835e72009-04-19 20:40:33 +0000128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000129 v = get_pylong(v);
130 if (v == NULL)
131 return -1;
132 assert(PyLong_Check(v));
133 x = PyLong_AsLong(v);
134 Py_DECREF(v);
135 if (x == (long)-1 && PyErr_Occurred()) {
136 if (PyErr_ExceptionMatches(PyExc_OverflowError))
137 PyErr_SetString(StructError,
138 "argument out of range");
139 return -1;
140 }
141 *p = x;
142 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000143}
144
145
146/* Same, but handling unsigned long */
147
148static int
149get_ulong(PyObject *v, unsigned long *p)
150{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000151 unsigned long x;
Mark Dickinsonea835e72009-04-19 20:40:33 +0000152
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000153 v = get_pylong(v);
154 if (v == NULL)
155 return -1;
156 assert(PyLong_Check(v));
157 x = PyLong_AsUnsignedLong(v);
158 Py_DECREF(v);
159 if (x == (unsigned long)-1 && PyErr_Occurred()) {
160 if (PyErr_ExceptionMatches(PyExc_OverflowError))
161 PyErr_SetString(StructError,
162 "argument out of range");
163 return -1;
164 }
165 *p = x;
166 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000167}
168
169#ifdef HAVE_LONG_LONG
170
171/* Same, but handling native long long. */
172
173static int
174get_longlong(PyObject *v, PY_LONG_LONG *p)
175{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000176 PY_LONG_LONG x;
Mark Dickinson055a3fb2010-04-03 15:26:31 +0000177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000178 v = get_pylong(v);
179 if (v == NULL)
180 return -1;
181 assert(PyLong_Check(v));
182 x = PyLong_AsLongLong(v);
183 Py_DECREF(v);
184 if (x == (PY_LONG_LONG)-1 && PyErr_Occurred()) {
185 if (PyErr_ExceptionMatches(PyExc_OverflowError))
186 PyErr_SetString(StructError,
187 "argument out of range");
188 return -1;
189 }
190 *p = x;
191 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000192}
193
194/* Same, but handling native unsigned long long. */
195
196static int
197get_ulonglong(PyObject *v, unsigned PY_LONG_LONG *p)
198{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000199 unsigned PY_LONG_LONG x;
Mark Dickinson055a3fb2010-04-03 15:26:31 +0000200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000201 v = get_pylong(v);
202 if (v == NULL)
203 return -1;
204 assert(PyLong_Check(v));
205 x = PyLong_AsUnsignedLongLong(v);
206 Py_DECREF(v);
207 if (x == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred()) {
208 if (PyErr_ExceptionMatches(PyExc_OverflowError))
209 PyErr_SetString(StructError,
210 "argument out of range");
211 return -1;
212 }
213 *p = x;
214 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000215}
216
217#endif
218
Antoine Pitrou45d9c912011-10-06 15:27:40 +0200219/* Same, but handling Py_ssize_t */
220
221static int
222get_ssize_t(PyObject *v, Py_ssize_t *p)
223{
224 Py_ssize_t x;
225
226 v = get_pylong(v);
227 if (v == NULL)
228 return -1;
229 assert(PyLong_Check(v));
230 x = PyLong_AsSsize_t(v);
231 Py_DECREF(v);
232 if (x == (Py_ssize_t)-1 && PyErr_Occurred()) {
233 if (PyErr_ExceptionMatches(PyExc_OverflowError))
234 PyErr_SetString(StructError,
235 "argument out of range");
236 return -1;
237 }
238 *p = x;
239 return 0;
240}
241
242/* Same, but handling size_t */
243
244static int
245get_size_t(PyObject *v, size_t *p)
246{
247 size_t x;
248
249 v = get_pylong(v);
250 if (v == NULL)
251 return -1;
252 assert(PyLong_Check(v));
253 x = PyLong_AsSize_t(v);
254 Py_DECREF(v);
255 if (x == (size_t)-1 && PyErr_Occurred()) {
256 if (PyErr_ExceptionMatches(PyExc_OverflowError))
257 PyErr_SetString(StructError,
258 "argument out of range");
259 return -1;
260 }
261 *p = x;
262 return 0;
263}
264
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000265
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000266#define RANGE_ERROR(x, f, flag, mask) return _range_error(f, flag)
267
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000268
Thomas Wouters477c8d52006-05-27 19:21:47 +0000269/* Floating point helpers */
270
271static PyObject *
272unpack_float(const char *p, /* start of 4-byte string */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000273 int le) /* true for little-endian, false for big-endian */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000274{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000275 double x;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000277 x = _PyFloat_Unpack4((unsigned char *)p, le);
278 if (x == -1.0 && PyErr_Occurred())
279 return NULL;
280 return PyFloat_FromDouble(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000281}
282
283static PyObject *
284unpack_double(const char *p, /* start of 8-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_Unpack8((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
295/* Helper to format the range error exceptions */
296static int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000297_range_error(const formatdef *f, int is_unsigned)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000298{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000299 /* ulargest is the largest unsigned value with f->size bytes.
300 * Note that the simpler:
301 * ((size_t)1 << (f->size * 8)) - 1
302 * doesn't work when f->size == sizeof(size_t) because C doesn't
303 * define what happens when a left shift count is >= the number of
304 * bits in the integer being shifted; e.g., on some boxes it doesn't
305 * shift at all when they're equal.
306 */
307 const size_t ulargest = (size_t)-1 >> ((SIZEOF_SIZE_T - f->size)*8);
308 assert(f->size >= 1 && f->size <= SIZEOF_SIZE_T);
309 if (is_unsigned)
310 PyErr_Format(StructError,
311 "'%c' format requires 0 <= number <= %zu",
312 f->format,
313 ulargest);
314 else {
315 const Py_ssize_t largest = (Py_ssize_t)(ulargest >> 1);
316 PyErr_Format(StructError,
317 "'%c' format requires %zd <= number <= %zd",
318 f->format,
319 ~ largest,
320 largest);
321 }
Mark Dickinsonae681df2009-03-21 10:26:31 +0000322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000323 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000324}
325
326
327
328/* A large number of small routines follow, with names of the form
329
330 [bln][up]_TYPE
331
332 [bln] distiguishes among big-endian, little-endian and native.
333 [pu] distiguishes between pack (to struct) and unpack (from struct).
334 TYPE is one of char, byte, ubyte, etc.
335*/
336
337/* Native mode routines. ****************************************************/
338/* NOTE:
339 In all n[up]_<type> routines handling types larger than 1 byte, there is
340 *no* guarantee that the p pointer is properly aligned for each type,
341 therefore memcpy is called. An intermediate variable is used to
342 compensate for big-endian architectures.
343 Normally both the intermediate variable and the memcpy call will be
344 skipped by C optimisation in little-endian architectures (gcc >= 2.91
345 does this). */
346
347static PyObject *
348nu_char(const char *p, const formatdef *f)
349{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000350 return PyBytes_FromStringAndSize(p, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000351}
352
353static PyObject *
354nu_byte(const char *p, const formatdef *f)
355{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000356 return PyLong_FromLong((long) *(signed char *)p);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000357}
358
359static PyObject *
360nu_ubyte(const char *p, const formatdef *f)
361{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000362 return PyLong_FromLong((long) *(unsigned char *)p);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000363}
364
365static PyObject *
366nu_short(const char *p, const formatdef *f)
367{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000368 short x;
369 memcpy((char *)&x, p, sizeof x);
370 return PyLong_FromLong((long)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000371}
372
373static PyObject *
374nu_ushort(const char *p, const formatdef *f)
375{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000376 unsigned short x;
377 memcpy((char *)&x, p, sizeof x);
378 return PyLong_FromLong((long)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000379}
380
381static PyObject *
382nu_int(const char *p, const formatdef *f)
383{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000384 int x;
385 memcpy((char *)&x, p, sizeof x);
386 return PyLong_FromLong((long)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000387}
388
389static PyObject *
390nu_uint(const char *p, const formatdef *f)
391{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000392 unsigned int x;
393 memcpy((char *)&x, p, sizeof x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000394#if (SIZEOF_LONG > SIZEOF_INT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000395 return PyLong_FromLong((long)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000396#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000397 if (x <= ((unsigned int)LONG_MAX))
398 return PyLong_FromLong((long)x);
399 return PyLong_FromUnsignedLong((unsigned long)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000400#endif
401}
402
403static PyObject *
404nu_long(const char *p, const formatdef *f)
405{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000406 long x;
407 memcpy((char *)&x, p, sizeof x);
408 return PyLong_FromLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000409}
410
411static PyObject *
412nu_ulong(const char *p, const formatdef *f)
413{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000414 unsigned long x;
415 memcpy((char *)&x, p, sizeof x);
416 if (x <= LONG_MAX)
417 return PyLong_FromLong((long)x);
418 return PyLong_FromUnsignedLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000419}
420
Antoine Pitrou45d9c912011-10-06 15:27:40 +0200421static PyObject *
422nu_ssize_t(const char *p, const formatdef *f)
423{
424 Py_ssize_t x;
425 memcpy((char *)&x, p, sizeof x);
426 return PyLong_FromSsize_t(x);
427}
428
429static PyObject *
430nu_size_t(const char *p, const formatdef *f)
431{
432 size_t x;
433 memcpy((char *)&x, p, sizeof x);
434 return PyLong_FromSize_t(x);
435}
436
437
Thomas Wouters477c8d52006-05-27 19:21:47 +0000438/* Native mode doesn't support q or Q unless the platform C supports
439 long long (or, on Windows, __int64). */
440
441#ifdef HAVE_LONG_LONG
442
443static PyObject *
444nu_longlong(const char *p, const formatdef *f)
445{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000446 PY_LONG_LONG x;
447 memcpy((char *)&x, p, sizeof x);
448 if (x >= LONG_MIN && x <= LONG_MAX)
449 return PyLong_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long));
450 return PyLong_FromLongLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000451}
452
453static PyObject *
454nu_ulonglong(const char *p, const formatdef *f)
455{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456 unsigned PY_LONG_LONG x;
457 memcpy((char *)&x, p, sizeof x);
458 if (x <= LONG_MAX)
459 return PyLong_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long));
460 return PyLong_FromUnsignedLongLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000461}
462
463#endif
464
465static PyObject *
Thomas Woutersb2137042007-02-01 18:02:27 +0000466nu_bool(const char *p, const formatdef *f)
467{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000468 BOOL_TYPE x;
469 memcpy((char *)&x, p, sizeof x);
470 return PyBool_FromLong(x != 0);
Thomas Woutersb2137042007-02-01 18:02:27 +0000471}
472
473
474static PyObject *
Thomas Wouters477c8d52006-05-27 19:21:47 +0000475nu_float(const char *p, const formatdef *f)
476{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 float x;
478 memcpy((char *)&x, p, sizeof x);
479 return PyFloat_FromDouble((double)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000480}
481
482static PyObject *
483nu_double(const char *p, const formatdef *f)
484{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485 double x;
486 memcpy((char *)&x, p, sizeof x);
487 return PyFloat_FromDouble(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000488}
489
490static PyObject *
491nu_void_p(const char *p, const formatdef *f)
492{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 void *x;
494 memcpy((char *)&x, p, sizeof x);
495 return PyLong_FromVoidPtr(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000496}
497
498static int
499np_byte(char *p, PyObject *v, const formatdef *f)
500{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 long x;
502 if (get_long(v, &x) < 0)
503 return -1;
504 if (x < -128 || x > 127){
505 PyErr_SetString(StructError,
506 "byte format requires -128 <= number <= 127");
507 return -1;
508 }
509 *p = (char)x;
510 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000511}
512
513static int
514np_ubyte(char *p, PyObject *v, const formatdef *f)
515{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 long x;
517 if (get_long(v, &x) < 0)
518 return -1;
519 if (x < 0 || x > 255){
520 PyErr_SetString(StructError,
521 "ubyte format requires 0 <= number <= 255");
522 return -1;
523 }
524 *p = (char)x;
525 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000526}
527
528static int
529np_char(char *p, PyObject *v, const formatdef *f)
530{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000531 if (!PyBytes_Check(v) || PyBytes_Size(v) != 1) {
532 PyErr_SetString(StructError,
Victor Stinnerda9ec992010-12-28 13:26:42 +0000533 "char format requires a bytes object of length 1");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 return -1;
535 }
536 *p = *PyBytes_AsString(v);
537 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000538}
539
540static int
541np_short(char *p, PyObject *v, const formatdef *f)
542{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000543 long x;
544 short y;
545 if (get_long(v, &x) < 0)
546 return -1;
547 if (x < SHRT_MIN || x > SHRT_MAX){
548 PyErr_SetString(StructError,
549 "short format requires " STRINGIFY(SHRT_MIN)
550 " <= number <= " STRINGIFY(SHRT_MAX));
551 return -1;
552 }
553 y = (short)x;
554 memcpy(p, (char *)&y, sizeof y);
555 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000556}
557
558static int
559np_ushort(char *p, PyObject *v, const formatdef *f)
560{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561 long x;
562 unsigned short y;
563 if (get_long(v, &x) < 0)
564 return -1;
565 if (x < 0 || x > USHRT_MAX){
566 PyErr_SetString(StructError,
567 "ushort format requires 0 <= number <= " STRINGIFY(USHRT_MAX));
568 return -1;
569 }
570 y = (unsigned short)x;
571 memcpy(p, (char *)&y, sizeof y);
572 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000573}
574
575static int
576np_int(char *p, PyObject *v, const formatdef *f)
577{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000578 long x;
579 int y;
580 if (get_long(v, &x) < 0)
581 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000582#if (SIZEOF_LONG > SIZEOF_INT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000583 if ((x < ((long)INT_MIN)) || (x > ((long)INT_MAX)))
584 RANGE_ERROR(x, f, 0, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000585#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000586 y = (int)x;
587 memcpy(p, (char *)&y, sizeof y);
588 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000589}
590
591static int
592np_uint(char *p, PyObject *v, const formatdef *f)
593{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 unsigned long x;
595 unsigned int y;
596 if (get_ulong(v, &x) < 0)
597 return -1;
598 y = (unsigned int)x;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000599#if (SIZEOF_LONG > SIZEOF_INT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000600 if (x > ((unsigned long)UINT_MAX))
601 RANGE_ERROR(y, f, 1, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000602#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000603 memcpy(p, (char *)&y, sizeof y);
604 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000605}
606
607static int
608np_long(char *p, PyObject *v, const formatdef *f)
609{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000610 long x;
611 if (get_long(v, &x) < 0)
612 return -1;
613 memcpy(p, (char *)&x, sizeof x);
614 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000615}
616
617static int
618np_ulong(char *p, PyObject *v, const formatdef *f)
619{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000620 unsigned long x;
621 if (get_ulong(v, &x) < 0)
622 return -1;
623 memcpy(p, (char *)&x, sizeof x);
624 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000625}
626
Antoine Pitrou45d9c912011-10-06 15:27:40 +0200627static int
628np_ssize_t(char *p, PyObject *v, const formatdef *f)
629{
630 Py_ssize_t x;
631 if (get_ssize_t(v, &x) < 0)
632 return -1;
633 memcpy(p, (char *)&x, sizeof x);
634 return 0;
635}
636
637static int
638np_size_t(char *p, PyObject *v, const formatdef *f)
639{
640 size_t x;
641 if (get_size_t(v, &x) < 0)
642 return -1;
643 memcpy(p, (char *)&x, sizeof x);
644 return 0;
645}
646
Thomas Wouters477c8d52006-05-27 19:21:47 +0000647#ifdef HAVE_LONG_LONG
648
649static int
650np_longlong(char *p, PyObject *v, const formatdef *f)
651{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000652 PY_LONG_LONG x;
653 if (get_longlong(v, &x) < 0)
654 return -1;
655 memcpy(p, (char *)&x, sizeof x);
656 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000657}
658
659static int
660np_ulonglong(char *p, PyObject *v, const formatdef *f)
661{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000662 unsigned PY_LONG_LONG x;
663 if (get_ulonglong(v, &x) < 0)
664 return -1;
665 memcpy(p, (char *)&x, sizeof x);
666 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000667}
668#endif
669
Thomas Woutersb2137042007-02-01 18:02:27 +0000670
671static int
672np_bool(char *p, PyObject *v, const formatdef *f)
673{
Benjamin Petersonde73c452010-07-07 18:54:59 +0000674 int y;
675 BOOL_TYPE x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 y = PyObject_IsTrue(v);
Benjamin Petersonde73c452010-07-07 18:54:59 +0000677 if (y < 0)
678 return -1;
679 x = y;
680 memcpy(p, (char *)&x, sizeof x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000681 return 0;
Thomas Woutersb2137042007-02-01 18:02:27 +0000682}
683
Thomas Wouters477c8d52006-05-27 19:21:47 +0000684static int
685np_float(char *p, PyObject *v, const formatdef *f)
686{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000687 float x = (float)PyFloat_AsDouble(v);
688 if (x == -1 && PyErr_Occurred()) {
689 PyErr_SetString(StructError,
690 "required argument is not a float");
691 return -1;
692 }
693 memcpy(p, (char *)&x, sizeof x);
694 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000695}
696
697static int
698np_double(char *p, PyObject *v, const formatdef *f)
699{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000700 double x = PyFloat_AsDouble(v);
701 if (x == -1 && PyErr_Occurred()) {
702 PyErr_SetString(StructError,
703 "required argument is not a float");
704 return -1;
705 }
706 memcpy(p, (char *)&x, sizeof(double));
707 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000708}
709
710static int
711np_void_p(char *p, PyObject *v, const formatdef *f)
712{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000713 void *x;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000714
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 v = get_pylong(v);
716 if (v == NULL)
717 return -1;
718 assert(PyLong_Check(v));
719 x = PyLong_AsVoidPtr(v);
720 Py_DECREF(v);
721 if (x == NULL && PyErr_Occurred())
722 return -1;
723 memcpy(p, (char *)&x, sizeof x);
724 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000725}
726
727static formatdef native_table[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000728 {'x', sizeof(char), 0, NULL},
729 {'b', sizeof(char), 0, nu_byte, np_byte},
730 {'B', sizeof(char), 0, nu_ubyte, np_ubyte},
731 {'c', sizeof(char), 0, nu_char, np_char},
732 {'s', sizeof(char), 0, NULL},
733 {'p', sizeof(char), 0, NULL},
734 {'h', sizeof(short), SHORT_ALIGN, nu_short, np_short},
735 {'H', sizeof(short), SHORT_ALIGN, nu_ushort, np_ushort},
736 {'i', sizeof(int), INT_ALIGN, nu_int, np_int},
737 {'I', sizeof(int), INT_ALIGN, nu_uint, np_uint},
738 {'l', sizeof(long), LONG_ALIGN, nu_long, np_long},
739 {'L', sizeof(long), LONG_ALIGN, nu_ulong, np_ulong},
Antoine Pitrou45d9c912011-10-06 15:27:40 +0200740 {'n', sizeof(size_t), SIZE_T_ALIGN, nu_ssize_t, np_ssize_t},
741 {'N', sizeof(size_t), SIZE_T_ALIGN, nu_size_t, np_size_t},
Thomas Wouters477c8d52006-05-27 19:21:47 +0000742#ifdef HAVE_LONG_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000743 {'q', sizeof(PY_LONG_LONG), LONG_LONG_ALIGN, nu_longlong, np_longlong},
744 {'Q', sizeof(PY_LONG_LONG), LONG_LONG_ALIGN, nu_ulonglong,np_ulonglong},
Thomas Wouters477c8d52006-05-27 19:21:47 +0000745#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000746 {'?', sizeof(BOOL_TYPE), BOOL_ALIGN, nu_bool, np_bool},
747 {'f', sizeof(float), FLOAT_ALIGN, nu_float, np_float},
748 {'d', sizeof(double), DOUBLE_ALIGN, nu_double, np_double},
749 {'P', sizeof(void *), VOID_P_ALIGN, nu_void_p, np_void_p},
750 {0}
Thomas Wouters477c8d52006-05-27 19:21:47 +0000751};
752
753/* Big-endian routines. *****************************************************/
754
755static PyObject *
756bu_int(const char *p, const formatdef *f)
757{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 long x = 0;
759 Py_ssize_t i = f->size;
760 const unsigned char *bytes = (const unsigned char *)p;
761 do {
762 x = (x<<8) | *bytes++;
763 } while (--i > 0);
764 /* Extend the sign bit. */
765 if (SIZEOF_LONG > f->size)
766 x |= -(x & (1L << ((8 * f->size) - 1)));
767 return PyLong_FromLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000768}
769
770static PyObject *
771bu_uint(const char *p, const formatdef *f)
772{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000773 unsigned long x = 0;
774 Py_ssize_t i = f->size;
775 const unsigned char *bytes = (const unsigned char *)p;
776 do {
777 x = (x<<8) | *bytes++;
778 } while (--i > 0);
779 if (x <= LONG_MAX)
780 return PyLong_FromLong((long)x);
781 return PyLong_FromUnsignedLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000782}
783
784static PyObject *
785bu_longlong(const char *p, const formatdef *f)
786{
787#ifdef HAVE_LONG_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000788 PY_LONG_LONG x = 0;
789 Py_ssize_t i = f->size;
790 const unsigned char *bytes = (const unsigned char *)p;
791 do {
792 x = (x<<8) | *bytes++;
793 } while (--i > 0);
794 /* Extend the sign bit. */
795 if (SIZEOF_LONG_LONG > f->size)
796 x |= -(x & ((PY_LONG_LONG)1 << ((8 * f->size) - 1)));
797 if (x >= LONG_MIN && x <= LONG_MAX)
798 return PyLong_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long));
799 return PyLong_FromLongLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000800#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000801 return _PyLong_FromByteArray((const unsigned char *)p,
802 8,
803 0, /* little-endian */
804 1 /* signed */);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000805#endif
806}
807
808static PyObject *
809bu_ulonglong(const char *p, const formatdef *f)
810{
811#ifdef HAVE_LONG_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 unsigned PY_LONG_LONG x = 0;
813 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 if (x <= LONG_MAX)
819 return PyLong_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long));
820 return PyLong_FromUnsignedLongLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000821#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000822 return _PyLong_FromByteArray((const unsigned char *)p,
823 8,
824 0, /* little-endian */
825 0 /* signed */);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000826#endif
827}
828
829static PyObject *
830bu_float(const char *p, const formatdef *f)
831{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000832 return unpack_float(p, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000833}
834
835static PyObject *
836bu_double(const char *p, const formatdef *f)
837{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 return unpack_double(p, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000839}
840
Thomas Woutersb2137042007-02-01 18:02:27 +0000841static PyObject *
842bu_bool(const char *p, const formatdef *f)
843{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000844 char x;
845 memcpy((char *)&x, p, sizeof x);
846 return PyBool_FromLong(x != 0);
Thomas Woutersb2137042007-02-01 18:02:27 +0000847}
848
Thomas Wouters477c8d52006-05-27 19:21:47 +0000849static int
850bp_int(char *p, PyObject *v, const formatdef *f)
851{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000852 long x;
853 Py_ssize_t i;
854 if (get_long(v, &x) < 0)
855 return -1;
856 i = f->size;
857 if (i != SIZEOF_LONG) {
858 if ((i == 2) && (x < -32768 || x > 32767))
859 RANGE_ERROR(x, f, 0, 0xffffL);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000860#if (SIZEOF_LONG != 4)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000861 else if ((i == 4) && (x < -2147483648L || x > 2147483647L))
862 RANGE_ERROR(x, f, 0, 0xffffffffL);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000863#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 }
865 do {
866 p[--i] = (char)x;
867 x >>= 8;
868 } while (i > 0);
869 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000870}
871
872static int
873bp_uint(char *p, PyObject *v, const formatdef *f)
874{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000875 unsigned long x;
876 Py_ssize_t i;
877 if (get_ulong(v, &x) < 0)
878 return -1;
879 i = f->size;
880 if (i != SIZEOF_LONG) {
881 unsigned long maxint = 1;
882 maxint <<= (unsigned long)(i * 8);
883 if (x >= maxint)
884 RANGE_ERROR(x, f, 1, maxint - 1);
885 }
886 do {
887 p[--i] = (char)x;
888 x >>= 8;
889 } while (i > 0);
890 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000891}
892
893static int
894bp_longlong(char *p, PyObject *v, const formatdef *f)
895{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 int res;
897 v = get_pylong(v);
898 if (v == NULL)
899 return -1;
900 res = _PyLong_AsByteArray((PyLongObject *)v,
901 (unsigned char *)p,
902 8,
903 0, /* little_endian */
904 1 /* signed */);
905 Py_DECREF(v);
906 return res;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000907}
908
909static int
910bp_ulonglong(char *p, PyObject *v, const formatdef *f)
911{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000912 int res;
913 v = get_pylong(v);
914 if (v == NULL)
915 return -1;
916 res = _PyLong_AsByteArray((PyLongObject *)v,
917 (unsigned char *)p,
918 8,
919 0, /* little_endian */
920 0 /* signed */);
921 Py_DECREF(v);
922 return res;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000923}
924
925static int
926bp_float(char *p, PyObject *v, const formatdef *f)
927{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 double x = PyFloat_AsDouble(v);
929 if (x == -1 && PyErr_Occurred()) {
930 PyErr_SetString(StructError,
931 "required argument is not a float");
932 return -1;
933 }
934 return _PyFloat_Pack4(x, (unsigned char *)p, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000935}
936
937static int
938bp_double(char *p, PyObject *v, const formatdef *f)
939{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 double x = PyFloat_AsDouble(v);
941 if (x == -1 && PyErr_Occurred()) {
942 PyErr_SetString(StructError,
943 "required argument is not a float");
944 return -1;
945 }
946 return _PyFloat_Pack8(x, (unsigned char *)p, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000947}
948
Thomas Woutersb2137042007-02-01 18:02:27 +0000949static int
950bp_bool(char *p, PyObject *v, const formatdef *f)
951{
Mark Dickinsoneff5d852010-07-18 07:29:02 +0000952 int y;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 y = PyObject_IsTrue(v);
Benjamin Petersonde73c452010-07-07 18:54:59 +0000954 if (y < 0)
955 return -1;
Mark Dickinsoneff5d852010-07-18 07:29:02 +0000956 *p = (char)y;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000957 return 0;
Thomas Woutersb2137042007-02-01 18:02:27 +0000958}
959
Thomas Wouters477c8d52006-05-27 19:21:47 +0000960static formatdef bigendian_table[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000961 {'x', 1, 0, NULL},
962 {'b', 1, 0, nu_byte, np_byte},
963 {'B', 1, 0, nu_ubyte, np_ubyte},
964 {'c', 1, 0, nu_char, np_char},
965 {'s', 1, 0, NULL},
966 {'p', 1, 0, NULL},
967 {'h', 2, 0, bu_int, bp_int},
968 {'H', 2, 0, bu_uint, bp_uint},
969 {'i', 4, 0, bu_int, bp_int},
970 {'I', 4, 0, bu_uint, bp_uint},
971 {'l', 4, 0, bu_int, bp_int},
972 {'L', 4, 0, bu_uint, bp_uint},
973 {'q', 8, 0, bu_longlong, bp_longlong},
974 {'Q', 8, 0, bu_ulonglong, bp_ulonglong},
975 {'?', 1, 0, bu_bool, bp_bool},
976 {'f', 4, 0, bu_float, bp_float},
977 {'d', 8, 0, bu_double, bp_double},
978 {0}
Thomas Wouters477c8d52006-05-27 19:21:47 +0000979};
980
981/* Little-endian routines. *****************************************************/
982
983static PyObject *
984lu_int(const char *p, const formatdef *f)
985{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 long x = 0;
987 Py_ssize_t i = f->size;
988 const unsigned char *bytes = (const unsigned char *)p;
989 do {
990 x = (x<<8) | bytes[--i];
991 } while (i > 0);
992 /* Extend the sign bit. */
993 if (SIZEOF_LONG > f->size)
994 x |= -(x & (1L << ((8 * f->size) - 1)));
995 return PyLong_FromLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000996}
997
998static PyObject *
999lu_uint(const char *p, const formatdef *f)
1000{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001001 unsigned long x = 0;
1002 Py_ssize_t i = f->size;
1003 const unsigned char *bytes = (const unsigned char *)p;
1004 do {
1005 x = (x<<8) | bytes[--i];
1006 } while (i > 0);
1007 if (x <= LONG_MAX)
1008 return PyLong_FromLong((long)x);
1009 return PyLong_FromUnsignedLong((long)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001010}
1011
1012static PyObject *
1013lu_longlong(const char *p, const formatdef *f)
1014{
1015#ifdef HAVE_LONG_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 PY_LONG_LONG x = 0;
1017 Py_ssize_t i = f->size;
1018 const unsigned char *bytes = (const unsigned char *)p;
1019 do {
1020 x = (x<<8) | bytes[--i];
1021 } while (i > 0);
1022 /* Extend the sign bit. */
1023 if (SIZEOF_LONG_LONG > f->size)
1024 x |= -(x & ((PY_LONG_LONG)1 << ((8 * f->size) - 1)));
1025 if (x >= LONG_MIN && x <= LONG_MAX)
1026 return PyLong_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long));
1027 return PyLong_FromLongLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001028#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 return _PyLong_FromByteArray((const unsigned char *)p,
1030 8,
1031 1, /* little-endian */
1032 1 /* signed */);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001033#endif
1034}
1035
1036static PyObject *
1037lu_ulonglong(const char *p, const formatdef *f)
1038{
1039#ifdef HAVE_LONG_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 unsigned PY_LONG_LONG x = 0;
1041 Py_ssize_t i = f->size;
1042 const unsigned char *bytes = (const unsigned char *)p;
1043 do {
1044 x = (x<<8) | bytes[--i];
1045 } while (i > 0);
1046 if (x <= LONG_MAX)
1047 return PyLong_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long));
1048 return PyLong_FromUnsignedLongLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001049#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 return _PyLong_FromByteArray((const unsigned char *)p,
1051 8,
1052 1, /* little-endian */
1053 0 /* signed */);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001054#endif
1055}
1056
1057static PyObject *
1058lu_float(const char *p, const formatdef *f)
1059{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001060 return unpack_float(p, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001061}
1062
1063static PyObject *
1064lu_double(const char *p, const formatdef *f)
1065{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001066 return unpack_double(p, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001067}
1068
1069static int
1070lp_int(char *p, PyObject *v, const formatdef *f)
1071{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001072 long x;
1073 Py_ssize_t i;
1074 if (get_long(v, &x) < 0)
1075 return -1;
1076 i = f->size;
1077 if (i != SIZEOF_LONG) {
1078 if ((i == 2) && (x < -32768 || x > 32767))
1079 RANGE_ERROR(x, f, 0, 0xffffL);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001080#if (SIZEOF_LONG != 4)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001081 else if ((i == 4) && (x < -2147483648L || x > 2147483647L))
1082 RANGE_ERROR(x, f, 0, 0xffffffffL);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001083#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 }
1085 do {
1086 *p++ = (char)x;
1087 x >>= 8;
1088 } while (--i > 0);
1089 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001090}
1091
1092static int
1093lp_uint(char *p, PyObject *v, const formatdef *f)
1094{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001095 unsigned long x;
1096 Py_ssize_t i;
1097 if (get_ulong(v, &x) < 0)
1098 return -1;
1099 i = f->size;
1100 if (i != SIZEOF_LONG) {
1101 unsigned long maxint = 1;
1102 maxint <<= (unsigned long)(i * 8);
1103 if (x >= maxint)
1104 RANGE_ERROR(x, f, 1, maxint - 1);
1105 }
1106 do {
1107 *p++ = (char)x;
1108 x >>= 8;
1109 } while (--i > 0);
1110 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001111}
1112
1113static int
1114lp_longlong(char *p, PyObject *v, const formatdef *f)
1115{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001116 int res;
1117 v = get_pylong(v);
1118 if (v == NULL)
1119 return -1;
1120 res = _PyLong_AsByteArray((PyLongObject*)v,
1121 (unsigned char *)p,
1122 8,
1123 1, /* little_endian */
1124 1 /* signed */);
1125 Py_DECREF(v);
1126 return res;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001127}
1128
1129static int
1130lp_ulonglong(char *p, PyObject *v, const formatdef *f)
1131{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001132 int res;
1133 v = get_pylong(v);
1134 if (v == NULL)
1135 return -1;
1136 res = _PyLong_AsByteArray((PyLongObject*)v,
1137 (unsigned char *)p,
1138 8,
1139 1, /* little_endian */
1140 0 /* signed */);
1141 Py_DECREF(v);
1142 return res;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001143}
1144
1145static int
1146lp_float(char *p, PyObject *v, const formatdef *f)
1147{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001148 double x = PyFloat_AsDouble(v);
1149 if (x == -1 && PyErr_Occurred()) {
1150 PyErr_SetString(StructError,
1151 "required argument is not a float");
1152 return -1;
1153 }
1154 return _PyFloat_Pack4(x, (unsigned char *)p, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001155}
1156
1157static int
1158lp_double(char *p, PyObject *v, const formatdef *f)
1159{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001160 double x = PyFloat_AsDouble(v);
1161 if (x == -1 && PyErr_Occurred()) {
1162 PyErr_SetString(StructError,
1163 "required argument is not a float");
1164 return -1;
1165 }
1166 return _PyFloat_Pack8(x, (unsigned char *)p, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001167}
1168
1169static formatdef lilendian_table[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001170 {'x', 1, 0, NULL},
1171 {'b', 1, 0, nu_byte, np_byte},
1172 {'B', 1, 0, nu_ubyte, np_ubyte},
1173 {'c', 1, 0, nu_char, np_char},
1174 {'s', 1, 0, NULL},
1175 {'p', 1, 0, NULL},
1176 {'h', 2, 0, lu_int, lp_int},
1177 {'H', 2, 0, lu_uint, lp_uint},
1178 {'i', 4, 0, lu_int, lp_int},
1179 {'I', 4, 0, lu_uint, lp_uint},
1180 {'l', 4, 0, lu_int, lp_int},
1181 {'L', 4, 0, lu_uint, lp_uint},
1182 {'q', 8, 0, lu_longlong, lp_longlong},
1183 {'Q', 8, 0, lu_ulonglong, lp_ulonglong},
1184 {'?', 1, 0, bu_bool, bp_bool}, /* Std rep not endian dep,
1185 but potentially different from native rep -- reuse bx_bool funcs. */
1186 {'f', 4, 0, lu_float, lp_float},
1187 {'d', 8, 0, lu_double, lp_double},
1188 {0}
Thomas Wouters477c8d52006-05-27 19:21:47 +00001189};
1190
1191
1192static const formatdef *
1193whichtable(char **pfmt)
1194{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195 const char *fmt = (*pfmt)++; /* May be backed out of later */
1196 switch (*fmt) {
1197 case '<':
1198 return lilendian_table;
1199 case '>':
1200 case '!': /* Network byte order is big-endian */
1201 return bigendian_table;
Ezio Melotti42da6632011-03-15 05:18:48 +02001202 case '=': { /* Host byte order -- different from native in alignment! */
Christian Heimes743e0cd2012-10-17 23:52:17 +02001203#if PY_LITTLE_ENDIAN
1204 return lilendian_table;
1205#else
1206 return bigendian_table;
1207#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001208 }
1209 default:
1210 --*pfmt; /* Back out of pointer increment */
1211 /* Fall through */
1212 case '@':
1213 return native_table;
1214 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001215}
1216
1217
1218/* Get the table entry for a format code */
1219
1220static const formatdef *
1221getentry(int c, const formatdef *f)
1222{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001223 for (; f->format != '\0'; f++) {
1224 if (f->format == c) {
1225 return f;
1226 }
1227 }
1228 PyErr_SetString(StructError, "bad char in struct format");
1229 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001230}
1231
1232
Mark Dickinsonb72e6862010-06-11 19:50:30 +00001233/* Align a size according to a format code. Return -1 on overflow. */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001234
Mark Dickinsoneac0e682010-06-11 19:05:08 +00001235static Py_ssize_t
Thomas Wouters477c8d52006-05-27 19:21:47 +00001236align(Py_ssize_t size, char c, const formatdef *e)
1237{
Mark Dickinsonb72e6862010-06-11 19:50:30 +00001238 Py_ssize_t extra;
1239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001240 if (e->format == c) {
Mark Dickinsonb72e6862010-06-11 19:50:30 +00001241 if (e->alignment && size > 0) {
1242 extra = (e->alignment - 1) - (size - 1) % (e->alignment);
1243 if (extra > PY_SSIZE_T_MAX - size)
1244 return -1;
1245 size += extra;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001246 }
1247 }
1248 return size;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001249}
1250
Antoine Pitrou9f146812013-04-27 00:20:04 +02001251/*
1252 * Struct object implementation.
1253 */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001254
1255/* calculate the size of a format string */
1256
1257static int
1258prepare_s(PyStructObject *self)
1259{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001260 const formatdef *f;
1261 const formatdef *e;
1262 formatcode *codes;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001264 const char *s;
1265 const char *fmt;
1266 char c;
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001267 Py_ssize_t size, len, ncodes, num, itemsize;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001269 fmt = PyBytes_AS_STRING(self->s_format);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001271 f = whichtable((char **)&fmt);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001273 s = fmt;
1274 size = 0;
1275 len = 0;
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001276 ncodes = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001277 while ((c = *s++) != '\0') {
Antoine Pitrou4de74572013-02-09 23:11:27 +01001278 if (Py_ISSPACE(Py_CHARMASK(c)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001279 continue;
1280 if ('0' <= c && c <= '9') {
1281 num = c - '0';
1282 while ('0' <= (c = *s++) && c <= '9') {
Mark Dickinsonab4096f2010-06-11 16:56:34 +00001283 /* overflow-safe version of
1284 if (num*10 + (c - '0') > PY_SSIZE_T_MAX) { ... } */
1285 if (num >= PY_SSIZE_T_MAX / 10 && (
1286 num > PY_SSIZE_T_MAX / 10 ||
Mark Dickinsonb72e6862010-06-11 19:50:30 +00001287 (c - '0') > PY_SSIZE_T_MAX % 10))
1288 goto overflow;
Mark Dickinsonab4096f2010-06-11 16:56:34 +00001289 num = num*10 + (c - '0');
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001290 }
Alexander Belopolsky177e8532010-06-11 16:04:59 +00001291 if (c == '\0') {
1292 PyErr_SetString(StructError,
1293 "repeat count given without format specifier");
1294 return -1;
1295 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001296 }
1297 else
1298 num = 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001300 e = getentry(c, f);
1301 if (e == NULL)
1302 return -1;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001304 switch (c) {
1305 case 's': /* fall through */
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001306 case 'p': len++; ncodes++; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001307 case 'x': break;
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001308 default: len += num; if (num) ncodes++; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001309 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001311 itemsize = e->size;
1312 size = align(size, c, e);
Mark Dickinsonb72e6862010-06-11 19:50:30 +00001313 if (size == -1)
1314 goto overflow;
1315
1316 /* if (size + num * itemsize > PY_SSIZE_T_MAX) { ... } */
1317 if (num > (PY_SSIZE_T_MAX - size) / itemsize)
1318 goto overflow;
1319 size += num * itemsize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001320 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001322 /* check for overflow */
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001323 if ((ncodes + 1) > (PY_SSIZE_T_MAX / sizeof(formatcode))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001324 PyErr_NoMemory();
1325 return -1;
1326 }
Amaury Forgeot d'Arc35c86582008-06-17 21:11:29 +00001327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001328 self->s_size = size;
1329 self->s_len = len;
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001330 codes = PyMem_MALLOC((ncodes + 1) * sizeof(formatcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001331 if (codes == NULL) {
1332 PyErr_NoMemory();
1333 return -1;
1334 }
Mark Dickinsoncf28b952010-07-29 21:41:59 +00001335 /* Free any s_codes value left over from a previous initialization. */
1336 if (self->s_codes != NULL)
1337 PyMem_FREE(self->s_codes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001338 self->s_codes = codes;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001340 s = fmt;
1341 size = 0;
1342 while ((c = *s++) != '\0') {
Antoine Pitrou4de74572013-02-09 23:11:27 +01001343 if (Py_ISSPACE(Py_CHARMASK(c)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001344 continue;
1345 if ('0' <= c && c <= '9') {
1346 num = c - '0';
1347 while ('0' <= (c = *s++) && c <= '9')
1348 num = num*10 + (c - '0');
1349 if (c == '\0')
1350 break;
1351 }
1352 else
1353 num = 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001355 e = getentry(c, f);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001357 size = align(size, c, e);
1358 if (c == 's' || c == 'p') {
1359 codes->offset = size;
1360 codes->size = num;
1361 codes->fmtdef = e;
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001362 codes->repeat = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001363 codes++;
1364 size += num;
1365 } else if (c == 'x') {
1366 size += num;
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001367 } else if (num) {
1368 codes->offset = size;
1369 codes->size = e->size;
1370 codes->fmtdef = e;
1371 codes->repeat = num;
1372 codes++;
1373 size += e->size * num;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001374 }
1375 }
1376 codes->fmtdef = NULL;
1377 codes->offset = size;
1378 codes->size = 0;
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001379 codes->repeat = 0;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001381 return 0;
Mark Dickinsonb72e6862010-06-11 19:50:30 +00001382
1383 overflow:
1384 PyErr_SetString(StructError,
1385 "total struct size too long");
1386 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001387}
1388
1389static PyObject *
1390s_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1391{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001392 PyObject *self;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001394 assert(type != NULL && type->tp_alloc != NULL);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001396 self = type->tp_alloc(type, 0);
1397 if (self != NULL) {
1398 PyStructObject *s = (PyStructObject*)self;
1399 Py_INCREF(Py_None);
1400 s->s_format = Py_None;
1401 s->s_codes = NULL;
1402 s->s_size = -1;
1403 s->s_len = -1;
1404 }
1405 return self;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001406}
1407
1408static int
1409s_init(PyObject *self, PyObject *args, PyObject *kwds)
1410{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001411 PyStructObject *soself = (PyStructObject *)self;
1412 PyObject *o_format = NULL;
1413 int ret = 0;
1414 static char *kwlist[] = {"format", 0};
Thomas Wouters477c8d52006-05-27 19:21:47 +00001415
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001416 assert(PyStruct_Check(self));
Thomas Wouters477c8d52006-05-27 19:21:47 +00001417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001418 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:Struct", kwlist,
1419 &o_format))
1420 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001422 if (PyUnicode_Check(o_format)) {
1423 o_format = PyUnicode_AsASCIIString(o_format);
1424 if (o_format == NULL)
1425 return -1;
1426 }
1427 /* XXX support buffer interface, too */
1428 else {
1429 Py_INCREF(o_format);
1430 }
Christian Heimesa34706f2008-01-04 03:06:10 +00001431
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001432 if (!PyBytes_Check(o_format)) {
1433 Py_DECREF(o_format);
1434 PyErr_Format(PyExc_TypeError,
Victor Stinnerda9ec992010-12-28 13:26:42 +00001435 "Struct() argument 1 must be a bytes object, not %.200s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001436 Py_TYPE(o_format)->tp_name);
1437 return -1;
1438 }
Christian Heimesa34706f2008-01-04 03:06:10 +00001439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001440 Py_CLEAR(soself->s_format);
1441 soself->s_format = o_format;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001442
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001443 ret = prepare_s(soself);
1444 return ret;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001445}
1446
1447static void
1448s_dealloc(PyStructObject *s)
1449{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001450 if (s->weakreflist != NULL)
1451 PyObject_ClearWeakRefs((PyObject *)s);
1452 if (s->s_codes != NULL) {
1453 PyMem_FREE(s->s_codes);
1454 }
1455 Py_XDECREF(s->s_format);
1456 Py_TYPE(s)->tp_free((PyObject *)s);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001457}
1458
1459static PyObject *
1460s_unpack_internal(PyStructObject *soself, char *startfrom) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001461 formatcode *code;
1462 Py_ssize_t i = 0;
1463 PyObject *result = PyTuple_New(soself->s_len);
1464 if (result == NULL)
1465 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001466
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001467 for (code = soself->s_codes; code->fmtdef != NULL; code++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001468 const formatdef *e = code->fmtdef;
1469 const char *res = startfrom + code->offset;
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001470 Py_ssize_t j = code->repeat;
1471 while (j--) {
1472 PyObject *v;
1473 if (e->format == 's') {
1474 v = PyBytes_FromStringAndSize(res, code->size);
1475 } else if (e->format == 'p') {
1476 Py_ssize_t n = *(unsigned char*)res;
1477 if (n >= code->size)
1478 n = code->size - 1;
1479 v = PyBytes_FromStringAndSize(res + 1, n);
1480 } else {
1481 v = e->unpack(res, e);
1482 }
1483 if (v == NULL)
1484 goto fail;
1485 PyTuple_SET_ITEM(result, i++, v);
1486 res += code->size;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001487 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001488 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001490 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001491fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001492 Py_DECREF(result);
1493 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001494}
1495
1496
1497PyDoc_STRVAR(s_unpack__doc__,
Guido van Rossum913dd0b2007-04-13 03:33:53 +00001498"S.unpack(buffer) -> (v1, v2, ...)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00001499\n\
Mark Dickinsonaacfa952010-06-12 15:43:45 +00001500Return a tuple containing values unpacked according to the format\n\
1501string S.format. Requires len(buffer) == S.size. See help(struct)\n\
1502for more on format strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001503
1504static PyObject *
Guido van Rossum98297ee2007-11-06 21:34:58 +00001505s_unpack(PyObject *self, PyObject *input)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001506{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001507 Py_buffer vbuf;
1508 PyObject *result;
1509 PyStructObject *soself = (PyStructObject *)self;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001511 assert(PyStruct_Check(self));
1512 assert(soself->s_codes != NULL);
1513 if (PyObject_GetBuffer(input, &vbuf, PyBUF_SIMPLE) < 0)
1514 return NULL;
1515 if (vbuf.len != soself->s_size) {
1516 PyErr_Format(StructError,
Victor Stinnerda9ec992010-12-28 13:26:42 +00001517 "unpack requires a bytes object of length %zd",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001518 soself->s_size);
1519 PyBuffer_Release(&vbuf);
1520 return NULL;
1521 }
1522 result = s_unpack_internal(soself, vbuf.buf);
1523 PyBuffer_Release(&vbuf);
1524 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001525}
1526
1527PyDoc_STRVAR(s_unpack_from__doc__,
Mark Dickinsonc6f13962010-06-13 09:17:13 +00001528"S.unpack_from(buffer, offset=0) -> (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\
1531string S.format. Requires len(buffer[offset:]) >= S.size. See\n\
1532help(struct) for more on format strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001533
1534static PyObject *
1535s_unpack_from(PyObject *self, PyObject *args, PyObject *kwds)
1536{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001537 static char *kwlist[] = {"buffer", "offset", 0};
Guido van Rossum98297ee2007-11-06 21:34:58 +00001538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001539 PyObject *input;
1540 Py_ssize_t offset = 0;
1541 Py_buffer vbuf;
1542 PyObject *result;
1543 PyStructObject *soself = (PyStructObject *)self;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001545 assert(PyStruct_Check(self));
1546 assert(soself->s_codes != NULL);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001548 if (!PyArg_ParseTupleAndKeywords(args, kwds,
1549 "O|n:unpack_from", kwlist,
1550 &input, &offset))
1551 return NULL;
1552 if (PyObject_GetBuffer(input, &vbuf, PyBUF_SIMPLE) < 0)
1553 return NULL;
1554 if (offset < 0)
1555 offset += vbuf.len;
1556 if (offset < 0 || vbuf.len - offset < soself->s_size) {
1557 PyErr_Format(StructError,
1558 "unpack_from requires a buffer of at least %zd bytes",
1559 soself->s_size);
1560 PyBuffer_Release(&vbuf);
1561 return NULL;
1562 }
1563 result = s_unpack_internal(soself, (char*)vbuf.buf + offset);
1564 PyBuffer_Release(&vbuf);
1565 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001566}
1567
1568
Antoine Pitrou9f146812013-04-27 00:20:04 +02001569/* Unpack iterator type */
1570
1571typedef struct {
1572 PyObject_HEAD
1573 PyStructObject *so;
1574 Py_buffer buf;
1575 Py_ssize_t index;
1576} unpackiterobject;
1577
1578static void
1579unpackiter_dealloc(unpackiterobject *self)
1580{
1581 Py_XDECREF(self->so);
1582 PyBuffer_Release(&self->buf);
1583 PyObject_GC_Del(self);
1584}
1585
1586static int
1587unpackiter_traverse(unpackiterobject *self, visitproc visit, void *arg)
1588{
1589 Py_VISIT(self->so);
1590 Py_VISIT(self->buf.obj);
1591 return 0;
1592}
1593
1594static PyObject *
1595unpackiter_len(unpackiterobject *self)
1596{
1597 Py_ssize_t len;
1598 if (self->so == NULL)
1599 len = 0;
1600 else
1601 len = (self->buf.len - self->index) / self->so->s_size;
1602 return PyLong_FromSsize_t(len);
1603}
1604
1605static PyMethodDef unpackiter_methods[] = {
1606 {"__length_hint__", (PyCFunction) unpackiter_len, METH_NOARGS, NULL},
1607 {NULL, NULL} /* sentinel */
1608};
1609
1610static PyObject *
1611unpackiter_iternext(unpackiterobject *self)
1612{
1613 PyObject *result;
1614 if (self->so == NULL)
1615 return NULL;
1616 if (self->index >= self->buf.len) {
1617 /* Iterator exhausted */
1618 Py_CLEAR(self->so);
1619 PyBuffer_Release(&self->buf);
1620 return NULL;
1621 }
1622 assert(self->index + self->so->s_size <= self->buf.len);
1623 result = s_unpack_internal(self->so,
1624 (char*) self->buf.buf + self->index);
1625 self->index += self->so->s_size;
1626 return result;
1627}
1628
doko@ubuntu.com46c5deb2013-11-23 16:07:55 +01001629static PyTypeObject unpackiter_type = {
Antoine Pitrou9f146812013-04-27 00:20:04 +02001630 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1631 "unpack_iterator", /* tp_name */
1632 sizeof(unpackiterobject), /* tp_basicsize */
1633 0, /* tp_itemsize */
1634 (destructor)unpackiter_dealloc, /* tp_dealloc */
1635 0, /* tp_print */
1636 0, /* tp_getattr */
1637 0, /* tp_setattr */
1638 0, /* tp_reserved */
1639 0, /* tp_repr */
1640 0, /* tp_as_number */
1641 0, /* tp_as_sequence */
1642 0, /* tp_as_mapping */
1643 0, /* tp_hash */
1644 0, /* tp_call */
1645 0, /* tp_str */
1646 PyObject_GenericGetAttr, /* tp_getattro */
1647 0, /* tp_setattro */
1648 0, /* tp_as_buffer */
1649 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
1650 0, /* tp_doc */
1651 (traverseproc)unpackiter_traverse, /* tp_traverse */
1652 0, /* tp_clear */
1653 0, /* tp_richcompare */
1654 0, /* tp_weaklistoffset */
1655 PyObject_SelfIter, /* tp_iter */
1656 (iternextfunc)unpackiter_iternext, /* tp_iternext */
1657 unpackiter_methods /* tp_methods */
1658};
1659
1660PyDoc_STRVAR(s_iter_unpack__doc__,
1661"S.iter_unpack(buffer) -> iterator(v1, v2, ...)\n\
1662\n\
1663Return an iterator yielding tuples unpacked from the given bytes\n\
1664source, like a repeated invocation of unpack_from(). Requires\n\
1665that the bytes length be a multiple of the struct size.");
1666
1667static PyObject *
1668s_iter_unpack(PyObject *_so, PyObject *input)
1669{
1670 PyStructObject *so = (PyStructObject *) _so;
1671 unpackiterobject *self;
1672
1673 assert(PyStruct_Check(_so));
1674 assert(so->s_codes != NULL);
1675
1676 if (so->s_size == 0) {
1677 PyErr_Format(StructError,
1678 "cannot iteratively unpack with a struct of length 0");
1679 return NULL;
1680 }
1681
1682 self = (unpackiterobject *) PyType_GenericAlloc(&unpackiter_type, 0);
1683 if (self == NULL)
1684 return NULL;
1685
1686 if (PyObject_GetBuffer(input, &self->buf, PyBUF_SIMPLE) < 0) {
1687 Py_DECREF(self);
1688 return NULL;
1689 }
1690 if (self->buf.len % so->s_size != 0) {
1691 PyErr_Format(StructError,
1692 "iterative unpacking requires a bytes length "
1693 "multiple of %zd",
1694 so->s_size);
1695 Py_DECREF(self);
1696 return NULL;
1697 }
1698 Py_INCREF(so);
1699 self->so = so;
1700 self->index = 0;
1701 return (PyObject *) self;
1702}
1703
1704
Thomas Wouters477c8d52006-05-27 19:21:47 +00001705/*
1706 * Guts of the pack function.
1707 *
1708 * Takes a struct object, a tuple of arguments, and offset in that tuple of
1709 * argument for where to start processing the arguments for packing, and a
1710 * character buffer for writing the packed string. The caller must insure
1711 * that the buffer may contain the required length for packing the arguments.
1712 * 0 is returned on success, 1 is returned if there is an error.
1713 *
1714 */
1715static int
1716s_pack_internal(PyStructObject *soself, PyObject *args, int offset, char* buf)
1717{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001718 formatcode *code;
1719 /* XXX(nnorwitz): why does i need to be a local? can we use
1720 the offset parameter or do we need the wider width? */
1721 Py_ssize_t i;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001722
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001723 memset(buf, '\0', soself->s_size);
1724 i = offset;
1725 for (code = soself->s_codes; code->fmtdef != NULL; code++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001726 const formatdef *e = code->fmtdef;
1727 char *res = buf + code->offset;
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001728 Py_ssize_t j = code->repeat;
1729 while (j--) {
1730 PyObject *v = PyTuple_GET_ITEM(args, i++);
1731 if (e->format == 's') {
1732 Py_ssize_t n;
1733 int isstring;
1734 void *p;
1735 isstring = PyBytes_Check(v);
1736 if (!isstring && !PyByteArray_Check(v)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001737 PyErr_SetString(StructError,
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001738 "argument for 's' must be a bytes object");
1739 return -1;
1740 }
1741 if (isstring) {
1742 n = PyBytes_GET_SIZE(v);
1743 p = PyBytes_AS_STRING(v);
1744 }
1745 else {
1746 n = PyByteArray_GET_SIZE(v);
1747 p = PyByteArray_AS_STRING(v);
1748 }
1749 if (n > code->size)
1750 n = code->size;
1751 if (n > 0)
1752 memcpy(res, p, n);
1753 } else if (e->format == 'p') {
1754 Py_ssize_t n;
1755 int isstring;
1756 void *p;
1757 isstring = PyBytes_Check(v);
1758 if (!isstring && !PyByteArray_Check(v)) {
1759 PyErr_SetString(StructError,
1760 "argument for 'p' must be a bytes object");
1761 return -1;
1762 }
1763 if (isstring) {
1764 n = PyBytes_GET_SIZE(v);
1765 p = PyBytes_AS_STRING(v);
1766 }
1767 else {
1768 n = PyByteArray_GET_SIZE(v);
1769 p = PyByteArray_AS_STRING(v);
1770 }
1771 if (n > (code->size - 1))
1772 n = code->size - 1;
1773 if (n > 0)
1774 memcpy(res + 1, p, n);
1775 if (n > 255)
1776 n = 255;
1777 *res = Py_SAFE_DOWNCAST(n, Py_ssize_t, unsigned char);
1778 } else {
1779 if (e->pack(res, v, e) < 0) {
1780 if (PyLong_Check(v) && PyErr_ExceptionMatches(PyExc_OverflowError))
1781 PyErr_SetString(StructError,
Serhiy Storchaka46e1ce22013-08-27 20:17:03 +03001782 "int too large to convert");
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001783 return -1;
1784 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001785 }
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001786 res += code->size;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001787 }
1788 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001790 /* Success */
1791 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001792}
1793
1794
1795PyDoc_STRVAR(s_pack__doc__,
Benjamin Peterson4ae19462008-07-31 15:03:40 +00001796"S.pack(v1, v2, ...) -> bytes\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00001797\n\
Mark Dickinsonaacfa952010-06-12 15:43:45 +00001798Return a bytes object containing values v1, v2, ... packed according\n\
1799to the format string S.format. See help(struct) for more on format\n\
1800strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001801
1802static PyObject *
1803s_pack(PyObject *self, PyObject *args)
1804{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001805 PyStructObject *soself;
1806 PyObject *result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001808 /* Validate arguments. */
1809 soself = (PyStructObject *)self;
1810 assert(PyStruct_Check(self));
1811 assert(soself->s_codes != NULL);
1812 if (PyTuple_GET_SIZE(args) != soself->s_len)
1813 {
1814 PyErr_Format(StructError,
Petri Lehtinen92c28ca2012-10-29 21:16:57 +02001815 "pack expected %zd items for packing (got %zd)", soself->s_len, PyTuple_GET_SIZE(args));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001816 return NULL;
1817 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001818
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001819 /* Allocate a new string */
1820 result = PyBytes_FromStringAndSize((char *)NULL, soself->s_size);
1821 if (result == NULL)
1822 return NULL;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001823
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001824 /* Call the guts */
1825 if ( s_pack_internal(soself, args, 0, PyBytes_AS_STRING(result)) != 0 ) {
1826 Py_DECREF(result);
1827 return NULL;
1828 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001829
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001830 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001831}
1832
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001833PyDoc_STRVAR(s_pack_into__doc__,
1834"S.pack_into(buffer, offset, v1, v2, ...)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00001835\n\
Mark Dickinsonaacfa952010-06-12 15:43:45 +00001836Pack the values v1, v2, ... according to the format string S.format\n\
1837and write the packed bytes into the writable buffer buf starting at\n\
Mark Dickinsonfdb99f12010-06-12 16:30:53 +00001838offset. Note that the offset is a required argument. See\n\
Mark Dickinsonaacfa952010-06-12 15:43:45 +00001839help(struct) for more on format strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001840
1841static PyObject *
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001842s_pack_into(PyObject *self, PyObject *args)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001843{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001844 PyStructObject *soself;
1845 char *buffer;
1846 Py_ssize_t buffer_len, offset;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001847
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001848 /* Validate arguments. +1 is for the first arg as buffer. */
1849 soself = (PyStructObject *)self;
1850 assert(PyStruct_Check(self));
1851 assert(soself->s_codes != NULL);
1852 if (PyTuple_GET_SIZE(args) != (soself->s_len + 2))
1853 {
Petri Lehtinen92c28ca2012-10-29 21:16:57 +02001854 if (PyTuple_GET_SIZE(args) == 0) {
1855 PyErr_Format(StructError,
1856 "pack_into expected buffer argument");
1857 }
1858 else if (PyTuple_GET_SIZE(args) == 1) {
1859 PyErr_Format(StructError,
1860 "pack_into expected offset argument");
1861 }
1862 else {
1863 PyErr_Format(StructError,
1864 "pack_into expected %zd items for packing (got %zd)",
1865 soself->s_len, (PyTuple_GET_SIZE(args) - 2));
1866 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001867 return NULL;
1868 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001870 /* Extract a writable memory buffer from the first argument */
1871 if ( PyObject_AsWriteBuffer(PyTuple_GET_ITEM(args, 0),
1872 (void**)&buffer, &buffer_len) == -1 ) {
1873 return NULL;
1874 }
1875 assert( buffer_len >= 0 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00001876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001877 /* Extract the offset from the first argument */
1878 offset = PyNumber_AsSsize_t(PyTuple_GET_ITEM(args, 1), PyExc_IndexError);
1879 if (offset == -1 && PyErr_Occurred())
1880 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001882 /* Support negative offsets. */
1883 if (offset < 0)
1884 offset += buffer_len;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001886 /* Check boundaries */
1887 if (offset < 0 || (buffer_len - offset) < soself->s_size) {
1888 PyErr_Format(StructError,
1889 "pack_into requires a buffer of at least %zd bytes",
1890 soself->s_size);
1891 return NULL;
1892 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001894 /* Call the guts */
1895 if ( s_pack_internal(soself, args, 2, buffer + offset) != 0 ) {
1896 return NULL;
1897 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001899 Py_RETURN_NONE;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001900}
1901
1902static PyObject *
1903s_get_format(PyStructObject *self, void *unused)
1904{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001905 Py_INCREF(self->s_format);
1906 return self->s_format;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001907}
1908
1909static PyObject *
1910s_get_size(PyStructObject *self, void *unused)
1911{
Christian Heimes217cfd12007-12-02 14:31:20 +00001912 return PyLong_FromSsize_t(self->s_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001913}
1914
Meador Ingeb14d8c92012-07-23 10:01:29 -05001915PyDoc_STRVAR(s_sizeof__doc__,
1916"S.__sizeof__() -> size of S in memory, in bytes");
1917
1918static PyObject *
Meador Inge90bc2dbc2012-07-28 22:16:39 -05001919s_sizeof(PyStructObject *self, void *unused)
Meador Ingeb14d8c92012-07-23 10:01:29 -05001920{
1921 Py_ssize_t size;
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001922 formatcode *code;
Meador Ingeb14d8c92012-07-23 10:01:29 -05001923
Serhiy Storchakafff61f22013-05-17 10:49:44 +03001924 size = sizeof(PyStructObject) + sizeof(formatcode);
1925 for (code = self->s_codes; code->fmtdef != NULL; code++)
1926 size += sizeof(formatcode);
Meador Ingeb14d8c92012-07-23 10:01:29 -05001927 return PyLong_FromSsize_t(size);
1928}
1929
Thomas Wouters477c8d52006-05-27 19:21:47 +00001930/* List of functions */
1931
1932static struct PyMethodDef s_methods[] = {
Antoine Pitrou9f146812013-04-27 00:20:04 +02001933 {"iter_unpack", s_iter_unpack, METH_O, s_iter_unpack__doc__},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001934 {"pack", s_pack, METH_VARARGS, s_pack__doc__},
1935 {"pack_into", s_pack_into, METH_VARARGS, s_pack_into__doc__},
1936 {"unpack", s_unpack, METH_O, s_unpack__doc__},
1937 {"unpack_from", (PyCFunction)s_unpack_from, METH_VARARGS|METH_KEYWORDS,
1938 s_unpack_from__doc__},
Meador Ingeb14d8c92012-07-23 10:01:29 -05001939 {"__sizeof__", (PyCFunction)s_sizeof, METH_NOARGS, s_sizeof__doc__},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001940 {NULL, NULL} /* sentinel */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001941};
1942
Victor Stinnerda9ec992010-12-28 13:26:42 +00001943PyDoc_STRVAR(s__doc__,
Alexander Belopolsky0bd003a2010-06-12 19:36:28 +00001944"Struct(fmt) --> compiled struct object\n"
1945"\n"
1946"Return a new Struct object which writes and reads binary data according to\n"
1947"the format string fmt. See help(struct) for more on format strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001948
1949#define OFF(x) offsetof(PyStructObject, x)
1950
1951static PyGetSetDef s_getsetlist[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001952 {"format", (getter)s_get_format, (setter)NULL, "struct format string", NULL},
1953 {"size", (getter)s_get_size, (setter)NULL, "struct size in bytes", NULL},
1954 {NULL} /* sentinel */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001955};
1956
1957static
1958PyTypeObject PyStructType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001959 PyVarObject_HEAD_INIT(NULL, 0)
1960 "Struct",
1961 sizeof(PyStructObject),
1962 0,
1963 (destructor)s_dealloc, /* tp_dealloc */
1964 0, /* tp_print */
1965 0, /* tp_getattr */
1966 0, /* tp_setattr */
1967 0, /* tp_reserved */
1968 0, /* tp_repr */
1969 0, /* tp_as_number */
1970 0, /* tp_as_sequence */
1971 0, /* tp_as_mapping */
1972 0, /* tp_hash */
1973 0, /* tp_call */
1974 0, /* tp_str */
1975 PyObject_GenericGetAttr, /* tp_getattro */
1976 PyObject_GenericSetAttr, /* tp_setattro */
1977 0, /* tp_as_buffer */
1978 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1979 s__doc__, /* tp_doc */
1980 0, /* tp_traverse */
1981 0, /* tp_clear */
1982 0, /* tp_richcompare */
1983 offsetof(PyStructObject, weakreflist), /* tp_weaklistoffset */
1984 0, /* tp_iter */
1985 0, /* tp_iternext */
1986 s_methods, /* tp_methods */
1987 NULL, /* tp_members */
1988 s_getsetlist, /* tp_getset */
1989 0, /* tp_base */
1990 0, /* tp_dict */
1991 0, /* tp_descr_get */
1992 0, /* tp_descr_set */
1993 0, /* tp_dictoffset */
1994 s_init, /* tp_init */
1995 PyType_GenericAlloc,/* tp_alloc */
1996 s_new, /* tp_new */
1997 PyObject_Del, /* tp_free */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001998};
1999
Christian Heimesa34706f2008-01-04 03:06:10 +00002000
2001/* ---- Standalone functions ---- */
2002
2003#define MAXCACHE 100
2004static PyObject *cache = NULL;
2005
2006static PyObject *
2007cache_struct(PyObject *fmt)
2008{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002009 PyObject * s_object;
Christian Heimesa34706f2008-01-04 03:06:10 +00002010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002011 if (cache == NULL) {
2012 cache = PyDict_New();
2013 if (cache == NULL)
2014 return NULL;
2015 }
Christian Heimesa34706f2008-01-04 03:06:10 +00002016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002017 s_object = PyDict_GetItem(cache, fmt);
2018 if (s_object != NULL) {
2019 Py_INCREF(s_object);
2020 return s_object;
2021 }
Christian Heimesa34706f2008-01-04 03:06:10 +00002022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002023 s_object = PyObject_CallFunctionObjArgs((PyObject *)(&PyStructType), fmt, NULL);
2024 if (s_object != NULL) {
2025 if (PyDict_Size(cache) >= MAXCACHE)
2026 PyDict_Clear(cache);
2027 /* Attempt to cache the result */
2028 if (PyDict_SetItem(cache, fmt, s_object) == -1)
2029 PyErr_Clear();
2030 }
2031 return s_object;
Christian Heimesa34706f2008-01-04 03:06:10 +00002032}
2033
2034PyDoc_STRVAR(clearcache_doc,
2035"Clear the internal cache.");
2036
2037static PyObject *
2038clearcache(PyObject *self)
2039{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002040 Py_CLEAR(cache);
2041 Py_RETURN_NONE;
Christian Heimesa34706f2008-01-04 03:06:10 +00002042}
2043
2044PyDoc_STRVAR(calcsize_doc,
Mark Dickinsonaacfa952010-06-12 15:43:45 +00002045"calcsize(fmt) -> integer\n\
2046\n\
2047Return size in bytes of the struct described by the format string fmt.");
Christian Heimesa34706f2008-01-04 03:06:10 +00002048
2049static PyObject *
2050calcsize(PyObject *self, PyObject *fmt)
2051{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002052 Py_ssize_t n;
2053 PyObject *s_object = cache_struct(fmt);
2054 if (s_object == NULL)
2055 return NULL;
2056 n = ((PyStructObject *)s_object)->s_size;
2057 Py_DECREF(s_object);
2058 return PyLong_FromSsize_t(n);
Christian Heimesa34706f2008-01-04 03:06:10 +00002059}
2060
2061PyDoc_STRVAR(pack_doc,
Mark Dickinsonaacfa952010-06-12 15:43:45 +00002062"pack(fmt, v1, v2, ...) -> bytes\n\
2063\n\
Mark Dickinsonfdb99f12010-06-12 16:30:53 +00002064Return a bytes object containing the values v1, v2, ... packed according\n\
2065to the format string fmt. See help(struct) for more on format strings.");
Christian Heimesa34706f2008-01-04 03:06:10 +00002066
2067static PyObject *
2068pack(PyObject *self, PyObject *args)
2069{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002070 PyObject *s_object, *fmt, *newargs, *result;
2071 Py_ssize_t n = PyTuple_GET_SIZE(args);
Christian Heimesa34706f2008-01-04 03:06:10 +00002072
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002073 if (n == 0) {
2074 PyErr_SetString(PyExc_TypeError, "missing format argument");
2075 return NULL;
2076 }
2077 fmt = PyTuple_GET_ITEM(args, 0);
2078 newargs = PyTuple_GetSlice(args, 1, n);
2079 if (newargs == NULL)
2080 return NULL;
Christian Heimesa34706f2008-01-04 03:06:10 +00002081
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002082 s_object = cache_struct(fmt);
2083 if (s_object == NULL) {
2084 Py_DECREF(newargs);
2085 return NULL;
2086 }
2087 result = s_pack(s_object, newargs);
2088 Py_DECREF(newargs);
2089 Py_DECREF(s_object);
2090 return result;
Christian Heimesa34706f2008-01-04 03:06:10 +00002091}
2092
2093PyDoc_STRVAR(pack_into_doc,
Mark Dickinsonaacfa952010-06-12 15:43:45 +00002094"pack_into(fmt, buffer, offset, v1, v2, ...)\n\
2095\n\
2096Pack the values v1, v2, ... according to the format string fmt and write\n\
2097the packed bytes into the writable buffer buf starting at offset. Note\n\
Mark Dickinsonfdb99f12010-06-12 16:30:53 +00002098that the offset is a required argument. See help(struct) for more\n\
Mark Dickinsonaacfa952010-06-12 15:43:45 +00002099on format strings.");
Christian Heimesa34706f2008-01-04 03:06:10 +00002100
2101static PyObject *
2102pack_into(PyObject *self, PyObject *args)
2103{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002104 PyObject *s_object, *fmt, *newargs, *result;
2105 Py_ssize_t n = PyTuple_GET_SIZE(args);
Christian Heimesa34706f2008-01-04 03:06:10 +00002106
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002107 if (n == 0) {
2108 PyErr_SetString(PyExc_TypeError, "missing format argument");
2109 return NULL;
2110 }
2111 fmt = PyTuple_GET_ITEM(args, 0);
2112 newargs = PyTuple_GetSlice(args, 1, n);
2113 if (newargs == NULL)
2114 return NULL;
Christian Heimesa34706f2008-01-04 03:06:10 +00002115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002116 s_object = cache_struct(fmt);
2117 if (s_object == NULL) {
2118 Py_DECREF(newargs);
2119 return NULL;
2120 }
2121 result = s_pack_into(s_object, newargs);
2122 Py_DECREF(newargs);
2123 Py_DECREF(s_object);
2124 return result;
Christian Heimesa34706f2008-01-04 03:06:10 +00002125}
2126
2127PyDoc_STRVAR(unpack_doc,
Mark Dickinsonaacfa952010-06-12 15:43:45 +00002128"unpack(fmt, buffer) -> (v1, v2, ...)\n\
2129\n\
2130Return a tuple containing values unpacked according to the format string\n\
2131fmt. Requires len(buffer) == calcsize(fmt). See help(struct) for more\n\
2132on format strings.");
Christian Heimesa34706f2008-01-04 03:06:10 +00002133
2134static PyObject *
2135unpack(PyObject *self, PyObject *args)
2136{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002137 PyObject *s_object, *fmt, *inputstr, *result;
Christian Heimesa34706f2008-01-04 03:06:10 +00002138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002139 if (!PyArg_UnpackTuple(args, "unpack", 2, 2, &fmt, &inputstr))
2140 return NULL;
Christian Heimesa34706f2008-01-04 03:06:10 +00002141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002142 s_object = cache_struct(fmt);
2143 if (s_object == NULL)
2144 return NULL;
2145 result = s_unpack(s_object, inputstr);
2146 Py_DECREF(s_object);
2147 return result;
Christian Heimesa34706f2008-01-04 03:06:10 +00002148}
2149
2150PyDoc_STRVAR(unpack_from_doc,
Mark Dickinsonc6f13962010-06-13 09:17:13 +00002151"unpack_from(fmt, buffer, offset=0) -> (v1, v2, ...)\n\
Mark Dickinsonaacfa952010-06-12 15:43:45 +00002152\n\
2153Return a tuple containing values unpacked according to the format string\n\
2154fmt. Requires len(buffer[offset:]) >= calcsize(fmt). See help(struct)\n\
2155for more on format strings.");
Christian Heimesa34706f2008-01-04 03:06:10 +00002156
2157static PyObject *
2158unpack_from(PyObject *self, PyObject *args, PyObject *kwds)
2159{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002160 PyObject *s_object, *fmt, *newargs, *result;
2161 Py_ssize_t n = PyTuple_GET_SIZE(args);
Christian Heimesa34706f2008-01-04 03:06:10 +00002162
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002163 if (n == 0) {
2164 PyErr_SetString(PyExc_TypeError, "missing format argument");
2165 return NULL;
2166 }
2167 fmt = PyTuple_GET_ITEM(args, 0);
2168 newargs = PyTuple_GetSlice(args, 1, n);
2169 if (newargs == NULL)
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 Py_DECREF(newargs);
2175 return NULL;
2176 }
2177 result = s_unpack_from(s_object, newargs, kwds);
2178 Py_DECREF(newargs);
2179 Py_DECREF(s_object);
2180 return result;
Christian Heimesa34706f2008-01-04 03:06:10 +00002181}
2182
Antoine Pitrou9f146812013-04-27 00:20:04 +02002183PyDoc_STRVAR(iter_unpack_doc,
2184"iter_unpack(fmt, buffer) -> iterator(v1, v2, ...)\n\
2185\n\
2186Return an iterator yielding tuples unpacked from the given bytes\n\
2187source according to the format string, like a repeated invocation of\n\
2188unpack_from(). Requires that the bytes length be a multiple of the\n\
2189format struct size.");
2190
2191static PyObject *
2192iter_unpack(PyObject *self, PyObject *args)
2193{
2194 PyObject *s_object, *fmt, *input, *result;
2195
2196 if (!PyArg_ParseTuple(args, "OO:iter_unpack", &fmt, &input))
2197 return NULL;
2198
2199 s_object = cache_struct(fmt);
2200 if (s_object == NULL)
2201 return NULL;
2202 result = s_iter_unpack(s_object, input);
2203 Py_DECREF(s_object);
2204 return result;
2205}
2206
Christian Heimesa34706f2008-01-04 03:06:10 +00002207static struct PyMethodDef module_functions[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002208 {"_clearcache", (PyCFunction)clearcache, METH_NOARGS, clearcache_doc},
2209 {"calcsize", calcsize, METH_O, calcsize_doc},
Antoine Pitrou9f146812013-04-27 00:20:04 +02002210 {"iter_unpack", iter_unpack, METH_VARARGS, iter_unpack_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002211 {"pack", pack, METH_VARARGS, pack_doc},
2212 {"pack_into", pack_into, METH_VARARGS, pack_into_doc},
2213 {"unpack", unpack, METH_VARARGS, unpack_doc},
2214 {"unpack_from", (PyCFunction)unpack_from,
2215 METH_VARARGS|METH_KEYWORDS, unpack_from_doc},
2216 {NULL, NULL} /* sentinel */
Christian Heimesa34706f2008-01-04 03:06:10 +00002217};
2218
2219
Thomas Wouters477c8d52006-05-27 19:21:47 +00002220/* Module initialization */
2221
Christian Heimesa34706f2008-01-04 03:06:10 +00002222PyDoc_STRVAR(module_doc,
2223"Functions to convert between Python values and C structs.\n\
Benjamin Peterson4ae19462008-07-31 15:03:40 +00002224Python bytes objects are used to hold the data representing the C struct\n\
Mark Dickinson40714af2009-10-08 15:59:20 +00002225and also as format strings (explained below) to describe the layout of data\n\
2226in the C struct.\n\
Christian Heimesa34706f2008-01-04 03:06:10 +00002227\n\
2228The optional first format char indicates byte order, size and alignment:\n\
Mark Dickinson40714af2009-10-08 15:59:20 +00002229 @: native order, size & alignment (default)\n\
2230 =: native order, std. size & alignment\n\
2231 <: little-endian, std. size & alignment\n\
2232 >: big-endian, std. size & alignment\n\
2233 !: same as >\n\
Christian Heimesa34706f2008-01-04 03:06:10 +00002234\n\
2235The remaining chars indicate types of args and must match exactly;\n\
2236these can be preceded by a decimal repeat count:\n\
2237 x: pad byte (no data); c:char; b:signed byte; B:unsigned byte;\n\
Mark Dickinson40714af2009-10-08 15:59:20 +00002238 ?: _Bool (requires C99; if not available, char is used instead)\n\
Christian Heimesa34706f2008-01-04 03:06:10 +00002239 h:short; H:unsigned short; i:int; I:unsigned int;\n\
2240 l:long; L:unsigned long; f:float; d:double.\n\
2241Special cases (preceding decimal count indicates length):\n\
2242 s:string (array of char); p: pascal string (with count byte).\n\
Antoine Pitrou45d9c912011-10-06 15:27:40 +02002243Special cases (only available in native format):\n\
2244 n:ssize_t; N:size_t;\n\
Christian Heimesa34706f2008-01-04 03:06:10 +00002245 P:an integer type that is wide enough to hold a pointer.\n\
2246Special case (not in native mode unless 'long long' in platform C):\n\
2247 q:long long; Q:unsigned long long\n\
2248Whitespace between formats is ignored.\n\
2249\n\
2250The variable struct.error is an exception raised on errors.\n");
2251
Martin v. Löwis1a214512008-06-11 05:26:20 +00002252
2253static struct PyModuleDef _structmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002254 PyModuleDef_HEAD_INIT,
2255 "_struct",
2256 module_doc,
2257 -1,
2258 module_functions,
2259 NULL,
2260 NULL,
2261 NULL,
2262 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002263};
2264
Thomas Wouters477c8d52006-05-27 19:21:47 +00002265PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002266PyInit__struct(void)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002267{
Mark Dickinson06817852010-06-12 09:25:13 +00002268 PyObject *m;
Christian Heimesa34706f2008-01-04 03:06:10 +00002269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002270 m = PyModule_Create(&_structmodule);
2271 if (m == NULL)
2272 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002274 Py_TYPE(&PyStructType) = &PyType_Type;
2275 if (PyType_Ready(&PyStructType) < 0)
2276 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002278 /* Check endian and swap in faster functions */
2279 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002280 formatdef *native = native_table;
2281 formatdef *other, *ptr;
Christian Heimes743e0cd2012-10-17 23:52:17 +02002282#if PY_LITTLE_ENDIAN
2283 other = lilendian_table;
2284#else
2285 other = bigendian_table;
2286#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002287 /* Scan through the native table, find a matching
2288 entry in the endian table and swap in the
2289 native implementations whenever possible
2290 (64-bit platforms may not have "standard" sizes) */
2291 while (native->format != '\0' && other->format != '\0') {
2292 ptr = other;
2293 while (ptr->format != '\0') {
2294 if (ptr->format == native->format) {
2295 /* Match faster when formats are
2296 listed in the same order */
2297 if (ptr == other)
2298 other++;
2299 /* Only use the trick if the
2300 size matches */
2301 if (ptr->size != native->size)
2302 break;
2303 /* Skip float and double, could be
2304 "unknown" float format */
2305 if (ptr->format == 'd' || ptr->format == 'f')
2306 break;
2307 ptr->pack = native->pack;
2308 ptr->unpack = native->unpack;
2309 break;
2310 }
2311 ptr++;
2312 }
2313 native++;
2314 }
2315 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002317 /* Add some symbolic constants to the module */
2318 if (StructError == NULL) {
2319 StructError = PyErr_NewException("struct.error", NULL, NULL);
2320 if (StructError == NULL)
2321 return NULL;
2322 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002324 Py_INCREF(StructError);
2325 PyModule_AddObject(m, "error", StructError);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002327 Py_INCREF((PyObject*)&PyStructType);
2328 PyModule_AddObject(m, "Struct", (PyObject*)&PyStructType);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002330 return m;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002331}