blob: 27f8881fc0cd385dc92562f13be2f1adea556cd7 [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/* If PY_STRUCT_FLOAT_COERCE is defined, the struct module will allow float
21 arguments for integer formats with a warning for backwards
22 compatibility. */
23
24#define PY_STRUCT_FLOAT_COERCE 1
25
26#ifdef PY_STRUCT_FLOAT_COERCE
27#define FLOAT_COERCE "integer argument expected, got float"
28#endif
29
30
Bob Ippolito232f3c92006-05-23 19:12:41 +000031/* The translation function for each format character is table driven */
Bob Ippolito232f3c92006-05-23 19:12:41 +000032typedef struct _formatdef {
33 char format;
Bob Ippolitoaa70a172006-05-26 20:25:23 +000034 Py_ssize_t size;
35 Py_ssize_t alignment;
Bob Ippolito232f3c92006-05-23 19:12:41 +000036 PyObject* (*unpack)(const char *,
37 const struct _formatdef *);
38 int (*pack)(char *, PyObject *,
39 const struct _formatdef *);
40} formatdef;
41
42typedef struct _formatcode {
43 const struct _formatdef *fmtdef;
Bob Ippolitoaa70a172006-05-26 20:25:23 +000044 Py_ssize_t offset;
45 Py_ssize_t size;
Bob Ippolito232f3c92006-05-23 19:12:41 +000046} formatcode;
47
48/* Struct object interface */
49
50typedef struct {
51 PyObject_HEAD
Bob Ippolitoaa70a172006-05-26 20:25:23 +000052 Py_ssize_t s_size;
53 Py_ssize_t s_len;
Bob Ippolito232f3c92006-05-23 19:12:41 +000054 formatcode *s_codes;
55 PyObject *s_format;
56 PyObject *weakreflist; /* List of weak references */
57} PyStructObject;
58
Bob Ippolitoeb621272006-05-24 15:32:06 +000059
Bob Ippolito07c023b2006-05-23 19:32:25 +000060#define PyStruct_Check(op) PyObject_TypeCheck(op, &PyStructType)
Christian Heimese93237d2007-12-19 02:37:44 +000061#define PyStruct_CheckExact(op) (Py_TYPE(op) == &PyStructType)
Bob Ippolito232f3c92006-05-23 19:12:41 +000062
63
64/* Exception */
65
66static PyObject *StructError;
67
68
69/* Define various structs to figure out the alignments of types */
70
71
72typedef struct { char c; short x; } st_short;
73typedef struct { char c; int x; } st_int;
74typedef struct { char c; long x; } st_long;
75typedef struct { char c; float x; } st_float;
76typedef struct { char c; double x; } st_double;
77typedef struct { char c; void *x; } st_void_p;
78
79#define SHORT_ALIGN (sizeof(st_short) - sizeof(short))
80#define INT_ALIGN (sizeof(st_int) - sizeof(int))
81#define LONG_ALIGN (sizeof(st_long) - sizeof(long))
82#define FLOAT_ALIGN (sizeof(st_float) - sizeof(float))
83#define DOUBLE_ALIGN (sizeof(st_double) - sizeof(double))
84#define VOID_P_ALIGN (sizeof(st_void_p) - sizeof(void *))
85
86/* We can't support q and Q in native mode unless the compiler does;
87 in std mode, they're 8 bytes on all platforms. */
88#ifdef HAVE_LONG_LONG
89typedef struct { char c; PY_LONG_LONG x; } s_long_long;
90#define LONG_LONG_ALIGN (sizeof(s_long_long) - sizeof(PY_LONG_LONG))
91#endif
92
Martin v. Löwisaef4c6b2007-01-21 09:33:07 +000093#ifdef HAVE_C99_BOOL
94#define BOOL_TYPE _Bool
95typedef struct { char c; _Bool x; } s_bool;
96#define BOOL_ALIGN (sizeof(s_bool) - sizeof(BOOL_TYPE))
97#else
98#define BOOL_TYPE char
99#define BOOL_ALIGN 0
100#endif
101
Bob Ippolito232f3c92006-05-23 19:12:41 +0000102#define STRINGIFY(x) #x
103
104#ifdef __powerc
105#pragma options align=reset
106#endif
107
Mark Dickinson5fd3af22009-07-07 15:08:28 +0000108static char *integer_codes = "bBhHiIlLqQ";
109
Bob Ippolito232f3c92006-05-23 19:12:41 +0000110/* Helper to get a PyLongObject by hook or by crook. Caller should decref. */
111
112static PyObject *
113get_pylong(PyObject *v)
114{
Bob Ippolito232f3c92006-05-23 19:12:41 +0000115 assert(v != NULL);
116 if (PyInt_Check(v))
117 return PyLong_FromLong(PyInt_AS_LONG(v));
118 if (PyLong_Check(v)) {
119 Py_INCREF(v);
120 return v;
121 }
Mark Dickinson463dc4b2009-07-05 10:01:24 +0000122#ifdef PY_STRUCT_FLOAT_COERCE
123 if (PyFloat_Check(v)) {
124 if (PyErr_WarnEx(PyExc_DeprecationWarning, FLOAT_COERCE, 2)<0)
Bob Ippolito232f3c92006-05-23 19:12:41 +0000125 return NULL;
Mark Dickinson463dc4b2009-07-05 10:01:24 +0000126 return PyNumber_Long(v);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000127 }
Mark Dickinson463dc4b2009-07-05 10:01:24 +0000128#endif
Bob Ippolito232f3c92006-05-23 19:12:41 +0000129 PyErr_SetString(StructError,
130 "cannot convert argument to long");
131 return NULL;
132}
133
Mark Dickinson5fd3af22009-07-07 15:08:28 +0000134/* Helper to convert a Python object to a C long. Sets an exception
135 (struct.error for an inconvertible type, OverflowError for
136 out-of-range values) and returns -1 on error. */
Bob Ippolito232f3c92006-05-23 19:12:41 +0000137
138static int
139get_long(PyObject *v, long *p)
140{
Mark Dickinson463dc4b2009-07-05 10:01:24 +0000141 long x;
142
143 v = get_pylong(v);
144 if (v == NULL)
145 return -1;
146 assert(PyLong_Check(v));
147 x = PyLong_AsLong(v);
148 Py_DECREF(v);
Mark Dickinson5fd3af22009-07-07 15:08:28 +0000149 if (x == (long)-1 && PyErr_Occurred())
Bob Ippolito232f3c92006-05-23 19:12:41 +0000150 return -1;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000151 *p = x;
152 return 0;
153}
154
Bob Ippolito232f3c92006-05-23 19:12:41 +0000155/* Same, but handling unsigned long */
156
157static int
158get_ulong(PyObject *v, unsigned long *p)
159{
Mark Dickinson463dc4b2009-07-05 10:01:24 +0000160 unsigned long x;
161
162 v = get_pylong(v);
163 if (v == NULL)
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000164 return -1;
Mark Dickinson463dc4b2009-07-05 10:01:24 +0000165 assert(PyLong_Check(v));
166 x = PyLong_AsUnsignedLong(v);
167 Py_DECREF(v);
Mark Dickinson5fd3af22009-07-07 15:08:28 +0000168 if (x == (unsigned long)-1 && PyErr_Occurred())
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000169 return -1;
Mark Dickinson463dc4b2009-07-05 10:01:24 +0000170 *p = x;
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000171 return 0;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000172}
173
174#ifdef HAVE_LONG_LONG
175
176/* Same, but handling native long long. */
177
178static int
179get_longlong(PyObject *v, PY_LONG_LONG *p)
180{
181 PY_LONG_LONG x;
182
183 v = get_pylong(v);
184 if (v == NULL)
185 return -1;
186 assert(PyLong_Check(v));
187 x = PyLong_AsLongLong(v);
188 Py_DECREF(v);
Mark Dickinson5fd3af22009-07-07 15:08:28 +0000189 if (x == (PY_LONG_LONG)-1 && PyErr_Occurred())
Bob Ippolito232f3c92006-05-23 19:12:41 +0000190 return -1;
191 *p = x;
192 return 0;
193}
194
195/* Same, but handling native unsigned long long. */
196
197static int
198get_ulonglong(PyObject *v, unsigned PY_LONG_LONG *p)
199{
200 unsigned PY_LONG_LONG x;
201
202 v = get_pylong(v);
203 if (v == NULL)
204 return -1;
205 assert(PyLong_Check(v));
206 x = PyLong_AsUnsignedLongLong(v);
207 Py_DECREF(v);
Mark Dickinson5fd3af22009-07-07 15:08:28 +0000208 if (x == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred())
Bob Ippolito232f3c92006-05-23 19:12:41 +0000209 return -1;
210 *p = x;
211 return 0;
212}
213
214#endif
215
216/* Floating point helpers */
217
218static PyObject *
219unpack_float(const char *p, /* start of 4-byte string */
220 int le) /* true for little-endian, false for big-endian */
221{
222 double x;
223
224 x = _PyFloat_Unpack4((unsigned char *)p, le);
225 if (x == -1.0 && PyErr_Occurred())
226 return NULL;
227 return PyFloat_FromDouble(x);
228}
229
230static PyObject *
231unpack_double(const char *p, /* start of 8-byte string */
232 int le) /* true for little-endian, false for big-endian */
233{
234 double x;
235
236 x = _PyFloat_Unpack8((unsigned char *)p, le);
237 if (x == -1.0 && PyErr_Occurred())
238 return NULL;
239 return PyFloat_FromDouble(x);
240}
241
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000242/* Helper to format the range error exceptions */
243static int
Armin Rigo162997e2006-05-29 17:59:47 +0000244_range_error(const formatdef *f, int is_unsigned)
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000245{
Tim Petersd6a6f022006-05-31 15:33:22 +0000246 /* ulargest is the largest unsigned value with f->size bytes.
247 * Note that the simpler:
248 * ((size_t)1 << (f->size * 8)) - 1
Tim Peters72270c22006-05-31 15:34:37 +0000249 * doesn't work when f->size == sizeof(size_t) because C doesn't
250 * define what happens when a left shift count is >= the number of
251 * bits in the integer being shifted; e.g., on some boxes it doesn't
252 * shift at all when they're equal.
Tim Petersd6a6f022006-05-31 15:33:22 +0000253 */
254 const size_t ulargest = (size_t)-1 >> ((SIZEOF_SIZE_T - f->size)*8);
255 assert(f->size >= 1 && f->size <= SIZEOF_SIZE_T);
256 if (is_unsigned)
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000257 PyErr_Format(StructError,
Neal Norwitz971ea112006-05-31 07:43:27 +0000258 "'%c' format requires 0 <= number <= %zu",
Bob Ippolito28b26862006-05-29 15:47:29 +0000259 f->format,
Tim Petersd6a6f022006-05-31 15:33:22 +0000260 ulargest);
261 else {
262 const Py_ssize_t largest = (Py_ssize_t)(ulargest >> 1);
263 PyErr_Format(StructError,
264 "'%c' format requires %zd <= number <= %zd",
265 f->format,
266 ~ largest,
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000267 largest);
268 }
269 return -1;
270}
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000271
272
Bob Ippolito232f3c92006-05-23 19:12:41 +0000273
274/* A large number of small routines follow, with names of the form
275
Bob Ippolitoaa70a172006-05-26 20:25:23 +0000276 [bln][up]_TYPE
Bob Ippolito232f3c92006-05-23 19:12:41 +0000277
278 [bln] distiguishes among big-endian, little-endian and native.
279 [pu] distiguishes between pack (to struct) and unpack (from struct).
280 TYPE is one of char, byte, ubyte, etc.
281*/
282
283/* Native mode routines. ****************************************************/
284/* NOTE:
285 In all n[up]_<type> routines handling types larger than 1 byte, there is
286 *no* guarantee that the p pointer is properly aligned for each type,
287 therefore memcpy is called. An intermediate variable is used to
288 compensate for big-endian architectures.
289 Normally both the intermediate variable and the memcpy call will be
290 skipped by C optimisation in little-endian architectures (gcc >= 2.91
291 does this). */
292
293static PyObject *
294nu_char(const char *p, const formatdef *f)
295{
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000296 return PyString_FromStringAndSize(p, 1);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000297}
298
299static PyObject *
300nu_byte(const char *p, const formatdef *f)
301{
302 return PyInt_FromLong((long) *(signed char *)p);
303}
304
305static PyObject *
306nu_ubyte(const char *p, const formatdef *f)
307{
308 return PyInt_FromLong((long) *(unsigned char *)p);
309}
310
311static PyObject *
312nu_short(const char *p, const formatdef *f)
313{
314 short x;
315 memcpy((char *)&x, p, sizeof x);
316 return PyInt_FromLong((long)x);
317}
318
319static PyObject *
320nu_ushort(const char *p, const formatdef *f)
321{
322 unsigned short x;
323 memcpy((char *)&x, p, sizeof x);
324 return PyInt_FromLong((long)x);
325}
326
327static PyObject *
328nu_int(const char *p, const formatdef *f)
329{
330 int x;
331 memcpy((char *)&x, p, sizeof x);
332 return PyInt_FromLong((long)x);
333}
334
335static PyObject *
336nu_uint(const char *p, const formatdef *f)
337{
338 unsigned int x;
339 memcpy((char *)&x, p, sizeof x);
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000340#if (SIZEOF_LONG > SIZEOF_INT)
341 return PyInt_FromLong((long)x);
342#else
343 if (x <= ((unsigned int)LONG_MAX))
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000344 return PyInt_FromLong((long)x);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000345 return PyLong_FromUnsignedLong((unsigned long)x);
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000346#endif
Bob Ippolito232f3c92006-05-23 19:12:41 +0000347}
348
349static PyObject *
350nu_long(const char *p, const formatdef *f)
351{
352 long x;
353 memcpy((char *)&x, p, sizeof x);
354 return PyInt_FromLong(x);
355}
356
357static PyObject *
358nu_ulong(const char *p, const formatdef *f)
359{
360 unsigned long x;
361 memcpy((char *)&x, p, sizeof x);
Bob Ippolito04ab9942006-05-25 19:33:38 +0000362 if (x <= LONG_MAX)
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000363 return PyInt_FromLong((long)x);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000364 return PyLong_FromUnsignedLong(x);
365}
366
367/* Native mode doesn't support q or Q unless the platform C supports
368 long long (or, on Windows, __int64). */
369
370#ifdef HAVE_LONG_LONG
371
372static PyObject *
373nu_longlong(const char *p, const formatdef *f)
374{
375 PY_LONG_LONG x;
376 memcpy((char *)&x, p, sizeof x);
Bob Ippolito04ab9942006-05-25 19:33:38 +0000377 if (x >= LONG_MIN && x <= LONG_MAX)
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000378 return PyInt_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long));
Bob Ippolito232f3c92006-05-23 19:12:41 +0000379 return PyLong_FromLongLong(x);
380}
381
382static PyObject *
383nu_ulonglong(const char *p, const formatdef *f)
384{
385 unsigned PY_LONG_LONG x;
386 memcpy((char *)&x, p, sizeof x);
Bob Ippolito04ab9942006-05-25 19:33:38 +0000387 if (x <= LONG_MAX)
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000388 return PyInt_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long));
Bob Ippolito232f3c92006-05-23 19:12:41 +0000389 return PyLong_FromUnsignedLongLong(x);
390}
391
392#endif
393
394static PyObject *
Martin v. Löwisaef4c6b2007-01-21 09:33:07 +0000395nu_bool(const char *p, const formatdef *f)
396{
397 BOOL_TYPE x;
398 memcpy((char *)&x, p, sizeof x);
399 return PyBool_FromLong(x != 0);
400}
401
402
403static PyObject *
Bob Ippolito232f3c92006-05-23 19:12:41 +0000404nu_float(const char *p, const formatdef *f)
405{
406 float x;
407 memcpy((char *)&x, p, sizeof x);
408 return PyFloat_FromDouble((double)x);
409}
410
411static PyObject *
412nu_double(const char *p, const formatdef *f)
413{
414 double x;
415 memcpy((char *)&x, p, sizeof x);
416 return PyFloat_FromDouble(x);
417}
418
419static PyObject *
420nu_void_p(const char *p, const formatdef *f)
421{
422 void *x;
423 memcpy((char *)&x, p, sizeof x);
424 return PyLong_FromVoidPtr(x);
425}
426
427static int
428np_byte(char *p, PyObject *v, const formatdef *f)
429{
430 long x;
431 if (get_long(v, &x) < 0)
432 return -1;
433 if (x < -128 || x > 127){
434 PyErr_SetString(StructError,
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000435 "byte format requires -128 <= number <= 127");
Bob Ippolito232f3c92006-05-23 19:12:41 +0000436 return -1;
437 }
438 *p = (char)x;
439 return 0;
440}
441
442static int
443np_ubyte(char *p, PyObject *v, const formatdef *f)
444{
445 long x;
446 if (get_long(v, &x) < 0)
447 return -1;
448 if (x < 0 || x > 255){
449 PyErr_SetString(StructError,
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000450 "ubyte format requires 0 <= number <= 255");
Bob Ippolito232f3c92006-05-23 19:12:41 +0000451 return -1;
452 }
453 *p = (char)x;
454 return 0;
455}
456
457static int
458np_char(char *p, PyObject *v, const formatdef *f)
459{
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000460 if (!PyString_Check(v) || PyString_Size(v) != 1) {
Bob Ippolito232f3c92006-05-23 19:12:41 +0000461 PyErr_SetString(StructError,
462 "char format require string of length 1");
463 return -1;
464 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000465 *p = *PyString_AsString(v);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000466 return 0;
467}
468
469static int
470np_short(char *p, PyObject *v, const formatdef *f)
471{
472 long x;
473 short y;
474 if (get_long(v, &x) < 0)
475 return -1;
476 if (x < SHRT_MIN || x > SHRT_MAX){
477 PyErr_SetString(StructError,
478 "short format requires " STRINGIFY(SHRT_MIN)
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000479 " <= number <= " STRINGIFY(SHRT_MAX));
Bob Ippolito232f3c92006-05-23 19:12:41 +0000480 return -1;
481 }
482 y = (short)x;
483 memcpy(p, (char *)&y, sizeof y);
484 return 0;
485}
486
487static int
488np_ushort(char *p, PyObject *v, const formatdef *f)
489{
490 long x;
491 unsigned short y;
492 if (get_long(v, &x) < 0)
493 return -1;
494 if (x < 0 || x > USHRT_MAX){
495 PyErr_SetString(StructError,
Mark Dickinson24766ba2009-07-07 10:18:22 +0000496 "ushort format requires 0 <= number <= " STRINGIFY(USHRT_MAX));
Bob Ippolito232f3c92006-05-23 19:12:41 +0000497 return -1;
498 }
499 y = (unsigned short)x;
500 memcpy(p, (char *)&y, sizeof y);
501 return 0;
502}
503
504static int
505np_int(char *p, PyObject *v, const formatdef *f)
506{
507 long x;
508 int y;
509 if (get_long(v, &x) < 0)
510 return -1;
Bob Ippolito90bd0a52006-05-27 11:47:12 +0000511#if (SIZEOF_LONG > SIZEOF_INT)
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000512 if ((x < ((long)INT_MIN)) || (x > ((long)INT_MAX)))
Mark Dickinson5fd3af22009-07-07 15:08:28 +0000513 return _range_error(f, 0);
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000514#endif
Bob Ippolito232f3c92006-05-23 19:12:41 +0000515 y = (int)x;
516 memcpy(p, (char *)&y, sizeof y);
517 return 0;
518}
519
520static int
521np_uint(char *p, PyObject *v, const formatdef *f)
522{
523 unsigned long x;
524 unsigned int y;
Mark Dickinson716a9cc2009-09-27 16:39:28 +0000525 if (get_ulong(v, &x) < 0)
Georg Brandl6269fec2009-01-01 12:15:31 +0000526 return -1;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000527 y = (unsigned int)x;
Bob Ippolito90bd0a52006-05-27 11:47:12 +0000528#if (SIZEOF_LONG > SIZEOF_INT)
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000529 if (x > ((unsigned long)UINT_MAX))
Mark Dickinson5fd3af22009-07-07 15:08:28 +0000530 return _range_error(f, 1);
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000531#endif
Bob Ippolito232f3c92006-05-23 19:12:41 +0000532 memcpy(p, (char *)&y, sizeof y);
533 return 0;
534}
535
536static int
537np_long(char *p, PyObject *v, const formatdef *f)
538{
539 long x;
540 if (get_long(v, &x) < 0)
541 return -1;
542 memcpy(p, (char *)&x, sizeof x);
543 return 0;
544}
545
546static int
547np_ulong(char *p, PyObject *v, const formatdef *f)
548{
549 unsigned long x;
Mark Dickinson716a9cc2009-09-27 16:39:28 +0000550 if (get_ulong(v, &x) < 0)
Georg Brandl6269fec2009-01-01 12:15:31 +0000551 return -1;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000552 memcpy(p, (char *)&x, sizeof x);
553 return 0;
554}
555
556#ifdef HAVE_LONG_LONG
557
558static int
559np_longlong(char *p, PyObject *v, const formatdef *f)
560{
561 PY_LONG_LONG x;
562 if (get_longlong(v, &x) < 0)
563 return -1;
564 memcpy(p, (char *)&x, sizeof x);
565 return 0;
566}
567
568static int
569np_ulonglong(char *p, PyObject *v, const formatdef *f)
570{
571 unsigned PY_LONG_LONG x;
572 if (get_ulonglong(v, &x) < 0)
573 return -1;
574 memcpy(p, (char *)&x, sizeof x);
575 return 0;
576}
577#endif
578
Martin v. Löwisaef4c6b2007-01-21 09:33:07 +0000579
580static int
581np_bool(char *p, PyObject *v, const formatdef *f)
582{
583 BOOL_TYPE y;
584 y = PyObject_IsTrue(v);
585 memcpy(p, (char *)&y, sizeof y);
586 return 0;
587}
588
Bob Ippolito232f3c92006-05-23 19:12:41 +0000589static int
590np_float(char *p, PyObject *v, const formatdef *f)
591{
592 float x = (float)PyFloat_AsDouble(v);
593 if (x == -1 && PyErr_Occurred()) {
594 PyErr_SetString(StructError,
595 "required argument is not a float");
596 return -1;
597 }
598 memcpy(p, (char *)&x, sizeof x);
599 return 0;
600}
601
602static int
603np_double(char *p, PyObject *v, const formatdef *f)
604{
605 double x = PyFloat_AsDouble(v);
606 if (x == -1 && PyErr_Occurred()) {
607 PyErr_SetString(StructError,
608 "required argument is not a float");
609 return -1;
610 }
611 memcpy(p, (char *)&x, sizeof(double));
612 return 0;
613}
614
615static int
616np_void_p(char *p, PyObject *v, const formatdef *f)
617{
618 void *x;
619
620 v = get_pylong(v);
621 if (v == NULL)
622 return -1;
623 assert(PyLong_Check(v));
624 x = PyLong_AsVoidPtr(v);
625 Py_DECREF(v);
626 if (x == NULL && PyErr_Occurred())
627 return -1;
628 memcpy(p, (char *)&x, sizeof x);
629 return 0;
630}
631
632static formatdef native_table[] = {
633 {'x', sizeof(char), 0, NULL},
634 {'b', sizeof(char), 0, nu_byte, np_byte},
635 {'B', sizeof(char), 0, nu_ubyte, np_ubyte},
636 {'c', sizeof(char), 0, nu_char, np_char},
637 {'s', sizeof(char), 0, NULL},
638 {'p', sizeof(char), 0, NULL},
639 {'h', sizeof(short), SHORT_ALIGN, nu_short, np_short},
640 {'H', sizeof(short), SHORT_ALIGN, nu_ushort, np_ushort},
641 {'i', sizeof(int), INT_ALIGN, nu_int, np_int},
642 {'I', sizeof(int), INT_ALIGN, nu_uint, np_uint},
643 {'l', sizeof(long), LONG_ALIGN, nu_long, np_long},
644 {'L', sizeof(long), LONG_ALIGN, nu_ulong, np_ulong},
Bob Ippolito232f3c92006-05-23 19:12:41 +0000645#ifdef HAVE_LONG_LONG
646 {'q', sizeof(PY_LONG_LONG), LONG_LONG_ALIGN, nu_longlong, np_longlong},
647 {'Q', sizeof(PY_LONG_LONG), LONG_LONG_ALIGN, nu_ulonglong,np_ulonglong},
648#endif
Thomas Hellerf3c05592008-03-05 15:34:29 +0000649 {'?', sizeof(BOOL_TYPE), BOOL_ALIGN, nu_bool, np_bool},
Bob Ippolitoa99865b2006-05-25 19:56:56 +0000650 {'f', sizeof(float), FLOAT_ALIGN, nu_float, np_float},
651 {'d', sizeof(double), DOUBLE_ALIGN, nu_double, np_double},
652 {'P', sizeof(void *), VOID_P_ALIGN, nu_void_p, np_void_p},
Bob Ippolito232f3c92006-05-23 19:12:41 +0000653 {0}
654};
655
656/* Big-endian routines. *****************************************************/
657
658static PyObject *
659bu_int(const char *p, const formatdef *f)
660{
661 long x = 0;
Bob Ippolitoaa70a172006-05-26 20:25:23 +0000662 Py_ssize_t i = f->size;
Bob Ippolito28b26862006-05-29 15:47:29 +0000663 const unsigned char *bytes = (const unsigned char *)p;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000664 do {
Bob Ippolito28b26862006-05-29 15:47:29 +0000665 x = (x<<8) | *bytes++;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000666 } while (--i > 0);
667 /* Extend the sign bit. */
668 if (SIZEOF_LONG > f->size)
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000669 x |= -(x & (1L << ((8 * f->size) - 1)));
Bob Ippolito232f3c92006-05-23 19:12:41 +0000670 return PyInt_FromLong(x);
671}
672
673static PyObject *
674bu_uint(const char *p, const formatdef *f)
675{
676 unsigned long x = 0;
Bob Ippolitoaa70a172006-05-26 20:25:23 +0000677 Py_ssize_t i = f->size;
Bob Ippolito28b26862006-05-29 15:47:29 +0000678 const unsigned char *bytes = (const unsigned char *)p;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000679 do {
Bob Ippolito28b26862006-05-29 15:47:29 +0000680 x = (x<<8) | *bytes++;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000681 } while (--i > 0);
Bob Ippolito04ab9942006-05-25 19:33:38 +0000682 if (x <= LONG_MAX)
Bob Ippolito232f3c92006-05-23 19:12:41 +0000683 return PyInt_FromLong((long)x);
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000684 return PyLong_FromUnsignedLong(x);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000685}
686
687static PyObject *
688bu_longlong(const char *p, const formatdef *f)
689{
Bob Ippolito90bd0a52006-05-27 11:47:12 +0000690#ifdef HAVE_LONG_LONG
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000691 PY_LONG_LONG x = 0;
Bob Ippolitoaa70a172006-05-26 20:25:23 +0000692 Py_ssize_t i = f->size;
Bob Ippolito28b26862006-05-29 15:47:29 +0000693 const unsigned char *bytes = (const unsigned char *)p;
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000694 do {
Bob Ippolito28b26862006-05-29 15:47:29 +0000695 x = (x<<8) | *bytes++;
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000696 } while (--i > 0);
697 /* Extend the sign bit. */
698 if (SIZEOF_LONG_LONG > f->size)
Kristján Valur Jónsson67387fb2007-04-25 00:17:39 +0000699 x |= -(x & ((PY_LONG_LONG)1 << ((8 * f->size) - 1)));
Bob Ippolito04ab9942006-05-25 19:33:38 +0000700 if (x >= LONG_MIN && x <= LONG_MAX)
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000701 return PyInt_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long));
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000702 return PyLong_FromLongLong(x);
703#else
Bob Ippolito232f3c92006-05-23 19:12:41 +0000704 return _PyLong_FromByteArray((const unsigned char *)p,
705 8,
706 0, /* little-endian */
707 1 /* signed */);
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000708#endif
Bob Ippolito232f3c92006-05-23 19:12:41 +0000709}
710
711static PyObject *
712bu_ulonglong(const char *p, const formatdef *f)
713{
Bob Ippolito90bd0a52006-05-27 11:47:12 +0000714#ifdef HAVE_LONG_LONG
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000715 unsigned PY_LONG_LONG x = 0;
Bob Ippolitoaa70a172006-05-26 20:25:23 +0000716 Py_ssize_t i = f->size;
Bob Ippolito28b26862006-05-29 15:47:29 +0000717 const unsigned char *bytes = (const unsigned char *)p;
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000718 do {
Bob Ippolito28b26862006-05-29 15:47:29 +0000719 x = (x<<8) | *bytes++;
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000720 } while (--i > 0);
Bob Ippolito04ab9942006-05-25 19:33:38 +0000721 if (x <= LONG_MAX)
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000722 return PyInt_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long));
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000723 return PyLong_FromUnsignedLongLong(x);
724#else
Bob Ippolito232f3c92006-05-23 19:12:41 +0000725 return _PyLong_FromByteArray((const unsigned char *)p,
726 8,
727 0, /* little-endian */
728 0 /* signed */);
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000729#endif
Bob Ippolito232f3c92006-05-23 19:12:41 +0000730}
731
732static PyObject *
733bu_float(const char *p, const formatdef *f)
734{
735 return unpack_float(p, 0);
736}
737
738static PyObject *
739bu_double(const char *p, const formatdef *f)
740{
741 return unpack_double(p, 0);
742}
743
Martin v. Löwisaef4c6b2007-01-21 09:33:07 +0000744static PyObject *
745bu_bool(const char *p, const formatdef *f)
746{
747 char x;
748 memcpy((char *)&x, p, sizeof x);
749 return PyBool_FromLong(x != 0);
750}
751
Bob Ippolito232f3c92006-05-23 19:12:41 +0000752static int
753bp_int(char *p, PyObject *v, const formatdef *f)
754{
755 long x;
Bob Ippolitoaa70a172006-05-26 20:25:23 +0000756 Py_ssize_t i;
Mark Dickinson716a9cc2009-09-27 16:39:28 +0000757 if (get_long(v, &x) < 0)
Bob Ippolito232f3c92006-05-23 19:12:41 +0000758 return -1;
759 i = f->size;
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000760 if (i != SIZEOF_LONG) {
761 if ((i == 2) && (x < -32768 || x > 32767))
Mark Dickinson5fd3af22009-07-07 15:08:28 +0000762 return _range_error(f, 0);
Bob Ippolito90bd0a52006-05-27 11:47:12 +0000763#if (SIZEOF_LONG != 4)
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000764 else if ((i == 4) && (x < -2147483648L || x > 2147483647L))
Mark Dickinson5fd3af22009-07-07 15:08:28 +0000765 return _range_error(f, 0);
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000766#endif
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000767 }
Bob Ippolito232f3c92006-05-23 19:12:41 +0000768 do {
769 p[--i] = (char)x;
770 x >>= 8;
771 } while (i > 0);
772 return 0;
773}
774
775static int
776bp_uint(char *p, PyObject *v, const formatdef *f)
777{
778 unsigned long x;
Bob Ippolitoaa70a172006-05-26 20:25:23 +0000779 Py_ssize_t i;
Mark Dickinson716a9cc2009-09-27 16:39:28 +0000780 if (get_ulong(v, &x) < 0)
Bob Ippolito232f3c92006-05-23 19:12:41 +0000781 return -1;
782 i = f->size;
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000783 if (i != SIZEOF_LONG) {
784 unsigned long maxint = 1;
785 maxint <<= (unsigned long)(i * 8);
786 if (x >= maxint)
Mark Dickinson5fd3af22009-07-07 15:08:28 +0000787 return _range_error(f, 1);
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000788 }
Bob Ippolito232f3c92006-05-23 19:12:41 +0000789 do {
790 p[--i] = (char)x;
791 x >>= 8;
792 } while (i > 0);
793 return 0;
794}
795
796static int
797bp_longlong(char *p, PyObject *v, const formatdef *f)
798{
799 int res;
800 v = get_pylong(v);
801 if (v == NULL)
802 return -1;
803 res = _PyLong_AsByteArray((PyLongObject *)v,
804 (unsigned char *)p,
805 8,
806 0, /* little_endian */
807 1 /* signed */);
808 Py_DECREF(v);
809 return res;
810}
811
812static int
813bp_ulonglong(char *p, PyObject *v, const formatdef *f)
814{
815 int res;
816 v = get_pylong(v);
817 if (v == NULL)
818 return -1;
819 res = _PyLong_AsByteArray((PyLongObject *)v,
820 (unsigned char *)p,
821 8,
822 0, /* little_endian */
823 0 /* signed */);
824 Py_DECREF(v);
825 return res;
826}
827
828static int
829bp_float(char *p, PyObject *v, const formatdef *f)
830{
831 double x = PyFloat_AsDouble(v);
832 if (x == -1 && PyErr_Occurred()) {
833 PyErr_SetString(StructError,
834 "required argument is not a float");
835 return -1;
836 }
837 return _PyFloat_Pack4(x, (unsigned char *)p, 0);
838}
839
840static int
841bp_double(char *p, PyObject *v, const formatdef *f)
842{
843 double x = PyFloat_AsDouble(v);
844 if (x == -1 && PyErr_Occurred()) {
845 PyErr_SetString(StructError,
846 "required argument is not a float");
847 return -1;
848 }
849 return _PyFloat_Pack8(x, (unsigned char *)p, 0);
850}
851
Martin v. Löwisaef4c6b2007-01-21 09:33:07 +0000852static int
853bp_bool(char *p, PyObject *v, const formatdef *f)
854{
855 char y;
856 y = PyObject_IsTrue(v);
857 memcpy(p, (char *)&y, sizeof y);
858 return 0;
859}
860
Bob Ippolito232f3c92006-05-23 19:12:41 +0000861static formatdef bigendian_table[] = {
862 {'x', 1, 0, NULL},
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000863 {'b', 1, 0, nu_byte, np_byte},
864 {'B', 1, 0, nu_ubyte, np_ubyte},
Bob Ippolito232f3c92006-05-23 19:12:41 +0000865 {'c', 1, 0, nu_char, np_char},
866 {'s', 1, 0, NULL},
867 {'p', 1, 0, NULL},
868 {'h', 2, 0, bu_int, bp_int},
869 {'H', 2, 0, bu_uint, bp_uint},
870 {'i', 4, 0, bu_int, bp_int},
871 {'I', 4, 0, bu_uint, bp_uint},
872 {'l', 4, 0, bu_int, bp_int},
873 {'L', 4, 0, bu_uint, bp_uint},
874 {'q', 8, 0, bu_longlong, bp_longlong},
875 {'Q', 8, 0, bu_ulonglong, bp_ulonglong},
Thomas Hellerf3c05592008-03-05 15:34:29 +0000876 {'?', 1, 0, bu_bool, bp_bool},
Bob Ippolito232f3c92006-05-23 19:12:41 +0000877 {'f', 4, 0, bu_float, bp_float},
878 {'d', 8, 0, bu_double, bp_double},
879 {0}
880};
881
882/* Little-endian routines. *****************************************************/
883
884static PyObject *
885lu_int(const char *p, const formatdef *f)
886{
887 long x = 0;
Bob Ippolitoaa70a172006-05-26 20:25:23 +0000888 Py_ssize_t i = f->size;
Bob Ippolito28b26862006-05-29 15:47:29 +0000889 const unsigned char *bytes = (const unsigned char *)p;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000890 do {
Bob Ippolito28b26862006-05-29 15:47:29 +0000891 x = (x<<8) | bytes[--i];
Bob Ippolito232f3c92006-05-23 19:12:41 +0000892 } while (i > 0);
893 /* Extend the sign bit. */
894 if (SIZEOF_LONG > f->size)
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000895 x |= -(x & (1L << ((8 * f->size) - 1)));
Bob Ippolito232f3c92006-05-23 19:12:41 +0000896 return PyInt_FromLong(x);
897}
898
899static PyObject *
900lu_uint(const char *p, const formatdef *f)
901{
902 unsigned long x = 0;
Bob Ippolitoaa70a172006-05-26 20:25:23 +0000903 Py_ssize_t i = f->size;
Bob Ippolito28b26862006-05-29 15:47:29 +0000904 const unsigned char *bytes = (const unsigned char *)p;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000905 do {
Bob Ippolito28b26862006-05-29 15:47:29 +0000906 x = (x<<8) | bytes[--i];
Bob Ippolito232f3c92006-05-23 19:12:41 +0000907 } while (i > 0);
Bob Ippolito04ab9942006-05-25 19:33:38 +0000908 if (x <= LONG_MAX)
Bob Ippolito232f3c92006-05-23 19:12:41 +0000909 return PyInt_FromLong((long)x);
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000910 return PyLong_FromUnsignedLong((long)x);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000911}
912
913static PyObject *
914lu_longlong(const char *p, const formatdef *f)
915{
Bob Ippolito90bd0a52006-05-27 11:47:12 +0000916#ifdef HAVE_LONG_LONG
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000917 PY_LONG_LONG x = 0;
Bob Ippolitoaa70a172006-05-26 20:25:23 +0000918 Py_ssize_t i = f->size;
Bob Ippolito28b26862006-05-29 15:47:29 +0000919 const unsigned char *bytes = (const unsigned char *)p;
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000920 do {
Bob Ippolito28b26862006-05-29 15:47:29 +0000921 x = (x<<8) | bytes[--i];
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000922 } while (i > 0);
923 /* Extend the sign bit. */
924 if (SIZEOF_LONG_LONG > f->size)
Kristján Valur Jónsson67387fb2007-04-25 00:17:39 +0000925 x |= -(x & ((PY_LONG_LONG)1 << ((8 * f->size) - 1)));
Bob Ippolito04ab9942006-05-25 19:33:38 +0000926 if (x >= LONG_MIN && x <= LONG_MAX)
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000927 return PyInt_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long));
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000928 return PyLong_FromLongLong(x);
929#else
Bob Ippolito232f3c92006-05-23 19:12:41 +0000930 return _PyLong_FromByteArray((const unsigned char *)p,
931 8,
932 1, /* little-endian */
933 1 /* signed */);
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000934#endif
Bob Ippolito232f3c92006-05-23 19:12:41 +0000935}
936
937static PyObject *
938lu_ulonglong(const char *p, const formatdef *f)
939{
Bob Ippolito90bd0a52006-05-27 11:47:12 +0000940#ifdef HAVE_LONG_LONG
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000941 unsigned PY_LONG_LONG x = 0;
Bob Ippolitoaa70a172006-05-26 20:25:23 +0000942 Py_ssize_t i = f->size;
Bob Ippolito28b26862006-05-29 15:47:29 +0000943 const unsigned char *bytes = (const unsigned char *)p;
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000944 do {
Bob Ippolito28b26862006-05-29 15:47:29 +0000945 x = (x<<8) | bytes[--i];
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000946 } while (i > 0);
Bob Ippolito04ab9942006-05-25 19:33:38 +0000947 if (x <= LONG_MAX)
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000948 return PyInt_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long));
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000949 return PyLong_FromUnsignedLongLong(x);
950#else
Bob Ippolito232f3c92006-05-23 19:12:41 +0000951 return _PyLong_FromByteArray((const unsigned char *)p,
952 8,
953 1, /* little-endian */
954 0 /* signed */);
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000955#endif
Bob Ippolito232f3c92006-05-23 19:12:41 +0000956}
957
958static PyObject *
959lu_float(const char *p, const formatdef *f)
960{
961 return unpack_float(p, 1);
962}
963
964static PyObject *
965lu_double(const char *p, const formatdef *f)
966{
967 return unpack_double(p, 1);
968}
969
970static int
971lp_int(char *p, PyObject *v, const formatdef *f)
972{
973 long x;
Bob Ippolitoaa70a172006-05-26 20:25:23 +0000974 Py_ssize_t i;
Mark Dickinson716a9cc2009-09-27 16:39:28 +0000975 if (get_long(v, &x) < 0)
Bob Ippolito232f3c92006-05-23 19:12:41 +0000976 return -1;
977 i = f->size;
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000978 if (i != SIZEOF_LONG) {
979 if ((i == 2) && (x < -32768 || x > 32767))
Mark Dickinson5fd3af22009-07-07 15:08:28 +0000980 return _range_error(f, 0);
Bob Ippolito90bd0a52006-05-27 11:47:12 +0000981#if (SIZEOF_LONG != 4)
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000982 else if ((i == 4) && (x < -2147483648L || x > 2147483647L))
Mark Dickinson5fd3af22009-07-07 15:08:28 +0000983 return _range_error(f, 0);
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000984#endif
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000985 }
Bob Ippolito232f3c92006-05-23 19:12:41 +0000986 do {
987 *p++ = (char)x;
988 x >>= 8;
989 } while (--i > 0);
990 return 0;
991}
992
993static int
994lp_uint(char *p, PyObject *v, const formatdef *f)
995{
996 unsigned long x;
Bob Ippolitoaa70a172006-05-26 20:25:23 +0000997 Py_ssize_t i;
Mark Dickinson716a9cc2009-09-27 16:39:28 +0000998 if (get_ulong(v, &x) < 0)
Bob Ippolito232f3c92006-05-23 19:12:41 +0000999 return -1;
1000 i = f->size;
Bob Ippolitocd51ca52006-05-27 15:53:49 +00001001 if (i != SIZEOF_LONG) {
1002 unsigned long maxint = 1;
1003 maxint <<= (unsigned long)(i * 8);
1004 if (x >= maxint)
Mark Dickinson5fd3af22009-07-07 15:08:28 +00001005 return _range_error(f, 1);
Bob Ippolitocd51ca52006-05-27 15:53:49 +00001006 }
Bob Ippolito232f3c92006-05-23 19:12:41 +00001007 do {
1008 *p++ = (char)x;
1009 x >>= 8;
1010 } while (--i > 0);
1011 return 0;
1012}
1013
1014static int
1015lp_longlong(char *p, PyObject *v, const formatdef *f)
1016{
1017 int res;
1018 v = get_pylong(v);
1019 if (v == NULL)
1020 return -1;
1021 res = _PyLong_AsByteArray((PyLongObject*)v,
1022 (unsigned char *)p,
1023 8,
1024 1, /* little_endian */
1025 1 /* signed */);
1026 Py_DECREF(v);
1027 return res;
1028}
1029
1030static int
1031lp_ulonglong(char *p, PyObject *v, const formatdef *f)
1032{
1033 int res;
1034 v = get_pylong(v);
1035 if (v == NULL)
1036 return -1;
1037 res = _PyLong_AsByteArray((PyLongObject*)v,
1038 (unsigned char *)p,
1039 8,
1040 1, /* little_endian */
1041 0 /* signed */);
1042 Py_DECREF(v);
1043 return res;
1044}
1045
1046static int
1047lp_float(char *p, PyObject *v, const formatdef *f)
1048{
1049 double x = PyFloat_AsDouble(v);
1050 if (x == -1 && PyErr_Occurred()) {
1051 PyErr_SetString(StructError,
1052 "required argument is not a float");
1053 return -1;
1054 }
1055 return _PyFloat_Pack4(x, (unsigned char *)p, 1);
1056}
1057
1058static int
1059lp_double(char *p, PyObject *v, const formatdef *f)
1060{
1061 double x = PyFloat_AsDouble(v);
1062 if (x == -1 && PyErr_Occurred()) {
1063 PyErr_SetString(StructError,
1064 "required argument is not a float");
1065 return -1;
1066 }
1067 return _PyFloat_Pack8(x, (unsigned char *)p, 1);
1068}
1069
1070static formatdef lilendian_table[] = {
1071 {'x', 1, 0, NULL},
Bob Ippolitoe27337b2006-05-26 13:15:44 +00001072 {'b', 1, 0, nu_byte, np_byte},
1073 {'B', 1, 0, nu_ubyte, np_ubyte},
Bob Ippolito232f3c92006-05-23 19:12:41 +00001074 {'c', 1, 0, nu_char, np_char},
1075 {'s', 1, 0, NULL},
1076 {'p', 1, 0, NULL},
1077 {'h', 2, 0, lu_int, lp_int},
1078 {'H', 2, 0, lu_uint, lp_uint},
1079 {'i', 4, 0, lu_int, lp_int},
1080 {'I', 4, 0, lu_uint, lp_uint},
1081 {'l', 4, 0, lu_int, lp_int},
1082 {'L', 4, 0, lu_uint, lp_uint},
1083 {'q', 8, 0, lu_longlong, lp_longlong},
1084 {'Q', 8, 0, lu_ulonglong, lp_ulonglong},
Thomas Hellerf3c05592008-03-05 15:34:29 +00001085 {'?', 1, 0, bu_bool, bp_bool}, /* Std rep not endian dep,
Martin v. Löwisaef4c6b2007-01-21 09:33:07 +00001086 but potentially different from native rep -- reuse bx_bool funcs. */
Bob Ippolito232f3c92006-05-23 19:12:41 +00001087 {'f', 4, 0, lu_float, lp_float},
1088 {'d', 8, 0, lu_double, lp_double},
1089 {0}
1090};
1091
1092
1093static const formatdef *
1094whichtable(char **pfmt)
1095{
1096 const char *fmt = (*pfmt)++; /* May be backed out of later */
1097 switch (*fmt) {
1098 case '<':
1099 return lilendian_table;
1100 case '>':
1101 case '!': /* Network byte order is big-endian */
1102 return bigendian_table;
1103 case '=': { /* Host byte order -- different from native in aligment! */
1104 int n = 1;
1105 char *p = (char *) &n;
1106 if (*p == 1)
1107 return lilendian_table;
1108 else
1109 return bigendian_table;
1110 }
1111 default:
1112 --*pfmt; /* Back out of pointer increment */
1113 /* Fall through */
1114 case '@':
1115 return native_table;
1116 }
1117}
1118
1119
1120/* Get the table entry for a format code */
1121
1122static const formatdef *
1123getentry(int c, const formatdef *f)
1124{
1125 for (; f->format != '\0'; f++) {
1126 if (f->format == c) {
1127 return f;
1128 }
1129 }
1130 PyErr_SetString(StructError, "bad char in struct format");
1131 return NULL;
1132}
1133
1134
1135/* Align a size according to a format code */
1136
1137static int
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001138align(Py_ssize_t size, char c, const formatdef *e)
Bob Ippolito232f3c92006-05-23 19:12:41 +00001139{
1140 if (e->format == c) {
1141 if (e->alignment) {
1142 size = ((size + e->alignment - 1)
1143 / e->alignment)
1144 * e->alignment;
1145 }
1146 }
1147 return size;
1148}
1149
1150
1151/* calculate the size of a format string */
1152
1153static int
1154prepare_s(PyStructObject *self)
1155{
1156 const formatdef *f;
1157 const formatdef *e;
1158 formatcode *codes;
Tim Petersc2b550e2006-05-31 14:28:07 +00001159
Bob Ippolito232f3c92006-05-23 19:12:41 +00001160 const char *s;
1161 const char *fmt;
1162 char c;
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001163 Py_ssize_t size, len, num, itemsize, x;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001164
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001165 fmt = PyString_AS_STRING(self->s_format);
Bob Ippolito232f3c92006-05-23 19:12:41 +00001166
1167 f = whichtable((char **)&fmt);
Tim Petersc2b550e2006-05-31 14:28:07 +00001168
Bob Ippolito232f3c92006-05-23 19:12:41 +00001169 s = fmt;
1170 size = 0;
1171 len = 0;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001172 while ((c = *s++) != '\0') {
1173 if (isspace(Py_CHARMASK(c)))
1174 continue;
1175 if ('0' <= c && c <= '9') {
1176 num = c - '0';
1177 while ('0' <= (c = *s++) && c <= '9') {
1178 x = num*10 + (c - '0');
1179 if (x/10 != num) {
1180 PyErr_SetString(
1181 StructError,
1182 "overflow in item count");
1183 return -1;
1184 }
1185 num = x;
1186 }
1187 if (c == '\0')
1188 break;
1189 }
1190 else
1191 num = 1;
1192
1193 e = getentry(c, f);
1194 if (e == NULL)
1195 return -1;
Tim Petersc2b550e2006-05-31 14:28:07 +00001196
Bob Ippolito232f3c92006-05-23 19:12:41 +00001197 switch (c) {
1198 case 's': /* fall through */
1199 case 'p': len++; break;
1200 case 'x': break;
1201 default: len += num; break;
1202 }
Bob Ippolito232f3c92006-05-23 19:12:41 +00001203
1204 itemsize = e->size;
1205 size = align(size, c, e);
1206 x = num * itemsize;
1207 size += x;
1208 if (x/itemsize != num || size < 0) {
1209 PyErr_SetString(StructError,
1210 "total struct size too long");
1211 return -1;
1212 }
1213 }
1214
Gregory P. Smith9d534572008-06-11 07:41:16 +00001215 /* check for overflow */
1216 if ((len + 1) > (PY_SSIZE_T_MAX / sizeof(formatcode))) {
1217 PyErr_NoMemory();
1218 return -1;
1219 }
1220
Bob Ippolito232f3c92006-05-23 19:12:41 +00001221 self->s_size = size;
1222 self->s_len = len;
Bob Ippolitoeb621272006-05-24 15:32:06 +00001223 codes = PyMem_MALLOC((len + 1) * sizeof(formatcode));
Bob Ippolito232f3c92006-05-23 19:12:41 +00001224 if (codes == NULL) {
1225 PyErr_NoMemory();
1226 return -1;
1227 }
1228 self->s_codes = codes;
Tim Petersc2b550e2006-05-31 14:28:07 +00001229
Bob Ippolito232f3c92006-05-23 19:12:41 +00001230 s = fmt;
1231 size = 0;
1232 while ((c = *s++) != '\0') {
1233 if (isspace(Py_CHARMASK(c)))
1234 continue;
1235 if ('0' <= c && c <= '9') {
1236 num = c - '0';
1237 while ('0' <= (c = *s++) && c <= '9')
1238 num = num*10 + (c - '0');
1239 if (c == '\0')
1240 break;
1241 }
1242 else
1243 num = 1;
1244
1245 e = getentry(c, f);
Tim Petersc2b550e2006-05-31 14:28:07 +00001246
Bob Ippolito232f3c92006-05-23 19:12:41 +00001247 size = align(size, c, e);
Bob Ippolitoeb621272006-05-24 15:32:06 +00001248 if (c == 's' || c == 'p') {
Bob Ippolito232f3c92006-05-23 19:12:41 +00001249 codes->offset = size;
Bob Ippolitoeb621272006-05-24 15:32:06 +00001250 codes->size = num;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001251 codes->fmtdef = e;
1252 codes++;
Bob Ippolitoeb621272006-05-24 15:32:06 +00001253 size += num;
1254 } else if (c == 'x') {
1255 size += num;
1256 } else {
1257 while (--num >= 0) {
1258 codes->offset = size;
1259 codes->size = e->size;
1260 codes->fmtdef = e;
1261 codes++;
1262 size += e->size;
1263 }
Bob Ippolito232f3c92006-05-23 19:12:41 +00001264 }
Bob Ippolito232f3c92006-05-23 19:12:41 +00001265 }
1266 codes->fmtdef = NULL;
Bob Ippolitoeb621272006-05-24 15:32:06 +00001267 codes->offset = size;
1268 codes->size = 0;
Tim Petersc2b550e2006-05-31 14:28:07 +00001269
Bob Ippolito232f3c92006-05-23 19:12:41 +00001270 return 0;
1271}
1272
1273static PyObject *
1274s_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1275{
1276 PyObject *self;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001277
1278 assert(type != NULL && type->tp_alloc != NULL);
1279
1280 self = type->tp_alloc(type, 0);
1281 if (self != NULL) {
1282 PyStructObject *s = (PyStructObject*)self;
1283 Py_INCREF(Py_None);
1284 s->s_format = Py_None;
1285 s->s_codes = NULL;
1286 s->s_size = -1;
1287 s->s_len = -1;
1288 }
1289 return self;
1290}
1291
1292static int
1293s_init(PyObject *self, PyObject *args, PyObject *kwds)
1294{
1295 PyStructObject *soself = (PyStructObject *)self;
1296 PyObject *o_format = NULL;
1297 int ret = 0;
1298 static char *kwlist[] = {"format", 0};
1299
1300 assert(PyStruct_Check(self));
1301
1302 if (!PyArg_ParseTupleAndKeywords(args, kwds, "S:Struct", kwlist,
1303 &o_format))
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001304 return -1;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001305
1306 Py_INCREF(o_format);
Amaury Forgeot d'Arc588ff932008-02-16 14:34:57 +00001307 Py_CLEAR(soself->s_format);
Bob Ippolito232f3c92006-05-23 19:12:41 +00001308 soself->s_format = o_format;
Tim Petersc2b550e2006-05-31 14:28:07 +00001309
Bob Ippolito232f3c92006-05-23 19:12:41 +00001310 ret = prepare_s(soself);
1311 return ret;
1312}
1313
1314static void
1315s_dealloc(PyStructObject *s)
1316{
Bob Ippolito232f3c92006-05-23 19:12:41 +00001317 if (s->weakreflist != NULL)
1318 PyObject_ClearWeakRefs((PyObject *)s);
1319 if (s->s_codes != NULL) {
1320 PyMem_FREE(s->s_codes);
1321 }
1322 Py_XDECREF(s->s_format);
Christian Heimese93237d2007-12-19 02:37:44 +00001323 Py_TYPE(s)->tp_free((PyObject *)s);
Bob Ippolito232f3c92006-05-23 19:12:41 +00001324}
1325
Bob Ippolitoeb621272006-05-24 15:32:06 +00001326static PyObject *
1327s_unpack_internal(PyStructObject *soself, char *startfrom) {
1328 formatcode *code;
1329 Py_ssize_t i = 0;
1330 PyObject *result = PyTuple_New(soself->s_len);
1331 if (result == NULL)
1332 return NULL;
1333
1334 for (code = soself->s_codes; code->fmtdef != NULL; code++) {
1335 PyObject *v;
1336 const formatdef *e = code->fmtdef;
1337 const char *res = startfrom + code->offset;
1338 if (e->format == 's') {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001339 v = PyString_FromStringAndSize(res, code->size);
Bob Ippolitoeb621272006-05-24 15:32:06 +00001340 } else if (e->format == 'p') {
1341 Py_ssize_t n = *(unsigned char*)res;
1342 if (n >= code->size)
1343 n = code->size - 1;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001344 v = PyString_FromStringAndSize(res + 1, n);
Bob Ippolitoeb621272006-05-24 15:32:06 +00001345 } else {
1346 v = e->unpack(res, e);
Bob Ippolitoeb621272006-05-24 15:32:06 +00001347 }
Neal Norwitz3c5431e2006-06-11 05:45:25 +00001348 if (v == NULL)
1349 goto fail;
1350 PyTuple_SET_ITEM(result, i++, v);
Bob Ippolitoeb621272006-05-24 15:32:06 +00001351 }
1352
1353 return result;
1354fail:
1355 Py_DECREF(result);
1356 return NULL;
Bob Ippolitocd51ca52006-05-27 15:53:49 +00001357}
Bob Ippolitoeb621272006-05-24 15:32:06 +00001358
1359
Bob Ippolito232f3c92006-05-23 19:12:41 +00001360PyDoc_STRVAR(s_unpack__doc__,
Bob Ippolito1fcdc232006-05-27 12:11:36 +00001361"S.unpack(str) -> (v1, v2, ...)\n\
Bob Ippolito232f3c92006-05-23 19:12:41 +00001362\n\
1363Return tuple containing values unpacked according to this Struct's format.\n\
1364Requires len(str) == self.size. See struct.__doc__ for more on format\n\
1365strings.");
1366
1367static PyObject *
1368s_unpack(PyObject *self, PyObject *inputstr)
1369{
Raymond Hettinger7a3d41f2007-04-05 18:00:03 +00001370 char *start;
1371 Py_ssize_t len;
1372 PyObject *args=NULL, *result;
Bob Ippolitoeb621272006-05-24 15:32:06 +00001373 PyStructObject *soself = (PyStructObject *)self;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001374 assert(PyStruct_Check(self));
Tim Petersc2b550e2006-05-31 14:28:07 +00001375 assert(soself->s_codes != NULL);
Raymond Hettinger7a3d41f2007-04-05 18:00:03 +00001376 if (inputstr == NULL)
1377 goto fail;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001378 if (PyString_Check(inputstr) &&
1379 PyString_GET_SIZE(inputstr) == soself->s_size) {
1380 return s_unpack_internal(soself, PyString_AS_STRING(inputstr));
Bob Ippolito232f3c92006-05-23 19:12:41 +00001381 }
Raymond Hettinger7a3d41f2007-04-05 18:00:03 +00001382 args = PyTuple_Pack(1, inputstr);
1383 if (args == NULL)
1384 return NULL;
1385 if (!PyArg_ParseTuple(args, "s#:unpack", &start, &len))
1386 goto fail;
1387 if (soself->s_size != len)
1388 goto fail;
1389 result = s_unpack_internal(soself, start);
1390 Py_DECREF(args);
1391 return result;
1392
1393fail:
1394 Py_XDECREF(args);
1395 PyErr_Format(StructError,
1396 "unpack requires a string argument of length %zd",
1397 soself->s_size);
1398 return NULL;
Bob Ippolitoeb621272006-05-24 15:32:06 +00001399}
1400
1401PyDoc_STRVAR(s_unpack_from__doc__,
Bob Ippolito1fcdc232006-05-27 12:11:36 +00001402"S.unpack_from(buffer[, offset]) -> (v1, v2, ...)\n\
Bob Ippolitoeb621272006-05-24 15:32:06 +00001403\n\
1404Return tuple containing values unpacked according to this Struct's format.\n\
1405Unlike unpack, unpack_from can unpack values from any object supporting\n\
1406the buffer API, not just str. Requires len(buffer[offset:]) >= self.size.\n\
1407See struct.__doc__ for more on format strings.");
1408
1409static PyObject *
1410s_unpack_from(PyObject *self, PyObject *args, PyObject *kwds)
1411{
1412 static char *kwlist[] = {"buffer", "offset", 0};
1413#if (PY_VERSION_HEX < 0x02050000)
1414 static char *fmt = "z#|i:unpack_from";
1415#else
1416 static char *fmt = "z#|n:unpack_from";
1417#endif
1418 Py_ssize_t buffer_len = 0, offset = 0;
1419 char *buffer = NULL;
1420 PyStructObject *soself = (PyStructObject *)self;
1421 assert(PyStruct_Check(self));
1422 assert(soself->s_codes != NULL);
1423
1424 if (!PyArg_ParseTupleAndKeywords(args, kwds, fmt, kwlist,
1425 &buffer, &buffer_len, &offset))
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001426 return NULL;
Bob Ippolitoeb621272006-05-24 15:32:06 +00001427
1428 if (buffer == NULL) {
1429 PyErr_Format(StructError,
1430 "unpack_from requires a buffer argument");
Bob Ippolito232f3c92006-05-23 19:12:41 +00001431 return NULL;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001432 }
Tim Petersc2b550e2006-05-31 14:28:07 +00001433
Bob Ippolitoeb621272006-05-24 15:32:06 +00001434 if (offset < 0)
1435 offset += buffer_len;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001436
Bob Ippolitoeb621272006-05-24 15:32:06 +00001437 if (offset < 0 || (buffer_len - offset) < soself->s_size) {
1438 PyErr_Format(StructError,
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001439 "unpack_from requires a buffer of at least %zd bytes",
Bob Ippolitoeb621272006-05-24 15:32:06 +00001440 soself->s_size);
1441 return NULL;
1442 }
1443 return s_unpack_internal(soself, buffer + offset);
1444}
Bob Ippolito232f3c92006-05-23 19:12:41 +00001445
Bob Ippolito232f3c92006-05-23 19:12:41 +00001446
Martin Blais2856e5f2006-05-26 12:03:27 +00001447/*
1448 * Guts of the pack function.
1449 *
1450 * Takes a struct object, a tuple of arguments, and offset in that tuple of
1451 * argument for where to start processing the arguments for packing, and a
1452 * character buffer for writing the packed string. The caller must insure
1453 * that the buffer may contain the required length for packing the arguments.
1454 * 0 is returned on success, 1 is returned if there is an error.
1455 *
1456 */
1457static int
1458s_pack_internal(PyStructObject *soself, PyObject *args, int offset, char* buf)
Bob Ippolito232f3c92006-05-23 19:12:41 +00001459{
Bob Ippolito232f3c92006-05-23 19:12:41 +00001460 formatcode *code;
Neal Norwitz3c5431e2006-06-11 05:45:25 +00001461 /* XXX(nnorwitz): why does i need to be a local? can we use
1462 the offset parameter or do we need the wider width? */
Bob Ippolito232f3c92006-05-23 19:12:41 +00001463 Py_ssize_t i;
Martin Blais2856e5f2006-05-26 12:03:27 +00001464
1465 memset(buf, '\0', soself->s_size);
1466 i = offset;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001467 for (code = soself->s_codes; code->fmtdef != NULL; code++) {
1468 Py_ssize_t n;
Neal Norwitz3c5431e2006-06-11 05:45:25 +00001469 PyObject *v = PyTuple_GET_ITEM(args, i++);
Bob Ippolito232f3c92006-05-23 19:12:41 +00001470 const formatdef *e = code->fmtdef;
Martin Blais2856e5f2006-05-26 12:03:27 +00001471 char *res = buf + code->offset;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001472 if (e->format == 's') {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001473 if (!PyString_Check(v)) {
Bob Ippolito232f3c92006-05-23 19:12:41 +00001474 PyErr_SetString(StructError,
Mark Dickinson5fd3af22009-07-07 15:08:28 +00001475 "argument for 's' must "
1476 "be a string");
Martin Blais2856e5f2006-05-26 12:03:27 +00001477 return -1;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001478 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001479 n = PyString_GET_SIZE(v);
Bob Ippolitoeb621272006-05-24 15:32:06 +00001480 if (n > code->size)
1481 n = code->size;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001482 if (n > 0)
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001483 memcpy(res, PyString_AS_STRING(v), n);
Bob Ippolito232f3c92006-05-23 19:12:41 +00001484 } else if (e->format == 'p') {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001485 if (!PyString_Check(v)) {
Bob Ippolito232f3c92006-05-23 19:12:41 +00001486 PyErr_SetString(StructError,
Mark Dickinson5fd3af22009-07-07 15:08:28 +00001487 "argument for 'p' must "
1488 "be a string");
Martin Blais2856e5f2006-05-26 12:03:27 +00001489 return -1;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001490 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001491 n = PyString_GET_SIZE(v);
Bob Ippolitoeb621272006-05-24 15:32:06 +00001492 if (n > (code->size - 1))
1493 n = code->size - 1;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001494 if (n > 0)
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001495 memcpy(res + 1, PyString_AS_STRING(v), n);
Bob Ippolito232f3c92006-05-23 19:12:41 +00001496 if (n > 255)
1497 n = 255;
1498 *res = Py_SAFE_DOWNCAST(n, Py_ssize_t, unsigned char);
Mark Dickinson5fd3af22009-07-07 15:08:28 +00001499 } else if (e->pack(res, v, e) < 0) {
1500 if (strchr(integer_codes, e->format) != NULL &&
1501 PyErr_ExceptionMatches(PyExc_OverflowError))
1502 PyErr_Format(StructError,
1503 "integer out of range for "
1504 "'%c' format code",
1505 e->format);
1506 return -1;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001507 }
1508 }
Tim Petersc2b550e2006-05-31 14:28:07 +00001509
Martin Blais2856e5f2006-05-26 12:03:27 +00001510 /* Success */
1511 return 0;
1512}
Bob Ippolito232f3c92006-05-23 19:12:41 +00001513
Martin Blais2856e5f2006-05-26 12:03:27 +00001514
1515PyDoc_STRVAR(s_pack__doc__,
Bob Ippolito1fcdc232006-05-27 12:11:36 +00001516"S.pack(v1, v2, ...) -> string\n\
Martin Blais2856e5f2006-05-26 12:03:27 +00001517\n\
1518Return a string containing values v1, v2, ... packed according to this\n\
1519Struct's format. See struct.__doc__ for more on format strings.");
1520
1521static PyObject *
1522s_pack(PyObject *self, PyObject *args)
1523{
1524 PyStructObject *soself;
1525 PyObject *result;
1526
1527 /* Validate arguments. */
1528 soself = (PyStructObject *)self;
1529 assert(PyStruct_Check(self));
1530 assert(soself->s_codes != NULL);
Martin Blaisaf2ae722006-06-04 13:49:49 +00001531 if (PyTuple_GET_SIZE(args) != soself->s_len)
Martin Blais2856e5f2006-05-26 12:03:27 +00001532 {
1533 PyErr_Format(StructError,
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001534 "pack requires exactly %zd arguments", soself->s_len);
Martin Blais2856e5f2006-05-26 12:03:27 +00001535 return NULL;
1536 }
Tim Petersc2b550e2006-05-31 14:28:07 +00001537
Martin Blais2856e5f2006-05-26 12:03:27 +00001538 /* Allocate a new string */
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001539 result = PyString_FromStringAndSize((char *)NULL, soself->s_size);
Martin Blais2856e5f2006-05-26 12:03:27 +00001540 if (result == NULL)
1541 return NULL;
Tim Petersc2b550e2006-05-31 14:28:07 +00001542
Martin Blais2856e5f2006-05-26 12:03:27 +00001543 /* Call the guts */
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001544 if ( s_pack_internal(soself, args, 0, PyString_AS_STRING(result)) != 0 ) {
Martin Blais2856e5f2006-05-26 12:03:27 +00001545 Py_DECREF(result);
1546 return NULL;
1547 }
1548
1549 return result;
1550}
1551
Martin Blaisaf2ae722006-06-04 13:49:49 +00001552PyDoc_STRVAR(s_pack_into__doc__,
1553"S.pack_into(buffer, offset, v1, v2, ...)\n\
Martin Blais2856e5f2006-05-26 12:03:27 +00001554\n\
Martin Blaisaf2ae722006-06-04 13:49:49 +00001555Pack the values v1, v2, ... according to this Struct's format, write \n\
Bob Ippolito1fcdc232006-05-27 12:11:36 +00001556the packed bytes into the writable buffer buf starting at offset. Note\n\
1557that the offset is not an optional argument. See struct.__doc__ for \n\
Martin Blais2856e5f2006-05-26 12:03:27 +00001558more on format strings.");
1559
1560static PyObject *
Martin Blaisaf2ae722006-06-04 13:49:49 +00001561s_pack_into(PyObject *self, PyObject *args)
Martin Blais2856e5f2006-05-26 12:03:27 +00001562{
1563 PyStructObject *soself;
1564 char *buffer;
1565 Py_ssize_t buffer_len, offset;
1566
1567 /* Validate arguments. +1 is for the first arg as buffer. */
1568 soself = (PyStructObject *)self;
1569 assert(PyStruct_Check(self));
1570 assert(soself->s_codes != NULL);
Martin Blaisaf2ae722006-06-04 13:49:49 +00001571 if (PyTuple_GET_SIZE(args) != (soself->s_len + 2))
Martin Blais2856e5f2006-05-26 12:03:27 +00001572 {
1573 PyErr_Format(StructError,
Martin Blaisaf2ae722006-06-04 13:49:49 +00001574 "pack_into requires exactly %zd arguments",
Martin Blais2856e5f2006-05-26 12:03:27 +00001575 (soself->s_len + 2));
1576 return NULL;
1577 }
1578
1579 /* Extract a writable memory buffer from the first argument */
Tim Petersc2b550e2006-05-31 14:28:07 +00001580 if ( PyObject_AsWriteBuffer(PyTuple_GET_ITEM(args, 0),
1581 (void**)&buffer, &buffer_len) == -1 ) {
Martin Blais2856e5f2006-05-26 12:03:27 +00001582 return NULL;
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001583 }
1584 assert( buffer_len >= 0 );
Martin Blais2856e5f2006-05-26 12:03:27 +00001585
1586 /* Extract the offset from the first argument */
Martin Blaisaf2ae722006-06-04 13:49:49 +00001587 offset = PyInt_AsSsize_t(PyTuple_GET_ITEM(args, 1));
Benjamin Peterson02252482008-09-30 02:11:07 +00001588 if (offset == -1 && PyErr_Occurred())
1589 return NULL;
Martin Blais2856e5f2006-05-26 12:03:27 +00001590
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001591 /* Support negative offsets. */
Martin Blais2856e5f2006-05-26 12:03:27 +00001592 if (offset < 0)
1593 offset += buffer_len;
1594
1595 /* Check boundaries */
1596 if (offset < 0 || (buffer_len - offset) < soself->s_size) {
1597 PyErr_Format(StructError,
Martin Blaisaf2ae722006-06-04 13:49:49 +00001598 "pack_into requires a buffer of at least %zd bytes",
Martin Blais2856e5f2006-05-26 12:03:27 +00001599 soself->s_size);
1600 return NULL;
1601 }
Tim Petersc2b550e2006-05-31 14:28:07 +00001602
Martin Blais2856e5f2006-05-26 12:03:27 +00001603 /* Call the guts */
1604 if ( s_pack_internal(soself, args, 2, buffer + offset) != 0 ) {
1605 return NULL;
1606 }
1607
Georg Brandlc26025c2006-05-28 21:42:54 +00001608 Py_RETURN_NONE;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001609}
1610
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001611static PyObject *
1612s_get_format(PyStructObject *self, void *unused)
1613{
1614 Py_INCREF(self->s_format);
1615 return self->s_format;
1616}
1617
1618static PyObject *
1619s_get_size(PyStructObject *self, void *unused)
1620{
1621 return PyInt_FromSsize_t(self->s_size);
1622}
Bob Ippolito232f3c92006-05-23 19:12:41 +00001623
1624/* List of functions */
1625
1626static struct PyMethodDef s_methods[] = {
Martin Blaisaf2ae722006-06-04 13:49:49 +00001627 {"pack", s_pack, METH_VARARGS, s_pack__doc__},
1628 {"pack_into", s_pack_into, METH_VARARGS, s_pack_into__doc__},
1629 {"unpack", s_unpack, METH_O, s_unpack__doc__},
Neal Norwitza84dcd72007-05-22 07:16:44 +00001630 {"unpack_from", (PyCFunction)s_unpack_from, METH_VARARGS|METH_KEYWORDS,
Tim Peters5ec2e852006-06-04 15:49:07 +00001631 s_unpack_from__doc__},
Bob Ippolito232f3c92006-05-23 19:12:41 +00001632 {NULL, NULL} /* sentinel */
1633};
1634
1635PyDoc_STRVAR(s__doc__, "Compiled struct object");
1636
1637#define OFF(x) offsetof(PyStructObject, x)
1638
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001639static PyGetSetDef s_getsetlist[] = {
Bob Ippolito1fcdc232006-05-27 12:11:36 +00001640 {"format", (getter)s_get_format, (setter)NULL, "struct format string", NULL},
1641 {"size", (getter)s_get_size, (setter)NULL, "struct size in bytes", NULL},
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001642 {NULL} /* sentinel */
Bob Ippolito232f3c92006-05-23 19:12:41 +00001643};
1644
Bob Ippolito232f3c92006-05-23 19:12:41 +00001645static
1646PyTypeObject PyStructType = {
Martin v. Löwis68192102007-07-21 06:55:02 +00001647 PyVarObject_HEAD_INIT(NULL, 0)
Bob Ippolito232f3c92006-05-23 19:12:41 +00001648 "Struct",
1649 sizeof(PyStructObject),
1650 0,
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001651 (destructor)s_dealloc, /* tp_dealloc */
Bob Ippolito232f3c92006-05-23 19:12:41 +00001652 0, /* tp_print */
1653 0, /* tp_getattr */
1654 0, /* tp_setattr */
1655 0, /* tp_compare */
1656 0, /* tp_repr */
1657 0, /* tp_as_number */
1658 0, /* tp_as_sequence */
1659 0, /* tp_as_mapping */
1660 0, /* tp_hash */
1661 0, /* tp_call */
1662 0, /* tp_str */
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001663 PyObject_GenericGetAttr, /* tp_getattro */
1664 PyObject_GenericSetAttr, /* tp_setattro */
Bob Ippolito232f3c92006-05-23 19:12:41 +00001665 0, /* tp_as_buffer */
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001666 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_WEAKREFS,/* tp_flags */
1667 s__doc__, /* tp_doc */
Bob Ippolito232f3c92006-05-23 19:12:41 +00001668 0, /* tp_traverse */
1669 0, /* tp_clear */
1670 0, /* tp_richcompare */
1671 offsetof(PyStructObject, weakreflist), /* tp_weaklistoffset */
1672 0, /* tp_iter */
1673 0, /* tp_iternext */
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001674 s_methods, /* tp_methods */
1675 NULL, /* tp_members */
1676 s_getsetlist, /* tp_getset */
Bob Ippolito232f3c92006-05-23 19:12:41 +00001677 0, /* tp_base */
1678 0, /* tp_dict */
1679 0, /* tp_descr_get */
1680 0, /* tp_descr_set */
1681 0, /* tp_dictoffset */
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001682 s_init, /* tp_init */
1683 PyType_GenericAlloc,/* tp_alloc */
1684 s_new, /* tp_new */
1685 PyObject_Del, /* tp_free */
Bob Ippolito232f3c92006-05-23 19:12:41 +00001686};
1687
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001688
1689/* ---- Standalone functions ---- */
1690
1691#define MAXCACHE 100
Christian Heimes76d19f62008-01-04 02:54:42 +00001692static PyObject *cache = NULL;
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001693
1694static PyObject *
1695cache_struct(PyObject *fmt)
1696{
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001697 PyObject * s_object;
1698
1699 if (cache == NULL) {
1700 cache = PyDict_New();
1701 if (cache == NULL)
1702 return NULL;
1703 }
1704
1705 s_object = PyDict_GetItem(cache, fmt);
1706 if (s_object != NULL) {
1707 Py_INCREF(s_object);
1708 return s_object;
1709 }
1710
1711 s_object = PyObject_CallFunctionObjArgs((PyObject *)(&PyStructType), fmt, NULL);
1712 if (s_object != NULL) {
1713 if (PyDict_Size(cache) >= MAXCACHE)
1714 PyDict_Clear(cache);
1715 /* Attempt to cache the result */
1716 if (PyDict_SetItem(cache, fmt, s_object) == -1)
1717 PyErr_Clear();
1718 }
1719 return s_object;
1720}
1721
Christian Heimes76d19f62008-01-04 02:54:42 +00001722PyDoc_STRVAR(clearcache_doc,
1723"Clear the internal cache.");
1724
1725static PyObject *
1726clearcache(PyObject *self)
1727{
Raymond Hettinger18e08e52008-01-18 00:10:42 +00001728 Py_CLEAR(cache);
Christian Heimes76d19f62008-01-04 02:54:42 +00001729 Py_RETURN_NONE;
1730}
1731
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001732PyDoc_STRVAR(calcsize_doc,
1733"Return size of C struct described by format string fmt.");
1734
1735static PyObject *
1736calcsize(PyObject *self, PyObject *fmt)
1737{
1738 Py_ssize_t n;
1739 PyObject *s_object = cache_struct(fmt);
1740 if (s_object == NULL)
1741 return NULL;
1742 n = ((PyStructObject *)s_object)->s_size;
1743 Py_DECREF(s_object);
1744 return PyInt_FromSsize_t(n);
1745}
1746
1747PyDoc_STRVAR(pack_doc,
1748"Return string containing values v1, v2, ... packed according to fmt.");
1749
1750static PyObject *
1751pack(PyObject *self, PyObject *args)
1752{
1753 PyObject *s_object, *fmt, *newargs, *result;
1754 Py_ssize_t n = PyTuple_GET_SIZE(args);
1755
1756 if (n == 0) {
1757 PyErr_SetString(PyExc_TypeError, "missing format argument");
1758 return NULL;
1759 }
1760 fmt = PyTuple_GET_ITEM(args, 0);
1761 newargs = PyTuple_GetSlice(args, 1, n);
1762 if (newargs == NULL)
1763 return NULL;
1764
1765 s_object = cache_struct(fmt);
1766 if (s_object == NULL) {
1767 Py_DECREF(newargs);
1768 return NULL;
1769 }
1770 result = s_pack(s_object, newargs);
1771 Py_DECREF(newargs);
1772 Py_DECREF(s_object);
1773 return result;
1774}
1775
1776PyDoc_STRVAR(pack_into_doc,
1777"Pack the values v1, v2, ... according to fmt.\n\
1778Write the packed bytes into the writable buffer buf starting at offset.");
1779
1780static PyObject *
1781pack_into(PyObject *self, PyObject *args)
1782{
1783 PyObject *s_object, *fmt, *newargs, *result;
1784 Py_ssize_t n = PyTuple_GET_SIZE(args);
1785
1786 if (n == 0) {
1787 PyErr_SetString(PyExc_TypeError, "missing format argument");
1788 return NULL;
1789 }
1790 fmt = PyTuple_GET_ITEM(args, 0);
1791 newargs = PyTuple_GetSlice(args, 1, n);
1792 if (newargs == NULL)
1793 return NULL;
1794
1795 s_object = cache_struct(fmt);
1796 if (s_object == NULL) {
1797 Py_DECREF(newargs);
1798 return NULL;
1799 }
1800 result = s_pack_into(s_object, newargs);
1801 Py_DECREF(newargs);
1802 Py_DECREF(s_object);
1803 return result;
1804}
1805
1806PyDoc_STRVAR(unpack_doc,
1807"Unpack the string containing packed C structure data, according to fmt.\n\
1808Requires len(string) == calcsize(fmt).");
1809
1810static PyObject *
1811unpack(PyObject *self, PyObject *args)
1812{
1813 PyObject *s_object, *fmt, *inputstr, *result;
1814
1815 if (!PyArg_UnpackTuple(args, "unpack", 2, 2, &fmt, &inputstr))
1816 return NULL;
1817
1818 s_object = cache_struct(fmt);
1819 if (s_object == NULL)
1820 return NULL;
1821 result = s_unpack(s_object, inputstr);
1822 Py_DECREF(s_object);
1823 return result;
1824}
1825
1826PyDoc_STRVAR(unpack_from_doc,
1827"Unpack the buffer, containing packed C structure data, according to\n\
1828fmt, starting at offset. Requires len(buffer[offset:]) >= calcsize(fmt).");
1829
1830static PyObject *
1831unpack_from(PyObject *self, PyObject *args, PyObject *kwds)
1832{
1833 PyObject *s_object, *fmt, *newargs, *result;
1834 Py_ssize_t n = PyTuple_GET_SIZE(args);
1835
1836 if (n == 0) {
1837 PyErr_SetString(PyExc_TypeError, "missing format argument");
1838 return NULL;
1839 }
1840 fmt = PyTuple_GET_ITEM(args, 0);
1841 newargs = PyTuple_GetSlice(args, 1, n);
1842 if (newargs == NULL)
1843 return NULL;
1844
1845 s_object = cache_struct(fmt);
1846 if (s_object == NULL) {
1847 Py_DECREF(newargs);
1848 return NULL;
1849 }
1850 result = s_unpack_from(s_object, newargs, kwds);
1851 Py_DECREF(newargs);
1852 Py_DECREF(s_object);
1853 return result;
1854}
1855
1856static struct PyMethodDef module_functions[] = {
Christian Heimes76d19f62008-01-04 02:54:42 +00001857 {"_clearcache", (PyCFunction)clearcache, METH_NOARGS, clearcache_doc},
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001858 {"calcsize", calcsize, METH_O, calcsize_doc},
1859 {"pack", pack, METH_VARARGS, pack_doc},
1860 {"pack_into", pack_into, METH_VARARGS, pack_into_doc},
1861 {"unpack", unpack, METH_VARARGS, unpack_doc},
1862 {"unpack_from", (PyCFunction)unpack_from,
1863 METH_VARARGS|METH_KEYWORDS, unpack_from_doc},
1864 {NULL, NULL} /* sentinel */
1865};
1866
1867
Bob Ippolito232f3c92006-05-23 19:12:41 +00001868/* Module initialization */
1869
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001870PyDoc_STRVAR(module_doc,
Mark Dickinson3d830822009-10-08 15:54:10 +00001871"Functions to convert between Python values and C structs represented\n\
1872as Python strings. It uses format strings (explained below) as compact\n\
1873descriptions of the lay-out of the C structs and the intended conversion\n\
1874to/from Python values.\n\
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001875\n\
1876The optional first format char indicates byte order, size and alignment:\n\
Mark Dickinson3d830822009-10-08 15:54:10 +00001877 @: native order, size & alignment (default)\n\
1878 =: native order, std. size & alignment\n\
1879 <: little-endian, std. size & alignment\n\
1880 >: big-endian, std. size & alignment\n\
1881 !: same as >\n\
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001882\n\
1883The remaining chars indicate types of args and must match exactly;\n\
1884these can be preceded by a decimal repeat count:\n\
1885 x: pad byte (no data); c:char; b:signed byte; B:unsigned byte;\n\
Mark Dickinson3d830822009-10-08 15:54:10 +00001886 ?: _Bool (requires C99; if not available, char is used instead)\n\
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001887 h:short; H:unsigned short; i:int; I:unsigned int;\n\
1888 l:long; L:unsigned long; f:float; d:double.\n\
1889Special cases (preceding decimal count indicates length):\n\
1890 s:string (array of char); p: pascal string (with count byte).\n\
1891Special case (only available in native format):\n\
1892 P:an integer type that is wide enough to hold a pointer.\n\
1893Special case (not in native mode unless 'long long' in platform C):\n\
1894 q:long long; Q:unsigned long long\n\
1895Whitespace between formats is ignored.\n\
1896\n\
1897The variable struct.error is an exception raised on errors.\n");
1898
Bob Ippolito232f3c92006-05-23 19:12:41 +00001899PyMODINIT_FUNC
1900init_struct(void)
1901{
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001902 PyObject *ver, *m;
1903
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001904 ver = PyString_FromString("0.2");
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001905 if (ver == NULL)
1906 return;
1907
1908 m = Py_InitModule3("_struct", module_functions, module_doc);
Bob Ippolito232f3c92006-05-23 19:12:41 +00001909 if (m == NULL)
1910 return;
1911
Christian Heimese93237d2007-12-19 02:37:44 +00001912 Py_TYPE(&PyStructType) = &PyType_Type;
Bob Ippolito3fc2bb92006-05-25 19:03:19 +00001913 if (PyType_Ready(&PyStructType) < 0)
1914 return;
1915
Mark Dickinson5fd3af22009-07-07 15:08:28 +00001916 /* This speed trick can't be used until overflow masking goes
1917 away, because native endian always raises exceptions
1918 instead of overflow masking. */
Tim Petersc2b550e2006-05-31 14:28:07 +00001919
Bob Ippolitoa99865b2006-05-25 19:56:56 +00001920 /* Check endian and swap in faster functions */
1921 {
1922 int one = 1;
1923 formatdef *native = native_table;
1924 formatdef *other, *ptr;
1925 if ((int)*(unsigned char*)&one)
1926 other = lilendian_table;
1927 else
1928 other = bigendian_table;
Bob Ippolito964e02a2006-05-25 21:09:45 +00001929 /* Scan through the native table, find a matching
1930 entry in the endian table and swap in the
1931 native implementations whenever possible
1932 (64-bit platforms may not have "standard" sizes) */
Bob Ippolitoa99865b2006-05-25 19:56:56 +00001933 while (native->format != '\0' && other->format != '\0') {
1934 ptr = other;
1935 while (ptr->format != '\0') {
1936 if (ptr->format == native->format) {
Bob Ippolito964e02a2006-05-25 21:09:45 +00001937 /* Match faster when formats are
1938 listed in the same order */
Bob Ippolitoa99865b2006-05-25 19:56:56 +00001939 if (ptr == other)
1940 other++;
Tim Petersc2b550e2006-05-31 14:28:07 +00001941 /* Only use the trick if the
Bob Ippolito964e02a2006-05-25 21:09:45 +00001942 size matches */
1943 if (ptr->size != native->size)
1944 break;
1945 /* Skip float and double, could be
1946 "unknown" float format */
1947 if (ptr->format == 'd' || ptr->format == 'f')
1948 break;
1949 ptr->pack = native->pack;
1950 ptr->unpack = native->unpack;
Bob Ippolitoa99865b2006-05-25 19:56:56 +00001951 break;
1952 }
1953 ptr++;
1954 }
1955 native++;
1956 }
1957 }
Tim Petersc2b550e2006-05-31 14:28:07 +00001958
Bob Ippolito232f3c92006-05-23 19:12:41 +00001959 /* Add some symbolic constants to the module */
1960 if (StructError == NULL) {
1961 StructError = PyErr_NewException("struct.error", NULL, NULL);
1962 if (StructError == NULL)
1963 return;
1964 }
Bob Ippolito04ab9942006-05-25 19:33:38 +00001965
Bob Ippolito232f3c92006-05-23 19:12:41 +00001966 Py_INCREF(StructError);
1967 PyModule_AddObject(m, "error", StructError);
Bob Ippolito04ab9942006-05-25 19:33:38 +00001968
Bob Ippolito232f3c92006-05-23 19:12:41 +00001969 Py_INCREF((PyObject*)&PyStructType);
1970 PyModule_AddObject(m, "Struct", (PyObject*)&PyStructType);
Tim Petersc2b550e2006-05-31 14:28:07 +00001971
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001972 PyModule_AddObject(m, "__version__", ver);
1973
Bob Ippolito2fd39772006-05-29 22:55:48 +00001974 PyModule_AddIntConstant(m, "_PY_STRUCT_RANGE_CHECKING", 1);
Bob Ippolitoe6c9f982006-08-04 23:59:21 +00001975#ifdef PY_STRUCT_FLOAT_COERCE
1976 PyModule_AddIntConstant(m, "_PY_STRUCT_FLOAT_COERCE", 1);
1977#endif
1978
Bob Ippolito232f3c92006-05-23 19:12:41 +00001979}