blob: d09013fe4efb01da8b53215bb01fd7f9a62a8795 [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 }
Mark Dickinson2db56872010-03-07 17:10:19 +0000158 else {
159 r = NULL; /* silence compiler warning about
160 possibly uninitialized variable */
Mark Dickinson154b7ad2010-03-07 16:24:45 +0000161 assert(0); /* shouldn't ever get here */
Mark Dickinson2db56872010-03-07 17:10:19 +0000162 }
Mark Dickinson154b7ad2010-03-07 16:24:45 +0000163
164 return r;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000165}
166
Mark Dickinson5fd3af22009-07-07 15:08:28 +0000167/* Helper to convert a Python object to a C long. Sets an exception
168 (struct.error for an inconvertible type, OverflowError for
169 out-of-range values) and returns -1 on error. */
Bob Ippolito232f3c92006-05-23 19:12:41 +0000170
171static int
172get_long(PyObject *v, long *p)
173{
Mark Dickinson463dc4b2009-07-05 10:01:24 +0000174 long x;
175
176 v = get_pylong(v);
177 if (v == NULL)
178 return -1;
179 assert(PyLong_Check(v));
180 x = PyLong_AsLong(v);
181 Py_DECREF(v);
Mark Dickinson5fd3af22009-07-07 15:08:28 +0000182 if (x == (long)-1 && PyErr_Occurred())
Bob Ippolito232f3c92006-05-23 19:12:41 +0000183 return -1;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000184 *p = x;
185 return 0;
186}
187
Bob Ippolito232f3c92006-05-23 19:12:41 +0000188/* Same, but handling unsigned long */
189
190static int
191get_ulong(PyObject *v, unsigned long *p)
192{
Mark Dickinson463dc4b2009-07-05 10:01:24 +0000193 unsigned long x;
194
195 v = get_pylong(v);
196 if (v == NULL)
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000197 return -1;
Mark Dickinson463dc4b2009-07-05 10:01:24 +0000198 assert(PyLong_Check(v));
199 x = PyLong_AsUnsignedLong(v);
200 Py_DECREF(v);
Mark Dickinson5fd3af22009-07-07 15:08:28 +0000201 if (x == (unsigned long)-1 && PyErr_Occurred())
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000202 return -1;
Mark Dickinson463dc4b2009-07-05 10:01:24 +0000203 *p = x;
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000204 return 0;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000205}
206
207#ifdef HAVE_LONG_LONG
208
209/* Same, but handling native long long. */
210
211static int
212get_longlong(PyObject *v, PY_LONG_LONG *p)
213{
214 PY_LONG_LONG x;
215
216 v = get_pylong(v);
217 if (v == NULL)
218 return -1;
219 assert(PyLong_Check(v));
220 x = PyLong_AsLongLong(v);
221 Py_DECREF(v);
Mark Dickinson5fd3af22009-07-07 15:08:28 +0000222 if (x == (PY_LONG_LONG)-1 && PyErr_Occurred())
Bob Ippolito232f3c92006-05-23 19:12:41 +0000223 return -1;
224 *p = x;
225 return 0;
226}
227
228/* Same, but handling native unsigned long long. */
229
230static int
231get_ulonglong(PyObject *v, unsigned PY_LONG_LONG *p)
232{
233 unsigned PY_LONG_LONG x;
234
235 v = get_pylong(v);
236 if (v == NULL)
237 return -1;
238 assert(PyLong_Check(v));
239 x = PyLong_AsUnsignedLongLong(v);
240 Py_DECREF(v);
Mark Dickinson5fd3af22009-07-07 15:08:28 +0000241 if (x == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred())
Bob Ippolito232f3c92006-05-23 19:12:41 +0000242 return -1;
243 *p = x;
244 return 0;
245}
246
247#endif
248
249/* Floating point helpers */
250
251static PyObject *
252unpack_float(const char *p, /* start of 4-byte string */
253 int le) /* true for little-endian, false for big-endian */
254{
255 double x;
256
257 x = _PyFloat_Unpack4((unsigned char *)p, le);
258 if (x == -1.0 && PyErr_Occurred())
259 return NULL;
260 return PyFloat_FromDouble(x);
261}
262
263static PyObject *
264unpack_double(const char *p, /* start of 8-byte string */
265 int le) /* true for little-endian, false for big-endian */
266{
267 double x;
268
269 x = _PyFloat_Unpack8((unsigned char *)p, le);
270 if (x == -1.0 && PyErr_Occurred())
271 return NULL;
272 return PyFloat_FromDouble(x);
273}
274
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000275/* Helper to format the range error exceptions */
276static int
Armin Rigo162997e2006-05-29 17:59:47 +0000277_range_error(const formatdef *f, int is_unsigned)
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000278{
Tim Petersd6a6f022006-05-31 15:33:22 +0000279 /* ulargest is the largest unsigned value with f->size bytes.
280 * Note that the simpler:
281 * ((size_t)1 << (f->size * 8)) - 1
Tim Peters72270c22006-05-31 15:34:37 +0000282 * doesn't work when f->size == sizeof(size_t) because C doesn't
283 * define what happens when a left shift count is >= the number of
284 * bits in the integer being shifted; e.g., on some boxes it doesn't
285 * shift at all when they're equal.
Tim Petersd6a6f022006-05-31 15:33:22 +0000286 */
287 const size_t ulargest = (size_t)-1 >> ((SIZEOF_SIZE_T - f->size)*8);
288 assert(f->size >= 1 && f->size <= SIZEOF_SIZE_T);
289 if (is_unsigned)
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000290 PyErr_Format(StructError,
Neal Norwitz971ea112006-05-31 07:43:27 +0000291 "'%c' format requires 0 <= number <= %zu",
Bob Ippolito28b26862006-05-29 15:47:29 +0000292 f->format,
Tim Petersd6a6f022006-05-31 15:33:22 +0000293 ulargest);
294 else {
295 const Py_ssize_t largest = (Py_ssize_t)(ulargest >> 1);
296 PyErr_Format(StructError,
297 "'%c' format requires %zd <= number <= %zd",
298 f->format,
299 ~ largest,
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000300 largest);
301 }
302 return -1;
303}
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000304
305
Bob Ippolito232f3c92006-05-23 19:12:41 +0000306
307/* A large number of small routines follow, with names of the form
308
Bob Ippolitoaa70a172006-05-26 20:25:23 +0000309 [bln][up]_TYPE
Bob Ippolito232f3c92006-05-23 19:12:41 +0000310
311 [bln] distiguishes among big-endian, little-endian and native.
312 [pu] distiguishes between pack (to struct) and unpack (from struct).
313 TYPE is one of char, byte, ubyte, etc.
314*/
315
316/* Native mode routines. ****************************************************/
317/* NOTE:
318 In all n[up]_<type> routines handling types larger than 1 byte, there is
319 *no* guarantee that the p pointer is properly aligned for each type,
320 therefore memcpy is called. An intermediate variable is used to
321 compensate for big-endian architectures.
322 Normally both the intermediate variable and the memcpy call will be
323 skipped by C optimisation in little-endian architectures (gcc >= 2.91
324 does this). */
325
326static PyObject *
327nu_char(const char *p, const formatdef *f)
328{
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000329 return PyString_FromStringAndSize(p, 1);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000330}
331
332static PyObject *
333nu_byte(const char *p, const formatdef *f)
334{
335 return PyInt_FromLong((long) *(signed char *)p);
336}
337
338static PyObject *
339nu_ubyte(const char *p, const formatdef *f)
340{
341 return PyInt_FromLong((long) *(unsigned char *)p);
342}
343
344static PyObject *
345nu_short(const char *p, const formatdef *f)
346{
347 short x;
348 memcpy((char *)&x, p, sizeof x);
349 return PyInt_FromLong((long)x);
350}
351
352static PyObject *
353nu_ushort(const char *p, const formatdef *f)
354{
355 unsigned short x;
356 memcpy((char *)&x, p, sizeof x);
357 return PyInt_FromLong((long)x);
358}
359
360static PyObject *
361nu_int(const char *p, const formatdef *f)
362{
363 int x;
364 memcpy((char *)&x, p, sizeof x);
365 return PyInt_FromLong((long)x);
366}
367
368static PyObject *
369nu_uint(const char *p, const formatdef *f)
370{
371 unsigned int x;
372 memcpy((char *)&x, p, sizeof x);
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000373#if (SIZEOF_LONG > SIZEOF_INT)
374 return PyInt_FromLong((long)x);
375#else
376 if (x <= ((unsigned int)LONG_MAX))
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000377 return PyInt_FromLong((long)x);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000378 return PyLong_FromUnsignedLong((unsigned long)x);
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000379#endif
Bob Ippolito232f3c92006-05-23 19:12:41 +0000380}
381
382static PyObject *
383nu_long(const char *p, const formatdef *f)
384{
385 long x;
386 memcpy((char *)&x, p, sizeof x);
387 return PyInt_FromLong(x);
388}
389
390static PyObject *
391nu_ulong(const char *p, const formatdef *f)
392{
393 unsigned long x;
394 memcpy((char *)&x, p, sizeof x);
Bob Ippolito04ab9942006-05-25 19:33:38 +0000395 if (x <= LONG_MAX)
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000396 return PyInt_FromLong((long)x);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000397 return PyLong_FromUnsignedLong(x);
398}
399
400/* Native mode doesn't support q or Q unless the platform C supports
401 long long (or, on Windows, __int64). */
402
403#ifdef HAVE_LONG_LONG
404
405static PyObject *
406nu_longlong(const char *p, const formatdef *f)
407{
408 PY_LONG_LONG x;
409 memcpy((char *)&x, p, sizeof x);
Bob Ippolito04ab9942006-05-25 19:33:38 +0000410 if (x >= LONG_MIN && x <= LONG_MAX)
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000411 return PyInt_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long));
Bob Ippolito232f3c92006-05-23 19:12:41 +0000412 return PyLong_FromLongLong(x);
413}
414
415static PyObject *
416nu_ulonglong(const char *p, const formatdef *f)
417{
418 unsigned PY_LONG_LONG x;
419 memcpy((char *)&x, p, sizeof x);
Bob Ippolito04ab9942006-05-25 19:33:38 +0000420 if (x <= LONG_MAX)
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000421 return PyInt_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long));
Bob Ippolito232f3c92006-05-23 19:12:41 +0000422 return PyLong_FromUnsignedLongLong(x);
423}
424
425#endif
426
427static PyObject *
Martin v. Löwisaef4c6b2007-01-21 09:33:07 +0000428nu_bool(const char *p, const formatdef *f)
429{
430 BOOL_TYPE x;
431 memcpy((char *)&x, p, sizeof x);
432 return PyBool_FromLong(x != 0);
433}
434
435
436static PyObject *
Bob Ippolito232f3c92006-05-23 19:12:41 +0000437nu_float(const char *p, const formatdef *f)
438{
439 float x;
440 memcpy((char *)&x, p, sizeof x);
441 return PyFloat_FromDouble((double)x);
442}
443
444static PyObject *
445nu_double(const char *p, const formatdef *f)
446{
447 double x;
448 memcpy((char *)&x, p, sizeof x);
449 return PyFloat_FromDouble(x);
450}
451
452static PyObject *
453nu_void_p(const char *p, const formatdef *f)
454{
455 void *x;
456 memcpy((char *)&x, p, sizeof x);
457 return PyLong_FromVoidPtr(x);
458}
459
460static int
461np_byte(char *p, PyObject *v, const formatdef *f)
462{
463 long x;
464 if (get_long(v, &x) < 0)
465 return -1;
466 if (x < -128 || x > 127){
467 PyErr_SetString(StructError,
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000468 "byte format requires -128 <= number <= 127");
Bob Ippolito232f3c92006-05-23 19:12:41 +0000469 return -1;
470 }
471 *p = (char)x;
472 return 0;
473}
474
475static int
476np_ubyte(char *p, PyObject *v, const formatdef *f)
477{
478 long x;
479 if (get_long(v, &x) < 0)
480 return -1;
481 if (x < 0 || x > 255){
482 PyErr_SetString(StructError,
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000483 "ubyte format requires 0 <= number <= 255");
Bob Ippolito232f3c92006-05-23 19:12:41 +0000484 return -1;
485 }
486 *p = (char)x;
487 return 0;
488}
489
490static int
491np_char(char *p, PyObject *v, const formatdef *f)
492{
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000493 if (!PyString_Check(v) || PyString_Size(v) != 1) {
Bob Ippolito232f3c92006-05-23 19:12:41 +0000494 PyErr_SetString(StructError,
495 "char format require string of length 1");
496 return -1;
497 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000498 *p = *PyString_AsString(v);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000499 return 0;
500}
501
502static int
503np_short(char *p, PyObject *v, const formatdef *f)
504{
505 long x;
506 short y;
507 if (get_long(v, &x) < 0)
508 return -1;
509 if (x < SHRT_MIN || x > SHRT_MAX){
510 PyErr_SetString(StructError,
511 "short format requires " STRINGIFY(SHRT_MIN)
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000512 " <= number <= " STRINGIFY(SHRT_MAX));
Bob Ippolito232f3c92006-05-23 19:12:41 +0000513 return -1;
514 }
515 y = (short)x;
516 memcpy(p, (char *)&y, sizeof y);
517 return 0;
518}
519
520static int
521np_ushort(char *p, PyObject *v, const formatdef *f)
522{
523 long x;
524 unsigned short y;
525 if (get_long(v, &x) < 0)
526 return -1;
527 if (x < 0 || x > USHRT_MAX){
528 PyErr_SetString(StructError,
Mark Dickinson24766ba2009-07-07 10:18:22 +0000529 "ushort format requires 0 <= number <= " STRINGIFY(USHRT_MAX));
Bob Ippolito232f3c92006-05-23 19:12:41 +0000530 return -1;
531 }
532 y = (unsigned short)x;
533 memcpy(p, (char *)&y, sizeof y);
534 return 0;
535}
536
537static int
538np_int(char *p, PyObject *v, const formatdef *f)
539{
540 long x;
541 int y;
542 if (get_long(v, &x) < 0)
543 return -1;
Bob Ippolito90bd0a52006-05-27 11:47:12 +0000544#if (SIZEOF_LONG > SIZEOF_INT)
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000545 if ((x < ((long)INT_MIN)) || (x > ((long)INT_MAX)))
Mark Dickinson5fd3af22009-07-07 15:08:28 +0000546 return _range_error(f, 0);
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000547#endif
Bob Ippolito232f3c92006-05-23 19:12:41 +0000548 y = (int)x;
549 memcpy(p, (char *)&y, sizeof y);
550 return 0;
551}
552
553static int
554np_uint(char *p, PyObject *v, const formatdef *f)
555{
556 unsigned long x;
557 unsigned int y;
Mark Dickinson716a9cc2009-09-27 16:39:28 +0000558 if (get_ulong(v, &x) < 0)
Georg Brandl6269fec2009-01-01 12:15:31 +0000559 return -1;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000560 y = (unsigned int)x;
Bob Ippolito90bd0a52006-05-27 11:47:12 +0000561#if (SIZEOF_LONG > SIZEOF_INT)
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000562 if (x > ((unsigned long)UINT_MAX))
Mark Dickinson5fd3af22009-07-07 15:08:28 +0000563 return _range_error(f, 1);
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000564#endif
Bob Ippolito232f3c92006-05-23 19:12:41 +0000565 memcpy(p, (char *)&y, sizeof y);
566 return 0;
567}
568
569static int
570np_long(char *p, PyObject *v, const formatdef *f)
571{
572 long x;
573 if (get_long(v, &x) < 0)
574 return -1;
575 memcpy(p, (char *)&x, sizeof x);
576 return 0;
577}
578
579static int
580np_ulong(char *p, PyObject *v, const formatdef *f)
581{
582 unsigned long x;
Mark Dickinson716a9cc2009-09-27 16:39:28 +0000583 if (get_ulong(v, &x) < 0)
Georg Brandl6269fec2009-01-01 12:15:31 +0000584 return -1;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000585 memcpy(p, (char *)&x, sizeof x);
586 return 0;
587}
588
589#ifdef HAVE_LONG_LONG
590
591static int
592np_longlong(char *p, PyObject *v, const formatdef *f)
593{
594 PY_LONG_LONG x;
595 if (get_longlong(v, &x) < 0)
596 return -1;
597 memcpy(p, (char *)&x, sizeof x);
598 return 0;
599}
600
601static int
602np_ulonglong(char *p, PyObject *v, const formatdef *f)
603{
604 unsigned PY_LONG_LONG x;
605 if (get_ulonglong(v, &x) < 0)
606 return -1;
607 memcpy(p, (char *)&x, sizeof x);
608 return 0;
609}
610#endif
611
Martin v. Löwisaef4c6b2007-01-21 09:33:07 +0000612
613static int
614np_bool(char *p, PyObject *v, const formatdef *f)
615{
616 BOOL_TYPE y;
617 y = PyObject_IsTrue(v);
618 memcpy(p, (char *)&y, sizeof y);
619 return 0;
620}
621
Bob Ippolito232f3c92006-05-23 19:12:41 +0000622static int
623np_float(char *p, PyObject *v, const formatdef *f)
624{
625 float x = (float)PyFloat_AsDouble(v);
626 if (x == -1 && PyErr_Occurred()) {
627 PyErr_SetString(StructError,
628 "required argument is not a float");
629 return -1;
630 }
631 memcpy(p, (char *)&x, sizeof x);
632 return 0;
633}
634
635static int
636np_double(char *p, PyObject *v, const formatdef *f)
637{
638 double x = PyFloat_AsDouble(v);
639 if (x == -1 && PyErr_Occurred()) {
640 PyErr_SetString(StructError,
641 "required argument is not a float");
642 return -1;
643 }
644 memcpy(p, (char *)&x, sizeof(double));
645 return 0;
646}
647
648static int
649np_void_p(char *p, PyObject *v, const formatdef *f)
650{
651 void *x;
652
653 v = get_pylong(v);
654 if (v == NULL)
655 return -1;
656 assert(PyLong_Check(v));
657 x = PyLong_AsVoidPtr(v);
658 Py_DECREF(v);
659 if (x == NULL && PyErr_Occurred())
660 return -1;
661 memcpy(p, (char *)&x, sizeof x);
662 return 0;
663}
664
665static formatdef native_table[] = {
666 {'x', sizeof(char), 0, NULL},
667 {'b', sizeof(char), 0, nu_byte, np_byte},
668 {'B', sizeof(char), 0, nu_ubyte, np_ubyte},
669 {'c', sizeof(char), 0, nu_char, np_char},
670 {'s', sizeof(char), 0, NULL},
671 {'p', sizeof(char), 0, NULL},
672 {'h', sizeof(short), SHORT_ALIGN, nu_short, np_short},
673 {'H', sizeof(short), SHORT_ALIGN, nu_ushort, np_ushort},
674 {'i', sizeof(int), INT_ALIGN, nu_int, np_int},
675 {'I', sizeof(int), INT_ALIGN, nu_uint, np_uint},
676 {'l', sizeof(long), LONG_ALIGN, nu_long, np_long},
677 {'L', sizeof(long), LONG_ALIGN, nu_ulong, np_ulong},
Bob Ippolito232f3c92006-05-23 19:12:41 +0000678#ifdef HAVE_LONG_LONG
679 {'q', sizeof(PY_LONG_LONG), LONG_LONG_ALIGN, nu_longlong, np_longlong},
680 {'Q', sizeof(PY_LONG_LONG), LONG_LONG_ALIGN, nu_ulonglong,np_ulonglong},
681#endif
Thomas Hellerf3c05592008-03-05 15:34:29 +0000682 {'?', sizeof(BOOL_TYPE), BOOL_ALIGN, nu_bool, np_bool},
Bob Ippolitoa99865b2006-05-25 19:56:56 +0000683 {'f', sizeof(float), FLOAT_ALIGN, nu_float, np_float},
684 {'d', sizeof(double), DOUBLE_ALIGN, nu_double, np_double},
685 {'P', sizeof(void *), VOID_P_ALIGN, nu_void_p, np_void_p},
Bob Ippolito232f3c92006-05-23 19:12:41 +0000686 {0}
687};
688
689/* Big-endian routines. *****************************************************/
690
691static PyObject *
692bu_int(const char *p, const formatdef *f)
693{
694 long x = 0;
Bob Ippolitoaa70a172006-05-26 20:25:23 +0000695 Py_ssize_t i = f->size;
Bob Ippolito28b26862006-05-29 15:47:29 +0000696 const unsigned char *bytes = (const unsigned char *)p;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000697 do {
Bob Ippolito28b26862006-05-29 15:47:29 +0000698 x = (x<<8) | *bytes++;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000699 } while (--i > 0);
700 /* Extend the sign bit. */
701 if (SIZEOF_LONG > f->size)
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000702 x |= -(x & (1L << ((8 * f->size) - 1)));
Bob Ippolito232f3c92006-05-23 19:12:41 +0000703 return PyInt_FromLong(x);
704}
705
706static PyObject *
707bu_uint(const char *p, const formatdef *f)
708{
709 unsigned long x = 0;
Bob Ippolitoaa70a172006-05-26 20:25:23 +0000710 Py_ssize_t i = f->size;
Bob Ippolito28b26862006-05-29 15:47:29 +0000711 const unsigned char *bytes = (const unsigned char *)p;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000712 do {
Bob Ippolito28b26862006-05-29 15:47:29 +0000713 x = (x<<8) | *bytes++;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000714 } while (--i > 0);
Bob Ippolito04ab9942006-05-25 19:33:38 +0000715 if (x <= LONG_MAX)
Bob Ippolito232f3c92006-05-23 19:12:41 +0000716 return PyInt_FromLong((long)x);
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000717 return PyLong_FromUnsignedLong(x);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000718}
719
720static PyObject *
721bu_longlong(const char *p, const formatdef *f)
722{
Bob Ippolito90bd0a52006-05-27 11:47:12 +0000723#ifdef HAVE_LONG_LONG
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000724 PY_LONG_LONG x = 0;
Bob Ippolitoaa70a172006-05-26 20:25:23 +0000725 Py_ssize_t i = f->size;
Bob Ippolito28b26862006-05-29 15:47:29 +0000726 const unsigned char *bytes = (const unsigned char *)p;
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000727 do {
Bob Ippolito28b26862006-05-29 15:47:29 +0000728 x = (x<<8) | *bytes++;
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000729 } while (--i > 0);
730 /* Extend the sign bit. */
731 if (SIZEOF_LONG_LONG > f->size)
Kristján Valur Jónsson67387fb2007-04-25 00:17:39 +0000732 x |= -(x & ((PY_LONG_LONG)1 << ((8 * f->size) - 1)));
Bob Ippolito04ab9942006-05-25 19:33:38 +0000733 if (x >= LONG_MIN && x <= LONG_MAX)
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000734 return PyInt_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long));
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000735 return PyLong_FromLongLong(x);
736#else
Bob Ippolito232f3c92006-05-23 19:12:41 +0000737 return _PyLong_FromByteArray((const unsigned char *)p,
738 8,
739 0, /* little-endian */
740 1 /* signed */);
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000741#endif
Bob Ippolito232f3c92006-05-23 19:12:41 +0000742}
743
744static PyObject *
745bu_ulonglong(const char *p, const formatdef *f)
746{
Bob Ippolito90bd0a52006-05-27 11:47:12 +0000747#ifdef HAVE_LONG_LONG
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000748 unsigned PY_LONG_LONG x = 0;
Bob Ippolitoaa70a172006-05-26 20:25:23 +0000749 Py_ssize_t i = f->size;
Bob Ippolito28b26862006-05-29 15:47:29 +0000750 const unsigned char *bytes = (const unsigned char *)p;
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000751 do {
Bob Ippolito28b26862006-05-29 15:47:29 +0000752 x = (x<<8) | *bytes++;
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000753 } while (--i > 0);
Bob Ippolito04ab9942006-05-25 19:33:38 +0000754 if (x <= LONG_MAX)
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000755 return PyInt_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long));
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000756 return PyLong_FromUnsignedLongLong(x);
757#else
Bob Ippolito232f3c92006-05-23 19:12:41 +0000758 return _PyLong_FromByteArray((const unsigned char *)p,
759 8,
760 0, /* little-endian */
761 0 /* signed */);
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000762#endif
Bob Ippolito232f3c92006-05-23 19:12:41 +0000763}
764
765static PyObject *
766bu_float(const char *p, const formatdef *f)
767{
768 return unpack_float(p, 0);
769}
770
771static PyObject *
772bu_double(const char *p, const formatdef *f)
773{
774 return unpack_double(p, 0);
775}
776
Martin v. Löwisaef4c6b2007-01-21 09:33:07 +0000777static PyObject *
778bu_bool(const char *p, const formatdef *f)
779{
780 char x;
781 memcpy((char *)&x, p, sizeof x);
782 return PyBool_FromLong(x != 0);
783}
784
Bob Ippolito232f3c92006-05-23 19:12:41 +0000785static int
786bp_int(char *p, PyObject *v, const formatdef *f)
787{
788 long x;
Bob Ippolitoaa70a172006-05-26 20:25:23 +0000789 Py_ssize_t i;
Mark Dickinson716a9cc2009-09-27 16:39:28 +0000790 if (get_long(v, &x) < 0)
Bob Ippolito232f3c92006-05-23 19:12:41 +0000791 return -1;
792 i = f->size;
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000793 if (i != SIZEOF_LONG) {
794 if ((i == 2) && (x < -32768 || x > 32767))
Mark Dickinson5fd3af22009-07-07 15:08:28 +0000795 return _range_error(f, 0);
Bob Ippolito90bd0a52006-05-27 11:47:12 +0000796#if (SIZEOF_LONG != 4)
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000797 else if ((i == 4) && (x < -2147483648L || x > 2147483647L))
Mark Dickinson5fd3af22009-07-07 15:08:28 +0000798 return _range_error(f, 0);
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000799#endif
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000800 }
Bob Ippolito232f3c92006-05-23 19:12:41 +0000801 do {
802 p[--i] = (char)x;
803 x >>= 8;
804 } while (i > 0);
805 return 0;
806}
807
808static int
809bp_uint(char *p, PyObject *v, const formatdef *f)
810{
811 unsigned long x;
Bob Ippolitoaa70a172006-05-26 20:25:23 +0000812 Py_ssize_t i;
Mark Dickinson716a9cc2009-09-27 16:39:28 +0000813 if (get_ulong(v, &x) < 0)
Bob Ippolito232f3c92006-05-23 19:12:41 +0000814 return -1;
815 i = f->size;
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000816 if (i != SIZEOF_LONG) {
817 unsigned long maxint = 1;
818 maxint <<= (unsigned long)(i * 8);
819 if (x >= maxint)
Mark Dickinson5fd3af22009-07-07 15:08:28 +0000820 return _range_error(f, 1);
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000821 }
Bob Ippolito232f3c92006-05-23 19:12:41 +0000822 do {
823 p[--i] = (char)x;
824 x >>= 8;
825 } while (i > 0);
826 return 0;
827}
828
829static int
830bp_longlong(char *p, PyObject *v, const formatdef *f)
831{
832 int res;
833 v = get_pylong(v);
834 if (v == NULL)
835 return -1;
836 res = _PyLong_AsByteArray((PyLongObject *)v,
837 (unsigned char *)p,
838 8,
839 0, /* little_endian */
840 1 /* signed */);
841 Py_DECREF(v);
842 return res;
843}
844
845static int
846bp_ulonglong(char *p, PyObject *v, const formatdef *f)
847{
848 int res;
849 v = get_pylong(v);
850 if (v == NULL)
851 return -1;
852 res = _PyLong_AsByteArray((PyLongObject *)v,
853 (unsigned char *)p,
854 8,
855 0, /* little_endian */
856 0 /* signed */);
857 Py_DECREF(v);
858 return res;
859}
860
861static int
862bp_float(char *p, PyObject *v, const formatdef *f)
863{
864 double x = PyFloat_AsDouble(v);
865 if (x == -1 && PyErr_Occurred()) {
866 PyErr_SetString(StructError,
867 "required argument is not a float");
868 return -1;
869 }
870 return _PyFloat_Pack4(x, (unsigned char *)p, 0);
871}
872
873static int
874bp_double(char *p, PyObject *v, const formatdef *f)
875{
876 double x = PyFloat_AsDouble(v);
877 if (x == -1 && PyErr_Occurred()) {
878 PyErr_SetString(StructError,
879 "required argument is not a float");
880 return -1;
881 }
882 return _PyFloat_Pack8(x, (unsigned char *)p, 0);
883}
884
Martin v. Löwisaef4c6b2007-01-21 09:33:07 +0000885static int
886bp_bool(char *p, PyObject *v, const formatdef *f)
887{
888 char y;
889 y = PyObject_IsTrue(v);
890 memcpy(p, (char *)&y, sizeof y);
891 return 0;
892}
893
Bob Ippolito232f3c92006-05-23 19:12:41 +0000894static formatdef bigendian_table[] = {
895 {'x', 1, 0, NULL},
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000896 {'b', 1, 0, nu_byte, np_byte},
897 {'B', 1, 0, nu_ubyte, np_ubyte},
Bob Ippolito232f3c92006-05-23 19:12:41 +0000898 {'c', 1, 0, nu_char, np_char},
899 {'s', 1, 0, NULL},
900 {'p', 1, 0, NULL},
901 {'h', 2, 0, bu_int, bp_int},
902 {'H', 2, 0, bu_uint, bp_uint},
903 {'i', 4, 0, bu_int, bp_int},
904 {'I', 4, 0, bu_uint, bp_uint},
905 {'l', 4, 0, bu_int, bp_int},
906 {'L', 4, 0, bu_uint, bp_uint},
907 {'q', 8, 0, bu_longlong, bp_longlong},
908 {'Q', 8, 0, bu_ulonglong, bp_ulonglong},
Thomas Hellerf3c05592008-03-05 15:34:29 +0000909 {'?', 1, 0, bu_bool, bp_bool},
Bob Ippolito232f3c92006-05-23 19:12:41 +0000910 {'f', 4, 0, bu_float, bp_float},
911 {'d', 8, 0, bu_double, bp_double},
912 {0}
913};
914
915/* Little-endian routines. *****************************************************/
916
917static PyObject *
918lu_int(const char *p, const formatdef *f)
919{
920 long x = 0;
Bob Ippolitoaa70a172006-05-26 20:25:23 +0000921 Py_ssize_t i = f->size;
Bob Ippolito28b26862006-05-29 15:47:29 +0000922 const unsigned char *bytes = (const unsigned char *)p;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000923 do {
Bob Ippolito28b26862006-05-29 15:47:29 +0000924 x = (x<<8) | bytes[--i];
Bob Ippolito232f3c92006-05-23 19:12:41 +0000925 } while (i > 0);
926 /* Extend the sign bit. */
927 if (SIZEOF_LONG > f->size)
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000928 x |= -(x & (1L << ((8 * f->size) - 1)));
Bob Ippolito232f3c92006-05-23 19:12:41 +0000929 return PyInt_FromLong(x);
930}
931
932static PyObject *
933lu_uint(const char *p, const formatdef *f)
934{
935 unsigned long x = 0;
Bob Ippolitoaa70a172006-05-26 20:25:23 +0000936 Py_ssize_t i = f->size;
Bob Ippolito28b26862006-05-29 15:47:29 +0000937 const unsigned char *bytes = (const unsigned char *)p;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000938 do {
Bob Ippolito28b26862006-05-29 15:47:29 +0000939 x = (x<<8) | bytes[--i];
Bob Ippolito232f3c92006-05-23 19:12:41 +0000940 } while (i > 0);
Bob Ippolito04ab9942006-05-25 19:33:38 +0000941 if (x <= LONG_MAX)
Bob Ippolito232f3c92006-05-23 19:12:41 +0000942 return PyInt_FromLong((long)x);
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000943 return PyLong_FromUnsignedLong((long)x);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000944}
945
946static PyObject *
947lu_longlong(const char *p, const formatdef *f)
948{
Bob Ippolito90bd0a52006-05-27 11:47:12 +0000949#ifdef HAVE_LONG_LONG
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000950 PY_LONG_LONG x = 0;
Bob Ippolitoaa70a172006-05-26 20:25:23 +0000951 Py_ssize_t i = f->size;
Bob Ippolito28b26862006-05-29 15:47:29 +0000952 const unsigned char *bytes = (const unsigned char *)p;
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000953 do {
Bob Ippolito28b26862006-05-29 15:47:29 +0000954 x = (x<<8) | bytes[--i];
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000955 } while (i > 0);
956 /* Extend the sign bit. */
957 if (SIZEOF_LONG_LONG > f->size)
Kristján Valur Jónsson67387fb2007-04-25 00:17:39 +0000958 x |= -(x & ((PY_LONG_LONG)1 << ((8 * f->size) - 1)));
Bob Ippolito04ab9942006-05-25 19:33:38 +0000959 if (x >= LONG_MIN && x <= LONG_MAX)
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000960 return PyInt_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long));
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000961 return PyLong_FromLongLong(x);
962#else
Bob Ippolito232f3c92006-05-23 19:12:41 +0000963 return _PyLong_FromByteArray((const unsigned char *)p,
964 8,
965 1, /* little-endian */
966 1 /* signed */);
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000967#endif
Bob Ippolito232f3c92006-05-23 19:12:41 +0000968}
969
970static PyObject *
971lu_ulonglong(const char *p, const formatdef *f)
972{
Bob Ippolito90bd0a52006-05-27 11:47:12 +0000973#ifdef HAVE_LONG_LONG
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000974 unsigned PY_LONG_LONG x = 0;
Bob Ippolitoaa70a172006-05-26 20:25:23 +0000975 Py_ssize_t i = f->size;
Bob Ippolito28b26862006-05-29 15:47:29 +0000976 const unsigned char *bytes = (const unsigned char *)p;
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000977 do {
Bob Ippolito28b26862006-05-29 15:47:29 +0000978 x = (x<<8) | bytes[--i];
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000979 } while (i > 0);
Bob Ippolito04ab9942006-05-25 19:33:38 +0000980 if (x <= LONG_MAX)
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000981 return PyInt_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long));
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000982 return PyLong_FromUnsignedLongLong(x);
983#else
Bob Ippolito232f3c92006-05-23 19:12:41 +0000984 return _PyLong_FromByteArray((const unsigned char *)p,
985 8,
986 1, /* little-endian */
987 0 /* signed */);
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000988#endif
Bob Ippolito232f3c92006-05-23 19:12:41 +0000989}
990
991static PyObject *
992lu_float(const char *p, const formatdef *f)
993{
994 return unpack_float(p, 1);
995}
996
997static PyObject *
998lu_double(const char *p, const formatdef *f)
999{
1000 return unpack_double(p, 1);
1001}
1002
1003static int
1004lp_int(char *p, PyObject *v, const formatdef *f)
1005{
1006 long x;
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001007 Py_ssize_t i;
Mark Dickinson716a9cc2009-09-27 16:39:28 +00001008 if (get_long(v, &x) < 0)
Bob Ippolito232f3c92006-05-23 19:12:41 +00001009 return -1;
1010 i = f->size;
Bob Ippolitocd51ca52006-05-27 15:53:49 +00001011 if (i != SIZEOF_LONG) {
1012 if ((i == 2) && (x < -32768 || x > 32767))
Mark Dickinson5fd3af22009-07-07 15:08:28 +00001013 return _range_error(f, 0);
Bob Ippolito90bd0a52006-05-27 11:47:12 +00001014#if (SIZEOF_LONG != 4)
Bob Ippolitocd51ca52006-05-27 15:53:49 +00001015 else if ((i == 4) && (x < -2147483648L || x > 2147483647L))
Mark Dickinson5fd3af22009-07-07 15:08:28 +00001016 return _range_error(f, 0);
Bob Ippolitoe27337b2006-05-26 13:15:44 +00001017#endif
Bob Ippolitocd51ca52006-05-27 15:53:49 +00001018 }
Bob Ippolito232f3c92006-05-23 19:12:41 +00001019 do {
1020 *p++ = (char)x;
1021 x >>= 8;
1022 } while (--i > 0);
1023 return 0;
1024}
1025
1026static int
1027lp_uint(char *p, PyObject *v, const formatdef *f)
1028{
1029 unsigned long x;
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001030 Py_ssize_t i;
Mark Dickinson716a9cc2009-09-27 16:39:28 +00001031 if (get_ulong(v, &x) < 0)
Bob Ippolito232f3c92006-05-23 19:12:41 +00001032 return -1;
1033 i = f->size;
Bob Ippolitocd51ca52006-05-27 15:53:49 +00001034 if (i != SIZEOF_LONG) {
1035 unsigned long maxint = 1;
1036 maxint <<= (unsigned long)(i * 8);
1037 if (x >= maxint)
Mark Dickinson5fd3af22009-07-07 15:08:28 +00001038 return _range_error(f, 1);
Bob Ippolitocd51ca52006-05-27 15:53:49 +00001039 }
Bob Ippolito232f3c92006-05-23 19:12:41 +00001040 do {
1041 *p++ = (char)x;
1042 x >>= 8;
1043 } while (--i > 0);
1044 return 0;
1045}
1046
1047static int
1048lp_longlong(char *p, PyObject *v, const formatdef *f)
1049{
1050 int res;
1051 v = get_pylong(v);
1052 if (v == NULL)
1053 return -1;
1054 res = _PyLong_AsByteArray((PyLongObject*)v,
1055 (unsigned char *)p,
1056 8,
1057 1, /* little_endian */
1058 1 /* signed */);
1059 Py_DECREF(v);
1060 return res;
1061}
1062
1063static int
1064lp_ulonglong(char *p, PyObject *v, const formatdef *f)
1065{
1066 int res;
1067 v = get_pylong(v);
1068 if (v == NULL)
1069 return -1;
1070 res = _PyLong_AsByteArray((PyLongObject*)v,
1071 (unsigned char *)p,
1072 8,
1073 1, /* little_endian */
1074 0 /* signed */);
1075 Py_DECREF(v);
1076 return res;
1077}
1078
1079static int
1080lp_float(char *p, PyObject *v, const formatdef *f)
1081{
1082 double x = PyFloat_AsDouble(v);
1083 if (x == -1 && PyErr_Occurred()) {
1084 PyErr_SetString(StructError,
1085 "required argument is not a float");
1086 return -1;
1087 }
1088 return _PyFloat_Pack4(x, (unsigned char *)p, 1);
1089}
1090
1091static int
1092lp_double(char *p, PyObject *v, const formatdef *f)
1093{
1094 double x = PyFloat_AsDouble(v);
1095 if (x == -1 && PyErr_Occurred()) {
1096 PyErr_SetString(StructError,
1097 "required argument is not a float");
1098 return -1;
1099 }
1100 return _PyFloat_Pack8(x, (unsigned char *)p, 1);
1101}
1102
1103static formatdef lilendian_table[] = {
1104 {'x', 1, 0, NULL},
Bob Ippolitoe27337b2006-05-26 13:15:44 +00001105 {'b', 1, 0, nu_byte, np_byte},
1106 {'B', 1, 0, nu_ubyte, np_ubyte},
Bob Ippolito232f3c92006-05-23 19:12:41 +00001107 {'c', 1, 0, nu_char, np_char},
1108 {'s', 1, 0, NULL},
1109 {'p', 1, 0, NULL},
1110 {'h', 2, 0, lu_int, lp_int},
1111 {'H', 2, 0, lu_uint, lp_uint},
1112 {'i', 4, 0, lu_int, lp_int},
1113 {'I', 4, 0, lu_uint, lp_uint},
1114 {'l', 4, 0, lu_int, lp_int},
1115 {'L', 4, 0, lu_uint, lp_uint},
1116 {'q', 8, 0, lu_longlong, lp_longlong},
1117 {'Q', 8, 0, lu_ulonglong, lp_ulonglong},
Thomas Hellerf3c05592008-03-05 15:34:29 +00001118 {'?', 1, 0, bu_bool, bp_bool}, /* Std rep not endian dep,
Martin v. Löwisaef4c6b2007-01-21 09:33:07 +00001119 but potentially different from native rep -- reuse bx_bool funcs. */
Bob Ippolito232f3c92006-05-23 19:12:41 +00001120 {'f', 4, 0, lu_float, lp_float},
1121 {'d', 8, 0, lu_double, lp_double},
1122 {0}
1123};
1124
1125
1126static const formatdef *
1127whichtable(char **pfmt)
1128{
1129 const char *fmt = (*pfmt)++; /* May be backed out of later */
1130 switch (*fmt) {
1131 case '<':
1132 return lilendian_table;
1133 case '>':
1134 case '!': /* Network byte order is big-endian */
1135 return bigendian_table;
1136 case '=': { /* Host byte order -- different from native in aligment! */
1137 int n = 1;
1138 char *p = (char *) &n;
1139 if (*p == 1)
1140 return lilendian_table;
1141 else
1142 return bigendian_table;
1143 }
1144 default:
1145 --*pfmt; /* Back out of pointer increment */
1146 /* Fall through */
1147 case '@':
1148 return native_table;
1149 }
1150}
1151
1152
1153/* Get the table entry for a format code */
1154
1155static const formatdef *
1156getentry(int c, const formatdef *f)
1157{
1158 for (; f->format != '\0'; f++) {
1159 if (f->format == c) {
1160 return f;
1161 }
1162 }
1163 PyErr_SetString(StructError, "bad char in struct format");
1164 return NULL;
1165}
1166
1167
1168/* Align a size according to a format code */
1169
1170static int
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001171align(Py_ssize_t size, char c, const formatdef *e)
Bob Ippolito232f3c92006-05-23 19:12:41 +00001172{
1173 if (e->format == c) {
1174 if (e->alignment) {
1175 size = ((size + e->alignment - 1)
1176 / e->alignment)
1177 * e->alignment;
1178 }
1179 }
1180 return size;
1181}
1182
1183
1184/* calculate the size of a format string */
1185
1186static int
1187prepare_s(PyStructObject *self)
1188{
1189 const formatdef *f;
1190 const formatdef *e;
1191 formatcode *codes;
Tim Petersc2b550e2006-05-31 14:28:07 +00001192
Bob Ippolito232f3c92006-05-23 19:12:41 +00001193 const char *s;
1194 const char *fmt;
1195 char c;
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001196 Py_ssize_t size, len, num, itemsize, x;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001197
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001198 fmt = PyString_AS_STRING(self->s_format);
Bob Ippolito232f3c92006-05-23 19:12:41 +00001199
1200 f = whichtable((char **)&fmt);
Tim Petersc2b550e2006-05-31 14:28:07 +00001201
Bob Ippolito232f3c92006-05-23 19:12:41 +00001202 s = fmt;
1203 size = 0;
1204 len = 0;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001205 while ((c = *s++) != '\0') {
1206 if (isspace(Py_CHARMASK(c)))
1207 continue;
1208 if ('0' <= c && c <= '9') {
1209 num = c - '0';
1210 while ('0' <= (c = *s++) && c <= '9') {
1211 x = num*10 + (c - '0');
1212 if (x/10 != num) {
1213 PyErr_SetString(
1214 StructError,
1215 "overflow in item count");
1216 return -1;
1217 }
1218 num = x;
1219 }
1220 if (c == '\0')
1221 break;
1222 }
1223 else
1224 num = 1;
1225
1226 e = getentry(c, f);
1227 if (e == NULL)
1228 return -1;
Tim Petersc2b550e2006-05-31 14:28:07 +00001229
Bob Ippolito232f3c92006-05-23 19:12:41 +00001230 switch (c) {
1231 case 's': /* fall through */
1232 case 'p': len++; break;
1233 case 'x': break;
1234 default: len += num; break;
1235 }
Bob Ippolito232f3c92006-05-23 19:12:41 +00001236
1237 itemsize = e->size;
1238 size = align(size, c, e);
1239 x = num * itemsize;
1240 size += x;
1241 if (x/itemsize != num || size < 0) {
1242 PyErr_SetString(StructError,
1243 "total struct size too long");
1244 return -1;
1245 }
1246 }
1247
Gregory P. Smith9d534572008-06-11 07:41:16 +00001248 /* check for overflow */
1249 if ((len + 1) > (PY_SSIZE_T_MAX / sizeof(formatcode))) {
1250 PyErr_NoMemory();
1251 return -1;
1252 }
1253
Bob Ippolito232f3c92006-05-23 19:12:41 +00001254 self->s_size = size;
1255 self->s_len = len;
Bob Ippolitoeb621272006-05-24 15:32:06 +00001256 codes = PyMem_MALLOC((len + 1) * sizeof(formatcode));
Bob Ippolito232f3c92006-05-23 19:12:41 +00001257 if (codes == NULL) {
1258 PyErr_NoMemory();
1259 return -1;
1260 }
1261 self->s_codes = codes;
Tim Petersc2b550e2006-05-31 14:28:07 +00001262
Bob Ippolito232f3c92006-05-23 19:12:41 +00001263 s = fmt;
1264 size = 0;
1265 while ((c = *s++) != '\0') {
1266 if (isspace(Py_CHARMASK(c)))
1267 continue;
1268 if ('0' <= c && c <= '9') {
1269 num = c - '0';
1270 while ('0' <= (c = *s++) && c <= '9')
1271 num = num*10 + (c - '0');
1272 if (c == '\0')
1273 break;
1274 }
1275 else
1276 num = 1;
1277
1278 e = getentry(c, f);
Tim Petersc2b550e2006-05-31 14:28:07 +00001279
Bob Ippolito232f3c92006-05-23 19:12:41 +00001280 size = align(size, c, e);
Bob Ippolitoeb621272006-05-24 15:32:06 +00001281 if (c == 's' || c == 'p') {
Bob Ippolito232f3c92006-05-23 19:12:41 +00001282 codes->offset = size;
Bob Ippolitoeb621272006-05-24 15:32:06 +00001283 codes->size = num;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001284 codes->fmtdef = e;
1285 codes++;
Bob Ippolitoeb621272006-05-24 15:32:06 +00001286 size += num;
1287 } else if (c == 'x') {
1288 size += num;
1289 } else {
1290 while (--num >= 0) {
1291 codes->offset = size;
1292 codes->size = e->size;
1293 codes->fmtdef = e;
1294 codes++;
1295 size += e->size;
1296 }
Bob Ippolito232f3c92006-05-23 19:12:41 +00001297 }
Bob Ippolito232f3c92006-05-23 19:12:41 +00001298 }
1299 codes->fmtdef = NULL;
Bob Ippolitoeb621272006-05-24 15:32:06 +00001300 codes->offset = size;
1301 codes->size = 0;
Tim Petersc2b550e2006-05-31 14:28:07 +00001302
Bob Ippolito232f3c92006-05-23 19:12:41 +00001303 return 0;
1304}
1305
1306static PyObject *
1307s_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1308{
1309 PyObject *self;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001310
1311 assert(type != NULL && type->tp_alloc != NULL);
1312
1313 self = type->tp_alloc(type, 0);
1314 if (self != NULL) {
1315 PyStructObject *s = (PyStructObject*)self;
1316 Py_INCREF(Py_None);
1317 s->s_format = Py_None;
1318 s->s_codes = NULL;
1319 s->s_size = -1;
1320 s->s_len = -1;
1321 }
1322 return self;
1323}
1324
1325static int
1326s_init(PyObject *self, PyObject *args, PyObject *kwds)
1327{
1328 PyStructObject *soself = (PyStructObject *)self;
1329 PyObject *o_format = NULL;
1330 int ret = 0;
1331 static char *kwlist[] = {"format", 0};
1332
1333 assert(PyStruct_Check(self));
1334
1335 if (!PyArg_ParseTupleAndKeywords(args, kwds, "S:Struct", kwlist,
1336 &o_format))
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001337 return -1;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001338
1339 Py_INCREF(o_format);
Amaury Forgeot d'Arc588ff932008-02-16 14:34:57 +00001340 Py_CLEAR(soself->s_format);
Bob Ippolito232f3c92006-05-23 19:12:41 +00001341 soself->s_format = o_format;
Tim Petersc2b550e2006-05-31 14:28:07 +00001342
Bob Ippolito232f3c92006-05-23 19:12:41 +00001343 ret = prepare_s(soself);
1344 return ret;
1345}
1346
1347static void
1348s_dealloc(PyStructObject *s)
1349{
Bob Ippolito232f3c92006-05-23 19:12:41 +00001350 if (s->weakreflist != NULL)
1351 PyObject_ClearWeakRefs((PyObject *)s);
1352 if (s->s_codes != NULL) {
1353 PyMem_FREE(s->s_codes);
1354 }
1355 Py_XDECREF(s->s_format);
Christian Heimese93237d2007-12-19 02:37:44 +00001356 Py_TYPE(s)->tp_free((PyObject *)s);
Bob Ippolito232f3c92006-05-23 19:12:41 +00001357}
1358
Bob Ippolitoeb621272006-05-24 15:32:06 +00001359static PyObject *
1360s_unpack_internal(PyStructObject *soself, char *startfrom) {
1361 formatcode *code;
1362 Py_ssize_t i = 0;
1363 PyObject *result = PyTuple_New(soself->s_len);
1364 if (result == NULL)
1365 return NULL;
1366
1367 for (code = soself->s_codes; code->fmtdef != NULL; code++) {
1368 PyObject *v;
1369 const formatdef *e = code->fmtdef;
1370 const char *res = startfrom + code->offset;
1371 if (e->format == 's') {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001372 v = PyString_FromStringAndSize(res, code->size);
Bob Ippolitoeb621272006-05-24 15:32:06 +00001373 } else if (e->format == 'p') {
1374 Py_ssize_t n = *(unsigned char*)res;
1375 if (n >= code->size)
1376 n = code->size - 1;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001377 v = PyString_FromStringAndSize(res + 1, n);
Bob Ippolitoeb621272006-05-24 15:32:06 +00001378 } else {
1379 v = e->unpack(res, e);
Bob Ippolitoeb621272006-05-24 15:32:06 +00001380 }
Neal Norwitz3c5431e2006-06-11 05:45:25 +00001381 if (v == NULL)
1382 goto fail;
1383 PyTuple_SET_ITEM(result, i++, v);
Bob Ippolitoeb621272006-05-24 15:32:06 +00001384 }
1385
1386 return result;
1387fail:
1388 Py_DECREF(result);
1389 return NULL;
Bob Ippolitocd51ca52006-05-27 15:53:49 +00001390}
Bob Ippolitoeb621272006-05-24 15:32:06 +00001391
1392
Bob Ippolito232f3c92006-05-23 19:12:41 +00001393PyDoc_STRVAR(s_unpack__doc__,
Bob Ippolito1fcdc232006-05-27 12:11:36 +00001394"S.unpack(str) -> (v1, v2, ...)\n\
Bob Ippolito232f3c92006-05-23 19:12:41 +00001395\n\
1396Return tuple containing values unpacked according to this Struct's format.\n\
1397Requires len(str) == self.size. See struct.__doc__ for more on format\n\
1398strings.");
1399
1400static PyObject *
1401s_unpack(PyObject *self, PyObject *inputstr)
1402{
Raymond Hettinger7a3d41f2007-04-05 18:00:03 +00001403 char *start;
1404 Py_ssize_t len;
1405 PyObject *args=NULL, *result;
Bob Ippolitoeb621272006-05-24 15:32:06 +00001406 PyStructObject *soself = (PyStructObject *)self;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001407 assert(PyStruct_Check(self));
Tim Petersc2b550e2006-05-31 14:28:07 +00001408 assert(soself->s_codes != NULL);
Raymond Hettinger7a3d41f2007-04-05 18:00:03 +00001409 if (inputstr == NULL)
1410 goto fail;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001411 if (PyString_Check(inputstr) &&
1412 PyString_GET_SIZE(inputstr) == soself->s_size) {
1413 return s_unpack_internal(soself, PyString_AS_STRING(inputstr));
Bob Ippolito232f3c92006-05-23 19:12:41 +00001414 }
Raymond Hettinger7a3d41f2007-04-05 18:00:03 +00001415 args = PyTuple_Pack(1, inputstr);
1416 if (args == NULL)
1417 return NULL;
1418 if (!PyArg_ParseTuple(args, "s#:unpack", &start, &len))
1419 goto fail;
1420 if (soself->s_size != len)
1421 goto fail;
1422 result = s_unpack_internal(soself, start);
1423 Py_DECREF(args);
1424 return result;
1425
1426fail:
1427 Py_XDECREF(args);
1428 PyErr_Format(StructError,
1429 "unpack requires a string argument of length %zd",
1430 soself->s_size);
1431 return NULL;
Bob Ippolitoeb621272006-05-24 15:32:06 +00001432}
1433
1434PyDoc_STRVAR(s_unpack_from__doc__,
Bob Ippolito1fcdc232006-05-27 12:11:36 +00001435"S.unpack_from(buffer[, offset]) -> (v1, v2, ...)\n\
Bob Ippolitoeb621272006-05-24 15:32:06 +00001436\n\
1437Return tuple containing values unpacked according to this Struct's format.\n\
1438Unlike unpack, unpack_from can unpack values from any object supporting\n\
1439the buffer API, not just str. Requires len(buffer[offset:]) >= self.size.\n\
1440See struct.__doc__ for more on format strings.");
1441
1442static PyObject *
1443s_unpack_from(PyObject *self, PyObject *args, PyObject *kwds)
1444{
1445 static char *kwlist[] = {"buffer", "offset", 0};
1446#if (PY_VERSION_HEX < 0x02050000)
1447 static char *fmt = "z#|i:unpack_from";
1448#else
1449 static char *fmt = "z#|n:unpack_from";
1450#endif
1451 Py_ssize_t buffer_len = 0, offset = 0;
1452 char *buffer = NULL;
1453 PyStructObject *soself = (PyStructObject *)self;
1454 assert(PyStruct_Check(self));
1455 assert(soself->s_codes != NULL);
1456
1457 if (!PyArg_ParseTupleAndKeywords(args, kwds, fmt, kwlist,
1458 &buffer, &buffer_len, &offset))
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001459 return NULL;
Bob Ippolitoeb621272006-05-24 15:32:06 +00001460
1461 if (buffer == NULL) {
1462 PyErr_Format(StructError,
1463 "unpack_from requires a buffer argument");
Bob Ippolito232f3c92006-05-23 19:12:41 +00001464 return NULL;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001465 }
Tim Petersc2b550e2006-05-31 14:28:07 +00001466
Bob Ippolitoeb621272006-05-24 15:32:06 +00001467 if (offset < 0)
1468 offset += buffer_len;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001469
Bob Ippolitoeb621272006-05-24 15:32:06 +00001470 if (offset < 0 || (buffer_len - offset) < soself->s_size) {
1471 PyErr_Format(StructError,
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001472 "unpack_from requires a buffer of at least %zd bytes",
Bob Ippolitoeb621272006-05-24 15:32:06 +00001473 soself->s_size);
1474 return NULL;
1475 }
1476 return s_unpack_internal(soself, buffer + offset);
1477}
Bob Ippolito232f3c92006-05-23 19:12:41 +00001478
Bob Ippolito232f3c92006-05-23 19:12:41 +00001479
Martin Blais2856e5f2006-05-26 12:03:27 +00001480/*
1481 * Guts of the pack function.
1482 *
1483 * Takes a struct object, a tuple of arguments, and offset in that tuple of
1484 * argument for where to start processing the arguments for packing, and a
1485 * character buffer for writing the packed string. The caller must insure
1486 * that the buffer may contain the required length for packing the arguments.
1487 * 0 is returned on success, 1 is returned if there is an error.
1488 *
1489 */
1490static int
1491s_pack_internal(PyStructObject *soself, PyObject *args, int offset, char* buf)
Bob Ippolito232f3c92006-05-23 19:12:41 +00001492{
Bob Ippolito232f3c92006-05-23 19:12:41 +00001493 formatcode *code;
Neal Norwitz3c5431e2006-06-11 05:45:25 +00001494 /* XXX(nnorwitz): why does i need to be a local? can we use
1495 the offset parameter or do we need the wider width? */
Bob Ippolito232f3c92006-05-23 19:12:41 +00001496 Py_ssize_t i;
Martin Blais2856e5f2006-05-26 12:03:27 +00001497
1498 memset(buf, '\0', soself->s_size);
1499 i = offset;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001500 for (code = soself->s_codes; code->fmtdef != NULL; code++) {
1501 Py_ssize_t n;
Neal Norwitz3c5431e2006-06-11 05:45:25 +00001502 PyObject *v = PyTuple_GET_ITEM(args, i++);
Bob Ippolito232f3c92006-05-23 19:12:41 +00001503 const formatdef *e = code->fmtdef;
Martin Blais2856e5f2006-05-26 12:03:27 +00001504 char *res = buf + code->offset;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001505 if (e->format == 's') {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001506 if (!PyString_Check(v)) {
Bob Ippolito232f3c92006-05-23 19:12:41 +00001507 PyErr_SetString(StructError,
Mark Dickinson5fd3af22009-07-07 15:08:28 +00001508 "argument for 's' must "
1509 "be a string");
Martin Blais2856e5f2006-05-26 12:03:27 +00001510 return -1;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001511 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001512 n = PyString_GET_SIZE(v);
Bob Ippolitoeb621272006-05-24 15:32:06 +00001513 if (n > code->size)
1514 n = code->size;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001515 if (n > 0)
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001516 memcpy(res, PyString_AS_STRING(v), n);
Bob Ippolito232f3c92006-05-23 19:12:41 +00001517 } else if (e->format == 'p') {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001518 if (!PyString_Check(v)) {
Bob Ippolito232f3c92006-05-23 19:12:41 +00001519 PyErr_SetString(StructError,
Mark Dickinson5fd3af22009-07-07 15:08:28 +00001520 "argument for 'p' must "
1521 "be a string");
Martin Blais2856e5f2006-05-26 12:03:27 +00001522 return -1;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001523 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001524 n = PyString_GET_SIZE(v);
Bob Ippolitoeb621272006-05-24 15:32:06 +00001525 if (n > (code->size - 1))
1526 n = code->size - 1;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001527 if (n > 0)
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001528 memcpy(res + 1, PyString_AS_STRING(v), n);
Bob Ippolito232f3c92006-05-23 19:12:41 +00001529 if (n > 255)
1530 n = 255;
1531 *res = Py_SAFE_DOWNCAST(n, Py_ssize_t, unsigned char);
Mark Dickinson5fd3af22009-07-07 15:08:28 +00001532 } else if (e->pack(res, v, e) < 0) {
1533 if (strchr(integer_codes, e->format) != NULL &&
1534 PyErr_ExceptionMatches(PyExc_OverflowError))
1535 PyErr_Format(StructError,
1536 "integer out of range for "
1537 "'%c' format code",
1538 e->format);
1539 return -1;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001540 }
1541 }
Tim Petersc2b550e2006-05-31 14:28:07 +00001542
Martin Blais2856e5f2006-05-26 12:03:27 +00001543 /* Success */
1544 return 0;
1545}
Bob Ippolito232f3c92006-05-23 19:12:41 +00001546
Martin Blais2856e5f2006-05-26 12:03:27 +00001547
1548PyDoc_STRVAR(s_pack__doc__,
Bob Ippolito1fcdc232006-05-27 12:11:36 +00001549"S.pack(v1, v2, ...) -> string\n\
Martin Blais2856e5f2006-05-26 12:03:27 +00001550\n\
1551Return a string containing values v1, v2, ... packed according to this\n\
1552Struct's format. See struct.__doc__ for more on format strings.");
1553
1554static PyObject *
1555s_pack(PyObject *self, PyObject *args)
1556{
1557 PyStructObject *soself;
1558 PyObject *result;
1559
1560 /* Validate arguments. */
1561 soself = (PyStructObject *)self;
1562 assert(PyStruct_Check(self));
1563 assert(soself->s_codes != NULL);
Martin Blaisaf2ae722006-06-04 13:49:49 +00001564 if (PyTuple_GET_SIZE(args) != soself->s_len)
Martin Blais2856e5f2006-05-26 12:03:27 +00001565 {
1566 PyErr_Format(StructError,
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001567 "pack requires exactly %zd arguments", soself->s_len);
Martin Blais2856e5f2006-05-26 12:03:27 +00001568 return NULL;
1569 }
Tim Petersc2b550e2006-05-31 14:28:07 +00001570
Martin Blais2856e5f2006-05-26 12:03:27 +00001571 /* Allocate a new string */
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001572 result = PyString_FromStringAndSize((char *)NULL, soself->s_size);
Martin Blais2856e5f2006-05-26 12:03:27 +00001573 if (result == NULL)
1574 return NULL;
Tim Petersc2b550e2006-05-31 14:28:07 +00001575
Martin Blais2856e5f2006-05-26 12:03:27 +00001576 /* Call the guts */
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001577 if ( s_pack_internal(soself, args, 0, PyString_AS_STRING(result)) != 0 ) {
Martin Blais2856e5f2006-05-26 12:03:27 +00001578 Py_DECREF(result);
1579 return NULL;
1580 }
1581
1582 return result;
1583}
1584
Martin Blaisaf2ae722006-06-04 13:49:49 +00001585PyDoc_STRVAR(s_pack_into__doc__,
1586"S.pack_into(buffer, offset, v1, v2, ...)\n\
Martin Blais2856e5f2006-05-26 12:03:27 +00001587\n\
Martin Blaisaf2ae722006-06-04 13:49:49 +00001588Pack the values v1, v2, ... according to this Struct's format, write \n\
Bob Ippolito1fcdc232006-05-27 12:11:36 +00001589the packed bytes into the writable buffer buf starting at offset. Note\n\
1590that the offset is not an optional argument. See struct.__doc__ for \n\
Martin Blais2856e5f2006-05-26 12:03:27 +00001591more on format strings.");
1592
1593static PyObject *
Martin Blaisaf2ae722006-06-04 13:49:49 +00001594s_pack_into(PyObject *self, PyObject *args)
Martin Blais2856e5f2006-05-26 12:03:27 +00001595{
1596 PyStructObject *soself;
1597 char *buffer;
1598 Py_ssize_t buffer_len, offset;
1599
1600 /* Validate arguments. +1 is for the first arg as buffer. */
1601 soself = (PyStructObject *)self;
1602 assert(PyStruct_Check(self));
1603 assert(soself->s_codes != NULL);
Martin Blaisaf2ae722006-06-04 13:49:49 +00001604 if (PyTuple_GET_SIZE(args) != (soself->s_len + 2))
Martin Blais2856e5f2006-05-26 12:03:27 +00001605 {
1606 PyErr_Format(StructError,
Martin Blaisaf2ae722006-06-04 13:49:49 +00001607 "pack_into requires exactly %zd arguments",
Martin Blais2856e5f2006-05-26 12:03:27 +00001608 (soself->s_len + 2));
1609 return NULL;
1610 }
1611
1612 /* Extract a writable memory buffer from the first argument */
Tim Petersc2b550e2006-05-31 14:28:07 +00001613 if ( PyObject_AsWriteBuffer(PyTuple_GET_ITEM(args, 0),
1614 (void**)&buffer, &buffer_len) == -1 ) {
Martin Blais2856e5f2006-05-26 12:03:27 +00001615 return NULL;
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001616 }
1617 assert( buffer_len >= 0 );
Martin Blais2856e5f2006-05-26 12:03:27 +00001618
1619 /* Extract the offset from the first argument */
Martin Blaisaf2ae722006-06-04 13:49:49 +00001620 offset = PyInt_AsSsize_t(PyTuple_GET_ITEM(args, 1));
Benjamin Peterson02252482008-09-30 02:11:07 +00001621 if (offset == -1 && PyErr_Occurred())
1622 return NULL;
Martin Blais2856e5f2006-05-26 12:03:27 +00001623
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001624 /* Support negative offsets. */
Martin Blais2856e5f2006-05-26 12:03:27 +00001625 if (offset < 0)
1626 offset += buffer_len;
1627
1628 /* Check boundaries */
1629 if (offset < 0 || (buffer_len - offset) < soself->s_size) {
1630 PyErr_Format(StructError,
Martin Blaisaf2ae722006-06-04 13:49:49 +00001631 "pack_into requires a buffer of at least %zd bytes",
Martin Blais2856e5f2006-05-26 12:03:27 +00001632 soself->s_size);
1633 return NULL;
1634 }
Tim Petersc2b550e2006-05-31 14:28:07 +00001635
Martin Blais2856e5f2006-05-26 12:03:27 +00001636 /* Call the guts */
1637 if ( s_pack_internal(soself, args, 2, buffer + offset) != 0 ) {
1638 return NULL;
1639 }
1640
Georg Brandlc26025c2006-05-28 21:42:54 +00001641 Py_RETURN_NONE;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001642}
1643
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001644static PyObject *
1645s_get_format(PyStructObject *self, void *unused)
1646{
1647 Py_INCREF(self->s_format);
1648 return self->s_format;
1649}
1650
1651static PyObject *
1652s_get_size(PyStructObject *self, void *unused)
1653{
1654 return PyInt_FromSsize_t(self->s_size);
1655}
Bob Ippolito232f3c92006-05-23 19:12:41 +00001656
1657/* List of functions */
1658
1659static struct PyMethodDef s_methods[] = {
Martin Blaisaf2ae722006-06-04 13:49:49 +00001660 {"pack", s_pack, METH_VARARGS, s_pack__doc__},
1661 {"pack_into", s_pack_into, METH_VARARGS, s_pack_into__doc__},
1662 {"unpack", s_unpack, METH_O, s_unpack__doc__},
Neal Norwitza84dcd72007-05-22 07:16:44 +00001663 {"unpack_from", (PyCFunction)s_unpack_from, METH_VARARGS|METH_KEYWORDS,
Tim Peters5ec2e852006-06-04 15:49:07 +00001664 s_unpack_from__doc__},
Bob Ippolito232f3c92006-05-23 19:12:41 +00001665 {NULL, NULL} /* sentinel */
1666};
1667
1668PyDoc_STRVAR(s__doc__, "Compiled struct object");
1669
1670#define OFF(x) offsetof(PyStructObject, x)
1671
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001672static PyGetSetDef s_getsetlist[] = {
Bob Ippolito1fcdc232006-05-27 12:11:36 +00001673 {"format", (getter)s_get_format, (setter)NULL, "struct format string", NULL},
1674 {"size", (getter)s_get_size, (setter)NULL, "struct size in bytes", NULL},
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001675 {NULL} /* sentinel */
Bob Ippolito232f3c92006-05-23 19:12:41 +00001676};
1677
Bob Ippolito232f3c92006-05-23 19:12:41 +00001678static
1679PyTypeObject PyStructType = {
Martin v. Löwis68192102007-07-21 06:55:02 +00001680 PyVarObject_HEAD_INIT(NULL, 0)
Bob Ippolito232f3c92006-05-23 19:12:41 +00001681 "Struct",
1682 sizeof(PyStructObject),
1683 0,
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001684 (destructor)s_dealloc, /* tp_dealloc */
Bob Ippolito232f3c92006-05-23 19:12:41 +00001685 0, /* tp_print */
1686 0, /* tp_getattr */
1687 0, /* tp_setattr */
1688 0, /* tp_compare */
1689 0, /* tp_repr */
1690 0, /* tp_as_number */
1691 0, /* tp_as_sequence */
1692 0, /* tp_as_mapping */
1693 0, /* tp_hash */
1694 0, /* tp_call */
1695 0, /* tp_str */
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001696 PyObject_GenericGetAttr, /* tp_getattro */
1697 PyObject_GenericSetAttr, /* tp_setattro */
Bob Ippolito232f3c92006-05-23 19:12:41 +00001698 0, /* tp_as_buffer */
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001699 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_WEAKREFS,/* tp_flags */
1700 s__doc__, /* tp_doc */
Bob Ippolito232f3c92006-05-23 19:12:41 +00001701 0, /* tp_traverse */
1702 0, /* tp_clear */
1703 0, /* tp_richcompare */
1704 offsetof(PyStructObject, weakreflist), /* tp_weaklistoffset */
1705 0, /* tp_iter */
1706 0, /* tp_iternext */
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001707 s_methods, /* tp_methods */
1708 NULL, /* tp_members */
1709 s_getsetlist, /* tp_getset */
Bob Ippolito232f3c92006-05-23 19:12:41 +00001710 0, /* tp_base */
1711 0, /* tp_dict */
1712 0, /* tp_descr_get */
1713 0, /* tp_descr_set */
1714 0, /* tp_dictoffset */
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001715 s_init, /* tp_init */
1716 PyType_GenericAlloc,/* tp_alloc */
1717 s_new, /* tp_new */
1718 PyObject_Del, /* tp_free */
Bob Ippolito232f3c92006-05-23 19:12:41 +00001719};
1720
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001721
1722/* ---- Standalone functions ---- */
1723
1724#define MAXCACHE 100
Christian Heimes76d19f62008-01-04 02:54:42 +00001725static PyObject *cache = NULL;
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001726
1727static PyObject *
1728cache_struct(PyObject *fmt)
1729{
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001730 PyObject * s_object;
1731
1732 if (cache == NULL) {
1733 cache = PyDict_New();
1734 if (cache == NULL)
1735 return NULL;
1736 }
1737
1738 s_object = PyDict_GetItem(cache, fmt);
1739 if (s_object != NULL) {
1740 Py_INCREF(s_object);
1741 return s_object;
1742 }
1743
1744 s_object = PyObject_CallFunctionObjArgs((PyObject *)(&PyStructType), fmt, NULL);
1745 if (s_object != NULL) {
1746 if (PyDict_Size(cache) >= MAXCACHE)
1747 PyDict_Clear(cache);
1748 /* Attempt to cache the result */
1749 if (PyDict_SetItem(cache, fmt, s_object) == -1)
1750 PyErr_Clear();
1751 }
1752 return s_object;
1753}
1754
Christian Heimes76d19f62008-01-04 02:54:42 +00001755PyDoc_STRVAR(clearcache_doc,
1756"Clear the internal cache.");
1757
1758static PyObject *
1759clearcache(PyObject *self)
1760{
Raymond Hettinger18e08e52008-01-18 00:10:42 +00001761 Py_CLEAR(cache);
Christian Heimes76d19f62008-01-04 02:54:42 +00001762 Py_RETURN_NONE;
1763}
1764
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001765PyDoc_STRVAR(calcsize_doc,
1766"Return size of C struct described by format string fmt.");
1767
1768static PyObject *
1769calcsize(PyObject *self, PyObject *fmt)
1770{
1771 Py_ssize_t n;
1772 PyObject *s_object = cache_struct(fmt);
1773 if (s_object == NULL)
1774 return NULL;
1775 n = ((PyStructObject *)s_object)->s_size;
1776 Py_DECREF(s_object);
1777 return PyInt_FromSsize_t(n);
1778}
1779
1780PyDoc_STRVAR(pack_doc,
1781"Return string containing values v1, v2, ... packed according to fmt.");
1782
1783static PyObject *
1784pack(PyObject *self, PyObject *args)
1785{
1786 PyObject *s_object, *fmt, *newargs, *result;
1787 Py_ssize_t n = PyTuple_GET_SIZE(args);
1788
1789 if (n == 0) {
1790 PyErr_SetString(PyExc_TypeError, "missing format argument");
1791 return NULL;
1792 }
1793 fmt = PyTuple_GET_ITEM(args, 0);
1794 newargs = PyTuple_GetSlice(args, 1, n);
1795 if (newargs == NULL)
1796 return NULL;
1797
1798 s_object = cache_struct(fmt);
1799 if (s_object == NULL) {
1800 Py_DECREF(newargs);
1801 return NULL;
1802 }
1803 result = s_pack(s_object, newargs);
1804 Py_DECREF(newargs);
1805 Py_DECREF(s_object);
1806 return result;
1807}
1808
1809PyDoc_STRVAR(pack_into_doc,
1810"Pack the values v1, v2, ... according to fmt.\n\
1811Write the packed bytes into the writable buffer buf starting at offset.");
1812
1813static PyObject *
1814pack_into(PyObject *self, PyObject *args)
1815{
1816 PyObject *s_object, *fmt, *newargs, *result;
1817 Py_ssize_t n = PyTuple_GET_SIZE(args);
1818
1819 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;
1827
1828 s_object = cache_struct(fmt);
1829 if (s_object == NULL) {
1830 Py_DECREF(newargs);
1831 return NULL;
1832 }
1833 result = s_pack_into(s_object, newargs);
1834 Py_DECREF(newargs);
1835 Py_DECREF(s_object);
1836 return result;
1837}
1838
1839PyDoc_STRVAR(unpack_doc,
1840"Unpack the string containing packed C structure data, according to fmt.\n\
1841Requires len(string) == calcsize(fmt).");
1842
1843static PyObject *
1844unpack(PyObject *self, PyObject *args)
1845{
1846 PyObject *s_object, *fmt, *inputstr, *result;
1847
1848 if (!PyArg_UnpackTuple(args, "unpack", 2, 2, &fmt, &inputstr))
1849 return NULL;
1850
1851 s_object = cache_struct(fmt);
1852 if (s_object == NULL)
1853 return NULL;
1854 result = s_unpack(s_object, inputstr);
1855 Py_DECREF(s_object);
1856 return result;
1857}
1858
1859PyDoc_STRVAR(unpack_from_doc,
1860"Unpack the buffer, containing packed C structure data, according to\n\
1861fmt, starting at offset. Requires len(buffer[offset:]) >= calcsize(fmt).");
1862
1863static PyObject *
1864unpack_from(PyObject *self, PyObject *args, PyObject *kwds)
1865{
1866 PyObject *s_object, *fmt, *newargs, *result;
1867 Py_ssize_t n = PyTuple_GET_SIZE(args);
1868
1869 if (n == 0) {
1870 PyErr_SetString(PyExc_TypeError, "missing format argument");
1871 return NULL;
1872 }
1873 fmt = PyTuple_GET_ITEM(args, 0);
1874 newargs = PyTuple_GetSlice(args, 1, n);
1875 if (newargs == NULL)
1876 return NULL;
1877
1878 s_object = cache_struct(fmt);
1879 if (s_object == NULL) {
1880 Py_DECREF(newargs);
1881 return NULL;
1882 }
1883 result = s_unpack_from(s_object, newargs, kwds);
1884 Py_DECREF(newargs);
1885 Py_DECREF(s_object);
1886 return result;
1887}
1888
1889static struct PyMethodDef module_functions[] = {
Christian Heimes76d19f62008-01-04 02:54:42 +00001890 {"_clearcache", (PyCFunction)clearcache, METH_NOARGS, clearcache_doc},
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001891 {"calcsize", calcsize, METH_O, calcsize_doc},
1892 {"pack", pack, METH_VARARGS, pack_doc},
1893 {"pack_into", pack_into, METH_VARARGS, pack_into_doc},
1894 {"unpack", unpack, METH_VARARGS, unpack_doc},
1895 {"unpack_from", (PyCFunction)unpack_from,
1896 METH_VARARGS|METH_KEYWORDS, unpack_from_doc},
1897 {NULL, NULL} /* sentinel */
1898};
1899
1900
Bob Ippolito232f3c92006-05-23 19:12:41 +00001901/* Module initialization */
1902
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001903PyDoc_STRVAR(module_doc,
Mark Dickinson3d830822009-10-08 15:54:10 +00001904"Functions to convert between Python values and C structs represented\n\
1905as Python strings. It uses format strings (explained below) as compact\n\
1906descriptions of the lay-out of the C structs and the intended conversion\n\
1907to/from Python values.\n\
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001908\n\
1909The optional first format char indicates byte order, size and alignment:\n\
Mark Dickinson3d830822009-10-08 15:54:10 +00001910 @: native order, size & alignment (default)\n\
1911 =: native order, std. size & alignment\n\
1912 <: little-endian, std. size & alignment\n\
1913 >: big-endian, std. size & alignment\n\
1914 !: same as >\n\
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001915\n\
1916The remaining chars indicate types of args and must match exactly;\n\
1917these can be preceded by a decimal repeat count:\n\
1918 x: pad byte (no data); c:char; b:signed byte; B:unsigned byte;\n\
Mark Dickinson3d830822009-10-08 15:54:10 +00001919 ?: _Bool (requires C99; if not available, char is used instead)\n\
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001920 h:short; H:unsigned short; i:int; I:unsigned int;\n\
1921 l:long; L:unsigned long; f:float; d:double.\n\
1922Special cases (preceding decimal count indicates length):\n\
1923 s:string (array of char); p: pascal string (with count byte).\n\
1924Special case (only available in native format):\n\
1925 P:an integer type that is wide enough to hold a pointer.\n\
1926Special case (not in native mode unless 'long long' in platform C):\n\
1927 q:long long; Q:unsigned long long\n\
1928Whitespace between formats is ignored.\n\
1929\n\
1930The variable struct.error is an exception raised on errors.\n");
1931
Bob Ippolito232f3c92006-05-23 19:12:41 +00001932PyMODINIT_FUNC
1933init_struct(void)
1934{
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001935 PyObject *ver, *m;
1936
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001937 ver = PyString_FromString("0.2");
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001938 if (ver == NULL)
1939 return;
1940
1941 m = Py_InitModule3("_struct", module_functions, module_doc);
Bob Ippolito232f3c92006-05-23 19:12:41 +00001942 if (m == NULL)
1943 return;
1944
Christian Heimese93237d2007-12-19 02:37:44 +00001945 Py_TYPE(&PyStructType) = &PyType_Type;
Bob Ippolito3fc2bb92006-05-25 19:03:19 +00001946 if (PyType_Ready(&PyStructType) < 0)
1947 return;
1948
Mark Dickinson5fd3af22009-07-07 15:08:28 +00001949 /* This speed trick can't be used until overflow masking goes
1950 away, because native endian always raises exceptions
1951 instead of overflow masking. */
Tim Petersc2b550e2006-05-31 14:28:07 +00001952
Bob Ippolitoa99865b2006-05-25 19:56:56 +00001953 /* Check endian and swap in faster functions */
1954 {
1955 int one = 1;
1956 formatdef *native = native_table;
1957 formatdef *other, *ptr;
1958 if ((int)*(unsigned char*)&one)
1959 other = lilendian_table;
1960 else
1961 other = bigendian_table;
Bob Ippolito964e02a2006-05-25 21:09:45 +00001962 /* Scan through the native table, find a matching
1963 entry in the endian table and swap in the
1964 native implementations whenever possible
1965 (64-bit platforms may not have "standard" sizes) */
Bob Ippolitoa99865b2006-05-25 19:56:56 +00001966 while (native->format != '\0' && other->format != '\0') {
1967 ptr = other;
1968 while (ptr->format != '\0') {
1969 if (ptr->format == native->format) {
Bob Ippolito964e02a2006-05-25 21:09:45 +00001970 /* Match faster when formats are
1971 listed in the same order */
Bob Ippolitoa99865b2006-05-25 19:56:56 +00001972 if (ptr == other)
1973 other++;
Tim Petersc2b550e2006-05-31 14:28:07 +00001974 /* Only use the trick if the
Bob Ippolito964e02a2006-05-25 21:09:45 +00001975 size matches */
1976 if (ptr->size != native->size)
1977 break;
1978 /* Skip float and double, could be
1979 "unknown" float format */
1980 if (ptr->format == 'd' || ptr->format == 'f')
1981 break;
1982 ptr->pack = native->pack;
1983 ptr->unpack = native->unpack;
Bob Ippolitoa99865b2006-05-25 19:56:56 +00001984 break;
1985 }
1986 ptr++;
1987 }
1988 native++;
1989 }
1990 }
Tim Petersc2b550e2006-05-31 14:28:07 +00001991
Bob Ippolito232f3c92006-05-23 19:12:41 +00001992 /* Add some symbolic constants to the module */
1993 if (StructError == NULL) {
1994 StructError = PyErr_NewException("struct.error", NULL, NULL);
1995 if (StructError == NULL)
1996 return;
1997 }
Bob Ippolito04ab9942006-05-25 19:33:38 +00001998
Bob Ippolito232f3c92006-05-23 19:12:41 +00001999 Py_INCREF(StructError);
2000 PyModule_AddObject(m, "error", StructError);
Bob Ippolito04ab9942006-05-25 19:33:38 +00002001
Bob Ippolito232f3c92006-05-23 19:12:41 +00002002 Py_INCREF((PyObject*)&PyStructType);
2003 PyModule_AddObject(m, "Struct", (PyObject*)&PyStructType);
Tim Petersc2b550e2006-05-31 14:28:07 +00002004
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00002005 PyModule_AddObject(m, "__version__", ver);
2006
Bob Ippolito2fd39772006-05-29 22:55:48 +00002007 PyModule_AddIntConstant(m, "_PY_STRUCT_RANGE_CHECKING", 1);
Bob Ippolitoe6c9f982006-08-04 23:59:21 +00002008 PyModule_AddIntConstant(m, "_PY_STRUCT_FLOAT_COERCE", 1);
Bob Ippolito232f3c92006-05-23 19:12:41 +00002009}