blob: b997d51bd65ad2b3c69a3716e25556692b2ff4cc [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 Ippolito4182a752006-05-30 17:37:54 +000020/* If PY_STRUCT_OVERFLOW_MASKING is defined, the struct module will wrap all input
Bob Ippolito2fd39772006-05-29 22:55:48 +000021 numbers for explicit endians such that they fit in the given type, much
22 like explicit casting in C. A warning will be raised if the number did
23 not originally fit within the range of the requested type. If it is
24 not defined, then all range errors and overflow will be struct.error
25 exceptions. */
26
Bob Ippolito4182a752006-05-30 17:37:54 +000027#define PY_STRUCT_OVERFLOW_MASKING 1
Bob Ippolito2fd39772006-05-29 22:55:48 +000028
Bob Ippolito4182a752006-05-30 17:37:54 +000029#ifdef PY_STRUCT_OVERFLOW_MASKING
Bob Ippolito2fd39772006-05-29 22:55:48 +000030static PyObject *pylong_ulong_mask = NULL;
31static PyObject *pyint_zero = NULL;
32#endif
33
Bob Ippolitoe6c9f982006-08-04 23:59:21 +000034/* If PY_STRUCT_FLOAT_COERCE is defined, the struct module will allow float
35 arguments for integer formats with a warning for backwards
36 compatibility. */
37
38#define PY_STRUCT_FLOAT_COERCE 1
39
40#ifdef PY_STRUCT_FLOAT_COERCE
41#define FLOAT_COERCE "integer argument expected, got float"
42#endif
43
44
Bob Ippolito232f3c92006-05-23 19:12:41 +000045/* The translation function for each format character is table driven */
Bob Ippolito232f3c92006-05-23 19:12:41 +000046typedef struct _formatdef {
Antoine Pitrouc7c96a92010-05-09 15:15:40 +000047 char format;
48 Py_ssize_t size;
49 Py_ssize_t alignment;
50 PyObject* (*unpack)(const char *,
51 const struct _formatdef *);
52 int (*pack)(char *, PyObject *,
53 const struct _formatdef *);
Bob Ippolito232f3c92006-05-23 19:12:41 +000054} formatdef;
55
56typedef struct _formatcode {
Antoine Pitrouc7c96a92010-05-09 15:15:40 +000057 const struct _formatdef *fmtdef;
58 Py_ssize_t offset;
59 Py_ssize_t size;
Bob Ippolito232f3c92006-05-23 19:12:41 +000060} formatcode;
61
62/* Struct object interface */
63
64typedef struct {
Antoine Pitrouc7c96a92010-05-09 15:15:40 +000065 PyObject_HEAD
66 Py_ssize_t s_size;
67 Py_ssize_t s_len;
68 formatcode *s_codes;
69 PyObject *s_format;
70 PyObject *weakreflist; /* List of weak references */
Bob Ippolito232f3c92006-05-23 19:12:41 +000071} PyStructObject;
72
Bob Ippolitoeb621272006-05-24 15:32:06 +000073
Bob Ippolito07c023b2006-05-23 19:32:25 +000074#define PyStruct_Check(op) PyObject_TypeCheck(op, &PyStructType)
Christian Heimese93237d2007-12-19 02:37:44 +000075#define PyStruct_CheckExact(op) (Py_TYPE(op) == &PyStructType)
Bob Ippolito232f3c92006-05-23 19:12:41 +000076
77
78/* Exception */
79
80static PyObject *StructError;
81
82
83/* Define various structs to figure out the alignments of types */
84
85
86typedef struct { char c; short x; } st_short;
87typedef struct { char c; int x; } st_int;
88typedef struct { char c; long x; } st_long;
89typedef struct { char c; float x; } st_float;
90typedef struct { char c; double x; } st_double;
91typedef struct { char c; void *x; } st_void_p;
92
93#define SHORT_ALIGN (sizeof(st_short) - sizeof(short))
94#define INT_ALIGN (sizeof(st_int) - sizeof(int))
95#define LONG_ALIGN (sizeof(st_long) - sizeof(long))
96#define FLOAT_ALIGN (sizeof(st_float) - sizeof(float))
97#define DOUBLE_ALIGN (sizeof(st_double) - sizeof(double))
98#define VOID_P_ALIGN (sizeof(st_void_p) - sizeof(void *))
99
100/* We can't support q and Q in native mode unless the compiler does;
101 in std mode, they're 8 bytes on all platforms. */
102#ifdef HAVE_LONG_LONG
103typedef struct { char c; PY_LONG_LONG x; } s_long_long;
104#define LONG_LONG_ALIGN (sizeof(s_long_long) - sizeof(PY_LONG_LONG))
105#endif
106
Martin v. Löwisaef4c6b2007-01-21 09:33:07 +0000107#ifdef HAVE_C99_BOOL
108#define BOOL_TYPE _Bool
109typedef struct { char c; _Bool x; } s_bool;
110#define BOOL_ALIGN (sizeof(s_bool) - sizeof(BOOL_TYPE))
111#else
112#define BOOL_TYPE char
113#define BOOL_ALIGN 0
114#endif
115
Bob Ippolito232f3c92006-05-23 19:12:41 +0000116#define STRINGIFY(x) #x
117
118#ifdef __powerc
119#pragma options align=reset
120#endif
121
122/* Helper to get a PyLongObject by hook or by crook. Caller should decref. */
123
124static PyObject *
125get_pylong(PyObject *v)
126{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000127 PyNumberMethods *m;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000128
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000129 assert(v != NULL);
130 if (PyInt_Check(v))
131 return PyLong_FromLong(PyInt_AS_LONG(v));
132 if (PyLong_Check(v)) {
133 Py_INCREF(v);
134 return v;
135 }
136 m = Py_TYPE(v)->tp_as_number;
137 if (m != NULL && m->nb_long != NULL) {
138 v = m->nb_long(v);
139 if (v == NULL)
140 return NULL;
141 if (PyLong_Check(v))
142 return v;
143 Py_DECREF(v);
144 }
145 PyErr_SetString(StructError,
146 "cannot convert argument to long");
147 return NULL;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000148}
149
150/* Helper routine to get a Python integer and raise the appropriate error
151 if it isn't one */
152
153static int
154get_long(PyObject *v, long *p)
155{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000156 long x = PyInt_AsLong(v);
157 if (x == -1 && PyErr_Occurred()) {
Bob Ippolitoe6c9f982006-08-04 23:59:21 +0000158#ifdef PY_STRUCT_FLOAT_COERCE
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000159 if (PyFloat_Check(v)) {
160 PyObject *o;
161 int res;
162 PyErr_Clear();
163 if (PyErr_WarnEx(PyExc_DeprecationWarning, FLOAT_COERCE, 1) < 0)
164 return -1;
165 o = PyNumber_Int(v);
166 if (o == NULL)
167 return -1;
168 res = get_long(o, p);
169 Py_DECREF(o);
170 return res;
171 }
Bob Ippolitoe6c9f982006-08-04 23:59:21 +0000172#endif
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000173 if (PyErr_ExceptionMatches(PyExc_TypeError))
174 PyErr_SetString(StructError,
175 "required argument is not an integer");
176 return -1;
177 }
178 *p = x;
179 return 0;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000180}
181
182
183/* Same, but handling unsigned long */
184
Mark Dickinsona55fe102009-09-27 16:32:34 +0000185#ifndef PY_STRUCT_OVERFLOW_MASKING
186
Bob Ippolito232f3c92006-05-23 19:12:41 +0000187static int
188get_ulong(PyObject *v, unsigned long *p)
189{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000190 if (PyLong_Check(v)) {
191 unsigned long x = PyLong_AsUnsignedLong(v);
192 if (x == (unsigned long)(-1) && PyErr_Occurred())
193 return -1;
194 *p = x;
195 return 0;
196 }
197 if (get_long(v, (long *)p) < 0)
198 return -1;
199 if (((long)*p) < 0) {
200 PyErr_SetString(StructError,
201 "unsigned argument is < 0");
202 return -1;
203 }
204 return 0;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000205}
206
Mark Dickinsona55fe102009-09-27 16:32:34 +0000207#endif /* PY_STRUCT_OVERFLOW_MASKING */
208
Bob Ippolito232f3c92006-05-23 19:12:41 +0000209#ifdef HAVE_LONG_LONG
210
211/* Same, but handling native long long. */
212
213static int
214get_longlong(PyObject *v, PY_LONG_LONG *p)
215{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000216 PY_LONG_LONG x;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000217
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000218 v = get_pylong(v);
219 if (v == NULL)
220 return -1;
221 assert(PyLong_Check(v));
222 x = PyLong_AsLongLong(v);
223 Py_DECREF(v);
224 if (x == (PY_LONG_LONG)-1 && PyErr_Occurred())
225 return -1;
226 *p = x;
227 return 0;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000228}
229
230/* Same, but handling native unsigned long long. */
231
232static int
233get_ulonglong(PyObject *v, unsigned PY_LONG_LONG *p)
234{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000235 unsigned PY_LONG_LONG x;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000236
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000237 v = get_pylong(v);
238 if (v == NULL)
239 return -1;
240 assert(PyLong_Check(v));
241 x = PyLong_AsUnsignedLongLong(v);
242 Py_DECREF(v);
243 if (x == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred())
244 return -1;
245 *p = x;
246 return 0;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000247}
248
249#endif
250
Bob Ippolito4182a752006-05-30 17:37:54 +0000251#ifdef PY_STRUCT_OVERFLOW_MASKING
Bob Ippolito2fd39772006-05-29 22:55:48 +0000252
253/* Helper routine to get a Python integer and raise the appropriate error
254 if it isn't one */
255
Neal Norwitz07aadb12006-07-30 06:55:48 +0000256#define INT_OVERFLOW "struct integer overflow masking is deprecated"
257
Bob Ippolito2fd39772006-05-29 22:55:48 +0000258static int
259get_wrapped_long(PyObject *v, long *p)
260{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000261 if (get_long(v, p) < 0) {
262 if (PyLong_Check(v) &&
263 PyErr_ExceptionMatches(PyExc_OverflowError)) {
264 PyObject *wrapped;
265 long x;
266 PyErr_Clear();
Bob Ippolitoe6c9f982006-08-04 23:59:21 +0000267#ifdef PY_STRUCT_FLOAT_COERCE
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000268 if (PyFloat_Check(v)) {
269 PyObject *o;
270 int res;
271 PyErr_Clear();
272 if (PyErr_WarnEx(PyExc_DeprecationWarning, FLOAT_COERCE, 1) < 0)
273 return -1;
274 o = PyNumber_Int(v);
275 if (o == NULL)
276 return -1;
277 res = get_wrapped_long(o, p);
278 Py_DECREF(o);
279 return res;
280 }
Bob Ippolitoe6c9f982006-08-04 23:59:21 +0000281#endif
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000282 if (PyErr_WarnEx(PyExc_DeprecationWarning, INT_OVERFLOW, 1) < 0)
283 return -1;
284 wrapped = PyNumber_And(v, pylong_ulong_mask);
285 if (wrapped == NULL)
286 return -1;
287 x = (long)PyLong_AsUnsignedLong(wrapped);
288 Py_DECREF(wrapped);
289 if (x == -1 && PyErr_Occurred())
290 return -1;
291 *p = x;
292 } else {
293 return -1;
294 }
295 }
296 return 0;
Bob Ippolito2fd39772006-05-29 22:55:48 +0000297}
298
299static int
300get_wrapped_ulong(PyObject *v, unsigned long *p)
301{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000302 long x = (long)PyLong_AsUnsignedLong(v);
303 if (x == -1 && PyErr_Occurred()) {
304 PyObject *wrapped;
305 PyErr_Clear();
Bob Ippolitoe6c9f982006-08-04 23:59:21 +0000306#ifdef PY_STRUCT_FLOAT_COERCE
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000307 if (PyFloat_Check(v)) {
308 PyObject *o;
309 int res;
310 PyErr_Clear();
311 if (PyErr_WarnEx(PyExc_DeprecationWarning, FLOAT_COERCE, 1) < 0)
312 return -1;
313 o = PyNumber_Int(v);
314 if (o == NULL)
315 return -1;
316 res = get_wrapped_ulong(o, p);
317 Py_DECREF(o);
318 return res;
319 }
Bob Ippolitoe6c9f982006-08-04 23:59:21 +0000320#endif
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000321 wrapped = PyNumber_And(v, pylong_ulong_mask);
322 if (wrapped == NULL)
323 return -1;
324 if (PyErr_WarnEx(PyExc_DeprecationWarning, INT_OVERFLOW, 1) < 0) {
325 Py_DECREF(wrapped);
326 return -1;
327 }
328 x = (long)PyLong_AsUnsignedLong(wrapped);
329 Py_DECREF(wrapped);
330 if (x == -1 && PyErr_Occurred())
331 return -1;
332 }
333 *p = (unsigned long)x;
334 return 0;
Bob Ippolito2fd39772006-05-29 22:55:48 +0000335}
336
337#define RANGE_ERROR(x, f, flag, mask) \
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000338 do { \
339 if (_range_error(f, flag) < 0) \
340 return -1; \
341 else \
342 (x) &= (mask); \
343 } while (0)
Bob Ippolito2fd39772006-05-29 22:55:48 +0000344
345#else
346
347#define get_wrapped_long get_long
348#define get_wrapped_ulong get_ulong
349#define RANGE_ERROR(x, f, flag, mask) return _range_error(f, flag)
350
351#endif
352
Bob Ippolito232f3c92006-05-23 19:12:41 +0000353/* Floating point helpers */
354
355static PyObject *
356unpack_float(const char *p, /* start of 4-byte string */
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000357 int le) /* true for little-endian, false for big-endian */
Bob Ippolito232f3c92006-05-23 19:12:41 +0000358{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000359 double x;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000360
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000361 x = _PyFloat_Unpack4((unsigned char *)p, le);
362 if (x == -1.0 && PyErr_Occurred())
363 return NULL;
364 return PyFloat_FromDouble(x);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000365}
366
367static PyObject *
368unpack_double(const char *p, /* start of 8-byte string */
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000369 int le) /* true for little-endian, false for big-endian */
Bob Ippolito232f3c92006-05-23 19:12:41 +0000370{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000371 double x;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000372
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000373 x = _PyFloat_Unpack8((unsigned char *)p, le);
374 if (x == -1.0 && PyErr_Occurred())
375 return NULL;
376 return PyFloat_FromDouble(x);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000377}
378
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000379/* Helper to format the range error exceptions */
380static int
Armin Rigo162997e2006-05-29 17:59:47 +0000381_range_error(const formatdef *f, int is_unsigned)
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000382{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000383 /* ulargest is the largest unsigned value with f->size bytes.
384 * Note that the simpler:
385 * ((size_t)1 << (f->size * 8)) - 1
386 * doesn't work when f->size == sizeof(size_t) because C doesn't
387 * define what happens when a left shift count is >= the number of
388 * bits in the integer being shifted; e.g., on some boxes it doesn't
389 * shift at all when they're equal.
390 */
391 const size_t ulargest = (size_t)-1 >> ((SIZEOF_SIZE_T - f->size)*8);
392 assert(f->size >= 1 && f->size <= SIZEOF_SIZE_T);
393 if (is_unsigned)
394 PyErr_Format(StructError,
395 "'%c' format requires 0 <= number <= %zu",
396 f->format,
397 ulargest);
398 else {
399 const Py_ssize_t largest = (Py_ssize_t)(ulargest >> 1);
400 PyErr_Format(StructError,
401 "'%c' format requires %zd <= number <= %zd",
402 f->format,
403 ~ largest,
404 largest);
405 }
Bob Ippolito4182a752006-05-30 17:37:54 +0000406#ifdef PY_STRUCT_OVERFLOW_MASKING
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000407 {
408 PyObject *ptype, *pvalue, *ptraceback;
409 PyObject *msg;
410 int rval;
411 PyErr_Fetch(&ptype, &pvalue, &ptraceback);
412 assert(pvalue != NULL);
413 msg = PyObject_Str(pvalue);
414 Py_XDECREF(ptype);
415 Py_XDECREF(pvalue);
416 Py_XDECREF(ptraceback);
417 if (msg == NULL)
418 return -1;
419 rval = PyErr_WarnEx(PyExc_DeprecationWarning,
420 PyString_AS_STRING(msg), 1);
421 Py_DECREF(msg);
422 if (rval == 0)
423 return 0;
424 }
Bob Ippolito2fd39772006-05-29 22:55:48 +0000425#endif
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000426 return -1;
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000427}
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000428
429
Bob Ippolito232f3c92006-05-23 19:12:41 +0000430
431/* A large number of small routines follow, with names of the form
432
Bob Ippolitoaa70a172006-05-26 20:25:23 +0000433 [bln][up]_TYPE
Bob Ippolito232f3c92006-05-23 19:12:41 +0000434
435 [bln] distiguishes among big-endian, little-endian and native.
436 [pu] distiguishes between pack (to struct) and unpack (from struct).
437 TYPE is one of char, byte, ubyte, etc.
438*/
439
440/* Native mode routines. ****************************************************/
441/* NOTE:
442 In all n[up]_<type> routines handling types larger than 1 byte, there is
443 *no* guarantee that the p pointer is properly aligned for each type,
444 therefore memcpy is called. An intermediate variable is used to
445 compensate for big-endian architectures.
446 Normally both the intermediate variable and the memcpy call will be
447 skipped by C optimisation in little-endian architectures (gcc >= 2.91
448 does this). */
449
450static PyObject *
451nu_char(const char *p, const formatdef *f)
452{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000453 return PyString_FromStringAndSize(p, 1);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000454}
455
456static PyObject *
457nu_byte(const char *p, const formatdef *f)
458{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000459 return PyInt_FromLong((long) *(signed char *)p);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000460}
461
462static PyObject *
463nu_ubyte(const char *p, const formatdef *f)
464{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000465 return PyInt_FromLong((long) *(unsigned char *)p);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000466}
467
468static PyObject *
469nu_short(const char *p, const formatdef *f)
470{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000471 short x;
472 memcpy((char *)&x, p, sizeof x);
473 return PyInt_FromLong((long)x);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000474}
475
476static PyObject *
477nu_ushort(const char *p, const formatdef *f)
478{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000479 unsigned short x;
480 memcpy((char *)&x, p, sizeof x);
481 return PyInt_FromLong((long)x);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000482}
483
484static PyObject *
485nu_int(const char *p, const formatdef *f)
486{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000487 int x;
488 memcpy((char *)&x, p, sizeof x);
489 return PyInt_FromLong((long)x);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000490}
491
492static PyObject *
493nu_uint(const char *p, const formatdef *f)
494{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000495 unsigned int x;
496 memcpy((char *)&x, p, sizeof x);
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000497#if (SIZEOF_LONG > SIZEOF_INT)
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000498 return PyInt_FromLong((long)x);
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000499#else
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000500 if (x <= ((unsigned int)LONG_MAX))
501 return PyInt_FromLong((long)x);
502 return PyLong_FromUnsignedLong((unsigned long)x);
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000503#endif
Bob Ippolito232f3c92006-05-23 19:12:41 +0000504}
505
506static PyObject *
507nu_long(const char *p, const formatdef *f)
508{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000509 long x;
510 memcpy((char *)&x, p, sizeof x);
511 return PyInt_FromLong(x);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000512}
513
514static PyObject *
515nu_ulong(const char *p, const formatdef *f)
516{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000517 unsigned long x;
518 memcpy((char *)&x, p, sizeof x);
519 if (x <= LONG_MAX)
520 return PyInt_FromLong((long)x);
521 return PyLong_FromUnsignedLong(x);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000522}
523
524/* Native mode doesn't support q or Q unless the platform C supports
525 long long (or, on Windows, __int64). */
526
527#ifdef HAVE_LONG_LONG
528
529static PyObject *
530nu_longlong(const char *p, const formatdef *f)
531{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000532 PY_LONG_LONG x;
533 memcpy((char *)&x, p, sizeof x);
534 if (x >= LONG_MIN && x <= LONG_MAX)
535 return PyInt_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long));
536 return PyLong_FromLongLong(x);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000537}
538
539static PyObject *
540nu_ulonglong(const char *p, const formatdef *f)
541{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000542 unsigned PY_LONG_LONG x;
543 memcpy((char *)&x, p, sizeof x);
544 if (x <= LONG_MAX)
545 return PyInt_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long));
546 return PyLong_FromUnsignedLongLong(x);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000547}
548
549#endif
550
551static PyObject *
Martin v. Löwisaef4c6b2007-01-21 09:33:07 +0000552nu_bool(const char *p, const formatdef *f)
553{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000554 BOOL_TYPE x;
555 memcpy((char *)&x, p, sizeof x);
556 return PyBool_FromLong(x != 0);
Martin v. Löwisaef4c6b2007-01-21 09:33:07 +0000557}
558
559
560static PyObject *
Bob Ippolito232f3c92006-05-23 19:12:41 +0000561nu_float(const char *p, const formatdef *f)
562{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000563 float x;
564 memcpy((char *)&x, p, sizeof x);
565 return PyFloat_FromDouble((double)x);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000566}
567
568static PyObject *
569nu_double(const char *p, const formatdef *f)
570{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000571 double x;
572 memcpy((char *)&x, p, sizeof x);
573 return PyFloat_FromDouble(x);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000574}
575
576static PyObject *
577nu_void_p(const char *p, const formatdef *f)
578{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000579 void *x;
580 memcpy((char *)&x, p, sizeof x);
581 return PyLong_FromVoidPtr(x);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000582}
583
584static int
585np_byte(char *p, PyObject *v, const formatdef *f)
586{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000587 long x;
588 if (get_long(v, &x) < 0)
589 return -1;
590 if (x < -128 || x > 127){
591 PyErr_SetString(StructError,
592 "byte format requires -128 <= number <= 127");
593 return -1;
594 }
595 *p = (char)x;
596 return 0;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000597}
598
599static int
600np_ubyte(char *p, PyObject *v, const formatdef *f)
601{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000602 long x;
603 if (get_long(v, &x) < 0)
604 return -1;
605 if (x < 0 || x > 255){
606 PyErr_SetString(StructError,
607 "ubyte format requires 0 <= number <= 255");
608 return -1;
609 }
610 *p = (char)x;
611 return 0;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000612}
613
614static int
615np_char(char *p, PyObject *v, const formatdef *f)
616{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000617 if (!PyString_Check(v) || PyString_Size(v) != 1) {
618 PyErr_SetString(StructError,
619 "char format require string of length 1");
620 return -1;
621 }
622 *p = *PyString_AsString(v);
623 return 0;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000624}
625
626static int
627np_short(char *p, PyObject *v, const formatdef *f)
628{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000629 long x;
630 short y;
631 if (get_long(v, &x) < 0)
632 return -1;
633 if (x < SHRT_MIN || x > SHRT_MAX){
634 PyErr_SetString(StructError,
635 "short format requires " STRINGIFY(SHRT_MIN)
636 " <= number <= " STRINGIFY(SHRT_MAX));
637 return -1;
638 }
639 y = (short)x;
640 memcpy(p, (char *)&y, sizeof y);
641 return 0;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000642}
643
644static int
645np_ushort(char *p, PyObject *v, const formatdef *f)
646{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000647 long x;
648 unsigned short y;
649 if (get_long(v, &x) < 0)
650 return -1;
651 if (x < 0 || x > USHRT_MAX){
652 PyErr_SetString(StructError,
653 "ushort format requires 0 <= number <= " STRINGIFY(USHRT_MAX));
654 return -1;
655 }
656 y = (unsigned short)x;
657 memcpy(p, (char *)&y, sizeof y);
658 return 0;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000659}
660
661static int
662np_int(char *p, PyObject *v, const formatdef *f)
663{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000664 long x;
665 int y;
666 if (get_long(v, &x) < 0)
667 return -1;
Bob Ippolito90bd0a52006-05-27 11:47:12 +0000668#if (SIZEOF_LONG > SIZEOF_INT)
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000669 if ((x < ((long)INT_MIN)) || (x > ((long)INT_MAX)))
670 RANGE_ERROR(x, f, 0, -1);
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000671#endif
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000672 y = (int)x;
673 memcpy(p, (char *)&y, sizeof y);
674 return 0;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000675}
676
677static int
678np_uint(char *p, PyObject *v, const formatdef *f)
679{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000680 unsigned long x;
681 unsigned int y;
682 if (get_wrapped_ulong(v, &x) < 0)
683 return -1;
684 y = (unsigned int)x;
Bob Ippolito90bd0a52006-05-27 11:47:12 +0000685#if (SIZEOF_LONG > SIZEOF_INT)
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000686 if (x > ((unsigned long)UINT_MAX))
687 RANGE_ERROR(y, f, 1, -1);
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000688#endif
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000689 memcpy(p, (char *)&y, sizeof y);
690 return 0;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000691}
692
693static int
694np_long(char *p, PyObject *v, const formatdef *f)
695{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000696 long x;
697 if (get_long(v, &x) < 0)
698 return -1;
699 memcpy(p, (char *)&x, sizeof x);
700 return 0;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000701}
702
703static int
704np_ulong(char *p, PyObject *v, const formatdef *f)
705{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000706 unsigned long x;
707 if (get_wrapped_ulong(v, &x) < 0)
708 return -1;
709 memcpy(p, (char *)&x, sizeof x);
710 return 0;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000711}
712
713#ifdef HAVE_LONG_LONG
714
715static int
716np_longlong(char *p, PyObject *v, const formatdef *f)
717{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000718 PY_LONG_LONG x;
719 if (get_longlong(v, &x) < 0)
720 return -1;
721 memcpy(p, (char *)&x, sizeof x);
722 return 0;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000723}
724
725static int
726np_ulonglong(char *p, PyObject *v, const formatdef *f)
727{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000728 unsigned PY_LONG_LONG x;
729 if (get_ulonglong(v, &x) < 0)
730 return -1;
731 memcpy(p, (char *)&x, sizeof x);
732 return 0;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000733}
734#endif
735
Martin v. Löwisaef4c6b2007-01-21 09:33:07 +0000736
737static int
738np_bool(char *p, PyObject *v, const formatdef *f)
739{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000740 BOOL_TYPE y;
741 y = PyObject_IsTrue(v);
742 memcpy(p, (char *)&y, sizeof y);
743 return 0;
Martin v. Löwisaef4c6b2007-01-21 09:33:07 +0000744}
745
Bob Ippolito232f3c92006-05-23 19:12:41 +0000746static int
747np_float(char *p, PyObject *v, const formatdef *f)
748{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000749 float x = (float)PyFloat_AsDouble(v);
750 if (x == -1 && PyErr_Occurred()) {
751 PyErr_SetString(StructError,
752 "required argument is not a float");
753 return -1;
754 }
755 memcpy(p, (char *)&x, sizeof x);
756 return 0;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000757}
758
759static int
760np_double(char *p, PyObject *v, const formatdef *f)
761{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000762 double x = PyFloat_AsDouble(v);
763 if (x == -1 && PyErr_Occurred()) {
764 PyErr_SetString(StructError,
765 "required argument is not a float");
766 return -1;
767 }
768 memcpy(p, (char *)&x, sizeof(double));
769 return 0;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000770}
771
772static int
773np_void_p(char *p, PyObject *v, const formatdef *f)
774{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000775 void *x;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000776
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000777 v = get_pylong(v);
778 if (v == NULL)
779 return -1;
780 assert(PyLong_Check(v));
781 x = PyLong_AsVoidPtr(v);
782 Py_DECREF(v);
783 if (x == NULL && PyErr_Occurred())
784 return -1;
785 memcpy(p, (char *)&x, sizeof x);
786 return 0;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000787}
788
789static formatdef native_table[] = {
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000790 {'x', sizeof(char), 0, NULL},
791 {'b', sizeof(char), 0, nu_byte, np_byte},
792 {'B', sizeof(char), 0, nu_ubyte, np_ubyte},
793 {'c', sizeof(char), 0, nu_char, np_char},
794 {'s', sizeof(char), 0, NULL},
795 {'p', sizeof(char), 0, NULL},
796 {'h', sizeof(short), SHORT_ALIGN, nu_short, np_short},
797 {'H', sizeof(short), SHORT_ALIGN, nu_ushort, np_ushort},
798 {'i', sizeof(int), INT_ALIGN, nu_int, np_int},
799 {'I', sizeof(int), INT_ALIGN, nu_uint, np_uint},
800 {'l', sizeof(long), LONG_ALIGN, nu_long, np_long},
801 {'L', sizeof(long), LONG_ALIGN, nu_ulong, np_ulong},
Bob Ippolito232f3c92006-05-23 19:12:41 +0000802#ifdef HAVE_LONG_LONG
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000803 {'q', sizeof(PY_LONG_LONG), LONG_LONG_ALIGN, nu_longlong, np_longlong},
804 {'Q', sizeof(PY_LONG_LONG), LONG_LONG_ALIGN, nu_ulonglong,np_ulonglong},
Bob Ippolito232f3c92006-05-23 19:12:41 +0000805#endif
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000806 {'?', sizeof(BOOL_TYPE), BOOL_ALIGN, nu_bool, np_bool},
807 {'f', sizeof(float), FLOAT_ALIGN, nu_float, np_float},
808 {'d', sizeof(double), DOUBLE_ALIGN, nu_double, np_double},
809 {'P', sizeof(void *), VOID_P_ALIGN, nu_void_p, np_void_p},
810 {0}
Bob Ippolito232f3c92006-05-23 19:12:41 +0000811};
812
813/* Big-endian routines. *****************************************************/
814
815static PyObject *
816bu_int(const char *p, const formatdef *f)
817{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000818 long x = 0;
819 Py_ssize_t i = f->size;
820 const unsigned char *bytes = (const unsigned char *)p;
821 do {
822 x = (x<<8) | *bytes++;
823 } while (--i > 0);
824 /* Extend the sign bit. */
825 if (SIZEOF_LONG > f->size)
826 x |= -(x & (1L << ((8 * f->size) - 1)));
827 return PyInt_FromLong(x);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000828}
829
830static PyObject *
831bu_uint(const char *p, const formatdef *f)
832{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000833 unsigned long x = 0;
834 Py_ssize_t i = f->size;
835 const unsigned char *bytes = (const unsigned char *)p;
836 do {
837 x = (x<<8) | *bytes++;
838 } while (--i > 0);
839 if (x <= LONG_MAX)
840 return PyInt_FromLong((long)x);
841 return PyLong_FromUnsignedLong(x);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000842}
843
844static PyObject *
845bu_longlong(const char *p, const formatdef *f)
846{
Bob Ippolito90bd0a52006-05-27 11:47:12 +0000847#ifdef HAVE_LONG_LONG
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000848 PY_LONG_LONG x = 0;
849 Py_ssize_t i = f->size;
850 const unsigned char *bytes = (const unsigned char *)p;
851 do {
852 x = (x<<8) | *bytes++;
853 } while (--i > 0);
854 /* Extend the sign bit. */
855 if (SIZEOF_LONG_LONG > f->size)
856 x |= -(x & ((PY_LONG_LONG)1 << ((8 * f->size) - 1)));
857 if (x >= LONG_MIN && x <= LONG_MAX)
858 return PyInt_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long));
859 return PyLong_FromLongLong(x);
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000860#else
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000861 return _PyLong_FromByteArray((const unsigned char *)p,
862 8,
863 0, /* little-endian */
864 1 /* signed */);
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000865#endif
Bob Ippolito232f3c92006-05-23 19:12:41 +0000866}
867
868static PyObject *
869bu_ulonglong(const char *p, const formatdef *f)
870{
Bob Ippolito90bd0a52006-05-27 11:47:12 +0000871#ifdef HAVE_LONG_LONG
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000872 unsigned PY_LONG_LONG x = 0;
873 Py_ssize_t i = f->size;
874 const unsigned char *bytes = (const unsigned char *)p;
875 do {
876 x = (x<<8) | *bytes++;
877 } while (--i > 0);
878 if (x <= LONG_MAX)
879 return PyInt_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long));
880 return PyLong_FromUnsignedLongLong(x);
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000881#else
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000882 return _PyLong_FromByteArray((const unsigned char *)p,
883 8,
884 0, /* little-endian */
885 0 /* signed */);
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000886#endif
Bob Ippolito232f3c92006-05-23 19:12:41 +0000887}
888
889static PyObject *
890bu_float(const char *p, const formatdef *f)
891{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000892 return unpack_float(p, 0);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000893}
894
895static PyObject *
896bu_double(const char *p, const formatdef *f)
897{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000898 return unpack_double(p, 0);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000899}
900
Martin v. Löwisaef4c6b2007-01-21 09:33:07 +0000901static PyObject *
902bu_bool(const char *p, const formatdef *f)
903{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000904 char x;
905 memcpy((char *)&x, p, sizeof x);
906 return PyBool_FromLong(x != 0);
Martin v. Löwisaef4c6b2007-01-21 09:33:07 +0000907}
908
Bob Ippolito232f3c92006-05-23 19:12:41 +0000909static int
910bp_int(char *p, PyObject *v, const formatdef *f)
911{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000912 long x;
913 Py_ssize_t i;
914 if (get_wrapped_long(v, &x) < 0)
915 return -1;
916 i = f->size;
917 if (i != SIZEOF_LONG) {
918 if ((i == 2) && (x < -32768 || x > 32767))
919 RANGE_ERROR(x, f, 0, 0xffffL);
Bob Ippolito90bd0a52006-05-27 11:47:12 +0000920#if (SIZEOF_LONG != 4)
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000921 else if ((i == 4) && (x < -2147483648L || x > 2147483647L))
922 RANGE_ERROR(x, f, 0, 0xffffffffL);
Bob Ippolito2fd39772006-05-29 22:55:48 +0000923#endif
Bob Ippolito4182a752006-05-30 17:37:54 +0000924#ifdef PY_STRUCT_OVERFLOW_MASKING
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000925 else if ((i == 1) && (x < -128 || x > 127))
926 RANGE_ERROR(x, f, 0, 0xffL);
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000927#endif
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000928 }
929 do {
930 p[--i] = (char)x;
931 x >>= 8;
932 } while (i > 0);
933 return 0;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000934}
935
936static int
937bp_uint(char *p, PyObject *v, const formatdef *f)
938{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000939 unsigned long x;
940 Py_ssize_t i;
941 if (get_wrapped_ulong(v, &x) < 0)
942 return -1;
943 i = f->size;
944 if (i != SIZEOF_LONG) {
945 unsigned long maxint = 1;
946 maxint <<= (unsigned long)(i * 8);
947 if (x >= maxint)
948 RANGE_ERROR(x, f, 1, maxint - 1);
949 }
950 do {
951 p[--i] = (char)x;
952 x >>= 8;
953 } while (i > 0);
954 return 0;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000955}
956
957static int
958bp_longlong(char *p, PyObject *v, const formatdef *f)
959{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000960 int res;
961 v = get_pylong(v);
962 if (v == NULL)
963 return -1;
964 res = _PyLong_AsByteArray((PyLongObject *)v,
965 (unsigned char *)p,
966 8,
967 0, /* little_endian */
968 1 /* signed */);
969 Py_DECREF(v);
970 return res;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000971}
972
973static int
974bp_ulonglong(char *p, PyObject *v, const formatdef *f)
975{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000976 int res;
977 v = get_pylong(v);
978 if (v == NULL)
979 return -1;
980 res = _PyLong_AsByteArray((PyLongObject *)v,
981 (unsigned char *)p,
982 8,
983 0, /* little_endian */
984 0 /* signed */);
985 Py_DECREF(v);
986 return res;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000987}
988
989static int
990bp_float(char *p, PyObject *v, const formatdef *f)
991{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000992 double x = PyFloat_AsDouble(v);
993 if (x == -1 && PyErr_Occurred()) {
994 PyErr_SetString(StructError,
995 "required argument is not a float");
996 return -1;
997 }
998 return _PyFloat_Pack4(x, (unsigned char *)p, 0);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000999}
1000
1001static int
1002bp_double(char *p, PyObject *v, const formatdef *f)
1003{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001004 double x = PyFloat_AsDouble(v);
1005 if (x == -1 && PyErr_Occurred()) {
1006 PyErr_SetString(StructError,
1007 "required argument is not a float");
1008 return -1;
1009 }
1010 return _PyFloat_Pack8(x, (unsigned char *)p, 0);
Bob Ippolito232f3c92006-05-23 19:12:41 +00001011}
1012
Martin v. Löwisaef4c6b2007-01-21 09:33:07 +00001013static int
1014bp_bool(char *p, PyObject *v, const formatdef *f)
1015{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001016 char y;
1017 y = PyObject_IsTrue(v);
1018 memcpy(p, (char *)&y, sizeof y);
1019 return 0;
Martin v. Löwisaef4c6b2007-01-21 09:33:07 +00001020}
1021
Bob Ippolito232f3c92006-05-23 19:12:41 +00001022static formatdef bigendian_table[] = {
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001023 {'x', 1, 0, NULL},
Bob Ippolito4182a752006-05-30 17:37:54 +00001024#ifdef PY_STRUCT_OVERFLOW_MASKING
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001025 /* Native packers do range checking without overflow masking. */
1026 {'b', 1, 0, nu_byte, bp_int},
1027 {'B', 1, 0, nu_ubyte, bp_uint},
Bob Ippolito2fd39772006-05-29 22:55:48 +00001028#else
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001029 {'b', 1, 0, nu_byte, np_byte},
1030 {'B', 1, 0, nu_ubyte, np_ubyte},
Bob Ippolito2fd39772006-05-29 22:55:48 +00001031#endif
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001032 {'c', 1, 0, nu_char, np_char},
1033 {'s', 1, 0, NULL},
1034 {'p', 1, 0, NULL},
1035 {'h', 2, 0, bu_int, bp_int},
1036 {'H', 2, 0, bu_uint, bp_uint},
1037 {'i', 4, 0, bu_int, bp_int},
1038 {'I', 4, 0, bu_uint, bp_uint},
1039 {'l', 4, 0, bu_int, bp_int},
1040 {'L', 4, 0, bu_uint, bp_uint},
1041 {'q', 8, 0, bu_longlong, bp_longlong},
1042 {'Q', 8, 0, bu_ulonglong, bp_ulonglong},
1043 {'?', 1, 0, bu_bool, bp_bool},
1044 {'f', 4, 0, bu_float, bp_float},
1045 {'d', 8, 0, bu_double, bp_double},
1046 {0}
Bob Ippolito232f3c92006-05-23 19:12:41 +00001047};
1048
1049/* Little-endian routines. *****************************************************/
1050
1051static PyObject *
1052lu_int(const char *p, const formatdef *f)
1053{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001054 long x = 0;
1055 Py_ssize_t i = f->size;
1056 const unsigned char *bytes = (const unsigned char *)p;
1057 do {
1058 x = (x<<8) | bytes[--i];
1059 } while (i > 0);
1060 /* Extend the sign bit. */
1061 if (SIZEOF_LONG > f->size)
1062 x |= -(x & (1L << ((8 * f->size) - 1)));
1063 return PyInt_FromLong(x);
Bob Ippolito232f3c92006-05-23 19:12:41 +00001064}
1065
1066static PyObject *
1067lu_uint(const char *p, const formatdef *f)
1068{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001069 unsigned long x = 0;
1070 Py_ssize_t i = f->size;
1071 const unsigned char *bytes = (const unsigned char *)p;
1072 do {
1073 x = (x<<8) | bytes[--i];
1074 } while (i > 0);
1075 if (x <= LONG_MAX)
1076 return PyInt_FromLong((long)x);
1077 return PyLong_FromUnsignedLong((long)x);
Bob Ippolito232f3c92006-05-23 19:12:41 +00001078}
1079
1080static PyObject *
1081lu_longlong(const char *p, const formatdef *f)
1082{
Bob Ippolito90bd0a52006-05-27 11:47:12 +00001083#ifdef HAVE_LONG_LONG
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001084 PY_LONG_LONG x = 0;
1085 Py_ssize_t i = f->size;
1086 const unsigned char *bytes = (const unsigned char *)p;
1087 do {
1088 x = (x<<8) | bytes[--i];
1089 } while (i > 0);
1090 /* Extend the sign bit. */
1091 if (SIZEOF_LONG_LONG > f->size)
1092 x |= -(x & ((PY_LONG_LONG)1 << ((8 * f->size) - 1)));
1093 if (x >= LONG_MIN && x <= LONG_MAX)
1094 return PyInt_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long));
1095 return PyLong_FromLongLong(x);
Bob Ippolito94f68ee2006-05-25 18:44:50 +00001096#else
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001097 return _PyLong_FromByteArray((const unsigned char *)p,
1098 8,
1099 1, /* little-endian */
1100 1 /* signed */);
Bob Ippolito94f68ee2006-05-25 18:44:50 +00001101#endif
Bob Ippolito232f3c92006-05-23 19:12:41 +00001102}
1103
1104static PyObject *
1105lu_ulonglong(const char *p, const formatdef *f)
1106{
Bob Ippolito90bd0a52006-05-27 11:47:12 +00001107#ifdef HAVE_LONG_LONG
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001108 unsigned PY_LONG_LONG x = 0;
1109 Py_ssize_t i = f->size;
1110 const unsigned char *bytes = (const unsigned char *)p;
1111 do {
1112 x = (x<<8) | bytes[--i];
1113 } while (i > 0);
1114 if (x <= LONG_MAX)
1115 return PyInt_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long));
1116 return PyLong_FromUnsignedLongLong(x);
Bob Ippolito94f68ee2006-05-25 18:44:50 +00001117#else
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001118 return _PyLong_FromByteArray((const unsigned char *)p,
1119 8,
1120 1, /* little-endian */
1121 0 /* signed */);
Bob Ippolito94f68ee2006-05-25 18:44:50 +00001122#endif
Bob Ippolito232f3c92006-05-23 19:12:41 +00001123}
1124
1125static PyObject *
1126lu_float(const char *p, const formatdef *f)
1127{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001128 return unpack_float(p, 1);
Bob Ippolito232f3c92006-05-23 19:12:41 +00001129}
1130
1131static PyObject *
1132lu_double(const char *p, const formatdef *f)
1133{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001134 return unpack_double(p, 1);
Bob Ippolito232f3c92006-05-23 19:12:41 +00001135}
1136
1137static int
1138lp_int(char *p, PyObject *v, const formatdef *f)
1139{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001140 long x;
1141 Py_ssize_t i;
1142 if (get_wrapped_long(v, &x) < 0)
1143 return -1;
1144 i = f->size;
1145 if (i != SIZEOF_LONG) {
1146 if ((i == 2) && (x < -32768 || x > 32767))
1147 RANGE_ERROR(x, f, 0, 0xffffL);
Bob Ippolito90bd0a52006-05-27 11:47:12 +00001148#if (SIZEOF_LONG != 4)
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001149 else if ((i == 4) && (x < -2147483648L || x > 2147483647L))
1150 RANGE_ERROR(x, f, 0, 0xffffffffL);
Bob Ippolito2fd39772006-05-29 22:55:48 +00001151#endif
Bob Ippolito4182a752006-05-30 17:37:54 +00001152#ifdef PY_STRUCT_OVERFLOW_MASKING
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001153 else if ((i == 1) && (x < -128 || x > 127))
1154 RANGE_ERROR(x, f, 0, 0xffL);
Bob Ippolitoe27337b2006-05-26 13:15:44 +00001155#endif
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001156 }
1157 do {
1158 *p++ = (char)x;
1159 x >>= 8;
1160 } while (--i > 0);
1161 return 0;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001162}
1163
1164static int
1165lp_uint(char *p, PyObject *v, const formatdef *f)
1166{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001167 unsigned long x;
1168 Py_ssize_t i;
1169 if (get_wrapped_ulong(v, &x) < 0)
1170 return -1;
1171 i = f->size;
1172 if (i != SIZEOF_LONG) {
1173 unsigned long maxint = 1;
1174 maxint <<= (unsigned long)(i * 8);
1175 if (x >= maxint)
1176 RANGE_ERROR(x, f, 1, maxint - 1);
1177 }
1178 do {
1179 *p++ = (char)x;
1180 x >>= 8;
1181 } while (--i > 0);
1182 return 0;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001183}
1184
1185static int
1186lp_longlong(char *p, PyObject *v, const formatdef *f)
1187{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001188 int res;
1189 v = get_pylong(v);
1190 if (v == NULL)
1191 return -1;
1192 res = _PyLong_AsByteArray((PyLongObject*)v,
1193 (unsigned char *)p,
1194 8,
1195 1, /* little_endian */
1196 1 /* signed */);
1197 Py_DECREF(v);
1198 return res;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001199}
1200
1201static int
1202lp_ulonglong(char *p, PyObject *v, const formatdef *f)
1203{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001204 int res;
1205 v = get_pylong(v);
1206 if (v == NULL)
1207 return -1;
1208 res = _PyLong_AsByteArray((PyLongObject*)v,
1209 (unsigned char *)p,
1210 8,
1211 1, /* little_endian */
1212 0 /* signed */);
1213 Py_DECREF(v);
1214 return res;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001215}
1216
1217static int
1218lp_float(char *p, PyObject *v, const formatdef *f)
1219{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001220 double x = PyFloat_AsDouble(v);
1221 if (x == -1 && PyErr_Occurred()) {
1222 PyErr_SetString(StructError,
1223 "required argument is not a float");
1224 return -1;
1225 }
1226 return _PyFloat_Pack4(x, (unsigned char *)p, 1);
Bob Ippolito232f3c92006-05-23 19:12:41 +00001227}
1228
1229static int
1230lp_double(char *p, PyObject *v, const formatdef *f)
1231{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001232 double x = PyFloat_AsDouble(v);
1233 if (x == -1 && PyErr_Occurred()) {
1234 PyErr_SetString(StructError,
1235 "required argument is not a float");
1236 return -1;
1237 }
1238 return _PyFloat_Pack8(x, (unsigned char *)p, 1);
Bob Ippolito232f3c92006-05-23 19:12:41 +00001239}
1240
1241static formatdef lilendian_table[] = {
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001242 {'x', 1, 0, NULL},
Bob Ippolito4182a752006-05-30 17:37:54 +00001243#ifdef PY_STRUCT_OVERFLOW_MASKING
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001244 /* Native packers do range checking without overflow masking. */
1245 {'b', 1, 0, nu_byte, lp_int},
1246 {'B', 1, 0, nu_ubyte, lp_uint},
Bob Ippolito2fd39772006-05-29 22:55:48 +00001247#else
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001248 {'b', 1, 0, nu_byte, np_byte},
1249 {'B', 1, 0, nu_ubyte, np_ubyte},
Bob Ippolito2fd39772006-05-29 22:55:48 +00001250#endif
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001251 {'c', 1, 0, nu_char, np_char},
1252 {'s', 1, 0, NULL},
1253 {'p', 1, 0, NULL},
1254 {'h', 2, 0, lu_int, lp_int},
1255 {'H', 2, 0, lu_uint, lp_uint},
1256 {'i', 4, 0, lu_int, lp_int},
1257 {'I', 4, 0, lu_uint, lp_uint},
1258 {'l', 4, 0, lu_int, lp_int},
1259 {'L', 4, 0, lu_uint, lp_uint},
1260 {'q', 8, 0, lu_longlong, lp_longlong},
1261 {'Q', 8, 0, lu_ulonglong, lp_ulonglong},
1262 {'?', 1, 0, bu_bool, bp_bool}, /* Std rep not endian dep,
1263 but potentially different from native rep -- reuse bx_bool funcs. */
1264 {'f', 4, 0, lu_float, lp_float},
1265 {'d', 8, 0, lu_double, lp_double},
1266 {0}
Bob Ippolito232f3c92006-05-23 19:12:41 +00001267};
1268
1269
1270static const formatdef *
1271whichtable(char **pfmt)
1272{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001273 const char *fmt = (*pfmt)++; /* May be backed out of later */
1274 switch (*fmt) {
1275 case '<':
1276 return lilendian_table;
1277 case '>':
1278 case '!': /* Network byte order is big-endian */
1279 return bigendian_table;
1280 case '=': { /* Host byte order -- different from native in aligment! */
1281 int n = 1;
1282 char *p = (char *) &n;
1283 if (*p == 1)
1284 return lilendian_table;
1285 else
1286 return bigendian_table;
1287 }
1288 default:
1289 --*pfmt; /* Back out of pointer increment */
1290 /* Fall through */
1291 case '@':
1292 return native_table;
1293 }
Bob Ippolito232f3c92006-05-23 19:12:41 +00001294}
1295
1296
1297/* Get the table entry for a format code */
1298
1299static const formatdef *
1300getentry(int c, const formatdef *f)
1301{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001302 for (; f->format != '\0'; f++) {
1303 if (f->format == c) {
1304 return f;
1305 }
1306 }
1307 PyErr_SetString(StructError, "bad char in struct format");
1308 return NULL;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001309}
1310
1311
Mark Dickinson38b4a892010-06-12 08:49:42 +00001312/* Align a size according to a format code. Return -1 on overflow. */
Bob Ippolito232f3c92006-05-23 19:12:41 +00001313
Mark Dickinson38b4a892010-06-12 08:49:42 +00001314static Py_ssize_t
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001315align(Py_ssize_t size, char c, const formatdef *e)
Bob Ippolito232f3c92006-05-23 19:12:41 +00001316{
Mark Dickinson38b4a892010-06-12 08:49:42 +00001317 Py_ssize_t extra;
1318
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001319 if (e->format == c) {
Mark Dickinson38b4a892010-06-12 08:49:42 +00001320 if (e->alignment && size > 0) {
1321 extra = (e->alignment - 1) - (size - 1) % (e->alignment);
1322 if (extra > PY_SSIZE_T_MAX - size)
1323 return -1;
1324 size += extra;
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001325 }
1326 }
1327 return size;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001328}
1329
1330
1331/* calculate the size of a format string */
1332
1333static int
1334prepare_s(PyStructObject *self)
1335{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001336 const formatdef *f;
1337 const formatdef *e;
1338 formatcode *codes;
Tim Petersc2b550e2006-05-31 14:28:07 +00001339
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001340 const char *s;
1341 const char *fmt;
1342 char c;
Mark Dickinson38b4a892010-06-12 08:49:42 +00001343 Py_ssize_t size, len, num, itemsize;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001344
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001345 fmt = PyString_AS_STRING(self->s_format);
Bob Ippolito232f3c92006-05-23 19:12:41 +00001346
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001347 f = whichtable((char **)&fmt);
Tim Petersc2b550e2006-05-31 14:28:07 +00001348
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001349 s = fmt;
1350 size = 0;
1351 len = 0;
1352 while ((c = *s++) != '\0') {
1353 if (isspace(Py_CHARMASK(c)))
1354 continue;
1355 if ('0' <= c && c <= '9') {
1356 num = c - '0';
1357 while ('0' <= (c = *s++) && c <= '9') {
Mark Dickinson38b4a892010-06-12 08:49:42 +00001358 /* overflow-safe version of
1359 if (num*10 + (c - '0') > PY_SSIZE_T_MAX) { ... } */
1360 if (num >= PY_SSIZE_T_MAX / 10 && (
1361 num > PY_SSIZE_T_MAX / 10 ||
1362 (c - '0') > PY_SSIZE_T_MAX % 10))
1363 goto overflow;
1364 num = num*10 + (c - '0');
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001365 }
1366 if (c == '\0')
1367 break;
1368 }
1369 else
1370 num = 1;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001371
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001372 e = getentry(c, f);
1373 if (e == NULL)
1374 return -1;
Tim Petersc2b550e2006-05-31 14:28:07 +00001375
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001376 switch (c) {
1377 case 's': /* fall through */
1378 case 'p': len++; break;
1379 case 'x': break;
1380 default: len += num; break;
1381 }
Bob Ippolito232f3c92006-05-23 19:12:41 +00001382
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001383 itemsize = e->size;
1384 size = align(size, c, e);
Mark Dickinson38b4a892010-06-12 08:49:42 +00001385 if (size == -1)
1386 goto overflow;
1387
1388 /* if (size + num * itemsize > PY_SSIZE_T_MAX) { ... } */
1389 if (num > (PY_SSIZE_T_MAX - size) / itemsize)
1390 goto overflow;
1391 size += num * itemsize;
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001392 }
Bob Ippolito232f3c92006-05-23 19:12:41 +00001393
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001394 /* check for overflow */
1395 if ((len + 1) > (PY_SSIZE_T_MAX / sizeof(formatcode))) {
1396 PyErr_NoMemory();
1397 return -1;
1398 }
Gregory P. Smith9d534572008-06-11 07:41:16 +00001399
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001400 self->s_size = size;
1401 self->s_len = len;
1402 codes = PyMem_MALLOC((len + 1) * sizeof(formatcode));
1403 if (codes == NULL) {
1404 PyErr_NoMemory();
1405 return -1;
1406 }
1407 self->s_codes = codes;
Tim Petersc2b550e2006-05-31 14:28:07 +00001408
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001409 s = fmt;
1410 size = 0;
1411 while ((c = *s++) != '\0') {
1412 if (isspace(Py_CHARMASK(c)))
1413 continue;
1414 if ('0' <= c && c <= '9') {
1415 num = c - '0';
1416 while ('0' <= (c = *s++) && c <= '9')
1417 num = num*10 + (c - '0');
1418 if (c == '\0')
1419 break;
1420 }
1421 else
1422 num = 1;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001423
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001424 e = getentry(c, f);
Tim Petersc2b550e2006-05-31 14:28:07 +00001425
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001426 size = align(size, c, e);
1427 if (c == 's' || c == 'p') {
1428 codes->offset = size;
1429 codes->size = num;
1430 codes->fmtdef = e;
1431 codes++;
1432 size += num;
1433 } else if (c == 'x') {
1434 size += num;
1435 } else {
1436 while (--num >= 0) {
1437 codes->offset = size;
1438 codes->size = e->size;
1439 codes->fmtdef = e;
1440 codes++;
1441 size += e->size;
1442 }
1443 }
1444 }
1445 codes->fmtdef = NULL;
1446 codes->offset = size;
1447 codes->size = 0;
Tim Petersc2b550e2006-05-31 14:28:07 +00001448
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001449 return 0;
Mark Dickinson38b4a892010-06-12 08:49:42 +00001450
1451 overflow:
1452 PyErr_SetString(StructError,
1453 "total struct size too long");
1454 return -1;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001455}
1456
1457static PyObject *
1458s_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1459{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001460 PyObject *self;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001461
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001462 assert(type != NULL && type->tp_alloc != NULL);
Bob Ippolito232f3c92006-05-23 19:12:41 +00001463
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001464 self = type->tp_alloc(type, 0);
1465 if (self != NULL) {
1466 PyStructObject *s = (PyStructObject*)self;
1467 Py_INCREF(Py_None);
1468 s->s_format = Py_None;
1469 s->s_codes = NULL;
1470 s->s_size = -1;
1471 s->s_len = -1;
1472 }
1473 return self;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001474}
1475
1476static int
1477s_init(PyObject *self, PyObject *args, PyObject *kwds)
1478{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001479 PyStructObject *soself = (PyStructObject *)self;
1480 PyObject *o_format = NULL;
1481 int ret = 0;
1482 static char *kwlist[] = {"format", 0};
Bob Ippolito232f3c92006-05-23 19:12:41 +00001483
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001484 assert(PyStruct_Check(self));
Bob Ippolito232f3c92006-05-23 19:12:41 +00001485
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001486 if (!PyArg_ParseTupleAndKeywords(args, kwds, "S:Struct", kwlist,
1487 &o_format))
1488 return -1;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001489
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001490 Py_INCREF(o_format);
1491 Py_CLEAR(soself->s_format);
1492 soself->s_format = o_format;
Tim Petersc2b550e2006-05-31 14:28:07 +00001493
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001494 ret = prepare_s(soself);
1495 return ret;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001496}
1497
1498static void
1499s_dealloc(PyStructObject *s)
1500{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001501 if (s->weakreflist != NULL)
1502 PyObject_ClearWeakRefs((PyObject *)s);
1503 if (s->s_codes != NULL) {
1504 PyMem_FREE(s->s_codes);
1505 }
1506 Py_XDECREF(s->s_format);
1507 Py_TYPE(s)->tp_free((PyObject *)s);
Bob Ippolito232f3c92006-05-23 19:12:41 +00001508}
1509
Bob Ippolitoeb621272006-05-24 15:32:06 +00001510static PyObject *
1511s_unpack_internal(PyStructObject *soself, char *startfrom) {
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001512 formatcode *code;
1513 Py_ssize_t i = 0;
1514 PyObject *result = PyTuple_New(soself->s_len);
1515 if (result == NULL)
1516 return NULL;
Bob Ippolitoeb621272006-05-24 15:32:06 +00001517
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001518 for (code = soself->s_codes; code->fmtdef != NULL; code++) {
1519 PyObject *v;
1520 const formatdef *e = code->fmtdef;
1521 const char *res = startfrom + code->offset;
1522 if (e->format == 's') {
1523 v = PyString_FromStringAndSize(res, code->size);
1524 } else if (e->format == 'p') {
1525 Py_ssize_t n = *(unsigned char*)res;
1526 if (n >= code->size)
1527 n = code->size - 1;
1528 v = PyString_FromStringAndSize(res + 1, n);
1529 } else {
1530 v = e->unpack(res, e);
1531 }
1532 if (v == NULL)
1533 goto fail;
1534 PyTuple_SET_ITEM(result, i++, v);
1535 }
Bob Ippolitoeb621272006-05-24 15:32:06 +00001536
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001537 return result;
Bob Ippolitoeb621272006-05-24 15:32:06 +00001538fail:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001539 Py_DECREF(result);
1540 return NULL;
Bob Ippolitocd51ca52006-05-27 15:53:49 +00001541}
Bob Ippolitoeb621272006-05-24 15:32:06 +00001542
1543
Bob Ippolito232f3c92006-05-23 19:12:41 +00001544PyDoc_STRVAR(s_unpack__doc__,
Bob Ippolito1fcdc232006-05-27 12:11:36 +00001545"S.unpack(str) -> (v1, v2, ...)\n\
Bob Ippolito232f3c92006-05-23 19:12:41 +00001546\n\
1547Return tuple containing values unpacked according to this Struct's format.\n\
1548Requires len(str) == self.size. See struct.__doc__ for more on format\n\
1549strings.");
1550
1551static PyObject *
1552s_unpack(PyObject *self, PyObject *inputstr)
1553{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001554 char *start;
1555 Py_ssize_t len;
1556 PyObject *args=NULL, *result;
1557 PyStructObject *soself = (PyStructObject *)self;
1558 assert(PyStruct_Check(self));
1559 assert(soself->s_codes != NULL);
1560 if (inputstr == NULL)
1561 goto fail;
1562 if (PyString_Check(inputstr) &&
1563 PyString_GET_SIZE(inputstr) == soself->s_size) {
1564 return s_unpack_internal(soself, PyString_AS_STRING(inputstr));
1565 }
1566 args = PyTuple_Pack(1, inputstr);
1567 if (args == NULL)
1568 return NULL;
1569 if (!PyArg_ParseTuple(args, "s#:unpack", &start, &len))
1570 goto fail;
1571 if (soself->s_size != len)
1572 goto fail;
1573 result = s_unpack_internal(soself, start);
1574 Py_DECREF(args);
1575 return result;
Raymond Hettinger7a3d41f2007-04-05 18:00:03 +00001576
1577fail:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001578 Py_XDECREF(args);
1579 PyErr_Format(StructError,
1580 "unpack requires a string argument of length %zd",
1581 soself->s_size);
1582 return NULL;
Bob Ippolitoeb621272006-05-24 15:32:06 +00001583}
1584
1585PyDoc_STRVAR(s_unpack_from__doc__,
Bob Ippolito1fcdc232006-05-27 12:11:36 +00001586"S.unpack_from(buffer[, offset]) -> (v1, v2, ...)\n\
Bob Ippolitoeb621272006-05-24 15:32:06 +00001587\n\
1588Return tuple containing values unpacked according to this Struct's format.\n\
1589Unlike unpack, unpack_from can unpack values from any object supporting\n\
1590the buffer API, not just str. Requires len(buffer[offset:]) >= self.size.\n\
1591See struct.__doc__ for more on format strings.");
1592
1593static PyObject *
1594s_unpack_from(PyObject *self, PyObject *args, PyObject *kwds)
1595{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001596 static char *kwlist[] = {"buffer", "offset", 0};
Bob Ippolitoeb621272006-05-24 15:32:06 +00001597#if (PY_VERSION_HEX < 0x02050000)
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001598 static char *fmt = "z#|i:unpack_from";
Bob Ippolitoeb621272006-05-24 15:32:06 +00001599#else
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001600 static char *fmt = "z#|n:unpack_from";
Bob Ippolitoeb621272006-05-24 15:32:06 +00001601#endif
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001602 Py_ssize_t buffer_len = 0, offset = 0;
1603 char *buffer = NULL;
1604 PyStructObject *soself = (PyStructObject *)self;
1605 assert(PyStruct_Check(self));
1606 assert(soself->s_codes != NULL);
Bob Ippolitoeb621272006-05-24 15:32:06 +00001607
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001608 if (!PyArg_ParseTupleAndKeywords(args, kwds, fmt, kwlist,
1609 &buffer, &buffer_len, &offset))
1610 return NULL;
Bob Ippolitoeb621272006-05-24 15:32:06 +00001611
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001612 if (buffer == NULL) {
1613 PyErr_Format(StructError,
1614 "unpack_from requires a buffer argument");
1615 return NULL;
1616 }
Tim Petersc2b550e2006-05-31 14:28:07 +00001617
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001618 if (offset < 0)
1619 offset += buffer_len;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001620
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001621 if (offset < 0 || (buffer_len - offset) < soself->s_size) {
1622 PyErr_Format(StructError,
1623 "unpack_from requires a buffer of at least %zd bytes",
1624 soself->s_size);
1625 return NULL;
1626 }
1627 return s_unpack_internal(soself, buffer + offset);
Bob Ippolitoeb621272006-05-24 15:32:06 +00001628}
Bob Ippolito232f3c92006-05-23 19:12:41 +00001629
Bob Ippolito232f3c92006-05-23 19:12:41 +00001630
Martin Blais2856e5f2006-05-26 12:03:27 +00001631/*
1632 * Guts of the pack function.
1633 *
1634 * Takes a struct object, a tuple of arguments, and offset in that tuple of
1635 * argument for where to start processing the arguments for packing, and a
1636 * character buffer for writing the packed string. The caller must insure
1637 * that the buffer may contain the required length for packing the arguments.
1638 * 0 is returned on success, 1 is returned if there is an error.
1639 *
1640 */
1641static int
1642s_pack_internal(PyStructObject *soself, PyObject *args, int offset, char* buf)
Bob Ippolito232f3c92006-05-23 19:12:41 +00001643{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001644 formatcode *code;
1645 /* XXX(nnorwitz): why does i need to be a local? can we use
1646 the offset parameter or do we need the wider width? */
1647 Py_ssize_t i;
Martin Blais2856e5f2006-05-26 12:03:27 +00001648
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001649 memset(buf, '\0', soself->s_size);
1650 i = offset;
1651 for (code = soself->s_codes; code->fmtdef != NULL; code++) {
1652 Py_ssize_t n;
1653 PyObject *v = PyTuple_GET_ITEM(args, i++);
1654 const formatdef *e = code->fmtdef;
1655 char *res = buf + code->offset;
1656 if (e->format == 's') {
1657 if (!PyString_Check(v)) {
1658 PyErr_SetString(StructError,
1659 "argument for 's' must be a string");
1660 return -1;
1661 }
1662 n = PyString_GET_SIZE(v);
1663 if (n > code->size)
1664 n = code->size;
1665 if (n > 0)
1666 memcpy(res, PyString_AS_STRING(v), n);
1667 } else if (e->format == 'p') {
1668 if (!PyString_Check(v)) {
1669 PyErr_SetString(StructError,
1670 "argument for 'p' must be a string");
1671 return -1;
1672 }
1673 n = PyString_GET_SIZE(v);
1674 if (n > (code->size - 1))
1675 n = code->size - 1;
1676 if (n > 0)
1677 memcpy(res + 1, PyString_AS_STRING(v), n);
1678 if (n > 255)
1679 n = 255;
1680 *res = Py_SAFE_DOWNCAST(n, Py_ssize_t, unsigned char);
1681 } else {
1682 if (e->pack(res, v, e) < 0) {
1683 if (PyLong_Check(v) && PyErr_ExceptionMatches(PyExc_OverflowError))
1684 PyErr_SetString(StructError,
1685 "long too large to convert to int");
1686 return -1;
1687 }
1688 }
1689 }
Tim Petersc2b550e2006-05-31 14:28:07 +00001690
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001691 /* Success */
1692 return 0;
Martin Blais2856e5f2006-05-26 12:03:27 +00001693}
Bob Ippolito232f3c92006-05-23 19:12:41 +00001694
Martin Blais2856e5f2006-05-26 12:03:27 +00001695
1696PyDoc_STRVAR(s_pack__doc__,
Bob Ippolito1fcdc232006-05-27 12:11:36 +00001697"S.pack(v1, v2, ...) -> string\n\
Martin Blais2856e5f2006-05-26 12:03:27 +00001698\n\
1699Return a string containing values v1, v2, ... packed according to this\n\
1700Struct's format. See struct.__doc__ for more on format strings.");
1701
1702static PyObject *
1703s_pack(PyObject *self, PyObject *args)
1704{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001705 PyStructObject *soself;
1706 PyObject *result;
Martin Blais2856e5f2006-05-26 12:03:27 +00001707
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001708 /* Validate arguments. */
1709 soself = (PyStructObject *)self;
1710 assert(PyStruct_Check(self));
1711 assert(soself->s_codes != NULL);
1712 if (PyTuple_GET_SIZE(args) != soself->s_len)
1713 {
1714 PyErr_Format(StructError,
1715 "pack requires exactly %zd arguments", soself->s_len);
1716 return NULL;
1717 }
Tim Petersc2b550e2006-05-31 14:28:07 +00001718
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001719 /* Allocate a new string */
1720 result = PyString_FromStringAndSize((char *)NULL, soself->s_size);
1721 if (result == NULL)
1722 return NULL;
Tim Petersc2b550e2006-05-31 14:28:07 +00001723
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001724 /* Call the guts */
1725 if ( s_pack_internal(soself, args, 0, PyString_AS_STRING(result)) != 0 ) {
1726 Py_DECREF(result);
1727 return NULL;
1728 }
Martin Blais2856e5f2006-05-26 12:03:27 +00001729
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001730 return result;
Martin Blais2856e5f2006-05-26 12:03:27 +00001731}
1732
Martin Blaisaf2ae722006-06-04 13:49:49 +00001733PyDoc_STRVAR(s_pack_into__doc__,
1734"S.pack_into(buffer, offset, v1, v2, ...)\n\
Martin Blais2856e5f2006-05-26 12:03:27 +00001735\n\
Martin Blaisaf2ae722006-06-04 13:49:49 +00001736Pack the values v1, v2, ... according to this Struct's format, write \n\
Bob Ippolito1fcdc232006-05-27 12:11:36 +00001737the packed bytes into the writable buffer buf starting at offset. Note\n\
1738that the offset is not an optional argument. See struct.__doc__ for \n\
Martin Blais2856e5f2006-05-26 12:03:27 +00001739more on format strings.");
1740
1741static PyObject *
Martin Blaisaf2ae722006-06-04 13:49:49 +00001742s_pack_into(PyObject *self, PyObject *args)
Martin Blais2856e5f2006-05-26 12:03:27 +00001743{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001744 PyStructObject *soself;
1745 char *buffer;
1746 Py_ssize_t buffer_len, offset;
Martin Blais2856e5f2006-05-26 12:03:27 +00001747
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001748 /* Validate arguments. +1 is for the first arg as buffer. */
1749 soself = (PyStructObject *)self;
1750 assert(PyStruct_Check(self));
1751 assert(soself->s_codes != NULL);
1752 if (PyTuple_GET_SIZE(args) != (soself->s_len + 2))
1753 {
1754 PyErr_Format(StructError,
1755 "pack_into requires exactly %zd arguments",
1756 (soself->s_len + 2));
1757 return NULL;
1758 }
Martin Blais2856e5f2006-05-26 12:03:27 +00001759
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001760 /* Extract a writable memory buffer from the first argument */
1761 if ( PyObject_AsWriteBuffer(PyTuple_GET_ITEM(args, 0),
1762 (void**)&buffer, &buffer_len) == -1 ) {
1763 return NULL;
1764 }
1765 assert( buffer_len >= 0 );
Martin Blais2856e5f2006-05-26 12:03:27 +00001766
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001767 /* Extract the offset from the first argument */
1768 offset = PyInt_AsSsize_t(PyTuple_GET_ITEM(args, 1));
1769 if (offset == -1 && PyErr_Occurred())
1770 return NULL;
Martin Blais2856e5f2006-05-26 12:03:27 +00001771
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001772 /* Support negative offsets. */
1773 if (offset < 0)
1774 offset += buffer_len;
Martin Blais2856e5f2006-05-26 12:03:27 +00001775
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001776 /* Check boundaries */
1777 if (offset < 0 || (buffer_len - offset) < soself->s_size) {
1778 PyErr_Format(StructError,
1779 "pack_into requires a buffer of at least %zd bytes",
1780 soself->s_size);
1781 return NULL;
1782 }
Tim Petersc2b550e2006-05-31 14:28:07 +00001783
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001784 /* Call the guts */
1785 if ( s_pack_internal(soself, args, 2, buffer + offset) != 0 ) {
1786 return NULL;
1787 }
Martin Blais2856e5f2006-05-26 12:03:27 +00001788
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001789 Py_RETURN_NONE;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001790}
1791
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001792static PyObject *
1793s_get_format(PyStructObject *self, void *unused)
1794{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001795 Py_INCREF(self->s_format);
1796 return self->s_format;
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001797}
1798
1799static PyObject *
1800s_get_size(PyStructObject *self, void *unused)
1801{
1802 return PyInt_FromSsize_t(self->s_size);
1803}
Bob Ippolito232f3c92006-05-23 19:12:41 +00001804
1805/* List of functions */
1806
1807static struct PyMethodDef s_methods[] = {
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001808 {"pack", s_pack, METH_VARARGS, s_pack__doc__},
1809 {"pack_into", s_pack_into, METH_VARARGS, s_pack_into__doc__},
1810 {"unpack", s_unpack, METH_O, s_unpack__doc__},
1811 {"unpack_from", (PyCFunction)s_unpack_from, METH_VARARGS|METH_KEYWORDS,
1812 s_unpack_from__doc__},
1813 {NULL, NULL} /* sentinel */
Bob Ippolito232f3c92006-05-23 19:12:41 +00001814};
1815
1816PyDoc_STRVAR(s__doc__, "Compiled struct object");
1817
1818#define OFF(x) offsetof(PyStructObject, x)
1819
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001820static PyGetSetDef s_getsetlist[] = {
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001821 {"format", (getter)s_get_format, (setter)NULL, "struct format string", NULL},
1822 {"size", (getter)s_get_size, (setter)NULL, "struct size in bytes", NULL},
1823 {NULL} /* sentinel */
Bob Ippolito232f3c92006-05-23 19:12:41 +00001824};
1825
Bob Ippolito232f3c92006-05-23 19:12:41 +00001826static
1827PyTypeObject PyStructType = {
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001828 PyVarObject_HEAD_INIT(NULL, 0)
1829 "Struct",
1830 sizeof(PyStructObject),
1831 0,
1832 (destructor)s_dealloc, /* tp_dealloc */
1833 0, /* tp_print */
1834 0, /* tp_getattr */
1835 0, /* tp_setattr */
1836 0, /* tp_compare */
1837 0, /* tp_repr */
1838 0, /* tp_as_number */
1839 0, /* tp_as_sequence */
1840 0, /* tp_as_mapping */
1841 0, /* tp_hash */
1842 0, /* tp_call */
1843 0, /* tp_str */
1844 PyObject_GenericGetAttr, /* tp_getattro */
1845 PyObject_GenericSetAttr, /* tp_setattro */
1846 0, /* tp_as_buffer */
1847 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_WEAKREFS,/* tp_flags */
1848 s__doc__, /* tp_doc */
1849 0, /* tp_traverse */
1850 0, /* tp_clear */
1851 0, /* tp_richcompare */
1852 offsetof(PyStructObject, weakreflist), /* tp_weaklistoffset */
1853 0, /* tp_iter */
1854 0, /* tp_iternext */
1855 s_methods, /* tp_methods */
1856 NULL, /* tp_members */
1857 s_getsetlist, /* tp_getset */
1858 0, /* tp_base */
1859 0, /* tp_dict */
1860 0, /* tp_descr_get */
1861 0, /* tp_descr_set */
1862 0, /* tp_dictoffset */
1863 s_init, /* tp_init */
1864 PyType_GenericAlloc,/* tp_alloc */
1865 s_new, /* tp_new */
1866 PyObject_Del, /* tp_free */
Bob Ippolito232f3c92006-05-23 19:12:41 +00001867};
1868
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001869
1870/* ---- Standalone functions ---- */
1871
1872#define MAXCACHE 100
Christian Heimes76d19f62008-01-04 02:54:42 +00001873static PyObject *cache = NULL;
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001874
1875static PyObject *
1876cache_struct(PyObject *fmt)
1877{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001878 PyObject * s_object;
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001879
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001880 if (cache == NULL) {
1881 cache = PyDict_New();
1882 if (cache == NULL)
1883 return NULL;
1884 }
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001885
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001886 s_object = PyDict_GetItem(cache, fmt);
1887 if (s_object != NULL) {
1888 Py_INCREF(s_object);
1889 return s_object;
1890 }
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001891
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001892 s_object = PyObject_CallFunctionObjArgs((PyObject *)(&PyStructType), fmt, NULL);
1893 if (s_object != NULL) {
1894 if (PyDict_Size(cache) >= MAXCACHE)
1895 PyDict_Clear(cache);
1896 /* Attempt to cache the result */
1897 if (PyDict_SetItem(cache, fmt, s_object) == -1)
1898 PyErr_Clear();
1899 }
1900 return s_object;
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001901}
1902
Christian Heimes76d19f62008-01-04 02:54:42 +00001903PyDoc_STRVAR(clearcache_doc,
1904"Clear the internal cache.");
1905
1906static PyObject *
1907clearcache(PyObject *self)
1908{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001909 Py_CLEAR(cache);
1910 Py_RETURN_NONE;
Christian Heimes76d19f62008-01-04 02:54:42 +00001911}
1912
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001913PyDoc_STRVAR(calcsize_doc,
1914"Return size of C struct described by format string fmt.");
1915
1916static PyObject *
1917calcsize(PyObject *self, PyObject *fmt)
1918{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001919 Py_ssize_t n;
1920 PyObject *s_object = cache_struct(fmt);
1921 if (s_object == NULL)
1922 return NULL;
1923 n = ((PyStructObject *)s_object)->s_size;
1924 Py_DECREF(s_object);
1925 return PyInt_FromSsize_t(n);
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001926}
1927
1928PyDoc_STRVAR(pack_doc,
1929"Return string containing values v1, v2, ... packed according to fmt.");
1930
1931static PyObject *
1932pack(PyObject *self, PyObject *args)
1933{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001934 PyObject *s_object, *fmt, *newargs, *result;
1935 Py_ssize_t n = PyTuple_GET_SIZE(args);
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001936
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001937 if (n == 0) {
1938 PyErr_SetString(PyExc_TypeError, "missing format argument");
1939 return NULL;
1940 }
1941 fmt = PyTuple_GET_ITEM(args, 0);
1942 newargs = PyTuple_GetSlice(args, 1, n);
1943 if (newargs == NULL)
1944 return NULL;
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001945
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001946 s_object = cache_struct(fmt);
1947 if (s_object == NULL) {
1948 Py_DECREF(newargs);
1949 return NULL;
1950 }
1951 result = s_pack(s_object, newargs);
1952 Py_DECREF(newargs);
1953 Py_DECREF(s_object);
1954 return result;
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001955}
1956
1957PyDoc_STRVAR(pack_into_doc,
1958"Pack the values v1, v2, ... according to fmt.\n\
1959Write the packed bytes into the writable buffer buf starting at offset.");
1960
1961static PyObject *
1962pack_into(PyObject *self, PyObject *args)
1963{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001964 PyObject *s_object, *fmt, *newargs, *result;
1965 Py_ssize_t n = PyTuple_GET_SIZE(args);
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001966
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001967 if (n == 0) {
1968 PyErr_SetString(PyExc_TypeError, "missing format argument");
1969 return NULL;
1970 }
1971 fmt = PyTuple_GET_ITEM(args, 0);
1972 newargs = PyTuple_GetSlice(args, 1, n);
1973 if (newargs == NULL)
1974 return NULL;
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001975
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001976 s_object = cache_struct(fmt);
1977 if (s_object == NULL) {
1978 Py_DECREF(newargs);
1979 return NULL;
1980 }
1981 result = s_pack_into(s_object, newargs);
1982 Py_DECREF(newargs);
1983 Py_DECREF(s_object);
1984 return result;
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001985}
1986
1987PyDoc_STRVAR(unpack_doc,
1988"Unpack the string containing packed C structure data, according to fmt.\n\
1989Requires len(string) == calcsize(fmt).");
1990
1991static PyObject *
1992unpack(PyObject *self, PyObject *args)
1993{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001994 PyObject *s_object, *fmt, *inputstr, *result;
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001995
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001996 if (!PyArg_UnpackTuple(args, "unpack", 2, 2, &fmt, &inputstr))
1997 return NULL;
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001998
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001999 s_object = cache_struct(fmt);
2000 if (s_object == NULL)
2001 return NULL;
2002 result = s_unpack(s_object, inputstr);
2003 Py_DECREF(s_object);
2004 return result;
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00002005}
2006
2007PyDoc_STRVAR(unpack_from_doc,
2008"Unpack the buffer, containing packed C structure data, according to\n\
2009fmt, starting at offset. Requires len(buffer[offset:]) >= calcsize(fmt).");
2010
2011static PyObject *
2012unpack_from(PyObject *self, PyObject *args, PyObject *kwds)
2013{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002014 PyObject *s_object, *fmt, *newargs, *result;
2015 Py_ssize_t n = PyTuple_GET_SIZE(args);
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00002016
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002017 if (n == 0) {
2018 PyErr_SetString(PyExc_TypeError, "missing format argument");
2019 return NULL;
2020 }
2021 fmt = PyTuple_GET_ITEM(args, 0);
2022 newargs = PyTuple_GetSlice(args, 1, n);
2023 if (newargs == NULL)
2024 return NULL;
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00002025
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002026 s_object = cache_struct(fmt);
2027 if (s_object == NULL) {
2028 Py_DECREF(newargs);
2029 return NULL;
2030 }
2031 result = s_unpack_from(s_object, newargs, kwds);
2032 Py_DECREF(newargs);
2033 Py_DECREF(s_object);
2034 return result;
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00002035}
2036
2037static struct PyMethodDef module_functions[] = {
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002038 {"_clearcache", (PyCFunction)clearcache, METH_NOARGS, clearcache_doc},
2039 {"calcsize", calcsize, METH_O, calcsize_doc},
2040 {"pack", pack, METH_VARARGS, pack_doc},
2041 {"pack_into", pack_into, METH_VARARGS, pack_into_doc},
2042 {"unpack", unpack, METH_VARARGS, unpack_doc},
2043 {"unpack_from", (PyCFunction)unpack_from,
2044 METH_VARARGS|METH_KEYWORDS, unpack_from_doc},
2045 {NULL, NULL} /* sentinel */
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00002046};
2047
2048
Bob Ippolito232f3c92006-05-23 19:12:41 +00002049/* Module initialization */
2050
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00002051PyDoc_STRVAR(module_doc,
Mark Dickinson9b125532009-10-27 17:00:03 +00002052"Functions to convert between Python values and C structs represented\n\
2053as Python strings. It uses format strings (explained below) as compact\n\
2054descriptions of the lay-out of the C structs and the intended conversion\n\
2055to/from Python values.\n\
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00002056\n\
2057The optional first format char indicates byte order, size and alignment:\n\
Mark Dickinson9b125532009-10-27 17:00:03 +00002058 @: native order, size & alignment (default)\n\
2059 =: native order, std. size & alignment\n\
2060 <: little-endian, std. size & alignment\n\
2061 >: big-endian, std. size & alignment\n\
2062 !: same as >\n\
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00002063\n\
2064The remaining chars indicate types of args and must match exactly;\n\
2065these can be preceded by a decimal repeat count:\n\
2066 x: pad byte (no data); c:char; b:signed byte; B:unsigned byte;\n\
Mark Dickinson9b125532009-10-27 17:00:03 +00002067 ?: _Bool (requires C99; if not available, char is used instead)\n\
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00002068 h:short; H:unsigned short; i:int; I:unsigned int;\n\
2069 l:long; L:unsigned long; f:float; d:double.\n\
2070Special cases (preceding decimal count indicates length):\n\
2071 s:string (array of char); p: pascal string (with count byte).\n\
2072Special case (only available in native format):\n\
2073 P:an integer type that is wide enough to hold a pointer.\n\
2074Special case (not in native mode unless 'long long' in platform C):\n\
2075 q:long long; Q:unsigned long long\n\
2076Whitespace between formats is ignored.\n\
2077\n\
2078The variable struct.error is an exception raised on errors.\n");
2079
Bob Ippolito232f3c92006-05-23 19:12:41 +00002080PyMODINIT_FUNC
2081init_struct(void)
2082{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002083 PyObject *ver, *m;
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00002084
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002085 ver = PyString_FromString("0.2");
2086 if (ver == NULL)
2087 return;
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00002088
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002089 m = Py_InitModule3("_struct", module_functions, module_doc);
2090 if (m == NULL)
2091 return;
Bob Ippolito232f3c92006-05-23 19:12:41 +00002092
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002093 Py_TYPE(&PyStructType) = &PyType_Type;
2094 if (PyType_Ready(&PyStructType) < 0)
2095 return;
Bob Ippolito3fc2bb92006-05-25 19:03:19 +00002096
Bob Ippolito4182a752006-05-30 17:37:54 +00002097#ifdef PY_STRUCT_OVERFLOW_MASKING
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002098 if (pyint_zero == NULL) {
2099 pyint_zero = PyInt_FromLong(0);
2100 if (pyint_zero == NULL)
2101 return;
2102 }
2103 if (pylong_ulong_mask == NULL) {
Bob Ippolito2fd39772006-05-29 22:55:48 +00002104#if (SIZEOF_LONG == 4)
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002105 pylong_ulong_mask = PyLong_FromString("FFFFFFFF", NULL, 16);
Bob Ippolito2fd39772006-05-29 22:55:48 +00002106#else
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002107 pylong_ulong_mask = PyLong_FromString("FFFFFFFFFFFFFFFF", NULL, 16);
Bob Ippolito2fd39772006-05-29 22:55:48 +00002108#endif
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002109 if (pylong_ulong_mask == NULL)
2110 return;
2111 }
Bob Ippolito2fd39772006-05-29 22:55:48 +00002112
Tim Petersc2b550e2006-05-31 14:28:07 +00002113#else
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002114 /* This speed trick can't be used until overflow masking goes away, because
2115 native endian always raises exceptions instead of overflow masking. */
Tim Petersc2b550e2006-05-31 14:28:07 +00002116
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002117 /* Check endian and swap in faster functions */
2118 {
2119 int one = 1;
2120 formatdef *native = native_table;
2121 formatdef *other, *ptr;
2122 if ((int)*(unsigned char*)&one)
2123 other = lilendian_table;
2124 else
2125 other = bigendian_table;
2126 /* Scan through the native table, find a matching
2127 entry in the endian table and swap in the
2128 native implementations whenever possible
2129 (64-bit platforms may not have "standard" sizes) */
2130 while (native->format != '\0' && other->format != '\0') {
2131 ptr = other;
2132 while (ptr->format != '\0') {
2133 if (ptr->format == native->format) {
2134 /* Match faster when formats are
2135 listed in the same order */
2136 if (ptr == other)
2137 other++;
2138 /* Only use the trick if the
2139 size matches */
2140 if (ptr->size != native->size)
2141 break;
2142 /* Skip float and double, could be
2143 "unknown" float format */
2144 if (ptr->format == 'd' || ptr->format == 'f')
2145 break;
2146 ptr->pack = native->pack;
2147 ptr->unpack = native->unpack;
2148 break;
2149 }
2150 ptr++;
2151 }
2152 native++;
2153 }
2154 }
Bob Ippolito2fd39772006-05-29 22:55:48 +00002155#endif
Tim Petersc2b550e2006-05-31 14:28:07 +00002156
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002157 /* Add some symbolic constants to the module */
2158 if (StructError == NULL) {
2159 StructError = PyErr_NewException("struct.error", NULL, NULL);
2160 if (StructError == NULL)
2161 return;
2162 }
Bob Ippolito04ab9942006-05-25 19:33:38 +00002163
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002164 Py_INCREF(StructError);
2165 PyModule_AddObject(m, "error", StructError);
Bob Ippolito04ab9942006-05-25 19:33:38 +00002166
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002167 Py_INCREF((PyObject*)&PyStructType);
2168 PyModule_AddObject(m, "Struct", (PyObject*)&PyStructType);
Tim Petersc2b550e2006-05-31 14:28:07 +00002169
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002170 PyModule_AddObject(m, "__version__", ver);
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00002171
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002172 PyModule_AddIntConstant(m, "_PY_STRUCT_RANGE_CHECKING", 1);
Bob Ippolito4182a752006-05-30 17:37:54 +00002173#ifdef PY_STRUCT_OVERFLOW_MASKING
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002174 PyModule_AddIntConstant(m, "_PY_STRUCT_OVERFLOW_MASKING", 1);
Bob Ippolito2fd39772006-05-29 22:55:48 +00002175#endif
Bob Ippolitoe6c9f982006-08-04 23:59:21 +00002176#ifdef PY_STRUCT_FLOAT_COERCE
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002177 PyModule_AddIntConstant(m, "_PY_STRUCT_FLOAT_COERCE", 1);
Bob Ippolitoe6c9f982006-08-04 23:59:21 +00002178#endif
2179
Bob Ippolito232f3c92006-05-23 19:12:41 +00002180}