blob: b6be5b69f1015e648e57e92fe3ee50d91f7eec85 [file] [log] [blame]
Bob Ippolito232f3c92006-05-23 19:12:41 +00001/* struct module -- pack values into and (out of) strings */
2
3/* New version supporting byte order, alignment and size options,
4 character strings, and unsigned numbers */
5
Bob Ippolitoaa70a172006-05-26 20:25:23 +00006#define PY_SSIZE_T_CLEAN
7
Bob Ippolito232f3c92006-05-23 19:12:41 +00008#include "Python.h"
9#include "structseq.h"
10#include "structmember.h"
11#include <ctype.h>
12
Bob Ippolitod3611eb2006-05-23 19:31:23 +000013static PyTypeObject PyStructType;
Bob Ippolito232f3c92006-05-23 19:12:41 +000014
15/* compatibility macros */
16#if (PY_VERSION_HEX < 0x02050000)
17typedef int Py_ssize_t;
18#endif
19
Mark Dickinson154b7ad2010-03-07 16:24:45 +000020/* warning messages */
21#define FLOAT_COERCE_WARN "integer argument expected, got float"
22#define NON_INTEGER_WARN "integer argument expected, got non-integer " \
23 "(implicit conversion using __int__ is deprecated)"
Bob Ippolitoe6c9f982006-08-04 23:59:21 +000024
25
Bob Ippolito232f3c92006-05-23 19:12:41 +000026/* The translation function for each format character is table driven */
Bob Ippolito232f3c92006-05-23 19:12:41 +000027typedef struct _formatdef {
28 char format;
Bob Ippolitoaa70a172006-05-26 20:25:23 +000029 Py_ssize_t size;
30 Py_ssize_t alignment;
Bob Ippolito232f3c92006-05-23 19:12:41 +000031 PyObject* (*unpack)(const char *,
32 const struct _formatdef *);
33 int (*pack)(char *, PyObject *,
34 const struct _formatdef *);
35} formatdef;
36
37typedef struct _formatcode {
38 const struct _formatdef *fmtdef;
Bob Ippolitoaa70a172006-05-26 20:25:23 +000039 Py_ssize_t offset;
40 Py_ssize_t size;
Bob Ippolito232f3c92006-05-23 19:12:41 +000041} formatcode;
42
43/* Struct object interface */
44
45typedef struct {
46 PyObject_HEAD
Bob Ippolitoaa70a172006-05-26 20:25:23 +000047 Py_ssize_t s_size;
48 Py_ssize_t s_len;
Bob Ippolito232f3c92006-05-23 19:12:41 +000049 formatcode *s_codes;
50 PyObject *s_format;
51 PyObject *weakreflist; /* List of weak references */
52} PyStructObject;
53
Bob Ippolitoeb621272006-05-24 15:32:06 +000054
Bob Ippolito07c023b2006-05-23 19:32:25 +000055#define PyStruct_Check(op) PyObject_TypeCheck(op, &PyStructType)
Christian Heimese93237d2007-12-19 02:37:44 +000056#define PyStruct_CheckExact(op) (Py_TYPE(op) == &PyStructType)
Bob Ippolito232f3c92006-05-23 19:12:41 +000057
58
59/* Exception */
60
61static PyObject *StructError;
62
63
64/* Define various structs to figure out the alignments of types */
65
66
67typedef struct { char c; short x; } st_short;
68typedef struct { char c; int x; } st_int;
69typedef struct { char c; long x; } st_long;
70typedef struct { char c; float x; } st_float;
71typedef struct { char c; double x; } st_double;
72typedef struct { char c; void *x; } st_void_p;
73
74#define SHORT_ALIGN (sizeof(st_short) - sizeof(short))
75#define INT_ALIGN (sizeof(st_int) - sizeof(int))
76#define LONG_ALIGN (sizeof(st_long) - sizeof(long))
77#define FLOAT_ALIGN (sizeof(st_float) - sizeof(float))
78#define DOUBLE_ALIGN (sizeof(st_double) - sizeof(double))
79#define VOID_P_ALIGN (sizeof(st_void_p) - sizeof(void *))
80
81/* We can't support q and Q in native mode unless the compiler does;
82 in std mode, they're 8 bytes on all platforms. */
83#ifdef HAVE_LONG_LONG
84typedef struct { char c; PY_LONG_LONG x; } s_long_long;
85#define LONG_LONG_ALIGN (sizeof(s_long_long) - sizeof(PY_LONG_LONG))
86#endif
87
Martin v. Löwisaef4c6b2007-01-21 09:33:07 +000088#ifdef HAVE_C99_BOOL
89#define BOOL_TYPE _Bool
90typedef struct { char c; _Bool x; } s_bool;
91#define BOOL_ALIGN (sizeof(s_bool) - sizeof(BOOL_TYPE))
92#else
93#define BOOL_TYPE char
94#define BOOL_ALIGN 0
95#endif
96
Bob Ippolito232f3c92006-05-23 19:12:41 +000097#define STRINGIFY(x) #x
98
99#ifdef __powerc
100#pragma options align=reset
101#endif
102
Mark Dickinson5fd3af22009-07-07 15:08:28 +0000103static char *integer_codes = "bBhHiIlLqQ";
104
Bob Ippolito232f3c92006-05-23 19:12:41 +0000105/* Helper to get a PyLongObject by hook or by crook. Caller should decref. */
106
107static PyObject *
108get_pylong(PyObject *v)
109{
Mark Dickinson4846a8e2010-04-03 14:05:10 +0000110 PyObject *r, *w;
111 int converted = 0;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000112 assert(v != NULL);
Mark Dickinson154b7ad2010-03-07 16:24:45 +0000113 if (!PyInt_Check(v) && !PyLong_Check(v)) {
114 PyNumberMethods *m;
Mark Dickinson4846a8e2010-04-03 14:05:10 +0000115 /* Not an integer; first try to use __index__ to
116 convert to an integer. If the __index__ method
117 doesn't exist, or raises a TypeError, try __int__.
118 Use of the latter is deprecated, and will fail in
Mark Dickinson154b7ad2010-03-07 16:24:45 +0000119 Python 3.x. */
Mark Dickinson4846a8e2010-04-03 14:05:10 +0000120
Mark Dickinson154b7ad2010-03-07 16:24:45 +0000121 m = Py_TYPE(v)->tp_as_number;
Mark Dickinson4846a8e2010-04-03 14:05:10 +0000122 if (PyIndex_Check(v)) {
123 w = PyNumber_Index(v);
124 if (w != NULL) {
125 v = w;
Mark Dickinson4846a8e2010-04-03 14:05:10 +0000126 /* successfully converted to an integer */
127 converted = 1;
128 }
129 else if (PyErr_ExceptionMatches(PyExc_TypeError)) {
130 PyErr_Clear();
131 }
132 else
133 return NULL;
134 }
135 if (!converted && m != NULL && m->nb_int != NULL) {
Mark Dickinson154b7ad2010-03-07 16:24:45 +0000136 /* Special case warning message for floats, for
137 backwards compatibility. */
138 if (PyFloat_Check(v)) {
Mark Dickinson4846a8e2010-04-03 14:05:10 +0000139 if (PyErr_WarnEx(
140 PyExc_DeprecationWarning,
141 FLOAT_COERCE_WARN, 1))
Mark Dickinson154b7ad2010-03-07 16:24:45 +0000142 return NULL;
143 }
144 else {
Mark Dickinson4846a8e2010-04-03 14:05:10 +0000145 if (PyErr_WarnEx(
146 PyExc_DeprecationWarning,
147 NON_INTEGER_WARN, 1))
Mark Dickinson154b7ad2010-03-07 16:24:45 +0000148 return NULL;
149 }
150 v = m->nb_int(v);
151 if (v == NULL)
152 return NULL;
153 if (!PyInt_Check(v) && !PyLong_Check(v)) {
154 PyErr_SetString(PyExc_TypeError,
Mark Dickinson4846a8e2010-04-03 14:05:10 +0000155 "__int__ method returned "
156 "non-integer");
Mark Dickinson154b7ad2010-03-07 16:24:45 +0000157 return NULL;
158 }
Mark Dickinson4846a8e2010-04-03 14:05:10 +0000159 converted = 1;
Mark Dickinson154b7ad2010-03-07 16:24:45 +0000160 }
Mark Dickinson4846a8e2010-04-03 14:05:10 +0000161 if (!converted) {
Mark Dickinson154b7ad2010-03-07 16:24:45 +0000162 PyErr_SetString(StructError,
Mark Dickinson4846a8e2010-04-03 14:05:10 +0000163 "cannot convert argument "
164 "to integer");
Bob Ippolito232f3c92006-05-23 19:12:41 +0000165 return NULL;
Mark Dickinson154b7ad2010-03-07 16:24:45 +0000166 }
Bob Ippolito232f3c92006-05-23 19:12:41 +0000167 }
Mark Dickinson154b7ad2010-03-07 16:24:45 +0000168 else
169 /* Ensure we own a reference to v. */
170 Py_INCREF(v);
171
Mark Dickinsonfdaaa9c2010-04-04 08:43:04 +0000172 assert(PyInt_Check(v) || PyLong_Check(v));
Mark Dickinson154b7ad2010-03-07 16:24:45 +0000173 if (PyInt_Check(v)) {
174 r = PyLong_FromLong(PyInt_AS_LONG(v));
175 Py_DECREF(v);
176 }
177 else if (PyLong_Check(v)) {
178 assert(PyLong_Check(v));
179 r = v;
180 }
Mark Dickinson2db56872010-03-07 17:10:19 +0000181 else {
182 r = NULL; /* silence compiler warning about
183 possibly uninitialized variable */
Mark Dickinson154b7ad2010-03-07 16:24:45 +0000184 assert(0); /* shouldn't ever get here */
Mark Dickinson2db56872010-03-07 17:10:19 +0000185 }
Mark Dickinson154b7ad2010-03-07 16:24:45 +0000186
187 return r;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000188}
189
Mark Dickinson5fd3af22009-07-07 15:08:28 +0000190/* Helper to convert a Python object to a C long. Sets an exception
191 (struct.error for an inconvertible type, OverflowError for
192 out-of-range values) and returns -1 on error. */
Bob Ippolito232f3c92006-05-23 19:12:41 +0000193
194static int
195get_long(PyObject *v, long *p)
196{
Mark Dickinson463dc4b2009-07-05 10:01:24 +0000197 long x;
198
199 v = get_pylong(v);
200 if (v == NULL)
201 return -1;
202 assert(PyLong_Check(v));
203 x = PyLong_AsLong(v);
204 Py_DECREF(v);
Mark Dickinson5fd3af22009-07-07 15:08:28 +0000205 if (x == (long)-1 && PyErr_Occurred())
Bob Ippolito232f3c92006-05-23 19:12:41 +0000206 return -1;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000207 *p = x;
208 return 0;
209}
210
Bob Ippolito232f3c92006-05-23 19:12:41 +0000211/* Same, but handling unsigned long */
212
213static int
214get_ulong(PyObject *v, unsigned long *p)
215{
Mark Dickinson463dc4b2009-07-05 10:01:24 +0000216 unsigned long x;
217
218 v = get_pylong(v);
219 if (v == NULL)
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000220 return -1;
Mark Dickinson463dc4b2009-07-05 10:01:24 +0000221 assert(PyLong_Check(v));
222 x = PyLong_AsUnsignedLong(v);
223 Py_DECREF(v);
Mark Dickinson5fd3af22009-07-07 15:08:28 +0000224 if (x == (unsigned long)-1 && PyErr_Occurred())
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000225 return -1;
Mark Dickinson463dc4b2009-07-05 10:01:24 +0000226 *p = x;
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000227 return 0;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000228}
229
230#ifdef HAVE_LONG_LONG
231
232/* Same, but handling native long long. */
233
234static int
235get_longlong(PyObject *v, PY_LONG_LONG *p)
236{
237 PY_LONG_LONG x;
238
239 v = get_pylong(v);
240 if (v == NULL)
241 return -1;
242 assert(PyLong_Check(v));
243 x = PyLong_AsLongLong(v);
244 Py_DECREF(v);
Mark Dickinson5fd3af22009-07-07 15:08:28 +0000245 if (x == (PY_LONG_LONG)-1 && PyErr_Occurred())
Bob Ippolito232f3c92006-05-23 19:12:41 +0000246 return -1;
247 *p = x;
248 return 0;
249}
250
251/* Same, but handling native unsigned long long. */
252
253static int
254get_ulonglong(PyObject *v, unsigned PY_LONG_LONG *p)
255{
256 unsigned PY_LONG_LONG x;
257
258 v = get_pylong(v);
259 if (v == NULL)
260 return -1;
261 assert(PyLong_Check(v));
262 x = PyLong_AsUnsignedLongLong(v);
263 Py_DECREF(v);
Mark Dickinson5fd3af22009-07-07 15:08:28 +0000264 if (x == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred())
Bob Ippolito232f3c92006-05-23 19:12:41 +0000265 return -1;
266 *p = x;
267 return 0;
268}
269
270#endif
271
272/* Floating point helpers */
273
274static PyObject *
275unpack_float(const char *p, /* start of 4-byte string */
Mark Dickinson4f185222010-04-04 21:19:35 +0000276 int le) /* true for little-endian, false for big-endian */
Bob Ippolito232f3c92006-05-23 19:12:41 +0000277{
278 double x;
279
280 x = _PyFloat_Unpack4((unsigned char *)p, le);
281 if (x == -1.0 && PyErr_Occurred())
282 return NULL;
283 return PyFloat_FromDouble(x);
284}
285
286static PyObject *
287unpack_double(const char *p, /* start of 8-byte string */
Mark Dickinson4f185222010-04-04 21:19:35 +0000288 int le) /* true for little-endian, false for big-endian */
Bob Ippolito232f3c92006-05-23 19:12:41 +0000289{
290 double x;
291
292 x = _PyFloat_Unpack8((unsigned char *)p, le);
293 if (x == -1.0 && PyErr_Occurred())
294 return NULL;
295 return PyFloat_FromDouble(x);
296}
297
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000298/* Helper to format the range error exceptions */
299static int
Armin Rigo162997e2006-05-29 17:59:47 +0000300_range_error(const formatdef *f, int is_unsigned)
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000301{
Tim Petersd6a6f022006-05-31 15:33:22 +0000302 /* ulargest is the largest unsigned value with f->size bytes.
303 * Note that the simpler:
304 * ((size_t)1 << (f->size * 8)) - 1
Tim Peters72270c22006-05-31 15:34:37 +0000305 * doesn't work when f->size == sizeof(size_t) because C doesn't
306 * define what happens when a left shift count is >= the number of
307 * bits in the integer being shifted; e.g., on some boxes it doesn't
308 * shift at all when they're equal.
Tim Petersd6a6f022006-05-31 15:33:22 +0000309 */
310 const size_t ulargest = (size_t)-1 >> ((SIZEOF_SIZE_T - f->size)*8);
311 assert(f->size >= 1 && f->size <= SIZEOF_SIZE_T);
312 if (is_unsigned)
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000313 PyErr_Format(StructError,
Neal Norwitz971ea112006-05-31 07:43:27 +0000314 "'%c' format requires 0 <= number <= %zu",
Bob Ippolito28b26862006-05-29 15:47:29 +0000315 f->format,
Tim Petersd6a6f022006-05-31 15:33:22 +0000316 ulargest);
317 else {
318 const Py_ssize_t largest = (Py_ssize_t)(ulargest >> 1);
319 PyErr_Format(StructError,
320 "'%c' format requires %zd <= number <= %zd",
321 f->format,
322 ~ largest,
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000323 largest);
324 }
325 return -1;
326}
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000327
328
Bob Ippolito232f3c92006-05-23 19:12:41 +0000329
330/* A large number of small routines follow, with names of the form
331
Bob Ippolitoaa70a172006-05-26 20:25:23 +0000332 [bln][up]_TYPE
Bob Ippolito232f3c92006-05-23 19:12:41 +0000333
334 [bln] distiguishes among big-endian, little-endian and native.
335 [pu] distiguishes between pack (to struct) and unpack (from struct).
336 TYPE is one of char, byte, ubyte, etc.
337*/
338
339/* Native mode routines. ****************************************************/
340/* NOTE:
341 In all n[up]_<type> routines handling types larger than 1 byte, there is
342 *no* guarantee that the p pointer is properly aligned for each type,
343 therefore memcpy is called. An intermediate variable is used to
344 compensate for big-endian architectures.
345 Normally both the intermediate variable and the memcpy call will be
346 skipped by C optimisation in little-endian architectures (gcc >= 2.91
347 does this). */
348
349static PyObject *
350nu_char(const char *p, const formatdef *f)
351{
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000352 return PyString_FromStringAndSize(p, 1);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000353}
354
355static PyObject *
356nu_byte(const char *p, const formatdef *f)
357{
358 return PyInt_FromLong((long) *(signed char *)p);
359}
360
361static PyObject *
362nu_ubyte(const char *p, const formatdef *f)
363{
364 return PyInt_FromLong((long) *(unsigned char *)p);
365}
366
367static PyObject *
368nu_short(const char *p, const formatdef *f)
369{
370 short x;
371 memcpy((char *)&x, p, sizeof x);
372 return PyInt_FromLong((long)x);
373}
374
375static PyObject *
376nu_ushort(const char *p, const formatdef *f)
377{
378 unsigned short x;
379 memcpy((char *)&x, p, sizeof x);
380 return PyInt_FromLong((long)x);
381}
382
383static PyObject *
384nu_int(const char *p, const formatdef *f)
385{
386 int x;
387 memcpy((char *)&x, p, sizeof x);
388 return PyInt_FromLong((long)x);
389}
390
391static PyObject *
392nu_uint(const char *p, const formatdef *f)
393{
394 unsigned int x;
395 memcpy((char *)&x, p, sizeof x);
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000396#if (SIZEOF_LONG > SIZEOF_INT)
397 return PyInt_FromLong((long)x);
398#else
399 if (x <= ((unsigned int)LONG_MAX))
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000400 return PyInt_FromLong((long)x);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000401 return PyLong_FromUnsignedLong((unsigned long)x);
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000402#endif
Bob Ippolito232f3c92006-05-23 19:12:41 +0000403}
404
405static PyObject *
406nu_long(const char *p, const formatdef *f)
407{
408 long x;
409 memcpy((char *)&x, p, sizeof x);
410 return PyInt_FromLong(x);
411}
412
413static PyObject *
414nu_ulong(const char *p, const formatdef *f)
415{
416 unsigned long x;
417 memcpy((char *)&x, p, sizeof x);
Bob Ippolito04ab9942006-05-25 19:33:38 +0000418 if (x <= LONG_MAX)
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000419 return PyInt_FromLong((long)x);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000420 return PyLong_FromUnsignedLong(x);
421}
422
423/* Native mode doesn't support q or Q unless the platform C supports
424 long long (or, on Windows, __int64). */
425
426#ifdef HAVE_LONG_LONG
427
428static PyObject *
429nu_longlong(const char *p, const formatdef *f)
430{
431 PY_LONG_LONG x;
432 memcpy((char *)&x, p, sizeof x);
Bob Ippolito04ab9942006-05-25 19:33:38 +0000433 if (x >= LONG_MIN && x <= LONG_MAX)
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000434 return PyInt_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long));
Bob Ippolito232f3c92006-05-23 19:12:41 +0000435 return PyLong_FromLongLong(x);
436}
437
438static PyObject *
439nu_ulonglong(const char *p, const formatdef *f)
440{
441 unsigned PY_LONG_LONG x;
442 memcpy((char *)&x, p, sizeof x);
Bob Ippolito04ab9942006-05-25 19:33:38 +0000443 if (x <= LONG_MAX)
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000444 return PyInt_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long));
Bob Ippolito232f3c92006-05-23 19:12:41 +0000445 return PyLong_FromUnsignedLongLong(x);
446}
447
448#endif
449
450static PyObject *
Martin v. Löwisaef4c6b2007-01-21 09:33:07 +0000451nu_bool(const char *p, const formatdef *f)
452{
453 BOOL_TYPE x;
454 memcpy((char *)&x, p, sizeof x);
455 return PyBool_FromLong(x != 0);
456}
457
458
459static PyObject *
Bob Ippolito232f3c92006-05-23 19:12:41 +0000460nu_float(const char *p, const formatdef *f)
461{
462 float x;
463 memcpy((char *)&x, p, sizeof x);
464 return PyFloat_FromDouble((double)x);
465}
466
467static PyObject *
468nu_double(const char *p, const formatdef *f)
469{
470 double x;
471 memcpy((char *)&x, p, sizeof x);
472 return PyFloat_FromDouble(x);
473}
474
475static PyObject *
476nu_void_p(const char *p, const formatdef *f)
477{
478 void *x;
479 memcpy((char *)&x, p, sizeof x);
480 return PyLong_FromVoidPtr(x);
481}
482
483static int
484np_byte(char *p, PyObject *v, const formatdef *f)
485{
486 long x;
487 if (get_long(v, &x) < 0)
488 return -1;
489 if (x < -128 || x > 127){
490 PyErr_SetString(StructError,
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000491 "byte format requires -128 <= number <= 127");
Bob Ippolito232f3c92006-05-23 19:12:41 +0000492 return -1;
493 }
494 *p = (char)x;
495 return 0;
496}
497
498static int
499np_ubyte(char *p, PyObject *v, const formatdef *f)
500{
501 long x;
502 if (get_long(v, &x) < 0)
503 return -1;
504 if (x < 0 || x > 255){
505 PyErr_SetString(StructError,
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000506 "ubyte format requires 0 <= number <= 255");
Bob Ippolito232f3c92006-05-23 19:12:41 +0000507 return -1;
508 }
509 *p = (char)x;
510 return 0;
511}
512
513static int
514np_char(char *p, PyObject *v, const formatdef *f)
515{
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000516 if (!PyString_Check(v) || PyString_Size(v) != 1) {
Bob Ippolito232f3c92006-05-23 19:12:41 +0000517 PyErr_SetString(StructError,
518 "char format require string of length 1");
519 return -1;
520 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000521 *p = *PyString_AsString(v);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000522 return 0;
523}
524
525static int
526np_short(char *p, PyObject *v, const formatdef *f)
527{
528 long x;
529 short y;
530 if (get_long(v, &x) < 0)
531 return -1;
532 if (x < SHRT_MIN || x > SHRT_MAX){
533 PyErr_SetString(StructError,
534 "short format requires " STRINGIFY(SHRT_MIN)
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000535 " <= number <= " STRINGIFY(SHRT_MAX));
Bob Ippolito232f3c92006-05-23 19:12:41 +0000536 return -1;
537 }
538 y = (short)x;
539 memcpy(p, (char *)&y, sizeof y);
540 return 0;
541}
542
543static int
544np_ushort(char *p, PyObject *v, const formatdef *f)
545{
546 long x;
547 unsigned short y;
548 if (get_long(v, &x) < 0)
549 return -1;
550 if (x < 0 || x > USHRT_MAX){
551 PyErr_SetString(StructError,
Mark Dickinson24766ba2009-07-07 10:18:22 +0000552 "ushort format requires 0 <= number <= " STRINGIFY(USHRT_MAX));
Bob Ippolito232f3c92006-05-23 19:12:41 +0000553 return -1;
554 }
555 y = (unsigned short)x;
556 memcpy(p, (char *)&y, sizeof y);
557 return 0;
558}
559
560static int
561np_int(char *p, PyObject *v, const formatdef *f)
562{
563 long x;
564 int y;
565 if (get_long(v, &x) < 0)
566 return -1;
Bob Ippolito90bd0a52006-05-27 11:47:12 +0000567#if (SIZEOF_LONG > SIZEOF_INT)
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000568 if ((x < ((long)INT_MIN)) || (x > ((long)INT_MAX)))
Mark Dickinson5fd3af22009-07-07 15:08:28 +0000569 return _range_error(f, 0);
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000570#endif
Bob Ippolito232f3c92006-05-23 19:12:41 +0000571 y = (int)x;
572 memcpy(p, (char *)&y, sizeof y);
573 return 0;
574}
575
576static int
577np_uint(char *p, PyObject *v, const formatdef *f)
578{
579 unsigned long x;
580 unsigned int y;
Mark Dickinson716a9cc2009-09-27 16:39:28 +0000581 if (get_ulong(v, &x) < 0)
Georg Brandl6269fec2009-01-01 12:15:31 +0000582 return -1;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000583 y = (unsigned int)x;
Bob Ippolito90bd0a52006-05-27 11:47:12 +0000584#if (SIZEOF_LONG > SIZEOF_INT)
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000585 if (x > ((unsigned long)UINT_MAX))
Mark Dickinson5fd3af22009-07-07 15:08:28 +0000586 return _range_error(f, 1);
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000587#endif
Bob Ippolito232f3c92006-05-23 19:12:41 +0000588 memcpy(p, (char *)&y, sizeof y);
589 return 0;
590}
591
592static int
593np_long(char *p, PyObject *v, const formatdef *f)
594{
595 long x;
596 if (get_long(v, &x) < 0)
597 return -1;
598 memcpy(p, (char *)&x, sizeof x);
599 return 0;
600}
601
602static int
603np_ulong(char *p, PyObject *v, const formatdef *f)
604{
605 unsigned long x;
Mark Dickinson716a9cc2009-09-27 16:39:28 +0000606 if (get_ulong(v, &x) < 0)
Georg Brandl6269fec2009-01-01 12:15:31 +0000607 return -1;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000608 memcpy(p, (char *)&x, sizeof x);
609 return 0;
610}
611
612#ifdef HAVE_LONG_LONG
613
614static int
615np_longlong(char *p, PyObject *v, const formatdef *f)
616{
617 PY_LONG_LONG x;
618 if (get_longlong(v, &x) < 0)
619 return -1;
620 memcpy(p, (char *)&x, sizeof x);
621 return 0;
622}
623
624static int
625np_ulonglong(char *p, PyObject *v, const formatdef *f)
626{
627 unsigned PY_LONG_LONG x;
628 if (get_ulonglong(v, &x) < 0)
629 return -1;
630 memcpy(p, (char *)&x, sizeof x);
631 return 0;
632}
633#endif
634
Martin v. Löwisaef4c6b2007-01-21 09:33:07 +0000635
636static int
637np_bool(char *p, PyObject *v, const formatdef *f)
638{
Mark Dickinson4f185222010-04-04 21:19:35 +0000639 BOOL_TYPE y;
Martin v. Löwisaef4c6b2007-01-21 09:33:07 +0000640 y = PyObject_IsTrue(v);
641 memcpy(p, (char *)&y, sizeof y);
642 return 0;
643}
644
Bob Ippolito232f3c92006-05-23 19:12:41 +0000645static int
646np_float(char *p, PyObject *v, const formatdef *f)
647{
648 float x = (float)PyFloat_AsDouble(v);
649 if (x == -1 && PyErr_Occurred()) {
650 PyErr_SetString(StructError,
651 "required argument is not a float");
652 return -1;
653 }
654 memcpy(p, (char *)&x, sizeof x);
655 return 0;
656}
657
658static int
659np_double(char *p, PyObject *v, const formatdef *f)
660{
661 double x = PyFloat_AsDouble(v);
662 if (x == -1 && PyErr_Occurred()) {
663 PyErr_SetString(StructError,
664 "required argument is not a float");
665 return -1;
666 }
667 memcpy(p, (char *)&x, sizeof(double));
668 return 0;
669}
670
671static int
672np_void_p(char *p, PyObject *v, const formatdef *f)
673{
674 void *x;
675
676 v = get_pylong(v);
677 if (v == NULL)
678 return -1;
679 assert(PyLong_Check(v));
680 x = PyLong_AsVoidPtr(v);
681 Py_DECREF(v);
682 if (x == NULL && PyErr_Occurred())
683 return -1;
684 memcpy(p, (char *)&x, sizeof x);
685 return 0;
686}
687
688static formatdef native_table[] = {
689 {'x', sizeof(char), 0, NULL},
690 {'b', sizeof(char), 0, nu_byte, np_byte},
691 {'B', sizeof(char), 0, nu_ubyte, np_ubyte},
692 {'c', sizeof(char), 0, nu_char, np_char},
693 {'s', sizeof(char), 0, NULL},
694 {'p', sizeof(char), 0, NULL},
695 {'h', sizeof(short), SHORT_ALIGN, nu_short, np_short},
696 {'H', sizeof(short), SHORT_ALIGN, nu_ushort, np_ushort},
697 {'i', sizeof(int), INT_ALIGN, nu_int, np_int},
698 {'I', sizeof(int), INT_ALIGN, nu_uint, np_uint},
699 {'l', sizeof(long), LONG_ALIGN, nu_long, np_long},
700 {'L', sizeof(long), LONG_ALIGN, nu_ulong, np_ulong},
Bob Ippolito232f3c92006-05-23 19:12:41 +0000701#ifdef HAVE_LONG_LONG
702 {'q', sizeof(PY_LONG_LONG), LONG_LONG_ALIGN, nu_longlong, np_longlong},
703 {'Q', sizeof(PY_LONG_LONG), LONG_LONG_ALIGN, nu_ulonglong,np_ulonglong},
704#endif
Thomas Hellerf3c05592008-03-05 15:34:29 +0000705 {'?', sizeof(BOOL_TYPE), BOOL_ALIGN, nu_bool, np_bool},
Bob Ippolitoa99865b2006-05-25 19:56:56 +0000706 {'f', sizeof(float), FLOAT_ALIGN, nu_float, np_float},
707 {'d', sizeof(double), DOUBLE_ALIGN, nu_double, np_double},
708 {'P', sizeof(void *), VOID_P_ALIGN, nu_void_p, np_void_p},
Bob Ippolito232f3c92006-05-23 19:12:41 +0000709 {0}
710};
711
712/* Big-endian routines. *****************************************************/
713
714static PyObject *
715bu_int(const char *p, const formatdef *f)
716{
717 long x = 0;
Bob Ippolitoaa70a172006-05-26 20:25:23 +0000718 Py_ssize_t i = f->size;
Bob Ippolito28b26862006-05-29 15:47:29 +0000719 const unsigned char *bytes = (const unsigned char *)p;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000720 do {
Bob Ippolito28b26862006-05-29 15:47:29 +0000721 x = (x<<8) | *bytes++;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000722 } while (--i > 0);
723 /* Extend the sign bit. */
724 if (SIZEOF_LONG > f->size)
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000725 x |= -(x & (1L << ((8 * f->size) - 1)));
Bob Ippolito232f3c92006-05-23 19:12:41 +0000726 return PyInt_FromLong(x);
727}
728
729static PyObject *
730bu_uint(const char *p, const formatdef *f)
731{
732 unsigned long x = 0;
Bob Ippolitoaa70a172006-05-26 20:25:23 +0000733 Py_ssize_t i = f->size;
Bob Ippolito28b26862006-05-29 15:47:29 +0000734 const unsigned char *bytes = (const unsigned char *)p;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000735 do {
Bob Ippolito28b26862006-05-29 15:47:29 +0000736 x = (x<<8) | *bytes++;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000737 } while (--i > 0);
Bob Ippolito04ab9942006-05-25 19:33:38 +0000738 if (x <= LONG_MAX)
Bob Ippolito232f3c92006-05-23 19:12:41 +0000739 return PyInt_FromLong((long)x);
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000740 return PyLong_FromUnsignedLong(x);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000741}
742
743static PyObject *
744bu_longlong(const char *p, const formatdef *f)
745{
Bob Ippolito90bd0a52006-05-27 11:47:12 +0000746#ifdef HAVE_LONG_LONG
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000747 PY_LONG_LONG x = 0;
Bob Ippolitoaa70a172006-05-26 20:25:23 +0000748 Py_ssize_t i = f->size;
Bob Ippolito28b26862006-05-29 15:47:29 +0000749 const unsigned char *bytes = (const unsigned char *)p;
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000750 do {
Bob Ippolito28b26862006-05-29 15:47:29 +0000751 x = (x<<8) | *bytes++;
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000752 } while (--i > 0);
753 /* Extend the sign bit. */
754 if (SIZEOF_LONG_LONG > f->size)
Kristján Valur Jónsson67387fb2007-04-25 00:17:39 +0000755 x |= -(x & ((PY_LONG_LONG)1 << ((8 * f->size) - 1)));
Bob Ippolito04ab9942006-05-25 19:33:38 +0000756 if (x >= LONG_MIN && x <= LONG_MAX)
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000757 return PyInt_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long));
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000758 return PyLong_FromLongLong(x);
759#else
Bob Ippolito232f3c92006-05-23 19:12:41 +0000760 return _PyLong_FromByteArray((const unsigned char *)p,
761 8,
762 0, /* little-endian */
763 1 /* signed */);
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000764#endif
Bob Ippolito232f3c92006-05-23 19:12:41 +0000765}
766
767static PyObject *
768bu_ulonglong(const char *p, const formatdef *f)
769{
Bob Ippolito90bd0a52006-05-27 11:47:12 +0000770#ifdef HAVE_LONG_LONG
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000771 unsigned PY_LONG_LONG x = 0;
Bob Ippolitoaa70a172006-05-26 20:25:23 +0000772 Py_ssize_t i = f->size;
Bob Ippolito28b26862006-05-29 15:47:29 +0000773 const unsigned char *bytes = (const unsigned char *)p;
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000774 do {
Bob Ippolito28b26862006-05-29 15:47:29 +0000775 x = (x<<8) | *bytes++;
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000776 } while (--i > 0);
Bob Ippolito04ab9942006-05-25 19:33:38 +0000777 if (x <= LONG_MAX)
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000778 return PyInt_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long));
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000779 return PyLong_FromUnsignedLongLong(x);
780#else
Bob Ippolito232f3c92006-05-23 19:12:41 +0000781 return _PyLong_FromByteArray((const unsigned char *)p,
782 8,
783 0, /* little-endian */
784 0 /* signed */);
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000785#endif
Bob Ippolito232f3c92006-05-23 19:12:41 +0000786}
787
788static PyObject *
789bu_float(const char *p, const formatdef *f)
790{
791 return unpack_float(p, 0);
792}
793
794static PyObject *
795bu_double(const char *p, const formatdef *f)
796{
797 return unpack_double(p, 0);
798}
799
Martin v. Löwisaef4c6b2007-01-21 09:33:07 +0000800static PyObject *
801bu_bool(const char *p, const formatdef *f)
802{
803 char x;
804 memcpy((char *)&x, p, sizeof x);
805 return PyBool_FromLong(x != 0);
806}
807
Bob Ippolito232f3c92006-05-23 19:12:41 +0000808static int
809bp_int(char *p, PyObject *v, const formatdef *f)
810{
811 long x;
Bob Ippolitoaa70a172006-05-26 20:25:23 +0000812 Py_ssize_t i;
Mark Dickinson716a9cc2009-09-27 16:39:28 +0000813 if (get_long(v, &x) < 0)
Bob Ippolito232f3c92006-05-23 19:12:41 +0000814 return -1;
815 i = f->size;
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000816 if (i != SIZEOF_LONG) {
817 if ((i == 2) && (x < -32768 || x > 32767))
Mark Dickinson5fd3af22009-07-07 15:08:28 +0000818 return _range_error(f, 0);
Bob Ippolito90bd0a52006-05-27 11:47:12 +0000819#if (SIZEOF_LONG != 4)
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000820 else if ((i == 4) && (x < -2147483648L || x > 2147483647L))
Mark Dickinson5fd3af22009-07-07 15:08:28 +0000821 return _range_error(f, 0);
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000822#endif
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000823 }
Bob Ippolito232f3c92006-05-23 19:12:41 +0000824 do {
825 p[--i] = (char)x;
826 x >>= 8;
827 } while (i > 0);
828 return 0;
829}
830
831static int
832bp_uint(char *p, PyObject *v, const formatdef *f)
833{
834 unsigned long x;
Bob Ippolitoaa70a172006-05-26 20:25:23 +0000835 Py_ssize_t i;
Mark Dickinson716a9cc2009-09-27 16:39:28 +0000836 if (get_ulong(v, &x) < 0)
Bob Ippolito232f3c92006-05-23 19:12:41 +0000837 return -1;
838 i = f->size;
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000839 if (i != SIZEOF_LONG) {
840 unsigned long maxint = 1;
841 maxint <<= (unsigned long)(i * 8);
842 if (x >= maxint)
Mark Dickinson5fd3af22009-07-07 15:08:28 +0000843 return _range_error(f, 1);
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000844 }
Bob Ippolito232f3c92006-05-23 19:12:41 +0000845 do {
846 p[--i] = (char)x;
847 x >>= 8;
848 } while (i > 0);
849 return 0;
850}
851
852static int
853bp_longlong(char *p, PyObject *v, const formatdef *f)
854{
855 int res;
856 v = get_pylong(v);
857 if (v == NULL)
858 return -1;
859 res = _PyLong_AsByteArray((PyLongObject *)v,
Mark Dickinson4f185222010-04-04 21:19:35 +0000860 (unsigned char *)p,
Bob Ippolito232f3c92006-05-23 19:12:41 +0000861 8,
862 0, /* little_endian */
863 1 /* signed */);
864 Py_DECREF(v);
865 return res;
866}
867
868static int
869bp_ulonglong(char *p, PyObject *v, const formatdef *f)
870{
871 int res;
872 v = get_pylong(v);
873 if (v == NULL)
874 return -1;
875 res = _PyLong_AsByteArray((PyLongObject *)v,
Mark Dickinson4f185222010-04-04 21:19:35 +0000876 (unsigned char *)p,
Bob Ippolito232f3c92006-05-23 19:12:41 +0000877 8,
878 0, /* little_endian */
879 0 /* signed */);
880 Py_DECREF(v);
881 return res;
882}
883
884static int
885bp_float(char *p, PyObject *v, const formatdef *f)
886{
887 double x = PyFloat_AsDouble(v);
888 if (x == -1 && PyErr_Occurred()) {
889 PyErr_SetString(StructError,
890 "required argument is not a float");
891 return -1;
892 }
893 return _PyFloat_Pack4(x, (unsigned char *)p, 0);
894}
895
896static int
897bp_double(char *p, PyObject *v, const formatdef *f)
898{
899 double x = PyFloat_AsDouble(v);
900 if (x == -1 && PyErr_Occurred()) {
901 PyErr_SetString(StructError,
902 "required argument is not a float");
903 return -1;
904 }
905 return _PyFloat_Pack8(x, (unsigned char *)p, 0);
906}
907
Martin v. Löwisaef4c6b2007-01-21 09:33:07 +0000908static int
909bp_bool(char *p, PyObject *v, const formatdef *f)
910{
Mark Dickinson4f185222010-04-04 21:19:35 +0000911 char y;
Martin v. Löwisaef4c6b2007-01-21 09:33:07 +0000912 y = PyObject_IsTrue(v);
913 memcpy(p, (char *)&y, sizeof y);
914 return 0;
915}
916
Bob Ippolito232f3c92006-05-23 19:12:41 +0000917static formatdef bigendian_table[] = {
918 {'x', 1, 0, NULL},
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000919 {'b', 1, 0, nu_byte, np_byte},
920 {'B', 1, 0, nu_ubyte, np_ubyte},
Bob Ippolito232f3c92006-05-23 19:12:41 +0000921 {'c', 1, 0, nu_char, np_char},
922 {'s', 1, 0, NULL},
923 {'p', 1, 0, NULL},
924 {'h', 2, 0, bu_int, bp_int},
925 {'H', 2, 0, bu_uint, bp_uint},
926 {'i', 4, 0, bu_int, bp_int},
927 {'I', 4, 0, bu_uint, bp_uint},
928 {'l', 4, 0, bu_int, bp_int},
929 {'L', 4, 0, bu_uint, bp_uint},
930 {'q', 8, 0, bu_longlong, bp_longlong},
931 {'Q', 8, 0, bu_ulonglong, bp_ulonglong},
Thomas Hellerf3c05592008-03-05 15:34:29 +0000932 {'?', 1, 0, bu_bool, bp_bool},
Bob Ippolito232f3c92006-05-23 19:12:41 +0000933 {'f', 4, 0, bu_float, bp_float},
934 {'d', 8, 0, bu_double, bp_double},
935 {0}
936};
937
938/* Little-endian routines. *****************************************************/
939
940static PyObject *
941lu_int(const char *p, const formatdef *f)
942{
943 long x = 0;
Bob Ippolitoaa70a172006-05-26 20:25:23 +0000944 Py_ssize_t i = f->size;
Bob Ippolito28b26862006-05-29 15:47:29 +0000945 const unsigned char *bytes = (const unsigned char *)p;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000946 do {
Bob Ippolito28b26862006-05-29 15:47:29 +0000947 x = (x<<8) | bytes[--i];
Bob Ippolito232f3c92006-05-23 19:12:41 +0000948 } while (i > 0);
949 /* Extend the sign bit. */
950 if (SIZEOF_LONG > f->size)
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000951 x |= -(x & (1L << ((8 * f->size) - 1)));
Bob Ippolito232f3c92006-05-23 19:12:41 +0000952 return PyInt_FromLong(x);
953}
954
955static PyObject *
956lu_uint(const char *p, const formatdef *f)
957{
958 unsigned long x = 0;
Bob Ippolitoaa70a172006-05-26 20:25:23 +0000959 Py_ssize_t i = f->size;
Bob Ippolito28b26862006-05-29 15:47:29 +0000960 const unsigned char *bytes = (const unsigned char *)p;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000961 do {
Bob Ippolito28b26862006-05-29 15:47:29 +0000962 x = (x<<8) | bytes[--i];
Bob Ippolito232f3c92006-05-23 19:12:41 +0000963 } while (i > 0);
Bob Ippolito04ab9942006-05-25 19:33:38 +0000964 if (x <= LONG_MAX)
Bob Ippolito232f3c92006-05-23 19:12:41 +0000965 return PyInt_FromLong((long)x);
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000966 return PyLong_FromUnsignedLong((long)x);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000967}
968
969static PyObject *
970lu_longlong(const char *p, const formatdef *f)
971{
Bob Ippolito90bd0a52006-05-27 11:47:12 +0000972#ifdef HAVE_LONG_LONG
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000973 PY_LONG_LONG x = 0;
Bob Ippolitoaa70a172006-05-26 20:25:23 +0000974 Py_ssize_t i = f->size;
Bob Ippolito28b26862006-05-29 15:47:29 +0000975 const unsigned char *bytes = (const unsigned char *)p;
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000976 do {
Bob Ippolito28b26862006-05-29 15:47:29 +0000977 x = (x<<8) | bytes[--i];
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000978 } while (i > 0);
979 /* Extend the sign bit. */
980 if (SIZEOF_LONG_LONG > f->size)
Kristján Valur Jónsson67387fb2007-04-25 00:17:39 +0000981 x |= -(x & ((PY_LONG_LONG)1 << ((8 * f->size) - 1)));
Bob Ippolito04ab9942006-05-25 19:33:38 +0000982 if (x >= LONG_MIN && x <= LONG_MAX)
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000983 return PyInt_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long));
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000984 return PyLong_FromLongLong(x);
985#else
Bob Ippolito232f3c92006-05-23 19:12:41 +0000986 return _PyLong_FromByteArray((const unsigned char *)p,
987 8,
988 1, /* little-endian */
989 1 /* signed */);
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000990#endif
Bob Ippolito232f3c92006-05-23 19:12:41 +0000991}
992
993static PyObject *
994lu_ulonglong(const char *p, const formatdef *f)
995{
Bob Ippolito90bd0a52006-05-27 11:47:12 +0000996#ifdef HAVE_LONG_LONG
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000997 unsigned PY_LONG_LONG x = 0;
Bob Ippolitoaa70a172006-05-26 20:25:23 +0000998 Py_ssize_t i = f->size;
Bob Ippolito28b26862006-05-29 15:47:29 +0000999 const unsigned char *bytes = (const unsigned char *)p;
Bob Ippolito94f68ee2006-05-25 18:44:50 +00001000 do {
Bob Ippolito28b26862006-05-29 15:47:29 +00001001 x = (x<<8) | bytes[--i];
Bob Ippolito94f68ee2006-05-25 18:44:50 +00001002 } while (i > 0);
Bob Ippolito04ab9942006-05-25 19:33:38 +00001003 if (x <= LONG_MAX)
Bob Ippolito94f68ee2006-05-25 18:44:50 +00001004 return PyInt_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long));
Bob Ippolito94f68ee2006-05-25 18:44:50 +00001005 return PyLong_FromUnsignedLongLong(x);
1006#else
Bob Ippolito232f3c92006-05-23 19:12:41 +00001007 return _PyLong_FromByteArray((const unsigned char *)p,
1008 8,
1009 1, /* little-endian */
1010 0 /* signed */);
Bob Ippolito94f68ee2006-05-25 18:44:50 +00001011#endif
Bob Ippolito232f3c92006-05-23 19:12:41 +00001012}
1013
1014static PyObject *
1015lu_float(const char *p, const formatdef *f)
1016{
1017 return unpack_float(p, 1);
1018}
1019
1020static PyObject *
1021lu_double(const char *p, const formatdef *f)
1022{
1023 return unpack_double(p, 1);
1024}
1025
1026static int
1027lp_int(char *p, PyObject *v, const formatdef *f)
1028{
1029 long x;
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001030 Py_ssize_t i;
Mark Dickinson716a9cc2009-09-27 16:39:28 +00001031 if (get_long(v, &x) < 0)
Bob Ippolito232f3c92006-05-23 19:12:41 +00001032 return -1;
1033 i = f->size;
Bob Ippolitocd51ca52006-05-27 15:53:49 +00001034 if (i != SIZEOF_LONG) {
1035 if ((i == 2) && (x < -32768 || x > 32767))
Mark Dickinson5fd3af22009-07-07 15:08:28 +00001036 return _range_error(f, 0);
Bob Ippolito90bd0a52006-05-27 11:47:12 +00001037#if (SIZEOF_LONG != 4)
Bob Ippolitocd51ca52006-05-27 15:53:49 +00001038 else if ((i == 4) && (x < -2147483648L || x > 2147483647L))
Mark Dickinson5fd3af22009-07-07 15:08:28 +00001039 return _range_error(f, 0);
Bob Ippolitoe27337b2006-05-26 13:15:44 +00001040#endif
Bob Ippolitocd51ca52006-05-27 15:53:49 +00001041 }
Bob Ippolito232f3c92006-05-23 19:12:41 +00001042 do {
1043 *p++ = (char)x;
1044 x >>= 8;
1045 } while (--i > 0);
1046 return 0;
1047}
1048
1049static int
1050lp_uint(char *p, PyObject *v, const formatdef *f)
1051{
1052 unsigned long x;
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001053 Py_ssize_t i;
Mark Dickinson716a9cc2009-09-27 16:39:28 +00001054 if (get_ulong(v, &x) < 0)
Bob Ippolito232f3c92006-05-23 19:12:41 +00001055 return -1;
1056 i = f->size;
Bob Ippolitocd51ca52006-05-27 15:53:49 +00001057 if (i != SIZEOF_LONG) {
1058 unsigned long maxint = 1;
1059 maxint <<= (unsigned long)(i * 8);
1060 if (x >= maxint)
Mark Dickinson5fd3af22009-07-07 15:08:28 +00001061 return _range_error(f, 1);
Bob Ippolitocd51ca52006-05-27 15:53:49 +00001062 }
Bob Ippolito232f3c92006-05-23 19:12:41 +00001063 do {
1064 *p++ = (char)x;
1065 x >>= 8;
1066 } while (--i > 0);
1067 return 0;
1068}
1069
1070static int
1071lp_longlong(char *p, PyObject *v, const formatdef *f)
1072{
1073 int res;
1074 v = get_pylong(v);
1075 if (v == NULL)
1076 return -1;
1077 res = _PyLong_AsByteArray((PyLongObject*)v,
Mark Dickinson4f185222010-04-04 21:19:35 +00001078 (unsigned char *)p,
Bob Ippolito232f3c92006-05-23 19:12:41 +00001079 8,
1080 1, /* little_endian */
1081 1 /* signed */);
1082 Py_DECREF(v);
1083 return res;
1084}
1085
1086static int
1087lp_ulonglong(char *p, PyObject *v, const formatdef *f)
1088{
1089 int res;
1090 v = get_pylong(v);
1091 if (v == NULL)
1092 return -1;
1093 res = _PyLong_AsByteArray((PyLongObject*)v,
Mark Dickinson4f185222010-04-04 21:19:35 +00001094 (unsigned char *)p,
Bob Ippolito232f3c92006-05-23 19:12:41 +00001095 8,
1096 1, /* little_endian */
1097 0 /* signed */);
1098 Py_DECREF(v);
1099 return res;
1100}
1101
1102static int
1103lp_float(char *p, PyObject *v, const formatdef *f)
1104{
1105 double x = PyFloat_AsDouble(v);
1106 if (x == -1 && PyErr_Occurred()) {
1107 PyErr_SetString(StructError,
1108 "required argument is not a float");
1109 return -1;
1110 }
1111 return _PyFloat_Pack4(x, (unsigned char *)p, 1);
1112}
1113
1114static int
1115lp_double(char *p, PyObject *v, const formatdef *f)
1116{
1117 double x = PyFloat_AsDouble(v);
1118 if (x == -1 && PyErr_Occurred()) {
1119 PyErr_SetString(StructError,
1120 "required argument is not a float");
1121 return -1;
1122 }
1123 return _PyFloat_Pack8(x, (unsigned char *)p, 1);
1124}
1125
1126static formatdef lilendian_table[] = {
1127 {'x', 1, 0, NULL},
Bob Ippolitoe27337b2006-05-26 13:15:44 +00001128 {'b', 1, 0, nu_byte, np_byte},
1129 {'B', 1, 0, nu_ubyte, np_ubyte},
Bob Ippolito232f3c92006-05-23 19:12:41 +00001130 {'c', 1, 0, nu_char, np_char},
1131 {'s', 1, 0, NULL},
1132 {'p', 1, 0, NULL},
1133 {'h', 2, 0, lu_int, lp_int},
1134 {'H', 2, 0, lu_uint, lp_uint},
1135 {'i', 4, 0, lu_int, lp_int},
1136 {'I', 4, 0, lu_uint, lp_uint},
1137 {'l', 4, 0, lu_int, lp_int},
1138 {'L', 4, 0, lu_uint, lp_uint},
1139 {'q', 8, 0, lu_longlong, lp_longlong},
1140 {'Q', 8, 0, lu_ulonglong, lp_ulonglong},
Thomas Hellerf3c05592008-03-05 15:34:29 +00001141 {'?', 1, 0, bu_bool, bp_bool}, /* Std rep not endian dep,
Martin v. Löwisaef4c6b2007-01-21 09:33:07 +00001142 but potentially different from native rep -- reuse bx_bool funcs. */
Bob Ippolito232f3c92006-05-23 19:12:41 +00001143 {'f', 4, 0, lu_float, lp_float},
1144 {'d', 8, 0, lu_double, lp_double},
1145 {0}
1146};
1147
1148
1149static const formatdef *
1150whichtable(char **pfmt)
1151{
1152 const char *fmt = (*pfmt)++; /* May be backed out of later */
1153 switch (*fmt) {
1154 case '<':
1155 return lilendian_table;
1156 case '>':
1157 case '!': /* Network byte order is big-endian */
1158 return bigendian_table;
1159 case '=': { /* Host byte order -- different from native in aligment! */
1160 int n = 1;
1161 char *p = (char *) &n;
1162 if (*p == 1)
1163 return lilendian_table;
1164 else
1165 return bigendian_table;
1166 }
1167 default:
1168 --*pfmt; /* Back out of pointer increment */
1169 /* Fall through */
1170 case '@':
1171 return native_table;
1172 }
1173}
1174
1175
1176/* Get the table entry for a format code */
1177
1178static const formatdef *
1179getentry(int c, const formatdef *f)
1180{
1181 for (; f->format != '\0'; f++) {
1182 if (f->format == c) {
1183 return f;
1184 }
1185 }
1186 PyErr_SetString(StructError, "bad char in struct format");
1187 return NULL;
1188}
1189
1190
1191/* Align a size according to a format code */
1192
1193static int
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001194align(Py_ssize_t size, char c, const formatdef *e)
Bob Ippolito232f3c92006-05-23 19:12:41 +00001195{
1196 if (e->format == c) {
1197 if (e->alignment) {
1198 size = ((size + e->alignment - 1)
1199 / e->alignment)
1200 * e->alignment;
1201 }
1202 }
1203 return size;
1204}
1205
1206
1207/* calculate the size of a format string */
1208
1209static int
1210prepare_s(PyStructObject *self)
1211{
1212 const formatdef *f;
1213 const formatdef *e;
1214 formatcode *codes;
Tim Petersc2b550e2006-05-31 14:28:07 +00001215
Bob Ippolito232f3c92006-05-23 19:12:41 +00001216 const char *s;
1217 const char *fmt;
1218 char c;
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001219 Py_ssize_t size, len, num, itemsize, x;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001220
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001221 fmt = PyString_AS_STRING(self->s_format);
Bob Ippolito232f3c92006-05-23 19:12:41 +00001222
1223 f = whichtable((char **)&fmt);
Tim Petersc2b550e2006-05-31 14:28:07 +00001224
Bob Ippolito232f3c92006-05-23 19:12:41 +00001225 s = fmt;
1226 size = 0;
1227 len = 0;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001228 while ((c = *s++) != '\0') {
1229 if (isspace(Py_CHARMASK(c)))
1230 continue;
1231 if ('0' <= c && c <= '9') {
1232 num = c - '0';
1233 while ('0' <= (c = *s++) && c <= '9') {
1234 x = num*10 + (c - '0');
1235 if (x/10 != num) {
1236 PyErr_SetString(
1237 StructError,
1238 "overflow in item count");
1239 return -1;
1240 }
1241 num = x;
1242 }
1243 if (c == '\0')
1244 break;
1245 }
1246 else
1247 num = 1;
1248
1249 e = getentry(c, f);
1250 if (e == NULL)
1251 return -1;
Tim Petersc2b550e2006-05-31 14:28:07 +00001252
Bob Ippolito232f3c92006-05-23 19:12:41 +00001253 switch (c) {
1254 case 's': /* fall through */
1255 case 'p': len++; break;
1256 case 'x': break;
1257 default: len += num; break;
1258 }
Bob Ippolito232f3c92006-05-23 19:12:41 +00001259
1260 itemsize = e->size;
1261 size = align(size, c, e);
1262 x = num * itemsize;
1263 size += x;
1264 if (x/itemsize != num || size < 0) {
1265 PyErr_SetString(StructError,
1266 "total struct size too long");
1267 return -1;
1268 }
1269 }
1270
Gregory P. Smith9d534572008-06-11 07:41:16 +00001271 /* check for overflow */
1272 if ((len + 1) > (PY_SSIZE_T_MAX / sizeof(formatcode))) {
1273 PyErr_NoMemory();
1274 return -1;
1275 }
1276
Bob Ippolito232f3c92006-05-23 19:12:41 +00001277 self->s_size = size;
1278 self->s_len = len;
Bob Ippolitoeb621272006-05-24 15:32:06 +00001279 codes = PyMem_MALLOC((len + 1) * sizeof(formatcode));
Bob Ippolito232f3c92006-05-23 19:12:41 +00001280 if (codes == NULL) {
1281 PyErr_NoMemory();
1282 return -1;
1283 }
1284 self->s_codes = codes;
Tim Petersc2b550e2006-05-31 14:28:07 +00001285
Bob Ippolito232f3c92006-05-23 19:12:41 +00001286 s = fmt;
1287 size = 0;
1288 while ((c = *s++) != '\0') {
1289 if (isspace(Py_CHARMASK(c)))
1290 continue;
1291 if ('0' <= c && c <= '9') {
1292 num = c - '0';
1293 while ('0' <= (c = *s++) && c <= '9')
1294 num = num*10 + (c - '0');
1295 if (c == '\0')
1296 break;
1297 }
1298 else
1299 num = 1;
1300
1301 e = getentry(c, f);
Tim Petersc2b550e2006-05-31 14:28:07 +00001302
Bob Ippolito232f3c92006-05-23 19:12:41 +00001303 size = align(size, c, e);
Bob Ippolitoeb621272006-05-24 15:32:06 +00001304 if (c == 's' || c == 'p') {
Bob Ippolito232f3c92006-05-23 19:12:41 +00001305 codes->offset = size;
Bob Ippolitoeb621272006-05-24 15:32:06 +00001306 codes->size = num;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001307 codes->fmtdef = e;
1308 codes++;
Bob Ippolitoeb621272006-05-24 15:32:06 +00001309 size += num;
1310 } else if (c == 'x') {
1311 size += num;
1312 } else {
1313 while (--num >= 0) {
1314 codes->offset = size;
1315 codes->size = e->size;
1316 codes->fmtdef = e;
1317 codes++;
1318 size += e->size;
1319 }
Bob Ippolito232f3c92006-05-23 19:12:41 +00001320 }
Bob Ippolito232f3c92006-05-23 19:12:41 +00001321 }
1322 codes->fmtdef = NULL;
Bob Ippolitoeb621272006-05-24 15:32:06 +00001323 codes->offset = size;
1324 codes->size = 0;
Tim Petersc2b550e2006-05-31 14:28:07 +00001325
Bob Ippolito232f3c92006-05-23 19:12:41 +00001326 return 0;
1327}
1328
1329static PyObject *
1330s_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1331{
1332 PyObject *self;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001333
1334 assert(type != NULL && type->tp_alloc != NULL);
1335
1336 self = type->tp_alloc(type, 0);
1337 if (self != NULL) {
1338 PyStructObject *s = (PyStructObject*)self;
1339 Py_INCREF(Py_None);
1340 s->s_format = Py_None;
1341 s->s_codes = NULL;
1342 s->s_size = -1;
1343 s->s_len = -1;
1344 }
1345 return self;
1346}
1347
1348static int
1349s_init(PyObject *self, PyObject *args, PyObject *kwds)
1350{
1351 PyStructObject *soself = (PyStructObject *)self;
1352 PyObject *o_format = NULL;
1353 int ret = 0;
1354 static char *kwlist[] = {"format", 0};
1355
1356 assert(PyStruct_Check(self));
1357
1358 if (!PyArg_ParseTupleAndKeywords(args, kwds, "S:Struct", kwlist,
1359 &o_format))
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001360 return -1;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001361
1362 Py_INCREF(o_format);
Amaury Forgeot d'Arc588ff932008-02-16 14:34:57 +00001363 Py_CLEAR(soself->s_format);
Bob Ippolito232f3c92006-05-23 19:12:41 +00001364 soself->s_format = o_format;
Tim Petersc2b550e2006-05-31 14:28:07 +00001365
Bob Ippolito232f3c92006-05-23 19:12:41 +00001366 ret = prepare_s(soself);
1367 return ret;
1368}
1369
1370static void
1371s_dealloc(PyStructObject *s)
1372{
Bob Ippolito232f3c92006-05-23 19:12:41 +00001373 if (s->weakreflist != NULL)
1374 PyObject_ClearWeakRefs((PyObject *)s);
1375 if (s->s_codes != NULL) {
1376 PyMem_FREE(s->s_codes);
1377 }
1378 Py_XDECREF(s->s_format);
Christian Heimese93237d2007-12-19 02:37:44 +00001379 Py_TYPE(s)->tp_free((PyObject *)s);
Bob Ippolito232f3c92006-05-23 19:12:41 +00001380}
1381
Bob Ippolitoeb621272006-05-24 15:32:06 +00001382static PyObject *
1383s_unpack_internal(PyStructObject *soself, char *startfrom) {
1384 formatcode *code;
1385 Py_ssize_t i = 0;
1386 PyObject *result = PyTuple_New(soself->s_len);
1387 if (result == NULL)
1388 return NULL;
1389
1390 for (code = soself->s_codes; code->fmtdef != NULL; code++) {
1391 PyObject *v;
1392 const formatdef *e = code->fmtdef;
1393 const char *res = startfrom + code->offset;
1394 if (e->format == 's') {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001395 v = PyString_FromStringAndSize(res, code->size);
Bob Ippolitoeb621272006-05-24 15:32:06 +00001396 } else if (e->format == 'p') {
1397 Py_ssize_t n = *(unsigned char*)res;
1398 if (n >= code->size)
1399 n = code->size - 1;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001400 v = PyString_FromStringAndSize(res + 1, n);
Bob Ippolitoeb621272006-05-24 15:32:06 +00001401 } else {
1402 v = e->unpack(res, e);
Bob Ippolitoeb621272006-05-24 15:32:06 +00001403 }
Neal Norwitz3c5431e2006-06-11 05:45:25 +00001404 if (v == NULL)
1405 goto fail;
1406 PyTuple_SET_ITEM(result, i++, v);
Bob Ippolitoeb621272006-05-24 15:32:06 +00001407 }
1408
1409 return result;
1410fail:
1411 Py_DECREF(result);
1412 return NULL;
Bob Ippolitocd51ca52006-05-27 15:53:49 +00001413}
Bob Ippolitoeb621272006-05-24 15:32:06 +00001414
1415
Bob Ippolito232f3c92006-05-23 19:12:41 +00001416PyDoc_STRVAR(s_unpack__doc__,
Bob Ippolito1fcdc232006-05-27 12:11:36 +00001417"S.unpack(str) -> (v1, v2, ...)\n\
Bob Ippolito232f3c92006-05-23 19:12:41 +00001418\n\
1419Return tuple containing values unpacked according to this Struct's format.\n\
1420Requires len(str) == self.size. See struct.__doc__ for more on format\n\
1421strings.");
1422
1423static PyObject *
1424s_unpack(PyObject *self, PyObject *inputstr)
1425{
Raymond Hettinger7a3d41f2007-04-05 18:00:03 +00001426 char *start;
1427 Py_ssize_t len;
1428 PyObject *args=NULL, *result;
Bob Ippolitoeb621272006-05-24 15:32:06 +00001429 PyStructObject *soself = (PyStructObject *)self;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001430 assert(PyStruct_Check(self));
Tim Petersc2b550e2006-05-31 14:28:07 +00001431 assert(soself->s_codes != NULL);
Raymond Hettinger7a3d41f2007-04-05 18:00:03 +00001432 if (inputstr == NULL)
1433 goto fail;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001434 if (PyString_Check(inputstr) &&
1435 PyString_GET_SIZE(inputstr) == soself->s_size) {
1436 return s_unpack_internal(soself, PyString_AS_STRING(inputstr));
Bob Ippolito232f3c92006-05-23 19:12:41 +00001437 }
Raymond Hettinger7a3d41f2007-04-05 18:00:03 +00001438 args = PyTuple_Pack(1, inputstr);
1439 if (args == NULL)
1440 return NULL;
1441 if (!PyArg_ParseTuple(args, "s#:unpack", &start, &len))
1442 goto fail;
1443 if (soself->s_size != len)
1444 goto fail;
1445 result = s_unpack_internal(soself, start);
1446 Py_DECREF(args);
1447 return result;
1448
1449fail:
1450 Py_XDECREF(args);
1451 PyErr_Format(StructError,
1452 "unpack requires a string argument of length %zd",
1453 soself->s_size);
1454 return NULL;
Bob Ippolitoeb621272006-05-24 15:32:06 +00001455}
1456
1457PyDoc_STRVAR(s_unpack_from__doc__,
Bob Ippolito1fcdc232006-05-27 12:11:36 +00001458"S.unpack_from(buffer[, offset]) -> (v1, v2, ...)\n\
Bob Ippolitoeb621272006-05-24 15:32:06 +00001459\n\
1460Return tuple containing values unpacked according to this Struct's format.\n\
1461Unlike unpack, unpack_from can unpack values from any object supporting\n\
1462the buffer API, not just str. Requires len(buffer[offset:]) >= self.size.\n\
1463See struct.__doc__ for more on format strings.");
1464
1465static PyObject *
1466s_unpack_from(PyObject *self, PyObject *args, PyObject *kwds)
1467{
1468 static char *kwlist[] = {"buffer", "offset", 0};
1469#if (PY_VERSION_HEX < 0x02050000)
1470 static char *fmt = "z#|i:unpack_from";
1471#else
1472 static char *fmt = "z#|n:unpack_from";
1473#endif
1474 Py_ssize_t buffer_len = 0, offset = 0;
1475 char *buffer = NULL;
1476 PyStructObject *soself = (PyStructObject *)self;
1477 assert(PyStruct_Check(self));
1478 assert(soself->s_codes != NULL);
1479
1480 if (!PyArg_ParseTupleAndKeywords(args, kwds, fmt, kwlist,
1481 &buffer, &buffer_len, &offset))
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001482 return NULL;
Bob Ippolitoeb621272006-05-24 15:32:06 +00001483
1484 if (buffer == NULL) {
1485 PyErr_Format(StructError,
1486 "unpack_from requires a buffer argument");
Bob Ippolito232f3c92006-05-23 19:12:41 +00001487 return NULL;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001488 }
Tim Petersc2b550e2006-05-31 14:28:07 +00001489
Bob Ippolitoeb621272006-05-24 15:32:06 +00001490 if (offset < 0)
1491 offset += buffer_len;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001492
Bob Ippolitoeb621272006-05-24 15:32:06 +00001493 if (offset < 0 || (buffer_len - offset) < soself->s_size) {
1494 PyErr_Format(StructError,
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001495 "unpack_from requires a buffer of at least %zd bytes",
Bob Ippolitoeb621272006-05-24 15:32:06 +00001496 soself->s_size);
1497 return NULL;
1498 }
1499 return s_unpack_internal(soself, buffer + offset);
1500}
Bob Ippolito232f3c92006-05-23 19:12:41 +00001501
Bob Ippolito232f3c92006-05-23 19:12:41 +00001502
Martin Blais2856e5f2006-05-26 12:03:27 +00001503/*
1504 * Guts of the pack function.
1505 *
1506 * Takes a struct object, a tuple of arguments, and offset in that tuple of
1507 * argument for where to start processing the arguments for packing, and a
1508 * character buffer for writing the packed string. The caller must insure
1509 * that the buffer may contain the required length for packing the arguments.
1510 * 0 is returned on success, 1 is returned if there is an error.
1511 *
1512 */
1513static int
1514s_pack_internal(PyStructObject *soself, PyObject *args, int offset, char* buf)
Bob Ippolito232f3c92006-05-23 19:12:41 +00001515{
Bob Ippolito232f3c92006-05-23 19:12:41 +00001516 formatcode *code;
Neal Norwitz3c5431e2006-06-11 05:45:25 +00001517 /* XXX(nnorwitz): why does i need to be a local? can we use
1518 the offset parameter or do we need the wider width? */
Bob Ippolito232f3c92006-05-23 19:12:41 +00001519 Py_ssize_t i;
Martin Blais2856e5f2006-05-26 12:03:27 +00001520
1521 memset(buf, '\0', soself->s_size);
1522 i = offset;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001523 for (code = soself->s_codes; code->fmtdef != NULL; code++) {
1524 Py_ssize_t n;
Neal Norwitz3c5431e2006-06-11 05:45:25 +00001525 PyObject *v = PyTuple_GET_ITEM(args, i++);
Bob Ippolito232f3c92006-05-23 19:12:41 +00001526 const formatdef *e = code->fmtdef;
Martin Blais2856e5f2006-05-26 12:03:27 +00001527 char *res = buf + code->offset;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001528 if (e->format == 's') {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001529 if (!PyString_Check(v)) {
Bob Ippolito232f3c92006-05-23 19:12:41 +00001530 PyErr_SetString(StructError,
Mark Dickinson5fd3af22009-07-07 15:08:28 +00001531 "argument for 's' must "
1532 "be a string");
Martin Blais2856e5f2006-05-26 12:03:27 +00001533 return -1;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001534 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001535 n = PyString_GET_SIZE(v);
Bob Ippolitoeb621272006-05-24 15:32:06 +00001536 if (n > code->size)
1537 n = code->size;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001538 if (n > 0)
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001539 memcpy(res, PyString_AS_STRING(v), n);
Bob Ippolito232f3c92006-05-23 19:12:41 +00001540 } else if (e->format == 'p') {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001541 if (!PyString_Check(v)) {
Bob Ippolito232f3c92006-05-23 19:12:41 +00001542 PyErr_SetString(StructError,
Mark Dickinson5fd3af22009-07-07 15:08:28 +00001543 "argument for 'p' must "
1544 "be a string");
Martin Blais2856e5f2006-05-26 12:03:27 +00001545 return -1;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001546 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001547 n = PyString_GET_SIZE(v);
Bob Ippolitoeb621272006-05-24 15:32:06 +00001548 if (n > (code->size - 1))
1549 n = code->size - 1;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001550 if (n > 0)
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001551 memcpy(res + 1, PyString_AS_STRING(v), n);
Bob Ippolito232f3c92006-05-23 19:12:41 +00001552 if (n > 255)
1553 n = 255;
1554 *res = Py_SAFE_DOWNCAST(n, Py_ssize_t, unsigned char);
Mark Dickinson5fd3af22009-07-07 15:08:28 +00001555 } else if (e->pack(res, v, e) < 0) {
1556 if (strchr(integer_codes, e->format) != NULL &&
1557 PyErr_ExceptionMatches(PyExc_OverflowError))
1558 PyErr_Format(StructError,
1559 "integer out of range for "
1560 "'%c' format code",
1561 e->format);
1562 return -1;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001563 }
1564 }
Tim Petersc2b550e2006-05-31 14:28:07 +00001565
Martin Blais2856e5f2006-05-26 12:03:27 +00001566 /* Success */
1567 return 0;
1568}
Bob Ippolito232f3c92006-05-23 19:12:41 +00001569
Martin Blais2856e5f2006-05-26 12:03:27 +00001570
1571PyDoc_STRVAR(s_pack__doc__,
Bob Ippolito1fcdc232006-05-27 12:11:36 +00001572"S.pack(v1, v2, ...) -> string\n\
Martin Blais2856e5f2006-05-26 12:03:27 +00001573\n\
1574Return a string containing values v1, v2, ... packed according to this\n\
1575Struct's format. See struct.__doc__ for more on format strings.");
1576
1577static PyObject *
1578s_pack(PyObject *self, PyObject *args)
1579{
1580 PyStructObject *soself;
1581 PyObject *result;
1582
1583 /* Validate arguments. */
1584 soself = (PyStructObject *)self;
1585 assert(PyStruct_Check(self));
1586 assert(soself->s_codes != NULL);
Martin Blaisaf2ae722006-06-04 13:49:49 +00001587 if (PyTuple_GET_SIZE(args) != soself->s_len)
Martin Blais2856e5f2006-05-26 12:03:27 +00001588 {
1589 PyErr_Format(StructError,
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001590 "pack requires exactly %zd arguments", soself->s_len);
Martin Blais2856e5f2006-05-26 12:03:27 +00001591 return NULL;
1592 }
Tim Petersc2b550e2006-05-31 14:28:07 +00001593
Martin Blais2856e5f2006-05-26 12:03:27 +00001594 /* Allocate a new string */
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001595 result = PyString_FromStringAndSize((char *)NULL, soself->s_size);
Martin Blais2856e5f2006-05-26 12:03:27 +00001596 if (result == NULL)
1597 return NULL;
Tim Petersc2b550e2006-05-31 14:28:07 +00001598
Martin Blais2856e5f2006-05-26 12:03:27 +00001599 /* Call the guts */
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001600 if ( s_pack_internal(soself, args, 0, PyString_AS_STRING(result)) != 0 ) {
Martin Blais2856e5f2006-05-26 12:03:27 +00001601 Py_DECREF(result);
1602 return NULL;
1603 }
1604
1605 return result;
1606}
1607
Martin Blaisaf2ae722006-06-04 13:49:49 +00001608PyDoc_STRVAR(s_pack_into__doc__,
1609"S.pack_into(buffer, offset, v1, v2, ...)\n\
Martin Blais2856e5f2006-05-26 12:03:27 +00001610\n\
Martin Blaisaf2ae722006-06-04 13:49:49 +00001611Pack the values v1, v2, ... according to this Struct's format, write \n\
Bob Ippolito1fcdc232006-05-27 12:11:36 +00001612the packed bytes into the writable buffer buf starting at offset. Note\n\
1613that the offset is not an optional argument. See struct.__doc__ for \n\
Martin Blais2856e5f2006-05-26 12:03:27 +00001614more on format strings.");
1615
1616static PyObject *
Martin Blaisaf2ae722006-06-04 13:49:49 +00001617s_pack_into(PyObject *self, PyObject *args)
Martin Blais2856e5f2006-05-26 12:03:27 +00001618{
1619 PyStructObject *soself;
1620 char *buffer;
1621 Py_ssize_t buffer_len, offset;
1622
1623 /* Validate arguments. +1 is for the first arg as buffer. */
1624 soself = (PyStructObject *)self;
1625 assert(PyStruct_Check(self));
1626 assert(soself->s_codes != NULL);
Martin Blaisaf2ae722006-06-04 13:49:49 +00001627 if (PyTuple_GET_SIZE(args) != (soself->s_len + 2))
Martin Blais2856e5f2006-05-26 12:03:27 +00001628 {
1629 PyErr_Format(StructError,
Martin Blaisaf2ae722006-06-04 13:49:49 +00001630 "pack_into requires exactly %zd arguments",
Martin Blais2856e5f2006-05-26 12:03:27 +00001631 (soself->s_len + 2));
1632 return NULL;
1633 }
1634
1635 /* Extract a writable memory buffer from the first argument */
Tim Petersc2b550e2006-05-31 14:28:07 +00001636 if ( PyObject_AsWriteBuffer(PyTuple_GET_ITEM(args, 0),
1637 (void**)&buffer, &buffer_len) == -1 ) {
Martin Blais2856e5f2006-05-26 12:03:27 +00001638 return NULL;
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001639 }
1640 assert( buffer_len >= 0 );
Martin Blais2856e5f2006-05-26 12:03:27 +00001641
1642 /* Extract the offset from the first argument */
Martin Blaisaf2ae722006-06-04 13:49:49 +00001643 offset = PyInt_AsSsize_t(PyTuple_GET_ITEM(args, 1));
Benjamin Peterson02252482008-09-30 02:11:07 +00001644 if (offset == -1 && PyErr_Occurred())
1645 return NULL;
Martin Blais2856e5f2006-05-26 12:03:27 +00001646
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001647 /* Support negative offsets. */
Martin Blais2856e5f2006-05-26 12:03:27 +00001648 if (offset < 0)
1649 offset += buffer_len;
1650
1651 /* Check boundaries */
1652 if (offset < 0 || (buffer_len - offset) < soself->s_size) {
1653 PyErr_Format(StructError,
Martin Blaisaf2ae722006-06-04 13:49:49 +00001654 "pack_into requires a buffer of at least %zd bytes",
Martin Blais2856e5f2006-05-26 12:03:27 +00001655 soself->s_size);
1656 return NULL;
1657 }
Tim Petersc2b550e2006-05-31 14:28:07 +00001658
Martin Blais2856e5f2006-05-26 12:03:27 +00001659 /* Call the guts */
1660 if ( s_pack_internal(soself, args, 2, buffer + offset) != 0 ) {
1661 return NULL;
1662 }
1663
Georg Brandlc26025c2006-05-28 21:42:54 +00001664 Py_RETURN_NONE;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001665}
1666
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001667static PyObject *
1668s_get_format(PyStructObject *self, void *unused)
1669{
1670 Py_INCREF(self->s_format);
1671 return self->s_format;
1672}
1673
1674static PyObject *
1675s_get_size(PyStructObject *self, void *unused)
1676{
1677 return PyInt_FromSsize_t(self->s_size);
1678}
Bob Ippolito232f3c92006-05-23 19:12:41 +00001679
1680/* List of functions */
1681
1682static struct PyMethodDef s_methods[] = {
Martin Blaisaf2ae722006-06-04 13:49:49 +00001683 {"pack", s_pack, METH_VARARGS, s_pack__doc__},
1684 {"pack_into", s_pack_into, METH_VARARGS, s_pack_into__doc__},
1685 {"unpack", s_unpack, METH_O, s_unpack__doc__},
Neal Norwitza84dcd72007-05-22 07:16:44 +00001686 {"unpack_from", (PyCFunction)s_unpack_from, METH_VARARGS|METH_KEYWORDS,
Tim Peters5ec2e852006-06-04 15:49:07 +00001687 s_unpack_from__doc__},
Bob Ippolito232f3c92006-05-23 19:12:41 +00001688 {NULL, NULL} /* sentinel */
1689};
1690
1691PyDoc_STRVAR(s__doc__, "Compiled struct object");
1692
1693#define OFF(x) offsetof(PyStructObject, x)
1694
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001695static PyGetSetDef s_getsetlist[] = {
Bob Ippolito1fcdc232006-05-27 12:11:36 +00001696 {"format", (getter)s_get_format, (setter)NULL, "struct format string", NULL},
1697 {"size", (getter)s_get_size, (setter)NULL, "struct size in bytes", NULL},
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001698 {NULL} /* sentinel */
Bob Ippolito232f3c92006-05-23 19:12:41 +00001699};
1700
Bob Ippolito232f3c92006-05-23 19:12:41 +00001701static
1702PyTypeObject PyStructType = {
Martin v. Löwis68192102007-07-21 06:55:02 +00001703 PyVarObject_HEAD_INIT(NULL, 0)
Bob Ippolito232f3c92006-05-23 19:12:41 +00001704 "Struct",
1705 sizeof(PyStructObject),
1706 0,
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001707 (destructor)s_dealloc, /* tp_dealloc */
Bob Ippolito232f3c92006-05-23 19:12:41 +00001708 0, /* tp_print */
1709 0, /* tp_getattr */
1710 0, /* tp_setattr */
1711 0, /* tp_compare */
1712 0, /* tp_repr */
1713 0, /* tp_as_number */
1714 0, /* tp_as_sequence */
1715 0, /* tp_as_mapping */
1716 0, /* tp_hash */
1717 0, /* tp_call */
1718 0, /* tp_str */
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001719 PyObject_GenericGetAttr, /* tp_getattro */
1720 PyObject_GenericSetAttr, /* tp_setattro */
Bob Ippolito232f3c92006-05-23 19:12:41 +00001721 0, /* tp_as_buffer */
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001722 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_WEAKREFS,/* tp_flags */
1723 s__doc__, /* tp_doc */
Bob Ippolito232f3c92006-05-23 19:12:41 +00001724 0, /* tp_traverse */
1725 0, /* tp_clear */
1726 0, /* tp_richcompare */
1727 offsetof(PyStructObject, weakreflist), /* tp_weaklistoffset */
1728 0, /* tp_iter */
1729 0, /* tp_iternext */
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001730 s_methods, /* tp_methods */
1731 NULL, /* tp_members */
1732 s_getsetlist, /* tp_getset */
Bob Ippolito232f3c92006-05-23 19:12:41 +00001733 0, /* tp_base */
1734 0, /* tp_dict */
1735 0, /* tp_descr_get */
1736 0, /* tp_descr_set */
1737 0, /* tp_dictoffset */
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001738 s_init, /* tp_init */
1739 PyType_GenericAlloc,/* tp_alloc */
1740 s_new, /* tp_new */
1741 PyObject_Del, /* tp_free */
Bob Ippolito232f3c92006-05-23 19:12:41 +00001742};
1743
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001744
1745/* ---- Standalone functions ---- */
1746
1747#define MAXCACHE 100
Christian Heimes76d19f62008-01-04 02:54:42 +00001748static PyObject *cache = NULL;
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001749
1750static PyObject *
1751cache_struct(PyObject *fmt)
1752{
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001753 PyObject * s_object;
1754
1755 if (cache == NULL) {
1756 cache = PyDict_New();
1757 if (cache == NULL)
1758 return NULL;
1759 }
1760
1761 s_object = PyDict_GetItem(cache, fmt);
1762 if (s_object != NULL) {
1763 Py_INCREF(s_object);
1764 return s_object;
1765 }
1766
1767 s_object = PyObject_CallFunctionObjArgs((PyObject *)(&PyStructType), fmt, NULL);
1768 if (s_object != NULL) {
1769 if (PyDict_Size(cache) >= MAXCACHE)
1770 PyDict_Clear(cache);
1771 /* Attempt to cache the result */
1772 if (PyDict_SetItem(cache, fmt, s_object) == -1)
1773 PyErr_Clear();
1774 }
1775 return s_object;
1776}
1777
Christian Heimes76d19f62008-01-04 02:54:42 +00001778PyDoc_STRVAR(clearcache_doc,
1779"Clear the internal cache.");
1780
1781static PyObject *
1782clearcache(PyObject *self)
1783{
Raymond Hettinger18e08e52008-01-18 00:10:42 +00001784 Py_CLEAR(cache);
Christian Heimes76d19f62008-01-04 02:54:42 +00001785 Py_RETURN_NONE;
1786}
1787
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001788PyDoc_STRVAR(calcsize_doc,
1789"Return size of C struct described by format string fmt.");
1790
1791static PyObject *
1792calcsize(PyObject *self, PyObject *fmt)
1793{
1794 Py_ssize_t n;
1795 PyObject *s_object = cache_struct(fmt);
1796 if (s_object == NULL)
1797 return NULL;
1798 n = ((PyStructObject *)s_object)->s_size;
1799 Py_DECREF(s_object);
Mark Dickinson4f185222010-04-04 21:19:35 +00001800 return PyInt_FromSsize_t(n);
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001801}
1802
1803PyDoc_STRVAR(pack_doc,
1804"Return string containing values v1, v2, ... packed according to fmt.");
1805
1806static PyObject *
1807pack(PyObject *self, PyObject *args)
1808{
1809 PyObject *s_object, *fmt, *newargs, *result;
1810 Py_ssize_t n = PyTuple_GET_SIZE(args);
1811
1812 if (n == 0) {
1813 PyErr_SetString(PyExc_TypeError, "missing format argument");
1814 return NULL;
1815 }
1816 fmt = PyTuple_GET_ITEM(args, 0);
1817 newargs = PyTuple_GetSlice(args, 1, n);
1818 if (newargs == NULL)
1819 return NULL;
1820
1821 s_object = cache_struct(fmt);
1822 if (s_object == NULL) {
1823 Py_DECREF(newargs);
1824 return NULL;
1825 }
Mark Dickinson4f185222010-04-04 21:19:35 +00001826 result = s_pack(s_object, newargs);
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001827 Py_DECREF(newargs);
1828 Py_DECREF(s_object);
1829 return result;
1830}
1831
1832PyDoc_STRVAR(pack_into_doc,
1833"Pack the values v1, v2, ... according to fmt.\n\
1834Write the packed bytes into the writable buffer buf starting at offset.");
1835
1836static PyObject *
1837pack_into(PyObject *self, PyObject *args)
1838{
1839 PyObject *s_object, *fmt, *newargs, *result;
1840 Py_ssize_t n = PyTuple_GET_SIZE(args);
1841
1842 if (n == 0) {
1843 PyErr_SetString(PyExc_TypeError, "missing format argument");
1844 return NULL;
1845 }
1846 fmt = PyTuple_GET_ITEM(args, 0);
1847 newargs = PyTuple_GetSlice(args, 1, n);
1848 if (newargs == NULL)
1849 return NULL;
1850
1851 s_object = cache_struct(fmt);
1852 if (s_object == NULL) {
1853 Py_DECREF(newargs);
1854 return NULL;
1855 }
Mark Dickinson4f185222010-04-04 21:19:35 +00001856 result = s_pack_into(s_object, newargs);
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001857 Py_DECREF(newargs);
1858 Py_DECREF(s_object);
1859 return result;
1860}
1861
1862PyDoc_STRVAR(unpack_doc,
1863"Unpack the string containing packed C structure data, according to fmt.\n\
1864Requires len(string) == calcsize(fmt).");
1865
1866static PyObject *
1867unpack(PyObject *self, PyObject *args)
1868{
1869 PyObject *s_object, *fmt, *inputstr, *result;
1870
1871 if (!PyArg_UnpackTuple(args, "unpack", 2, 2, &fmt, &inputstr))
1872 return NULL;
1873
1874 s_object = cache_struct(fmt);
1875 if (s_object == NULL)
1876 return NULL;
Mark Dickinson4f185222010-04-04 21:19:35 +00001877 result = s_unpack(s_object, inputstr);
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001878 Py_DECREF(s_object);
1879 return result;
1880}
1881
1882PyDoc_STRVAR(unpack_from_doc,
1883"Unpack the buffer, containing packed C structure data, according to\n\
1884fmt, starting at offset. Requires len(buffer[offset:]) >= calcsize(fmt).");
1885
1886static PyObject *
1887unpack_from(PyObject *self, PyObject *args, PyObject *kwds)
1888{
1889 PyObject *s_object, *fmt, *newargs, *result;
1890 Py_ssize_t n = PyTuple_GET_SIZE(args);
1891
1892 if (n == 0) {
1893 PyErr_SetString(PyExc_TypeError, "missing format argument");
1894 return NULL;
1895 }
1896 fmt = PyTuple_GET_ITEM(args, 0);
1897 newargs = PyTuple_GetSlice(args, 1, n);
1898 if (newargs == NULL)
1899 return NULL;
1900
1901 s_object = cache_struct(fmt);
1902 if (s_object == NULL) {
1903 Py_DECREF(newargs);
1904 return NULL;
1905 }
Mark Dickinson4f185222010-04-04 21:19:35 +00001906 result = s_unpack_from(s_object, newargs, kwds);
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001907 Py_DECREF(newargs);
1908 Py_DECREF(s_object);
1909 return result;
1910}
1911
1912static struct PyMethodDef module_functions[] = {
Mark Dickinson4f185222010-04-04 21:19:35 +00001913 {"_clearcache", (PyCFunction)clearcache, METH_NOARGS, clearcache_doc},
1914 {"calcsize", calcsize, METH_O, calcsize_doc},
1915 {"pack", pack, METH_VARARGS, pack_doc},
1916 {"pack_into", pack_into, METH_VARARGS, pack_into_doc},
1917 {"unpack", unpack, METH_VARARGS, unpack_doc},
1918 {"unpack_from", (PyCFunction)unpack_from,
1919 METH_VARARGS|METH_KEYWORDS, unpack_from_doc},
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001920 {NULL, NULL} /* sentinel */
1921};
1922
1923
Bob Ippolito232f3c92006-05-23 19:12:41 +00001924/* Module initialization */
1925
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001926PyDoc_STRVAR(module_doc,
Mark Dickinson3d830822009-10-08 15:54:10 +00001927"Functions to convert between Python values and C structs represented\n\
1928as Python strings. It uses format strings (explained below) as compact\n\
1929descriptions of the lay-out of the C structs and the intended conversion\n\
1930to/from Python values.\n\
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001931\n\
1932The optional first format char indicates byte order, size and alignment:\n\
Mark Dickinson3d830822009-10-08 15:54:10 +00001933 @: native order, size & alignment (default)\n\
1934 =: native order, std. size & alignment\n\
1935 <: little-endian, std. size & alignment\n\
1936 >: big-endian, std. size & alignment\n\
1937 !: same as >\n\
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001938\n\
1939The remaining chars indicate types of args and must match exactly;\n\
1940these can be preceded by a decimal repeat count:\n\
1941 x: pad byte (no data); c:char; b:signed byte; B:unsigned byte;\n\
Mark Dickinson3d830822009-10-08 15:54:10 +00001942 ?: _Bool (requires C99; if not available, char is used instead)\n\
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001943 h:short; H:unsigned short; i:int; I:unsigned int;\n\
1944 l:long; L:unsigned long; f:float; d:double.\n\
1945Special cases (preceding decimal count indicates length):\n\
1946 s:string (array of char); p: pascal string (with count byte).\n\
1947Special case (only available in native format):\n\
1948 P:an integer type that is wide enough to hold a pointer.\n\
1949Special case (not in native mode unless 'long long' in platform C):\n\
1950 q:long long; Q:unsigned long long\n\
1951Whitespace between formats is ignored.\n\
1952\n\
1953The variable struct.error is an exception raised on errors.\n");
1954
Bob Ippolito232f3c92006-05-23 19:12:41 +00001955PyMODINIT_FUNC
1956init_struct(void)
1957{
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001958 PyObject *ver, *m;
1959
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001960 ver = PyString_FromString("0.2");
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001961 if (ver == NULL)
1962 return;
1963
1964 m = Py_InitModule3("_struct", module_functions, module_doc);
Bob Ippolito232f3c92006-05-23 19:12:41 +00001965 if (m == NULL)
1966 return;
1967
Christian Heimese93237d2007-12-19 02:37:44 +00001968 Py_TYPE(&PyStructType) = &PyType_Type;
Bob Ippolito3fc2bb92006-05-25 19:03:19 +00001969 if (PyType_Ready(&PyStructType) < 0)
1970 return;
1971
Mark Dickinson5fd3af22009-07-07 15:08:28 +00001972 /* This speed trick can't be used until overflow masking goes
1973 away, because native endian always raises exceptions
1974 instead of overflow masking. */
Tim Petersc2b550e2006-05-31 14:28:07 +00001975
Bob Ippolitoa99865b2006-05-25 19:56:56 +00001976 /* Check endian and swap in faster functions */
1977 {
1978 int one = 1;
1979 formatdef *native = native_table;
1980 formatdef *other, *ptr;
1981 if ((int)*(unsigned char*)&one)
1982 other = lilendian_table;
1983 else
1984 other = bigendian_table;
Bob Ippolito964e02a2006-05-25 21:09:45 +00001985 /* Scan through the native table, find a matching
1986 entry in the endian table and swap in the
1987 native implementations whenever possible
1988 (64-bit platforms may not have "standard" sizes) */
Bob Ippolitoa99865b2006-05-25 19:56:56 +00001989 while (native->format != '\0' && other->format != '\0') {
1990 ptr = other;
1991 while (ptr->format != '\0') {
1992 if (ptr->format == native->format) {
Bob Ippolito964e02a2006-05-25 21:09:45 +00001993 /* Match faster when formats are
1994 listed in the same order */
Bob Ippolitoa99865b2006-05-25 19:56:56 +00001995 if (ptr == other)
1996 other++;
Tim Petersc2b550e2006-05-31 14:28:07 +00001997 /* Only use the trick if the
Bob Ippolito964e02a2006-05-25 21:09:45 +00001998 size matches */
1999 if (ptr->size != native->size)
2000 break;
2001 /* Skip float and double, could be
2002 "unknown" float format */
2003 if (ptr->format == 'd' || ptr->format == 'f')
2004 break;
2005 ptr->pack = native->pack;
2006 ptr->unpack = native->unpack;
Bob Ippolitoa99865b2006-05-25 19:56:56 +00002007 break;
2008 }
2009 ptr++;
2010 }
2011 native++;
2012 }
2013 }
Tim Petersc2b550e2006-05-31 14:28:07 +00002014
Bob Ippolito232f3c92006-05-23 19:12:41 +00002015 /* Add some symbolic constants to the module */
2016 if (StructError == NULL) {
2017 StructError = PyErr_NewException("struct.error", NULL, NULL);
2018 if (StructError == NULL)
2019 return;
2020 }
Bob Ippolito04ab9942006-05-25 19:33:38 +00002021
Bob Ippolito232f3c92006-05-23 19:12:41 +00002022 Py_INCREF(StructError);
2023 PyModule_AddObject(m, "error", StructError);
Bob Ippolito04ab9942006-05-25 19:33:38 +00002024
Bob Ippolito232f3c92006-05-23 19:12:41 +00002025 Py_INCREF((PyObject*)&PyStructType);
2026 PyModule_AddObject(m, "Struct", (PyObject*)&PyStructType);
Tim Petersc2b550e2006-05-31 14:28:07 +00002027
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00002028 PyModule_AddObject(m, "__version__", ver);
2029
Bob Ippolito2fd39772006-05-29 22:55:48 +00002030 PyModule_AddIntConstant(m, "_PY_STRUCT_RANGE_CHECKING", 1);
Bob Ippolitoe6c9f982006-08-04 23:59:21 +00002031 PyModule_AddIntConstant(m, "_PY_STRUCT_FLOAT_COERCE", 1);
Bob Ippolito232f3c92006-05-23 19:12:41 +00002032}