blob: 2eb461f4f9d46d92050c03080b203ccc1b3cd664 [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 " \
Antoine Pitrouc83ea132010-05-09 14:46:46 +000023 "(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 {
Antoine Pitrouc83ea132010-05-09 14:46:46 +000028 char format;
29 Py_ssize_t size;
30 Py_ssize_t alignment;
31 PyObject* (*unpack)(const char *,
32 const struct _formatdef *);
33 int (*pack)(char *, PyObject *,
34 const struct _formatdef *);
Bob Ippolito232f3c92006-05-23 19:12:41 +000035} formatdef;
36
37typedef struct _formatcode {
Antoine Pitrouc83ea132010-05-09 14:46:46 +000038 const struct _formatdef *fmtdef;
39 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 {
Antoine Pitrouc83ea132010-05-09 14:46:46 +000046 PyObject_HEAD
47 Py_ssize_t s_size;
48 Py_ssize_t s_len;
49 formatcode *s_codes;
50 PyObject *s_format;
51 PyObject *weakreflist; /* List of weak references */
Bob Ippolito232f3c92006-05-23 19:12:41 +000052} 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{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000110 PyObject *r, *w;
111 int converted = 0;
112 assert(v != NULL);
113 if (!PyInt_Check(v) && !PyLong_Check(v)) {
114 PyNumberMethods *m;
115 /* 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
119 Python 3.x. */
Mark Dickinson4846a8e2010-04-03 14:05:10 +0000120
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000121 m = Py_TYPE(v)->tp_as_number;
122 if (PyIndex_Check(v)) {
123 w = PyNumber_Index(v);
124 if (w != NULL) {
125 v = w;
126 /* 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) {
136 /* Special case warning message for floats, for
137 backwards compatibility. */
138 if (PyFloat_Check(v)) {
139 if (PyErr_WarnEx(
140 PyExc_DeprecationWarning,
141 FLOAT_COERCE_WARN, 1))
142 return NULL;
143 }
144 else {
145 if (PyErr_WarnEx(
146 PyExc_DeprecationWarning,
147 NON_INTEGER_WARN, 1))
148 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,
155 "__int__ method returned "
156 "non-integer");
157 return NULL;
158 }
159 converted = 1;
160 }
161 if (!converted) {
162 PyErr_SetString(StructError,
163 "cannot convert argument "
164 "to integer");
165 return NULL;
166 }
167 }
168 else
169 /* Ensure we own a reference to v. */
170 Py_INCREF(v);
Mark Dickinson154b7ad2010-03-07 16:24:45 +0000171
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000172 assert(PyInt_Check(v) || PyLong_Check(v));
173 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 }
181 else {
182 r = NULL; /* silence compiler warning about
183 possibly uninitialized variable */
184 assert(0); /* shouldn't ever get here */
185 }
Mark Dickinson154b7ad2010-03-07 16:24:45 +0000186
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000187 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{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000197 long x;
Mark Dickinson463dc4b2009-07-05 10:01:24 +0000198
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000199 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);
205 if (x == (long)-1 && PyErr_Occurred())
206 return -1;
207 *p = x;
208 return 0;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000209}
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{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000216 unsigned long x;
Mark Dickinson463dc4b2009-07-05 10:01:24 +0000217
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000218 v = get_pylong(v);
219 if (v == NULL)
220 return -1;
221 assert(PyLong_Check(v));
222 x = PyLong_AsUnsignedLong(v);
223 Py_DECREF(v);
224 if (x == (unsigned long)-1 && PyErr_Occurred())
225 return -1;
226 *p = x;
227 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{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000237 PY_LONG_LONG x;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000238
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000239 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);
245 if (x == (PY_LONG_LONG)-1 && PyErr_Occurred())
246 return -1;
247 *p = x;
248 return 0;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000249}
250
251/* Same, but handling native unsigned long long. */
252
253static int
254get_ulonglong(PyObject *v, unsigned PY_LONG_LONG *p)
255{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000256 unsigned PY_LONG_LONG x;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000257
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000258 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);
264 if (x == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred())
265 return -1;
266 *p = x;
267 return 0;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000268}
269
270#endif
271
272/* Floating point helpers */
273
274static PyObject *
275unpack_float(const char *p, /* start of 4-byte string */
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000276 int le) /* true for little-endian, false for big-endian */
Bob Ippolito232f3c92006-05-23 19:12:41 +0000277{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000278 double x;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000279
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000280 x = _PyFloat_Unpack4((unsigned char *)p, le);
281 if (x == -1.0 && PyErr_Occurred())
282 return NULL;
283 return PyFloat_FromDouble(x);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000284}
285
286static PyObject *
287unpack_double(const char *p, /* start of 8-byte string */
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000288 int le) /* true for little-endian, false for big-endian */
Bob Ippolito232f3c92006-05-23 19:12:41 +0000289{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000290 double x;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000291
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000292 x = _PyFloat_Unpack8((unsigned char *)p, le);
293 if (x == -1.0 && PyErr_Occurred())
294 return NULL;
295 return PyFloat_FromDouble(x);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000296}
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{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000302 /* ulargest is the largest unsigned value with f->size bytes.
303 * Note that the simpler:
304 * ((size_t)1 << (f->size * 8)) - 1
305 * 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.
309 */
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)
313 PyErr_Format(StructError,
314 "'%c' format requires 0 <= number <= %zu",
315 f->format,
316 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,
323 largest);
324 }
325 return -1;
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000326}
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{
Antoine Pitrouc83ea132010-05-09 14:46:46 +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{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000358 return PyInt_FromLong((long) *(signed char *)p);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000359}
360
361static PyObject *
362nu_ubyte(const char *p, const formatdef *f)
363{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000364 return PyInt_FromLong((long) *(unsigned char *)p);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000365}
366
367static PyObject *
368nu_short(const char *p, const formatdef *f)
369{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000370 short x;
371 memcpy((char *)&x, p, sizeof x);
372 return PyInt_FromLong((long)x);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000373}
374
375static PyObject *
376nu_ushort(const char *p, const formatdef *f)
377{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000378 unsigned short x;
379 memcpy((char *)&x, p, sizeof x);
380 return PyInt_FromLong((long)x);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000381}
382
383static PyObject *
384nu_int(const char *p, const formatdef *f)
385{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000386 int x;
387 memcpy((char *)&x, p, sizeof x);
388 return PyInt_FromLong((long)x);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000389}
390
391static PyObject *
392nu_uint(const char *p, const formatdef *f)
393{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000394 unsigned int x;
395 memcpy((char *)&x, p, sizeof x);
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000396#if (SIZEOF_LONG > SIZEOF_INT)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000397 return PyInt_FromLong((long)x);
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000398#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000399 if (x <= ((unsigned int)LONG_MAX))
400 return PyInt_FromLong((long)x);
401 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{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000408 long x;
409 memcpy((char *)&x, p, sizeof x);
410 return PyInt_FromLong(x);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000411}
412
413static PyObject *
414nu_ulong(const char *p, const formatdef *f)
415{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000416 unsigned long x;
417 memcpy((char *)&x, p, sizeof x);
418 if (x <= LONG_MAX)
419 return PyInt_FromLong((long)x);
420 return PyLong_FromUnsignedLong(x);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000421}
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{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000431 PY_LONG_LONG x;
432 memcpy((char *)&x, p, sizeof x);
433 if (x >= LONG_MIN && x <= LONG_MAX)
434 return PyInt_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long));
435 return PyLong_FromLongLong(x);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000436}
437
438static PyObject *
439nu_ulonglong(const char *p, const formatdef *f)
440{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000441 unsigned PY_LONG_LONG x;
442 memcpy((char *)&x, p, sizeof x);
443 if (x <= LONG_MAX)
444 return PyInt_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long));
445 return PyLong_FromUnsignedLongLong(x);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000446}
447
448#endif
449
450static PyObject *
Martin v. Löwisaef4c6b2007-01-21 09:33:07 +0000451nu_bool(const char *p, const formatdef *f)
452{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000453 BOOL_TYPE x;
454 memcpy((char *)&x, p, sizeof x);
455 return PyBool_FromLong(x != 0);
Martin v. Löwisaef4c6b2007-01-21 09:33:07 +0000456}
457
458
459static PyObject *
Bob Ippolito232f3c92006-05-23 19:12:41 +0000460nu_float(const char *p, const formatdef *f)
461{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000462 float x;
463 memcpy((char *)&x, p, sizeof x);
464 return PyFloat_FromDouble((double)x);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000465}
466
467static PyObject *
468nu_double(const char *p, const formatdef *f)
469{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000470 double x;
471 memcpy((char *)&x, p, sizeof x);
472 return PyFloat_FromDouble(x);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000473}
474
475static PyObject *
476nu_void_p(const char *p, const formatdef *f)
477{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000478 void *x;
479 memcpy((char *)&x, p, sizeof x);
480 return PyLong_FromVoidPtr(x);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000481}
482
483static int
484np_byte(char *p, PyObject *v, const formatdef *f)
485{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000486 long x;
487 if (get_long(v, &x) < 0)
488 return -1;
489 if (x < -128 || x > 127){
490 PyErr_SetString(StructError,
491 "byte format requires -128 <= number <= 127");
492 return -1;
493 }
494 *p = (char)x;
495 return 0;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000496}
497
498static int
499np_ubyte(char *p, PyObject *v, const formatdef *f)
500{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000501 long x;
502 if (get_long(v, &x) < 0)
503 return -1;
504 if (x < 0 || x > 255){
505 PyErr_SetString(StructError,
506 "ubyte format requires 0 <= number <= 255");
507 return -1;
508 }
509 *p = (char)x;
510 return 0;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000511}
512
513static int
514np_char(char *p, PyObject *v, const formatdef *f)
515{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000516 if (!PyString_Check(v) || PyString_Size(v) != 1) {
517 PyErr_SetString(StructError,
518 "char format require string of length 1");
519 return -1;
520 }
521 *p = *PyString_AsString(v);
522 return 0;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000523}
524
525static int
526np_short(char *p, PyObject *v, const formatdef *f)
527{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000528 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)
535 " <= number <= " STRINGIFY(SHRT_MAX));
536 return -1;
537 }
538 y = (short)x;
539 memcpy(p, (char *)&y, sizeof y);
540 return 0;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000541}
542
543static int
544np_ushort(char *p, PyObject *v, const formatdef *f)
545{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000546 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,
552 "ushort format requires 0 <= number <= " STRINGIFY(USHRT_MAX));
553 return -1;
554 }
555 y = (unsigned short)x;
556 memcpy(p, (char *)&y, sizeof y);
557 return 0;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000558}
559
560static int
561np_int(char *p, PyObject *v, const formatdef *f)
562{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000563 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)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000568 if ((x < ((long)INT_MIN)) || (x > ((long)INT_MAX)))
569 return _range_error(f, 0);
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000570#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000571 y = (int)x;
572 memcpy(p, (char *)&y, sizeof y);
573 return 0;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000574}
575
576static int
577np_uint(char *p, PyObject *v, const formatdef *f)
578{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000579 unsigned long x;
580 unsigned int y;
581 if (get_ulong(v, &x) < 0)
582 return -1;
583 y = (unsigned int)x;
Bob Ippolito90bd0a52006-05-27 11:47:12 +0000584#if (SIZEOF_LONG > SIZEOF_INT)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000585 if (x > ((unsigned long)UINT_MAX))
586 return _range_error(f, 1);
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000587#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000588 memcpy(p, (char *)&y, sizeof y);
589 return 0;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000590}
591
592static int
593np_long(char *p, PyObject *v, const formatdef *f)
594{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000595 long x;
596 if (get_long(v, &x) < 0)
597 return -1;
598 memcpy(p, (char *)&x, sizeof x);
599 return 0;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000600}
601
602static int
603np_ulong(char *p, PyObject *v, const formatdef *f)
604{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000605 unsigned long x;
606 if (get_ulong(v, &x) < 0)
607 return -1;
608 memcpy(p, (char *)&x, sizeof x);
609 return 0;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000610}
611
612#ifdef HAVE_LONG_LONG
613
614static int
615np_longlong(char *p, PyObject *v, const formatdef *f)
616{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000617 PY_LONG_LONG x;
618 if (get_longlong(v, &x) < 0)
619 return -1;
620 memcpy(p, (char *)&x, sizeof x);
621 return 0;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000622}
623
624static int
625np_ulonglong(char *p, PyObject *v, const formatdef *f)
626{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000627 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;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000632}
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{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000639 BOOL_TYPE y;
640 y = PyObject_IsTrue(v);
641 memcpy(p, (char *)&y, sizeof y);
642 return 0;
Martin v. Löwisaef4c6b2007-01-21 09:33:07 +0000643}
644
Bob Ippolito232f3c92006-05-23 19:12:41 +0000645static int
646np_float(char *p, PyObject *v, const formatdef *f)
647{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000648 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;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000656}
657
658static int
659np_double(char *p, PyObject *v, const formatdef *f)
660{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000661 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;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000669}
670
671static int
672np_void_p(char *p, PyObject *v, const formatdef *f)
673{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000674 void *x;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000675
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000676 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;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000686}
687
688static formatdef native_table[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000689 {'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
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000702 {'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},
Bob Ippolito232f3c92006-05-23 19:12:41 +0000704#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000705 {'?', sizeof(BOOL_TYPE), BOOL_ALIGN, nu_bool, np_bool},
706 {'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},
709 {0}
Bob Ippolito232f3c92006-05-23 19:12:41 +0000710};
711
712/* Big-endian routines. *****************************************************/
713
714static PyObject *
715bu_int(const char *p, const formatdef *f)
716{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000717 long x = 0;
718 Py_ssize_t i = f->size;
719 const unsigned char *bytes = (const unsigned char *)p;
720 do {
721 x = (x<<8) | *bytes++;
722 } while (--i > 0);
723 /* Extend the sign bit. */
724 if (SIZEOF_LONG > f->size)
725 x |= -(x & (1L << ((8 * f->size) - 1)));
726 return PyInt_FromLong(x);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000727}
728
729static PyObject *
730bu_uint(const char *p, const formatdef *f)
731{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000732 unsigned long x = 0;
733 Py_ssize_t i = f->size;
734 const unsigned char *bytes = (const unsigned char *)p;
735 do {
736 x = (x<<8) | *bytes++;
737 } while (--i > 0);
738 if (x <= LONG_MAX)
739 return PyInt_FromLong((long)x);
740 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
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000747 PY_LONG_LONG x = 0;
748 Py_ssize_t i = f->size;
749 const unsigned char *bytes = (const unsigned char *)p;
750 do {
751 x = (x<<8) | *bytes++;
752 } while (--i > 0);
753 /* Extend the sign bit. */
754 if (SIZEOF_LONG_LONG > f->size)
755 x |= -(x & ((PY_LONG_LONG)1 << ((8 * f->size) - 1)));
756 if (x >= LONG_MIN && x <= LONG_MAX)
757 return PyInt_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long));
758 return PyLong_FromLongLong(x);
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000759#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +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
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000771 unsigned PY_LONG_LONG x = 0;
772 Py_ssize_t i = f->size;
773 const unsigned char *bytes = (const unsigned char *)p;
774 do {
775 x = (x<<8) | *bytes++;
776 } while (--i > 0);
777 if (x <= LONG_MAX)
778 return PyInt_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long));
779 return PyLong_FromUnsignedLongLong(x);
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000780#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +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{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000791 return unpack_float(p, 0);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000792}
793
794static PyObject *
795bu_double(const char *p, const formatdef *f)
796{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000797 return unpack_double(p, 0);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000798}
799
Martin v. Löwisaef4c6b2007-01-21 09:33:07 +0000800static PyObject *
801bu_bool(const char *p, const formatdef *f)
802{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000803 char x;
804 memcpy((char *)&x, p, sizeof x);
805 return PyBool_FromLong(x != 0);
Martin v. Löwisaef4c6b2007-01-21 09:33:07 +0000806}
807
Bob Ippolito232f3c92006-05-23 19:12:41 +0000808static int
809bp_int(char *p, PyObject *v, const formatdef *f)
810{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000811 long x;
812 Py_ssize_t i;
813 if (get_long(v, &x) < 0)
814 return -1;
815 i = f->size;
816 if (i != SIZEOF_LONG) {
817 if ((i == 2) && (x < -32768 || x > 32767))
818 return _range_error(f, 0);
Bob Ippolito90bd0a52006-05-27 11:47:12 +0000819#if (SIZEOF_LONG != 4)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000820 else if ((i == 4) && (x < -2147483648L || x > 2147483647L))
821 return _range_error(f, 0);
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000822#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000823 }
824 do {
825 p[--i] = (char)x;
826 x >>= 8;
827 } while (i > 0);
828 return 0;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000829}
830
831static int
832bp_uint(char *p, PyObject *v, const formatdef *f)
833{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000834 unsigned long x;
835 Py_ssize_t i;
836 if (get_ulong(v, &x) < 0)
837 return -1;
838 i = f->size;
839 if (i != SIZEOF_LONG) {
840 unsigned long maxint = 1;
841 maxint <<= (unsigned long)(i * 8);
842 if (x >= maxint)
843 return _range_error(f, 1);
844 }
845 do {
846 p[--i] = (char)x;
847 x >>= 8;
848 } while (i > 0);
849 return 0;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000850}
851
852static int
853bp_longlong(char *p, PyObject *v, const formatdef *f)
854{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000855 int res;
856 v = get_pylong(v);
857 if (v == NULL)
858 return -1;
859 res = _PyLong_AsByteArray((PyLongObject *)v,
860 (unsigned char *)p,
861 8,
862 0, /* little_endian */
863 1 /* signed */);
864 Py_DECREF(v);
865 return res;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000866}
867
868static int
869bp_ulonglong(char *p, PyObject *v, const formatdef *f)
870{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000871 int res;
872 v = get_pylong(v);
873 if (v == NULL)
874 return -1;
875 res = _PyLong_AsByteArray((PyLongObject *)v,
876 (unsigned char *)p,
877 8,
878 0, /* little_endian */
879 0 /* signed */);
880 Py_DECREF(v);
881 return res;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000882}
883
884static int
885bp_float(char *p, PyObject *v, const formatdef *f)
886{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000887 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);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000894}
895
896static int
897bp_double(char *p, PyObject *v, const formatdef *f)
898{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000899 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);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000906}
907
Martin v. Löwisaef4c6b2007-01-21 09:33:07 +0000908static int
909bp_bool(char *p, PyObject *v, const formatdef *f)
910{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000911 char y;
912 y = PyObject_IsTrue(v);
913 memcpy(p, (char *)&y, sizeof y);
914 return 0;
Martin v. Löwisaef4c6b2007-01-21 09:33:07 +0000915}
916
Bob Ippolito232f3c92006-05-23 19:12:41 +0000917static formatdef bigendian_table[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000918 {'x', 1, 0, NULL},
919 {'b', 1, 0, nu_byte, np_byte},
920 {'B', 1, 0, nu_ubyte, np_ubyte},
921 {'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},
932 {'?', 1, 0, bu_bool, bp_bool},
933 {'f', 4, 0, bu_float, bp_float},
934 {'d', 8, 0, bu_double, bp_double},
935 {0}
Bob Ippolito232f3c92006-05-23 19:12:41 +0000936};
937
938/* Little-endian routines. *****************************************************/
939
940static PyObject *
941lu_int(const char *p, const formatdef *f)
942{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000943 long x = 0;
944 Py_ssize_t i = f->size;
945 const unsigned char *bytes = (const unsigned char *)p;
946 do {
947 x = (x<<8) | bytes[--i];
948 } while (i > 0);
949 /* Extend the sign bit. */
950 if (SIZEOF_LONG > f->size)
951 x |= -(x & (1L << ((8 * f->size) - 1)));
952 return PyInt_FromLong(x);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000953}
954
955static PyObject *
956lu_uint(const char *p, const formatdef *f)
957{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000958 unsigned long x = 0;
959 Py_ssize_t i = f->size;
960 const unsigned char *bytes = (const unsigned char *)p;
961 do {
962 x = (x<<8) | bytes[--i];
963 } while (i > 0);
964 if (x <= LONG_MAX)
965 return PyInt_FromLong((long)x);
966 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
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000973 PY_LONG_LONG x = 0;
974 Py_ssize_t i = f->size;
975 const unsigned char *bytes = (const unsigned char *)p;
976 do {
977 x = (x<<8) | bytes[--i];
978 } while (i > 0);
979 /* Extend the sign bit. */
980 if (SIZEOF_LONG_LONG > f->size)
981 x |= -(x & ((PY_LONG_LONG)1 << ((8 * f->size) - 1)));
982 if (x >= LONG_MIN && x <= LONG_MAX)
983 return PyInt_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long));
984 return PyLong_FromLongLong(x);
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000985#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +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
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000997 unsigned PY_LONG_LONG x = 0;
998 Py_ssize_t i = f->size;
999 const unsigned char *bytes = (const unsigned char *)p;
1000 do {
1001 x = (x<<8) | bytes[--i];
1002 } while (i > 0);
1003 if (x <= LONG_MAX)
1004 return PyInt_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long));
1005 return PyLong_FromUnsignedLongLong(x);
Bob Ippolito94f68ee2006-05-25 18:44:50 +00001006#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +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{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001017 return unpack_float(p, 1);
Bob Ippolito232f3c92006-05-23 19:12:41 +00001018}
1019
1020static PyObject *
1021lu_double(const char *p, const formatdef *f)
1022{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001023 return unpack_double(p, 1);
Bob Ippolito232f3c92006-05-23 19:12:41 +00001024}
1025
1026static int
1027lp_int(char *p, PyObject *v, const formatdef *f)
1028{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001029 long x;
1030 Py_ssize_t i;
1031 if (get_long(v, &x) < 0)
1032 return -1;
1033 i = f->size;
1034 if (i != SIZEOF_LONG) {
1035 if ((i == 2) && (x < -32768 || x > 32767))
1036 return _range_error(f, 0);
Bob Ippolito90bd0a52006-05-27 11:47:12 +00001037#if (SIZEOF_LONG != 4)
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001038 else if ((i == 4) && (x < -2147483648L || x > 2147483647L))
1039 return _range_error(f, 0);
Bob Ippolitoe27337b2006-05-26 13:15:44 +00001040#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001041 }
1042 do {
1043 *p++ = (char)x;
1044 x >>= 8;
1045 } while (--i > 0);
1046 return 0;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001047}
1048
1049static int
1050lp_uint(char *p, PyObject *v, const formatdef *f)
1051{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001052 unsigned long x;
1053 Py_ssize_t i;
1054 if (get_ulong(v, &x) < 0)
1055 return -1;
1056 i = f->size;
1057 if (i != SIZEOF_LONG) {
1058 unsigned long maxint = 1;
1059 maxint <<= (unsigned long)(i * 8);
1060 if (x >= maxint)
1061 return _range_error(f, 1);
1062 }
1063 do {
1064 *p++ = (char)x;
1065 x >>= 8;
1066 } while (--i > 0);
1067 return 0;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001068}
1069
1070static int
1071lp_longlong(char *p, PyObject *v, const formatdef *f)
1072{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001073 int res;
1074 v = get_pylong(v);
1075 if (v == NULL)
1076 return -1;
1077 res = _PyLong_AsByteArray((PyLongObject*)v,
1078 (unsigned char *)p,
1079 8,
1080 1, /* little_endian */
1081 1 /* signed */);
1082 Py_DECREF(v);
1083 return res;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001084}
1085
1086static int
1087lp_ulonglong(char *p, PyObject *v, const formatdef *f)
1088{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001089 int res;
1090 v = get_pylong(v);
1091 if (v == NULL)
1092 return -1;
1093 res = _PyLong_AsByteArray((PyLongObject*)v,
1094 (unsigned char *)p,
1095 8,
1096 1, /* little_endian */
1097 0 /* signed */);
1098 Py_DECREF(v);
1099 return res;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001100}
1101
1102static int
1103lp_float(char *p, PyObject *v, const formatdef *f)
1104{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001105 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);
Bob Ippolito232f3c92006-05-23 19:12:41 +00001112}
1113
1114static int
1115lp_double(char *p, PyObject *v, const formatdef *f)
1116{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001117 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);
Bob Ippolito232f3c92006-05-23 19:12:41 +00001124}
1125
1126static formatdef lilendian_table[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001127 {'x', 1, 0, NULL},
1128 {'b', 1, 0, nu_byte, np_byte},
1129 {'B', 1, 0, nu_ubyte, np_ubyte},
1130 {'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},
1141 {'?', 1, 0, bu_bool, bp_bool}, /* Std rep not endian dep,
1142 but potentially different from native rep -- reuse bx_bool funcs. */
1143 {'f', 4, 0, lu_float, lp_float},
1144 {'d', 8, 0, lu_double, lp_double},
1145 {0}
Bob Ippolito232f3c92006-05-23 19:12:41 +00001146};
1147
1148
1149static const formatdef *
1150whichtable(char **pfmt)
1151{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001152 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 }
Bob Ippolito232f3c92006-05-23 19:12:41 +00001173}
1174
1175
1176/* Get the table entry for a format code */
1177
1178static const formatdef *
1179getentry(int c, const formatdef *f)
1180{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001181 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;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001188}
1189
1190
Mark Dickinson40228912010-06-11 20:27:05 +00001191/* Align a size according to a format code. Return -1 on overflow. */
Bob Ippolito232f3c92006-05-23 19:12:41 +00001192
Mark Dickinson40228912010-06-11 20:27:05 +00001193static Py_ssize_t
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{
Mark Dickinson40228912010-06-11 20:27:05 +00001196 Py_ssize_t extra;
1197
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001198 if (e->format == c) {
Mark Dickinson40228912010-06-11 20:27:05 +00001199 if (e->alignment && size > 0) {
1200 extra = (e->alignment - 1) - (size - 1) % (e->alignment);
1201 if (extra > PY_SSIZE_T_MAX - size)
1202 return -1;
1203 size += extra;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001204 }
1205 }
1206 return size;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001207}
1208
1209
1210/* calculate the size of a format string */
1211
1212static int
1213prepare_s(PyStructObject *self)
1214{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001215 const formatdef *f;
1216 const formatdef *e;
1217 formatcode *codes;
Tim Petersc2b550e2006-05-31 14:28:07 +00001218
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001219 const char *s;
1220 const char *fmt;
1221 char c;
Mark Dickinson40228912010-06-11 20:27:05 +00001222 Py_ssize_t size, len, num, itemsize;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001223
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001224 fmt = PyString_AS_STRING(self->s_format);
Bob Ippolito232f3c92006-05-23 19:12:41 +00001225
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001226 f = whichtable((char **)&fmt);
Tim Petersc2b550e2006-05-31 14:28:07 +00001227
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001228 s = fmt;
1229 size = 0;
1230 len = 0;
1231 while ((c = *s++) != '\0') {
1232 if (isspace(Py_CHARMASK(c)))
1233 continue;
1234 if ('0' <= c && c <= '9') {
1235 num = c - '0';
1236 while ('0' <= (c = *s++) && c <= '9') {
Mark Dickinson40228912010-06-11 20:27:05 +00001237 /* overflow-safe version of
1238 if (num*10 + (c - '0') > PY_SSIZE_T_MAX) { ... } */
1239 if (num >= PY_SSIZE_T_MAX / 10 && (
1240 num > PY_SSIZE_T_MAX / 10 ||
1241 (c - '0') > PY_SSIZE_T_MAX % 10))
1242 goto overflow;
1243 num = num*10 + (c - '0');
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001244 }
1245 if (c == '\0')
1246 break;
1247 }
1248 else
1249 num = 1;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001250
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001251 e = getentry(c, f);
1252 if (e == NULL)
1253 return -1;
Tim Petersc2b550e2006-05-31 14:28:07 +00001254
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001255 switch (c) {
1256 case 's': /* fall through */
1257 case 'p': len++; break;
1258 case 'x': break;
1259 default: len += num; break;
1260 }
Bob Ippolito232f3c92006-05-23 19:12:41 +00001261
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001262 itemsize = e->size;
1263 size = align(size, c, e);
Mark Dickinson40228912010-06-11 20:27:05 +00001264 if (size == -1)
1265 goto overflow;
1266
1267 /* if (size + num * itemsize > PY_SSIZE_T_MAX) { ... } */
1268 if (num > (PY_SSIZE_T_MAX - size) / itemsize)
1269 goto overflow;
1270 size += num * itemsize;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001271 }
Bob Ippolito232f3c92006-05-23 19:12:41 +00001272
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001273 /* check for overflow */
1274 if ((len + 1) > (PY_SSIZE_T_MAX / sizeof(formatcode))) {
1275 PyErr_NoMemory();
1276 return -1;
1277 }
Gregory P. Smith9d534572008-06-11 07:41:16 +00001278
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001279 self->s_size = size;
1280 self->s_len = len;
1281 codes = PyMem_MALLOC((len + 1) * sizeof(formatcode));
1282 if (codes == NULL) {
1283 PyErr_NoMemory();
1284 return -1;
1285 }
1286 self->s_codes = codes;
Tim Petersc2b550e2006-05-31 14:28:07 +00001287
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001288 s = fmt;
1289 size = 0;
1290 while ((c = *s++) != '\0') {
1291 if (isspace(Py_CHARMASK(c)))
1292 continue;
1293 if ('0' <= c && c <= '9') {
1294 num = c - '0';
1295 while ('0' <= (c = *s++) && c <= '9')
1296 num = num*10 + (c - '0');
1297 if (c == '\0')
1298 break;
1299 }
1300 else
1301 num = 1;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001302
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001303 e = getentry(c, f);
Tim Petersc2b550e2006-05-31 14:28:07 +00001304
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001305 size = align(size, c, e);
1306 if (c == 's' || c == 'p') {
1307 codes->offset = size;
1308 codes->size = num;
1309 codes->fmtdef = e;
1310 codes++;
1311 size += num;
1312 } else if (c == 'x') {
1313 size += num;
1314 } else {
1315 while (--num >= 0) {
1316 codes->offset = size;
1317 codes->size = e->size;
1318 codes->fmtdef = e;
1319 codes++;
1320 size += e->size;
1321 }
1322 }
1323 }
1324 codes->fmtdef = NULL;
1325 codes->offset = size;
1326 codes->size = 0;
Tim Petersc2b550e2006-05-31 14:28:07 +00001327
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001328 return 0;
Mark Dickinson40228912010-06-11 20:27:05 +00001329
1330 overflow:
1331 PyErr_SetString(StructError,
1332 "total struct size too long");
1333 return -1;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001334}
1335
1336static PyObject *
1337s_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1338{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001339 PyObject *self;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001340
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001341 assert(type != NULL && type->tp_alloc != NULL);
Bob Ippolito232f3c92006-05-23 19:12:41 +00001342
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001343 self = type->tp_alloc(type, 0);
1344 if (self != NULL) {
1345 PyStructObject *s = (PyStructObject*)self;
1346 Py_INCREF(Py_None);
1347 s->s_format = Py_None;
1348 s->s_codes = NULL;
1349 s->s_size = -1;
1350 s->s_len = -1;
1351 }
1352 return self;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001353}
1354
1355static int
1356s_init(PyObject *self, PyObject *args, PyObject *kwds)
1357{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001358 PyStructObject *soself = (PyStructObject *)self;
1359 PyObject *o_format = NULL;
1360 int ret = 0;
1361 static char *kwlist[] = {"format", 0};
Bob Ippolito232f3c92006-05-23 19:12:41 +00001362
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001363 assert(PyStruct_Check(self));
Bob Ippolito232f3c92006-05-23 19:12:41 +00001364
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001365 if (!PyArg_ParseTupleAndKeywords(args, kwds, "S:Struct", kwlist,
1366 &o_format))
1367 return -1;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001368
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001369 Py_INCREF(o_format);
1370 Py_CLEAR(soself->s_format);
1371 soself->s_format = o_format;
Tim Petersc2b550e2006-05-31 14:28:07 +00001372
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001373 ret = prepare_s(soself);
1374 return ret;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001375}
1376
1377static void
1378s_dealloc(PyStructObject *s)
1379{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001380 if (s->weakreflist != NULL)
1381 PyObject_ClearWeakRefs((PyObject *)s);
1382 if (s->s_codes != NULL) {
1383 PyMem_FREE(s->s_codes);
1384 }
1385 Py_XDECREF(s->s_format);
1386 Py_TYPE(s)->tp_free((PyObject *)s);
Bob Ippolito232f3c92006-05-23 19:12:41 +00001387}
1388
Bob Ippolitoeb621272006-05-24 15:32:06 +00001389static PyObject *
1390s_unpack_internal(PyStructObject *soself, char *startfrom) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001391 formatcode *code;
1392 Py_ssize_t i = 0;
1393 PyObject *result = PyTuple_New(soself->s_len);
1394 if (result == NULL)
1395 return NULL;
Bob Ippolitoeb621272006-05-24 15:32:06 +00001396
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001397 for (code = soself->s_codes; code->fmtdef != NULL; code++) {
1398 PyObject *v;
1399 const formatdef *e = code->fmtdef;
1400 const char *res = startfrom + code->offset;
1401 if (e->format == 's') {
1402 v = PyString_FromStringAndSize(res, code->size);
1403 } else if (e->format == 'p') {
1404 Py_ssize_t n = *(unsigned char*)res;
1405 if (n >= code->size)
1406 n = code->size - 1;
1407 v = PyString_FromStringAndSize(res + 1, n);
1408 } else {
1409 v = e->unpack(res, e);
1410 }
1411 if (v == NULL)
1412 goto fail;
1413 PyTuple_SET_ITEM(result, i++, v);
1414 }
Bob Ippolitoeb621272006-05-24 15:32:06 +00001415
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001416 return result;
Bob Ippolitoeb621272006-05-24 15:32:06 +00001417fail:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001418 Py_DECREF(result);
1419 return NULL;
Bob Ippolitocd51ca52006-05-27 15:53:49 +00001420}
Bob Ippolitoeb621272006-05-24 15:32:06 +00001421
1422
Bob Ippolito232f3c92006-05-23 19:12:41 +00001423PyDoc_STRVAR(s_unpack__doc__,
Bob Ippolito1fcdc232006-05-27 12:11:36 +00001424"S.unpack(str) -> (v1, v2, ...)\n\
Bob Ippolito232f3c92006-05-23 19:12:41 +00001425\n\
1426Return tuple containing values unpacked according to this Struct's format.\n\
1427Requires len(str) == self.size. See struct.__doc__ for more on format\n\
1428strings.");
1429
1430static PyObject *
1431s_unpack(PyObject *self, PyObject *inputstr)
1432{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001433 char *start;
1434 Py_ssize_t len;
1435 PyObject *args=NULL, *result;
1436 PyStructObject *soself = (PyStructObject *)self;
1437 assert(PyStruct_Check(self));
1438 assert(soself->s_codes != NULL);
1439 if (inputstr == NULL)
1440 goto fail;
1441 if (PyString_Check(inputstr) &&
1442 PyString_GET_SIZE(inputstr) == soself->s_size) {
1443 return s_unpack_internal(soself, PyString_AS_STRING(inputstr));
1444 }
1445 args = PyTuple_Pack(1, inputstr);
1446 if (args == NULL)
1447 return NULL;
1448 if (!PyArg_ParseTuple(args, "s#:unpack", &start, &len))
1449 goto fail;
1450 if (soself->s_size != len)
1451 goto fail;
1452 result = s_unpack_internal(soself, start);
1453 Py_DECREF(args);
1454 return result;
Raymond Hettinger7a3d41f2007-04-05 18:00:03 +00001455
1456fail:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001457 Py_XDECREF(args);
1458 PyErr_Format(StructError,
1459 "unpack requires a string argument of length %zd",
1460 soself->s_size);
1461 return NULL;
Bob Ippolitoeb621272006-05-24 15:32:06 +00001462}
1463
1464PyDoc_STRVAR(s_unpack_from__doc__,
Bob Ippolito1fcdc232006-05-27 12:11:36 +00001465"S.unpack_from(buffer[, offset]) -> (v1, v2, ...)\n\
Bob Ippolitoeb621272006-05-24 15:32:06 +00001466\n\
1467Return tuple containing values unpacked according to this Struct's format.\n\
1468Unlike unpack, unpack_from can unpack values from any object supporting\n\
1469the buffer API, not just str. Requires len(buffer[offset:]) >= self.size.\n\
1470See struct.__doc__ for more on format strings.");
1471
1472static PyObject *
1473s_unpack_from(PyObject *self, PyObject *args, PyObject *kwds)
1474{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001475 static char *kwlist[] = {"buffer", "offset", 0};
Bob Ippolitoeb621272006-05-24 15:32:06 +00001476#if (PY_VERSION_HEX < 0x02050000)
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001477 static char *fmt = "z#|i:unpack_from";
Bob Ippolitoeb621272006-05-24 15:32:06 +00001478#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001479 static char *fmt = "z#|n:unpack_from";
Bob Ippolitoeb621272006-05-24 15:32:06 +00001480#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001481 Py_ssize_t buffer_len = 0, offset = 0;
1482 char *buffer = NULL;
1483 PyStructObject *soself = (PyStructObject *)self;
1484 assert(PyStruct_Check(self));
1485 assert(soself->s_codes != NULL);
Bob Ippolitoeb621272006-05-24 15:32:06 +00001486
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001487 if (!PyArg_ParseTupleAndKeywords(args, kwds, fmt, kwlist,
1488 &buffer, &buffer_len, &offset))
1489 return NULL;
Bob Ippolitoeb621272006-05-24 15:32:06 +00001490
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001491 if (buffer == NULL) {
1492 PyErr_Format(StructError,
1493 "unpack_from requires a buffer argument");
1494 return NULL;
1495 }
Tim Petersc2b550e2006-05-31 14:28:07 +00001496
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001497 if (offset < 0)
1498 offset += buffer_len;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001499
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001500 if (offset < 0 || (buffer_len - offset) < soself->s_size) {
1501 PyErr_Format(StructError,
1502 "unpack_from requires a buffer of at least %zd bytes",
1503 soself->s_size);
1504 return NULL;
1505 }
1506 return s_unpack_internal(soself, buffer + offset);
Bob Ippolitoeb621272006-05-24 15:32:06 +00001507}
Bob Ippolito232f3c92006-05-23 19:12:41 +00001508
Bob Ippolito232f3c92006-05-23 19:12:41 +00001509
Martin Blais2856e5f2006-05-26 12:03:27 +00001510/*
1511 * Guts of the pack function.
1512 *
1513 * Takes a struct object, a tuple of arguments, and offset in that tuple of
1514 * argument for where to start processing the arguments for packing, and a
1515 * character buffer for writing the packed string. The caller must insure
1516 * that the buffer may contain the required length for packing the arguments.
1517 * 0 is returned on success, 1 is returned if there is an error.
1518 *
1519 */
1520static int
1521s_pack_internal(PyStructObject *soself, PyObject *args, int offset, char* buf)
Bob Ippolito232f3c92006-05-23 19:12:41 +00001522{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001523 formatcode *code;
1524 /* XXX(nnorwitz): why does i need to be a local? can we use
1525 the offset parameter or do we need the wider width? */
1526 Py_ssize_t i;
Martin Blais2856e5f2006-05-26 12:03:27 +00001527
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001528 memset(buf, '\0', soself->s_size);
1529 i = offset;
1530 for (code = soself->s_codes; code->fmtdef != NULL; code++) {
1531 Py_ssize_t n;
1532 PyObject *v = PyTuple_GET_ITEM(args, i++);
1533 const formatdef *e = code->fmtdef;
1534 char *res = buf + code->offset;
1535 if (e->format == 's') {
1536 if (!PyString_Check(v)) {
1537 PyErr_SetString(StructError,
1538 "argument for 's' must "
1539 "be a string");
1540 return -1;
1541 }
1542 n = PyString_GET_SIZE(v);
1543 if (n > code->size)
1544 n = code->size;
1545 if (n > 0)
1546 memcpy(res, PyString_AS_STRING(v), n);
1547 } else if (e->format == 'p') {
1548 if (!PyString_Check(v)) {
1549 PyErr_SetString(StructError,
1550 "argument for 'p' must "
1551 "be a string");
1552 return -1;
1553 }
1554 n = PyString_GET_SIZE(v);
1555 if (n > (code->size - 1))
1556 n = code->size - 1;
1557 if (n > 0)
1558 memcpy(res + 1, PyString_AS_STRING(v), n);
1559 if (n > 255)
1560 n = 255;
1561 *res = Py_SAFE_DOWNCAST(n, Py_ssize_t, unsigned char);
1562 } else if (e->pack(res, v, e) < 0) {
1563 if (strchr(integer_codes, e->format) != NULL &&
1564 PyErr_ExceptionMatches(PyExc_OverflowError))
1565 PyErr_Format(StructError,
1566 "integer out of range for "
1567 "'%c' format code",
1568 e->format);
1569 return -1;
1570 }
1571 }
Tim Petersc2b550e2006-05-31 14:28:07 +00001572
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001573 /* Success */
1574 return 0;
Martin Blais2856e5f2006-05-26 12:03:27 +00001575}
Bob Ippolito232f3c92006-05-23 19:12:41 +00001576
Martin Blais2856e5f2006-05-26 12:03:27 +00001577
1578PyDoc_STRVAR(s_pack__doc__,
Bob Ippolito1fcdc232006-05-27 12:11:36 +00001579"S.pack(v1, v2, ...) -> string\n\
Martin Blais2856e5f2006-05-26 12:03:27 +00001580\n\
1581Return a string containing values v1, v2, ... packed according to this\n\
1582Struct's format. See struct.__doc__ for more on format strings.");
1583
1584static PyObject *
1585s_pack(PyObject *self, PyObject *args)
1586{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001587 PyStructObject *soself;
1588 PyObject *result;
Martin Blais2856e5f2006-05-26 12:03:27 +00001589
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001590 /* Validate arguments. */
1591 soself = (PyStructObject *)self;
1592 assert(PyStruct_Check(self));
1593 assert(soself->s_codes != NULL);
1594 if (PyTuple_GET_SIZE(args) != soself->s_len)
1595 {
1596 PyErr_Format(StructError,
1597 "pack requires exactly %zd arguments", soself->s_len);
1598 return NULL;
1599 }
Tim Petersc2b550e2006-05-31 14:28:07 +00001600
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001601 /* Allocate a new string */
1602 result = PyString_FromStringAndSize((char *)NULL, soself->s_size);
1603 if (result == NULL)
1604 return NULL;
Tim Petersc2b550e2006-05-31 14:28:07 +00001605
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001606 /* Call the guts */
1607 if ( s_pack_internal(soself, args, 0, PyString_AS_STRING(result)) != 0 ) {
1608 Py_DECREF(result);
1609 return NULL;
1610 }
Martin Blais2856e5f2006-05-26 12:03:27 +00001611
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001612 return result;
Martin Blais2856e5f2006-05-26 12:03:27 +00001613}
1614
Martin Blaisaf2ae722006-06-04 13:49:49 +00001615PyDoc_STRVAR(s_pack_into__doc__,
1616"S.pack_into(buffer, offset, v1, v2, ...)\n\
Martin Blais2856e5f2006-05-26 12:03:27 +00001617\n\
Martin Blaisaf2ae722006-06-04 13:49:49 +00001618Pack the values v1, v2, ... according to this Struct's format, write \n\
Bob Ippolito1fcdc232006-05-27 12:11:36 +00001619the packed bytes into the writable buffer buf starting at offset. Note\n\
1620that the offset is not an optional argument. See struct.__doc__ for \n\
Martin Blais2856e5f2006-05-26 12:03:27 +00001621more on format strings.");
1622
1623static PyObject *
Martin Blaisaf2ae722006-06-04 13:49:49 +00001624s_pack_into(PyObject *self, PyObject *args)
Martin Blais2856e5f2006-05-26 12:03:27 +00001625{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001626 PyStructObject *soself;
1627 char *buffer;
1628 Py_ssize_t buffer_len, offset;
Martin Blais2856e5f2006-05-26 12:03:27 +00001629
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001630 /* Validate arguments. +1 is for the first arg as buffer. */
1631 soself = (PyStructObject *)self;
1632 assert(PyStruct_Check(self));
1633 assert(soself->s_codes != NULL);
1634 if (PyTuple_GET_SIZE(args) != (soself->s_len + 2))
1635 {
1636 PyErr_Format(StructError,
1637 "pack_into requires exactly %zd arguments",
1638 (soself->s_len + 2));
1639 return NULL;
1640 }
Martin Blais2856e5f2006-05-26 12:03:27 +00001641
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001642 /* Extract a writable memory buffer from the first argument */
1643 if ( PyObject_AsWriteBuffer(PyTuple_GET_ITEM(args, 0),
1644 (void**)&buffer, &buffer_len) == -1 ) {
1645 return NULL;
1646 }
1647 assert( buffer_len >= 0 );
Martin Blais2856e5f2006-05-26 12:03:27 +00001648
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001649 /* Extract the offset from the first argument */
1650 offset = PyInt_AsSsize_t(PyTuple_GET_ITEM(args, 1));
1651 if (offset == -1 && PyErr_Occurred())
1652 return NULL;
Martin Blais2856e5f2006-05-26 12:03:27 +00001653
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001654 /* Support negative offsets. */
1655 if (offset < 0)
1656 offset += buffer_len;
Martin Blais2856e5f2006-05-26 12:03:27 +00001657
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001658 /* Check boundaries */
1659 if (offset < 0 || (buffer_len - offset) < soself->s_size) {
1660 PyErr_Format(StructError,
1661 "pack_into requires a buffer of at least %zd bytes",
1662 soself->s_size);
1663 return NULL;
1664 }
Tim Petersc2b550e2006-05-31 14:28:07 +00001665
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001666 /* Call the guts */
1667 if ( s_pack_internal(soself, args, 2, buffer + offset) != 0 ) {
1668 return NULL;
1669 }
Martin Blais2856e5f2006-05-26 12:03:27 +00001670
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001671 Py_RETURN_NONE;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001672}
1673
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001674static PyObject *
1675s_get_format(PyStructObject *self, void *unused)
1676{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001677 Py_INCREF(self->s_format);
1678 return self->s_format;
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001679}
1680
1681static PyObject *
1682s_get_size(PyStructObject *self, void *unused)
1683{
1684 return PyInt_FromSsize_t(self->s_size);
1685}
Bob Ippolito232f3c92006-05-23 19:12:41 +00001686
1687/* List of functions */
1688
1689static struct PyMethodDef s_methods[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001690 {"pack", s_pack, METH_VARARGS, s_pack__doc__},
1691 {"pack_into", s_pack_into, METH_VARARGS, s_pack_into__doc__},
1692 {"unpack", s_unpack, METH_O, s_unpack__doc__},
1693 {"unpack_from", (PyCFunction)s_unpack_from, METH_VARARGS|METH_KEYWORDS,
1694 s_unpack_from__doc__},
1695 {NULL, NULL} /* sentinel */
Bob Ippolito232f3c92006-05-23 19:12:41 +00001696};
1697
1698PyDoc_STRVAR(s__doc__, "Compiled struct object");
1699
1700#define OFF(x) offsetof(PyStructObject, x)
1701
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001702static PyGetSetDef s_getsetlist[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001703 {"format", (getter)s_get_format, (setter)NULL, "struct format string", NULL},
1704 {"size", (getter)s_get_size, (setter)NULL, "struct size in bytes", NULL},
1705 {NULL} /* sentinel */
Bob Ippolito232f3c92006-05-23 19:12:41 +00001706};
1707
Bob Ippolito232f3c92006-05-23 19:12:41 +00001708static
1709PyTypeObject PyStructType = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001710 PyVarObject_HEAD_INIT(NULL, 0)
1711 "Struct",
1712 sizeof(PyStructObject),
1713 0,
1714 (destructor)s_dealloc, /* tp_dealloc */
1715 0, /* tp_print */
1716 0, /* tp_getattr */
1717 0, /* tp_setattr */
1718 0, /* tp_compare */
1719 0, /* tp_repr */
1720 0, /* tp_as_number */
1721 0, /* tp_as_sequence */
1722 0, /* tp_as_mapping */
1723 0, /* tp_hash */
1724 0, /* tp_call */
1725 0, /* tp_str */
1726 PyObject_GenericGetAttr, /* tp_getattro */
1727 PyObject_GenericSetAttr, /* tp_setattro */
1728 0, /* tp_as_buffer */
1729 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_WEAKREFS,/* tp_flags */
1730 s__doc__, /* tp_doc */
1731 0, /* tp_traverse */
1732 0, /* tp_clear */
1733 0, /* tp_richcompare */
1734 offsetof(PyStructObject, weakreflist), /* tp_weaklistoffset */
1735 0, /* tp_iter */
1736 0, /* tp_iternext */
1737 s_methods, /* tp_methods */
1738 NULL, /* tp_members */
1739 s_getsetlist, /* tp_getset */
1740 0, /* tp_base */
1741 0, /* tp_dict */
1742 0, /* tp_descr_get */
1743 0, /* tp_descr_set */
1744 0, /* tp_dictoffset */
1745 s_init, /* tp_init */
1746 PyType_GenericAlloc,/* tp_alloc */
1747 s_new, /* tp_new */
1748 PyObject_Del, /* tp_free */
Bob Ippolito232f3c92006-05-23 19:12:41 +00001749};
1750
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001751
1752/* ---- Standalone functions ---- */
1753
1754#define MAXCACHE 100
Christian Heimes76d19f62008-01-04 02:54:42 +00001755static PyObject *cache = NULL;
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001756
1757static PyObject *
1758cache_struct(PyObject *fmt)
1759{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001760 PyObject * s_object;
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001761
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001762 if (cache == NULL) {
1763 cache = PyDict_New();
1764 if (cache == NULL)
1765 return NULL;
1766 }
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001767
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001768 s_object = PyDict_GetItem(cache, fmt);
1769 if (s_object != NULL) {
1770 Py_INCREF(s_object);
1771 return s_object;
1772 }
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001773
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001774 s_object = PyObject_CallFunctionObjArgs((PyObject *)(&PyStructType), fmt, NULL);
1775 if (s_object != NULL) {
1776 if (PyDict_Size(cache) >= MAXCACHE)
1777 PyDict_Clear(cache);
1778 /* Attempt to cache the result */
1779 if (PyDict_SetItem(cache, fmt, s_object) == -1)
1780 PyErr_Clear();
1781 }
1782 return s_object;
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001783}
1784
Christian Heimes76d19f62008-01-04 02:54:42 +00001785PyDoc_STRVAR(clearcache_doc,
1786"Clear the internal cache.");
1787
1788static PyObject *
1789clearcache(PyObject *self)
1790{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001791 Py_CLEAR(cache);
1792 Py_RETURN_NONE;
Christian Heimes76d19f62008-01-04 02:54:42 +00001793}
1794
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001795PyDoc_STRVAR(calcsize_doc,
1796"Return size of C struct described by format string fmt.");
1797
1798static PyObject *
1799calcsize(PyObject *self, PyObject *fmt)
1800{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001801 Py_ssize_t n;
1802 PyObject *s_object = cache_struct(fmt);
1803 if (s_object == NULL)
1804 return NULL;
1805 n = ((PyStructObject *)s_object)->s_size;
1806 Py_DECREF(s_object);
1807 return PyInt_FromSsize_t(n);
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001808}
1809
1810PyDoc_STRVAR(pack_doc,
1811"Return string containing values v1, v2, ... packed according to fmt.");
1812
1813static PyObject *
1814pack(PyObject *self, PyObject *args)
1815{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001816 PyObject *s_object, *fmt, *newargs, *result;
1817 Py_ssize_t n = PyTuple_GET_SIZE(args);
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001818
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001819 if (n == 0) {
1820 PyErr_SetString(PyExc_TypeError, "missing format argument");
1821 return NULL;
1822 }
1823 fmt = PyTuple_GET_ITEM(args, 0);
1824 newargs = PyTuple_GetSlice(args, 1, n);
1825 if (newargs == NULL)
1826 return NULL;
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001827
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001828 s_object = cache_struct(fmt);
1829 if (s_object == NULL) {
1830 Py_DECREF(newargs);
1831 return NULL;
1832 }
1833 result = s_pack(s_object, newargs);
1834 Py_DECREF(newargs);
1835 Py_DECREF(s_object);
1836 return result;
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001837}
1838
1839PyDoc_STRVAR(pack_into_doc,
1840"Pack the values v1, v2, ... according to fmt.\n\
1841Write the packed bytes into the writable buffer buf starting at offset.");
1842
1843static PyObject *
1844pack_into(PyObject *self, PyObject *args)
1845{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001846 PyObject *s_object, *fmt, *newargs, *result;
1847 Py_ssize_t n = PyTuple_GET_SIZE(args);
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001848
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001849 if (n == 0) {
1850 PyErr_SetString(PyExc_TypeError, "missing format argument");
1851 return NULL;
1852 }
1853 fmt = PyTuple_GET_ITEM(args, 0);
1854 newargs = PyTuple_GetSlice(args, 1, n);
1855 if (newargs == NULL)
1856 return NULL;
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001857
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001858 s_object = cache_struct(fmt);
1859 if (s_object == NULL) {
1860 Py_DECREF(newargs);
1861 return NULL;
1862 }
1863 result = s_pack_into(s_object, newargs);
1864 Py_DECREF(newargs);
1865 Py_DECREF(s_object);
1866 return result;
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001867}
1868
1869PyDoc_STRVAR(unpack_doc,
1870"Unpack the string containing packed C structure data, according to fmt.\n\
1871Requires len(string) == calcsize(fmt).");
1872
1873static PyObject *
1874unpack(PyObject *self, PyObject *args)
1875{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001876 PyObject *s_object, *fmt, *inputstr, *result;
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001877
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001878 if (!PyArg_UnpackTuple(args, "unpack", 2, 2, &fmt, &inputstr))
1879 return NULL;
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001880
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001881 s_object = cache_struct(fmt);
1882 if (s_object == NULL)
1883 return NULL;
1884 result = s_unpack(s_object, inputstr);
1885 Py_DECREF(s_object);
1886 return result;
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001887}
1888
1889PyDoc_STRVAR(unpack_from_doc,
1890"Unpack the buffer, containing packed C structure data, according to\n\
1891fmt, starting at offset. Requires len(buffer[offset:]) >= calcsize(fmt).");
1892
1893static PyObject *
1894unpack_from(PyObject *self, PyObject *args, PyObject *kwds)
1895{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001896 PyObject *s_object, *fmt, *newargs, *result;
1897 Py_ssize_t n = PyTuple_GET_SIZE(args);
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001898
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001899 if (n == 0) {
1900 PyErr_SetString(PyExc_TypeError, "missing format argument");
1901 return NULL;
1902 }
1903 fmt = PyTuple_GET_ITEM(args, 0);
1904 newargs = PyTuple_GetSlice(args, 1, n);
1905 if (newargs == NULL)
1906 return NULL;
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001907
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001908 s_object = cache_struct(fmt);
1909 if (s_object == NULL) {
1910 Py_DECREF(newargs);
1911 return NULL;
1912 }
1913 result = s_unpack_from(s_object, newargs, kwds);
1914 Py_DECREF(newargs);
1915 Py_DECREF(s_object);
1916 return result;
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001917}
1918
1919static struct PyMethodDef module_functions[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001920 {"_clearcache", (PyCFunction)clearcache, METH_NOARGS, clearcache_doc},
1921 {"calcsize", calcsize, METH_O, calcsize_doc},
1922 {"pack", pack, METH_VARARGS, pack_doc},
1923 {"pack_into", pack_into, METH_VARARGS, pack_into_doc},
1924 {"unpack", unpack, METH_VARARGS, unpack_doc},
1925 {"unpack_from", (PyCFunction)unpack_from,
1926 METH_VARARGS|METH_KEYWORDS, unpack_from_doc},
1927 {NULL, NULL} /* sentinel */
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001928};
1929
1930
Bob Ippolito232f3c92006-05-23 19:12:41 +00001931/* Module initialization */
1932
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001933PyDoc_STRVAR(module_doc,
Mark Dickinson3d830822009-10-08 15:54:10 +00001934"Functions to convert between Python values and C structs represented\n\
1935as Python strings. It uses format strings (explained below) as compact\n\
1936descriptions of the lay-out of the C structs and the intended conversion\n\
1937to/from Python values.\n\
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001938\n\
1939The optional first format char indicates byte order, size and alignment:\n\
Mark Dickinson3d830822009-10-08 15:54:10 +00001940 @: native order, size & alignment (default)\n\
1941 =: native order, std. size & alignment\n\
1942 <: little-endian, std. size & alignment\n\
1943 >: big-endian, std. size & alignment\n\
1944 !: same as >\n\
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001945\n\
1946The remaining chars indicate types of args and must match exactly;\n\
1947these can be preceded by a decimal repeat count:\n\
1948 x: pad byte (no data); c:char; b:signed byte; B:unsigned byte;\n\
Mark Dickinson3d830822009-10-08 15:54:10 +00001949 ?: _Bool (requires C99; if not available, char is used instead)\n\
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001950 h:short; H:unsigned short; i:int; I:unsigned int;\n\
1951 l:long; L:unsigned long; f:float; d:double.\n\
1952Special cases (preceding decimal count indicates length):\n\
1953 s:string (array of char); p: pascal string (with count byte).\n\
1954Special case (only available in native format):\n\
1955 P:an integer type that is wide enough to hold a pointer.\n\
1956Special case (not in native mode unless 'long long' in platform C):\n\
1957 q:long long; Q:unsigned long long\n\
1958Whitespace between formats is ignored.\n\
1959\n\
1960The variable struct.error is an exception raised on errors.\n");
1961
Bob Ippolito232f3c92006-05-23 19:12:41 +00001962PyMODINIT_FUNC
1963init_struct(void)
1964{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001965 PyObject *ver, *m;
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001966
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001967 ver = PyString_FromString("0.2");
1968 if (ver == NULL)
1969 return;
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001970
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001971 m = Py_InitModule3("_struct", module_functions, module_doc);
1972 if (m == NULL)
1973 return;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001974
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001975 Py_TYPE(&PyStructType) = &PyType_Type;
1976 if (PyType_Ready(&PyStructType) < 0)
1977 return;
Bob Ippolito3fc2bb92006-05-25 19:03:19 +00001978
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001979 /* This speed trick can't be used until overflow masking goes
1980 away, because native endian always raises exceptions
1981 instead of overflow masking. */
Tim Petersc2b550e2006-05-31 14:28:07 +00001982
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001983 /* Check endian and swap in faster functions */
1984 {
1985 int one = 1;
1986 formatdef *native = native_table;
1987 formatdef *other, *ptr;
1988 if ((int)*(unsigned char*)&one)
1989 other = lilendian_table;
1990 else
1991 other = bigendian_table;
1992 /* Scan through the native table, find a matching
1993 entry in the endian table and swap in the
1994 native implementations whenever possible
1995 (64-bit platforms may not have "standard" sizes) */
1996 while (native->format != '\0' && other->format != '\0') {
1997 ptr = other;
1998 while (ptr->format != '\0') {
1999 if (ptr->format == native->format) {
2000 /* Match faster when formats are
2001 listed in the same order */
2002 if (ptr == other)
2003 other++;
2004 /* Only use the trick if the
2005 size matches */
2006 if (ptr->size != native->size)
2007 break;
2008 /* Skip float and double, could be
2009 "unknown" float format */
2010 if (ptr->format == 'd' || ptr->format == 'f')
2011 break;
2012 ptr->pack = native->pack;
2013 ptr->unpack = native->unpack;
2014 break;
2015 }
2016 ptr++;
2017 }
2018 native++;
2019 }
2020 }
Tim Petersc2b550e2006-05-31 14:28:07 +00002021
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002022 /* Add some symbolic constants to the module */
2023 if (StructError == NULL) {
2024 StructError = PyErr_NewException("struct.error", NULL, NULL);
2025 if (StructError == NULL)
2026 return;
2027 }
Bob Ippolito04ab9942006-05-25 19:33:38 +00002028
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002029 Py_INCREF(StructError);
2030 PyModule_AddObject(m, "error", StructError);
Bob Ippolito04ab9942006-05-25 19:33:38 +00002031
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002032 Py_INCREF((PyObject*)&PyStructType);
2033 PyModule_AddObject(m, "Struct", (PyObject*)&PyStructType);
Tim Petersc2b550e2006-05-31 14:28:07 +00002034
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002035 PyModule_AddObject(m, "__version__", ver);
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00002036
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002037 PyModule_AddIntConstant(m, "_PY_STRUCT_RANGE_CHECKING", 1);
2038 PyModule_AddIntConstant(m, "_PY_STRUCT_FLOAT_COERCE", 1);
Bob Ippolito232f3c92006-05-23 19:12:41 +00002039}