blob: 97f2f75cf36a8ffa466a8053785c97ca5588479f [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
Bob Ippolitoe6c9f982006-08-04 23:59:21 +000020#define FLOAT_COERCE "integer argument expected, got float"
Bob Ippolitoe6c9f982006-08-04 23:59:21 +000021
22
Bob Ippolito232f3c92006-05-23 19:12:41 +000023/* The translation function for each format character is table driven */
Bob Ippolito232f3c92006-05-23 19:12:41 +000024typedef struct _formatdef {
25 char format;
Bob Ippolitoaa70a172006-05-26 20:25:23 +000026 Py_ssize_t size;
27 Py_ssize_t alignment;
Bob Ippolito232f3c92006-05-23 19:12:41 +000028 PyObject* (*unpack)(const char *,
29 const struct _formatdef *);
30 int (*pack)(char *, PyObject *,
31 const struct _formatdef *);
32} formatdef;
33
34typedef struct _formatcode {
35 const struct _formatdef *fmtdef;
Bob Ippolitoaa70a172006-05-26 20:25:23 +000036 Py_ssize_t offset;
37 Py_ssize_t size;
Bob Ippolito232f3c92006-05-23 19:12:41 +000038} formatcode;
39
40/* Struct object interface */
41
42typedef struct {
43 PyObject_HEAD
Bob Ippolitoaa70a172006-05-26 20:25:23 +000044 Py_ssize_t s_size;
45 Py_ssize_t s_len;
Bob Ippolito232f3c92006-05-23 19:12:41 +000046 formatcode *s_codes;
47 PyObject *s_format;
48 PyObject *weakreflist; /* List of weak references */
49} PyStructObject;
50
Bob Ippolitoeb621272006-05-24 15:32:06 +000051
Bob Ippolito07c023b2006-05-23 19:32:25 +000052#define PyStruct_Check(op) PyObject_TypeCheck(op, &PyStructType)
Christian Heimese93237d2007-12-19 02:37:44 +000053#define PyStruct_CheckExact(op) (Py_TYPE(op) == &PyStructType)
Bob Ippolito232f3c92006-05-23 19:12:41 +000054
55
56/* Exception */
57
58static PyObject *StructError;
59
60
61/* Define various structs to figure out the alignments of types */
62
63
64typedef struct { char c; short x; } st_short;
65typedef struct { char c; int x; } st_int;
66typedef struct { char c; long x; } st_long;
67typedef struct { char c; float x; } st_float;
68typedef struct { char c; double x; } st_double;
69typedef struct { char c; void *x; } st_void_p;
70
71#define SHORT_ALIGN (sizeof(st_short) - sizeof(short))
72#define INT_ALIGN (sizeof(st_int) - sizeof(int))
73#define LONG_ALIGN (sizeof(st_long) - sizeof(long))
74#define FLOAT_ALIGN (sizeof(st_float) - sizeof(float))
75#define DOUBLE_ALIGN (sizeof(st_double) - sizeof(double))
76#define VOID_P_ALIGN (sizeof(st_void_p) - sizeof(void *))
77
78/* We can't support q and Q in native mode unless the compiler does;
79 in std mode, they're 8 bytes on all platforms. */
80#ifdef HAVE_LONG_LONG
81typedef struct { char c; PY_LONG_LONG x; } s_long_long;
82#define LONG_LONG_ALIGN (sizeof(s_long_long) - sizeof(PY_LONG_LONG))
83#endif
84
Martin v. Löwisaef4c6b2007-01-21 09:33:07 +000085#ifdef HAVE_C99_BOOL
86#define BOOL_TYPE _Bool
87typedef struct { char c; _Bool x; } s_bool;
88#define BOOL_ALIGN (sizeof(s_bool) - sizeof(BOOL_TYPE))
89#else
90#define BOOL_TYPE char
91#define BOOL_ALIGN 0
92#endif
93
Bob Ippolito232f3c92006-05-23 19:12:41 +000094#define STRINGIFY(x) #x
95
96#ifdef __powerc
97#pragma options align=reset
98#endif
99
Mark Dickinson5fd3af22009-07-07 15:08:28 +0000100static char *integer_codes = "bBhHiIlLqQ";
101
Bob Ippolito232f3c92006-05-23 19:12:41 +0000102/* Helper to get a PyLongObject by hook or by crook. Caller should decref. */
103
104static PyObject *
105get_pylong(PyObject *v)
106{
Bob Ippolito232f3c92006-05-23 19:12:41 +0000107 assert(v != NULL);
108 if (PyInt_Check(v))
109 return PyLong_FromLong(PyInt_AS_LONG(v));
110 if (PyLong_Check(v)) {
111 Py_INCREF(v);
112 return v;
113 }
Mark Dickinson463dc4b2009-07-05 10:01:24 +0000114 if (PyFloat_Check(v)) {
Mark Dickinson1c0c78c2010-03-05 14:36:20 +0000115 if (PyErr_WarnEx(PyExc_DeprecationWarning, FLOAT_COERCE, 1)<0)
Bob Ippolito232f3c92006-05-23 19:12:41 +0000116 return NULL;
Mark Dickinson463dc4b2009-07-05 10:01:24 +0000117 return PyNumber_Long(v);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000118 }
119 PyErr_SetString(StructError,
120 "cannot convert argument to long");
121 return NULL;
122}
123
Mark Dickinson5fd3af22009-07-07 15:08:28 +0000124/* Helper to convert a Python object to a C long. Sets an exception
125 (struct.error for an inconvertible type, OverflowError for
126 out-of-range values) and returns -1 on error. */
Bob Ippolito232f3c92006-05-23 19:12:41 +0000127
128static int
129get_long(PyObject *v, long *p)
130{
Mark Dickinson463dc4b2009-07-05 10:01:24 +0000131 long x;
132
133 v = get_pylong(v);
134 if (v == NULL)
135 return -1;
136 assert(PyLong_Check(v));
137 x = PyLong_AsLong(v);
138 Py_DECREF(v);
Mark Dickinson5fd3af22009-07-07 15:08:28 +0000139 if (x == (long)-1 && PyErr_Occurred())
Bob Ippolito232f3c92006-05-23 19:12:41 +0000140 return -1;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000141 *p = x;
142 return 0;
143}
144
Bob Ippolito232f3c92006-05-23 19:12:41 +0000145/* Same, but handling unsigned long */
146
147static int
148get_ulong(PyObject *v, unsigned long *p)
149{
Mark Dickinson463dc4b2009-07-05 10:01:24 +0000150 unsigned long x;
151
152 v = get_pylong(v);
153 if (v == NULL)
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000154 return -1;
Mark Dickinson463dc4b2009-07-05 10:01:24 +0000155 assert(PyLong_Check(v));
156 x = PyLong_AsUnsignedLong(v);
157 Py_DECREF(v);
Mark Dickinson5fd3af22009-07-07 15:08:28 +0000158 if (x == (unsigned long)-1 && PyErr_Occurred())
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000159 return -1;
Mark Dickinson463dc4b2009-07-05 10:01:24 +0000160 *p = x;
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000161 return 0;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000162}
163
164#ifdef HAVE_LONG_LONG
165
166/* Same, but handling native long long. */
167
168static int
169get_longlong(PyObject *v, PY_LONG_LONG *p)
170{
171 PY_LONG_LONG x;
172
173 v = get_pylong(v);
174 if (v == NULL)
175 return -1;
176 assert(PyLong_Check(v));
177 x = PyLong_AsLongLong(v);
178 Py_DECREF(v);
Mark Dickinson5fd3af22009-07-07 15:08:28 +0000179 if (x == (PY_LONG_LONG)-1 && PyErr_Occurred())
Bob Ippolito232f3c92006-05-23 19:12:41 +0000180 return -1;
181 *p = x;
182 return 0;
183}
184
185/* Same, but handling native unsigned long long. */
186
187static int
188get_ulonglong(PyObject *v, unsigned PY_LONG_LONG *p)
189{
190 unsigned PY_LONG_LONG x;
191
192 v = get_pylong(v);
193 if (v == NULL)
194 return -1;
195 assert(PyLong_Check(v));
196 x = PyLong_AsUnsignedLongLong(v);
197 Py_DECREF(v);
Mark Dickinson5fd3af22009-07-07 15:08:28 +0000198 if (x == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred())
Bob Ippolito232f3c92006-05-23 19:12:41 +0000199 return -1;
200 *p = x;
201 return 0;
202}
203
204#endif
205
206/* Floating point helpers */
207
208static PyObject *
209unpack_float(const char *p, /* start of 4-byte string */
210 int le) /* true for little-endian, false for big-endian */
211{
212 double x;
213
214 x = _PyFloat_Unpack4((unsigned char *)p, le);
215 if (x == -1.0 && PyErr_Occurred())
216 return NULL;
217 return PyFloat_FromDouble(x);
218}
219
220static PyObject *
221unpack_double(const char *p, /* start of 8-byte string */
222 int le) /* true for little-endian, false for big-endian */
223{
224 double x;
225
226 x = _PyFloat_Unpack8((unsigned char *)p, le);
227 if (x == -1.0 && PyErr_Occurred())
228 return NULL;
229 return PyFloat_FromDouble(x);
230}
231
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000232/* Helper to format the range error exceptions */
233static int
Armin Rigo162997e2006-05-29 17:59:47 +0000234_range_error(const formatdef *f, int is_unsigned)
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000235{
Tim Petersd6a6f022006-05-31 15:33:22 +0000236 /* ulargest is the largest unsigned value with f->size bytes.
237 * Note that the simpler:
238 * ((size_t)1 << (f->size * 8)) - 1
Tim Peters72270c22006-05-31 15:34:37 +0000239 * doesn't work when f->size == sizeof(size_t) because C doesn't
240 * define what happens when a left shift count is >= the number of
241 * bits in the integer being shifted; e.g., on some boxes it doesn't
242 * shift at all when they're equal.
Tim Petersd6a6f022006-05-31 15:33:22 +0000243 */
244 const size_t ulargest = (size_t)-1 >> ((SIZEOF_SIZE_T - f->size)*8);
245 assert(f->size >= 1 && f->size <= SIZEOF_SIZE_T);
246 if (is_unsigned)
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000247 PyErr_Format(StructError,
Neal Norwitz971ea112006-05-31 07:43:27 +0000248 "'%c' format requires 0 <= number <= %zu",
Bob Ippolito28b26862006-05-29 15:47:29 +0000249 f->format,
Tim Petersd6a6f022006-05-31 15:33:22 +0000250 ulargest);
251 else {
252 const Py_ssize_t largest = (Py_ssize_t)(ulargest >> 1);
253 PyErr_Format(StructError,
254 "'%c' format requires %zd <= number <= %zd",
255 f->format,
256 ~ largest,
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000257 largest);
258 }
259 return -1;
260}
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000261
262
Bob Ippolito232f3c92006-05-23 19:12:41 +0000263
264/* A large number of small routines follow, with names of the form
265
Bob Ippolitoaa70a172006-05-26 20:25:23 +0000266 [bln][up]_TYPE
Bob Ippolito232f3c92006-05-23 19:12:41 +0000267
268 [bln] distiguishes among big-endian, little-endian and native.
269 [pu] distiguishes between pack (to struct) and unpack (from struct).
270 TYPE is one of char, byte, ubyte, etc.
271*/
272
273/* Native mode routines. ****************************************************/
274/* NOTE:
275 In all n[up]_<type> routines handling types larger than 1 byte, there is
276 *no* guarantee that the p pointer is properly aligned for each type,
277 therefore memcpy is called. An intermediate variable is used to
278 compensate for big-endian architectures.
279 Normally both the intermediate variable and the memcpy call will be
280 skipped by C optimisation in little-endian architectures (gcc >= 2.91
281 does this). */
282
283static PyObject *
284nu_char(const char *p, const formatdef *f)
285{
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000286 return PyString_FromStringAndSize(p, 1);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000287}
288
289static PyObject *
290nu_byte(const char *p, const formatdef *f)
291{
292 return PyInt_FromLong((long) *(signed char *)p);
293}
294
295static PyObject *
296nu_ubyte(const char *p, const formatdef *f)
297{
298 return PyInt_FromLong((long) *(unsigned char *)p);
299}
300
301static PyObject *
302nu_short(const char *p, const formatdef *f)
303{
304 short x;
305 memcpy((char *)&x, p, sizeof x);
306 return PyInt_FromLong((long)x);
307}
308
309static PyObject *
310nu_ushort(const char *p, const formatdef *f)
311{
312 unsigned short x;
313 memcpy((char *)&x, p, sizeof x);
314 return PyInt_FromLong((long)x);
315}
316
317static PyObject *
318nu_int(const char *p, const formatdef *f)
319{
320 int x;
321 memcpy((char *)&x, p, sizeof x);
322 return PyInt_FromLong((long)x);
323}
324
325static PyObject *
326nu_uint(const char *p, const formatdef *f)
327{
328 unsigned int x;
329 memcpy((char *)&x, p, sizeof x);
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000330#if (SIZEOF_LONG > SIZEOF_INT)
331 return PyInt_FromLong((long)x);
332#else
333 if (x <= ((unsigned int)LONG_MAX))
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000334 return PyInt_FromLong((long)x);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000335 return PyLong_FromUnsignedLong((unsigned long)x);
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000336#endif
Bob Ippolito232f3c92006-05-23 19:12:41 +0000337}
338
339static PyObject *
340nu_long(const char *p, const formatdef *f)
341{
342 long x;
343 memcpy((char *)&x, p, sizeof x);
344 return PyInt_FromLong(x);
345}
346
347static PyObject *
348nu_ulong(const char *p, const formatdef *f)
349{
350 unsigned long x;
351 memcpy((char *)&x, p, sizeof x);
Bob Ippolito04ab9942006-05-25 19:33:38 +0000352 if (x <= LONG_MAX)
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000353 return PyInt_FromLong((long)x);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000354 return PyLong_FromUnsignedLong(x);
355}
356
357/* Native mode doesn't support q or Q unless the platform C supports
358 long long (or, on Windows, __int64). */
359
360#ifdef HAVE_LONG_LONG
361
362static PyObject *
363nu_longlong(const char *p, const formatdef *f)
364{
365 PY_LONG_LONG x;
366 memcpy((char *)&x, p, sizeof x);
Bob Ippolito04ab9942006-05-25 19:33:38 +0000367 if (x >= LONG_MIN && x <= LONG_MAX)
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000368 return PyInt_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long));
Bob Ippolito232f3c92006-05-23 19:12:41 +0000369 return PyLong_FromLongLong(x);
370}
371
372static PyObject *
373nu_ulonglong(const char *p, const formatdef *f)
374{
375 unsigned PY_LONG_LONG x;
376 memcpy((char *)&x, p, sizeof x);
Bob Ippolito04ab9942006-05-25 19:33:38 +0000377 if (x <= LONG_MAX)
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000378 return PyInt_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long));
Bob Ippolito232f3c92006-05-23 19:12:41 +0000379 return PyLong_FromUnsignedLongLong(x);
380}
381
382#endif
383
384static PyObject *
Martin v. Löwisaef4c6b2007-01-21 09:33:07 +0000385nu_bool(const char *p, const formatdef *f)
386{
387 BOOL_TYPE x;
388 memcpy((char *)&x, p, sizeof x);
389 return PyBool_FromLong(x != 0);
390}
391
392
393static PyObject *
Bob Ippolito232f3c92006-05-23 19:12:41 +0000394nu_float(const char *p, const formatdef *f)
395{
396 float x;
397 memcpy((char *)&x, p, sizeof x);
398 return PyFloat_FromDouble((double)x);
399}
400
401static PyObject *
402nu_double(const char *p, const formatdef *f)
403{
404 double x;
405 memcpy((char *)&x, p, sizeof x);
406 return PyFloat_FromDouble(x);
407}
408
409static PyObject *
410nu_void_p(const char *p, const formatdef *f)
411{
412 void *x;
413 memcpy((char *)&x, p, sizeof x);
414 return PyLong_FromVoidPtr(x);
415}
416
417static int
418np_byte(char *p, PyObject *v, const formatdef *f)
419{
420 long x;
421 if (get_long(v, &x) < 0)
422 return -1;
423 if (x < -128 || x > 127){
424 PyErr_SetString(StructError,
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000425 "byte format requires -128 <= number <= 127");
Bob Ippolito232f3c92006-05-23 19:12:41 +0000426 return -1;
427 }
428 *p = (char)x;
429 return 0;
430}
431
432static int
433np_ubyte(char *p, PyObject *v, const formatdef *f)
434{
435 long x;
436 if (get_long(v, &x) < 0)
437 return -1;
438 if (x < 0 || x > 255){
439 PyErr_SetString(StructError,
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000440 "ubyte format requires 0 <= number <= 255");
Bob Ippolito232f3c92006-05-23 19:12:41 +0000441 return -1;
442 }
443 *p = (char)x;
444 return 0;
445}
446
447static int
448np_char(char *p, PyObject *v, const formatdef *f)
449{
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000450 if (!PyString_Check(v) || PyString_Size(v) != 1) {
Bob Ippolito232f3c92006-05-23 19:12:41 +0000451 PyErr_SetString(StructError,
452 "char format require string of length 1");
453 return -1;
454 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000455 *p = *PyString_AsString(v);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000456 return 0;
457}
458
459static int
460np_short(char *p, PyObject *v, const formatdef *f)
461{
462 long x;
463 short y;
464 if (get_long(v, &x) < 0)
465 return -1;
466 if (x < SHRT_MIN || x > SHRT_MAX){
467 PyErr_SetString(StructError,
468 "short format requires " STRINGIFY(SHRT_MIN)
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000469 " <= number <= " STRINGIFY(SHRT_MAX));
Bob Ippolito232f3c92006-05-23 19:12:41 +0000470 return -1;
471 }
472 y = (short)x;
473 memcpy(p, (char *)&y, sizeof y);
474 return 0;
475}
476
477static int
478np_ushort(char *p, PyObject *v, const formatdef *f)
479{
480 long x;
481 unsigned short y;
482 if (get_long(v, &x) < 0)
483 return -1;
484 if (x < 0 || x > USHRT_MAX){
485 PyErr_SetString(StructError,
Mark Dickinson24766ba2009-07-07 10:18:22 +0000486 "ushort format requires 0 <= number <= " STRINGIFY(USHRT_MAX));
Bob Ippolito232f3c92006-05-23 19:12:41 +0000487 return -1;
488 }
489 y = (unsigned short)x;
490 memcpy(p, (char *)&y, sizeof y);
491 return 0;
492}
493
494static int
495np_int(char *p, PyObject *v, const formatdef *f)
496{
497 long x;
498 int y;
499 if (get_long(v, &x) < 0)
500 return -1;
Bob Ippolito90bd0a52006-05-27 11:47:12 +0000501#if (SIZEOF_LONG > SIZEOF_INT)
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000502 if ((x < ((long)INT_MIN)) || (x > ((long)INT_MAX)))
Mark Dickinson5fd3af22009-07-07 15:08:28 +0000503 return _range_error(f, 0);
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000504#endif
Bob Ippolito232f3c92006-05-23 19:12:41 +0000505 y = (int)x;
506 memcpy(p, (char *)&y, sizeof y);
507 return 0;
508}
509
510static int
511np_uint(char *p, PyObject *v, const formatdef *f)
512{
513 unsigned long x;
514 unsigned int y;
Mark Dickinson716a9cc2009-09-27 16:39:28 +0000515 if (get_ulong(v, &x) < 0)
Georg Brandl6269fec2009-01-01 12:15:31 +0000516 return -1;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000517 y = (unsigned int)x;
Bob Ippolito90bd0a52006-05-27 11:47:12 +0000518#if (SIZEOF_LONG > SIZEOF_INT)
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000519 if (x > ((unsigned long)UINT_MAX))
Mark Dickinson5fd3af22009-07-07 15:08:28 +0000520 return _range_error(f, 1);
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000521#endif
Bob Ippolito232f3c92006-05-23 19:12:41 +0000522 memcpy(p, (char *)&y, sizeof y);
523 return 0;
524}
525
526static int
527np_long(char *p, PyObject *v, const formatdef *f)
528{
529 long x;
530 if (get_long(v, &x) < 0)
531 return -1;
532 memcpy(p, (char *)&x, sizeof x);
533 return 0;
534}
535
536static int
537np_ulong(char *p, PyObject *v, const formatdef *f)
538{
539 unsigned long x;
Mark Dickinson716a9cc2009-09-27 16:39:28 +0000540 if (get_ulong(v, &x) < 0)
Georg Brandl6269fec2009-01-01 12:15:31 +0000541 return -1;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000542 memcpy(p, (char *)&x, sizeof x);
543 return 0;
544}
545
546#ifdef HAVE_LONG_LONG
547
548static int
549np_longlong(char *p, PyObject *v, const formatdef *f)
550{
551 PY_LONG_LONG x;
552 if (get_longlong(v, &x) < 0)
553 return -1;
554 memcpy(p, (char *)&x, sizeof x);
555 return 0;
556}
557
558static int
559np_ulonglong(char *p, PyObject *v, const formatdef *f)
560{
561 unsigned PY_LONG_LONG x;
562 if (get_ulonglong(v, &x) < 0)
563 return -1;
564 memcpy(p, (char *)&x, sizeof x);
565 return 0;
566}
567#endif
568
Martin v. Löwisaef4c6b2007-01-21 09:33:07 +0000569
570static int
571np_bool(char *p, PyObject *v, const formatdef *f)
572{
573 BOOL_TYPE y;
574 y = PyObject_IsTrue(v);
575 memcpy(p, (char *)&y, sizeof y);
576 return 0;
577}
578
Bob Ippolito232f3c92006-05-23 19:12:41 +0000579static int
580np_float(char *p, PyObject *v, const formatdef *f)
581{
582 float x = (float)PyFloat_AsDouble(v);
583 if (x == -1 && PyErr_Occurred()) {
584 PyErr_SetString(StructError,
585 "required argument is not a float");
586 return -1;
587 }
588 memcpy(p, (char *)&x, sizeof x);
589 return 0;
590}
591
592static int
593np_double(char *p, PyObject *v, const formatdef *f)
594{
595 double x = PyFloat_AsDouble(v);
596 if (x == -1 && PyErr_Occurred()) {
597 PyErr_SetString(StructError,
598 "required argument is not a float");
599 return -1;
600 }
601 memcpy(p, (char *)&x, sizeof(double));
602 return 0;
603}
604
605static int
606np_void_p(char *p, PyObject *v, const formatdef *f)
607{
608 void *x;
609
610 v = get_pylong(v);
611 if (v == NULL)
612 return -1;
613 assert(PyLong_Check(v));
614 x = PyLong_AsVoidPtr(v);
615 Py_DECREF(v);
616 if (x == NULL && PyErr_Occurred())
617 return -1;
618 memcpy(p, (char *)&x, sizeof x);
619 return 0;
620}
621
622static formatdef native_table[] = {
623 {'x', sizeof(char), 0, NULL},
624 {'b', sizeof(char), 0, nu_byte, np_byte},
625 {'B', sizeof(char), 0, nu_ubyte, np_ubyte},
626 {'c', sizeof(char), 0, nu_char, np_char},
627 {'s', sizeof(char), 0, NULL},
628 {'p', sizeof(char), 0, NULL},
629 {'h', sizeof(short), SHORT_ALIGN, nu_short, np_short},
630 {'H', sizeof(short), SHORT_ALIGN, nu_ushort, np_ushort},
631 {'i', sizeof(int), INT_ALIGN, nu_int, np_int},
632 {'I', sizeof(int), INT_ALIGN, nu_uint, np_uint},
633 {'l', sizeof(long), LONG_ALIGN, nu_long, np_long},
634 {'L', sizeof(long), LONG_ALIGN, nu_ulong, np_ulong},
Bob Ippolito232f3c92006-05-23 19:12:41 +0000635#ifdef HAVE_LONG_LONG
636 {'q', sizeof(PY_LONG_LONG), LONG_LONG_ALIGN, nu_longlong, np_longlong},
637 {'Q', sizeof(PY_LONG_LONG), LONG_LONG_ALIGN, nu_ulonglong,np_ulonglong},
638#endif
Thomas Hellerf3c05592008-03-05 15:34:29 +0000639 {'?', sizeof(BOOL_TYPE), BOOL_ALIGN, nu_bool, np_bool},
Bob Ippolitoa99865b2006-05-25 19:56:56 +0000640 {'f', sizeof(float), FLOAT_ALIGN, nu_float, np_float},
641 {'d', sizeof(double), DOUBLE_ALIGN, nu_double, np_double},
642 {'P', sizeof(void *), VOID_P_ALIGN, nu_void_p, np_void_p},
Bob Ippolito232f3c92006-05-23 19:12:41 +0000643 {0}
644};
645
646/* Big-endian routines. *****************************************************/
647
648static PyObject *
649bu_int(const char *p, const formatdef *f)
650{
651 long x = 0;
Bob Ippolitoaa70a172006-05-26 20:25:23 +0000652 Py_ssize_t i = f->size;
Bob Ippolito28b26862006-05-29 15:47:29 +0000653 const unsigned char *bytes = (const unsigned char *)p;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000654 do {
Bob Ippolito28b26862006-05-29 15:47:29 +0000655 x = (x<<8) | *bytes++;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000656 } while (--i > 0);
657 /* Extend the sign bit. */
658 if (SIZEOF_LONG > f->size)
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000659 x |= -(x & (1L << ((8 * f->size) - 1)));
Bob Ippolito232f3c92006-05-23 19:12:41 +0000660 return PyInt_FromLong(x);
661}
662
663static PyObject *
664bu_uint(const char *p, const formatdef *f)
665{
666 unsigned long x = 0;
Bob Ippolitoaa70a172006-05-26 20:25:23 +0000667 Py_ssize_t i = f->size;
Bob Ippolito28b26862006-05-29 15:47:29 +0000668 const unsigned char *bytes = (const unsigned char *)p;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000669 do {
Bob Ippolito28b26862006-05-29 15:47:29 +0000670 x = (x<<8) | *bytes++;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000671 } while (--i > 0);
Bob Ippolito04ab9942006-05-25 19:33:38 +0000672 if (x <= LONG_MAX)
Bob Ippolito232f3c92006-05-23 19:12:41 +0000673 return PyInt_FromLong((long)x);
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000674 return PyLong_FromUnsignedLong(x);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000675}
676
677static PyObject *
678bu_longlong(const char *p, const formatdef *f)
679{
Bob Ippolito90bd0a52006-05-27 11:47:12 +0000680#ifdef HAVE_LONG_LONG
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000681 PY_LONG_LONG x = 0;
Bob Ippolitoaa70a172006-05-26 20:25:23 +0000682 Py_ssize_t i = f->size;
Bob Ippolito28b26862006-05-29 15:47:29 +0000683 const unsigned char *bytes = (const unsigned char *)p;
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000684 do {
Bob Ippolito28b26862006-05-29 15:47:29 +0000685 x = (x<<8) | *bytes++;
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000686 } while (--i > 0);
687 /* Extend the sign bit. */
688 if (SIZEOF_LONG_LONG > f->size)
Kristján Valur Jónsson67387fb2007-04-25 00:17:39 +0000689 x |= -(x & ((PY_LONG_LONG)1 << ((8 * f->size) - 1)));
Bob Ippolito04ab9942006-05-25 19:33:38 +0000690 if (x >= LONG_MIN && x <= LONG_MAX)
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000691 return PyInt_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long));
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000692 return PyLong_FromLongLong(x);
693#else
Bob Ippolito232f3c92006-05-23 19:12:41 +0000694 return _PyLong_FromByteArray((const unsigned char *)p,
695 8,
696 0, /* little-endian */
697 1 /* signed */);
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000698#endif
Bob Ippolito232f3c92006-05-23 19:12:41 +0000699}
700
701static PyObject *
702bu_ulonglong(const char *p, const formatdef *f)
703{
Bob Ippolito90bd0a52006-05-27 11:47:12 +0000704#ifdef HAVE_LONG_LONG
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000705 unsigned PY_LONG_LONG x = 0;
Bob Ippolitoaa70a172006-05-26 20:25:23 +0000706 Py_ssize_t i = f->size;
Bob Ippolito28b26862006-05-29 15:47:29 +0000707 const unsigned char *bytes = (const unsigned char *)p;
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000708 do {
Bob Ippolito28b26862006-05-29 15:47:29 +0000709 x = (x<<8) | *bytes++;
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000710 } while (--i > 0);
Bob Ippolito04ab9942006-05-25 19:33:38 +0000711 if (x <= LONG_MAX)
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000712 return PyInt_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long));
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000713 return PyLong_FromUnsignedLongLong(x);
714#else
Bob Ippolito232f3c92006-05-23 19:12:41 +0000715 return _PyLong_FromByteArray((const unsigned char *)p,
716 8,
717 0, /* little-endian */
718 0 /* signed */);
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000719#endif
Bob Ippolito232f3c92006-05-23 19:12:41 +0000720}
721
722static PyObject *
723bu_float(const char *p, const formatdef *f)
724{
725 return unpack_float(p, 0);
726}
727
728static PyObject *
729bu_double(const char *p, const formatdef *f)
730{
731 return unpack_double(p, 0);
732}
733
Martin v. Löwisaef4c6b2007-01-21 09:33:07 +0000734static PyObject *
735bu_bool(const char *p, const formatdef *f)
736{
737 char x;
738 memcpy((char *)&x, p, sizeof x);
739 return PyBool_FromLong(x != 0);
740}
741
Bob Ippolito232f3c92006-05-23 19:12:41 +0000742static int
743bp_int(char *p, PyObject *v, const formatdef *f)
744{
745 long x;
Bob Ippolitoaa70a172006-05-26 20:25:23 +0000746 Py_ssize_t i;
Mark Dickinson716a9cc2009-09-27 16:39:28 +0000747 if (get_long(v, &x) < 0)
Bob Ippolito232f3c92006-05-23 19:12:41 +0000748 return -1;
749 i = f->size;
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000750 if (i != SIZEOF_LONG) {
751 if ((i == 2) && (x < -32768 || x > 32767))
Mark Dickinson5fd3af22009-07-07 15:08:28 +0000752 return _range_error(f, 0);
Bob Ippolito90bd0a52006-05-27 11:47:12 +0000753#if (SIZEOF_LONG != 4)
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000754 else if ((i == 4) && (x < -2147483648L || x > 2147483647L))
Mark Dickinson5fd3af22009-07-07 15:08:28 +0000755 return _range_error(f, 0);
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000756#endif
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000757 }
Bob Ippolito232f3c92006-05-23 19:12:41 +0000758 do {
759 p[--i] = (char)x;
760 x >>= 8;
761 } while (i > 0);
762 return 0;
763}
764
765static int
766bp_uint(char *p, PyObject *v, const formatdef *f)
767{
768 unsigned long x;
Bob Ippolitoaa70a172006-05-26 20:25:23 +0000769 Py_ssize_t i;
Mark Dickinson716a9cc2009-09-27 16:39:28 +0000770 if (get_ulong(v, &x) < 0)
Bob Ippolito232f3c92006-05-23 19:12:41 +0000771 return -1;
772 i = f->size;
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000773 if (i != SIZEOF_LONG) {
774 unsigned long maxint = 1;
775 maxint <<= (unsigned long)(i * 8);
776 if (x >= maxint)
Mark Dickinson5fd3af22009-07-07 15:08:28 +0000777 return _range_error(f, 1);
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000778 }
Bob Ippolito232f3c92006-05-23 19:12:41 +0000779 do {
780 p[--i] = (char)x;
781 x >>= 8;
782 } while (i > 0);
783 return 0;
784}
785
786static int
787bp_longlong(char *p, PyObject *v, const formatdef *f)
788{
789 int res;
790 v = get_pylong(v);
791 if (v == NULL)
792 return -1;
793 res = _PyLong_AsByteArray((PyLongObject *)v,
794 (unsigned char *)p,
795 8,
796 0, /* little_endian */
797 1 /* signed */);
798 Py_DECREF(v);
799 return res;
800}
801
802static int
803bp_ulonglong(char *p, PyObject *v, const formatdef *f)
804{
805 int res;
806 v = get_pylong(v);
807 if (v == NULL)
808 return -1;
809 res = _PyLong_AsByteArray((PyLongObject *)v,
810 (unsigned char *)p,
811 8,
812 0, /* little_endian */
813 0 /* signed */);
814 Py_DECREF(v);
815 return res;
816}
817
818static int
819bp_float(char *p, PyObject *v, const formatdef *f)
820{
821 double x = PyFloat_AsDouble(v);
822 if (x == -1 && PyErr_Occurred()) {
823 PyErr_SetString(StructError,
824 "required argument is not a float");
825 return -1;
826 }
827 return _PyFloat_Pack4(x, (unsigned char *)p, 0);
828}
829
830static int
831bp_double(char *p, PyObject *v, const formatdef *f)
832{
833 double x = PyFloat_AsDouble(v);
834 if (x == -1 && PyErr_Occurred()) {
835 PyErr_SetString(StructError,
836 "required argument is not a float");
837 return -1;
838 }
839 return _PyFloat_Pack8(x, (unsigned char *)p, 0);
840}
841
Martin v. Löwisaef4c6b2007-01-21 09:33:07 +0000842static int
843bp_bool(char *p, PyObject *v, const formatdef *f)
844{
845 char y;
846 y = PyObject_IsTrue(v);
847 memcpy(p, (char *)&y, sizeof y);
848 return 0;
849}
850
Bob Ippolito232f3c92006-05-23 19:12:41 +0000851static formatdef bigendian_table[] = {
852 {'x', 1, 0, NULL},
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000853 {'b', 1, 0, nu_byte, np_byte},
854 {'B', 1, 0, nu_ubyte, np_ubyte},
Bob Ippolito232f3c92006-05-23 19:12:41 +0000855 {'c', 1, 0, nu_char, np_char},
856 {'s', 1, 0, NULL},
857 {'p', 1, 0, NULL},
858 {'h', 2, 0, bu_int, bp_int},
859 {'H', 2, 0, bu_uint, bp_uint},
860 {'i', 4, 0, bu_int, bp_int},
861 {'I', 4, 0, bu_uint, bp_uint},
862 {'l', 4, 0, bu_int, bp_int},
863 {'L', 4, 0, bu_uint, bp_uint},
864 {'q', 8, 0, bu_longlong, bp_longlong},
865 {'Q', 8, 0, bu_ulonglong, bp_ulonglong},
Thomas Hellerf3c05592008-03-05 15:34:29 +0000866 {'?', 1, 0, bu_bool, bp_bool},
Bob Ippolito232f3c92006-05-23 19:12:41 +0000867 {'f', 4, 0, bu_float, bp_float},
868 {'d', 8, 0, bu_double, bp_double},
869 {0}
870};
871
872/* Little-endian routines. *****************************************************/
873
874static PyObject *
875lu_int(const char *p, const formatdef *f)
876{
877 long x = 0;
Bob Ippolitoaa70a172006-05-26 20:25:23 +0000878 Py_ssize_t i = f->size;
Bob Ippolito28b26862006-05-29 15:47:29 +0000879 const unsigned char *bytes = (const unsigned char *)p;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000880 do {
Bob Ippolito28b26862006-05-29 15:47:29 +0000881 x = (x<<8) | bytes[--i];
Bob Ippolito232f3c92006-05-23 19:12:41 +0000882 } while (i > 0);
883 /* Extend the sign bit. */
884 if (SIZEOF_LONG > f->size)
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000885 x |= -(x & (1L << ((8 * f->size) - 1)));
Bob Ippolito232f3c92006-05-23 19:12:41 +0000886 return PyInt_FromLong(x);
887}
888
889static PyObject *
890lu_uint(const char *p, const formatdef *f)
891{
892 unsigned long x = 0;
Bob Ippolitoaa70a172006-05-26 20:25:23 +0000893 Py_ssize_t i = f->size;
Bob Ippolito28b26862006-05-29 15:47:29 +0000894 const unsigned char *bytes = (const unsigned char *)p;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000895 do {
Bob Ippolito28b26862006-05-29 15:47:29 +0000896 x = (x<<8) | bytes[--i];
Bob Ippolito232f3c92006-05-23 19:12:41 +0000897 } while (i > 0);
Bob Ippolito04ab9942006-05-25 19:33:38 +0000898 if (x <= LONG_MAX)
Bob Ippolito232f3c92006-05-23 19:12:41 +0000899 return PyInt_FromLong((long)x);
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000900 return PyLong_FromUnsignedLong((long)x);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000901}
902
903static PyObject *
904lu_longlong(const char *p, const formatdef *f)
905{
Bob Ippolito90bd0a52006-05-27 11:47:12 +0000906#ifdef HAVE_LONG_LONG
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000907 PY_LONG_LONG x = 0;
Bob Ippolitoaa70a172006-05-26 20:25:23 +0000908 Py_ssize_t i = f->size;
Bob Ippolito28b26862006-05-29 15:47:29 +0000909 const unsigned char *bytes = (const unsigned char *)p;
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000910 do {
Bob Ippolito28b26862006-05-29 15:47:29 +0000911 x = (x<<8) | bytes[--i];
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000912 } while (i > 0);
913 /* Extend the sign bit. */
914 if (SIZEOF_LONG_LONG > f->size)
Kristján Valur Jónsson67387fb2007-04-25 00:17:39 +0000915 x |= -(x & ((PY_LONG_LONG)1 << ((8 * f->size) - 1)));
Bob Ippolito04ab9942006-05-25 19:33:38 +0000916 if (x >= LONG_MIN && x <= LONG_MAX)
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000917 return PyInt_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long));
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000918 return PyLong_FromLongLong(x);
919#else
Bob Ippolito232f3c92006-05-23 19:12:41 +0000920 return _PyLong_FromByteArray((const unsigned char *)p,
921 8,
922 1, /* little-endian */
923 1 /* signed */);
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000924#endif
Bob Ippolito232f3c92006-05-23 19:12:41 +0000925}
926
927static PyObject *
928lu_ulonglong(const char *p, const formatdef *f)
929{
Bob Ippolito90bd0a52006-05-27 11:47:12 +0000930#ifdef HAVE_LONG_LONG
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000931 unsigned PY_LONG_LONG x = 0;
Bob Ippolitoaa70a172006-05-26 20:25:23 +0000932 Py_ssize_t i = f->size;
Bob Ippolito28b26862006-05-29 15:47:29 +0000933 const unsigned char *bytes = (const unsigned char *)p;
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000934 do {
Bob Ippolito28b26862006-05-29 15:47:29 +0000935 x = (x<<8) | bytes[--i];
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000936 } while (i > 0);
Bob Ippolito04ab9942006-05-25 19:33:38 +0000937 if (x <= LONG_MAX)
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000938 return PyInt_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long));
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000939 return PyLong_FromUnsignedLongLong(x);
940#else
Bob Ippolito232f3c92006-05-23 19:12:41 +0000941 return _PyLong_FromByteArray((const unsigned char *)p,
942 8,
943 1, /* little-endian */
944 0 /* signed */);
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000945#endif
Bob Ippolito232f3c92006-05-23 19:12:41 +0000946}
947
948static PyObject *
949lu_float(const char *p, const formatdef *f)
950{
951 return unpack_float(p, 1);
952}
953
954static PyObject *
955lu_double(const char *p, const formatdef *f)
956{
957 return unpack_double(p, 1);
958}
959
960static int
961lp_int(char *p, PyObject *v, const formatdef *f)
962{
963 long x;
Bob Ippolitoaa70a172006-05-26 20:25:23 +0000964 Py_ssize_t i;
Mark Dickinson716a9cc2009-09-27 16:39:28 +0000965 if (get_long(v, &x) < 0)
Bob Ippolito232f3c92006-05-23 19:12:41 +0000966 return -1;
967 i = f->size;
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000968 if (i != SIZEOF_LONG) {
969 if ((i == 2) && (x < -32768 || x > 32767))
Mark Dickinson5fd3af22009-07-07 15:08:28 +0000970 return _range_error(f, 0);
Bob Ippolito90bd0a52006-05-27 11:47:12 +0000971#if (SIZEOF_LONG != 4)
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000972 else if ((i == 4) && (x < -2147483648L || x > 2147483647L))
Mark Dickinson5fd3af22009-07-07 15:08:28 +0000973 return _range_error(f, 0);
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000974#endif
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000975 }
Bob Ippolito232f3c92006-05-23 19:12:41 +0000976 do {
977 *p++ = (char)x;
978 x >>= 8;
979 } while (--i > 0);
980 return 0;
981}
982
983static int
984lp_uint(char *p, PyObject *v, const formatdef *f)
985{
986 unsigned long x;
Bob Ippolitoaa70a172006-05-26 20:25:23 +0000987 Py_ssize_t i;
Mark Dickinson716a9cc2009-09-27 16:39:28 +0000988 if (get_ulong(v, &x) < 0)
Bob Ippolito232f3c92006-05-23 19:12:41 +0000989 return -1;
990 i = f->size;
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000991 if (i != SIZEOF_LONG) {
992 unsigned long maxint = 1;
993 maxint <<= (unsigned long)(i * 8);
994 if (x >= maxint)
Mark Dickinson5fd3af22009-07-07 15:08:28 +0000995 return _range_error(f, 1);
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000996 }
Bob Ippolito232f3c92006-05-23 19:12:41 +0000997 do {
998 *p++ = (char)x;
999 x >>= 8;
1000 } while (--i > 0);
1001 return 0;
1002}
1003
1004static int
1005lp_longlong(char *p, PyObject *v, const formatdef *f)
1006{
1007 int res;
1008 v = get_pylong(v);
1009 if (v == NULL)
1010 return -1;
1011 res = _PyLong_AsByteArray((PyLongObject*)v,
1012 (unsigned char *)p,
1013 8,
1014 1, /* little_endian */
1015 1 /* signed */);
1016 Py_DECREF(v);
1017 return res;
1018}
1019
1020static int
1021lp_ulonglong(char *p, PyObject *v, const formatdef *f)
1022{
1023 int res;
1024 v = get_pylong(v);
1025 if (v == NULL)
1026 return -1;
1027 res = _PyLong_AsByteArray((PyLongObject*)v,
1028 (unsigned char *)p,
1029 8,
1030 1, /* little_endian */
1031 0 /* signed */);
1032 Py_DECREF(v);
1033 return res;
1034}
1035
1036static int
1037lp_float(char *p, PyObject *v, const formatdef *f)
1038{
1039 double x = PyFloat_AsDouble(v);
1040 if (x == -1 && PyErr_Occurred()) {
1041 PyErr_SetString(StructError,
1042 "required argument is not a float");
1043 return -1;
1044 }
1045 return _PyFloat_Pack4(x, (unsigned char *)p, 1);
1046}
1047
1048static int
1049lp_double(char *p, PyObject *v, const formatdef *f)
1050{
1051 double x = PyFloat_AsDouble(v);
1052 if (x == -1 && PyErr_Occurred()) {
1053 PyErr_SetString(StructError,
1054 "required argument is not a float");
1055 return -1;
1056 }
1057 return _PyFloat_Pack8(x, (unsigned char *)p, 1);
1058}
1059
1060static formatdef lilendian_table[] = {
1061 {'x', 1, 0, NULL},
Bob Ippolitoe27337b2006-05-26 13:15:44 +00001062 {'b', 1, 0, nu_byte, np_byte},
1063 {'B', 1, 0, nu_ubyte, np_ubyte},
Bob Ippolito232f3c92006-05-23 19:12:41 +00001064 {'c', 1, 0, nu_char, np_char},
1065 {'s', 1, 0, NULL},
1066 {'p', 1, 0, NULL},
1067 {'h', 2, 0, lu_int, lp_int},
1068 {'H', 2, 0, lu_uint, lp_uint},
1069 {'i', 4, 0, lu_int, lp_int},
1070 {'I', 4, 0, lu_uint, lp_uint},
1071 {'l', 4, 0, lu_int, lp_int},
1072 {'L', 4, 0, lu_uint, lp_uint},
1073 {'q', 8, 0, lu_longlong, lp_longlong},
1074 {'Q', 8, 0, lu_ulonglong, lp_ulonglong},
Thomas Hellerf3c05592008-03-05 15:34:29 +00001075 {'?', 1, 0, bu_bool, bp_bool}, /* Std rep not endian dep,
Martin v. Löwisaef4c6b2007-01-21 09:33:07 +00001076 but potentially different from native rep -- reuse bx_bool funcs. */
Bob Ippolito232f3c92006-05-23 19:12:41 +00001077 {'f', 4, 0, lu_float, lp_float},
1078 {'d', 8, 0, lu_double, lp_double},
1079 {0}
1080};
1081
1082
1083static const formatdef *
1084whichtable(char **pfmt)
1085{
1086 const char *fmt = (*pfmt)++; /* May be backed out of later */
1087 switch (*fmt) {
1088 case '<':
1089 return lilendian_table;
1090 case '>':
1091 case '!': /* Network byte order is big-endian */
1092 return bigendian_table;
1093 case '=': { /* Host byte order -- different from native in aligment! */
1094 int n = 1;
1095 char *p = (char *) &n;
1096 if (*p == 1)
1097 return lilendian_table;
1098 else
1099 return bigendian_table;
1100 }
1101 default:
1102 --*pfmt; /* Back out of pointer increment */
1103 /* Fall through */
1104 case '@':
1105 return native_table;
1106 }
1107}
1108
1109
1110/* Get the table entry for a format code */
1111
1112static const formatdef *
1113getentry(int c, const formatdef *f)
1114{
1115 for (; f->format != '\0'; f++) {
1116 if (f->format == c) {
1117 return f;
1118 }
1119 }
1120 PyErr_SetString(StructError, "bad char in struct format");
1121 return NULL;
1122}
1123
1124
1125/* Align a size according to a format code */
1126
1127static int
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001128align(Py_ssize_t size, char c, const formatdef *e)
Bob Ippolito232f3c92006-05-23 19:12:41 +00001129{
1130 if (e->format == c) {
1131 if (e->alignment) {
1132 size = ((size + e->alignment - 1)
1133 / e->alignment)
1134 * e->alignment;
1135 }
1136 }
1137 return size;
1138}
1139
1140
1141/* calculate the size of a format string */
1142
1143static int
1144prepare_s(PyStructObject *self)
1145{
1146 const formatdef *f;
1147 const formatdef *e;
1148 formatcode *codes;
Tim Petersc2b550e2006-05-31 14:28:07 +00001149
Bob Ippolito232f3c92006-05-23 19:12:41 +00001150 const char *s;
1151 const char *fmt;
1152 char c;
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001153 Py_ssize_t size, len, num, itemsize, x;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001154
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001155 fmt = PyString_AS_STRING(self->s_format);
Bob Ippolito232f3c92006-05-23 19:12:41 +00001156
1157 f = whichtable((char **)&fmt);
Tim Petersc2b550e2006-05-31 14:28:07 +00001158
Bob Ippolito232f3c92006-05-23 19:12:41 +00001159 s = fmt;
1160 size = 0;
1161 len = 0;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001162 while ((c = *s++) != '\0') {
1163 if (isspace(Py_CHARMASK(c)))
1164 continue;
1165 if ('0' <= c && c <= '9') {
1166 num = c - '0';
1167 while ('0' <= (c = *s++) && c <= '9') {
1168 x = num*10 + (c - '0');
1169 if (x/10 != num) {
1170 PyErr_SetString(
1171 StructError,
1172 "overflow in item count");
1173 return -1;
1174 }
1175 num = x;
1176 }
1177 if (c == '\0')
1178 break;
1179 }
1180 else
1181 num = 1;
1182
1183 e = getentry(c, f);
1184 if (e == NULL)
1185 return -1;
Tim Petersc2b550e2006-05-31 14:28:07 +00001186
Bob Ippolito232f3c92006-05-23 19:12:41 +00001187 switch (c) {
1188 case 's': /* fall through */
1189 case 'p': len++; break;
1190 case 'x': break;
1191 default: len += num; break;
1192 }
Bob Ippolito232f3c92006-05-23 19:12:41 +00001193
1194 itemsize = e->size;
1195 size = align(size, c, e);
1196 x = num * itemsize;
1197 size += x;
1198 if (x/itemsize != num || size < 0) {
1199 PyErr_SetString(StructError,
1200 "total struct size too long");
1201 return -1;
1202 }
1203 }
1204
Gregory P. Smith9d534572008-06-11 07:41:16 +00001205 /* check for overflow */
1206 if ((len + 1) > (PY_SSIZE_T_MAX / sizeof(formatcode))) {
1207 PyErr_NoMemory();
1208 return -1;
1209 }
1210
Bob Ippolito232f3c92006-05-23 19:12:41 +00001211 self->s_size = size;
1212 self->s_len = len;
Bob Ippolitoeb621272006-05-24 15:32:06 +00001213 codes = PyMem_MALLOC((len + 1) * sizeof(formatcode));
Bob Ippolito232f3c92006-05-23 19:12:41 +00001214 if (codes == NULL) {
1215 PyErr_NoMemory();
1216 return -1;
1217 }
1218 self->s_codes = codes;
Tim Petersc2b550e2006-05-31 14:28:07 +00001219
Bob Ippolito232f3c92006-05-23 19:12:41 +00001220 s = fmt;
1221 size = 0;
1222 while ((c = *s++) != '\0') {
1223 if (isspace(Py_CHARMASK(c)))
1224 continue;
1225 if ('0' <= c && c <= '9') {
1226 num = c - '0';
1227 while ('0' <= (c = *s++) && c <= '9')
1228 num = num*10 + (c - '0');
1229 if (c == '\0')
1230 break;
1231 }
1232 else
1233 num = 1;
1234
1235 e = getentry(c, f);
Tim Petersc2b550e2006-05-31 14:28:07 +00001236
Bob Ippolito232f3c92006-05-23 19:12:41 +00001237 size = align(size, c, e);
Bob Ippolitoeb621272006-05-24 15:32:06 +00001238 if (c == 's' || c == 'p') {
Bob Ippolito232f3c92006-05-23 19:12:41 +00001239 codes->offset = size;
Bob Ippolitoeb621272006-05-24 15:32:06 +00001240 codes->size = num;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001241 codes->fmtdef = e;
1242 codes++;
Bob Ippolitoeb621272006-05-24 15:32:06 +00001243 size += num;
1244 } else if (c == 'x') {
1245 size += num;
1246 } else {
1247 while (--num >= 0) {
1248 codes->offset = size;
1249 codes->size = e->size;
1250 codes->fmtdef = e;
1251 codes++;
1252 size += e->size;
1253 }
Bob Ippolito232f3c92006-05-23 19:12:41 +00001254 }
Bob Ippolito232f3c92006-05-23 19:12:41 +00001255 }
1256 codes->fmtdef = NULL;
Bob Ippolitoeb621272006-05-24 15:32:06 +00001257 codes->offset = size;
1258 codes->size = 0;
Tim Petersc2b550e2006-05-31 14:28:07 +00001259
Bob Ippolito232f3c92006-05-23 19:12:41 +00001260 return 0;
1261}
1262
1263static PyObject *
1264s_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1265{
1266 PyObject *self;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001267
1268 assert(type != NULL && type->tp_alloc != NULL);
1269
1270 self = type->tp_alloc(type, 0);
1271 if (self != NULL) {
1272 PyStructObject *s = (PyStructObject*)self;
1273 Py_INCREF(Py_None);
1274 s->s_format = Py_None;
1275 s->s_codes = NULL;
1276 s->s_size = -1;
1277 s->s_len = -1;
1278 }
1279 return self;
1280}
1281
1282static int
1283s_init(PyObject *self, PyObject *args, PyObject *kwds)
1284{
1285 PyStructObject *soself = (PyStructObject *)self;
1286 PyObject *o_format = NULL;
1287 int ret = 0;
1288 static char *kwlist[] = {"format", 0};
1289
1290 assert(PyStruct_Check(self));
1291
1292 if (!PyArg_ParseTupleAndKeywords(args, kwds, "S:Struct", kwlist,
1293 &o_format))
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001294 return -1;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001295
1296 Py_INCREF(o_format);
Amaury Forgeot d'Arc588ff932008-02-16 14:34:57 +00001297 Py_CLEAR(soself->s_format);
Bob Ippolito232f3c92006-05-23 19:12:41 +00001298 soself->s_format = o_format;
Tim Petersc2b550e2006-05-31 14:28:07 +00001299
Bob Ippolito232f3c92006-05-23 19:12:41 +00001300 ret = prepare_s(soself);
1301 return ret;
1302}
1303
1304static void
1305s_dealloc(PyStructObject *s)
1306{
Bob Ippolito232f3c92006-05-23 19:12:41 +00001307 if (s->weakreflist != NULL)
1308 PyObject_ClearWeakRefs((PyObject *)s);
1309 if (s->s_codes != NULL) {
1310 PyMem_FREE(s->s_codes);
1311 }
1312 Py_XDECREF(s->s_format);
Christian Heimese93237d2007-12-19 02:37:44 +00001313 Py_TYPE(s)->tp_free((PyObject *)s);
Bob Ippolito232f3c92006-05-23 19:12:41 +00001314}
1315
Bob Ippolitoeb621272006-05-24 15:32:06 +00001316static PyObject *
1317s_unpack_internal(PyStructObject *soself, char *startfrom) {
1318 formatcode *code;
1319 Py_ssize_t i = 0;
1320 PyObject *result = PyTuple_New(soself->s_len);
1321 if (result == NULL)
1322 return NULL;
1323
1324 for (code = soself->s_codes; code->fmtdef != NULL; code++) {
1325 PyObject *v;
1326 const formatdef *e = code->fmtdef;
1327 const char *res = startfrom + code->offset;
1328 if (e->format == 's') {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001329 v = PyString_FromStringAndSize(res, code->size);
Bob Ippolitoeb621272006-05-24 15:32:06 +00001330 } else if (e->format == 'p') {
1331 Py_ssize_t n = *(unsigned char*)res;
1332 if (n >= code->size)
1333 n = code->size - 1;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001334 v = PyString_FromStringAndSize(res + 1, n);
Bob Ippolitoeb621272006-05-24 15:32:06 +00001335 } else {
1336 v = e->unpack(res, e);
Bob Ippolitoeb621272006-05-24 15:32:06 +00001337 }
Neal Norwitz3c5431e2006-06-11 05:45:25 +00001338 if (v == NULL)
1339 goto fail;
1340 PyTuple_SET_ITEM(result, i++, v);
Bob Ippolitoeb621272006-05-24 15:32:06 +00001341 }
1342
1343 return result;
1344fail:
1345 Py_DECREF(result);
1346 return NULL;
Bob Ippolitocd51ca52006-05-27 15:53:49 +00001347}
Bob Ippolitoeb621272006-05-24 15:32:06 +00001348
1349
Bob Ippolito232f3c92006-05-23 19:12:41 +00001350PyDoc_STRVAR(s_unpack__doc__,
Bob Ippolito1fcdc232006-05-27 12:11:36 +00001351"S.unpack(str) -> (v1, v2, ...)\n\
Bob Ippolito232f3c92006-05-23 19:12:41 +00001352\n\
1353Return tuple containing values unpacked according to this Struct's format.\n\
1354Requires len(str) == self.size. See struct.__doc__ for more on format\n\
1355strings.");
1356
1357static PyObject *
1358s_unpack(PyObject *self, PyObject *inputstr)
1359{
Raymond Hettinger7a3d41f2007-04-05 18:00:03 +00001360 char *start;
1361 Py_ssize_t len;
1362 PyObject *args=NULL, *result;
Bob Ippolitoeb621272006-05-24 15:32:06 +00001363 PyStructObject *soself = (PyStructObject *)self;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001364 assert(PyStruct_Check(self));
Tim Petersc2b550e2006-05-31 14:28:07 +00001365 assert(soself->s_codes != NULL);
Raymond Hettinger7a3d41f2007-04-05 18:00:03 +00001366 if (inputstr == NULL)
1367 goto fail;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001368 if (PyString_Check(inputstr) &&
1369 PyString_GET_SIZE(inputstr) == soself->s_size) {
1370 return s_unpack_internal(soself, PyString_AS_STRING(inputstr));
Bob Ippolito232f3c92006-05-23 19:12:41 +00001371 }
Raymond Hettinger7a3d41f2007-04-05 18:00:03 +00001372 args = PyTuple_Pack(1, inputstr);
1373 if (args == NULL)
1374 return NULL;
1375 if (!PyArg_ParseTuple(args, "s#:unpack", &start, &len))
1376 goto fail;
1377 if (soself->s_size != len)
1378 goto fail;
1379 result = s_unpack_internal(soself, start);
1380 Py_DECREF(args);
1381 return result;
1382
1383fail:
1384 Py_XDECREF(args);
1385 PyErr_Format(StructError,
1386 "unpack requires a string argument of length %zd",
1387 soself->s_size);
1388 return NULL;
Bob Ippolitoeb621272006-05-24 15:32:06 +00001389}
1390
1391PyDoc_STRVAR(s_unpack_from__doc__,
Bob Ippolito1fcdc232006-05-27 12:11:36 +00001392"S.unpack_from(buffer[, offset]) -> (v1, v2, ...)\n\
Bob Ippolitoeb621272006-05-24 15:32:06 +00001393\n\
1394Return tuple containing values unpacked according to this Struct's format.\n\
1395Unlike unpack, unpack_from can unpack values from any object supporting\n\
1396the buffer API, not just str. Requires len(buffer[offset:]) >= self.size.\n\
1397See struct.__doc__ for more on format strings.");
1398
1399static PyObject *
1400s_unpack_from(PyObject *self, PyObject *args, PyObject *kwds)
1401{
1402 static char *kwlist[] = {"buffer", "offset", 0};
1403#if (PY_VERSION_HEX < 0x02050000)
1404 static char *fmt = "z#|i:unpack_from";
1405#else
1406 static char *fmt = "z#|n:unpack_from";
1407#endif
1408 Py_ssize_t buffer_len = 0, offset = 0;
1409 char *buffer = NULL;
1410 PyStructObject *soself = (PyStructObject *)self;
1411 assert(PyStruct_Check(self));
1412 assert(soself->s_codes != NULL);
1413
1414 if (!PyArg_ParseTupleAndKeywords(args, kwds, fmt, kwlist,
1415 &buffer, &buffer_len, &offset))
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001416 return NULL;
Bob Ippolitoeb621272006-05-24 15:32:06 +00001417
1418 if (buffer == NULL) {
1419 PyErr_Format(StructError,
1420 "unpack_from requires a buffer argument");
Bob Ippolito232f3c92006-05-23 19:12:41 +00001421 return NULL;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001422 }
Tim Petersc2b550e2006-05-31 14:28:07 +00001423
Bob Ippolitoeb621272006-05-24 15:32:06 +00001424 if (offset < 0)
1425 offset += buffer_len;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001426
Bob Ippolitoeb621272006-05-24 15:32:06 +00001427 if (offset < 0 || (buffer_len - offset) < soself->s_size) {
1428 PyErr_Format(StructError,
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001429 "unpack_from requires a buffer of at least %zd bytes",
Bob Ippolitoeb621272006-05-24 15:32:06 +00001430 soself->s_size);
1431 return NULL;
1432 }
1433 return s_unpack_internal(soself, buffer + offset);
1434}
Bob Ippolito232f3c92006-05-23 19:12:41 +00001435
Bob Ippolito232f3c92006-05-23 19:12:41 +00001436
Martin Blais2856e5f2006-05-26 12:03:27 +00001437/*
1438 * Guts of the pack function.
1439 *
1440 * Takes a struct object, a tuple of arguments, and offset in that tuple of
1441 * argument for where to start processing the arguments for packing, and a
1442 * character buffer for writing the packed string. The caller must insure
1443 * that the buffer may contain the required length for packing the arguments.
1444 * 0 is returned on success, 1 is returned if there is an error.
1445 *
1446 */
1447static int
1448s_pack_internal(PyStructObject *soself, PyObject *args, int offset, char* buf)
Bob Ippolito232f3c92006-05-23 19:12:41 +00001449{
Bob Ippolito232f3c92006-05-23 19:12:41 +00001450 formatcode *code;
Neal Norwitz3c5431e2006-06-11 05:45:25 +00001451 /* XXX(nnorwitz): why does i need to be a local? can we use
1452 the offset parameter or do we need the wider width? */
Bob Ippolito232f3c92006-05-23 19:12:41 +00001453 Py_ssize_t i;
Martin Blais2856e5f2006-05-26 12:03:27 +00001454
1455 memset(buf, '\0', soself->s_size);
1456 i = offset;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001457 for (code = soself->s_codes; code->fmtdef != NULL; code++) {
1458 Py_ssize_t n;
Neal Norwitz3c5431e2006-06-11 05:45:25 +00001459 PyObject *v = PyTuple_GET_ITEM(args, i++);
Bob Ippolito232f3c92006-05-23 19:12:41 +00001460 const formatdef *e = code->fmtdef;
Martin Blais2856e5f2006-05-26 12:03:27 +00001461 char *res = buf + code->offset;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001462 if (e->format == 's') {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001463 if (!PyString_Check(v)) {
Bob Ippolito232f3c92006-05-23 19:12:41 +00001464 PyErr_SetString(StructError,
Mark Dickinson5fd3af22009-07-07 15:08:28 +00001465 "argument for 's' must "
1466 "be a string");
Martin Blais2856e5f2006-05-26 12:03:27 +00001467 return -1;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001468 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001469 n = PyString_GET_SIZE(v);
Bob Ippolitoeb621272006-05-24 15:32:06 +00001470 if (n > code->size)
1471 n = code->size;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001472 if (n > 0)
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001473 memcpy(res, PyString_AS_STRING(v), n);
Bob Ippolito232f3c92006-05-23 19:12:41 +00001474 } else if (e->format == 'p') {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001475 if (!PyString_Check(v)) {
Bob Ippolito232f3c92006-05-23 19:12:41 +00001476 PyErr_SetString(StructError,
Mark Dickinson5fd3af22009-07-07 15:08:28 +00001477 "argument for 'p' must "
1478 "be a string");
Martin Blais2856e5f2006-05-26 12:03:27 +00001479 return -1;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001480 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001481 n = PyString_GET_SIZE(v);
Bob Ippolitoeb621272006-05-24 15:32:06 +00001482 if (n > (code->size - 1))
1483 n = code->size - 1;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001484 if (n > 0)
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001485 memcpy(res + 1, PyString_AS_STRING(v), n);
Bob Ippolito232f3c92006-05-23 19:12:41 +00001486 if (n > 255)
1487 n = 255;
1488 *res = Py_SAFE_DOWNCAST(n, Py_ssize_t, unsigned char);
Mark Dickinson5fd3af22009-07-07 15:08:28 +00001489 } else if (e->pack(res, v, e) < 0) {
1490 if (strchr(integer_codes, e->format) != NULL &&
1491 PyErr_ExceptionMatches(PyExc_OverflowError))
1492 PyErr_Format(StructError,
1493 "integer out of range for "
1494 "'%c' format code",
1495 e->format);
1496 return -1;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001497 }
1498 }
Tim Petersc2b550e2006-05-31 14:28:07 +00001499
Martin Blais2856e5f2006-05-26 12:03:27 +00001500 /* Success */
1501 return 0;
1502}
Bob Ippolito232f3c92006-05-23 19:12:41 +00001503
Martin Blais2856e5f2006-05-26 12:03:27 +00001504
1505PyDoc_STRVAR(s_pack__doc__,
Bob Ippolito1fcdc232006-05-27 12:11:36 +00001506"S.pack(v1, v2, ...) -> string\n\
Martin Blais2856e5f2006-05-26 12:03:27 +00001507\n\
1508Return a string containing values v1, v2, ... packed according to this\n\
1509Struct's format. See struct.__doc__ for more on format strings.");
1510
1511static PyObject *
1512s_pack(PyObject *self, PyObject *args)
1513{
1514 PyStructObject *soself;
1515 PyObject *result;
1516
1517 /* Validate arguments. */
1518 soself = (PyStructObject *)self;
1519 assert(PyStruct_Check(self));
1520 assert(soself->s_codes != NULL);
Martin Blaisaf2ae722006-06-04 13:49:49 +00001521 if (PyTuple_GET_SIZE(args) != soself->s_len)
Martin Blais2856e5f2006-05-26 12:03:27 +00001522 {
1523 PyErr_Format(StructError,
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001524 "pack requires exactly %zd arguments", soself->s_len);
Martin Blais2856e5f2006-05-26 12:03:27 +00001525 return NULL;
1526 }
Tim Petersc2b550e2006-05-31 14:28:07 +00001527
Martin Blais2856e5f2006-05-26 12:03:27 +00001528 /* Allocate a new string */
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001529 result = PyString_FromStringAndSize((char *)NULL, soself->s_size);
Martin Blais2856e5f2006-05-26 12:03:27 +00001530 if (result == NULL)
1531 return NULL;
Tim Petersc2b550e2006-05-31 14:28:07 +00001532
Martin Blais2856e5f2006-05-26 12:03:27 +00001533 /* Call the guts */
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001534 if ( s_pack_internal(soself, args, 0, PyString_AS_STRING(result)) != 0 ) {
Martin Blais2856e5f2006-05-26 12:03:27 +00001535 Py_DECREF(result);
1536 return NULL;
1537 }
1538
1539 return result;
1540}
1541
Martin Blaisaf2ae722006-06-04 13:49:49 +00001542PyDoc_STRVAR(s_pack_into__doc__,
1543"S.pack_into(buffer, offset, v1, v2, ...)\n\
Martin Blais2856e5f2006-05-26 12:03:27 +00001544\n\
Martin Blaisaf2ae722006-06-04 13:49:49 +00001545Pack the values v1, v2, ... according to this Struct's format, write \n\
Bob Ippolito1fcdc232006-05-27 12:11:36 +00001546the packed bytes into the writable buffer buf starting at offset. Note\n\
1547that the offset is not an optional argument. See struct.__doc__ for \n\
Martin Blais2856e5f2006-05-26 12:03:27 +00001548more on format strings.");
1549
1550static PyObject *
Martin Blaisaf2ae722006-06-04 13:49:49 +00001551s_pack_into(PyObject *self, PyObject *args)
Martin Blais2856e5f2006-05-26 12:03:27 +00001552{
1553 PyStructObject *soself;
1554 char *buffer;
1555 Py_ssize_t buffer_len, offset;
1556
1557 /* Validate arguments. +1 is for the first arg as buffer. */
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 + 2))
Martin Blais2856e5f2006-05-26 12:03:27 +00001562 {
1563 PyErr_Format(StructError,
Martin Blaisaf2ae722006-06-04 13:49:49 +00001564 "pack_into requires exactly %zd arguments",
Martin Blais2856e5f2006-05-26 12:03:27 +00001565 (soself->s_len + 2));
1566 return NULL;
1567 }
1568
1569 /* Extract a writable memory buffer from the first argument */
Tim Petersc2b550e2006-05-31 14:28:07 +00001570 if ( PyObject_AsWriteBuffer(PyTuple_GET_ITEM(args, 0),
1571 (void**)&buffer, &buffer_len) == -1 ) {
Martin Blais2856e5f2006-05-26 12:03:27 +00001572 return NULL;
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001573 }
1574 assert( buffer_len >= 0 );
Martin Blais2856e5f2006-05-26 12:03:27 +00001575
1576 /* Extract the offset from the first argument */
Martin Blaisaf2ae722006-06-04 13:49:49 +00001577 offset = PyInt_AsSsize_t(PyTuple_GET_ITEM(args, 1));
Benjamin Peterson02252482008-09-30 02:11:07 +00001578 if (offset == -1 && PyErr_Occurred())
1579 return NULL;
Martin Blais2856e5f2006-05-26 12:03:27 +00001580
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001581 /* Support negative offsets. */
Martin Blais2856e5f2006-05-26 12:03:27 +00001582 if (offset < 0)
1583 offset += buffer_len;
1584
1585 /* Check boundaries */
1586 if (offset < 0 || (buffer_len - offset) < soself->s_size) {
1587 PyErr_Format(StructError,
Martin Blaisaf2ae722006-06-04 13:49:49 +00001588 "pack_into requires a buffer of at least %zd bytes",
Martin Blais2856e5f2006-05-26 12:03:27 +00001589 soself->s_size);
1590 return NULL;
1591 }
Tim Petersc2b550e2006-05-31 14:28:07 +00001592
Martin Blais2856e5f2006-05-26 12:03:27 +00001593 /* Call the guts */
1594 if ( s_pack_internal(soself, args, 2, buffer + offset) != 0 ) {
1595 return NULL;
1596 }
1597
Georg Brandlc26025c2006-05-28 21:42:54 +00001598 Py_RETURN_NONE;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001599}
1600
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001601static PyObject *
1602s_get_format(PyStructObject *self, void *unused)
1603{
1604 Py_INCREF(self->s_format);
1605 return self->s_format;
1606}
1607
1608static PyObject *
1609s_get_size(PyStructObject *self, void *unused)
1610{
1611 return PyInt_FromSsize_t(self->s_size);
1612}
Bob Ippolito232f3c92006-05-23 19:12:41 +00001613
1614/* List of functions */
1615
1616static struct PyMethodDef s_methods[] = {
Martin Blaisaf2ae722006-06-04 13:49:49 +00001617 {"pack", s_pack, METH_VARARGS, s_pack__doc__},
1618 {"pack_into", s_pack_into, METH_VARARGS, s_pack_into__doc__},
1619 {"unpack", s_unpack, METH_O, s_unpack__doc__},
Neal Norwitza84dcd72007-05-22 07:16:44 +00001620 {"unpack_from", (PyCFunction)s_unpack_from, METH_VARARGS|METH_KEYWORDS,
Tim Peters5ec2e852006-06-04 15:49:07 +00001621 s_unpack_from__doc__},
Bob Ippolito232f3c92006-05-23 19:12:41 +00001622 {NULL, NULL} /* sentinel */
1623};
1624
1625PyDoc_STRVAR(s__doc__, "Compiled struct object");
1626
1627#define OFF(x) offsetof(PyStructObject, x)
1628
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001629static PyGetSetDef s_getsetlist[] = {
Bob Ippolito1fcdc232006-05-27 12:11:36 +00001630 {"format", (getter)s_get_format, (setter)NULL, "struct format string", NULL},
1631 {"size", (getter)s_get_size, (setter)NULL, "struct size in bytes", NULL},
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001632 {NULL} /* sentinel */
Bob Ippolito232f3c92006-05-23 19:12:41 +00001633};
1634
Bob Ippolito232f3c92006-05-23 19:12:41 +00001635static
1636PyTypeObject PyStructType = {
Martin v. Löwis68192102007-07-21 06:55:02 +00001637 PyVarObject_HEAD_INIT(NULL, 0)
Bob Ippolito232f3c92006-05-23 19:12:41 +00001638 "Struct",
1639 sizeof(PyStructObject),
1640 0,
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001641 (destructor)s_dealloc, /* tp_dealloc */
Bob Ippolito232f3c92006-05-23 19:12:41 +00001642 0, /* tp_print */
1643 0, /* tp_getattr */
1644 0, /* tp_setattr */
1645 0, /* tp_compare */
1646 0, /* tp_repr */
1647 0, /* tp_as_number */
1648 0, /* tp_as_sequence */
1649 0, /* tp_as_mapping */
1650 0, /* tp_hash */
1651 0, /* tp_call */
1652 0, /* tp_str */
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001653 PyObject_GenericGetAttr, /* tp_getattro */
1654 PyObject_GenericSetAttr, /* tp_setattro */
Bob Ippolito232f3c92006-05-23 19:12:41 +00001655 0, /* tp_as_buffer */
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001656 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_WEAKREFS,/* tp_flags */
1657 s__doc__, /* tp_doc */
Bob Ippolito232f3c92006-05-23 19:12:41 +00001658 0, /* tp_traverse */
1659 0, /* tp_clear */
1660 0, /* tp_richcompare */
1661 offsetof(PyStructObject, weakreflist), /* tp_weaklistoffset */
1662 0, /* tp_iter */
1663 0, /* tp_iternext */
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001664 s_methods, /* tp_methods */
1665 NULL, /* tp_members */
1666 s_getsetlist, /* tp_getset */
Bob Ippolito232f3c92006-05-23 19:12:41 +00001667 0, /* tp_base */
1668 0, /* tp_dict */
1669 0, /* tp_descr_get */
1670 0, /* tp_descr_set */
1671 0, /* tp_dictoffset */
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001672 s_init, /* tp_init */
1673 PyType_GenericAlloc,/* tp_alloc */
1674 s_new, /* tp_new */
1675 PyObject_Del, /* tp_free */
Bob Ippolito232f3c92006-05-23 19:12:41 +00001676};
1677
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001678
1679/* ---- Standalone functions ---- */
1680
1681#define MAXCACHE 100
Christian Heimes76d19f62008-01-04 02:54:42 +00001682static PyObject *cache = NULL;
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001683
1684static PyObject *
1685cache_struct(PyObject *fmt)
1686{
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001687 PyObject * s_object;
1688
1689 if (cache == NULL) {
1690 cache = PyDict_New();
1691 if (cache == NULL)
1692 return NULL;
1693 }
1694
1695 s_object = PyDict_GetItem(cache, fmt);
1696 if (s_object != NULL) {
1697 Py_INCREF(s_object);
1698 return s_object;
1699 }
1700
1701 s_object = PyObject_CallFunctionObjArgs((PyObject *)(&PyStructType), fmt, NULL);
1702 if (s_object != NULL) {
1703 if (PyDict_Size(cache) >= MAXCACHE)
1704 PyDict_Clear(cache);
1705 /* Attempt to cache the result */
1706 if (PyDict_SetItem(cache, fmt, s_object) == -1)
1707 PyErr_Clear();
1708 }
1709 return s_object;
1710}
1711
Christian Heimes76d19f62008-01-04 02:54:42 +00001712PyDoc_STRVAR(clearcache_doc,
1713"Clear the internal cache.");
1714
1715static PyObject *
1716clearcache(PyObject *self)
1717{
Raymond Hettinger18e08e52008-01-18 00:10:42 +00001718 Py_CLEAR(cache);
Christian Heimes76d19f62008-01-04 02:54:42 +00001719 Py_RETURN_NONE;
1720}
1721
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001722PyDoc_STRVAR(calcsize_doc,
1723"Return size of C struct described by format string fmt.");
1724
1725static PyObject *
1726calcsize(PyObject *self, PyObject *fmt)
1727{
1728 Py_ssize_t n;
1729 PyObject *s_object = cache_struct(fmt);
1730 if (s_object == NULL)
1731 return NULL;
1732 n = ((PyStructObject *)s_object)->s_size;
1733 Py_DECREF(s_object);
1734 return PyInt_FromSsize_t(n);
1735}
1736
1737PyDoc_STRVAR(pack_doc,
1738"Return string containing values v1, v2, ... packed according to fmt.");
1739
1740static PyObject *
1741pack(PyObject *self, PyObject *args)
1742{
1743 PyObject *s_object, *fmt, *newargs, *result;
1744 Py_ssize_t n = PyTuple_GET_SIZE(args);
1745
1746 if (n == 0) {
1747 PyErr_SetString(PyExc_TypeError, "missing format argument");
1748 return NULL;
1749 }
1750 fmt = PyTuple_GET_ITEM(args, 0);
1751 newargs = PyTuple_GetSlice(args, 1, n);
1752 if (newargs == NULL)
1753 return NULL;
1754
1755 s_object = cache_struct(fmt);
1756 if (s_object == NULL) {
1757 Py_DECREF(newargs);
1758 return NULL;
1759 }
1760 result = s_pack(s_object, newargs);
1761 Py_DECREF(newargs);
1762 Py_DECREF(s_object);
1763 return result;
1764}
1765
1766PyDoc_STRVAR(pack_into_doc,
1767"Pack the values v1, v2, ... according to fmt.\n\
1768Write the packed bytes into the writable buffer buf starting at offset.");
1769
1770static PyObject *
1771pack_into(PyObject *self, PyObject *args)
1772{
1773 PyObject *s_object, *fmt, *newargs, *result;
1774 Py_ssize_t n = PyTuple_GET_SIZE(args);
1775
1776 if (n == 0) {
1777 PyErr_SetString(PyExc_TypeError, "missing format argument");
1778 return NULL;
1779 }
1780 fmt = PyTuple_GET_ITEM(args, 0);
1781 newargs = PyTuple_GetSlice(args, 1, n);
1782 if (newargs == NULL)
1783 return NULL;
1784
1785 s_object = cache_struct(fmt);
1786 if (s_object == NULL) {
1787 Py_DECREF(newargs);
1788 return NULL;
1789 }
1790 result = s_pack_into(s_object, newargs);
1791 Py_DECREF(newargs);
1792 Py_DECREF(s_object);
1793 return result;
1794}
1795
1796PyDoc_STRVAR(unpack_doc,
1797"Unpack the string containing packed C structure data, according to fmt.\n\
1798Requires len(string) == calcsize(fmt).");
1799
1800static PyObject *
1801unpack(PyObject *self, PyObject *args)
1802{
1803 PyObject *s_object, *fmt, *inputstr, *result;
1804
1805 if (!PyArg_UnpackTuple(args, "unpack", 2, 2, &fmt, &inputstr))
1806 return NULL;
1807
1808 s_object = cache_struct(fmt);
1809 if (s_object == NULL)
1810 return NULL;
1811 result = s_unpack(s_object, inputstr);
1812 Py_DECREF(s_object);
1813 return result;
1814}
1815
1816PyDoc_STRVAR(unpack_from_doc,
1817"Unpack the buffer, containing packed C structure data, according to\n\
1818fmt, starting at offset. Requires len(buffer[offset:]) >= calcsize(fmt).");
1819
1820static PyObject *
1821unpack_from(PyObject *self, PyObject *args, PyObject *kwds)
1822{
1823 PyObject *s_object, *fmt, *newargs, *result;
1824 Py_ssize_t n = PyTuple_GET_SIZE(args);
1825
1826 if (n == 0) {
1827 PyErr_SetString(PyExc_TypeError, "missing format argument");
1828 return NULL;
1829 }
1830 fmt = PyTuple_GET_ITEM(args, 0);
1831 newargs = PyTuple_GetSlice(args, 1, n);
1832 if (newargs == NULL)
1833 return NULL;
1834
1835 s_object = cache_struct(fmt);
1836 if (s_object == NULL) {
1837 Py_DECREF(newargs);
1838 return NULL;
1839 }
1840 result = s_unpack_from(s_object, newargs, kwds);
1841 Py_DECREF(newargs);
1842 Py_DECREF(s_object);
1843 return result;
1844}
1845
1846static struct PyMethodDef module_functions[] = {
Christian Heimes76d19f62008-01-04 02:54:42 +00001847 {"_clearcache", (PyCFunction)clearcache, METH_NOARGS, clearcache_doc},
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001848 {"calcsize", calcsize, METH_O, calcsize_doc},
1849 {"pack", pack, METH_VARARGS, pack_doc},
1850 {"pack_into", pack_into, METH_VARARGS, pack_into_doc},
1851 {"unpack", unpack, METH_VARARGS, unpack_doc},
1852 {"unpack_from", (PyCFunction)unpack_from,
1853 METH_VARARGS|METH_KEYWORDS, unpack_from_doc},
1854 {NULL, NULL} /* sentinel */
1855};
1856
1857
Bob Ippolito232f3c92006-05-23 19:12:41 +00001858/* Module initialization */
1859
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001860PyDoc_STRVAR(module_doc,
Mark Dickinson3d830822009-10-08 15:54:10 +00001861"Functions to convert between Python values and C structs represented\n\
1862as Python strings. It uses format strings (explained below) as compact\n\
1863descriptions of the lay-out of the C structs and the intended conversion\n\
1864to/from Python values.\n\
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001865\n\
1866The optional first format char indicates byte order, size and alignment:\n\
Mark Dickinson3d830822009-10-08 15:54:10 +00001867 @: native order, size & alignment (default)\n\
1868 =: native order, std. size & alignment\n\
1869 <: little-endian, std. size & alignment\n\
1870 >: big-endian, std. size & alignment\n\
1871 !: same as >\n\
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001872\n\
1873The remaining chars indicate types of args and must match exactly;\n\
1874these can be preceded by a decimal repeat count:\n\
1875 x: pad byte (no data); c:char; b:signed byte; B:unsigned byte;\n\
Mark Dickinson3d830822009-10-08 15:54:10 +00001876 ?: _Bool (requires C99; if not available, char is used instead)\n\
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001877 h:short; H:unsigned short; i:int; I:unsigned int;\n\
1878 l:long; L:unsigned long; f:float; d:double.\n\
1879Special cases (preceding decimal count indicates length):\n\
1880 s:string (array of char); p: pascal string (with count byte).\n\
1881Special case (only available in native format):\n\
1882 P:an integer type that is wide enough to hold a pointer.\n\
1883Special case (not in native mode unless 'long long' in platform C):\n\
1884 q:long long; Q:unsigned long long\n\
1885Whitespace between formats is ignored.\n\
1886\n\
1887The variable struct.error is an exception raised on errors.\n");
1888
Bob Ippolito232f3c92006-05-23 19:12:41 +00001889PyMODINIT_FUNC
1890init_struct(void)
1891{
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001892 PyObject *ver, *m;
1893
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001894 ver = PyString_FromString("0.2");
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001895 if (ver == NULL)
1896 return;
1897
1898 m = Py_InitModule3("_struct", module_functions, module_doc);
Bob Ippolito232f3c92006-05-23 19:12:41 +00001899 if (m == NULL)
1900 return;
1901
Christian Heimese93237d2007-12-19 02:37:44 +00001902 Py_TYPE(&PyStructType) = &PyType_Type;
Bob Ippolito3fc2bb92006-05-25 19:03:19 +00001903 if (PyType_Ready(&PyStructType) < 0)
1904 return;
1905
Mark Dickinson5fd3af22009-07-07 15:08:28 +00001906 /* This speed trick can't be used until overflow masking goes
1907 away, because native endian always raises exceptions
1908 instead of overflow masking. */
Tim Petersc2b550e2006-05-31 14:28:07 +00001909
Bob Ippolitoa99865b2006-05-25 19:56:56 +00001910 /* Check endian and swap in faster functions */
1911 {
1912 int one = 1;
1913 formatdef *native = native_table;
1914 formatdef *other, *ptr;
1915 if ((int)*(unsigned char*)&one)
1916 other = lilendian_table;
1917 else
1918 other = bigendian_table;
Bob Ippolito964e02a2006-05-25 21:09:45 +00001919 /* Scan through the native table, find a matching
1920 entry in the endian table and swap in the
1921 native implementations whenever possible
1922 (64-bit platforms may not have "standard" sizes) */
Bob Ippolitoa99865b2006-05-25 19:56:56 +00001923 while (native->format != '\0' && other->format != '\0') {
1924 ptr = other;
1925 while (ptr->format != '\0') {
1926 if (ptr->format == native->format) {
Bob Ippolito964e02a2006-05-25 21:09:45 +00001927 /* Match faster when formats are
1928 listed in the same order */
Bob Ippolitoa99865b2006-05-25 19:56:56 +00001929 if (ptr == other)
1930 other++;
Tim Petersc2b550e2006-05-31 14:28:07 +00001931 /* Only use the trick if the
Bob Ippolito964e02a2006-05-25 21:09:45 +00001932 size matches */
1933 if (ptr->size != native->size)
1934 break;
1935 /* Skip float and double, could be
1936 "unknown" float format */
1937 if (ptr->format == 'd' || ptr->format == 'f')
1938 break;
1939 ptr->pack = native->pack;
1940 ptr->unpack = native->unpack;
Bob Ippolitoa99865b2006-05-25 19:56:56 +00001941 break;
1942 }
1943 ptr++;
1944 }
1945 native++;
1946 }
1947 }
Tim Petersc2b550e2006-05-31 14:28:07 +00001948
Bob Ippolito232f3c92006-05-23 19:12:41 +00001949 /* Add some symbolic constants to the module */
1950 if (StructError == NULL) {
1951 StructError = PyErr_NewException("struct.error", NULL, NULL);
1952 if (StructError == NULL)
1953 return;
1954 }
Bob Ippolito04ab9942006-05-25 19:33:38 +00001955
Bob Ippolito232f3c92006-05-23 19:12:41 +00001956 Py_INCREF(StructError);
1957 PyModule_AddObject(m, "error", StructError);
Bob Ippolito04ab9942006-05-25 19:33:38 +00001958
Bob Ippolito232f3c92006-05-23 19:12:41 +00001959 Py_INCREF((PyObject*)&PyStructType);
1960 PyModule_AddObject(m, "Struct", (PyObject*)&PyStructType);
Tim Petersc2b550e2006-05-31 14:28:07 +00001961
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001962 PyModule_AddObject(m, "__version__", ver);
1963
Bob Ippolito2fd39772006-05-29 22:55:48 +00001964 PyModule_AddIntConstant(m, "_PY_STRUCT_RANGE_CHECKING", 1);
Bob Ippolitoe6c9f982006-08-04 23:59:21 +00001965 PyModule_AddIntConstant(m, "_PY_STRUCT_FLOAT_COERCE", 1);
Bob Ippolito232f3c92006-05-23 19:12:41 +00001966}