blob: e8fe67d5fa38959c1eab2d3116a5108a136a624b [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 Dickinson154b7ad2010-03-07 16:24:45 +0000110 PyObject *r;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000111 assert(v != NULL);
Mark Dickinson154b7ad2010-03-07 16:24:45 +0000112 if (!PyInt_Check(v) && !PyLong_Check(v)) {
113 PyNumberMethods *m;
114 /* Not an integer; try to use __int__ to convert to an
115 integer. This behaviour is deprecated, and is removed in
116 Python 3.x. */
117 m = Py_TYPE(v)->tp_as_number;
118 if (m != NULL && m->nb_int != NULL) {
119 /* Special case warning message for floats, for
120 backwards compatibility. */
121 if (PyFloat_Check(v)) {
122 if (PyErr_WarnEx(PyExc_DeprecationWarning,
123 FLOAT_COERCE_WARN, 1))
124 return NULL;
125 }
126 else {
127 if (PyErr_WarnEx(PyExc_DeprecationWarning,
128 NON_INTEGER_WARN, 1))
129 return NULL;
130 }
131 v = m->nb_int(v);
132 if (v == NULL)
133 return NULL;
134 if (!PyInt_Check(v) && !PyLong_Check(v)) {
135 PyErr_SetString(PyExc_TypeError,
136 "__int__ method returned non-integer");
137 return NULL;
138 }
139 }
140 else {
141 PyErr_SetString(StructError,
142 "cannot convert argument to integer");
Bob Ippolito232f3c92006-05-23 19:12:41 +0000143 return NULL;
Mark Dickinson154b7ad2010-03-07 16:24:45 +0000144 }
Bob Ippolito232f3c92006-05-23 19:12:41 +0000145 }
Mark Dickinson154b7ad2010-03-07 16:24:45 +0000146 else
147 /* Ensure we own a reference to v. */
148 Py_INCREF(v);
149
150 if (PyInt_Check(v)) {
151 r = PyLong_FromLong(PyInt_AS_LONG(v));
152 Py_DECREF(v);
153 }
154 else if (PyLong_Check(v)) {
155 assert(PyLong_Check(v));
156 r = v;
157 }
158 else
159 assert(0); /* shouldn't ever get here */
160
161 return r;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000162}
163
Mark Dickinson5fd3af22009-07-07 15:08:28 +0000164/* Helper to convert a Python object to a C long. Sets an exception
165 (struct.error for an inconvertible type, OverflowError for
166 out-of-range values) and returns -1 on error. */
Bob Ippolito232f3c92006-05-23 19:12:41 +0000167
168static int
169get_long(PyObject *v, long *p)
170{
Mark Dickinson463dc4b2009-07-05 10:01:24 +0000171 long x;
172
173 v = get_pylong(v);
174 if (v == NULL)
175 return -1;
176 assert(PyLong_Check(v));
177 x = PyLong_AsLong(v);
178 Py_DECREF(v);
Mark Dickinson5fd3af22009-07-07 15:08:28 +0000179 if (x == (long)-1 && PyErr_Occurred())
Bob Ippolito232f3c92006-05-23 19:12:41 +0000180 return -1;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000181 *p = x;
182 return 0;
183}
184
Bob Ippolito232f3c92006-05-23 19:12:41 +0000185/* Same, but handling unsigned long */
186
187static int
188get_ulong(PyObject *v, unsigned long *p)
189{
Mark Dickinson463dc4b2009-07-05 10:01:24 +0000190 unsigned long x;
191
192 v = get_pylong(v);
193 if (v == NULL)
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000194 return -1;
Mark Dickinson463dc4b2009-07-05 10:01:24 +0000195 assert(PyLong_Check(v));
196 x = PyLong_AsUnsignedLong(v);
197 Py_DECREF(v);
Mark Dickinson5fd3af22009-07-07 15:08:28 +0000198 if (x == (unsigned long)-1 && PyErr_Occurred())
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000199 return -1;
Mark Dickinson463dc4b2009-07-05 10:01:24 +0000200 *p = x;
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000201 return 0;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000202}
203
204#ifdef HAVE_LONG_LONG
205
206/* Same, but handling native long long. */
207
208static int
209get_longlong(PyObject *v, PY_LONG_LONG *p)
210{
211 PY_LONG_LONG x;
212
213 v = get_pylong(v);
214 if (v == NULL)
215 return -1;
216 assert(PyLong_Check(v));
217 x = PyLong_AsLongLong(v);
218 Py_DECREF(v);
Mark Dickinson5fd3af22009-07-07 15:08:28 +0000219 if (x == (PY_LONG_LONG)-1 && PyErr_Occurred())
Bob Ippolito232f3c92006-05-23 19:12:41 +0000220 return -1;
221 *p = x;
222 return 0;
223}
224
225/* Same, but handling native unsigned long long. */
226
227static int
228get_ulonglong(PyObject *v, unsigned PY_LONG_LONG *p)
229{
230 unsigned PY_LONG_LONG x;
231
232 v = get_pylong(v);
233 if (v == NULL)
234 return -1;
235 assert(PyLong_Check(v));
236 x = PyLong_AsUnsignedLongLong(v);
237 Py_DECREF(v);
Mark Dickinson5fd3af22009-07-07 15:08:28 +0000238 if (x == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred())
Bob Ippolito232f3c92006-05-23 19:12:41 +0000239 return -1;
240 *p = x;
241 return 0;
242}
243
244#endif
245
246/* Floating point helpers */
247
248static PyObject *
249unpack_float(const char *p, /* start of 4-byte string */
250 int le) /* true for little-endian, false for big-endian */
251{
252 double x;
253
254 x = _PyFloat_Unpack4((unsigned char *)p, le);
255 if (x == -1.0 && PyErr_Occurred())
256 return NULL;
257 return PyFloat_FromDouble(x);
258}
259
260static PyObject *
261unpack_double(const char *p, /* start of 8-byte string */
262 int le) /* true for little-endian, false for big-endian */
263{
264 double x;
265
266 x = _PyFloat_Unpack8((unsigned char *)p, le);
267 if (x == -1.0 && PyErr_Occurred())
268 return NULL;
269 return PyFloat_FromDouble(x);
270}
271
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000272/* Helper to format the range error exceptions */
273static int
Armin Rigo162997e2006-05-29 17:59:47 +0000274_range_error(const formatdef *f, int is_unsigned)
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000275{
Tim Petersd6a6f022006-05-31 15:33:22 +0000276 /* ulargest is the largest unsigned value with f->size bytes.
277 * Note that the simpler:
278 * ((size_t)1 << (f->size * 8)) - 1
Tim Peters72270c22006-05-31 15:34:37 +0000279 * doesn't work when f->size == sizeof(size_t) because C doesn't
280 * define what happens when a left shift count is >= the number of
281 * bits in the integer being shifted; e.g., on some boxes it doesn't
282 * shift at all when they're equal.
Tim Petersd6a6f022006-05-31 15:33:22 +0000283 */
284 const size_t ulargest = (size_t)-1 >> ((SIZEOF_SIZE_T - f->size)*8);
285 assert(f->size >= 1 && f->size <= SIZEOF_SIZE_T);
286 if (is_unsigned)
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000287 PyErr_Format(StructError,
Neal Norwitz971ea112006-05-31 07:43:27 +0000288 "'%c' format requires 0 <= number <= %zu",
Bob Ippolito28b26862006-05-29 15:47:29 +0000289 f->format,
Tim Petersd6a6f022006-05-31 15:33:22 +0000290 ulargest);
291 else {
292 const Py_ssize_t largest = (Py_ssize_t)(ulargest >> 1);
293 PyErr_Format(StructError,
294 "'%c' format requires %zd <= number <= %zd",
295 f->format,
296 ~ largest,
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000297 largest);
298 }
299 return -1;
300}
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000301
302
Bob Ippolito232f3c92006-05-23 19:12:41 +0000303
304/* A large number of small routines follow, with names of the form
305
Bob Ippolitoaa70a172006-05-26 20:25:23 +0000306 [bln][up]_TYPE
Bob Ippolito232f3c92006-05-23 19:12:41 +0000307
308 [bln] distiguishes among big-endian, little-endian and native.
309 [pu] distiguishes between pack (to struct) and unpack (from struct).
310 TYPE is one of char, byte, ubyte, etc.
311*/
312
313/* Native mode routines. ****************************************************/
314/* NOTE:
315 In all n[up]_<type> routines handling types larger than 1 byte, there is
316 *no* guarantee that the p pointer is properly aligned for each type,
317 therefore memcpy is called. An intermediate variable is used to
318 compensate for big-endian architectures.
319 Normally both the intermediate variable and the memcpy call will be
320 skipped by C optimisation in little-endian architectures (gcc >= 2.91
321 does this). */
322
323static PyObject *
324nu_char(const char *p, const formatdef *f)
325{
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000326 return PyString_FromStringAndSize(p, 1);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000327}
328
329static PyObject *
330nu_byte(const char *p, const formatdef *f)
331{
332 return PyInt_FromLong((long) *(signed char *)p);
333}
334
335static PyObject *
336nu_ubyte(const char *p, const formatdef *f)
337{
338 return PyInt_FromLong((long) *(unsigned char *)p);
339}
340
341static PyObject *
342nu_short(const char *p, const formatdef *f)
343{
344 short x;
345 memcpy((char *)&x, p, sizeof x);
346 return PyInt_FromLong((long)x);
347}
348
349static PyObject *
350nu_ushort(const char *p, const formatdef *f)
351{
352 unsigned short x;
353 memcpy((char *)&x, p, sizeof x);
354 return PyInt_FromLong((long)x);
355}
356
357static PyObject *
358nu_int(const char *p, const formatdef *f)
359{
360 int x;
361 memcpy((char *)&x, p, sizeof x);
362 return PyInt_FromLong((long)x);
363}
364
365static PyObject *
366nu_uint(const char *p, const formatdef *f)
367{
368 unsigned int x;
369 memcpy((char *)&x, p, sizeof x);
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000370#if (SIZEOF_LONG > SIZEOF_INT)
371 return PyInt_FromLong((long)x);
372#else
373 if (x <= ((unsigned int)LONG_MAX))
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000374 return PyInt_FromLong((long)x);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000375 return PyLong_FromUnsignedLong((unsigned long)x);
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000376#endif
Bob Ippolito232f3c92006-05-23 19:12:41 +0000377}
378
379static PyObject *
380nu_long(const char *p, const formatdef *f)
381{
382 long x;
383 memcpy((char *)&x, p, sizeof x);
384 return PyInt_FromLong(x);
385}
386
387static PyObject *
388nu_ulong(const char *p, const formatdef *f)
389{
390 unsigned long x;
391 memcpy((char *)&x, p, sizeof x);
Bob Ippolito04ab9942006-05-25 19:33:38 +0000392 if (x <= LONG_MAX)
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000393 return PyInt_FromLong((long)x);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000394 return PyLong_FromUnsignedLong(x);
395}
396
397/* Native mode doesn't support q or Q unless the platform C supports
398 long long (or, on Windows, __int64). */
399
400#ifdef HAVE_LONG_LONG
401
402static PyObject *
403nu_longlong(const char *p, const formatdef *f)
404{
405 PY_LONG_LONG x;
406 memcpy((char *)&x, p, sizeof x);
Bob Ippolito04ab9942006-05-25 19:33:38 +0000407 if (x >= LONG_MIN && x <= LONG_MAX)
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000408 return PyInt_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long));
Bob Ippolito232f3c92006-05-23 19:12:41 +0000409 return PyLong_FromLongLong(x);
410}
411
412static PyObject *
413nu_ulonglong(const char *p, const formatdef *f)
414{
415 unsigned PY_LONG_LONG x;
416 memcpy((char *)&x, p, sizeof x);
Bob Ippolito04ab9942006-05-25 19:33:38 +0000417 if (x <= LONG_MAX)
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000418 return PyInt_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long));
Bob Ippolito232f3c92006-05-23 19:12:41 +0000419 return PyLong_FromUnsignedLongLong(x);
420}
421
422#endif
423
424static PyObject *
Martin v. Löwisaef4c6b2007-01-21 09:33:07 +0000425nu_bool(const char *p, const formatdef *f)
426{
427 BOOL_TYPE x;
428 memcpy((char *)&x, p, sizeof x);
429 return PyBool_FromLong(x != 0);
430}
431
432
433static PyObject *
Bob Ippolito232f3c92006-05-23 19:12:41 +0000434nu_float(const char *p, const formatdef *f)
435{
436 float x;
437 memcpy((char *)&x, p, sizeof x);
438 return PyFloat_FromDouble((double)x);
439}
440
441static PyObject *
442nu_double(const char *p, const formatdef *f)
443{
444 double x;
445 memcpy((char *)&x, p, sizeof x);
446 return PyFloat_FromDouble(x);
447}
448
449static PyObject *
450nu_void_p(const char *p, const formatdef *f)
451{
452 void *x;
453 memcpy((char *)&x, p, sizeof x);
454 return PyLong_FromVoidPtr(x);
455}
456
457static int
458np_byte(char *p, PyObject *v, const formatdef *f)
459{
460 long x;
461 if (get_long(v, &x) < 0)
462 return -1;
463 if (x < -128 || x > 127){
464 PyErr_SetString(StructError,
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000465 "byte format requires -128 <= number <= 127");
Bob Ippolito232f3c92006-05-23 19:12:41 +0000466 return -1;
467 }
468 *p = (char)x;
469 return 0;
470}
471
472static int
473np_ubyte(char *p, PyObject *v, const formatdef *f)
474{
475 long x;
476 if (get_long(v, &x) < 0)
477 return -1;
478 if (x < 0 || x > 255){
479 PyErr_SetString(StructError,
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000480 "ubyte format requires 0 <= number <= 255");
Bob Ippolito232f3c92006-05-23 19:12:41 +0000481 return -1;
482 }
483 *p = (char)x;
484 return 0;
485}
486
487static int
488np_char(char *p, PyObject *v, const formatdef *f)
489{
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000490 if (!PyString_Check(v) || PyString_Size(v) != 1) {
Bob Ippolito232f3c92006-05-23 19:12:41 +0000491 PyErr_SetString(StructError,
492 "char format require string of length 1");
493 return -1;
494 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000495 *p = *PyString_AsString(v);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000496 return 0;
497}
498
499static int
500np_short(char *p, PyObject *v, const formatdef *f)
501{
502 long x;
503 short y;
504 if (get_long(v, &x) < 0)
505 return -1;
506 if (x < SHRT_MIN || x > SHRT_MAX){
507 PyErr_SetString(StructError,
508 "short format requires " STRINGIFY(SHRT_MIN)
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000509 " <= number <= " STRINGIFY(SHRT_MAX));
Bob Ippolito232f3c92006-05-23 19:12:41 +0000510 return -1;
511 }
512 y = (short)x;
513 memcpy(p, (char *)&y, sizeof y);
514 return 0;
515}
516
517static int
518np_ushort(char *p, PyObject *v, const formatdef *f)
519{
520 long x;
521 unsigned short y;
522 if (get_long(v, &x) < 0)
523 return -1;
524 if (x < 0 || x > USHRT_MAX){
525 PyErr_SetString(StructError,
Mark Dickinson24766ba2009-07-07 10:18:22 +0000526 "ushort format requires 0 <= number <= " STRINGIFY(USHRT_MAX));
Bob Ippolito232f3c92006-05-23 19:12:41 +0000527 return -1;
528 }
529 y = (unsigned short)x;
530 memcpy(p, (char *)&y, sizeof y);
531 return 0;
532}
533
534static int
535np_int(char *p, PyObject *v, const formatdef *f)
536{
537 long x;
538 int y;
539 if (get_long(v, &x) < 0)
540 return -1;
Bob Ippolito90bd0a52006-05-27 11:47:12 +0000541#if (SIZEOF_LONG > SIZEOF_INT)
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000542 if ((x < ((long)INT_MIN)) || (x > ((long)INT_MAX)))
Mark Dickinson5fd3af22009-07-07 15:08:28 +0000543 return _range_error(f, 0);
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000544#endif
Bob Ippolito232f3c92006-05-23 19:12:41 +0000545 y = (int)x;
546 memcpy(p, (char *)&y, sizeof y);
547 return 0;
548}
549
550static int
551np_uint(char *p, PyObject *v, const formatdef *f)
552{
553 unsigned long x;
554 unsigned int y;
Mark Dickinson716a9cc2009-09-27 16:39:28 +0000555 if (get_ulong(v, &x) < 0)
Georg Brandl6269fec2009-01-01 12:15:31 +0000556 return -1;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000557 y = (unsigned int)x;
Bob Ippolito90bd0a52006-05-27 11:47:12 +0000558#if (SIZEOF_LONG > SIZEOF_INT)
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000559 if (x > ((unsigned long)UINT_MAX))
Mark Dickinson5fd3af22009-07-07 15:08:28 +0000560 return _range_error(f, 1);
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000561#endif
Bob Ippolito232f3c92006-05-23 19:12:41 +0000562 memcpy(p, (char *)&y, sizeof y);
563 return 0;
564}
565
566static int
567np_long(char *p, PyObject *v, const formatdef *f)
568{
569 long x;
570 if (get_long(v, &x) < 0)
571 return -1;
572 memcpy(p, (char *)&x, sizeof x);
573 return 0;
574}
575
576static int
577np_ulong(char *p, PyObject *v, const formatdef *f)
578{
579 unsigned long x;
Mark Dickinson716a9cc2009-09-27 16:39:28 +0000580 if (get_ulong(v, &x) < 0)
Georg Brandl6269fec2009-01-01 12:15:31 +0000581 return -1;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000582 memcpy(p, (char *)&x, sizeof x);
583 return 0;
584}
585
586#ifdef HAVE_LONG_LONG
587
588static int
589np_longlong(char *p, PyObject *v, const formatdef *f)
590{
591 PY_LONG_LONG x;
592 if (get_longlong(v, &x) < 0)
593 return -1;
594 memcpy(p, (char *)&x, sizeof x);
595 return 0;
596}
597
598static int
599np_ulonglong(char *p, PyObject *v, const formatdef *f)
600{
601 unsigned PY_LONG_LONG x;
602 if (get_ulonglong(v, &x) < 0)
603 return -1;
604 memcpy(p, (char *)&x, sizeof x);
605 return 0;
606}
607#endif
608
Martin v. Löwisaef4c6b2007-01-21 09:33:07 +0000609
610static int
611np_bool(char *p, PyObject *v, const formatdef *f)
612{
613 BOOL_TYPE y;
614 y = PyObject_IsTrue(v);
615 memcpy(p, (char *)&y, sizeof y);
616 return 0;
617}
618
Bob Ippolito232f3c92006-05-23 19:12:41 +0000619static int
620np_float(char *p, PyObject *v, const formatdef *f)
621{
622 float x = (float)PyFloat_AsDouble(v);
623 if (x == -1 && PyErr_Occurred()) {
624 PyErr_SetString(StructError,
625 "required argument is not a float");
626 return -1;
627 }
628 memcpy(p, (char *)&x, sizeof x);
629 return 0;
630}
631
632static int
633np_double(char *p, PyObject *v, const formatdef *f)
634{
635 double x = PyFloat_AsDouble(v);
636 if (x == -1 && PyErr_Occurred()) {
637 PyErr_SetString(StructError,
638 "required argument is not a float");
639 return -1;
640 }
641 memcpy(p, (char *)&x, sizeof(double));
642 return 0;
643}
644
645static int
646np_void_p(char *p, PyObject *v, const formatdef *f)
647{
648 void *x;
649
650 v = get_pylong(v);
651 if (v == NULL)
652 return -1;
653 assert(PyLong_Check(v));
654 x = PyLong_AsVoidPtr(v);
655 Py_DECREF(v);
656 if (x == NULL && PyErr_Occurred())
657 return -1;
658 memcpy(p, (char *)&x, sizeof x);
659 return 0;
660}
661
662static formatdef native_table[] = {
663 {'x', sizeof(char), 0, NULL},
664 {'b', sizeof(char), 0, nu_byte, np_byte},
665 {'B', sizeof(char), 0, nu_ubyte, np_ubyte},
666 {'c', sizeof(char), 0, nu_char, np_char},
667 {'s', sizeof(char), 0, NULL},
668 {'p', sizeof(char), 0, NULL},
669 {'h', sizeof(short), SHORT_ALIGN, nu_short, np_short},
670 {'H', sizeof(short), SHORT_ALIGN, nu_ushort, np_ushort},
671 {'i', sizeof(int), INT_ALIGN, nu_int, np_int},
672 {'I', sizeof(int), INT_ALIGN, nu_uint, np_uint},
673 {'l', sizeof(long), LONG_ALIGN, nu_long, np_long},
674 {'L', sizeof(long), LONG_ALIGN, nu_ulong, np_ulong},
Bob Ippolito232f3c92006-05-23 19:12:41 +0000675#ifdef HAVE_LONG_LONG
676 {'q', sizeof(PY_LONG_LONG), LONG_LONG_ALIGN, nu_longlong, np_longlong},
677 {'Q', sizeof(PY_LONG_LONG), LONG_LONG_ALIGN, nu_ulonglong,np_ulonglong},
678#endif
Thomas Hellerf3c05592008-03-05 15:34:29 +0000679 {'?', sizeof(BOOL_TYPE), BOOL_ALIGN, nu_bool, np_bool},
Bob Ippolitoa99865b2006-05-25 19:56:56 +0000680 {'f', sizeof(float), FLOAT_ALIGN, nu_float, np_float},
681 {'d', sizeof(double), DOUBLE_ALIGN, nu_double, np_double},
682 {'P', sizeof(void *), VOID_P_ALIGN, nu_void_p, np_void_p},
Bob Ippolito232f3c92006-05-23 19:12:41 +0000683 {0}
684};
685
686/* Big-endian routines. *****************************************************/
687
688static PyObject *
689bu_int(const char *p, const formatdef *f)
690{
691 long x = 0;
Bob Ippolitoaa70a172006-05-26 20:25:23 +0000692 Py_ssize_t i = f->size;
Bob Ippolito28b26862006-05-29 15:47:29 +0000693 const unsigned char *bytes = (const unsigned char *)p;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000694 do {
Bob Ippolito28b26862006-05-29 15:47:29 +0000695 x = (x<<8) | *bytes++;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000696 } while (--i > 0);
697 /* Extend the sign bit. */
698 if (SIZEOF_LONG > f->size)
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000699 x |= -(x & (1L << ((8 * f->size) - 1)));
Bob Ippolito232f3c92006-05-23 19:12:41 +0000700 return PyInt_FromLong(x);
701}
702
703static PyObject *
704bu_uint(const char *p, const formatdef *f)
705{
706 unsigned long x = 0;
Bob Ippolitoaa70a172006-05-26 20:25:23 +0000707 Py_ssize_t i = f->size;
Bob Ippolito28b26862006-05-29 15:47:29 +0000708 const unsigned char *bytes = (const unsigned char *)p;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000709 do {
Bob Ippolito28b26862006-05-29 15:47:29 +0000710 x = (x<<8) | *bytes++;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000711 } while (--i > 0);
Bob Ippolito04ab9942006-05-25 19:33:38 +0000712 if (x <= LONG_MAX)
Bob Ippolito232f3c92006-05-23 19:12:41 +0000713 return PyInt_FromLong((long)x);
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000714 return PyLong_FromUnsignedLong(x);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000715}
716
717static PyObject *
718bu_longlong(const char *p, const formatdef *f)
719{
Bob Ippolito90bd0a52006-05-27 11:47:12 +0000720#ifdef HAVE_LONG_LONG
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000721 PY_LONG_LONG x = 0;
Bob Ippolitoaa70a172006-05-26 20:25:23 +0000722 Py_ssize_t i = f->size;
Bob Ippolito28b26862006-05-29 15:47:29 +0000723 const unsigned char *bytes = (const unsigned char *)p;
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000724 do {
Bob Ippolito28b26862006-05-29 15:47:29 +0000725 x = (x<<8) | *bytes++;
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000726 } while (--i > 0);
727 /* Extend the sign bit. */
728 if (SIZEOF_LONG_LONG > f->size)
Kristján Valur Jónsson67387fb2007-04-25 00:17:39 +0000729 x |= -(x & ((PY_LONG_LONG)1 << ((8 * f->size) - 1)));
Bob Ippolito04ab9942006-05-25 19:33:38 +0000730 if (x >= LONG_MIN && x <= LONG_MAX)
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000731 return PyInt_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long));
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000732 return PyLong_FromLongLong(x);
733#else
Bob Ippolito232f3c92006-05-23 19:12:41 +0000734 return _PyLong_FromByteArray((const unsigned char *)p,
735 8,
736 0, /* little-endian */
737 1 /* signed */);
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000738#endif
Bob Ippolito232f3c92006-05-23 19:12:41 +0000739}
740
741static PyObject *
742bu_ulonglong(const char *p, const formatdef *f)
743{
Bob Ippolito90bd0a52006-05-27 11:47:12 +0000744#ifdef HAVE_LONG_LONG
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000745 unsigned PY_LONG_LONG x = 0;
Bob Ippolitoaa70a172006-05-26 20:25:23 +0000746 Py_ssize_t i = f->size;
Bob Ippolito28b26862006-05-29 15:47:29 +0000747 const unsigned char *bytes = (const unsigned char *)p;
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000748 do {
Bob Ippolito28b26862006-05-29 15:47:29 +0000749 x = (x<<8) | *bytes++;
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000750 } while (--i > 0);
Bob Ippolito04ab9942006-05-25 19:33:38 +0000751 if (x <= LONG_MAX)
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000752 return PyInt_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long));
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000753 return PyLong_FromUnsignedLongLong(x);
754#else
Bob Ippolito232f3c92006-05-23 19:12:41 +0000755 return _PyLong_FromByteArray((const unsigned char *)p,
756 8,
757 0, /* little-endian */
758 0 /* signed */);
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000759#endif
Bob Ippolito232f3c92006-05-23 19:12:41 +0000760}
761
762static PyObject *
763bu_float(const char *p, const formatdef *f)
764{
765 return unpack_float(p, 0);
766}
767
768static PyObject *
769bu_double(const char *p, const formatdef *f)
770{
771 return unpack_double(p, 0);
772}
773
Martin v. Löwisaef4c6b2007-01-21 09:33:07 +0000774static PyObject *
775bu_bool(const char *p, const formatdef *f)
776{
777 char x;
778 memcpy((char *)&x, p, sizeof x);
779 return PyBool_FromLong(x != 0);
780}
781
Bob Ippolito232f3c92006-05-23 19:12:41 +0000782static int
783bp_int(char *p, PyObject *v, const formatdef *f)
784{
785 long x;
Bob Ippolitoaa70a172006-05-26 20:25:23 +0000786 Py_ssize_t i;
Mark Dickinson716a9cc2009-09-27 16:39:28 +0000787 if (get_long(v, &x) < 0)
Bob Ippolito232f3c92006-05-23 19:12:41 +0000788 return -1;
789 i = f->size;
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000790 if (i != SIZEOF_LONG) {
791 if ((i == 2) && (x < -32768 || x > 32767))
Mark Dickinson5fd3af22009-07-07 15:08:28 +0000792 return _range_error(f, 0);
Bob Ippolito90bd0a52006-05-27 11:47:12 +0000793#if (SIZEOF_LONG != 4)
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000794 else if ((i == 4) && (x < -2147483648L || x > 2147483647L))
Mark Dickinson5fd3af22009-07-07 15:08:28 +0000795 return _range_error(f, 0);
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000796#endif
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000797 }
Bob Ippolito232f3c92006-05-23 19:12:41 +0000798 do {
799 p[--i] = (char)x;
800 x >>= 8;
801 } while (i > 0);
802 return 0;
803}
804
805static int
806bp_uint(char *p, PyObject *v, const formatdef *f)
807{
808 unsigned long x;
Bob Ippolitoaa70a172006-05-26 20:25:23 +0000809 Py_ssize_t i;
Mark Dickinson716a9cc2009-09-27 16:39:28 +0000810 if (get_ulong(v, &x) < 0)
Bob Ippolito232f3c92006-05-23 19:12:41 +0000811 return -1;
812 i = f->size;
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000813 if (i != SIZEOF_LONG) {
814 unsigned long maxint = 1;
815 maxint <<= (unsigned long)(i * 8);
816 if (x >= maxint)
Mark Dickinson5fd3af22009-07-07 15:08:28 +0000817 return _range_error(f, 1);
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000818 }
Bob Ippolito232f3c92006-05-23 19:12:41 +0000819 do {
820 p[--i] = (char)x;
821 x >>= 8;
822 } while (i > 0);
823 return 0;
824}
825
826static int
827bp_longlong(char *p, PyObject *v, const formatdef *f)
828{
829 int res;
830 v = get_pylong(v);
831 if (v == NULL)
832 return -1;
833 res = _PyLong_AsByteArray((PyLongObject *)v,
834 (unsigned char *)p,
835 8,
836 0, /* little_endian */
837 1 /* signed */);
838 Py_DECREF(v);
839 return res;
840}
841
842static int
843bp_ulonglong(char *p, PyObject *v, const formatdef *f)
844{
845 int res;
846 v = get_pylong(v);
847 if (v == NULL)
848 return -1;
849 res = _PyLong_AsByteArray((PyLongObject *)v,
850 (unsigned char *)p,
851 8,
852 0, /* little_endian */
853 0 /* signed */);
854 Py_DECREF(v);
855 return res;
856}
857
858static int
859bp_float(char *p, PyObject *v, const formatdef *f)
860{
861 double x = PyFloat_AsDouble(v);
862 if (x == -1 && PyErr_Occurred()) {
863 PyErr_SetString(StructError,
864 "required argument is not a float");
865 return -1;
866 }
867 return _PyFloat_Pack4(x, (unsigned char *)p, 0);
868}
869
870static int
871bp_double(char *p, PyObject *v, const formatdef *f)
872{
873 double x = PyFloat_AsDouble(v);
874 if (x == -1 && PyErr_Occurred()) {
875 PyErr_SetString(StructError,
876 "required argument is not a float");
877 return -1;
878 }
879 return _PyFloat_Pack8(x, (unsigned char *)p, 0);
880}
881
Martin v. Löwisaef4c6b2007-01-21 09:33:07 +0000882static int
883bp_bool(char *p, PyObject *v, const formatdef *f)
884{
885 char y;
886 y = PyObject_IsTrue(v);
887 memcpy(p, (char *)&y, sizeof y);
888 return 0;
889}
890
Bob Ippolito232f3c92006-05-23 19:12:41 +0000891static formatdef bigendian_table[] = {
892 {'x', 1, 0, NULL},
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000893 {'b', 1, 0, nu_byte, np_byte},
894 {'B', 1, 0, nu_ubyte, np_ubyte},
Bob Ippolito232f3c92006-05-23 19:12:41 +0000895 {'c', 1, 0, nu_char, np_char},
896 {'s', 1, 0, NULL},
897 {'p', 1, 0, NULL},
898 {'h', 2, 0, bu_int, bp_int},
899 {'H', 2, 0, bu_uint, bp_uint},
900 {'i', 4, 0, bu_int, bp_int},
901 {'I', 4, 0, bu_uint, bp_uint},
902 {'l', 4, 0, bu_int, bp_int},
903 {'L', 4, 0, bu_uint, bp_uint},
904 {'q', 8, 0, bu_longlong, bp_longlong},
905 {'Q', 8, 0, bu_ulonglong, bp_ulonglong},
Thomas Hellerf3c05592008-03-05 15:34:29 +0000906 {'?', 1, 0, bu_bool, bp_bool},
Bob Ippolito232f3c92006-05-23 19:12:41 +0000907 {'f', 4, 0, bu_float, bp_float},
908 {'d', 8, 0, bu_double, bp_double},
909 {0}
910};
911
912/* Little-endian routines. *****************************************************/
913
914static PyObject *
915lu_int(const char *p, const formatdef *f)
916{
917 long x = 0;
Bob Ippolitoaa70a172006-05-26 20:25:23 +0000918 Py_ssize_t i = f->size;
Bob Ippolito28b26862006-05-29 15:47:29 +0000919 const unsigned char *bytes = (const unsigned char *)p;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000920 do {
Bob Ippolito28b26862006-05-29 15:47:29 +0000921 x = (x<<8) | bytes[--i];
Bob Ippolito232f3c92006-05-23 19:12:41 +0000922 } while (i > 0);
923 /* Extend the sign bit. */
924 if (SIZEOF_LONG > f->size)
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000925 x |= -(x & (1L << ((8 * f->size) - 1)));
Bob Ippolito232f3c92006-05-23 19:12:41 +0000926 return PyInt_FromLong(x);
927}
928
929static PyObject *
930lu_uint(const char *p, const formatdef *f)
931{
932 unsigned long x = 0;
Bob Ippolitoaa70a172006-05-26 20:25:23 +0000933 Py_ssize_t i = f->size;
Bob Ippolito28b26862006-05-29 15:47:29 +0000934 const unsigned char *bytes = (const unsigned char *)p;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000935 do {
Bob Ippolito28b26862006-05-29 15:47:29 +0000936 x = (x<<8) | bytes[--i];
Bob Ippolito232f3c92006-05-23 19:12:41 +0000937 } while (i > 0);
Bob Ippolito04ab9942006-05-25 19:33:38 +0000938 if (x <= LONG_MAX)
Bob Ippolito232f3c92006-05-23 19:12:41 +0000939 return PyInt_FromLong((long)x);
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000940 return PyLong_FromUnsignedLong((long)x);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000941}
942
943static PyObject *
944lu_longlong(const char *p, const formatdef *f)
945{
Bob Ippolito90bd0a52006-05-27 11:47:12 +0000946#ifdef HAVE_LONG_LONG
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000947 PY_LONG_LONG x = 0;
Bob Ippolitoaa70a172006-05-26 20:25:23 +0000948 Py_ssize_t i = f->size;
Bob Ippolito28b26862006-05-29 15:47:29 +0000949 const unsigned char *bytes = (const unsigned char *)p;
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000950 do {
Bob Ippolito28b26862006-05-29 15:47:29 +0000951 x = (x<<8) | bytes[--i];
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000952 } while (i > 0);
953 /* Extend the sign bit. */
954 if (SIZEOF_LONG_LONG > f->size)
Kristján Valur Jónsson67387fb2007-04-25 00:17:39 +0000955 x |= -(x & ((PY_LONG_LONG)1 << ((8 * f->size) - 1)));
Bob Ippolito04ab9942006-05-25 19:33:38 +0000956 if (x >= LONG_MIN && x <= LONG_MAX)
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000957 return PyInt_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long));
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000958 return PyLong_FromLongLong(x);
959#else
Bob Ippolito232f3c92006-05-23 19:12:41 +0000960 return _PyLong_FromByteArray((const unsigned char *)p,
961 8,
962 1, /* little-endian */
963 1 /* signed */);
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000964#endif
Bob Ippolito232f3c92006-05-23 19:12:41 +0000965}
966
967static PyObject *
968lu_ulonglong(const char *p, const formatdef *f)
969{
Bob Ippolito90bd0a52006-05-27 11:47:12 +0000970#ifdef HAVE_LONG_LONG
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000971 unsigned PY_LONG_LONG x = 0;
Bob Ippolitoaa70a172006-05-26 20:25:23 +0000972 Py_ssize_t i = f->size;
Bob Ippolito28b26862006-05-29 15:47:29 +0000973 const unsigned char *bytes = (const unsigned char *)p;
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000974 do {
Bob Ippolito28b26862006-05-29 15:47:29 +0000975 x = (x<<8) | bytes[--i];
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000976 } while (i > 0);
Bob Ippolito04ab9942006-05-25 19:33:38 +0000977 if (x <= LONG_MAX)
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000978 return PyInt_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long));
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000979 return PyLong_FromUnsignedLongLong(x);
980#else
Bob Ippolito232f3c92006-05-23 19:12:41 +0000981 return _PyLong_FromByteArray((const unsigned char *)p,
982 8,
983 1, /* little-endian */
984 0 /* signed */);
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000985#endif
Bob Ippolito232f3c92006-05-23 19:12:41 +0000986}
987
988static PyObject *
989lu_float(const char *p, const formatdef *f)
990{
991 return unpack_float(p, 1);
992}
993
994static PyObject *
995lu_double(const char *p, const formatdef *f)
996{
997 return unpack_double(p, 1);
998}
999
1000static int
1001lp_int(char *p, PyObject *v, const formatdef *f)
1002{
1003 long x;
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001004 Py_ssize_t i;
Mark Dickinson716a9cc2009-09-27 16:39:28 +00001005 if (get_long(v, &x) < 0)
Bob Ippolito232f3c92006-05-23 19:12:41 +00001006 return -1;
1007 i = f->size;
Bob Ippolitocd51ca52006-05-27 15:53:49 +00001008 if (i != SIZEOF_LONG) {
1009 if ((i == 2) && (x < -32768 || x > 32767))
Mark Dickinson5fd3af22009-07-07 15:08:28 +00001010 return _range_error(f, 0);
Bob Ippolito90bd0a52006-05-27 11:47:12 +00001011#if (SIZEOF_LONG != 4)
Bob Ippolitocd51ca52006-05-27 15:53:49 +00001012 else if ((i == 4) && (x < -2147483648L || x > 2147483647L))
Mark Dickinson5fd3af22009-07-07 15:08:28 +00001013 return _range_error(f, 0);
Bob Ippolitoe27337b2006-05-26 13:15:44 +00001014#endif
Bob Ippolitocd51ca52006-05-27 15:53:49 +00001015 }
Bob Ippolito232f3c92006-05-23 19:12:41 +00001016 do {
1017 *p++ = (char)x;
1018 x >>= 8;
1019 } while (--i > 0);
1020 return 0;
1021}
1022
1023static int
1024lp_uint(char *p, PyObject *v, const formatdef *f)
1025{
1026 unsigned long x;
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001027 Py_ssize_t i;
Mark Dickinson716a9cc2009-09-27 16:39:28 +00001028 if (get_ulong(v, &x) < 0)
Bob Ippolito232f3c92006-05-23 19:12:41 +00001029 return -1;
1030 i = f->size;
Bob Ippolitocd51ca52006-05-27 15:53:49 +00001031 if (i != SIZEOF_LONG) {
1032 unsigned long maxint = 1;
1033 maxint <<= (unsigned long)(i * 8);
1034 if (x >= maxint)
Mark Dickinson5fd3af22009-07-07 15:08:28 +00001035 return _range_error(f, 1);
Bob Ippolitocd51ca52006-05-27 15:53:49 +00001036 }
Bob Ippolito232f3c92006-05-23 19:12:41 +00001037 do {
1038 *p++ = (char)x;
1039 x >>= 8;
1040 } while (--i > 0);
1041 return 0;
1042}
1043
1044static int
1045lp_longlong(char *p, PyObject *v, const formatdef *f)
1046{
1047 int res;
1048 v = get_pylong(v);
1049 if (v == NULL)
1050 return -1;
1051 res = _PyLong_AsByteArray((PyLongObject*)v,
1052 (unsigned char *)p,
1053 8,
1054 1, /* little_endian */
1055 1 /* signed */);
1056 Py_DECREF(v);
1057 return res;
1058}
1059
1060static int
1061lp_ulonglong(char *p, PyObject *v, const formatdef *f)
1062{
1063 int res;
1064 v = get_pylong(v);
1065 if (v == NULL)
1066 return -1;
1067 res = _PyLong_AsByteArray((PyLongObject*)v,
1068 (unsigned char *)p,
1069 8,
1070 1, /* little_endian */
1071 0 /* signed */);
1072 Py_DECREF(v);
1073 return res;
1074}
1075
1076static int
1077lp_float(char *p, PyObject *v, const formatdef *f)
1078{
1079 double x = PyFloat_AsDouble(v);
1080 if (x == -1 && PyErr_Occurred()) {
1081 PyErr_SetString(StructError,
1082 "required argument is not a float");
1083 return -1;
1084 }
1085 return _PyFloat_Pack4(x, (unsigned char *)p, 1);
1086}
1087
1088static int
1089lp_double(char *p, PyObject *v, const formatdef *f)
1090{
1091 double x = PyFloat_AsDouble(v);
1092 if (x == -1 && PyErr_Occurred()) {
1093 PyErr_SetString(StructError,
1094 "required argument is not a float");
1095 return -1;
1096 }
1097 return _PyFloat_Pack8(x, (unsigned char *)p, 1);
1098}
1099
1100static formatdef lilendian_table[] = {
1101 {'x', 1, 0, NULL},
Bob Ippolitoe27337b2006-05-26 13:15:44 +00001102 {'b', 1, 0, nu_byte, np_byte},
1103 {'B', 1, 0, nu_ubyte, np_ubyte},
Bob Ippolito232f3c92006-05-23 19:12:41 +00001104 {'c', 1, 0, nu_char, np_char},
1105 {'s', 1, 0, NULL},
1106 {'p', 1, 0, NULL},
1107 {'h', 2, 0, lu_int, lp_int},
1108 {'H', 2, 0, lu_uint, lp_uint},
1109 {'i', 4, 0, lu_int, lp_int},
1110 {'I', 4, 0, lu_uint, lp_uint},
1111 {'l', 4, 0, lu_int, lp_int},
1112 {'L', 4, 0, lu_uint, lp_uint},
1113 {'q', 8, 0, lu_longlong, lp_longlong},
1114 {'Q', 8, 0, lu_ulonglong, lp_ulonglong},
Thomas Hellerf3c05592008-03-05 15:34:29 +00001115 {'?', 1, 0, bu_bool, bp_bool}, /* Std rep not endian dep,
Martin v. Löwisaef4c6b2007-01-21 09:33:07 +00001116 but potentially different from native rep -- reuse bx_bool funcs. */
Bob Ippolito232f3c92006-05-23 19:12:41 +00001117 {'f', 4, 0, lu_float, lp_float},
1118 {'d', 8, 0, lu_double, lp_double},
1119 {0}
1120};
1121
1122
1123static const formatdef *
1124whichtable(char **pfmt)
1125{
1126 const char *fmt = (*pfmt)++; /* May be backed out of later */
1127 switch (*fmt) {
1128 case '<':
1129 return lilendian_table;
1130 case '>':
1131 case '!': /* Network byte order is big-endian */
1132 return bigendian_table;
1133 case '=': { /* Host byte order -- different from native in aligment! */
1134 int n = 1;
1135 char *p = (char *) &n;
1136 if (*p == 1)
1137 return lilendian_table;
1138 else
1139 return bigendian_table;
1140 }
1141 default:
1142 --*pfmt; /* Back out of pointer increment */
1143 /* Fall through */
1144 case '@':
1145 return native_table;
1146 }
1147}
1148
1149
1150/* Get the table entry for a format code */
1151
1152static const formatdef *
1153getentry(int c, const formatdef *f)
1154{
1155 for (; f->format != '\0'; f++) {
1156 if (f->format == c) {
1157 return f;
1158 }
1159 }
1160 PyErr_SetString(StructError, "bad char in struct format");
1161 return NULL;
1162}
1163
1164
1165/* Align a size according to a format code */
1166
1167static int
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001168align(Py_ssize_t size, char c, const formatdef *e)
Bob Ippolito232f3c92006-05-23 19:12:41 +00001169{
1170 if (e->format == c) {
1171 if (e->alignment) {
1172 size = ((size + e->alignment - 1)
1173 / e->alignment)
1174 * e->alignment;
1175 }
1176 }
1177 return size;
1178}
1179
1180
1181/* calculate the size of a format string */
1182
1183static int
1184prepare_s(PyStructObject *self)
1185{
1186 const formatdef *f;
1187 const formatdef *e;
1188 formatcode *codes;
Tim Petersc2b550e2006-05-31 14:28:07 +00001189
Bob Ippolito232f3c92006-05-23 19:12:41 +00001190 const char *s;
1191 const char *fmt;
1192 char c;
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001193 Py_ssize_t size, len, num, itemsize, x;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001194
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001195 fmt = PyString_AS_STRING(self->s_format);
Bob Ippolito232f3c92006-05-23 19:12:41 +00001196
1197 f = whichtable((char **)&fmt);
Tim Petersc2b550e2006-05-31 14:28:07 +00001198
Bob Ippolito232f3c92006-05-23 19:12:41 +00001199 s = fmt;
1200 size = 0;
1201 len = 0;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001202 while ((c = *s++) != '\0') {
1203 if (isspace(Py_CHARMASK(c)))
1204 continue;
1205 if ('0' <= c && c <= '9') {
1206 num = c - '0';
1207 while ('0' <= (c = *s++) && c <= '9') {
1208 x = num*10 + (c - '0');
1209 if (x/10 != num) {
1210 PyErr_SetString(
1211 StructError,
1212 "overflow in item count");
1213 return -1;
1214 }
1215 num = x;
1216 }
1217 if (c == '\0')
1218 break;
1219 }
1220 else
1221 num = 1;
1222
1223 e = getentry(c, f);
1224 if (e == NULL)
1225 return -1;
Tim Petersc2b550e2006-05-31 14:28:07 +00001226
Bob Ippolito232f3c92006-05-23 19:12:41 +00001227 switch (c) {
1228 case 's': /* fall through */
1229 case 'p': len++; break;
1230 case 'x': break;
1231 default: len += num; break;
1232 }
Bob Ippolito232f3c92006-05-23 19:12:41 +00001233
1234 itemsize = e->size;
1235 size = align(size, c, e);
1236 x = num * itemsize;
1237 size += x;
1238 if (x/itemsize != num || size < 0) {
1239 PyErr_SetString(StructError,
1240 "total struct size too long");
1241 return -1;
1242 }
1243 }
1244
Gregory P. Smith9d534572008-06-11 07:41:16 +00001245 /* check for overflow */
1246 if ((len + 1) > (PY_SSIZE_T_MAX / sizeof(formatcode))) {
1247 PyErr_NoMemory();
1248 return -1;
1249 }
1250
Bob Ippolito232f3c92006-05-23 19:12:41 +00001251 self->s_size = size;
1252 self->s_len = len;
Bob Ippolitoeb621272006-05-24 15:32:06 +00001253 codes = PyMem_MALLOC((len + 1) * sizeof(formatcode));
Bob Ippolito232f3c92006-05-23 19:12:41 +00001254 if (codes == NULL) {
1255 PyErr_NoMemory();
1256 return -1;
1257 }
1258 self->s_codes = codes;
Tim Petersc2b550e2006-05-31 14:28:07 +00001259
Bob Ippolito232f3c92006-05-23 19:12:41 +00001260 s = fmt;
1261 size = 0;
1262 while ((c = *s++) != '\0') {
1263 if (isspace(Py_CHARMASK(c)))
1264 continue;
1265 if ('0' <= c && c <= '9') {
1266 num = c - '0';
1267 while ('0' <= (c = *s++) && c <= '9')
1268 num = num*10 + (c - '0');
1269 if (c == '\0')
1270 break;
1271 }
1272 else
1273 num = 1;
1274
1275 e = getentry(c, f);
Tim Petersc2b550e2006-05-31 14:28:07 +00001276
Bob Ippolito232f3c92006-05-23 19:12:41 +00001277 size = align(size, c, e);
Bob Ippolitoeb621272006-05-24 15:32:06 +00001278 if (c == 's' || c == 'p') {
Bob Ippolito232f3c92006-05-23 19:12:41 +00001279 codes->offset = size;
Bob Ippolitoeb621272006-05-24 15:32:06 +00001280 codes->size = num;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001281 codes->fmtdef = e;
1282 codes++;
Bob Ippolitoeb621272006-05-24 15:32:06 +00001283 size += num;
1284 } else if (c == 'x') {
1285 size += num;
1286 } else {
1287 while (--num >= 0) {
1288 codes->offset = size;
1289 codes->size = e->size;
1290 codes->fmtdef = e;
1291 codes++;
1292 size += e->size;
1293 }
Bob Ippolito232f3c92006-05-23 19:12:41 +00001294 }
Bob Ippolito232f3c92006-05-23 19:12:41 +00001295 }
1296 codes->fmtdef = NULL;
Bob Ippolitoeb621272006-05-24 15:32:06 +00001297 codes->offset = size;
1298 codes->size = 0;
Tim Petersc2b550e2006-05-31 14:28:07 +00001299
Bob Ippolito232f3c92006-05-23 19:12:41 +00001300 return 0;
1301}
1302
1303static PyObject *
1304s_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1305{
1306 PyObject *self;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001307
1308 assert(type != NULL && type->tp_alloc != NULL);
1309
1310 self = type->tp_alloc(type, 0);
1311 if (self != NULL) {
1312 PyStructObject *s = (PyStructObject*)self;
1313 Py_INCREF(Py_None);
1314 s->s_format = Py_None;
1315 s->s_codes = NULL;
1316 s->s_size = -1;
1317 s->s_len = -1;
1318 }
1319 return self;
1320}
1321
1322static int
1323s_init(PyObject *self, PyObject *args, PyObject *kwds)
1324{
1325 PyStructObject *soself = (PyStructObject *)self;
1326 PyObject *o_format = NULL;
1327 int ret = 0;
1328 static char *kwlist[] = {"format", 0};
1329
1330 assert(PyStruct_Check(self));
1331
1332 if (!PyArg_ParseTupleAndKeywords(args, kwds, "S:Struct", kwlist,
1333 &o_format))
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001334 return -1;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001335
1336 Py_INCREF(o_format);
Amaury Forgeot d'Arc588ff932008-02-16 14:34:57 +00001337 Py_CLEAR(soself->s_format);
Bob Ippolito232f3c92006-05-23 19:12:41 +00001338 soself->s_format = o_format;
Tim Petersc2b550e2006-05-31 14:28:07 +00001339
Bob Ippolito232f3c92006-05-23 19:12:41 +00001340 ret = prepare_s(soself);
1341 return ret;
1342}
1343
1344static void
1345s_dealloc(PyStructObject *s)
1346{
Bob Ippolito232f3c92006-05-23 19:12:41 +00001347 if (s->weakreflist != NULL)
1348 PyObject_ClearWeakRefs((PyObject *)s);
1349 if (s->s_codes != NULL) {
1350 PyMem_FREE(s->s_codes);
1351 }
1352 Py_XDECREF(s->s_format);
Christian Heimese93237d2007-12-19 02:37:44 +00001353 Py_TYPE(s)->tp_free((PyObject *)s);
Bob Ippolito232f3c92006-05-23 19:12:41 +00001354}
1355
Bob Ippolitoeb621272006-05-24 15:32:06 +00001356static PyObject *
1357s_unpack_internal(PyStructObject *soself, char *startfrom) {
1358 formatcode *code;
1359 Py_ssize_t i = 0;
1360 PyObject *result = PyTuple_New(soself->s_len);
1361 if (result == NULL)
1362 return NULL;
1363
1364 for (code = soself->s_codes; code->fmtdef != NULL; code++) {
1365 PyObject *v;
1366 const formatdef *e = code->fmtdef;
1367 const char *res = startfrom + code->offset;
1368 if (e->format == 's') {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001369 v = PyString_FromStringAndSize(res, code->size);
Bob Ippolitoeb621272006-05-24 15:32:06 +00001370 } else if (e->format == 'p') {
1371 Py_ssize_t n = *(unsigned char*)res;
1372 if (n >= code->size)
1373 n = code->size - 1;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001374 v = PyString_FromStringAndSize(res + 1, n);
Bob Ippolitoeb621272006-05-24 15:32:06 +00001375 } else {
1376 v = e->unpack(res, e);
Bob Ippolitoeb621272006-05-24 15:32:06 +00001377 }
Neal Norwitz3c5431e2006-06-11 05:45:25 +00001378 if (v == NULL)
1379 goto fail;
1380 PyTuple_SET_ITEM(result, i++, v);
Bob Ippolitoeb621272006-05-24 15:32:06 +00001381 }
1382
1383 return result;
1384fail:
1385 Py_DECREF(result);
1386 return NULL;
Bob Ippolitocd51ca52006-05-27 15:53:49 +00001387}
Bob Ippolitoeb621272006-05-24 15:32:06 +00001388
1389
Bob Ippolito232f3c92006-05-23 19:12:41 +00001390PyDoc_STRVAR(s_unpack__doc__,
Bob Ippolito1fcdc232006-05-27 12:11:36 +00001391"S.unpack(str) -> (v1, v2, ...)\n\
Bob Ippolito232f3c92006-05-23 19:12:41 +00001392\n\
1393Return tuple containing values unpacked according to this Struct's format.\n\
1394Requires len(str) == self.size. See struct.__doc__ for more on format\n\
1395strings.");
1396
1397static PyObject *
1398s_unpack(PyObject *self, PyObject *inputstr)
1399{
Raymond Hettinger7a3d41f2007-04-05 18:00:03 +00001400 char *start;
1401 Py_ssize_t len;
1402 PyObject *args=NULL, *result;
Bob Ippolitoeb621272006-05-24 15:32:06 +00001403 PyStructObject *soself = (PyStructObject *)self;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001404 assert(PyStruct_Check(self));
Tim Petersc2b550e2006-05-31 14:28:07 +00001405 assert(soself->s_codes != NULL);
Raymond Hettinger7a3d41f2007-04-05 18:00:03 +00001406 if (inputstr == NULL)
1407 goto fail;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001408 if (PyString_Check(inputstr) &&
1409 PyString_GET_SIZE(inputstr) == soself->s_size) {
1410 return s_unpack_internal(soself, PyString_AS_STRING(inputstr));
Bob Ippolito232f3c92006-05-23 19:12:41 +00001411 }
Raymond Hettinger7a3d41f2007-04-05 18:00:03 +00001412 args = PyTuple_Pack(1, inputstr);
1413 if (args == NULL)
1414 return NULL;
1415 if (!PyArg_ParseTuple(args, "s#:unpack", &start, &len))
1416 goto fail;
1417 if (soself->s_size != len)
1418 goto fail;
1419 result = s_unpack_internal(soself, start);
1420 Py_DECREF(args);
1421 return result;
1422
1423fail:
1424 Py_XDECREF(args);
1425 PyErr_Format(StructError,
1426 "unpack requires a string argument of length %zd",
1427 soself->s_size);
1428 return NULL;
Bob Ippolitoeb621272006-05-24 15:32:06 +00001429}
1430
1431PyDoc_STRVAR(s_unpack_from__doc__,
Bob Ippolito1fcdc232006-05-27 12:11:36 +00001432"S.unpack_from(buffer[, offset]) -> (v1, v2, ...)\n\
Bob Ippolitoeb621272006-05-24 15:32:06 +00001433\n\
1434Return tuple containing values unpacked according to this Struct's format.\n\
1435Unlike unpack, unpack_from can unpack values from any object supporting\n\
1436the buffer API, not just str. Requires len(buffer[offset:]) >= self.size.\n\
1437See struct.__doc__ for more on format strings.");
1438
1439static PyObject *
1440s_unpack_from(PyObject *self, PyObject *args, PyObject *kwds)
1441{
1442 static char *kwlist[] = {"buffer", "offset", 0};
1443#if (PY_VERSION_HEX < 0x02050000)
1444 static char *fmt = "z#|i:unpack_from";
1445#else
1446 static char *fmt = "z#|n:unpack_from";
1447#endif
1448 Py_ssize_t buffer_len = 0, offset = 0;
1449 char *buffer = NULL;
1450 PyStructObject *soself = (PyStructObject *)self;
1451 assert(PyStruct_Check(self));
1452 assert(soself->s_codes != NULL);
1453
1454 if (!PyArg_ParseTupleAndKeywords(args, kwds, fmt, kwlist,
1455 &buffer, &buffer_len, &offset))
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001456 return NULL;
Bob Ippolitoeb621272006-05-24 15:32:06 +00001457
1458 if (buffer == NULL) {
1459 PyErr_Format(StructError,
1460 "unpack_from requires a buffer argument");
Bob Ippolito232f3c92006-05-23 19:12:41 +00001461 return NULL;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001462 }
Tim Petersc2b550e2006-05-31 14:28:07 +00001463
Bob Ippolitoeb621272006-05-24 15:32:06 +00001464 if (offset < 0)
1465 offset += buffer_len;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001466
Bob Ippolitoeb621272006-05-24 15:32:06 +00001467 if (offset < 0 || (buffer_len - offset) < soself->s_size) {
1468 PyErr_Format(StructError,
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001469 "unpack_from requires a buffer of at least %zd bytes",
Bob Ippolitoeb621272006-05-24 15:32:06 +00001470 soself->s_size);
1471 return NULL;
1472 }
1473 return s_unpack_internal(soself, buffer + offset);
1474}
Bob Ippolito232f3c92006-05-23 19:12:41 +00001475
Bob Ippolito232f3c92006-05-23 19:12:41 +00001476
Martin Blais2856e5f2006-05-26 12:03:27 +00001477/*
1478 * Guts of the pack function.
1479 *
1480 * Takes a struct object, a tuple of arguments, and offset in that tuple of
1481 * argument for where to start processing the arguments for packing, and a
1482 * character buffer for writing the packed string. The caller must insure
1483 * that the buffer may contain the required length for packing the arguments.
1484 * 0 is returned on success, 1 is returned if there is an error.
1485 *
1486 */
1487static int
1488s_pack_internal(PyStructObject *soself, PyObject *args, int offset, char* buf)
Bob Ippolito232f3c92006-05-23 19:12:41 +00001489{
Bob Ippolito232f3c92006-05-23 19:12:41 +00001490 formatcode *code;
Neal Norwitz3c5431e2006-06-11 05:45:25 +00001491 /* XXX(nnorwitz): why does i need to be a local? can we use
1492 the offset parameter or do we need the wider width? */
Bob Ippolito232f3c92006-05-23 19:12:41 +00001493 Py_ssize_t i;
Martin Blais2856e5f2006-05-26 12:03:27 +00001494
1495 memset(buf, '\0', soself->s_size);
1496 i = offset;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001497 for (code = soself->s_codes; code->fmtdef != NULL; code++) {
1498 Py_ssize_t n;
Neal Norwitz3c5431e2006-06-11 05:45:25 +00001499 PyObject *v = PyTuple_GET_ITEM(args, i++);
Bob Ippolito232f3c92006-05-23 19:12:41 +00001500 const formatdef *e = code->fmtdef;
Martin Blais2856e5f2006-05-26 12:03:27 +00001501 char *res = buf + code->offset;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001502 if (e->format == 's') {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001503 if (!PyString_Check(v)) {
Bob Ippolito232f3c92006-05-23 19:12:41 +00001504 PyErr_SetString(StructError,
Mark Dickinson5fd3af22009-07-07 15:08:28 +00001505 "argument for 's' must "
1506 "be a string");
Martin Blais2856e5f2006-05-26 12:03:27 +00001507 return -1;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001508 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001509 n = PyString_GET_SIZE(v);
Bob Ippolitoeb621272006-05-24 15:32:06 +00001510 if (n > code->size)
1511 n = code->size;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001512 if (n > 0)
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001513 memcpy(res, PyString_AS_STRING(v), n);
Bob Ippolito232f3c92006-05-23 19:12:41 +00001514 } else if (e->format == 'p') {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001515 if (!PyString_Check(v)) {
Bob Ippolito232f3c92006-05-23 19:12:41 +00001516 PyErr_SetString(StructError,
Mark Dickinson5fd3af22009-07-07 15:08:28 +00001517 "argument for 'p' must "
1518 "be a string");
Martin Blais2856e5f2006-05-26 12:03:27 +00001519 return -1;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001520 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001521 n = PyString_GET_SIZE(v);
Bob Ippolitoeb621272006-05-24 15:32:06 +00001522 if (n > (code->size - 1))
1523 n = code->size - 1;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001524 if (n > 0)
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001525 memcpy(res + 1, PyString_AS_STRING(v), n);
Bob Ippolito232f3c92006-05-23 19:12:41 +00001526 if (n > 255)
1527 n = 255;
1528 *res = Py_SAFE_DOWNCAST(n, Py_ssize_t, unsigned char);
Mark Dickinson5fd3af22009-07-07 15:08:28 +00001529 } else if (e->pack(res, v, e) < 0) {
1530 if (strchr(integer_codes, e->format) != NULL &&
1531 PyErr_ExceptionMatches(PyExc_OverflowError))
1532 PyErr_Format(StructError,
1533 "integer out of range for "
1534 "'%c' format code",
1535 e->format);
1536 return -1;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001537 }
1538 }
Tim Petersc2b550e2006-05-31 14:28:07 +00001539
Martin Blais2856e5f2006-05-26 12:03:27 +00001540 /* Success */
1541 return 0;
1542}
Bob Ippolito232f3c92006-05-23 19:12:41 +00001543
Martin Blais2856e5f2006-05-26 12:03:27 +00001544
1545PyDoc_STRVAR(s_pack__doc__,
Bob Ippolito1fcdc232006-05-27 12:11:36 +00001546"S.pack(v1, v2, ...) -> string\n\
Martin Blais2856e5f2006-05-26 12:03:27 +00001547\n\
1548Return a string containing values v1, v2, ... packed according to this\n\
1549Struct's format. See struct.__doc__ for more on format strings.");
1550
1551static PyObject *
1552s_pack(PyObject *self, PyObject *args)
1553{
1554 PyStructObject *soself;
1555 PyObject *result;
1556
1557 /* Validate arguments. */
1558 soself = (PyStructObject *)self;
1559 assert(PyStruct_Check(self));
1560 assert(soself->s_codes != NULL);
Martin Blaisaf2ae722006-06-04 13:49:49 +00001561 if (PyTuple_GET_SIZE(args) != soself->s_len)
Martin Blais2856e5f2006-05-26 12:03:27 +00001562 {
1563 PyErr_Format(StructError,
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001564 "pack requires exactly %zd arguments", soself->s_len);
Martin Blais2856e5f2006-05-26 12:03:27 +00001565 return NULL;
1566 }
Tim Petersc2b550e2006-05-31 14:28:07 +00001567
Martin Blais2856e5f2006-05-26 12:03:27 +00001568 /* Allocate a new string */
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001569 result = PyString_FromStringAndSize((char *)NULL, soself->s_size);
Martin Blais2856e5f2006-05-26 12:03:27 +00001570 if (result == NULL)
1571 return NULL;
Tim Petersc2b550e2006-05-31 14:28:07 +00001572
Martin Blais2856e5f2006-05-26 12:03:27 +00001573 /* Call the guts */
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001574 if ( s_pack_internal(soself, args, 0, PyString_AS_STRING(result)) != 0 ) {
Martin Blais2856e5f2006-05-26 12:03:27 +00001575 Py_DECREF(result);
1576 return NULL;
1577 }
1578
1579 return result;
1580}
1581
Martin Blaisaf2ae722006-06-04 13:49:49 +00001582PyDoc_STRVAR(s_pack_into__doc__,
1583"S.pack_into(buffer, offset, v1, v2, ...)\n\
Martin Blais2856e5f2006-05-26 12:03:27 +00001584\n\
Martin Blaisaf2ae722006-06-04 13:49:49 +00001585Pack the values v1, v2, ... according to this Struct's format, write \n\
Bob Ippolito1fcdc232006-05-27 12:11:36 +00001586the packed bytes into the writable buffer buf starting at offset. Note\n\
1587that the offset is not an optional argument. See struct.__doc__ for \n\
Martin Blais2856e5f2006-05-26 12:03:27 +00001588more on format strings.");
1589
1590static PyObject *
Martin Blaisaf2ae722006-06-04 13:49:49 +00001591s_pack_into(PyObject *self, PyObject *args)
Martin Blais2856e5f2006-05-26 12:03:27 +00001592{
1593 PyStructObject *soself;
1594 char *buffer;
1595 Py_ssize_t buffer_len, offset;
1596
1597 /* Validate arguments. +1 is for the first arg as buffer. */
1598 soself = (PyStructObject *)self;
1599 assert(PyStruct_Check(self));
1600 assert(soself->s_codes != NULL);
Martin Blaisaf2ae722006-06-04 13:49:49 +00001601 if (PyTuple_GET_SIZE(args) != (soself->s_len + 2))
Martin Blais2856e5f2006-05-26 12:03:27 +00001602 {
1603 PyErr_Format(StructError,
Martin Blaisaf2ae722006-06-04 13:49:49 +00001604 "pack_into requires exactly %zd arguments",
Martin Blais2856e5f2006-05-26 12:03:27 +00001605 (soself->s_len + 2));
1606 return NULL;
1607 }
1608
1609 /* Extract a writable memory buffer from the first argument */
Tim Petersc2b550e2006-05-31 14:28:07 +00001610 if ( PyObject_AsWriteBuffer(PyTuple_GET_ITEM(args, 0),
1611 (void**)&buffer, &buffer_len) == -1 ) {
Martin Blais2856e5f2006-05-26 12:03:27 +00001612 return NULL;
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001613 }
1614 assert( buffer_len >= 0 );
Martin Blais2856e5f2006-05-26 12:03:27 +00001615
1616 /* Extract the offset from the first argument */
Martin Blaisaf2ae722006-06-04 13:49:49 +00001617 offset = PyInt_AsSsize_t(PyTuple_GET_ITEM(args, 1));
Benjamin Peterson02252482008-09-30 02:11:07 +00001618 if (offset == -1 && PyErr_Occurred())
1619 return NULL;
Martin Blais2856e5f2006-05-26 12:03:27 +00001620
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001621 /* Support negative offsets. */
Martin Blais2856e5f2006-05-26 12:03:27 +00001622 if (offset < 0)
1623 offset += buffer_len;
1624
1625 /* Check boundaries */
1626 if (offset < 0 || (buffer_len - offset) < soself->s_size) {
1627 PyErr_Format(StructError,
Martin Blaisaf2ae722006-06-04 13:49:49 +00001628 "pack_into requires a buffer of at least %zd bytes",
Martin Blais2856e5f2006-05-26 12:03:27 +00001629 soself->s_size);
1630 return NULL;
1631 }
Tim Petersc2b550e2006-05-31 14:28:07 +00001632
Martin Blais2856e5f2006-05-26 12:03:27 +00001633 /* Call the guts */
1634 if ( s_pack_internal(soself, args, 2, buffer + offset) != 0 ) {
1635 return NULL;
1636 }
1637
Georg Brandlc26025c2006-05-28 21:42:54 +00001638 Py_RETURN_NONE;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001639}
1640
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001641static PyObject *
1642s_get_format(PyStructObject *self, void *unused)
1643{
1644 Py_INCREF(self->s_format);
1645 return self->s_format;
1646}
1647
1648static PyObject *
1649s_get_size(PyStructObject *self, void *unused)
1650{
1651 return PyInt_FromSsize_t(self->s_size);
1652}
Bob Ippolito232f3c92006-05-23 19:12:41 +00001653
1654/* List of functions */
1655
1656static struct PyMethodDef s_methods[] = {
Martin Blaisaf2ae722006-06-04 13:49:49 +00001657 {"pack", s_pack, METH_VARARGS, s_pack__doc__},
1658 {"pack_into", s_pack_into, METH_VARARGS, s_pack_into__doc__},
1659 {"unpack", s_unpack, METH_O, s_unpack__doc__},
Neal Norwitza84dcd72007-05-22 07:16:44 +00001660 {"unpack_from", (PyCFunction)s_unpack_from, METH_VARARGS|METH_KEYWORDS,
Tim Peters5ec2e852006-06-04 15:49:07 +00001661 s_unpack_from__doc__},
Bob Ippolito232f3c92006-05-23 19:12:41 +00001662 {NULL, NULL} /* sentinel */
1663};
1664
1665PyDoc_STRVAR(s__doc__, "Compiled struct object");
1666
1667#define OFF(x) offsetof(PyStructObject, x)
1668
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001669static PyGetSetDef s_getsetlist[] = {
Bob Ippolito1fcdc232006-05-27 12:11:36 +00001670 {"format", (getter)s_get_format, (setter)NULL, "struct format string", NULL},
1671 {"size", (getter)s_get_size, (setter)NULL, "struct size in bytes", NULL},
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001672 {NULL} /* sentinel */
Bob Ippolito232f3c92006-05-23 19:12:41 +00001673};
1674
Bob Ippolito232f3c92006-05-23 19:12:41 +00001675static
1676PyTypeObject PyStructType = {
Martin v. Löwis68192102007-07-21 06:55:02 +00001677 PyVarObject_HEAD_INIT(NULL, 0)
Bob Ippolito232f3c92006-05-23 19:12:41 +00001678 "Struct",
1679 sizeof(PyStructObject),
1680 0,
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001681 (destructor)s_dealloc, /* tp_dealloc */
Bob Ippolito232f3c92006-05-23 19:12:41 +00001682 0, /* tp_print */
1683 0, /* tp_getattr */
1684 0, /* tp_setattr */
1685 0, /* tp_compare */
1686 0, /* tp_repr */
1687 0, /* tp_as_number */
1688 0, /* tp_as_sequence */
1689 0, /* tp_as_mapping */
1690 0, /* tp_hash */
1691 0, /* tp_call */
1692 0, /* tp_str */
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001693 PyObject_GenericGetAttr, /* tp_getattro */
1694 PyObject_GenericSetAttr, /* tp_setattro */
Bob Ippolito232f3c92006-05-23 19:12:41 +00001695 0, /* tp_as_buffer */
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001696 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_WEAKREFS,/* tp_flags */
1697 s__doc__, /* tp_doc */
Bob Ippolito232f3c92006-05-23 19:12:41 +00001698 0, /* tp_traverse */
1699 0, /* tp_clear */
1700 0, /* tp_richcompare */
1701 offsetof(PyStructObject, weakreflist), /* tp_weaklistoffset */
1702 0, /* tp_iter */
1703 0, /* tp_iternext */
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001704 s_methods, /* tp_methods */
1705 NULL, /* tp_members */
1706 s_getsetlist, /* tp_getset */
Bob Ippolito232f3c92006-05-23 19:12:41 +00001707 0, /* tp_base */
1708 0, /* tp_dict */
1709 0, /* tp_descr_get */
1710 0, /* tp_descr_set */
1711 0, /* tp_dictoffset */
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001712 s_init, /* tp_init */
1713 PyType_GenericAlloc,/* tp_alloc */
1714 s_new, /* tp_new */
1715 PyObject_Del, /* tp_free */
Bob Ippolito232f3c92006-05-23 19:12:41 +00001716};
1717
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001718
1719/* ---- Standalone functions ---- */
1720
1721#define MAXCACHE 100
Christian Heimes76d19f62008-01-04 02:54:42 +00001722static PyObject *cache = NULL;
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001723
1724static PyObject *
1725cache_struct(PyObject *fmt)
1726{
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001727 PyObject * s_object;
1728
1729 if (cache == NULL) {
1730 cache = PyDict_New();
1731 if (cache == NULL)
1732 return NULL;
1733 }
1734
1735 s_object = PyDict_GetItem(cache, fmt);
1736 if (s_object != NULL) {
1737 Py_INCREF(s_object);
1738 return s_object;
1739 }
1740
1741 s_object = PyObject_CallFunctionObjArgs((PyObject *)(&PyStructType), fmt, NULL);
1742 if (s_object != NULL) {
1743 if (PyDict_Size(cache) >= MAXCACHE)
1744 PyDict_Clear(cache);
1745 /* Attempt to cache the result */
1746 if (PyDict_SetItem(cache, fmt, s_object) == -1)
1747 PyErr_Clear();
1748 }
1749 return s_object;
1750}
1751
Christian Heimes76d19f62008-01-04 02:54:42 +00001752PyDoc_STRVAR(clearcache_doc,
1753"Clear the internal cache.");
1754
1755static PyObject *
1756clearcache(PyObject *self)
1757{
Raymond Hettinger18e08e52008-01-18 00:10:42 +00001758 Py_CLEAR(cache);
Christian Heimes76d19f62008-01-04 02:54:42 +00001759 Py_RETURN_NONE;
1760}
1761
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001762PyDoc_STRVAR(calcsize_doc,
1763"Return size of C struct described by format string fmt.");
1764
1765static PyObject *
1766calcsize(PyObject *self, PyObject *fmt)
1767{
1768 Py_ssize_t n;
1769 PyObject *s_object = cache_struct(fmt);
1770 if (s_object == NULL)
1771 return NULL;
1772 n = ((PyStructObject *)s_object)->s_size;
1773 Py_DECREF(s_object);
1774 return PyInt_FromSsize_t(n);
1775}
1776
1777PyDoc_STRVAR(pack_doc,
1778"Return string containing values v1, v2, ... packed according to fmt.");
1779
1780static PyObject *
1781pack(PyObject *self, PyObject *args)
1782{
1783 PyObject *s_object, *fmt, *newargs, *result;
1784 Py_ssize_t n = PyTuple_GET_SIZE(args);
1785
1786 if (n == 0) {
1787 PyErr_SetString(PyExc_TypeError, "missing format argument");
1788 return NULL;
1789 }
1790 fmt = PyTuple_GET_ITEM(args, 0);
1791 newargs = PyTuple_GetSlice(args, 1, n);
1792 if (newargs == NULL)
1793 return NULL;
1794
1795 s_object = cache_struct(fmt);
1796 if (s_object == NULL) {
1797 Py_DECREF(newargs);
1798 return NULL;
1799 }
1800 result = s_pack(s_object, newargs);
1801 Py_DECREF(newargs);
1802 Py_DECREF(s_object);
1803 return result;
1804}
1805
1806PyDoc_STRVAR(pack_into_doc,
1807"Pack the values v1, v2, ... according to fmt.\n\
1808Write the packed bytes into the writable buffer buf starting at offset.");
1809
1810static PyObject *
1811pack_into(PyObject *self, PyObject *args)
1812{
1813 PyObject *s_object, *fmt, *newargs, *result;
1814 Py_ssize_t n = PyTuple_GET_SIZE(args);
1815
1816 if (n == 0) {
1817 PyErr_SetString(PyExc_TypeError, "missing format argument");
1818 return NULL;
1819 }
1820 fmt = PyTuple_GET_ITEM(args, 0);
1821 newargs = PyTuple_GetSlice(args, 1, n);
1822 if (newargs == NULL)
1823 return NULL;
1824
1825 s_object = cache_struct(fmt);
1826 if (s_object == NULL) {
1827 Py_DECREF(newargs);
1828 return NULL;
1829 }
1830 result = s_pack_into(s_object, newargs);
1831 Py_DECREF(newargs);
1832 Py_DECREF(s_object);
1833 return result;
1834}
1835
1836PyDoc_STRVAR(unpack_doc,
1837"Unpack the string containing packed C structure data, according to fmt.\n\
1838Requires len(string) == calcsize(fmt).");
1839
1840static PyObject *
1841unpack(PyObject *self, PyObject *args)
1842{
1843 PyObject *s_object, *fmt, *inputstr, *result;
1844
1845 if (!PyArg_UnpackTuple(args, "unpack", 2, 2, &fmt, &inputstr))
1846 return NULL;
1847
1848 s_object = cache_struct(fmt);
1849 if (s_object == NULL)
1850 return NULL;
1851 result = s_unpack(s_object, inputstr);
1852 Py_DECREF(s_object);
1853 return result;
1854}
1855
1856PyDoc_STRVAR(unpack_from_doc,
1857"Unpack the buffer, containing packed C structure data, according to\n\
1858fmt, starting at offset. Requires len(buffer[offset:]) >= calcsize(fmt).");
1859
1860static PyObject *
1861unpack_from(PyObject *self, PyObject *args, PyObject *kwds)
1862{
1863 PyObject *s_object, *fmt, *newargs, *result;
1864 Py_ssize_t n = PyTuple_GET_SIZE(args);
1865
1866 if (n == 0) {
1867 PyErr_SetString(PyExc_TypeError, "missing format argument");
1868 return NULL;
1869 }
1870 fmt = PyTuple_GET_ITEM(args, 0);
1871 newargs = PyTuple_GetSlice(args, 1, n);
1872 if (newargs == NULL)
1873 return NULL;
1874
1875 s_object = cache_struct(fmt);
1876 if (s_object == NULL) {
1877 Py_DECREF(newargs);
1878 return NULL;
1879 }
1880 result = s_unpack_from(s_object, newargs, kwds);
1881 Py_DECREF(newargs);
1882 Py_DECREF(s_object);
1883 return result;
1884}
1885
1886static struct PyMethodDef module_functions[] = {
Christian Heimes76d19f62008-01-04 02:54:42 +00001887 {"_clearcache", (PyCFunction)clearcache, METH_NOARGS, clearcache_doc},
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001888 {"calcsize", calcsize, METH_O, calcsize_doc},
1889 {"pack", pack, METH_VARARGS, pack_doc},
1890 {"pack_into", pack_into, METH_VARARGS, pack_into_doc},
1891 {"unpack", unpack, METH_VARARGS, unpack_doc},
1892 {"unpack_from", (PyCFunction)unpack_from,
1893 METH_VARARGS|METH_KEYWORDS, unpack_from_doc},
1894 {NULL, NULL} /* sentinel */
1895};
1896
1897
Bob Ippolito232f3c92006-05-23 19:12:41 +00001898/* Module initialization */
1899
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001900PyDoc_STRVAR(module_doc,
Mark Dickinson3d830822009-10-08 15:54:10 +00001901"Functions to convert between Python values and C structs represented\n\
1902as Python strings. It uses format strings (explained below) as compact\n\
1903descriptions of the lay-out of the C structs and the intended conversion\n\
1904to/from Python values.\n\
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001905\n\
1906The optional first format char indicates byte order, size and alignment:\n\
Mark Dickinson3d830822009-10-08 15:54:10 +00001907 @: native order, size & alignment (default)\n\
1908 =: native order, std. size & alignment\n\
1909 <: little-endian, std. size & alignment\n\
1910 >: big-endian, std. size & alignment\n\
1911 !: same as >\n\
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001912\n\
1913The remaining chars indicate types of args and must match exactly;\n\
1914these can be preceded by a decimal repeat count:\n\
1915 x: pad byte (no data); c:char; b:signed byte; B:unsigned byte;\n\
Mark Dickinson3d830822009-10-08 15:54:10 +00001916 ?: _Bool (requires C99; if not available, char is used instead)\n\
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001917 h:short; H:unsigned short; i:int; I:unsigned int;\n\
1918 l:long; L:unsigned long; f:float; d:double.\n\
1919Special cases (preceding decimal count indicates length):\n\
1920 s:string (array of char); p: pascal string (with count byte).\n\
1921Special case (only available in native format):\n\
1922 P:an integer type that is wide enough to hold a pointer.\n\
1923Special case (not in native mode unless 'long long' in platform C):\n\
1924 q:long long; Q:unsigned long long\n\
1925Whitespace between formats is ignored.\n\
1926\n\
1927The variable struct.error is an exception raised on errors.\n");
1928
Bob Ippolito232f3c92006-05-23 19:12:41 +00001929PyMODINIT_FUNC
1930init_struct(void)
1931{
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001932 PyObject *ver, *m;
1933
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001934 ver = PyString_FromString("0.2");
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001935 if (ver == NULL)
1936 return;
1937
1938 m = Py_InitModule3("_struct", module_functions, module_doc);
Bob Ippolito232f3c92006-05-23 19:12:41 +00001939 if (m == NULL)
1940 return;
1941
Christian Heimese93237d2007-12-19 02:37:44 +00001942 Py_TYPE(&PyStructType) = &PyType_Type;
Bob Ippolito3fc2bb92006-05-25 19:03:19 +00001943 if (PyType_Ready(&PyStructType) < 0)
1944 return;
1945
Mark Dickinson5fd3af22009-07-07 15:08:28 +00001946 /* This speed trick can't be used until overflow masking goes
1947 away, because native endian always raises exceptions
1948 instead of overflow masking. */
Tim Petersc2b550e2006-05-31 14:28:07 +00001949
Bob Ippolitoa99865b2006-05-25 19:56:56 +00001950 /* Check endian and swap in faster functions */
1951 {
1952 int one = 1;
1953 formatdef *native = native_table;
1954 formatdef *other, *ptr;
1955 if ((int)*(unsigned char*)&one)
1956 other = lilendian_table;
1957 else
1958 other = bigendian_table;
Bob Ippolito964e02a2006-05-25 21:09:45 +00001959 /* Scan through the native table, find a matching
1960 entry in the endian table and swap in the
1961 native implementations whenever possible
1962 (64-bit platforms may not have "standard" sizes) */
Bob Ippolitoa99865b2006-05-25 19:56:56 +00001963 while (native->format != '\0' && other->format != '\0') {
1964 ptr = other;
1965 while (ptr->format != '\0') {
1966 if (ptr->format == native->format) {
Bob Ippolito964e02a2006-05-25 21:09:45 +00001967 /* Match faster when formats are
1968 listed in the same order */
Bob Ippolitoa99865b2006-05-25 19:56:56 +00001969 if (ptr == other)
1970 other++;
Tim Petersc2b550e2006-05-31 14:28:07 +00001971 /* Only use the trick if the
Bob Ippolito964e02a2006-05-25 21:09:45 +00001972 size matches */
1973 if (ptr->size != native->size)
1974 break;
1975 /* Skip float and double, could be
1976 "unknown" float format */
1977 if (ptr->format == 'd' || ptr->format == 'f')
1978 break;
1979 ptr->pack = native->pack;
1980 ptr->unpack = native->unpack;
Bob Ippolitoa99865b2006-05-25 19:56:56 +00001981 break;
1982 }
1983 ptr++;
1984 }
1985 native++;
1986 }
1987 }
Tim Petersc2b550e2006-05-31 14:28:07 +00001988
Bob Ippolito232f3c92006-05-23 19:12:41 +00001989 /* Add some symbolic constants to the module */
1990 if (StructError == NULL) {
1991 StructError = PyErr_NewException("struct.error", NULL, NULL);
1992 if (StructError == NULL)
1993 return;
1994 }
Bob Ippolito04ab9942006-05-25 19:33:38 +00001995
Bob Ippolito232f3c92006-05-23 19:12:41 +00001996 Py_INCREF(StructError);
1997 PyModule_AddObject(m, "error", StructError);
Bob Ippolito04ab9942006-05-25 19:33:38 +00001998
Bob Ippolito232f3c92006-05-23 19:12:41 +00001999 Py_INCREF((PyObject*)&PyStructType);
2000 PyModule_AddObject(m, "Struct", (PyObject*)&PyStructType);
Tim Petersc2b550e2006-05-31 14:28:07 +00002001
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00002002 PyModule_AddObject(m, "__version__", ver);
2003
Bob Ippolito2fd39772006-05-29 22:55:48 +00002004 PyModule_AddIntConstant(m, "_PY_STRUCT_RANGE_CHECKING", 1);
Bob Ippolitoe6c9f982006-08-04 23:59:21 +00002005 PyModule_AddIntConstant(m, "_PY_STRUCT_FLOAT_COERCE", 1);
Bob Ippolito232f3c92006-05-23 19:12:41 +00002006}