blob: dcdc83ec5ea8086db68ef58261d5183604ae97f9 [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;
Thomas Wouters477c8d52006-05-27 19:21:47 +000029} formatcode;
30
31/* Struct object interface */
32
33typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000034 PyObject_HEAD
35 Py_ssize_t s_size;
36 Py_ssize_t s_len;
37 formatcode *s_codes;
38 PyObject *s_format;
39 PyObject *weakreflist; /* List of weak references */
Thomas Wouters477c8d52006-05-27 19:21:47 +000040} PyStructObject;
41
42
43#define PyStruct_Check(op) PyObject_TypeCheck(op, &PyStructType)
Christian Heimes90aa7642007-12-19 02:45:37 +000044#define PyStruct_CheckExact(op) (Py_TYPE(op) == &PyStructType)
Thomas Wouters477c8d52006-05-27 19:21:47 +000045
46
47/* Exception */
48
49static PyObject *StructError;
50
51
52/* Define various structs to figure out the alignments of types */
53
54
55typedef struct { char c; short x; } st_short;
56typedef struct { char c; int x; } st_int;
57typedef struct { char c; long x; } st_long;
58typedef struct { char c; float x; } st_float;
59typedef struct { char c; double x; } st_double;
60typedef struct { char c; void *x; } st_void_p;
Antoine Pitrou45d9c912011-10-06 15:27:40 +020061typedef struct { char c; size_t x; } st_size_t;
Thomas Wouters477c8d52006-05-27 19:21:47 +000062
63#define SHORT_ALIGN (sizeof(st_short) - sizeof(short))
64#define INT_ALIGN (sizeof(st_int) - sizeof(int))
65#define LONG_ALIGN (sizeof(st_long) - sizeof(long))
66#define FLOAT_ALIGN (sizeof(st_float) - sizeof(float))
67#define DOUBLE_ALIGN (sizeof(st_double) - sizeof(double))
68#define VOID_P_ALIGN (sizeof(st_void_p) - sizeof(void *))
Antoine Pitrou45d9c912011-10-06 15:27:40 +020069#define SIZE_T_ALIGN (sizeof(st_size_t) - sizeof(size_t))
Thomas Wouters477c8d52006-05-27 19:21:47 +000070
71/* We can't support q and Q in native mode unless the compiler does;
72 in std mode, they're 8 bytes on all platforms. */
73#ifdef HAVE_LONG_LONG
74typedef struct { char c; PY_LONG_LONG x; } s_long_long;
75#define LONG_LONG_ALIGN (sizeof(s_long_long) - sizeof(PY_LONG_LONG))
76#endif
77
Thomas Woutersb2137042007-02-01 18:02:27 +000078#ifdef HAVE_C99_BOOL
79#define BOOL_TYPE _Bool
80typedef struct { char c; _Bool x; } s_bool;
81#define BOOL_ALIGN (sizeof(s_bool) - sizeof(BOOL_TYPE))
82#else
83#define BOOL_TYPE char
84#define BOOL_ALIGN 0
85#endif
86
Thomas Wouters477c8d52006-05-27 19:21:47 +000087#define STRINGIFY(x) #x
88
89#ifdef __powerc
90#pragma options align=reset
91#endif
92
Mark Dickinson055a3fb2010-04-03 15:26:31 +000093/* Helper for integer format codes: converts an arbitrary Python object to a
94 PyLongObject if possible, otherwise fails. Caller should decref. */
Thomas Wouters477c8d52006-05-27 19:21:47 +000095
96static PyObject *
97get_pylong(PyObject *v)
98{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000099 assert(v != NULL);
100 if (!PyLong_Check(v)) {
101 /* Not an integer; try to use __index__ to convert. */
102 if (PyIndex_Check(v)) {
103 v = PyNumber_Index(v);
104 if (v == NULL)
105 return NULL;
106 }
107 else {
108 PyErr_SetString(StructError,
109 "required argument is not an integer");
110 return NULL;
111 }
112 }
113 else
114 Py_INCREF(v);
Mark Dickinsonea835e72009-04-19 20:40:33 +0000115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000116 assert(PyLong_Check(v));
117 return v;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000118}
119
Mark Dickinsonea835e72009-04-19 20:40:33 +0000120/* Helper routine to get a C long and raise the appropriate error if it isn't
121 one */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000122
123static int
124get_long(PyObject *v, long *p)
125{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000126 long x;
Mark Dickinsonea835e72009-04-19 20:40:33 +0000127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000128 v = get_pylong(v);
129 if (v == NULL)
130 return -1;
131 assert(PyLong_Check(v));
132 x = PyLong_AsLong(v);
133 Py_DECREF(v);
134 if (x == (long)-1 && PyErr_Occurred()) {
135 if (PyErr_ExceptionMatches(PyExc_OverflowError))
136 PyErr_SetString(StructError,
137 "argument out of range");
138 return -1;
139 }
140 *p = x;
141 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000142}
143
144
145/* Same, but handling unsigned long */
146
147static int
148get_ulong(PyObject *v, unsigned long *p)
149{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000150 unsigned long x;
Mark Dickinsonea835e72009-04-19 20:40:33 +0000151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000152 v = get_pylong(v);
153 if (v == NULL)
154 return -1;
155 assert(PyLong_Check(v));
156 x = PyLong_AsUnsignedLong(v);
157 Py_DECREF(v);
158 if (x == (unsigned long)-1 && PyErr_Occurred()) {
159 if (PyErr_ExceptionMatches(PyExc_OverflowError))
160 PyErr_SetString(StructError,
161 "argument out of range");
162 return -1;
163 }
164 *p = x;
165 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000166}
167
168#ifdef HAVE_LONG_LONG
169
170/* Same, but handling native long long. */
171
172static int
173get_longlong(PyObject *v, PY_LONG_LONG *p)
174{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175 PY_LONG_LONG x;
Mark Dickinson055a3fb2010-04-03 15:26:31 +0000176
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000177 v = get_pylong(v);
178 if (v == NULL)
179 return -1;
180 assert(PyLong_Check(v));
181 x = PyLong_AsLongLong(v);
182 Py_DECREF(v);
183 if (x == (PY_LONG_LONG)-1 && PyErr_Occurred()) {
184 if (PyErr_ExceptionMatches(PyExc_OverflowError))
185 PyErr_SetString(StructError,
186 "argument out of range");
187 return -1;
188 }
189 *p = x;
190 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000191}
192
193/* Same, but handling native unsigned long long. */
194
195static int
196get_ulonglong(PyObject *v, unsigned PY_LONG_LONG *p)
197{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000198 unsigned PY_LONG_LONG x;
Mark Dickinson055a3fb2010-04-03 15:26:31 +0000199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000200 v = get_pylong(v);
201 if (v == NULL)
202 return -1;
203 assert(PyLong_Check(v));
204 x = PyLong_AsUnsignedLongLong(v);
205 Py_DECREF(v);
206 if (x == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred()) {
207 if (PyErr_ExceptionMatches(PyExc_OverflowError))
208 PyErr_SetString(StructError,
209 "argument out of range");
210 return -1;
211 }
212 *p = x;
213 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000214}
215
216#endif
217
Antoine Pitrou45d9c912011-10-06 15:27:40 +0200218/* Same, but handling Py_ssize_t */
219
220static int
221get_ssize_t(PyObject *v, Py_ssize_t *p)
222{
223 Py_ssize_t x;
224
225 v = get_pylong(v);
226 if (v == NULL)
227 return -1;
228 assert(PyLong_Check(v));
229 x = PyLong_AsSsize_t(v);
230 Py_DECREF(v);
231 if (x == (Py_ssize_t)-1 && PyErr_Occurred()) {
232 if (PyErr_ExceptionMatches(PyExc_OverflowError))
233 PyErr_SetString(StructError,
234 "argument out of range");
235 return -1;
236 }
237 *p = x;
238 return 0;
239}
240
241/* Same, but handling size_t */
242
243static int
244get_size_t(PyObject *v, size_t *p)
245{
246 size_t x;
247
248 v = get_pylong(v);
249 if (v == NULL)
250 return -1;
251 assert(PyLong_Check(v));
252 x = PyLong_AsSize_t(v);
253 Py_DECREF(v);
254 if (x == (size_t)-1 && PyErr_Occurred()) {
255 if (PyErr_ExceptionMatches(PyExc_OverflowError))
256 PyErr_SetString(StructError,
257 "argument out of range");
258 return -1;
259 }
260 *p = x;
261 return 0;
262}
263
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000264
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000265#define RANGE_ERROR(x, f, flag, mask) return _range_error(f, flag)
266
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000267
Thomas Wouters477c8d52006-05-27 19:21:47 +0000268/* Floating point helpers */
269
270static PyObject *
271unpack_float(const char *p, /* start of 4-byte string */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000272 int le) /* true for little-endian, false for big-endian */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000273{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000274 double x;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000276 x = _PyFloat_Unpack4((unsigned char *)p, le);
277 if (x == -1.0 && PyErr_Occurred())
278 return NULL;
279 return PyFloat_FromDouble(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000280}
281
282static PyObject *
283unpack_double(const char *p, /* start of 8-byte string */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000284 int le) /* true for little-endian, false for big-endian */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000285{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 double x;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000288 x = _PyFloat_Unpack8((unsigned char *)p, le);
289 if (x == -1.0 && PyErr_Occurred())
290 return NULL;
291 return PyFloat_FromDouble(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000292}
293
294/* Helper to format the range error exceptions */
295static int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000296_range_error(const formatdef *f, int is_unsigned)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000297{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000298 /* ulargest is the largest unsigned value with f->size bytes.
299 * Note that the simpler:
300 * ((size_t)1 << (f->size * 8)) - 1
301 * doesn't work when f->size == sizeof(size_t) because C doesn't
302 * define what happens when a left shift count is >= the number of
303 * bits in the integer being shifted; e.g., on some boxes it doesn't
304 * shift at all when they're equal.
305 */
306 const size_t ulargest = (size_t)-1 >> ((SIZEOF_SIZE_T - f->size)*8);
307 assert(f->size >= 1 && f->size <= SIZEOF_SIZE_T);
308 if (is_unsigned)
309 PyErr_Format(StructError,
310 "'%c' format requires 0 <= number <= %zu",
311 f->format,
312 ulargest);
313 else {
314 const Py_ssize_t largest = (Py_ssize_t)(ulargest >> 1);
315 PyErr_Format(StructError,
316 "'%c' format requires %zd <= number <= %zd",
317 f->format,
318 ~ largest,
319 largest);
320 }
Mark Dickinsonae681df2009-03-21 10:26:31 +0000321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000322 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000323}
324
325
326
327/* A large number of small routines follow, with names of the form
328
329 [bln][up]_TYPE
330
331 [bln] distiguishes among big-endian, little-endian and native.
332 [pu] distiguishes between pack (to struct) and unpack (from struct).
333 TYPE is one of char, byte, ubyte, etc.
334*/
335
336/* Native mode routines. ****************************************************/
337/* NOTE:
338 In all n[up]_<type> routines handling types larger than 1 byte, there is
339 *no* guarantee that the p pointer is properly aligned for each type,
340 therefore memcpy is called. An intermediate variable is used to
341 compensate for big-endian architectures.
342 Normally both the intermediate variable and the memcpy call will be
343 skipped by C optimisation in little-endian architectures (gcc >= 2.91
344 does this). */
345
346static PyObject *
347nu_char(const char *p, const formatdef *f)
348{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000349 return PyBytes_FromStringAndSize(p, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000350}
351
352static PyObject *
353nu_byte(const char *p, const formatdef *f)
354{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000355 return PyLong_FromLong((long) *(signed char *)p);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000356}
357
358static PyObject *
359nu_ubyte(const char *p, const formatdef *f)
360{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000361 return PyLong_FromLong((long) *(unsigned char *)p);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000362}
363
364static PyObject *
365nu_short(const char *p, const formatdef *f)
366{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000367 short x;
368 memcpy((char *)&x, p, sizeof x);
369 return PyLong_FromLong((long)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000370}
371
372static PyObject *
373nu_ushort(const char *p, const formatdef *f)
374{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 unsigned short x;
376 memcpy((char *)&x, p, sizeof x);
377 return PyLong_FromLong((long)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000378}
379
380static PyObject *
381nu_int(const char *p, const formatdef *f)
382{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000383 int x;
384 memcpy((char *)&x, p, sizeof x);
385 return PyLong_FromLong((long)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000386}
387
388static PyObject *
389nu_uint(const char *p, const formatdef *f)
390{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000391 unsigned int x;
392 memcpy((char *)&x, p, sizeof x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000393#if (SIZEOF_LONG > SIZEOF_INT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000394 return PyLong_FromLong((long)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000395#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000396 if (x <= ((unsigned int)LONG_MAX))
397 return PyLong_FromLong((long)x);
398 return PyLong_FromUnsignedLong((unsigned long)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000399#endif
400}
401
402static PyObject *
403nu_long(const char *p, const formatdef *f)
404{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000405 long x;
406 memcpy((char *)&x, p, sizeof x);
407 return PyLong_FromLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000408}
409
410static PyObject *
411nu_ulong(const char *p, const formatdef *f)
412{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000413 unsigned long x;
414 memcpy((char *)&x, p, sizeof x);
415 if (x <= LONG_MAX)
416 return PyLong_FromLong((long)x);
417 return PyLong_FromUnsignedLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000418}
419
Antoine Pitrou45d9c912011-10-06 15:27:40 +0200420static PyObject *
421nu_ssize_t(const char *p, const formatdef *f)
422{
423 Py_ssize_t x;
424 memcpy((char *)&x, p, sizeof x);
425 return PyLong_FromSsize_t(x);
426}
427
428static PyObject *
429nu_size_t(const char *p, const formatdef *f)
430{
431 size_t x;
432 memcpy((char *)&x, p, sizeof x);
433 return PyLong_FromSize_t(x);
434}
435
436
Thomas Wouters477c8d52006-05-27 19:21:47 +0000437/* Native mode doesn't support q or Q unless the platform C supports
438 long long (or, on Windows, __int64). */
439
440#ifdef HAVE_LONG_LONG
441
442static PyObject *
443nu_longlong(const char *p, const formatdef *f)
444{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000445 PY_LONG_LONG x;
446 memcpy((char *)&x, p, sizeof x);
447 if (x >= LONG_MIN && x <= LONG_MAX)
448 return PyLong_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long));
449 return PyLong_FromLongLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000450}
451
452static PyObject *
453nu_ulonglong(const char *p, const formatdef *f)
454{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000455 unsigned PY_LONG_LONG x;
456 memcpy((char *)&x, p, sizeof x);
457 if (x <= LONG_MAX)
458 return PyLong_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long));
459 return PyLong_FromUnsignedLongLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000460}
461
462#endif
463
464static PyObject *
Thomas Woutersb2137042007-02-01 18:02:27 +0000465nu_bool(const char *p, const formatdef *f)
466{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000467 BOOL_TYPE x;
468 memcpy((char *)&x, p, sizeof x);
469 return PyBool_FromLong(x != 0);
Thomas Woutersb2137042007-02-01 18:02:27 +0000470}
471
472
473static PyObject *
Thomas Wouters477c8d52006-05-27 19:21:47 +0000474nu_float(const char *p, const formatdef *f)
475{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 float x;
477 memcpy((char *)&x, p, sizeof x);
478 return PyFloat_FromDouble((double)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000479}
480
481static PyObject *
482nu_double(const char *p, const formatdef *f)
483{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 double x;
485 memcpy((char *)&x, p, sizeof x);
486 return PyFloat_FromDouble(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000487}
488
489static PyObject *
490nu_void_p(const char *p, const formatdef *f)
491{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 void *x;
493 memcpy((char *)&x, p, sizeof x);
494 return PyLong_FromVoidPtr(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000495}
496
497static int
498np_byte(char *p, PyObject *v, const formatdef *f)
499{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 long x;
501 if (get_long(v, &x) < 0)
502 return -1;
503 if (x < -128 || x > 127){
504 PyErr_SetString(StructError,
505 "byte format requires -128 <= number <= 127");
506 return -1;
507 }
508 *p = (char)x;
509 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000510}
511
512static int
513np_ubyte(char *p, PyObject *v, const formatdef *f)
514{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000515 long x;
516 if (get_long(v, &x) < 0)
517 return -1;
518 if (x < 0 || x > 255){
519 PyErr_SetString(StructError,
520 "ubyte format requires 0 <= number <= 255");
521 return -1;
522 }
523 *p = (char)x;
524 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000525}
526
527static int
528np_char(char *p, PyObject *v, const formatdef *f)
529{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 if (!PyBytes_Check(v) || PyBytes_Size(v) != 1) {
531 PyErr_SetString(StructError,
Victor Stinnerda9ec992010-12-28 13:26:42 +0000532 "char format requires a bytes object of length 1");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000533 return -1;
534 }
535 *p = *PyBytes_AsString(v);
536 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000537}
538
539static int
540np_short(char *p, PyObject *v, const formatdef *f)
541{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000542 long x;
543 short y;
544 if (get_long(v, &x) < 0)
545 return -1;
546 if (x < SHRT_MIN || x > SHRT_MAX){
547 PyErr_SetString(StructError,
548 "short format requires " STRINGIFY(SHRT_MIN)
549 " <= number <= " STRINGIFY(SHRT_MAX));
550 return -1;
551 }
552 y = (short)x;
553 memcpy(p, (char *)&y, sizeof y);
554 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000555}
556
557static int
558np_ushort(char *p, PyObject *v, const formatdef *f)
559{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 long x;
561 unsigned short y;
562 if (get_long(v, &x) < 0)
563 return -1;
564 if (x < 0 || x > USHRT_MAX){
565 PyErr_SetString(StructError,
566 "ushort format requires 0 <= number <= " STRINGIFY(USHRT_MAX));
567 return -1;
568 }
569 y = (unsigned short)x;
570 memcpy(p, (char *)&y, sizeof y);
571 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000572}
573
574static int
575np_int(char *p, PyObject *v, const formatdef *f)
576{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577 long x;
578 int y;
579 if (get_long(v, &x) < 0)
580 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000581#if (SIZEOF_LONG > SIZEOF_INT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000582 if ((x < ((long)INT_MIN)) || (x > ((long)INT_MAX)))
583 RANGE_ERROR(x, f, 0, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000584#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000585 y = (int)x;
586 memcpy(p, (char *)&y, sizeof y);
587 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000588}
589
590static int
591np_uint(char *p, PyObject *v, const formatdef *f)
592{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000593 unsigned long x;
594 unsigned int y;
595 if (get_ulong(v, &x) < 0)
596 return -1;
597 y = (unsigned int)x;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000598#if (SIZEOF_LONG > SIZEOF_INT)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000599 if (x > ((unsigned long)UINT_MAX))
600 RANGE_ERROR(y, f, 1, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000601#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000602 memcpy(p, (char *)&y, sizeof y);
603 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000604}
605
606static int
607np_long(char *p, PyObject *v, const formatdef *f)
608{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 long x;
610 if (get_long(v, &x) < 0)
611 return -1;
612 memcpy(p, (char *)&x, sizeof x);
613 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000614}
615
616static int
617np_ulong(char *p, PyObject *v, const formatdef *f)
618{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 unsigned long x;
620 if (get_ulong(v, &x) < 0)
621 return -1;
622 memcpy(p, (char *)&x, sizeof x);
623 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000624}
625
Antoine Pitrou45d9c912011-10-06 15:27:40 +0200626static int
627np_ssize_t(char *p, PyObject *v, const formatdef *f)
628{
629 Py_ssize_t x;
630 if (get_ssize_t(v, &x) < 0)
631 return -1;
632 memcpy(p, (char *)&x, sizeof x);
633 return 0;
634}
635
636static int
637np_size_t(char *p, PyObject *v, const formatdef *f)
638{
639 size_t x;
640 if (get_size_t(v, &x) < 0)
641 return -1;
642 memcpy(p, (char *)&x, sizeof x);
643 return 0;
644}
645
Thomas Wouters477c8d52006-05-27 19:21:47 +0000646#ifdef HAVE_LONG_LONG
647
648static int
649np_longlong(char *p, PyObject *v, const formatdef *f)
650{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000651 PY_LONG_LONG x;
652 if (get_longlong(v, &x) < 0)
653 return -1;
654 memcpy(p, (char *)&x, sizeof x);
655 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000656}
657
658static int
659np_ulonglong(char *p, PyObject *v, const formatdef *f)
660{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 unsigned PY_LONG_LONG x;
662 if (get_ulonglong(v, &x) < 0)
663 return -1;
664 memcpy(p, (char *)&x, sizeof x);
665 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000666}
667#endif
668
Thomas Woutersb2137042007-02-01 18:02:27 +0000669
670static int
671np_bool(char *p, PyObject *v, const formatdef *f)
672{
Benjamin Petersonde73c452010-07-07 18:54:59 +0000673 int y;
674 BOOL_TYPE x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000675 y = PyObject_IsTrue(v);
Benjamin Petersonde73c452010-07-07 18:54:59 +0000676 if (y < 0)
677 return -1;
678 x = y;
679 memcpy(p, (char *)&x, sizeof x);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000680 return 0;
Thomas Woutersb2137042007-02-01 18:02:27 +0000681}
682
Thomas Wouters477c8d52006-05-27 19:21:47 +0000683static int
684np_float(char *p, PyObject *v, const formatdef *f)
685{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000686 float x = (float)PyFloat_AsDouble(v);
687 if (x == -1 && PyErr_Occurred()) {
688 PyErr_SetString(StructError,
689 "required argument is not a float");
690 return -1;
691 }
692 memcpy(p, (char *)&x, sizeof x);
693 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000694}
695
696static int
697np_double(char *p, PyObject *v, const formatdef *f)
698{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000699 double x = PyFloat_AsDouble(v);
700 if (x == -1 && PyErr_Occurred()) {
701 PyErr_SetString(StructError,
702 "required argument is not a float");
703 return -1;
704 }
705 memcpy(p, (char *)&x, sizeof(double));
706 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000707}
708
709static int
710np_void_p(char *p, PyObject *v, const formatdef *f)
711{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000712 void *x;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 v = get_pylong(v);
715 if (v == NULL)
716 return -1;
717 assert(PyLong_Check(v));
718 x = PyLong_AsVoidPtr(v);
719 Py_DECREF(v);
720 if (x == NULL && PyErr_Occurred())
721 return -1;
722 memcpy(p, (char *)&x, sizeof x);
723 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000724}
725
726static formatdef native_table[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000727 {'x', sizeof(char), 0, NULL},
728 {'b', sizeof(char), 0, nu_byte, np_byte},
729 {'B', sizeof(char), 0, nu_ubyte, np_ubyte},
730 {'c', sizeof(char), 0, nu_char, np_char},
731 {'s', sizeof(char), 0, NULL},
732 {'p', sizeof(char), 0, NULL},
733 {'h', sizeof(short), SHORT_ALIGN, nu_short, np_short},
734 {'H', sizeof(short), SHORT_ALIGN, nu_ushort, np_ushort},
735 {'i', sizeof(int), INT_ALIGN, nu_int, np_int},
736 {'I', sizeof(int), INT_ALIGN, nu_uint, np_uint},
737 {'l', sizeof(long), LONG_ALIGN, nu_long, np_long},
738 {'L', sizeof(long), LONG_ALIGN, nu_ulong, np_ulong},
Antoine Pitrou45d9c912011-10-06 15:27:40 +0200739 {'n', sizeof(size_t), SIZE_T_ALIGN, nu_ssize_t, np_ssize_t},
740 {'N', sizeof(size_t), SIZE_T_ALIGN, nu_size_t, np_size_t},
Thomas Wouters477c8d52006-05-27 19:21:47 +0000741#ifdef HAVE_LONG_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000742 {'q', sizeof(PY_LONG_LONG), LONG_LONG_ALIGN, nu_longlong, np_longlong},
743 {'Q', sizeof(PY_LONG_LONG), LONG_LONG_ALIGN, nu_ulonglong,np_ulonglong},
Thomas Wouters477c8d52006-05-27 19:21:47 +0000744#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000745 {'?', sizeof(BOOL_TYPE), BOOL_ALIGN, nu_bool, np_bool},
746 {'f', sizeof(float), FLOAT_ALIGN, nu_float, np_float},
747 {'d', sizeof(double), DOUBLE_ALIGN, nu_double, np_double},
748 {'P', sizeof(void *), VOID_P_ALIGN, nu_void_p, np_void_p},
749 {0}
Thomas Wouters477c8d52006-05-27 19:21:47 +0000750};
751
752/* Big-endian routines. *****************************************************/
753
754static PyObject *
755bu_int(const char *p, const formatdef *f)
756{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000757 long x = 0;
758 Py_ssize_t i = f->size;
759 const unsigned char *bytes = (const unsigned char *)p;
760 do {
761 x = (x<<8) | *bytes++;
762 } while (--i > 0);
763 /* Extend the sign bit. */
764 if (SIZEOF_LONG > f->size)
765 x |= -(x & (1L << ((8 * f->size) - 1)));
766 return PyLong_FromLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000767}
768
769static PyObject *
770bu_uint(const char *p, const formatdef *f)
771{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000772 unsigned long x = 0;
773 Py_ssize_t i = f->size;
774 const unsigned char *bytes = (const unsigned char *)p;
775 do {
776 x = (x<<8) | *bytes++;
777 } while (--i > 0);
778 if (x <= LONG_MAX)
779 return PyLong_FromLong((long)x);
780 return PyLong_FromUnsignedLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000781}
782
783static PyObject *
784bu_longlong(const char *p, const formatdef *f)
785{
786#ifdef HAVE_LONG_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 PY_LONG_LONG x = 0;
788 Py_ssize_t i = f->size;
789 const unsigned char *bytes = (const unsigned char *)p;
790 do {
791 x = (x<<8) | *bytes++;
792 } while (--i > 0);
793 /* Extend the sign bit. */
794 if (SIZEOF_LONG_LONG > f->size)
795 x |= -(x & ((PY_LONG_LONG)1 << ((8 * f->size) - 1)));
796 if (x >= LONG_MIN && x <= LONG_MAX)
797 return PyLong_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long));
798 return PyLong_FromLongLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000799#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000800 return _PyLong_FromByteArray((const unsigned char *)p,
801 8,
802 0, /* little-endian */
803 1 /* signed */);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000804#endif
805}
806
807static PyObject *
808bu_ulonglong(const char *p, const formatdef *f)
809{
810#ifdef HAVE_LONG_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000811 unsigned PY_LONG_LONG x = 0;
812 Py_ssize_t i = f->size;
813 const unsigned char *bytes = (const unsigned char *)p;
814 do {
815 x = (x<<8) | *bytes++;
816 } while (--i > 0);
817 if (x <= LONG_MAX)
818 return PyLong_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long));
819 return PyLong_FromUnsignedLongLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000820#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000821 return _PyLong_FromByteArray((const unsigned char *)p,
822 8,
823 0, /* little-endian */
824 0 /* signed */);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000825#endif
826}
827
828static PyObject *
829bu_float(const char *p, const formatdef *f)
830{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000831 return unpack_float(p, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000832}
833
834static PyObject *
835bu_double(const char *p, const formatdef *f)
836{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000837 return unpack_double(p, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000838}
839
Thomas Woutersb2137042007-02-01 18:02:27 +0000840static PyObject *
841bu_bool(const char *p, const formatdef *f)
842{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000843 char x;
844 memcpy((char *)&x, p, sizeof x);
845 return PyBool_FromLong(x != 0);
Thomas Woutersb2137042007-02-01 18:02:27 +0000846}
847
Thomas Wouters477c8d52006-05-27 19:21:47 +0000848static int
849bp_int(char *p, PyObject *v, const formatdef *f)
850{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000851 long x;
852 Py_ssize_t i;
853 if (get_long(v, &x) < 0)
854 return -1;
855 i = f->size;
856 if (i != SIZEOF_LONG) {
857 if ((i == 2) && (x < -32768 || x > 32767))
858 RANGE_ERROR(x, f, 0, 0xffffL);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000859#if (SIZEOF_LONG != 4)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000860 else if ((i == 4) && (x < -2147483648L || x > 2147483647L))
861 RANGE_ERROR(x, f, 0, 0xffffffffL);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000862#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000863 }
864 do {
865 p[--i] = (char)x;
866 x >>= 8;
867 } while (i > 0);
868 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000869}
870
871static int
872bp_uint(char *p, PyObject *v, const formatdef *f)
873{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000874 unsigned long x;
875 Py_ssize_t i;
876 if (get_ulong(v, &x) < 0)
877 return -1;
878 i = f->size;
879 if (i != SIZEOF_LONG) {
880 unsigned long maxint = 1;
881 maxint <<= (unsigned long)(i * 8);
882 if (x >= maxint)
883 RANGE_ERROR(x, f, 1, maxint - 1);
884 }
885 do {
886 p[--i] = (char)x;
887 x >>= 8;
888 } while (i > 0);
889 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000890}
891
892static int
893bp_longlong(char *p, PyObject *v, const formatdef *f)
894{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000895 int res;
896 v = get_pylong(v);
897 if (v == NULL)
898 return -1;
899 res = _PyLong_AsByteArray((PyLongObject *)v,
900 (unsigned char *)p,
901 8,
902 0, /* little_endian */
903 1 /* signed */);
904 Py_DECREF(v);
905 return res;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000906}
907
908static int
909bp_ulonglong(char *p, PyObject *v, const formatdef *f)
910{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000911 int res;
912 v = get_pylong(v);
913 if (v == NULL)
914 return -1;
915 res = _PyLong_AsByteArray((PyLongObject *)v,
916 (unsigned char *)p,
917 8,
918 0, /* little_endian */
919 0 /* signed */);
920 Py_DECREF(v);
921 return res;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000922}
923
924static int
925bp_float(char *p, PyObject *v, const formatdef *f)
926{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000927 double x = PyFloat_AsDouble(v);
928 if (x == -1 && PyErr_Occurred()) {
929 PyErr_SetString(StructError,
930 "required argument is not a float");
931 return -1;
932 }
933 return _PyFloat_Pack4(x, (unsigned char *)p, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000934}
935
936static int
937bp_double(char *p, PyObject *v, const formatdef *f)
938{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 double x = PyFloat_AsDouble(v);
940 if (x == -1 && PyErr_Occurred()) {
941 PyErr_SetString(StructError,
942 "required argument is not a float");
943 return -1;
944 }
945 return _PyFloat_Pack8(x, (unsigned char *)p, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000946}
947
Thomas Woutersb2137042007-02-01 18:02:27 +0000948static int
949bp_bool(char *p, PyObject *v, const formatdef *f)
950{
Mark Dickinsoneff5d852010-07-18 07:29:02 +0000951 int y;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 y = PyObject_IsTrue(v);
Benjamin Petersonde73c452010-07-07 18:54:59 +0000953 if (y < 0)
954 return -1;
Mark Dickinsoneff5d852010-07-18 07:29:02 +0000955 *p = (char)y;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000956 return 0;
Thomas Woutersb2137042007-02-01 18:02:27 +0000957}
958
Thomas Wouters477c8d52006-05-27 19:21:47 +0000959static formatdef bigendian_table[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 {'x', 1, 0, NULL},
961 {'b', 1, 0, nu_byte, np_byte},
962 {'B', 1, 0, nu_ubyte, np_ubyte},
963 {'c', 1, 0, nu_char, np_char},
964 {'s', 1, 0, NULL},
965 {'p', 1, 0, NULL},
966 {'h', 2, 0, bu_int, bp_int},
967 {'H', 2, 0, bu_uint, bp_uint},
968 {'i', 4, 0, bu_int, bp_int},
969 {'I', 4, 0, bu_uint, bp_uint},
970 {'l', 4, 0, bu_int, bp_int},
971 {'L', 4, 0, bu_uint, bp_uint},
972 {'q', 8, 0, bu_longlong, bp_longlong},
973 {'Q', 8, 0, bu_ulonglong, bp_ulonglong},
974 {'?', 1, 0, bu_bool, bp_bool},
975 {'f', 4, 0, bu_float, bp_float},
976 {'d', 8, 0, bu_double, bp_double},
977 {0}
Thomas Wouters477c8d52006-05-27 19:21:47 +0000978};
979
980/* Little-endian routines. *****************************************************/
981
982static PyObject *
983lu_int(const char *p, const formatdef *f)
984{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000985 long x = 0;
986 Py_ssize_t i = f->size;
987 const unsigned char *bytes = (const unsigned char *)p;
988 do {
989 x = (x<<8) | bytes[--i];
990 } while (i > 0);
991 /* Extend the sign bit. */
992 if (SIZEOF_LONG > f->size)
993 x |= -(x & (1L << ((8 * f->size) - 1)));
994 return PyLong_FromLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000995}
996
997static PyObject *
998lu_uint(const char *p, const formatdef *f)
999{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001000 unsigned long x = 0;
1001 Py_ssize_t i = f->size;
1002 const unsigned char *bytes = (const unsigned char *)p;
1003 do {
1004 x = (x<<8) | bytes[--i];
1005 } while (i > 0);
1006 if (x <= LONG_MAX)
1007 return PyLong_FromLong((long)x);
1008 return PyLong_FromUnsignedLong((long)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001009}
1010
1011static PyObject *
1012lu_longlong(const char *p, const formatdef *f)
1013{
1014#ifdef HAVE_LONG_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 PY_LONG_LONG x = 0;
1016 Py_ssize_t i = f->size;
1017 const unsigned char *bytes = (const unsigned char *)p;
1018 do {
1019 x = (x<<8) | bytes[--i];
1020 } while (i > 0);
1021 /* Extend the sign bit. */
1022 if (SIZEOF_LONG_LONG > f->size)
1023 x |= -(x & ((PY_LONG_LONG)1 << ((8 * f->size) - 1)));
1024 if (x >= LONG_MIN && x <= LONG_MAX)
1025 return PyLong_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long));
1026 return PyLong_FromLongLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001027#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 return _PyLong_FromByteArray((const unsigned char *)p,
1029 8,
1030 1, /* little-endian */
1031 1 /* signed */);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001032#endif
1033}
1034
1035static PyObject *
1036lu_ulonglong(const char *p, const formatdef *f)
1037{
1038#ifdef HAVE_LONG_LONG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001039 unsigned PY_LONG_LONG x = 0;
1040 Py_ssize_t i = f->size;
1041 const unsigned char *bytes = (const unsigned char *)p;
1042 do {
1043 x = (x<<8) | bytes[--i];
1044 } while (i > 0);
1045 if (x <= LONG_MAX)
1046 return PyLong_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long));
1047 return PyLong_FromUnsignedLongLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001048#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049 return _PyLong_FromByteArray((const unsigned char *)p,
1050 8,
1051 1, /* little-endian */
1052 0 /* signed */);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001053#endif
1054}
1055
1056static PyObject *
1057lu_float(const char *p, const formatdef *f)
1058{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001059 return unpack_float(p, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001060}
1061
1062static PyObject *
1063lu_double(const char *p, const formatdef *f)
1064{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001065 return unpack_double(p, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001066}
1067
1068static int
1069lp_int(char *p, PyObject *v, const formatdef *f)
1070{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 long x;
1072 Py_ssize_t i;
1073 if (get_long(v, &x) < 0)
1074 return -1;
1075 i = f->size;
1076 if (i != SIZEOF_LONG) {
1077 if ((i == 2) && (x < -32768 || x > 32767))
1078 RANGE_ERROR(x, f, 0, 0xffffL);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001079#if (SIZEOF_LONG != 4)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001080 else if ((i == 4) && (x < -2147483648L || x > 2147483647L))
1081 RANGE_ERROR(x, f, 0, 0xffffffffL);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001082#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 }
1084 do {
1085 *p++ = (char)x;
1086 x >>= 8;
1087 } while (--i > 0);
1088 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001089}
1090
1091static int
1092lp_uint(char *p, PyObject *v, const formatdef *f)
1093{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001094 unsigned long x;
1095 Py_ssize_t i;
1096 if (get_ulong(v, &x) < 0)
1097 return -1;
1098 i = f->size;
1099 if (i != SIZEOF_LONG) {
1100 unsigned long maxint = 1;
1101 maxint <<= (unsigned long)(i * 8);
1102 if (x >= maxint)
1103 RANGE_ERROR(x, f, 1, maxint - 1);
1104 }
1105 do {
1106 *p++ = (char)x;
1107 x >>= 8;
1108 } while (--i > 0);
1109 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001110}
1111
1112static int
1113lp_longlong(char *p, PyObject *v, const formatdef *f)
1114{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 int res;
1116 v = get_pylong(v);
1117 if (v == NULL)
1118 return -1;
1119 res = _PyLong_AsByteArray((PyLongObject*)v,
1120 (unsigned char *)p,
1121 8,
1122 1, /* little_endian */
1123 1 /* signed */);
1124 Py_DECREF(v);
1125 return res;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001126}
1127
1128static int
1129lp_ulonglong(char *p, PyObject *v, const formatdef *f)
1130{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001131 int res;
1132 v = get_pylong(v);
1133 if (v == NULL)
1134 return -1;
1135 res = _PyLong_AsByteArray((PyLongObject*)v,
1136 (unsigned char *)p,
1137 8,
1138 1, /* little_endian */
1139 0 /* signed */);
1140 Py_DECREF(v);
1141 return res;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001142}
1143
1144static int
1145lp_float(char *p, PyObject *v, const formatdef *f)
1146{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001147 double x = PyFloat_AsDouble(v);
1148 if (x == -1 && PyErr_Occurred()) {
1149 PyErr_SetString(StructError,
1150 "required argument is not a float");
1151 return -1;
1152 }
1153 return _PyFloat_Pack4(x, (unsigned char *)p, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001154}
1155
1156static int
1157lp_double(char *p, PyObject *v, const formatdef *f)
1158{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001159 double x = PyFloat_AsDouble(v);
1160 if (x == -1 && PyErr_Occurred()) {
1161 PyErr_SetString(StructError,
1162 "required argument is not a float");
1163 return -1;
1164 }
1165 return _PyFloat_Pack8(x, (unsigned char *)p, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001166}
1167
1168static formatdef lilendian_table[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001169 {'x', 1, 0, NULL},
1170 {'b', 1, 0, nu_byte, np_byte},
1171 {'B', 1, 0, nu_ubyte, np_ubyte},
1172 {'c', 1, 0, nu_char, np_char},
1173 {'s', 1, 0, NULL},
1174 {'p', 1, 0, NULL},
1175 {'h', 2, 0, lu_int, lp_int},
1176 {'H', 2, 0, lu_uint, lp_uint},
1177 {'i', 4, 0, lu_int, lp_int},
1178 {'I', 4, 0, lu_uint, lp_uint},
1179 {'l', 4, 0, lu_int, lp_int},
1180 {'L', 4, 0, lu_uint, lp_uint},
1181 {'q', 8, 0, lu_longlong, lp_longlong},
1182 {'Q', 8, 0, lu_ulonglong, lp_ulonglong},
1183 {'?', 1, 0, bu_bool, bp_bool}, /* Std rep not endian dep,
1184 but potentially different from native rep -- reuse bx_bool funcs. */
1185 {'f', 4, 0, lu_float, lp_float},
1186 {'d', 8, 0, lu_double, lp_double},
1187 {0}
Thomas Wouters477c8d52006-05-27 19:21:47 +00001188};
1189
1190
1191static const formatdef *
1192whichtable(char **pfmt)
1193{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 const char *fmt = (*pfmt)++; /* May be backed out of later */
1195 switch (*fmt) {
1196 case '<':
1197 return lilendian_table;
1198 case '>':
1199 case '!': /* Network byte order is big-endian */
1200 return bigendian_table;
Ezio Melotti42da6632011-03-15 05:18:48 +02001201 case '=': { /* Host byte order -- different from native in alignment! */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001202 int n = 1;
1203 char *p = (char *) &n;
1204 if (*p == 1)
1205 return lilendian_table;
1206 else
1207 return bigendian_table;
1208 }
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
1251
1252/* calculate the size of a format string */
1253
1254static int
1255prepare_s(PyStructObject *self)
1256{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001257 const formatdef *f;
1258 const formatdef *e;
1259 formatcode *codes;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001261 const char *s;
1262 const char *fmt;
1263 char c;
Mark Dickinsonb72e6862010-06-11 19:50:30 +00001264 Py_ssize_t size, len, num, itemsize;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001265
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001266 fmt = PyBytes_AS_STRING(self->s_format);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001267
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001268 f = whichtable((char **)&fmt);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001270 s = fmt;
1271 size = 0;
1272 len = 0;
1273 while ((c = *s++) != '\0') {
1274 if (isspace(Py_CHARMASK(c)))
1275 continue;
1276 if ('0' <= c && c <= '9') {
1277 num = c - '0';
1278 while ('0' <= (c = *s++) && c <= '9') {
Mark Dickinsonab4096f2010-06-11 16:56:34 +00001279 /* overflow-safe version of
1280 if (num*10 + (c - '0') > PY_SSIZE_T_MAX) { ... } */
1281 if (num >= PY_SSIZE_T_MAX / 10 && (
1282 num > PY_SSIZE_T_MAX / 10 ||
Mark Dickinsonb72e6862010-06-11 19:50:30 +00001283 (c - '0') > PY_SSIZE_T_MAX % 10))
1284 goto overflow;
Mark Dickinsonab4096f2010-06-11 16:56:34 +00001285 num = num*10 + (c - '0');
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001286 }
Alexander Belopolsky177e8532010-06-11 16:04:59 +00001287 if (c == '\0') {
1288 PyErr_SetString(StructError,
1289 "repeat count given without format specifier");
1290 return -1;
1291 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001292 }
1293 else
1294 num = 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001296 e = getentry(c, f);
1297 if (e == NULL)
1298 return -1;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001300 switch (c) {
1301 case 's': /* fall through */
1302 case 'p': len++; break;
1303 case 'x': break;
1304 default: len += num; break;
1305 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001307 itemsize = e->size;
1308 size = align(size, c, e);
Mark Dickinsonb72e6862010-06-11 19:50:30 +00001309 if (size == -1)
1310 goto overflow;
1311
1312 /* if (size + num * itemsize > PY_SSIZE_T_MAX) { ... } */
1313 if (num > (PY_SSIZE_T_MAX - size) / itemsize)
1314 goto overflow;
1315 size += num * itemsize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001316 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001318 /* check for overflow */
1319 if ((len + 1) > (PY_SSIZE_T_MAX / sizeof(formatcode))) {
1320 PyErr_NoMemory();
1321 return -1;
1322 }
Amaury Forgeot d'Arc35c86582008-06-17 21:11:29 +00001323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001324 self->s_size = size;
1325 self->s_len = len;
1326 codes = PyMem_MALLOC((len + 1) * sizeof(formatcode));
1327 if (codes == NULL) {
1328 PyErr_NoMemory();
1329 return -1;
1330 }
Mark Dickinsoncf28b952010-07-29 21:41:59 +00001331 /* Free any s_codes value left over from a previous initialization. */
1332 if (self->s_codes != NULL)
1333 PyMem_FREE(self->s_codes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001334 self->s_codes = codes;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001336 s = fmt;
1337 size = 0;
1338 while ((c = *s++) != '\0') {
1339 if (isspace(Py_CHARMASK(c)))
1340 continue;
1341 if ('0' <= c && c <= '9') {
1342 num = c - '0';
1343 while ('0' <= (c = *s++) && c <= '9')
1344 num = num*10 + (c - '0');
1345 if (c == '\0')
1346 break;
1347 }
1348 else
1349 num = 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001351 e = getentry(c, f);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001353 size = align(size, c, e);
1354 if (c == 's' || c == 'p') {
1355 codes->offset = size;
1356 codes->size = num;
1357 codes->fmtdef = e;
1358 codes++;
1359 size += num;
1360 } else if (c == 'x') {
1361 size += num;
1362 } else {
1363 while (--num >= 0) {
1364 codes->offset = size;
1365 codes->size = e->size;
1366 codes->fmtdef = e;
1367 codes++;
1368 size += e->size;
1369 }
1370 }
1371 }
1372 codes->fmtdef = NULL;
1373 codes->offset = size;
1374 codes->size = 0;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001376 return 0;
Mark Dickinsonb72e6862010-06-11 19:50:30 +00001377
1378 overflow:
1379 PyErr_SetString(StructError,
1380 "total struct size too long");
1381 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001382}
1383
1384static PyObject *
1385s_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1386{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001387 PyObject *self;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001389 assert(type != NULL && type->tp_alloc != NULL);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001391 self = type->tp_alloc(type, 0);
1392 if (self != NULL) {
1393 PyStructObject *s = (PyStructObject*)self;
1394 Py_INCREF(Py_None);
1395 s->s_format = Py_None;
1396 s->s_codes = NULL;
1397 s->s_size = -1;
1398 s->s_len = -1;
1399 }
1400 return self;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001401}
1402
1403static int
1404s_init(PyObject *self, PyObject *args, PyObject *kwds)
1405{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001406 PyStructObject *soself = (PyStructObject *)self;
1407 PyObject *o_format = NULL;
1408 int ret = 0;
1409 static char *kwlist[] = {"format", 0};
Thomas Wouters477c8d52006-05-27 19:21:47 +00001410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001411 assert(PyStruct_Check(self));
Thomas Wouters477c8d52006-05-27 19:21:47 +00001412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001413 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:Struct", kwlist,
1414 &o_format))
1415 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001417 if (PyUnicode_Check(o_format)) {
1418 o_format = PyUnicode_AsASCIIString(o_format);
1419 if (o_format == NULL)
1420 return -1;
1421 }
1422 /* XXX support buffer interface, too */
1423 else {
1424 Py_INCREF(o_format);
1425 }
Christian Heimesa34706f2008-01-04 03:06:10 +00001426
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001427 if (!PyBytes_Check(o_format)) {
1428 Py_DECREF(o_format);
1429 PyErr_Format(PyExc_TypeError,
Victor Stinnerda9ec992010-12-28 13:26:42 +00001430 "Struct() argument 1 must be a bytes object, not %.200s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001431 Py_TYPE(o_format)->tp_name);
1432 return -1;
1433 }
Christian Heimesa34706f2008-01-04 03:06:10 +00001434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001435 Py_CLEAR(soself->s_format);
1436 soself->s_format = o_format;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001437
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001438 ret = prepare_s(soself);
1439 return ret;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001440}
1441
1442static void
1443s_dealloc(PyStructObject *s)
1444{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001445 if (s->weakreflist != NULL)
1446 PyObject_ClearWeakRefs((PyObject *)s);
1447 if (s->s_codes != NULL) {
1448 PyMem_FREE(s->s_codes);
1449 }
1450 Py_XDECREF(s->s_format);
1451 Py_TYPE(s)->tp_free((PyObject *)s);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001452}
1453
1454static PyObject *
1455s_unpack_internal(PyStructObject *soself, char *startfrom) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001456 formatcode *code;
1457 Py_ssize_t i = 0;
1458 PyObject *result = PyTuple_New(soself->s_len);
1459 if (result == NULL)
1460 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001462 for (code = soself->s_codes; code->fmtdef != NULL; code++) {
1463 PyObject *v;
1464 const formatdef *e = code->fmtdef;
1465 const char *res = startfrom + code->offset;
1466 if (e->format == 's') {
1467 v = PyBytes_FromStringAndSize(res, code->size);
1468 } else if (e->format == 'p') {
1469 Py_ssize_t n = *(unsigned char*)res;
1470 if (n >= code->size)
1471 n = code->size - 1;
1472 v = PyBytes_FromStringAndSize(res + 1, n);
1473 } else {
1474 v = e->unpack(res, e);
1475 }
1476 if (v == NULL)
1477 goto fail;
1478 PyTuple_SET_ITEM(result, i++, v);
1479 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001481 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001482fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001483 Py_DECREF(result);
1484 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001485}
1486
1487
1488PyDoc_STRVAR(s_unpack__doc__,
Guido van Rossum913dd0b2007-04-13 03:33:53 +00001489"S.unpack(buffer) -> (v1, v2, ...)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00001490\n\
Mark Dickinsonaacfa952010-06-12 15:43:45 +00001491Return a tuple containing values unpacked according to the format\n\
1492string S.format. Requires len(buffer) == S.size. See help(struct)\n\
1493for more on format strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001494
1495static PyObject *
Guido van Rossum98297ee2007-11-06 21:34:58 +00001496s_unpack(PyObject *self, PyObject *input)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001497{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001498 Py_buffer vbuf;
1499 PyObject *result;
1500 PyStructObject *soself = (PyStructObject *)self;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001502 assert(PyStruct_Check(self));
1503 assert(soself->s_codes != NULL);
1504 if (PyObject_GetBuffer(input, &vbuf, PyBUF_SIMPLE) < 0)
1505 return NULL;
1506 if (vbuf.len != soself->s_size) {
1507 PyErr_Format(StructError,
Victor Stinnerda9ec992010-12-28 13:26:42 +00001508 "unpack requires a bytes object of length %zd",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001509 soself->s_size);
1510 PyBuffer_Release(&vbuf);
1511 return NULL;
1512 }
1513 result = s_unpack_internal(soself, vbuf.buf);
1514 PyBuffer_Release(&vbuf);
1515 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001516}
1517
1518PyDoc_STRVAR(s_unpack_from__doc__,
Mark Dickinsonc6f13962010-06-13 09:17:13 +00001519"S.unpack_from(buffer, offset=0) -> (v1, v2, ...)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00001520\n\
Mark Dickinsonaacfa952010-06-12 15:43:45 +00001521Return a tuple containing values unpacked according to the format\n\
1522string S.format. Requires len(buffer[offset:]) >= S.size. See\n\
1523help(struct) for more on format strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001524
1525static PyObject *
1526s_unpack_from(PyObject *self, PyObject *args, PyObject *kwds)
1527{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001528 static char *kwlist[] = {"buffer", "offset", 0};
Guido van Rossum98297ee2007-11-06 21:34:58 +00001529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001530 PyObject *input;
1531 Py_ssize_t offset = 0;
1532 Py_buffer vbuf;
1533 PyObject *result;
1534 PyStructObject *soself = (PyStructObject *)self;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001536 assert(PyStruct_Check(self));
1537 assert(soself->s_codes != NULL);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001539 if (!PyArg_ParseTupleAndKeywords(args, kwds,
1540 "O|n:unpack_from", kwlist,
1541 &input, &offset))
1542 return NULL;
1543 if (PyObject_GetBuffer(input, &vbuf, PyBUF_SIMPLE) < 0)
1544 return NULL;
1545 if (offset < 0)
1546 offset += vbuf.len;
1547 if (offset < 0 || vbuf.len - offset < soself->s_size) {
1548 PyErr_Format(StructError,
1549 "unpack_from requires a buffer of at least %zd bytes",
1550 soself->s_size);
1551 PyBuffer_Release(&vbuf);
1552 return NULL;
1553 }
1554 result = s_unpack_internal(soself, (char*)vbuf.buf + offset);
1555 PyBuffer_Release(&vbuf);
1556 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001557}
1558
1559
1560/*
1561 * Guts of the pack function.
1562 *
1563 * Takes a struct object, a tuple of arguments, and offset in that tuple of
1564 * argument for where to start processing the arguments for packing, and a
1565 * character buffer for writing the packed string. The caller must insure
1566 * that the buffer may contain the required length for packing the arguments.
1567 * 0 is returned on success, 1 is returned if there is an error.
1568 *
1569 */
1570static int
1571s_pack_internal(PyStructObject *soself, PyObject *args, int offset, char* buf)
1572{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001573 formatcode *code;
1574 /* XXX(nnorwitz): why does i need to be a local? can we use
1575 the offset parameter or do we need the wider width? */
1576 Py_ssize_t i;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001578 memset(buf, '\0', soself->s_size);
1579 i = offset;
1580 for (code = soself->s_codes; code->fmtdef != NULL; code++) {
1581 Py_ssize_t n;
1582 PyObject *v = PyTuple_GET_ITEM(args, i++);
1583 const formatdef *e = code->fmtdef;
1584 char *res = buf + code->offset;
1585 if (e->format == 's') {
1586 int isstring;
1587 void *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001588 isstring = PyBytes_Check(v);
1589 if (!isstring && !PyByteArray_Check(v)) {
1590 PyErr_SetString(StructError,
Victor Stinnerda9ec992010-12-28 13:26:42 +00001591 "argument for 's' must be a bytes object");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001592 return -1;
1593 }
1594 if (isstring) {
1595 n = PyBytes_GET_SIZE(v);
1596 p = PyBytes_AS_STRING(v);
1597 }
1598 else {
1599 n = PyByteArray_GET_SIZE(v);
1600 p = PyByteArray_AS_STRING(v);
1601 }
1602 if (n > code->size)
1603 n = code->size;
1604 if (n > 0)
1605 memcpy(res, p, n);
1606 } else if (e->format == 'p') {
1607 int isstring;
1608 void *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001609 isstring = PyBytes_Check(v);
1610 if (!isstring && !PyByteArray_Check(v)) {
1611 PyErr_SetString(StructError,
Victor Stinnerda9ec992010-12-28 13:26:42 +00001612 "argument for 'p' must be a bytes object");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001613 return -1;
1614 }
1615 if (isstring) {
1616 n = PyBytes_GET_SIZE(v);
1617 p = PyBytes_AS_STRING(v);
1618 }
1619 else {
1620 n = PyByteArray_GET_SIZE(v);
1621 p = PyByteArray_AS_STRING(v);
1622 }
1623 if (n > (code->size - 1))
1624 n = code->size - 1;
1625 if (n > 0)
1626 memcpy(res + 1, p, n);
1627 if (n > 255)
1628 n = 255;
1629 *res = Py_SAFE_DOWNCAST(n, Py_ssize_t, unsigned char);
1630 } else {
1631 if (e->pack(res, v, e) < 0) {
1632 if (PyLong_Check(v) && PyErr_ExceptionMatches(PyExc_OverflowError))
1633 PyErr_SetString(StructError,
1634 "long too large to convert to int");
1635 return -1;
1636 }
1637 }
1638 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001640 /* Success */
1641 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001642}
1643
1644
1645PyDoc_STRVAR(s_pack__doc__,
Benjamin Peterson4ae19462008-07-31 15:03:40 +00001646"S.pack(v1, v2, ...) -> bytes\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00001647\n\
Mark Dickinsonaacfa952010-06-12 15:43:45 +00001648Return a bytes object containing values v1, v2, ... packed according\n\
1649to the format string S.format. See help(struct) for more on format\n\
1650strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001651
1652static PyObject *
1653s_pack(PyObject *self, PyObject *args)
1654{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001655 PyStructObject *soself;
1656 PyObject *result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001657
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001658 /* Validate arguments. */
1659 soself = (PyStructObject *)self;
1660 assert(PyStruct_Check(self));
1661 assert(soself->s_codes != NULL);
1662 if (PyTuple_GET_SIZE(args) != soself->s_len)
1663 {
1664 PyErr_Format(StructError,
1665 "pack requires exactly %zd arguments", soself->s_len);
1666 return NULL;
1667 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001668
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001669 /* Allocate a new string */
1670 result = PyBytes_FromStringAndSize((char *)NULL, soself->s_size);
1671 if (result == NULL)
1672 return NULL;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001673
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001674 /* Call the guts */
1675 if ( s_pack_internal(soself, args, 0, PyBytes_AS_STRING(result)) != 0 ) {
1676 Py_DECREF(result);
1677 return NULL;
1678 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001679
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001680 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001681}
1682
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001683PyDoc_STRVAR(s_pack_into__doc__,
1684"S.pack_into(buffer, offset, v1, v2, ...)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00001685\n\
Mark Dickinsonaacfa952010-06-12 15:43:45 +00001686Pack the values v1, v2, ... according to the format string S.format\n\
1687and write the packed bytes into the writable buffer buf starting at\n\
Mark Dickinsonfdb99f12010-06-12 16:30:53 +00001688offset. Note that the offset is a required argument. See\n\
Mark Dickinsonaacfa952010-06-12 15:43:45 +00001689help(struct) for more on format strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001690
1691static PyObject *
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001692s_pack_into(PyObject *self, PyObject *args)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001693{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001694 PyStructObject *soself;
1695 char *buffer;
1696 Py_ssize_t buffer_len, offset;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001697
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001698 /* Validate arguments. +1 is for the first arg as buffer. */
1699 soself = (PyStructObject *)self;
1700 assert(PyStruct_Check(self));
1701 assert(soself->s_codes != NULL);
1702 if (PyTuple_GET_SIZE(args) != (soself->s_len + 2))
1703 {
1704 PyErr_Format(StructError,
1705 "pack_into requires exactly %zd arguments",
1706 (soself->s_len + 2));
1707 return NULL;
1708 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001709
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001710 /* Extract a writable memory buffer from the first argument */
1711 if ( PyObject_AsWriteBuffer(PyTuple_GET_ITEM(args, 0),
1712 (void**)&buffer, &buffer_len) == -1 ) {
1713 return NULL;
1714 }
1715 assert( buffer_len >= 0 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00001716
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001717 /* Extract the offset from the first argument */
1718 offset = PyNumber_AsSsize_t(PyTuple_GET_ITEM(args, 1), PyExc_IndexError);
1719 if (offset == -1 && PyErr_Occurred())
1720 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001721
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001722 /* Support negative offsets. */
1723 if (offset < 0)
1724 offset += buffer_len;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001725
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001726 /* Check boundaries */
1727 if (offset < 0 || (buffer_len - offset) < soself->s_size) {
1728 PyErr_Format(StructError,
1729 "pack_into requires a buffer of at least %zd bytes",
1730 soself->s_size);
1731 return NULL;
1732 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001734 /* Call the guts */
1735 if ( s_pack_internal(soself, args, 2, buffer + offset) != 0 ) {
1736 return NULL;
1737 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001739 Py_RETURN_NONE;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001740}
1741
1742static PyObject *
1743s_get_format(PyStructObject *self, void *unused)
1744{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001745 Py_INCREF(self->s_format);
1746 return self->s_format;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001747}
1748
1749static PyObject *
1750s_get_size(PyStructObject *self, void *unused)
1751{
Christian Heimes217cfd12007-12-02 14:31:20 +00001752 return PyLong_FromSsize_t(self->s_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001753}
1754
1755/* List of functions */
1756
1757static struct PyMethodDef s_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001758 {"pack", s_pack, METH_VARARGS, s_pack__doc__},
1759 {"pack_into", s_pack_into, METH_VARARGS, s_pack_into__doc__},
1760 {"unpack", s_unpack, METH_O, s_unpack__doc__},
1761 {"unpack_from", (PyCFunction)s_unpack_from, METH_VARARGS|METH_KEYWORDS,
1762 s_unpack_from__doc__},
1763 {NULL, NULL} /* sentinel */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001764};
1765
Victor Stinnerda9ec992010-12-28 13:26:42 +00001766PyDoc_STRVAR(s__doc__,
Alexander Belopolsky0bd003a2010-06-12 19:36:28 +00001767"Struct(fmt) --> compiled struct object\n"
1768"\n"
1769"Return a new Struct object which writes and reads binary data according to\n"
1770"the format string fmt. See help(struct) for more on format strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001771
1772#define OFF(x) offsetof(PyStructObject, x)
1773
1774static PyGetSetDef s_getsetlist[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001775 {"format", (getter)s_get_format, (setter)NULL, "struct format string", NULL},
1776 {"size", (getter)s_get_size, (setter)NULL, "struct size in bytes", NULL},
1777 {NULL} /* sentinel */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001778};
1779
1780static
1781PyTypeObject PyStructType = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001782 PyVarObject_HEAD_INIT(NULL, 0)
1783 "Struct",
1784 sizeof(PyStructObject),
1785 0,
1786 (destructor)s_dealloc, /* tp_dealloc */
1787 0, /* tp_print */
1788 0, /* tp_getattr */
1789 0, /* tp_setattr */
1790 0, /* tp_reserved */
1791 0, /* tp_repr */
1792 0, /* tp_as_number */
1793 0, /* tp_as_sequence */
1794 0, /* tp_as_mapping */
1795 0, /* tp_hash */
1796 0, /* tp_call */
1797 0, /* tp_str */
1798 PyObject_GenericGetAttr, /* tp_getattro */
1799 PyObject_GenericSetAttr, /* tp_setattro */
1800 0, /* tp_as_buffer */
1801 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
1802 s__doc__, /* tp_doc */
1803 0, /* tp_traverse */
1804 0, /* tp_clear */
1805 0, /* tp_richcompare */
1806 offsetof(PyStructObject, weakreflist), /* tp_weaklistoffset */
1807 0, /* tp_iter */
1808 0, /* tp_iternext */
1809 s_methods, /* tp_methods */
1810 NULL, /* tp_members */
1811 s_getsetlist, /* tp_getset */
1812 0, /* tp_base */
1813 0, /* tp_dict */
1814 0, /* tp_descr_get */
1815 0, /* tp_descr_set */
1816 0, /* tp_dictoffset */
1817 s_init, /* tp_init */
1818 PyType_GenericAlloc,/* tp_alloc */
1819 s_new, /* tp_new */
1820 PyObject_Del, /* tp_free */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001821};
1822
Christian Heimesa34706f2008-01-04 03:06:10 +00001823
1824/* ---- Standalone functions ---- */
1825
1826#define MAXCACHE 100
1827static PyObject *cache = NULL;
1828
1829static PyObject *
1830cache_struct(PyObject *fmt)
1831{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001832 PyObject * s_object;
Christian Heimesa34706f2008-01-04 03:06:10 +00001833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001834 if (cache == NULL) {
1835 cache = PyDict_New();
1836 if (cache == NULL)
1837 return NULL;
1838 }
Christian Heimesa34706f2008-01-04 03:06:10 +00001839
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001840 s_object = PyDict_GetItem(cache, fmt);
1841 if (s_object != NULL) {
1842 Py_INCREF(s_object);
1843 return s_object;
1844 }
Christian Heimesa34706f2008-01-04 03:06:10 +00001845
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001846 s_object = PyObject_CallFunctionObjArgs((PyObject *)(&PyStructType), fmt, NULL);
1847 if (s_object != NULL) {
1848 if (PyDict_Size(cache) >= MAXCACHE)
1849 PyDict_Clear(cache);
1850 /* Attempt to cache the result */
1851 if (PyDict_SetItem(cache, fmt, s_object) == -1)
1852 PyErr_Clear();
1853 }
1854 return s_object;
Christian Heimesa34706f2008-01-04 03:06:10 +00001855}
1856
1857PyDoc_STRVAR(clearcache_doc,
1858"Clear the internal cache.");
1859
1860static PyObject *
1861clearcache(PyObject *self)
1862{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001863 Py_CLEAR(cache);
1864 Py_RETURN_NONE;
Christian Heimesa34706f2008-01-04 03:06:10 +00001865}
1866
1867PyDoc_STRVAR(calcsize_doc,
Mark Dickinsonaacfa952010-06-12 15:43:45 +00001868"calcsize(fmt) -> integer\n\
1869\n\
1870Return size in bytes of the struct described by the format string fmt.");
Christian Heimesa34706f2008-01-04 03:06:10 +00001871
1872static PyObject *
1873calcsize(PyObject *self, PyObject *fmt)
1874{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001875 Py_ssize_t n;
1876 PyObject *s_object = cache_struct(fmt);
1877 if (s_object == NULL)
1878 return NULL;
1879 n = ((PyStructObject *)s_object)->s_size;
1880 Py_DECREF(s_object);
1881 return PyLong_FromSsize_t(n);
Christian Heimesa34706f2008-01-04 03:06:10 +00001882}
1883
1884PyDoc_STRVAR(pack_doc,
Mark Dickinsonaacfa952010-06-12 15:43:45 +00001885"pack(fmt, v1, v2, ...) -> bytes\n\
1886\n\
Mark Dickinsonfdb99f12010-06-12 16:30:53 +00001887Return a bytes object containing the values v1, v2, ... packed according\n\
1888to the format string fmt. See help(struct) for more on format strings.");
Christian Heimesa34706f2008-01-04 03:06:10 +00001889
1890static PyObject *
1891pack(PyObject *self, PyObject *args)
1892{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001893 PyObject *s_object, *fmt, *newargs, *result;
1894 Py_ssize_t n = PyTuple_GET_SIZE(args);
Christian Heimesa34706f2008-01-04 03:06:10 +00001895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001896 if (n == 0) {
1897 PyErr_SetString(PyExc_TypeError, "missing format argument");
1898 return NULL;
1899 }
1900 fmt = PyTuple_GET_ITEM(args, 0);
1901 newargs = PyTuple_GetSlice(args, 1, n);
1902 if (newargs == NULL)
1903 return NULL;
Christian Heimesa34706f2008-01-04 03:06:10 +00001904
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001905 s_object = cache_struct(fmt);
1906 if (s_object == NULL) {
1907 Py_DECREF(newargs);
1908 return NULL;
1909 }
1910 result = s_pack(s_object, newargs);
1911 Py_DECREF(newargs);
1912 Py_DECREF(s_object);
1913 return result;
Christian Heimesa34706f2008-01-04 03:06:10 +00001914}
1915
1916PyDoc_STRVAR(pack_into_doc,
Mark Dickinsonaacfa952010-06-12 15:43:45 +00001917"pack_into(fmt, buffer, offset, v1, v2, ...)\n\
1918\n\
1919Pack the values v1, v2, ... according to the format string fmt and write\n\
1920the packed bytes into the writable buffer buf starting at offset. Note\n\
Mark Dickinsonfdb99f12010-06-12 16:30:53 +00001921that the offset is a required argument. See help(struct) for more\n\
Mark Dickinsonaacfa952010-06-12 15:43:45 +00001922on format strings.");
Christian Heimesa34706f2008-01-04 03:06:10 +00001923
1924static PyObject *
1925pack_into(PyObject *self, PyObject *args)
1926{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001927 PyObject *s_object, *fmt, *newargs, *result;
1928 Py_ssize_t n = PyTuple_GET_SIZE(args);
Christian Heimesa34706f2008-01-04 03:06:10 +00001929
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001930 if (n == 0) {
1931 PyErr_SetString(PyExc_TypeError, "missing format argument");
1932 return NULL;
1933 }
1934 fmt = PyTuple_GET_ITEM(args, 0);
1935 newargs = PyTuple_GetSlice(args, 1, n);
1936 if (newargs == NULL)
1937 return NULL;
Christian Heimesa34706f2008-01-04 03:06:10 +00001938
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001939 s_object = cache_struct(fmt);
1940 if (s_object == NULL) {
1941 Py_DECREF(newargs);
1942 return NULL;
1943 }
1944 result = s_pack_into(s_object, newargs);
1945 Py_DECREF(newargs);
1946 Py_DECREF(s_object);
1947 return result;
Christian Heimesa34706f2008-01-04 03:06:10 +00001948}
1949
1950PyDoc_STRVAR(unpack_doc,
Mark Dickinsonaacfa952010-06-12 15:43:45 +00001951"unpack(fmt, buffer) -> (v1, v2, ...)\n\
1952\n\
1953Return a tuple containing values unpacked according to the format string\n\
1954fmt. Requires len(buffer) == calcsize(fmt). See help(struct) for more\n\
1955on format strings.");
Christian Heimesa34706f2008-01-04 03:06:10 +00001956
1957static PyObject *
1958unpack(PyObject *self, PyObject *args)
1959{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001960 PyObject *s_object, *fmt, *inputstr, *result;
Christian Heimesa34706f2008-01-04 03:06:10 +00001961
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001962 if (!PyArg_UnpackTuple(args, "unpack", 2, 2, &fmt, &inputstr))
1963 return NULL;
Christian Heimesa34706f2008-01-04 03:06:10 +00001964
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001965 s_object = cache_struct(fmt);
1966 if (s_object == NULL)
1967 return NULL;
1968 result = s_unpack(s_object, inputstr);
1969 Py_DECREF(s_object);
1970 return result;
Christian Heimesa34706f2008-01-04 03:06:10 +00001971}
1972
1973PyDoc_STRVAR(unpack_from_doc,
Mark Dickinsonc6f13962010-06-13 09:17:13 +00001974"unpack_from(fmt, buffer, offset=0) -> (v1, v2, ...)\n\
Mark Dickinsonaacfa952010-06-12 15:43:45 +00001975\n\
1976Return a tuple containing values unpacked according to the format string\n\
1977fmt. Requires len(buffer[offset:]) >= calcsize(fmt). See help(struct)\n\
1978for more on format strings.");
Christian Heimesa34706f2008-01-04 03:06:10 +00001979
1980static PyObject *
1981unpack_from(PyObject *self, PyObject *args, PyObject *kwds)
1982{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001983 PyObject *s_object, *fmt, *newargs, *result;
1984 Py_ssize_t n = PyTuple_GET_SIZE(args);
Christian Heimesa34706f2008-01-04 03:06:10 +00001985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001986 if (n == 0) {
1987 PyErr_SetString(PyExc_TypeError, "missing format argument");
1988 return NULL;
1989 }
1990 fmt = PyTuple_GET_ITEM(args, 0);
1991 newargs = PyTuple_GetSlice(args, 1, n);
1992 if (newargs == NULL)
1993 return NULL;
Christian Heimesa34706f2008-01-04 03:06:10 +00001994
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001995 s_object = cache_struct(fmt);
1996 if (s_object == NULL) {
1997 Py_DECREF(newargs);
1998 return NULL;
1999 }
2000 result = s_unpack_from(s_object, newargs, kwds);
2001 Py_DECREF(newargs);
2002 Py_DECREF(s_object);
2003 return result;
Christian Heimesa34706f2008-01-04 03:06:10 +00002004}
2005
2006static struct PyMethodDef module_functions[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002007 {"_clearcache", (PyCFunction)clearcache, METH_NOARGS, clearcache_doc},
2008 {"calcsize", calcsize, METH_O, calcsize_doc},
2009 {"pack", pack, METH_VARARGS, pack_doc},
2010 {"pack_into", pack_into, METH_VARARGS, pack_into_doc},
2011 {"unpack", unpack, METH_VARARGS, unpack_doc},
2012 {"unpack_from", (PyCFunction)unpack_from,
2013 METH_VARARGS|METH_KEYWORDS, unpack_from_doc},
2014 {NULL, NULL} /* sentinel */
Christian Heimesa34706f2008-01-04 03:06:10 +00002015};
2016
2017
Thomas Wouters477c8d52006-05-27 19:21:47 +00002018/* Module initialization */
2019
Christian Heimesa34706f2008-01-04 03:06:10 +00002020PyDoc_STRVAR(module_doc,
2021"Functions to convert between Python values and C structs.\n\
Benjamin Peterson4ae19462008-07-31 15:03:40 +00002022Python bytes objects are used to hold the data representing the C struct\n\
Mark Dickinson40714af2009-10-08 15:59:20 +00002023and also as format strings (explained below) to describe the layout of data\n\
2024in the C struct.\n\
Christian Heimesa34706f2008-01-04 03:06:10 +00002025\n\
2026The optional first format char indicates byte order, size and alignment:\n\
Mark Dickinson40714af2009-10-08 15:59:20 +00002027 @: native order, size & alignment (default)\n\
2028 =: native order, std. size & alignment\n\
2029 <: little-endian, std. size & alignment\n\
2030 >: big-endian, std. size & alignment\n\
2031 !: same as >\n\
Christian Heimesa34706f2008-01-04 03:06:10 +00002032\n\
2033The remaining chars indicate types of args and must match exactly;\n\
2034these can be preceded by a decimal repeat count:\n\
2035 x: pad byte (no data); c:char; b:signed byte; B:unsigned byte;\n\
Mark Dickinson40714af2009-10-08 15:59:20 +00002036 ?: _Bool (requires C99; if not available, char is used instead)\n\
Christian Heimesa34706f2008-01-04 03:06:10 +00002037 h:short; H:unsigned short; i:int; I:unsigned int;\n\
2038 l:long; L:unsigned long; f:float; d:double.\n\
2039Special cases (preceding decimal count indicates length):\n\
2040 s:string (array of char); p: pascal string (with count byte).\n\
Antoine Pitrou45d9c912011-10-06 15:27:40 +02002041Special cases (only available in native format):\n\
2042 n:ssize_t; N:size_t;\n\
Christian Heimesa34706f2008-01-04 03:06:10 +00002043 P:an integer type that is wide enough to hold a pointer.\n\
2044Special case (not in native mode unless 'long long' in platform C):\n\
2045 q:long long; Q:unsigned long long\n\
2046Whitespace between formats is ignored.\n\
2047\n\
2048The variable struct.error is an exception raised on errors.\n");
2049
Martin v. Löwis1a214512008-06-11 05:26:20 +00002050
2051static struct PyModuleDef _structmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002052 PyModuleDef_HEAD_INIT,
2053 "_struct",
2054 module_doc,
2055 -1,
2056 module_functions,
2057 NULL,
2058 NULL,
2059 NULL,
2060 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002061};
2062
Thomas Wouters477c8d52006-05-27 19:21:47 +00002063PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002064PyInit__struct(void)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002065{
Mark Dickinson06817852010-06-12 09:25:13 +00002066 PyObject *m;
Christian Heimesa34706f2008-01-04 03:06:10 +00002067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002068 m = PyModule_Create(&_structmodule);
2069 if (m == NULL)
2070 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002071
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002072 Py_TYPE(&PyStructType) = &PyType_Type;
2073 if (PyType_Ready(&PyStructType) < 0)
2074 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002075
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002076 /* Check endian and swap in faster functions */
2077 {
2078 int one = 1;
2079 formatdef *native = native_table;
2080 formatdef *other, *ptr;
2081 if ((int)*(unsigned char*)&one)
2082 other = lilendian_table;
2083 else
2084 other = bigendian_table;
2085 /* Scan through the native table, find a matching
2086 entry in the endian table and swap in the
2087 native implementations whenever possible
2088 (64-bit platforms may not have "standard" sizes) */
2089 while (native->format != '\0' && other->format != '\0') {
2090 ptr = other;
2091 while (ptr->format != '\0') {
2092 if (ptr->format == native->format) {
2093 /* Match faster when formats are
2094 listed in the same order */
2095 if (ptr == other)
2096 other++;
2097 /* Only use the trick if the
2098 size matches */
2099 if (ptr->size != native->size)
2100 break;
2101 /* Skip float and double, could be
2102 "unknown" float format */
2103 if (ptr->format == 'd' || ptr->format == 'f')
2104 break;
2105 ptr->pack = native->pack;
2106 ptr->unpack = native->unpack;
2107 break;
2108 }
2109 ptr++;
2110 }
2111 native++;
2112 }
2113 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002115 /* Add some symbolic constants to the module */
2116 if (StructError == NULL) {
2117 StructError = PyErr_NewException("struct.error", NULL, NULL);
2118 if (StructError == NULL)
2119 return NULL;
2120 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002122 Py_INCREF(StructError);
2123 PyModule_AddObject(m, "error", StructError);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002125 Py_INCREF((PyObject*)&PyStructType);
2126 PyModule_AddObject(m, "Struct", (PyObject*)&PyStructType);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002128 return m;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002129}