blob: 6a89d8c403ffc26f24bea278dfc6852527343739 [file] [log] [blame]
Benjamin Peterson4ae19462008-07-31 15:03:40 +00001/* struct module -- pack values into and (out of) bytes objects */
Thomas Wouters477c8d52006-05-27 19:21:47 +00002
3/* New version supporting byte order, alignment and size options,
4 character strings, and unsigned numbers */
5
6#define PY_SSIZE_T_CLEAN
7
8#include "Python.h"
9#include "structseq.h"
10#include "structmember.h"
11#include <ctype.h>
12
13static PyTypeObject PyStructType;
14
Thomas Wouters477c8d52006-05-27 19:21:47 +000015/* The translation function for each format character is table driven */
16typedef struct _formatdef {
17 char format;
18 Py_ssize_t size;
19 Py_ssize_t alignment;
20 PyObject* (*unpack)(const char *,
21 const struct _formatdef *);
22 int (*pack)(char *, PyObject *,
23 const struct _formatdef *);
24} formatdef;
25
26typedef struct _formatcode {
27 const struct _formatdef *fmtdef;
28 Py_ssize_t offset;
29 Py_ssize_t size;
30} formatcode;
31
32/* Struct object interface */
33
34typedef struct {
35 PyObject_HEAD
36 Py_ssize_t s_size;
37 Py_ssize_t s_len;
38 formatcode *s_codes;
39 PyObject *s_format;
40 PyObject *weakreflist; /* List of weak references */
41} PyStructObject;
42
43
44#define PyStruct_Check(op) PyObject_TypeCheck(op, &PyStructType)
Christian Heimes90aa7642007-12-19 02:45:37 +000045#define PyStruct_CheckExact(op) (Py_TYPE(op) == &PyStructType)
Thomas Wouters477c8d52006-05-27 19:21:47 +000046
47
48/* Exception */
49
50static PyObject *StructError;
51
52
53/* Define various structs to figure out the alignments of types */
54
55
56typedef struct { char c; short x; } st_short;
57typedef struct { char c; int x; } st_int;
58typedef struct { char c; long x; } st_long;
59typedef struct { char c; float x; } st_float;
60typedef struct { char c; double x; } st_double;
61typedef struct { char c; void *x; } st_void_p;
62
63#define SHORT_ALIGN (sizeof(st_short) - sizeof(short))
64#define INT_ALIGN (sizeof(st_int) - sizeof(int))
65#define LONG_ALIGN (sizeof(st_long) - sizeof(long))
66#define FLOAT_ALIGN (sizeof(st_float) - sizeof(float))
67#define DOUBLE_ALIGN (sizeof(st_double) - sizeof(double))
68#define VOID_P_ALIGN (sizeof(st_void_p) - sizeof(void *))
69
70/* We can't support q and Q in native mode unless the compiler does;
71 in std mode, they're 8 bytes on all platforms. */
72#ifdef HAVE_LONG_LONG
73typedef struct { char c; PY_LONG_LONG x; } s_long_long;
74#define LONG_LONG_ALIGN (sizeof(s_long_long) - sizeof(PY_LONG_LONG))
75#endif
76
Thomas Woutersb2137042007-02-01 18:02:27 +000077#ifdef HAVE_C99_BOOL
78#define BOOL_TYPE _Bool
79typedef struct { char c; _Bool x; } s_bool;
80#define BOOL_ALIGN (sizeof(s_bool) - sizeof(BOOL_TYPE))
81#else
82#define BOOL_TYPE char
83#define BOOL_ALIGN 0
84#endif
85
Thomas Wouters477c8d52006-05-27 19:21:47 +000086#define STRINGIFY(x) #x
87
88#ifdef __powerc
89#pragma options align=reset
90#endif
91
Mark Dickinsonea835e72009-04-19 20:40:33 +000092/* Helper to get a PyLongObject. Caller should decref. */
Thomas Wouters477c8d52006-05-27 19:21:47 +000093
94static PyObject *
95get_pylong(PyObject *v)
96{
Thomas Wouters477c8d52006-05-27 19:21:47 +000097 assert(v != NULL);
Mark Dickinsonea835e72009-04-19 20:40:33 +000098 if (!PyLong_Check(v)) {
99 PyErr_SetString(StructError,
100 "required argument is not an integer");
101 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000102 }
Mark Dickinsonea835e72009-04-19 20:40:33 +0000103
104 Py_INCREF(v);
105 return v;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000106}
107
Mark Dickinsonea835e72009-04-19 20:40:33 +0000108/* Helper routine to get a C long and raise the appropriate error if it isn't
109 one */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000110
111static int
112get_long(PyObject *v, long *p)
113{
Mark Dickinsonea835e72009-04-19 20:40:33 +0000114 long x;
115
116 if (!PyLong_Check(v)) {
117 PyErr_SetString(StructError,
118 "required argument is not an integer");
119 return -1;
120 }
121 x = PyLong_AsLong(v);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000122 if (x == -1 && PyErr_Occurred()) {
Mark Dickinsonea835e72009-04-19 20:40:33 +0000123 if (PyErr_ExceptionMatches(PyExc_OverflowError))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000124 PyErr_SetString(StructError,
Mark Dickinsonea835e72009-04-19 20:40:33 +0000125 "argument out of range");
Thomas Wouters477c8d52006-05-27 19:21:47 +0000126 return -1;
127 }
128 *p = x;
129 return 0;
130}
131
132
133/* Same, but handling unsigned long */
134
Benjamin Peterson0289b152009-06-28 17:22:03 +0000135#ifndef PY_STRUCT_OVERFLOW_MASKING
Thomas Wouters477c8d52006-05-27 19:21:47 +0000136static int
137get_ulong(PyObject *v, unsigned long *p)
138{
Mark Dickinsonea835e72009-04-19 20:40:33 +0000139 unsigned long x;
140
141 if (!PyLong_Check(v)) {
Thomas Wouters477c8d52006-05-27 19:21:47 +0000142 PyErr_SetString(StructError,
Mark Dickinsonea835e72009-04-19 20:40:33 +0000143 "required argument is not an integer");
Thomas Wouters477c8d52006-05-27 19:21:47 +0000144 return -1;
145 }
Mark Dickinsonea835e72009-04-19 20:40:33 +0000146 x = PyLong_AsUnsignedLong(v);
147 if (x == (unsigned long)-1 && PyErr_Occurred()) {
148 if (PyErr_ExceptionMatches(PyExc_OverflowError))
149 PyErr_SetString(StructError,
150 "argument out of range");
151 return -1;
152 }
153 *p = x;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000154 return 0;
155}
Benjamin Peterson0289b152009-06-28 17:22:03 +0000156#endif /* PY_STRUCT_OVERFLOW_MASKING */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000157
158#ifdef HAVE_LONG_LONG
159
160/* Same, but handling native long long. */
161
162static int
163get_longlong(PyObject *v, PY_LONG_LONG *p)
164{
165 PY_LONG_LONG x;
Mark Dickinsonea835e72009-04-19 20:40:33 +0000166 if (!PyLong_Check(v)) {
167 PyErr_SetString(StructError,
168 "required argument is not an integer");
Thomas Wouters477c8d52006-05-27 19:21:47 +0000169 return -1;
Mark Dickinsonea835e72009-04-19 20:40:33 +0000170 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000171 x = PyLong_AsLongLong(v);
Mark Dickinsonea835e72009-04-19 20:40:33 +0000172 if (x == -1 && PyErr_Occurred()) {
173 if (PyErr_ExceptionMatches(PyExc_OverflowError))
174 PyErr_SetString(StructError,
175 "argument out of range");
Thomas Wouters477c8d52006-05-27 19:21:47 +0000176 return -1;
Mark Dickinsonea835e72009-04-19 20:40:33 +0000177 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000178 *p = x;
179 return 0;
180}
181
182/* Same, but handling native unsigned long long. */
183
184static int
185get_ulonglong(PyObject *v, unsigned PY_LONG_LONG *p)
186{
187 unsigned PY_LONG_LONG x;
Mark Dickinsonea835e72009-04-19 20:40:33 +0000188 if (!PyLong_Check(v)) {
189 PyErr_SetString(StructError,
190 "required argument is not an integer");
Thomas Wouters477c8d52006-05-27 19:21:47 +0000191 return -1;
Mark Dickinsonea835e72009-04-19 20:40:33 +0000192 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000193 x = PyLong_AsUnsignedLongLong(v);
Mark Dickinsonea835e72009-04-19 20:40:33 +0000194 if (x == -1 && PyErr_Occurred()) {
195 if (PyErr_ExceptionMatches(PyExc_OverflowError))
196 PyErr_SetString(StructError,
197 "argument out of range");
Thomas Wouters477c8d52006-05-27 19:21:47 +0000198 return -1;
Mark Dickinsonea835e72009-04-19 20:40:33 +0000199 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000200 *p = x;
201 return 0;
202}
203
204#endif
205
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000206
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000207#define RANGE_ERROR(x, f, flag, mask) return _range_error(f, flag)
208
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000209
Thomas Wouters477c8d52006-05-27 19:21:47 +0000210/* Floating point helpers */
211
212static PyObject *
213unpack_float(const char *p, /* start of 4-byte string */
214 int le) /* true for little-endian, false for big-endian */
215{
216 double x;
217
218 x = _PyFloat_Unpack4((unsigned char *)p, le);
219 if (x == -1.0 && PyErr_Occurred())
220 return NULL;
221 return PyFloat_FromDouble(x);
222}
223
224static PyObject *
225unpack_double(const char *p, /* start of 8-byte string */
226 int le) /* true for little-endian, false for big-endian */
227{
228 double x;
229
230 x = _PyFloat_Unpack8((unsigned char *)p, le);
231 if (x == -1.0 && PyErr_Occurred())
232 return NULL;
233 return PyFloat_FromDouble(x);
234}
235
236/* Helper to format the range error exceptions */
237static int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000238_range_error(const formatdef *f, int is_unsigned)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000239{
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000240 /* ulargest is the largest unsigned value with f->size bytes.
241 * Note that the simpler:
242 * ((size_t)1 << (f->size * 8)) - 1
243 * doesn't work when f->size == sizeof(size_t) because C doesn't
244 * define what happens when a left shift count is >= the number of
245 * bits in the integer being shifted; e.g., on some boxes it doesn't
246 * shift at all when they're equal.
247 */
248 const size_t ulargest = (size_t)-1 >> ((SIZEOF_SIZE_T - f->size)*8);
249 assert(f->size >= 1 && f->size <= SIZEOF_SIZE_T);
250 if (is_unsigned)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000251 PyErr_Format(StructError,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000252 "'%c' format requires 0 <= number <= %zu",
253 f->format,
254 ulargest);
255 else {
256 const Py_ssize_t largest = (Py_ssize_t)(ulargest >> 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000257 PyErr_Format(StructError,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000258 "'%c' format requires %zd <= number <= %zd",
259 f->format,
260 ~ largest,
Thomas Wouters477c8d52006-05-27 19:21:47 +0000261 largest);
262 }
Mark Dickinsonae681df2009-03-21 10:26:31 +0000263
Thomas Wouters477c8d52006-05-27 19:21:47 +0000264 return -1;
265}
266
267
268
269/* A large number of small routines follow, with names of the form
270
271 [bln][up]_TYPE
272
273 [bln] distiguishes among big-endian, little-endian and native.
274 [pu] distiguishes between pack (to struct) and unpack (from struct).
275 TYPE is one of char, byte, ubyte, etc.
276*/
277
278/* Native mode routines. ****************************************************/
279/* NOTE:
280 In all n[up]_<type> routines handling types larger than 1 byte, there is
281 *no* guarantee that the p pointer is properly aligned for each type,
282 therefore memcpy is called. An intermediate variable is used to
283 compensate for big-endian architectures.
284 Normally both the intermediate variable and the memcpy call will be
285 skipped by C optimisation in little-endian architectures (gcc >= 2.91
286 does this). */
287
288static PyObject *
289nu_char(const char *p, const formatdef *f)
290{
Christian Heimes72b710a2008-05-26 13:28:38 +0000291 return PyBytes_FromStringAndSize(p, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000292}
293
294static PyObject *
295nu_byte(const char *p, const formatdef *f)
296{
Christian Heimes217cfd12007-12-02 14:31:20 +0000297 return PyLong_FromLong((long) *(signed char *)p);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000298}
299
300static PyObject *
301nu_ubyte(const char *p, const formatdef *f)
302{
Christian Heimes217cfd12007-12-02 14:31:20 +0000303 return PyLong_FromLong((long) *(unsigned char *)p);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000304}
305
306static PyObject *
307nu_short(const char *p, const formatdef *f)
308{
309 short x;
310 memcpy((char *)&x, p, sizeof x);
Christian Heimes217cfd12007-12-02 14:31:20 +0000311 return PyLong_FromLong((long)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000312}
313
314static PyObject *
315nu_ushort(const char *p, const formatdef *f)
316{
317 unsigned short x;
318 memcpy((char *)&x, p, sizeof x);
Christian Heimes217cfd12007-12-02 14:31:20 +0000319 return PyLong_FromLong((long)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000320}
321
322static PyObject *
323nu_int(const char *p, const formatdef *f)
324{
325 int x;
326 memcpy((char *)&x, p, sizeof x);
Christian Heimes217cfd12007-12-02 14:31:20 +0000327 return PyLong_FromLong((long)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000328}
329
330static PyObject *
331nu_uint(const char *p, const formatdef *f)
332{
333 unsigned int x;
334 memcpy((char *)&x, p, sizeof x);
335#if (SIZEOF_LONG > SIZEOF_INT)
Christian Heimes217cfd12007-12-02 14:31:20 +0000336 return PyLong_FromLong((long)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000337#else
338 if (x <= ((unsigned int)LONG_MAX))
Christian Heimes217cfd12007-12-02 14:31:20 +0000339 return PyLong_FromLong((long)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000340 return PyLong_FromUnsignedLong((unsigned long)x);
341#endif
342}
343
344static PyObject *
345nu_long(const char *p, const formatdef *f)
346{
347 long x;
348 memcpy((char *)&x, p, sizeof x);
Christian Heimes217cfd12007-12-02 14:31:20 +0000349 return PyLong_FromLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000350}
351
352static PyObject *
353nu_ulong(const char *p, const formatdef *f)
354{
355 unsigned long x;
356 memcpy((char *)&x, p, sizeof x);
357 if (x <= LONG_MAX)
Christian Heimes217cfd12007-12-02 14:31:20 +0000358 return PyLong_FromLong((long)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000359 return PyLong_FromUnsignedLong(x);
360}
361
362/* Native mode doesn't support q or Q unless the platform C supports
363 long long (or, on Windows, __int64). */
364
365#ifdef HAVE_LONG_LONG
366
367static PyObject *
368nu_longlong(const char *p, const formatdef *f)
369{
370 PY_LONG_LONG x;
371 memcpy((char *)&x, p, sizeof x);
372 if (x >= LONG_MIN && x <= LONG_MAX)
Christian Heimes217cfd12007-12-02 14:31:20 +0000373 return PyLong_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long));
Thomas Wouters477c8d52006-05-27 19:21:47 +0000374 return PyLong_FromLongLong(x);
375}
376
377static PyObject *
378nu_ulonglong(const char *p, const formatdef *f)
379{
380 unsigned PY_LONG_LONG x;
381 memcpy((char *)&x, p, sizeof x);
382 if (x <= LONG_MAX)
Christian Heimes217cfd12007-12-02 14:31:20 +0000383 return PyLong_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long));
Thomas Wouters477c8d52006-05-27 19:21:47 +0000384 return PyLong_FromUnsignedLongLong(x);
385}
386
387#endif
388
389static PyObject *
Thomas Woutersb2137042007-02-01 18:02:27 +0000390nu_bool(const char *p, const formatdef *f)
391{
392 BOOL_TYPE x;
393 memcpy((char *)&x, p, sizeof x);
394 return PyBool_FromLong(x != 0);
395}
396
397
398static PyObject *
Thomas Wouters477c8d52006-05-27 19:21:47 +0000399nu_float(const char *p, const formatdef *f)
400{
401 float x;
402 memcpy((char *)&x, p, sizeof x);
403 return PyFloat_FromDouble((double)x);
404}
405
406static PyObject *
407nu_double(const char *p, const formatdef *f)
408{
409 double x;
410 memcpy((char *)&x, p, sizeof x);
411 return PyFloat_FromDouble(x);
412}
413
414static PyObject *
415nu_void_p(const char *p, const formatdef *f)
416{
417 void *x;
418 memcpy((char *)&x, p, sizeof x);
419 return PyLong_FromVoidPtr(x);
420}
421
422static int
423np_byte(char *p, PyObject *v, const formatdef *f)
424{
425 long x;
426 if (get_long(v, &x) < 0)
427 return -1;
428 if (x < -128 || x > 127){
429 PyErr_SetString(StructError,
430 "byte format requires -128 <= number <= 127");
431 return -1;
432 }
433 *p = (char)x;
434 return 0;
435}
436
437static int
438np_ubyte(char *p, PyObject *v, const formatdef *f)
439{
440 long x;
441 if (get_long(v, &x) < 0)
442 return -1;
443 if (x < 0 || x > 255){
444 PyErr_SetString(StructError,
445 "ubyte format requires 0 <= number <= 255");
446 return -1;
447 }
448 *p = (char)x;
449 return 0;
450}
451
452static int
453np_char(char *p, PyObject *v, const formatdef *f)
454{
Guido van Rossume625fd52007-05-27 09:19:04 +0000455 if (PyUnicode_Check(v)) {
456 v = _PyUnicode_AsDefaultEncodedString(v, NULL);
457 if (v == NULL)
458 return -1;
459 }
Christian Heimes72b710a2008-05-26 13:28:38 +0000460 if (!PyBytes_Check(v) || PyBytes_Size(v) != 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +0000461 PyErr_SetString(StructError,
Benjamin Peterson4ae19462008-07-31 15:03:40 +0000462 "char format requires bytes or string of length 1");
Thomas Wouters477c8d52006-05-27 19:21:47 +0000463 return -1;
464 }
Christian Heimes72b710a2008-05-26 13:28:38 +0000465 *p = *PyBytes_AsString(v);
Thomas Wouters477c8d52006-05-27 19:21:47 +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)
479 " <= number <= " STRINGIFY(SHRT_MAX));
480 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 Dickinsond99620d2009-07-07 10:21:03 +0000496 "ushort format requires 0 <= number <= " STRINGIFY(USHRT_MAX));
Thomas Wouters477c8d52006-05-27 19:21:47 +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;
511#if (SIZEOF_LONG > SIZEOF_INT)
512 if ((x < ((long)INT_MIN)) || (x > ((long)INT_MAX)))
Georg Brandlb1441c72009-01-03 22:33:39 +0000513 RANGE_ERROR(x, f, 0, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000514#endif
515 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 Dickinsonae681df2009-03-21 10:26:31 +0000525 if (get_ulong(v, &x) < 0)
Georg Brandlb1441c72009-01-03 22:33:39 +0000526 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000527 y = (unsigned int)x;
528#if (SIZEOF_LONG > SIZEOF_INT)
529 if (x > ((unsigned long)UINT_MAX))
Georg Brandlb1441c72009-01-03 22:33:39 +0000530 RANGE_ERROR(y, f, 1, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000531#endif
532 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 Dickinsonae681df2009-03-21 10:26:31 +0000550 if (get_ulong(v, &x) < 0)
Georg Brandlb1441c72009-01-03 22:33:39 +0000551 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +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
Thomas Woutersb2137042007-02-01 18:02:27 +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
Thomas Wouters477c8d52006-05-27 19:21:47 +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},
645#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
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000649 {'?', sizeof(BOOL_TYPE), BOOL_ALIGN, nu_bool, np_bool},
Thomas Wouters477c8d52006-05-27 19:21:47 +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},
653 {0}
654};
655
656/* Big-endian routines. *****************************************************/
657
658static PyObject *
659bu_int(const char *p, const formatdef *f)
660{
661 long x = 0;
662 Py_ssize_t i = f->size;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000663 const unsigned char *bytes = (const unsigned char *)p;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000664 do {
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000665 x = (x<<8) | *bytes++;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000666 } while (--i > 0);
667 /* Extend the sign bit. */
668 if (SIZEOF_LONG > f->size)
669 x |= -(x & (1L << ((8 * f->size) - 1)));
Christian Heimes217cfd12007-12-02 14:31:20 +0000670 return PyLong_FromLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000671}
672
673static PyObject *
674bu_uint(const char *p, const formatdef *f)
675{
676 unsigned long x = 0;
677 Py_ssize_t i = f->size;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000678 const unsigned char *bytes = (const unsigned char *)p;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000679 do {
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000680 x = (x<<8) | *bytes++;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000681 } while (--i > 0);
682 if (x <= LONG_MAX)
Christian Heimes217cfd12007-12-02 14:31:20 +0000683 return PyLong_FromLong((long)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000684 return PyLong_FromUnsignedLong(x);
685}
686
687static PyObject *
688bu_longlong(const char *p, const formatdef *f)
689{
690#ifdef HAVE_LONG_LONG
691 PY_LONG_LONG x = 0;
692 Py_ssize_t i = f->size;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000693 const unsigned char *bytes = (const unsigned char *)p;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000694 do {
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000695 x = (x<<8) | *bytes++;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000696 } while (--i > 0);
697 /* Extend the sign bit. */
698 if (SIZEOF_LONG_LONG > f->size)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000699 x |= -(x & ((PY_LONG_LONG)1 << ((8 * f->size) - 1)));
Thomas Wouters477c8d52006-05-27 19:21:47 +0000700 if (x >= LONG_MIN && x <= LONG_MAX)
Christian Heimes217cfd12007-12-02 14:31:20 +0000701 return PyLong_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long));
Thomas Wouters477c8d52006-05-27 19:21:47 +0000702 return PyLong_FromLongLong(x);
703#else
704 return _PyLong_FromByteArray((const unsigned char *)p,
705 8,
706 0, /* little-endian */
707 1 /* signed */);
708#endif
709}
710
711static PyObject *
712bu_ulonglong(const char *p, const formatdef *f)
713{
714#ifdef HAVE_LONG_LONG
715 unsigned PY_LONG_LONG x = 0;
716 Py_ssize_t i = f->size;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000717 const unsigned char *bytes = (const unsigned char *)p;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000718 do {
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000719 x = (x<<8) | *bytes++;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000720 } while (--i > 0);
721 if (x <= LONG_MAX)
Christian Heimes217cfd12007-12-02 14:31:20 +0000722 return PyLong_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long));
Thomas Wouters477c8d52006-05-27 19:21:47 +0000723 return PyLong_FromUnsignedLongLong(x);
724#else
725 return _PyLong_FromByteArray((const unsigned char *)p,
726 8,
727 0, /* little-endian */
728 0 /* signed */);
729#endif
730}
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
Thomas Woutersb2137042007-02-01 18:02:27 +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
Thomas Wouters477c8d52006-05-27 19:21:47 +0000752static int
753bp_int(char *p, PyObject *v, const formatdef *f)
754{
755 long x;
756 Py_ssize_t i;
Mark Dickinsonae681df2009-03-21 10:26:31 +0000757 if (get_long(v, &x) < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000758 return -1;
759 i = f->size;
760 if (i != SIZEOF_LONG) {
761 if ((i == 2) && (x < -32768 || x > 32767))
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000762 RANGE_ERROR(x, f, 0, 0xffffL);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000763#if (SIZEOF_LONG != 4)
764 else if ((i == 4) && (x < -2147483648L || x > 2147483647L))
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000765 RANGE_ERROR(x, f, 0, 0xffffffffL);
766#endif
Thomas Wouters477c8d52006-05-27 19:21:47 +0000767 }
768 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;
779 Py_ssize_t i;
Mark Dickinsonae681df2009-03-21 10:26:31 +0000780 if (get_ulong(v, &x) < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000781 return -1;
782 i = f->size;
783 if (i != SIZEOF_LONG) {
784 unsigned long maxint = 1;
785 maxint <<= (unsigned long)(i * 8);
786 if (x >= maxint)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000787 RANGE_ERROR(x, f, 1, maxint - 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000788 }
789 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
Thomas Woutersb2137042007-02-01 18:02:27 +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
Thomas Wouters477c8d52006-05-27 19:21:47 +0000861static formatdef bigendian_table[] = {
862 {'x', 1, 0, NULL},
863 {'b', 1, 0, nu_byte, np_byte},
864 {'B', 1, 0, nu_ubyte, np_ubyte},
865 {'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},
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000876 {'?', 1, 0, bu_bool, bp_bool},
Thomas Wouters477c8d52006-05-27 19:21:47 +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;
888 Py_ssize_t i = f->size;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000889 const unsigned char *bytes = (const unsigned char *)p;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000890 do {
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000891 x = (x<<8) | bytes[--i];
Thomas Wouters477c8d52006-05-27 19:21:47 +0000892 } while (i > 0);
893 /* Extend the sign bit. */
894 if (SIZEOF_LONG > f->size)
895 x |= -(x & (1L << ((8 * f->size) - 1)));
Christian Heimes217cfd12007-12-02 14:31:20 +0000896 return PyLong_FromLong(x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000897}
898
899static PyObject *
900lu_uint(const char *p, const formatdef *f)
901{
902 unsigned long x = 0;
903 Py_ssize_t i = f->size;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000904 const unsigned char *bytes = (const unsigned char *)p;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000905 do {
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000906 x = (x<<8) | bytes[--i];
Thomas Wouters477c8d52006-05-27 19:21:47 +0000907 } while (i > 0);
908 if (x <= LONG_MAX)
Christian Heimes217cfd12007-12-02 14:31:20 +0000909 return PyLong_FromLong((long)x);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000910 return PyLong_FromUnsignedLong((long)x);
911}
912
913static PyObject *
914lu_longlong(const char *p, const formatdef *f)
915{
916#ifdef HAVE_LONG_LONG
917 PY_LONG_LONG x = 0;
918 Py_ssize_t i = f->size;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000919 const unsigned char *bytes = (const unsigned char *)p;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000920 do {
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000921 x = (x<<8) | bytes[--i];
Thomas Wouters477c8d52006-05-27 19:21:47 +0000922 } while (i > 0);
923 /* Extend the sign bit. */
924 if (SIZEOF_LONG_LONG > f->size)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000925 x |= -(x & ((PY_LONG_LONG)1 << ((8 * f->size) - 1)));
Thomas Wouters477c8d52006-05-27 19:21:47 +0000926 if (x >= LONG_MIN && x <= LONG_MAX)
Christian Heimes217cfd12007-12-02 14:31:20 +0000927 return PyLong_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long));
Thomas Wouters477c8d52006-05-27 19:21:47 +0000928 return PyLong_FromLongLong(x);
929#else
930 return _PyLong_FromByteArray((const unsigned char *)p,
931 8,
932 1, /* little-endian */
933 1 /* signed */);
934#endif
935}
936
937static PyObject *
938lu_ulonglong(const char *p, const formatdef *f)
939{
940#ifdef HAVE_LONG_LONG
941 unsigned PY_LONG_LONG x = 0;
942 Py_ssize_t i = f->size;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000943 const unsigned char *bytes = (const unsigned char *)p;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000944 do {
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000945 x = (x<<8) | bytes[--i];
Thomas Wouters477c8d52006-05-27 19:21:47 +0000946 } while (i > 0);
947 if (x <= LONG_MAX)
Christian Heimes217cfd12007-12-02 14:31:20 +0000948 return PyLong_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long));
Thomas Wouters477c8d52006-05-27 19:21:47 +0000949 return PyLong_FromUnsignedLongLong(x);
950#else
951 return _PyLong_FromByteArray((const unsigned char *)p,
952 8,
953 1, /* little-endian */
954 0 /* signed */);
955#endif
956}
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;
974 Py_ssize_t i;
Mark Dickinsonae681df2009-03-21 10:26:31 +0000975 if (get_long(v, &x) < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000976 return -1;
977 i = f->size;
978 if (i != SIZEOF_LONG) {
979 if ((i == 2) && (x < -32768 || x > 32767))
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000980 RANGE_ERROR(x, f, 0, 0xffffL);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000981#if (SIZEOF_LONG != 4)
982 else if ((i == 4) && (x < -2147483648L || x > 2147483647L))
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000983 RANGE_ERROR(x, f, 0, 0xffffffffL);
984#endif
Thomas Wouters477c8d52006-05-27 19:21:47 +0000985 }
986 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;
997 Py_ssize_t i;
Mark Dickinsonae681df2009-03-21 10:26:31 +0000998 if (get_ulong(v, &x) < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000999 return -1;
1000 i = f->size;
1001 if (i != SIZEOF_LONG) {
1002 unsigned long maxint = 1;
1003 maxint <<= (unsigned long)(i * 8);
1004 if (x >= maxint)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001005 RANGE_ERROR(x, f, 1, maxint - 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001006 }
1007 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},
1072 {'b', 1, 0, nu_byte, np_byte},
1073 {'B', 1, 0, nu_ubyte, np_ubyte},
1074 {'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},
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001085 {'?', 1, 0, bu_bool, bp_bool}, /* Std rep not endian dep,
Thomas Woutersb2137042007-02-01 18:02:27 +00001086 but potentially different from native rep -- reuse bx_bool funcs. */
Thomas Wouters477c8d52006-05-27 19:21:47 +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
1138align(Py_ssize_t size, char c, const formatdef *e)
1139{
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;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001159
Thomas Wouters477c8d52006-05-27 19:21:47 +00001160 const char *s;
1161 const char *fmt;
1162 char c;
1163 Py_ssize_t size, len, num, itemsize, x;
1164
Christian Heimes72b710a2008-05-26 13:28:38 +00001165 fmt = PyBytes_AS_STRING(self->s_format);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001166
1167 f = whichtable((char **)&fmt);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001168
Thomas Wouters477c8d52006-05-27 19:21:47 +00001169 s = fmt;
1170 size = 0;
1171 len = 0;
1172 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;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001196
Thomas Wouters477c8d52006-05-27 19:21:47 +00001197 switch (c) {
1198 case 's': /* fall through */
1199 case 'p': len++; break;
1200 case 'x': break;
1201 default: len += num; break;
1202 }
1203
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
Amaury Forgeot d'Arc35c86582008-06-17 21:11:29 +00001215 /* check for overflow */
1216 if ((len + 1) > (PY_SSIZE_T_MAX / sizeof(formatcode))) {
1217 PyErr_NoMemory();
1218 return -1;
1219 }
1220
Thomas Wouters477c8d52006-05-27 19:21:47 +00001221 self->s_size = size;
1222 self->s_len = len;
1223 codes = PyMem_MALLOC((len + 1) * sizeof(formatcode));
1224 if (codes == NULL) {
1225 PyErr_NoMemory();
1226 return -1;
1227 }
1228 self->s_codes = codes;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001229
Thomas Wouters477c8d52006-05-27 19:21:47 +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);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001246
Thomas Wouters477c8d52006-05-27 19:21:47 +00001247 size = align(size, c, e);
1248 if (c == 's' || c == 'p') {
1249 codes->offset = size;
1250 codes->size = num;
1251 codes->fmtdef = e;
1252 codes++;
1253 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 }
1264 }
1265 }
1266 codes->fmtdef = NULL;
1267 codes->offset = size;
1268 codes->size = 0;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001269
Thomas Wouters477c8d52006-05-27 19:21:47 +00001270 return 0;
1271}
1272
1273static PyObject *
1274s_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1275{
1276 PyObject *self;
1277
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
Christian Heimesa34706f2008-01-04 03:06:10 +00001302 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:Struct", kwlist,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001303 &o_format))
1304 return -1;
1305
Christian Heimesa34706f2008-01-04 03:06:10 +00001306 if (PyUnicode_Check(o_format)) {
1307 o_format = PyUnicode_AsASCIIString(o_format);
1308 if (o_format == NULL)
1309 return -1;
1310 }
1311 /* XXX support buffer interface, too */
1312 else {
1313 Py_INCREF(o_format);
1314 }
1315
Christian Heimes72b710a2008-05-26 13:28:38 +00001316 if (!PyBytes_Check(o_format)) {
Christian Heimesa34706f2008-01-04 03:06:10 +00001317 Py_DECREF(o_format);
1318 PyErr_Format(PyExc_TypeError,
1319 "Struct() argument 1 must be bytes, not %.200s",
1320 Py_TYPE(o_format)->tp_name);
1321 return -1;
1322 }
1323
Christian Heimes18c66892008-02-17 13:31:39 +00001324 Py_CLEAR(soself->s_format);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001325 soself->s_format = o_format;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001326
Thomas Wouters477c8d52006-05-27 19:21:47 +00001327 ret = prepare_s(soself);
1328 return ret;
1329}
1330
1331static void
1332s_dealloc(PyStructObject *s)
1333{
1334 if (s->weakreflist != NULL)
1335 PyObject_ClearWeakRefs((PyObject *)s);
1336 if (s->s_codes != NULL) {
1337 PyMem_FREE(s->s_codes);
1338 }
1339 Py_XDECREF(s->s_format);
Christian Heimes90aa7642007-12-19 02:45:37 +00001340 Py_TYPE(s)->tp_free((PyObject *)s);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001341}
1342
1343static PyObject *
1344s_unpack_internal(PyStructObject *soself, char *startfrom) {
1345 formatcode *code;
1346 Py_ssize_t i = 0;
1347 PyObject *result = PyTuple_New(soself->s_len);
1348 if (result == NULL)
1349 return NULL;
1350
1351 for (code = soself->s_codes; code->fmtdef != NULL; code++) {
1352 PyObject *v;
1353 const formatdef *e = code->fmtdef;
1354 const char *res = startfrom + code->offset;
1355 if (e->format == 's') {
Christian Heimes72b710a2008-05-26 13:28:38 +00001356 v = PyBytes_FromStringAndSize(res, code->size);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001357 } else if (e->format == 'p') {
1358 Py_ssize_t n = *(unsigned char*)res;
1359 if (n >= code->size)
1360 n = code->size - 1;
Christian Heimes72b710a2008-05-26 13:28:38 +00001361 v = PyBytes_FromStringAndSize(res + 1, n);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001362 } else {
1363 v = e->unpack(res, e);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001364 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001365 if (v == NULL)
1366 goto fail;
1367 PyTuple_SET_ITEM(result, i++, v);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001368 }
1369
1370 return result;
1371fail:
1372 Py_DECREF(result);
1373 return NULL;
1374}
1375
1376
1377PyDoc_STRVAR(s_unpack__doc__,
Guido van Rossum913dd0b2007-04-13 03:33:53 +00001378"S.unpack(buffer) -> (v1, v2, ...)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00001379\n\
1380Return tuple containing values unpacked according to this Struct's format.\n\
Guido van Rossum913dd0b2007-04-13 03:33:53 +00001381Requires len(buffer) == self.size. See struct.__doc__ for more on format\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00001382strings.");
1383
1384static PyObject *
Guido van Rossum98297ee2007-11-06 21:34:58 +00001385s_unpack(PyObject *self, PyObject *input)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001386{
Guido van Rossum98297ee2007-11-06 21:34:58 +00001387 Py_buffer vbuf;
1388 PyObject *result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001389 PyStructObject *soself = (PyStructObject *)self;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001390
Thomas Wouters477c8d52006-05-27 19:21:47 +00001391 assert(PyStruct_Check(self));
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001392 assert(soself->s_codes != NULL);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001393 if (PyObject_GetBuffer(input, &vbuf, PyBUF_SIMPLE) < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001394 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001395 if (vbuf.len != soself->s_size) {
1396 PyErr_Format(StructError,
1397 "unpack requires a bytes argument of length %zd",
1398 soself->s_size);
Martin v. Löwis423be952008-08-13 15:53:07 +00001399 PyBuffer_Release(&vbuf);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001400 return NULL;
1401 }
1402 result = s_unpack_internal(soself, vbuf.buf);
Martin v. Löwis423be952008-08-13 15:53:07 +00001403 PyBuffer_Release(&vbuf);
Guido van Rossumd8faa362007-04-27 19:54:29 +00001404 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001405}
1406
1407PyDoc_STRVAR(s_unpack_from__doc__,
1408"S.unpack_from(buffer[, offset]) -> (v1, v2, ...)\n\
1409\n\
1410Return tuple containing values unpacked according to this Struct's format.\n\
1411Unlike unpack, unpack_from can unpack values from any object supporting\n\
1412the buffer API, not just str. Requires len(buffer[offset:]) >= self.size.\n\
1413See struct.__doc__ for more on format strings.");
1414
1415static PyObject *
1416s_unpack_from(PyObject *self, PyObject *args, PyObject *kwds)
1417{
1418 static char *kwlist[] = {"buffer", "offset", 0};
Guido van Rossum98297ee2007-11-06 21:34:58 +00001419
1420 PyObject *input;
1421 Py_ssize_t offset = 0;
1422 Py_buffer vbuf;
1423 PyObject *result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001424 PyStructObject *soself = (PyStructObject *)self;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001425
Thomas Wouters477c8d52006-05-27 19:21:47 +00001426 assert(PyStruct_Check(self));
1427 assert(soself->s_codes != NULL);
1428
Guido van Rossum98297ee2007-11-06 21:34:58 +00001429 if (!PyArg_ParseTupleAndKeywords(args, kwds,
1430 "O|n:unpack_from", kwlist,
1431 &input, &offset))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001432 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001433 if (PyObject_GetBuffer(input, &vbuf, PyBUF_SIMPLE) < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001434 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001435 if (offset < 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00001436 offset += vbuf.len;
1437 if (offset < 0 || vbuf.len - offset < soself->s_size) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001438 PyErr_Format(StructError,
1439 "unpack_from requires a buffer of at least %zd bytes",
1440 soself->s_size);
Martin v. Löwis423be952008-08-13 15:53:07 +00001441 PyBuffer_Release(&vbuf);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001442 return NULL;
1443 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00001444 result = s_unpack_internal(soself, (char*)vbuf.buf + offset);
Martin v. Löwis423be952008-08-13 15:53:07 +00001445 PyBuffer_Release(&vbuf);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001446 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001447}
1448
1449
1450/*
1451 * Guts of the pack function.
1452 *
1453 * Takes a struct object, a tuple of arguments, and offset in that tuple of
1454 * argument for where to start processing the arguments for packing, and a
1455 * character buffer for writing the packed string. The caller must insure
1456 * that the buffer may contain the required length for packing the arguments.
1457 * 0 is returned on success, 1 is returned if there is an error.
1458 *
1459 */
1460static int
1461s_pack_internal(PyStructObject *soself, PyObject *args, int offset, char* buf)
1462{
1463 formatcode *code;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001464 /* XXX(nnorwitz): why does i need to be a local? can we use
1465 the offset parameter or do we need the wider width? */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001466 Py_ssize_t i;
1467
1468 memset(buf, '\0', soself->s_size);
1469 i = offset;
1470 for (code = soself->s_codes; code->fmtdef != NULL; code++) {
1471 Py_ssize_t n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001472 PyObject *v = PyTuple_GET_ITEM(args, i++);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001473 const formatdef *e = code->fmtdef;
1474 char *res = buf + code->offset;
1475 if (e->format == 's') {
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001476 int isstring;
1477 void *p;
1478 if (PyUnicode_Check(v)) {
1479 v = _PyUnicode_AsDefaultEncodedString(v, NULL);
1480 if (v == NULL)
1481 return -1;
1482 }
Christian Heimes72b710a2008-05-26 13:28:38 +00001483 isstring = PyBytes_Check(v);
Christian Heimes9c4756e2008-05-26 13:22:05 +00001484 if (!isstring && !PyByteArray_Check(v)) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001485 PyErr_SetString(StructError,
Benjamin Peterson4ae19462008-07-31 15:03:40 +00001486 "argument for 's' must be a bytes or string");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001487 return -1;
1488 }
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001489 if (isstring) {
Christian Heimes72b710a2008-05-26 13:28:38 +00001490 n = PyBytes_GET_SIZE(v);
1491 p = PyBytes_AS_STRING(v);
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001492 }
1493 else {
Christian Heimes9c4756e2008-05-26 13:22:05 +00001494 n = PyByteArray_GET_SIZE(v);
1495 p = PyByteArray_AS_STRING(v);
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001496 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001497 if (n > code->size)
1498 n = code->size;
1499 if (n > 0)
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001500 memcpy(res, p, n);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001501 } else if (e->format == 'p') {
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001502 int isstring;
1503 void *p;
1504 if (PyUnicode_Check(v)) {
1505 v = _PyUnicode_AsDefaultEncodedString(v, NULL);
1506 if (v == NULL)
1507 return -1;
1508 }
Christian Heimes72b710a2008-05-26 13:28:38 +00001509 isstring = PyBytes_Check(v);
Christian Heimes9c4756e2008-05-26 13:22:05 +00001510 if (!isstring && !PyByteArray_Check(v)) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001511 PyErr_SetString(StructError,
Benjamin Peterson4ae19462008-07-31 15:03:40 +00001512 "argument for 'p' must be a bytes or string");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001513 return -1;
1514 }
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001515 if (isstring) {
Christian Heimes72b710a2008-05-26 13:28:38 +00001516 n = PyBytes_GET_SIZE(v);
1517 p = PyBytes_AS_STRING(v);
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001518 }
1519 else {
Christian Heimes9c4756e2008-05-26 13:22:05 +00001520 n = PyByteArray_GET_SIZE(v);
1521 p = PyByteArray_AS_STRING(v);
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001522 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001523 if (n > (code->size - 1))
1524 n = code->size - 1;
1525 if (n > 0)
Guido van Rossumd6ca5462007-05-22 01:29:33 +00001526 memcpy(res + 1, p, n);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001527 if (n > 255)
1528 n = 255;
1529 *res = Py_SAFE_DOWNCAST(n, Py_ssize_t, unsigned char);
1530 } else {
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001531 if (e->pack(res, v, e) < 0) {
1532 if (PyLong_Check(v) && PyErr_ExceptionMatches(PyExc_OverflowError))
1533 PyErr_SetString(StructError,
1534 "long too large to convert to int");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001535 return -1;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001536 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001537 }
1538 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001539
Thomas Wouters477c8d52006-05-27 19:21:47 +00001540 /* Success */
1541 return 0;
1542}
1543
1544
1545PyDoc_STRVAR(s_pack__doc__,
Benjamin Peterson4ae19462008-07-31 15:03:40 +00001546"S.pack(v1, v2, ...) -> bytes\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00001547\n\
Benjamin Peterson4ae19462008-07-31 15:03:40 +00001548Return a bytes containing values v1, v2, ... packed according to this\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00001549Struct's format. See struct.__doc__ for more on format strings.");
1550
1551static PyObject *
1552s_pack(PyObject *self, PyObject *args)
1553{
1554 PyStructObject *soself;
1555 PyObject *result;
1556
1557 /* Validate arguments. */
1558 soself = (PyStructObject *)self;
1559 assert(PyStruct_Check(self));
1560 assert(soself->s_codes != NULL);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001561 if (PyTuple_GET_SIZE(args) != soself->s_len)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001562 {
1563 PyErr_Format(StructError,
1564 "pack requires exactly %zd arguments", soself->s_len);
1565 return NULL;
1566 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001567
Thomas Wouters477c8d52006-05-27 19:21:47 +00001568 /* Allocate a new string */
Christian Heimes72b710a2008-05-26 13:28:38 +00001569 result = PyBytes_FromStringAndSize((char *)NULL, soself->s_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001570 if (result == NULL)
1571 return NULL;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001572
Thomas Wouters477c8d52006-05-27 19:21:47 +00001573 /* Call the guts */
Christian Heimes72b710a2008-05-26 13:28:38 +00001574 if ( s_pack_internal(soself, args, 0, PyBytes_AS_STRING(result)) != 0 ) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001575 Py_DECREF(result);
1576 return NULL;
1577 }
1578
1579 return result;
1580}
1581
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001582PyDoc_STRVAR(s_pack_into__doc__,
1583"S.pack_into(buffer, offset, v1, v2, ...)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00001584\n\
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001585Pack the values v1, v2, ... according to this Struct's format, write \n\
Thomas Wouters477c8d52006-05-27 19:21:47 +00001586the packed bytes into the writable buffer buf starting at offset. Note\n\
1587that the offset is not an optional argument. See struct.__doc__ for \n\
1588more on format strings.");
1589
1590static PyObject *
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001591s_pack_into(PyObject *self, PyObject *args)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001592{
1593 PyStructObject *soself;
1594 char *buffer;
1595 Py_ssize_t buffer_len, offset;
1596
1597 /* Validate arguments. +1 is for the first arg as buffer. */
1598 soself = (PyStructObject *)self;
1599 assert(PyStruct_Check(self));
1600 assert(soself->s_codes != NULL);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001601 if (PyTuple_GET_SIZE(args) != (soself->s_len + 2))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001602 {
1603 PyErr_Format(StructError,
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001604 "pack_into requires exactly %zd arguments",
Thomas Wouters477c8d52006-05-27 19:21:47 +00001605 (soself->s_len + 2));
1606 return NULL;
1607 }
1608
1609 /* Extract a writable memory buffer from the first argument */
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001610 if ( PyObject_AsWriteBuffer(PyTuple_GET_ITEM(args, 0),
1611 (void**)&buffer, &buffer_len) == -1 ) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001612 return NULL;
1613 }
1614 assert( buffer_len >= 0 );
1615
1616 /* Extract the offset from the first argument */
Georg Brandl75c3d6f2009-02-13 11:01:07 +00001617 offset = PyNumber_AsSsize_t(PyTuple_GET_ITEM(args, 1), PyExc_IndexError);
Benjamin Petersona8a93042008-09-30 02:18:09 +00001618 if (offset == -1 && PyErr_Occurred())
1619 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001620
1621 /* Support negative offsets. */
1622 if (offset < 0)
1623 offset += buffer_len;
1624
1625 /* Check boundaries */
1626 if (offset < 0 || (buffer_len - offset) < soself->s_size) {
1627 PyErr_Format(StructError,
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001628 "pack_into requires a buffer of at least %zd bytes",
Thomas Wouters477c8d52006-05-27 19:21:47 +00001629 soself->s_size);
1630 return NULL;
1631 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001632
Thomas Wouters477c8d52006-05-27 19:21:47 +00001633 /* Call the guts */
1634 if ( s_pack_internal(soself, args, 2, buffer + offset) != 0 ) {
1635 return NULL;
1636 }
1637
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001638 Py_RETURN_NONE;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001639}
1640
1641static PyObject *
1642s_get_format(PyStructObject *self, void *unused)
1643{
1644 Py_INCREF(self->s_format);
1645 return self->s_format;
1646}
1647
1648static PyObject *
1649s_get_size(PyStructObject *self, void *unused)
1650{
Christian Heimes217cfd12007-12-02 14:31:20 +00001651 return PyLong_FromSsize_t(self->s_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001652}
1653
1654/* List of functions */
1655
1656static struct PyMethodDef s_methods[] = {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001657 {"pack", s_pack, METH_VARARGS, s_pack__doc__},
1658 {"pack_into", s_pack_into, METH_VARARGS, s_pack_into__doc__},
1659 {"unpack", s_unpack, METH_O, s_unpack__doc__},
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001660 {"unpack_from", (PyCFunction)s_unpack_from, METH_VARARGS|METH_KEYWORDS,
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001661 s_unpack_from__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +00001662 {NULL, NULL} /* sentinel */
1663};
1664
1665PyDoc_STRVAR(s__doc__, "Compiled struct object");
1666
1667#define OFF(x) offsetof(PyStructObject, x)
1668
1669static PyGetSetDef s_getsetlist[] = {
1670 {"format", (getter)s_get_format, (setter)NULL, "struct format string", NULL},
1671 {"size", (getter)s_get_size, (setter)NULL, "struct size in bytes", NULL},
1672 {NULL} /* sentinel */
1673};
1674
1675static
1676PyTypeObject PyStructType = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001677 PyVarObject_HEAD_INIT(NULL, 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001678 "Struct",
1679 sizeof(PyStructObject),
1680 0,
1681 (destructor)s_dealloc, /* tp_dealloc */
1682 0, /* tp_print */
1683 0, /* tp_getattr */
1684 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00001685 0, /* tp_reserved */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001686 0, /* tp_repr */
1687 0, /* tp_as_number */
1688 0, /* tp_as_sequence */
1689 0, /* tp_as_mapping */
1690 0, /* tp_hash */
1691 0, /* tp_call */
1692 0, /* tp_str */
1693 PyObject_GenericGetAttr, /* tp_getattro */
1694 PyObject_GenericSetAttr, /* tp_setattro */
1695 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00001696 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001697 s__doc__, /* tp_doc */
1698 0, /* tp_traverse */
1699 0, /* tp_clear */
1700 0, /* tp_richcompare */
1701 offsetof(PyStructObject, weakreflist), /* tp_weaklistoffset */
1702 0, /* tp_iter */
1703 0, /* tp_iternext */
1704 s_methods, /* tp_methods */
1705 NULL, /* tp_members */
1706 s_getsetlist, /* tp_getset */
1707 0, /* tp_base */
1708 0, /* tp_dict */
1709 0, /* tp_descr_get */
1710 0, /* tp_descr_set */
1711 0, /* tp_dictoffset */
1712 s_init, /* tp_init */
1713 PyType_GenericAlloc,/* tp_alloc */
1714 s_new, /* tp_new */
1715 PyObject_Del, /* tp_free */
1716};
1717
Christian Heimesa34706f2008-01-04 03:06:10 +00001718
1719/* ---- Standalone functions ---- */
1720
1721#define MAXCACHE 100
1722static PyObject *cache = NULL;
1723
1724static PyObject *
1725cache_struct(PyObject *fmt)
1726{
1727 PyObject * s_object;
1728
1729 if (cache == NULL) {
1730 cache = PyDict_New();
1731 if (cache == NULL)
1732 return NULL;
1733 }
1734
1735 s_object = PyDict_GetItem(cache, fmt);
1736 if (s_object != NULL) {
1737 Py_INCREF(s_object);
1738 return s_object;
1739 }
1740
1741 s_object = PyObject_CallFunctionObjArgs((PyObject *)(&PyStructType), fmt, NULL);
1742 if (s_object != NULL) {
1743 if (PyDict_Size(cache) >= MAXCACHE)
1744 PyDict_Clear(cache);
1745 /* Attempt to cache the result */
1746 if (PyDict_SetItem(cache, fmt, s_object) == -1)
1747 PyErr_Clear();
1748 }
1749 return s_object;
1750}
1751
1752PyDoc_STRVAR(clearcache_doc,
1753"Clear the internal cache.");
1754
1755static PyObject *
1756clearcache(PyObject *self)
1757{
Christian Heimes679db4a2008-01-18 09:56:22 +00001758 Py_CLEAR(cache);
Christian Heimesa34706f2008-01-04 03:06:10 +00001759 Py_RETURN_NONE;
1760}
1761
1762PyDoc_STRVAR(calcsize_doc,
1763"Return size of C struct described by format string fmt.");
1764
1765static PyObject *
1766calcsize(PyObject *self, PyObject *fmt)
1767{
1768 Py_ssize_t n;
1769 PyObject *s_object = cache_struct(fmt);
1770 if (s_object == NULL)
1771 return NULL;
1772 n = ((PyStructObject *)s_object)->s_size;
1773 Py_DECREF(s_object);
1774 return PyLong_FromSsize_t(n);
1775}
1776
1777PyDoc_STRVAR(pack_doc,
Benjamin Peterson4ae19462008-07-31 15:03:40 +00001778"Return bytes containing values v1, v2, ... packed according to fmt.");
Christian Heimesa34706f2008-01-04 03:06:10 +00001779
1780static PyObject *
1781pack(PyObject *self, PyObject *args)
1782{
1783 PyObject *s_object, *fmt, *newargs, *result;
1784 Py_ssize_t n = PyTuple_GET_SIZE(args);
1785
1786 if (n == 0) {
1787 PyErr_SetString(PyExc_TypeError, "missing format argument");
1788 return NULL;
1789 }
1790 fmt = PyTuple_GET_ITEM(args, 0);
1791 newargs = PyTuple_GetSlice(args, 1, n);
1792 if (newargs == NULL)
1793 return NULL;
1794
1795 s_object = cache_struct(fmt);
1796 if (s_object == NULL) {
1797 Py_DECREF(newargs);
1798 return NULL;
1799 }
1800 result = s_pack(s_object, newargs);
1801 Py_DECREF(newargs);
1802 Py_DECREF(s_object);
1803 return result;
1804}
1805
1806PyDoc_STRVAR(pack_into_doc,
1807"Pack the values v1, v2, ... according to fmt.\n\
1808Write the packed bytes into the writable buffer buf starting at offset.");
1809
1810static PyObject *
1811pack_into(PyObject *self, PyObject *args)
1812{
1813 PyObject *s_object, *fmt, *newargs, *result;
1814 Py_ssize_t n = PyTuple_GET_SIZE(args);
1815
1816 if (n == 0) {
1817 PyErr_SetString(PyExc_TypeError, "missing format argument");
1818 return NULL;
1819 }
1820 fmt = PyTuple_GET_ITEM(args, 0);
1821 newargs = PyTuple_GetSlice(args, 1, n);
1822 if (newargs == NULL)
1823 return NULL;
1824
1825 s_object = cache_struct(fmt);
1826 if (s_object == NULL) {
1827 Py_DECREF(newargs);
1828 return NULL;
1829 }
1830 result = s_pack_into(s_object, newargs);
1831 Py_DECREF(newargs);
1832 Py_DECREF(s_object);
1833 return result;
1834}
1835
1836PyDoc_STRVAR(unpack_doc,
Benjamin Peterson4ae19462008-07-31 15:03:40 +00001837"Unpack the bytes containing packed C structure data, according to fmt.\n\
1838Requires len(bytes) == calcsize(fmt).");
Christian Heimesa34706f2008-01-04 03:06:10 +00001839
1840static PyObject *
1841unpack(PyObject *self, PyObject *args)
1842{
1843 PyObject *s_object, *fmt, *inputstr, *result;
1844
1845 if (!PyArg_UnpackTuple(args, "unpack", 2, 2, &fmt, &inputstr))
1846 return NULL;
1847
1848 s_object = cache_struct(fmt);
1849 if (s_object == NULL)
1850 return NULL;
1851 result = s_unpack(s_object, inputstr);
1852 Py_DECREF(s_object);
1853 return result;
1854}
1855
1856PyDoc_STRVAR(unpack_from_doc,
1857"Unpack the buffer, containing packed C structure data, according to\n\
1858fmt, starting at offset. Requires len(buffer[offset:]) >= calcsize(fmt).");
1859
1860static PyObject *
1861unpack_from(PyObject *self, PyObject *args, PyObject *kwds)
1862{
1863 PyObject *s_object, *fmt, *newargs, *result;
1864 Py_ssize_t n = PyTuple_GET_SIZE(args);
1865
1866 if (n == 0) {
1867 PyErr_SetString(PyExc_TypeError, "missing format argument");
1868 return NULL;
1869 }
1870 fmt = PyTuple_GET_ITEM(args, 0);
1871 newargs = PyTuple_GetSlice(args, 1, n);
1872 if (newargs == NULL)
1873 return NULL;
1874
1875 s_object = cache_struct(fmt);
1876 if (s_object == NULL) {
1877 Py_DECREF(newargs);
1878 return NULL;
1879 }
1880 result = s_unpack_from(s_object, newargs, kwds);
1881 Py_DECREF(newargs);
1882 Py_DECREF(s_object);
1883 return result;
1884}
1885
1886static struct PyMethodDef module_functions[] = {
1887 {"_clearcache", (PyCFunction)clearcache, METH_NOARGS, clearcache_doc},
1888 {"calcsize", calcsize, METH_O, calcsize_doc},
1889 {"pack", pack, METH_VARARGS, pack_doc},
1890 {"pack_into", pack_into, METH_VARARGS, pack_into_doc},
1891 {"unpack", unpack, METH_VARARGS, unpack_doc},
1892 {"unpack_from", (PyCFunction)unpack_from,
1893 METH_VARARGS|METH_KEYWORDS, unpack_from_doc},
1894 {NULL, NULL} /* sentinel */
1895};
1896
1897
Thomas Wouters477c8d52006-05-27 19:21:47 +00001898/* Module initialization */
1899
Christian Heimesa34706f2008-01-04 03:06:10 +00001900PyDoc_STRVAR(module_doc,
1901"Functions to convert between Python values and C structs.\n\
Benjamin Peterson4ae19462008-07-31 15:03:40 +00001902Python bytes objects are used to hold the data representing the C struct\n\
Mark Dickinson40714af2009-10-08 15:59:20 +00001903and also as format strings (explained below) to describe the layout of data\n\
1904in the C struct.\n\
Christian Heimesa34706f2008-01-04 03:06:10 +00001905\n\
1906The optional first format char indicates byte order, size and alignment:\n\
Mark Dickinson40714af2009-10-08 15:59:20 +00001907 @: native order, size & alignment (default)\n\
1908 =: native order, std. size & alignment\n\
1909 <: little-endian, std. size & alignment\n\
1910 >: big-endian, std. size & alignment\n\
1911 !: same as >\n\
Christian Heimesa34706f2008-01-04 03:06:10 +00001912\n\
1913The remaining chars indicate types of args and must match exactly;\n\
1914these can be preceded by a decimal repeat count:\n\
1915 x: pad byte (no data); c:char; b:signed byte; B:unsigned byte;\n\
Mark Dickinson40714af2009-10-08 15:59:20 +00001916 ?: _Bool (requires C99; if not available, char is used instead)\n\
Christian Heimesa34706f2008-01-04 03:06:10 +00001917 h:short; H:unsigned short; i:int; I:unsigned int;\n\
1918 l:long; L:unsigned long; f:float; d:double.\n\
1919Special cases (preceding decimal count indicates length):\n\
1920 s:string (array of char); p: pascal string (with count byte).\n\
1921Special case (only available in native format):\n\
1922 P:an integer type that is wide enough to hold a pointer.\n\
1923Special case (not in native mode unless 'long long' in platform C):\n\
1924 q:long long; Q:unsigned long long\n\
1925Whitespace between formats is ignored.\n\
1926\n\
1927The variable struct.error is an exception raised on errors.\n");
1928
Martin v. Löwis1a214512008-06-11 05:26:20 +00001929
1930static struct PyModuleDef _structmodule = {
1931 PyModuleDef_HEAD_INIT,
1932 "_struct",
1933 module_doc,
1934 -1,
1935 module_functions,
1936 NULL,
1937 NULL,
1938 NULL,
1939 NULL
1940};
1941
Thomas Wouters477c8d52006-05-27 19:21:47 +00001942PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001943PyInit__struct(void)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001944{
Christian Heimesa34706f2008-01-04 03:06:10 +00001945 PyObject *ver, *m;
1946
Mark Dickinsonea835e72009-04-19 20:40:33 +00001947 ver = PyBytes_FromString("0.3");
Christian Heimesa34706f2008-01-04 03:06:10 +00001948 if (ver == NULL)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001949 return NULL;
Christian Heimesa34706f2008-01-04 03:06:10 +00001950
Martin v. Löwis1a214512008-06-11 05:26:20 +00001951 m = PyModule_Create(&_structmodule);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001952 if (m == NULL)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001953 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001954
Christian Heimes90aa7642007-12-19 02:45:37 +00001955 Py_TYPE(&PyStructType) = &PyType_Type;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001956 if (PyType_Ready(&PyStructType) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001957 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001958
1959 /* Check endian and swap in faster functions */
1960 {
1961 int one = 1;
1962 formatdef *native = native_table;
1963 formatdef *other, *ptr;
1964 if ((int)*(unsigned char*)&one)
1965 other = lilendian_table;
1966 else
1967 other = bigendian_table;
1968 /* Scan through the native table, find a matching
1969 entry in the endian table and swap in the
1970 native implementations whenever possible
1971 (64-bit platforms may not have "standard" sizes) */
1972 while (native->format != '\0' && other->format != '\0') {
1973 ptr = other;
1974 while (ptr->format != '\0') {
1975 if (ptr->format == native->format) {
1976 /* Match faster when formats are
1977 listed in the same order */
1978 if (ptr == other)
1979 other++;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001980 /* Only use the trick if the
Thomas Wouters477c8d52006-05-27 19:21:47 +00001981 size matches */
1982 if (ptr->size != native->size)
1983 break;
1984 /* Skip float and double, could be
1985 "unknown" float format */
1986 if (ptr->format == 'd' || ptr->format == 'f')
1987 break;
1988 ptr->pack = native->pack;
1989 ptr->unpack = native->unpack;
1990 break;
1991 }
1992 ptr++;
1993 }
1994 native++;
1995 }
1996 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001997
Thomas Wouters477c8d52006-05-27 19:21:47 +00001998 /* Add some symbolic constants to the module */
1999 if (StructError == NULL) {
2000 StructError = PyErr_NewException("struct.error", NULL, NULL);
2001 if (StructError == NULL)
Martin v. Löwis1a214512008-06-11 05:26:20 +00002002 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002003 }
2004
2005 Py_INCREF(StructError);
2006 PyModule_AddObject(m, "error", StructError);
2007
2008 Py_INCREF((PyObject*)&PyStructType);
2009 PyModule_AddObject(m, "Struct", (PyObject*)&PyStructType);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002010
Christian Heimesa34706f2008-01-04 03:06:10 +00002011 PyModule_AddObject(m, "__version__", ver);
2012
Martin v. Löwis1a214512008-06-11 05:26:20 +00002013 return m;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002014}