blob: d924cad63b9f3c43d533da947c2a4012d1a060d0 [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 {
47 char format;
Bob Ippolitoaa70a172006-05-26 20:25:23 +000048 Py_ssize_t size;
49 Py_ssize_t alignment;
Bob Ippolito232f3c92006-05-23 19:12:41 +000050 PyObject* (*unpack)(const char *,
51 const struct _formatdef *);
52 int (*pack)(char *, PyObject *,
53 const struct _formatdef *);
54} formatdef;
55
56typedef struct _formatcode {
57 const struct _formatdef *fmtdef;
Bob Ippolitoaa70a172006-05-26 20:25:23 +000058 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 {
65 PyObject_HEAD
Bob Ippolitoaa70a172006-05-26 20:25:23 +000066 Py_ssize_t s_size;
67 Py_ssize_t s_len;
Bob Ippolito232f3c92006-05-23 19:12:41 +000068 formatcode *s_codes;
69 PyObject *s_format;
70 PyObject *weakreflist; /* List of weak references */
71} 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{
127 PyNumberMethods *m;
128
129 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 }
Christian Heimese93237d2007-12-19 02:37:44 +0000136 m = Py_TYPE(v)->tp_as_number;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000137 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;
148}
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{
156 long x = PyInt_AsLong(v);
157 if (x == -1 && PyErr_Occurred()) {
Bob Ippolitoe6c9f982006-08-04 23:59:21 +0000158#ifdef PY_STRUCT_FLOAT_COERCE
159 if (PyFloat_Check(v)) {
160 PyObject *o;
161 int res;
162 PyErr_Clear();
Mark Dickinsone9a5a542010-04-06 15:19:40 +0000163 if (PyErr_WarnEx(PyExc_DeprecationWarning, FLOAT_COERCE, 1) < 0)
Bob Ippolitoe6c9f982006-08-04 23:59:21 +0000164 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 }
172#endif
Bob Ippolito232f3c92006-05-23 19:12:41 +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;
180}
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{
190 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 }
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000197 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;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000203 }
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000204 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{
216 PY_LONG_LONG x;
217
218 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;
228}
229
230/* Same, but handling native unsigned long long. */
231
232static int
233get_ulonglong(PyObject *v, unsigned PY_LONG_LONG *p)
234{
235 unsigned PY_LONG_LONG x;
236
237 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;
247}
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{
261 if (get_long(v, p) < 0) {
Neal Norwitz3c5431e2006-06-11 05:45:25 +0000262 if (PyLong_Check(v) &&
263 PyErr_ExceptionMatches(PyExc_OverflowError)) {
Bob Ippolito2fd39772006-05-29 22:55:48 +0000264 PyObject *wrapped;
265 long x;
266 PyErr_Clear();
Bob Ippolitoe6c9f982006-08-04 23:59:21 +0000267#ifdef PY_STRUCT_FLOAT_COERCE
268 if (PyFloat_Check(v)) {
269 PyObject *o;
270 int res;
271 PyErr_Clear();
Mark Dickinsone9a5a542010-04-06 15:19:40 +0000272 if (PyErr_WarnEx(PyExc_DeprecationWarning, FLOAT_COERCE, 1) < 0)
Bob Ippolitoe6c9f982006-08-04 23:59:21 +0000273 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 }
281#endif
Mark Dickinsone9a5a542010-04-06 15:19:40 +0000282 if (PyErr_WarnEx(PyExc_DeprecationWarning, INT_OVERFLOW, 1) < 0)
Bob Ippolito2fd39772006-05-29 22:55:48 +0000283 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;
297}
298
299static int
300get_wrapped_ulong(PyObject *v, unsigned long *p)
301{
302 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
307 if (PyFloat_Check(v)) {
308 PyObject *o;
309 int res;
310 PyErr_Clear();
Mark Dickinsone9a5a542010-04-06 15:19:40 +0000311 if (PyErr_WarnEx(PyExc_DeprecationWarning, FLOAT_COERCE, 1) < 0)
Bob Ippolitoe6c9f982006-08-04 23:59:21 +0000312 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 }
320#endif
Bob Ippolito2fd39772006-05-29 22:55:48 +0000321 wrapped = PyNumber_And(v, pylong_ulong_mask);
322 if (wrapped == NULL)
323 return -1;
Mark Dickinsone9a5a542010-04-06 15:19:40 +0000324 if (PyErr_WarnEx(PyExc_DeprecationWarning, INT_OVERFLOW, 1) < 0) {
Bob Ippolito2fd39772006-05-29 22:55:48 +0000325 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;
335}
336
337#define RANGE_ERROR(x, f, flag, mask) \
338 do { \
339 if (_range_error(f, flag) < 0) \
340 return -1; \
341 else \
342 (x) &= (mask); \
343 } while (0)
344
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 */
357 int le) /* true for little-endian, false for big-endian */
358{
359 double x;
360
361 x = _PyFloat_Unpack4((unsigned char *)p, le);
362 if (x == -1.0 && PyErr_Occurred())
363 return NULL;
364 return PyFloat_FromDouble(x);
365}
366
367static PyObject *
368unpack_double(const char *p, /* start of 8-byte string */
369 int le) /* true for little-endian, false for big-endian */
370{
371 double x;
372
373 x = _PyFloat_Unpack8((unsigned char *)p, le);
374 if (x == -1.0 && PyErr_Occurred())
375 return NULL;
376 return PyFloat_FromDouble(x);
377}
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{
Tim Petersd6a6f022006-05-31 15:33:22 +0000383 /* ulargest is the largest unsigned value with f->size bytes.
384 * Note that the simpler:
385 * ((size_t)1 << (f->size * 8)) - 1
Tim Peters72270c22006-05-31 15:34:37 +0000386 * 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.
Tim Petersd6a6f022006-05-31 15:33:22 +0000390 */
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)
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000394 PyErr_Format(StructError,
Neal Norwitz971ea112006-05-31 07:43:27 +0000395 "'%c' format requires 0 <= number <= %zu",
Bob Ippolito28b26862006-05-29 15:47:29 +0000396 f->format,
Tim Petersd6a6f022006-05-31 15:33:22 +0000397 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,
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000404 largest);
405 }
Bob Ippolito4182a752006-05-30 17:37:54 +0000406#ifdef PY_STRUCT_OVERFLOW_MASKING
Bob Ippolito2fd39772006-05-29 22:55:48 +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;
Neal Norwitz07aadb12006-07-30 06:55:48 +0000419 rval = PyErr_WarnEx(PyExc_DeprecationWarning,
Mark Dickinsone9a5a542010-04-06 15:19:40 +0000420 PyString_AS_STRING(msg), 1);
Bob Ippolito2fd39772006-05-29 22:55:48 +0000421 Py_DECREF(msg);
422 if (rval == 0)
423 return 0;
424 }
425#endif
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000426 return -1;
427}
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{
Gregory P. Smithdd96db62008-06-09 04:58:54 +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{
459 return PyInt_FromLong((long) *(signed char *)p);
460}
461
462static PyObject *
463nu_ubyte(const char *p, const formatdef *f)
464{
465 return PyInt_FromLong((long) *(unsigned char *)p);
466}
467
468static PyObject *
469nu_short(const char *p, const formatdef *f)
470{
471 short x;
472 memcpy((char *)&x, p, sizeof x);
473 return PyInt_FromLong((long)x);
474}
475
476static PyObject *
477nu_ushort(const char *p, const formatdef *f)
478{
479 unsigned short x;
480 memcpy((char *)&x, p, sizeof x);
481 return PyInt_FromLong((long)x);
482}
483
484static PyObject *
485nu_int(const char *p, const formatdef *f)
486{
487 int x;
488 memcpy((char *)&x, p, sizeof x);
489 return PyInt_FromLong((long)x);
490}
491
492static PyObject *
493nu_uint(const char *p, const formatdef *f)
494{
495 unsigned int x;
496 memcpy((char *)&x, p, sizeof x);
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000497#if (SIZEOF_LONG > SIZEOF_INT)
498 return PyInt_FromLong((long)x);
499#else
500 if (x <= ((unsigned int)LONG_MAX))
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000501 return PyInt_FromLong((long)x);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000502 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{
509 long x;
510 memcpy((char *)&x, p, sizeof x);
511 return PyInt_FromLong(x);
512}
513
514static PyObject *
515nu_ulong(const char *p, const formatdef *f)
516{
517 unsigned long x;
518 memcpy((char *)&x, p, sizeof x);
Bob Ippolito04ab9942006-05-25 19:33:38 +0000519 if (x <= LONG_MAX)
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000520 return PyInt_FromLong((long)x);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000521 return PyLong_FromUnsignedLong(x);
522}
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{
532 PY_LONG_LONG x;
533 memcpy((char *)&x, p, sizeof x);
Bob Ippolito04ab9942006-05-25 19:33:38 +0000534 if (x >= LONG_MIN && x <= LONG_MAX)
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000535 return PyInt_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long));
Bob Ippolito232f3c92006-05-23 19:12:41 +0000536 return PyLong_FromLongLong(x);
537}
538
539static PyObject *
540nu_ulonglong(const char *p, const formatdef *f)
541{
542 unsigned PY_LONG_LONG x;
543 memcpy((char *)&x, p, sizeof x);
Bob Ippolito04ab9942006-05-25 19:33:38 +0000544 if (x <= LONG_MAX)
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000545 return PyInt_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long));
Bob Ippolito232f3c92006-05-23 19:12:41 +0000546 return PyLong_FromUnsignedLongLong(x);
547}
548
549#endif
550
551static PyObject *
Martin v. Löwisaef4c6b2007-01-21 09:33:07 +0000552nu_bool(const char *p, const formatdef *f)
553{
554 BOOL_TYPE x;
555 memcpy((char *)&x, p, sizeof x);
556 return PyBool_FromLong(x != 0);
557}
558
559
560static PyObject *
Bob Ippolito232f3c92006-05-23 19:12:41 +0000561nu_float(const char *p, const formatdef *f)
562{
563 float x;
564 memcpy((char *)&x, p, sizeof x);
565 return PyFloat_FromDouble((double)x);
566}
567
568static PyObject *
569nu_double(const char *p, const formatdef *f)
570{
571 double x;
572 memcpy((char *)&x, p, sizeof x);
573 return PyFloat_FromDouble(x);
574}
575
576static PyObject *
577nu_void_p(const char *p, const formatdef *f)
578{
579 void *x;
580 memcpy((char *)&x, p, sizeof x);
581 return PyLong_FromVoidPtr(x);
582}
583
584static int
585np_byte(char *p, PyObject *v, const formatdef *f)
586{
587 long x;
588 if (get_long(v, &x) < 0)
589 return -1;
590 if (x < -128 || x > 127){
591 PyErr_SetString(StructError,
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000592 "byte format requires -128 <= number <= 127");
Bob Ippolito232f3c92006-05-23 19:12:41 +0000593 return -1;
594 }
595 *p = (char)x;
596 return 0;
597}
598
599static int
600np_ubyte(char *p, PyObject *v, const formatdef *f)
601{
602 long x;
603 if (get_long(v, &x) < 0)
604 return -1;
605 if (x < 0 || x > 255){
606 PyErr_SetString(StructError,
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000607 "ubyte format requires 0 <= number <= 255");
Bob Ippolito232f3c92006-05-23 19:12:41 +0000608 return -1;
609 }
610 *p = (char)x;
611 return 0;
612}
613
614static int
615np_char(char *p, PyObject *v, const formatdef *f)
616{
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000617 if (!PyString_Check(v) || PyString_Size(v) != 1) {
Bob Ippolito232f3c92006-05-23 19:12:41 +0000618 PyErr_SetString(StructError,
619 "char format require string of length 1");
620 return -1;
621 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000622 *p = *PyString_AsString(v);
Bob Ippolito232f3c92006-05-23 19:12:41 +0000623 return 0;
624}
625
626static int
627np_short(char *p, PyObject *v, const formatdef *f)
628{
629 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)
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000636 " <= number <= " STRINGIFY(SHRT_MAX));
Bob Ippolito232f3c92006-05-23 19:12:41 +0000637 return -1;
638 }
639 y = (short)x;
640 memcpy(p, (char *)&y, sizeof y);
641 return 0;
642}
643
644static int
645np_ushort(char *p, PyObject *v, const formatdef *f)
646{
647 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,
Mark Dickinson7ad3f922009-07-07 10:19:18 +0000653 "ushort format requires 0 <= number <= " STRINGIFY(USHRT_MAX));
Bob Ippolito232f3c92006-05-23 19:12:41 +0000654 return -1;
655 }
656 y = (unsigned short)x;
657 memcpy(p, (char *)&y, sizeof y);
658 return 0;
659}
660
661static int
662np_int(char *p, PyObject *v, const formatdef *f)
663{
664 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)
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000669 if ((x < ((long)INT_MIN)) || (x > ((long)INT_MAX)))
Georg Brandl47fe9812009-01-01 15:46:10 +0000670 RANGE_ERROR(x, f, 0, -1);
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000671#endif
Bob Ippolito232f3c92006-05-23 19:12:41 +0000672 y = (int)x;
673 memcpy(p, (char *)&y, sizeof y);
674 return 0;
675}
676
677static int
678np_uint(char *p, PyObject *v, const formatdef *f)
679{
680 unsigned long x;
681 unsigned int y;
Georg Brandl47fe9812009-01-01 15:46:10 +0000682 if (get_wrapped_ulong(v, &x) < 0)
683 return -1;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000684 y = (unsigned int)x;
Bob Ippolito90bd0a52006-05-27 11:47:12 +0000685#if (SIZEOF_LONG > SIZEOF_INT)
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000686 if (x > ((unsigned long)UINT_MAX))
Georg Brandl47fe9812009-01-01 15:46:10 +0000687 RANGE_ERROR(y, f, 1, -1);
Bob Ippolitoe27337b2006-05-26 13:15:44 +0000688#endif
Bob Ippolito232f3c92006-05-23 19:12:41 +0000689 memcpy(p, (char *)&y, sizeof y);
690 return 0;
691}
692
693static int
694np_long(char *p, PyObject *v, const formatdef *f)
695{
696 long x;
697 if (get_long(v, &x) < 0)
698 return -1;
699 memcpy(p, (char *)&x, sizeof x);
700 return 0;
701}
702
703static int
704np_ulong(char *p, PyObject *v, const formatdef *f)
705{
706 unsigned long x;
Georg Brandl47fe9812009-01-01 15:46:10 +0000707 if (get_wrapped_ulong(v, &x) < 0)
708 return -1;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000709 memcpy(p, (char *)&x, sizeof x);
710 return 0;
711}
712
713#ifdef HAVE_LONG_LONG
714
715static int
716np_longlong(char *p, PyObject *v, const formatdef *f)
717{
718 PY_LONG_LONG x;
719 if (get_longlong(v, &x) < 0)
720 return -1;
721 memcpy(p, (char *)&x, sizeof x);
722 return 0;
723}
724
725static int
726np_ulonglong(char *p, PyObject *v, const formatdef *f)
727{
728 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;
733}
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{
740 BOOL_TYPE y;
741 y = PyObject_IsTrue(v);
742 memcpy(p, (char *)&y, sizeof y);
743 return 0;
744}
745
Bob Ippolito232f3c92006-05-23 19:12:41 +0000746static int
747np_float(char *p, PyObject *v, const formatdef *f)
748{
749 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;
757}
758
759static int
760np_double(char *p, PyObject *v, const formatdef *f)
761{
762 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;
770}
771
772static int
773np_void_p(char *p, PyObject *v, const formatdef *f)
774{
775 void *x;
776
777 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;
787}
788
789static formatdef native_table[] = {
790 {'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
803 {'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},
805#endif
Thomas Hellerf3c05592008-03-05 15:34:29 +0000806 {'?', sizeof(BOOL_TYPE), BOOL_ALIGN, nu_bool, np_bool},
Bob Ippolitoa99865b2006-05-25 19:56:56 +0000807 {'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},
Bob Ippolito232f3c92006-05-23 19:12:41 +0000810 {0}
811};
812
813/* Big-endian routines. *****************************************************/
814
815static PyObject *
816bu_int(const char *p, const formatdef *f)
817{
818 long x = 0;
Bob Ippolitoaa70a172006-05-26 20:25:23 +0000819 Py_ssize_t i = f->size;
Bob Ippolito28b26862006-05-29 15:47:29 +0000820 const unsigned char *bytes = (const unsigned char *)p;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000821 do {
Bob Ippolito28b26862006-05-29 15:47:29 +0000822 x = (x<<8) | *bytes++;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000823 } while (--i > 0);
824 /* Extend the sign bit. */
825 if (SIZEOF_LONG > f->size)
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000826 x |= -(x & (1L << ((8 * f->size) - 1)));
Bob Ippolito232f3c92006-05-23 19:12:41 +0000827 return PyInt_FromLong(x);
828}
829
830static PyObject *
831bu_uint(const char *p, const formatdef *f)
832{
833 unsigned long x = 0;
Bob Ippolitoaa70a172006-05-26 20:25:23 +0000834 Py_ssize_t i = f->size;
Bob Ippolito28b26862006-05-29 15:47:29 +0000835 const unsigned char *bytes = (const unsigned char *)p;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000836 do {
Bob Ippolito28b26862006-05-29 15:47:29 +0000837 x = (x<<8) | *bytes++;
Bob Ippolito232f3c92006-05-23 19:12:41 +0000838 } while (--i > 0);
Bob Ippolito04ab9942006-05-25 19:33:38 +0000839 if (x <= LONG_MAX)
Bob Ippolito232f3c92006-05-23 19:12:41 +0000840 return PyInt_FromLong((long)x);
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000841 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
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000848 PY_LONG_LONG x = 0;
Bob Ippolitoaa70a172006-05-26 20:25:23 +0000849 Py_ssize_t i = f->size;
Bob Ippolito28b26862006-05-29 15:47:29 +0000850 const unsigned char *bytes = (const unsigned char *)p;
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000851 do {
Bob Ippolito28b26862006-05-29 15:47:29 +0000852 x = (x<<8) | *bytes++;
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000853 } while (--i > 0);
854 /* Extend the sign bit. */
855 if (SIZEOF_LONG_LONG > f->size)
Kristján Valur Jónsson67387fb2007-04-25 00:17:39 +0000856 x |= -(x & ((PY_LONG_LONG)1 << ((8 * f->size) - 1)));
Bob Ippolito04ab9942006-05-25 19:33:38 +0000857 if (x >= LONG_MIN && x <= LONG_MAX)
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000858 return PyInt_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long));
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000859 return PyLong_FromLongLong(x);
860#else
Bob Ippolito232f3c92006-05-23 19:12:41 +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
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000872 unsigned PY_LONG_LONG x = 0;
Bob Ippolitoaa70a172006-05-26 20:25:23 +0000873 Py_ssize_t i = f->size;
Bob Ippolito28b26862006-05-29 15:47:29 +0000874 const unsigned char *bytes = (const unsigned char *)p;
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000875 do {
Bob Ippolito28b26862006-05-29 15:47:29 +0000876 x = (x<<8) | *bytes++;
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000877 } while (--i > 0);
Bob Ippolito04ab9942006-05-25 19:33:38 +0000878 if (x <= LONG_MAX)
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000879 return PyInt_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long));
Bob Ippolito94f68ee2006-05-25 18:44:50 +0000880 return PyLong_FromUnsignedLongLong(x);
881#else
Bob Ippolito232f3c92006-05-23 19:12:41 +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{
892 return unpack_float(p, 0);
893}
894
895static PyObject *
896bu_double(const char *p, const formatdef *f)
897{
898 return unpack_double(p, 0);
899}
900
Martin v. Löwisaef4c6b2007-01-21 09:33:07 +0000901static PyObject *
902bu_bool(const char *p, const formatdef *f)
903{
904 char x;
905 memcpy((char *)&x, p, sizeof x);
906 return PyBool_FromLong(x != 0);
907}
908
Bob Ippolito232f3c92006-05-23 19:12:41 +0000909static int
910bp_int(char *p, PyObject *v, const formatdef *f)
911{
912 long x;
Bob Ippolitoaa70a172006-05-26 20:25:23 +0000913 Py_ssize_t i;
Bob Ippolito2fd39772006-05-29 22:55:48 +0000914 if (get_wrapped_long(v, &x) < 0)
Bob Ippolito232f3c92006-05-23 19:12:41 +0000915 return -1;
916 i = f->size;
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000917 if (i != SIZEOF_LONG) {
918 if ((i == 2) && (x < -32768 || x > 32767))
Bob Ippolito2fd39772006-05-29 22:55:48 +0000919 RANGE_ERROR(x, f, 0, 0xffffL);
Bob Ippolito90bd0a52006-05-27 11:47:12 +0000920#if (SIZEOF_LONG != 4)
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000921 else if ((i == 4) && (x < -2147483648L || x > 2147483647L))
Bob Ippolito2fd39772006-05-29 22:55:48 +0000922 RANGE_ERROR(x, f, 0, 0xffffffffL);
923#endif
Bob Ippolito4182a752006-05-30 17:37:54 +0000924#ifdef PY_STRUCT_OVERFLOW_MASKING
Bob Ippolito2fd39772006-05-29 22:55:48 +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
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000928 }
Bob Ippolito232f3c92006-05-23 19:12:41 +0000929 do {
930 p[--i] = (char)x;
931 x >>= 8;
932 } while (i > 0);
933 return 0;
934}
935
936static int
937bp_uint(char *p, PyObject *v, const formatdef *f)
938{
939 unsigned long x;
Bob Ippolitoaa70a172006-05-26 20:25:23 +0000940 Py_ssize_t i;
Bob Ippolito2fd39772006-05-29 22:55:48 +0000941 if (get_wrapped_ulong(v, &x) < 0)
Bob Ippolito232f3c92006-05-23 19:12:41 +0000942 return -1;
943 i = f->size;
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000944 if (i != SIZEOF_LONG) {
945 unsigned long maxint = 1;
946 maxint <<= (unsigned long)(i * 8);
947 if (x >= maxint)
Bob Ippolito2fd39772006-05-29 22:55:48 +0000948 RANGE_ERROR(x, f, 1, maxint - 1);
Bob Ippolitocd51ca52006-05-27 15:53:49 +0000949 }
Bob Ippolito232f3c92006-05-23 19:12:41 +0000950 do {
951 p[--i] = (char)x;
952 x >>= 8;
953 } while (i > 0);
954 return 0;
955}
956
957static int
958bp_longlong(char *p, PyObject *v, const formatdef *f)
959{
960 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;
971}
972
973static int
974bp_ulonglong(char *p, PyObject *v, const formatdef *f)
975{
976 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;
987}
988
989static int
990bp_float(char *p, PyObject *v, const formatdef *f)
991{
992 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);
999}
1000
1001static int
1002bp_double(char *p, PyObject *v, const formatdef *f)
1003{
1004 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);
1011}
1012
Martin v. Löwisaef4c6b2007-01-21 09:33:07 +00001013static int
1014bp_bool(char *p, PyObject *v, const formatdef *f)
1015{
1016 char y;
1017 y = PyObject_IsTrue(v);
1018 memcpy(p, (char *)&y, sizeof y);
1019 return 0;
1020}
1021
Bob Ippolito232f3c92006-05-23 19:12:41 +00001022static formatdef bigendian_table[] = {
1023 {'x', 1, 0, NULL},
Bob Ippolito4182a752006-05-30 17:37:54 +00001024#ifdef PY_STRUCT_OVERFLOW_MASKING
1025 /* Native packers do range checking without overflow masking. */
Bob Ippolito2fd39772006-05-29 22:55:48 +00001026 {'b', 1, 0, nu_byte, bp_int},
1027 {'B', 1, 0, nu_ubyte, bp_uint},
1028#else
Bob Ippolitoe27337b2006-05-26 13:15:44 +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
Bob Ippolito232f3c92006-05-23 19:12:41 +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},
Thomas Hellerf3c05592008-03-05 15:34:29 +00001043 {'?', 1, 0, bu_bool, bp_bool},
Bob Ippolito232f3c92006-05-23 19:12:41 +00001044 {'f', 4, 0, bu_float, bp_float},
1045 {'d', 8, 0, bu_double, bp_double},
1046 {0}
1047};
1048
1049/* Little-endian routines. *****************************************************/
1050
1051static PyObject *
1052lu_int(const char *p, const formatdef *f)
1053{
1054 long x = 0;
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001055 Py_ssize_t i = f->size;
Bob Ippolito28b26862006-05-29 15:47:29 +00001056 const unsigned char *bytes = (const unsigned char *)p;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001057 do {
Bob Ippolito28b26862006-05-29 15:47:29 +00001058 x = (x<<8) | bytes[--i];
Bob Ippolito232f3c92006-05-23 19:12:41 +00001059 } while (i > 0);
1060 /* Extend the sign bit. */
1061 if (SIZEOF_LONG > f->size)
Bob Ippolitocd51ca52006-05-27 15:53:49 +00001062 x |= -(x & (1L << ((8 * f->size) - 1)));
Bob Ippolito232f3c92006-05-23 19:12:41 +00001063 return PyInt_FromLong(x);
1064}
1065
1066static PyObject *
1067lu_uint(const char *p, const formatdef *f)
1068{
1069 unsigned long x = 0;
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001070 Py_ssize_t i = f->size;
Bob Ippolito28b26862006-05-29 15:47:29 +00001071 const unsigned char *bytes = (const unsigned char *)p;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001072 do {
Bob Ippolito28b26862006-05-29 15:47:29 +00001073 x = (x<<8) | bytes[--i];
Bob Ippolito232f3c92006-05-23 19:12:41 +00001074 } while (i > 0);
Bob Ippolito04ab9942006-05-25 19:33:38 +00001075 if (x <= LONG_MAX)
Bob Ippolito232f3c92006-05-23 19:12:41 +00001076 return PyInt_FromLong((long)x);
Bob Ippolito94f68ee2006-05-25 18:44:50 +00001077 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
Bob Ippolito94f68ee2006-05-25 18:44:50 +00001084 PY_LONG_LONG x = 0;
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001085 Py_ssize_t i = f->size;
Bob Ippolito28b26862006-05-29 15:47:29 +00001086 const unsigned char *bytes = (const unsigned char *)p;
Bob Ippolito94f68ee2006-05-25 18:44:50 +00001087 do {
Bob Ippolito28b26862006-05-29 15:47:29 +00001088 x = (x<<8) | bytes[--i];
Bob Ippolito94f68ee2006-05-25 18:44:50 +00001089 } while (i > 0);
1090 /* Extend the sign bit. */
1091 if (SIZEOF_LONG_LONG > f->size)
Kristján Valur Jónsson67387fb2007-04-25 00:17:39 +00001092 x |= -(x & ((PY_LONG_LONG)1 << ((8 * f->size) - 1)));
Bob Ippolito04ab9942006-05-25 19:33:38 +00001093 if (x >= LONG_MIN && x <= LONG_MAX)
Bob Ippolito94f68ee2006-05-25 18:44:50 +00001094 return PyInt_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long));
Bob Ippolito94f68ee2006-05-25 18:44:50 +00001095 return PyLong_FromLongLong(x);
1096#else
Bob Ippolito232f3c92006-05-23 19:12:41 +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
Bob Ippolito94f68ee2006-05-25 18:44:50 +00001108 unsigned PY_LONG_LONG x = 0;
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001109 Py_ssize_t i = f->size;
Bob Ippolito28b26862006-05-29 15:47:29 +00001110 const unsigned char *bytes = (const unsigned char *)p;
Bob Ippolito94f68ee2006-05-25 18:44:50 +00001111 do {
Bob Ippolito28b26862006-05-29 15:47:29 +00001112 x = (x<<8) | bytes[--i];
Bob Ippolito94f68ee2006-05-25 18:44:50 +00001113 } while (i > 0);
Bob Ippolito04ab9942006-05-25 19:33:38 +00001114 if (x <= LONG_MAX)
Bob Ippolito94f68ee2006-05-25 18:44:50 +00001115 return PyInt_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long));
Bob Ippolito94f68ee2006-05-25 18:44:50 +00001116 return PyLong_FromUnsignedLongLong(x);
1117#else
Bob Ippolito232f3c92006-05-23 19:12:41 +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{
1128 return unpack_float(p, 1);
1129}
1130
1131static PyObject *
1132lu_double(const char *p, const formatdef *f)
1133{
1134 return unpack_double(p, 1);
1135}
1136
1137static int
1138lp_int(char *p, PyObject *v, const formatdef *f)
1139{
1140 long x;
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001141 Py_ssize_t i;
Bob Ippolito2fd39772006-05-29 22:55:48 +00001142 if (get_wrapped_long(v, &x) < 0)
Bob Ippolito232f3c92006-05-23 19:12:41 +00001143 return -1;
1144 i = f->size;
Bob Ippolitocd51ca52006-05-27 15:53:49 +00001145 if (i != SIZEOF_LONG) {
1146 if ((i == 2) && (x < -32768 || x > 32767))
Bob Ippolito2fd39772006-05-29 22:55:48 +00001147 RANGE_ERROR(x, f, 0, 0xffffL);
Bob Ippolito90bd0a52006-05-27 11:47:12 +00001148#if (SIZEOF_LONG != 4)
Bob Ippolitocd51ca52006-05-27 15:53:49 +00001149 else if ((i == 4) && (x < -2147483648L || x > 2147483647L))
Bob Ippolito2fd39772006-05-29 22:55:48 +00001150 RANGE_ERROR(x, f, 0, 0xffffffffL);
1151#endif
Bob Ippolito4182a752006-05-30 17:37:54 +00001152#ifdef PY_STRUCT_OVERFLOW_MASKING
Bob Ippolito2fd39772006-05-29 22:55:48 +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
Bob Ippolitocd51ca52006-05-27 15:53:49 +00001156 }
Bob Ippolito232f3c92006-05-23 19:12:41 +00001157 do {
1158 *p++ = (char)x;
1159 x >>= 8;
1160 } while (--i > 0);
1161 return 0;
1162}
1163
1164static int
1165lp_uint(char *p, PyObject *v, const formatdef *f)
1166{
1167 unsigned long x;
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001168 Py_ssize_t i;
Bob Ippolito2fd39772006-05-29 22:55:48 +00001169 if (get_wrapped_ulong(v, &x) < 0)
Bob Ippolito232f3c92006-05-23 19:12:41 +00001170 return -1;
1171 i = f->size;
Bob Ippolitocd51ca52006-05-27 15:53:49 +00001172 if (i != SIZEOF_LONG) {
1173 unsigned long maxint = 1;
1174 maxint <<= (unsigned long)(i * 8);
1175 if (x >= maxint)
Bob Ippolito2fd39772006-05-29 22:55:48 +00001176 RANGE_ERROR(x, f, 1, maxint - 1);
Bob Ippolitocd51ca52006-05-27 15:53:49 +00001177 }
Bob Ippolito232f3c92006-05-23 19:12:41 +00001178 do {
1179 *p++ = (char)x;
1180 x >>= 8;
1181 } while (--i > 0);
1182 return 0;
1183}
1184
1185static int
1186lp_longlong(char *p, PyObject *v, const formatdef *f)
1187{
1188 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;
1199}
1200
1201static int
1202lp_ulonglong(char *p, PyObject *v, const formatdef *f)
1203{
1204 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;
1215}
1216
1217static int
1218lp_float(char *p, PyObject *v, const formatdef *f)
1219{
1220 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);
1227}
1228
1229static int
1230lp_double(char *p, PyObject *v, const formatdef *f)
1231{
1232 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);
1239}
1240
1241static formatdef lilendian_table[] = {
1242 {'x', 1, 0, NULL},
Bob Ippolito4182a752006-05-30 17:37:54 +00001243#ifdef PY_STRUCT_OVERFLOW_MASKING
1244 /* Native packers do range checking without overflow masking. */
Bob Ippolito2fd39772006-05-29 22:55:48 +00001245 {'b', 1, 0, nu_byte, lp_int},
1246 {'B', 1, 0, nu_ubyte, lp_uint},
1247#else
Bob Ippolitoe27337b2006-05-26 13:15:44 +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
Bob Ippolito232f3c92006-05-23 19:12:41 +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},
Thomas Hellerf3c05592008-03-05 15:34:29 +00001262 {'?', 1, 0, bu_bool, bp_bool}, /* Std rep not endian dep,
Martin v. Löwisaef4c6b2007-01-21 09:33:07 +00001263 but potentially different from native rep -- reuse bx_bool funcs. */
Bob Ippolito232f3c92006-05-23 19:12:41 +00001264 {'f', 4, 0, lu_float, lp_float},
1265 {'d', 8, 0, lu_double, lp_double},
1266 {0}
1267};
1268
1269
1270static const formatdef *
1271whichtable(char **pfmt)
1272{
1273 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 }
1294}
1295
1296
1297/* Get the table entry for a format code */
1298
1299static const formatdef *
1300getentry(int c, const formatdef *f)
1301{
1302 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;
1309}
1310
1311
1312/* Align a size according to a format code */
1313
1314static int
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{
1317 if (e->format == c) {
1318 if (e->alignment) {
1319 size = ((size + e->alignment - 1)
1320 / e->alignment)
1321 * e->alignment;
1322 }
1323 }
1324 return size;
1325}
1326
1327
1328/* calculate the size of a format string */
1329
1330static int
1331prepare_s(PyStructObject *self)
1332{
1333 const formatdef *f;
1334 const formatdef *e;
1335 formatcode *codes;
Tim Petersc2b550e2006-05-31 14:28:07 +00001336
Bob Ippolito232f3c92006-05-23 19:12:41 +00001337 const char *s;
1338 const char *fmt;
1339 char c;
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001340 Py_ssize_t size, len, num, itemsize, x;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001341
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001342 fmt = PyString_AS_STRING(self->s_format);
Bob Ippolito232f3c92006-05-23 19:12:41 +00001343
1344 f = whichtable((char **)&fmt);
Tim Petersc2b550e2006-05-31 14:28:07 +00001345
Bob Ippolito232f3c92006-05-23 19:12:41 +00001346 s = fmt;
1347 size = 0;
1348 len = 0;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001349 while ((c = *s++) != '\0') {
1350 if (isspace(Py_CHARMASK(c)))
1351 continue;
1352 if ('0' <= c && c <= '9') {
1353 num = c - '0';
1354 while ('0' <= (c = *s++) && c <= '9') {
1355 x = num*10 + (c - '0');
1356 if (x/10 != num) {
1357 PyErr_SetString(
1358 StructError,
1359 "overflow in item count");
1360 return -1;
1361 }
1362 num = x;
1363 }
1364 if (c == '\0')
1365 break;
1366 }
1367 else
1368 num = 1;
1369
1370 e = getentry(c, f);
1371 if (e == NULL)
1372 return -1;
Tim Petersc2b550e2006-05-31 14:28:07 +00001373
Bob Ippolito232f3c92006-05-23 19:12:41 +00001374 switch (c) {
1375 case 's': /* fall through */
1376 case 'p': len++; break;
1377 case 'x': break;
1378 default: len += num; break;
1379 }
Bob Ippolito232f3c92006-05-23 19:12:41 +00001380
1381 itemsize = e->size;
1382 size = align(size, c, e);
1383 x = num * itemsize;
1384 size += x;
1385 if (x/itemsize != num || size < 0) {
1386 PyErr_SetString(StructError,
1387 "total struct size too long");
1388 return -1;
1389 }
1390 }
1391
Gregory P. Smith9d534572008-06-11 07:41:16 +00001392 /* check for overflow */
1393 if ((len + 1) > (PY_SSIZE_T_MAX / sizeof(formatcode))) {
1394 PyErr_NoMemory();
1395 return -1;
1396 }
1397
Bob Ippolito232f3c92006-05-23 19:12:41 +00001398 self->s_size = size;
1399 self->s_len = len;
Bob Ippolitoeb621272006-05-24 15:32:06 +00001400 codes = PyMem_MALLOC((len + 1) * sizeof(formatcode));
Bob Ippolito232f3c92006-05-23 19:12:41 +00001401 if (codes == NULL) {
1402 PyErr_NoMemory();
1403 return -1;
1404 }
1405 self->s_codes = codes;
Tim Petersc2b550e2006-05-31 14:28:07 +00001406
Bob Ippolito232f3c92006-05-23 19:12:41 +00001407 s = fmt;
1408 size = 0;
1409 while ((c = *s++) != '\0') {
1410 if (isspace(Py_CHARMASK(c)))
1411 continue;
1412 if ('0' <= c && c <= '9') {
1413 num = c - '0';
1414 while ('0' <= (c = *s++) && c <= '9')
1415 num = num*10 + (c - '0');
1416 if (c == '\0')
1417 break;
1418 }
1419 else
1420 num = 1;
1421
1422 e = getentry(c, f);
Tim Petersc2b550e2006-05-31 14:28:07 +00001423
Bob Ippolito232f3c92006-05-23 19:12:41 +00001424 size = align(size, c, e);
Bob Ippolitoeb621272006-05-24 15:32:06 +00001425 if (c == 's' || c == 'p') {
Bob Ippolito232f3c92006-05-23 19:12:41 +00001426 codes->offset = size;
Bob Ippolitoeb621272006-05-24 15:32:06 +00001427 codes->size = num;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001428 codes->fmtdef = e;
1429 codes++;
Bob Ippolitoeb621272006-05-24 15:32:06 +00001430 size += num;
1431 } else if (c == 'x') {
1432 size += num;
1433 } else {
1434 while (--num >= 0) {
1435 codes->offset = size;
1436 codes->size = e->size;
1437 codes->fmtdef = e;
1438 codes++;
1439 size += e->size;
1440 }
Bob Ippolito232f3c92006-05-23 19:12:41 +00001441 }
Bob Ippolito232f3c92006-05-23 19:12:41 +00001442 }
1443 codes->fmtdef = NULL;
Bob Ippolitoeb621272006-05-24 15:32:06 +00001444 codes->offset = size;
1445 codes->size = 0;
Tim Petersc2b550e2006-05-31 14:28:07 +00001446
Bob Ippolito232f3c92006-05-23 19:12:41 +00001447 return 0;
1448}
1449
1450static PyObject *
1451s_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1452{
1453 PyObject *self;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001454
1455 assert(type != NULL && type->tp_alloc != NULL);
1456
1457 self = type->tp_alloc(type, 0);
1458 if (self != NULL) {
1459 PyStructObject *s = (PyStructObject*)self;
1460 Py_INCREF(Py_None);
1461 s->s_format = Py_None;
1462 s->s_codes = NULL;
1463 s->s_size = -1;
1464 s->s_len = -1;
1465 }
1466 return self;
1467}
1468
1469static int
1470s_init(PyObject *self, PyObject *args, PyObject *kwds)
1471{
1472 PyStructObject *soself = (PyStructObject *)self;
1473 PyObject *o_format = NULL;
1474 int ret = 0;
1475 static char *kwlist[] = {"format", 0};
1476
1477 assert(PyStruct_Check(self));
1478
1479 if (!PyArg_ParseTupleAndKeywords(args, kwds, "S:Struct", kwlist,
1480 &o_format))
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001481 return -1;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001482
1483 Py_INCREF(o_format);
Amaury Forgeot d'Arc588ff932008-02-16 14:34:57 +00001484 Py_CLEAR(soself->s_format);
Bob Ippolito232f3c92006-05-23 19:12:41 +00001485 soself->s_format = o_format;
Tim Petersc2b550e2006-05-31 14:28:07 +00001486
Bob Ippolito232f3c92006-05-23 19:12:41 +00001487 ret = prepare_s(soself);
1488 return ret;
1489}
1490
1491static void
1492s_dealloc(PyStructObject *s)
1493{
Bob Ippolito232f3c92006-05-23 19:12:41 +00001494 if (s->weakreflist != NULL)
1495 PyObject_ClearWeakRefs((PyObject *)s);
1496 if (s->s_codes != NULL) {
1497 PyMem_FREE(s->s_codes);
1498 }
1499 Py_XDECREF(s->s_format);
Christian Heimese93237d2007-12-19 02:37:44 +00001500 Py_TYPE(s)->tp_free((PyObject *)s);
Bob Ippolito232f3c92006-05-23 19:12:41 +00001501}
1502
Bob Ippolitoeb621272006-05-24 15:32:06 +00001503static PyObject *
1504s_unpack_internal(PyStructObject *soself, char *startfrom) {
1505 formatcode *code;
1506 Py_ssize_t i = 0;
1507 PyObject *result = PyTuple_New(soself->s_len);
1508 if (result == NULL)
1509 return NULL;
1510
1511 for (code = soself->s_codes; code->fmtdef != NULL; code++) {
1512 PyObject *v;
1513 const formatdef *e = code->fmtdef;
1514 const char *res = startfrom + code->offset;
1515 if (e->format == 's') {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001516 v = PyString_FromStringAndSize(res, code->size);
Bob Ippolitoeb621272006-05-24 15:32:06 +00001517 } else if (e->format == 'p') {
1518 Py_ssize_t n = *(unsigned char*)res;
1519 if (n >= code->size)
1520 n = code->size - 1;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001521 v = PyString_FromStringAndSize(res + 1, n);
Bob Ippolitoeb621272006-05-24 15:32:06 +00001522 } else {
1523 v = e->unpack(res, e);
Bob Ippolitoeb621272006-05-24 15:32:06 +00001524 }
Neal Norwitz3c5431e2006-06-11 05:45:25 +00001525 if (v == NULL)
1526 goto fail;
1527 PyTuple_SET_ITEM(result, i++, v);
Bob Ippolitoeb621272006-05-24 15:32:06 +00001528 }
1529
1530 return result;
1531fail:
1532 Py_DECREF(result);
1533 return NULL;
Bob Ippolitocd51ca52006-05-27 15:53:49 +00001534}
Bob Ippolitoeb621272006-05-24 15:32:06 +00001535
1536
Bob Ippolito232f3c92006-05-23 19:12:41 +00001537PyDoc_STRVAR(s_unpack__doc__,
Bob Ippolito1fcdc232006-05-27 12:11:36 +00001538"S.unpack(str) -> (v1, v2, ...)\n\
Bob Ippolito232f3c92006-05-23 19:12:41 +00001539\n\
1540Return tuple containing values unpacked according to this Struct's format.\n\
1541Requires len(str) == self.size. See struct.__doc__ for more on format\n\
1542strings.");
1543
1544static PyObject *
1545s_unpack(PyObject *self, PyObject *inputstr)
1546{
Raymond Hettinger7a3d41f2007-04-05 18:00:03 +00001547 char *start;
1548 Py_ssize_t len;
1549 PyObject *args=NULL, *result;
Bob Ippolitoeb621272006-05-24 15:32:06 +00001550 PyStructObject *soself = (PyStructObject *)self;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001551 assert(PyStruct_Check(self));
Tim Petersc2b550e2006-05-31 14:28:07 +00001552 assert(soself->s_codes != NULL);
Raymond Hettinger7a3d41f2007-04-05 18:00:03 +00001553 if (inputstr == NULL)
1554 goto fail;
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001555 if (PyString_Check(inputstr) &&
1556 PyString_GET_SIZE(inputstr) == soself->s_size) {
1557 return s_unpack_internal(soself, PyString_AS_STRING(inputstr));
Bob Ippolito232f3c92006-05-23 19:12:41 +00001558 }
Raymond Hettinger7a3d41f2007-04-05 18:00:03 +00001559 args = PyTuple_Pack(1, inputstr);
1560 if (args == NULL)
1561 return NULL;
1562 if (!PyArg_ParseTuple(args, "s#:unpack", &start, &len))
1563 goto fail;
1564 if (soself->s_size != len)
1565 goto fail;
1566 result = s_unpack_internal(soself, start);
1567 Py_DECREF(args);
1568 return result;
1569
1570fail:
1571 Py_XDECREF(args);
1572 PyErr_Format(StructError,
1573 "unpack requires a string argument of length %zd",
1574 soself->s_size);
1575 return NULL;
Bob Ippolitoeb621272006-05-24 15:32:06 +00001576}
1577
1578PyDoc_STRVAR(s_unpack_from__doc__,
Bob Ippolito1fcdc232006-05-27 12:11:36 +00001579"S.unpack_from(buffer[, offset]) -> (v1, v2, ...)\n\
Bob Ippolitoeb621272006-05-24 15:32:06 +00001580\n\
1581Return tuple containing values unpacked according to this Struct's format.\n\
1582Unlike unpack, unpack_from can unpack values from any object supporting\n\
1583the buffer API, not just str. Requires len(buffer[offset:]) >= self.size.\n\
1584See struct.__doc__ for more on format strings.");
1585
1586static PyObject *
1587s_unpack_from(PyObject *self, PyObject *args, PyObject *kwds)
1588{
1589 static char *kwlist[] = {"buffer", "offset", 0};
1590#if (PY_VERSION_HEX < 0x02050000)
1591 static char *fmt = "z#|i:unpack_from";
1592#else
1593 static char *fmt = "z#|n:unpack_from";
1594#endif
1595 Py_ssize_t buffer_len = 0, offset = 0;
1596 char *buffer = NULL;
1597 PyStructObject *soself = (PyStructObject *)self;
1598 assert(PyStruct_Check(self));
1599 assert(soself->s_codes != NULL);
1600
1601 if (!PyArg_ParseTupleAndKeywords(args, kwds, fmt, kwlist,
1602 &buffer, &buffer_len, &offset))
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001603 return NULL;
Bob Ippolitoeb621272006-05-24 15:32:06 +00001604
1605 if (buffer == NULL) {
1606 PyErr_Format(StructError,
1607 "unpack_from requires a buffer argument");
Bob Ippolito232f3c92006-05-23 19:12:41 +00001608 return NULL;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001609 }
Tim Petersc2b550e2006-05-31 14:28:07 +00001610
Bob Ippolitoeb621272006-05-24 15:32:06 +00001611 if (offset < 0)
1612 offset += buffer_len;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001613
Bob Ippolitoeb621272006-05-24 15:32:06 +00001614 if (offset < 0 || (buffer_len - offset) < soself->s_size) {
1615 PyErr_Format(StructError,
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001616 "unpack_from requires a buffer of at least %zd bytes",
Bob Ippolitoeb621272006-05-24 15:32:06 +00001617 soself->s_size);
1618 return NULL;
1619 }
1620 return s_unpack_internal(soself, buffer + offset);
1621}
Bob Ippolito232f3c92006-05-23 19:12:41 +00001622
Bob Ippolito232f3c92006-05-23 19:12:41 +00001623
Martin Blais2856e5f2006-05-26 12:03:27 +00001624/*
1625 * Guts of the pack function.
1626 *
1627 * Takes a struct object, a tuple of arguments, and offset in that tuple of
1628 * argument for where to start processing the arguments for packing, and a
1629 * character buffer for writing the packed string. The caller must insure
1630 * that the buffer may contain the required length for packing the arguments.
1631 * 0 is returned on success, 1 is returned if there is an error.
1632 *
1633 */
1634static int
1635s_pack_internal(PyStructObject *soself, PyObject *args, int offset, char* buf)
Bob Ippolito232f3c92006-05-23 19:12:41 +00001636{
Bob Ippolito232f3c92006-05-23 19:12:41 +00001637 formatcode *code;
Neal Norwitz3c5431e2006-06-11 05:45:25 +00001638 /* XXX(nnorwitz): why does i need to be a local? can we use
1639 the offset parameter or do we need the wider width? */
Bob Ippolito232f3c92006-05-23 19:12:41 +00001640 Py_ssize_t i;
Martin Blais2856e5f2006-05-26 12:03:27 +00001641
1642 memset(buf, '\0', soself->s_size);
1643 i = offset;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001644 for (code = soself->s_codes; code->fmtdef != NULL; code++) {
1645 Py_ssize_t n;
Neal Norwitz3c5431e2006-06-11 05:45:25 +00001646 PyObject *v = PyTuple_GET_ITEM(args, i++);
Bob Ippolito232f3c92006-05-23 19:12:41 +00001647 const formatdef *e = code->fmtdef;
Martin Blais2856e5f2006-05-26 12:03:27 +00001648 char *res = buf + code->offset;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001649 if (e->format == 's') {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001650 if (!PyString_Check(v)) {
Bob Ippolito232f3c92006-05-23 19:12:41 +00001651 PyErr_SetString(StructError,
1652 "argument for 's' must be a string");
Martin Blais2856e5f2006-05-26 12:03:27 +00001653 return -1;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001654 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001655 n = PyString_GET_SIZE(v);
Bob Ippolitoeb621272006-05-24 15:32:06 +00001656 if (n > code->size)
1657 n = code->size;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001658 if (n > 0)
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001659 memcpy(res, PyString_AS_STRING(v), n);
Bob Ippolito232f3c92006-05-23 19:12:41 +00001660 } else if (e->format == 'p') {
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001661 if (!PyString_Check(v)) {
Bob Ippolito232f3c92006-05-23 19:12:41 +00001662 PyErr_SetString(StructError,
1663 "argument for 'p' must be a string");
Martin Blais2856e5f2006-05-26 12:03:27 +00001664 return -1;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001665 }
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001666 n = PyString_GET_SIZE(v);
Bob Ippolitoeb621272006-05-24 15:32:06 +00001667 if (n > (code->size - 1))
1668 n = code->size - 1;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001669 if (n > 0)
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001670 memcpy(res + 1, PyString_AS_STRING(v), n);
Bob Ippolito232f3c92006-05-23 19:12:41 +00001671 if (n > 255)
1672 n = 255;
1673 *res = Py_SAFE_DOWNCAST(n, Py_ssize_t, unsigned char);
1674 } else {
Bob Ippolito2fd39772006-05-29 22:55:48 +00001675 if (e->pack(res, v, e) < 0) {
1676 if (PyLong_Check(v) && PyErr_ExceptionMatches(PyExc_OverflowError))
1677 PyErr_SetString(StructError,
1678 "long too large to convert to int");
Martin Blais2856e5f2006-05-26 12:03:27 +00001679 return -1;
Bob Ippolito2fd39772006-05-29 22:55:48 +00001680 }
Bob Ippolito232f3c92006-05-23 19:12:41 +00001681 }
1682 }
Tim Petersc2b550e2006-05-31 14:28:07 +00001683
Martin Blais2856e5f2006-05-26 12:03:27 +00001684 /* Success */
1685 return 0;
1686}
Bob Ippolito232f3c92006-05-23 19:12:41 +00001687
Martin Blais2856e5f2006-05-26 12:03:27 +00001688
1689PyDoc_STRVAR(s_pack__doc__,
Bob Ippolito1fcdc232006-05-27 12:11:36 +00001690"S.pack(v1, v2, ...) -> string\n\
Martin Blais2856e5f2006-05-26 12:03:27 +00001691\n\
1692Return a string containing values v1, v2, ... packed according to this\n\
1693Struct's format. See struct.__doc__ for more on format strings.");
1694
1695static PyObject *
1696s_pack(PyObject *self, PyObject *args)
1697{
1698 PyStructObject *soself;
1699 PyObject *result;
1700
1701 /* Validate arguments. */
1702 soself = (PyStructObject *)self;
1703 assert(PyStruct_Check(self));
1704 assert(soself->s_codes != NULL);
Martin Blaisaf2ae722006-06-04 13:49:49 +00001705 if (PyTuple_GET_SIZE(args) != soself->s_len)
Martin Blais2856e5f2006-05-26 12:03:27 +00001706 {
1707 PyErr_Format(StructError,
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001708 "pack requires exactly %zd arguments", soself->s_len);
Martin Blais2856e5f2006-05-26 12:03:27 +00001709 return NULL;
1710 }
Tim Petersc2b550e2006-05-31 14:28:07 +00001711
Martin Blais2856e5f2006-05-26 12:03:27 +00001712 /* Allocate a new string */
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001713 result = PyString_FromStringAndSize((char *)NULL, soself->s_size);
Martin Blais2856e5f2006-05-26 12:03:27 +00001714 if (result == NULL)
1715 return NULL;
Tim Petersc2b550e2006-05-31 14:28:07 +00001716
Martin Blais2856e5f2006-05-26 12:03:27 +00001717 /* Call the guts */
Gregory P. Smithdd96db62008-06-09 04:58:54 +00001718 if ( s_pack_internal(soself, args, 0, PyString_AS_STRING(result)) != 0 ) {
Martin Blais2856e5f2006-05-26 12:03:27 +00001719 Py_DECREF(result);
1720 return NULL;
1721 }
1722
1723 return result;
1724}
1725
Martin Blaisaf2ae722006-06-04 13:49:49 +00001726PyDoc_STRVAR(s_pack_into__doc__,
1727"S.pack_into(buffer, offset, v1, v2, ...)\n\
Martin Blais2856e5f2006-05-26 12:03:27 +00001728\n\
Martin Blaisaf2ae722006-06-04 13:49:49 +00001729Pack the values v1, v2, ... according to this Struct's format, write \n\
Bob Ippolito1fcdc232006-05-27 12:11:36 +00001730the packed bytes into the writable buffer buf starting at offset. Note\n\
1731that the offset is not an optional argument. See struct.__doc__ for \n\
Martin Blais2856e5f2006-05-26 12:03:27 +00001732more on format strings.");
1733
1734static PyObject *
Martin Blaisaf2ae722006-06-04 13:49:49 +00001735s_pack_into(PyObject *self, PyObject *args)
Martin Blais2856e5f2006-05-26 12:03:27 +00001736{
1737 PyStructObject *soself;
1738 char *buffer;
1739 Py_ssize_t buffer_len, offset;
1740
1741 /* Validate arguments. +1 is for the first arg as buffer. */
1742 soself = (PyStructObject *)self;
1743 assert(PyStruct_Check(self));
1744 assert(soself->s_codes != NULL);
Martin Blaisaf2ae722006-06-04 13:49:49 +00001745 if (PyTuple_GET_SIZE(args) != (soself->s_len + 2))
Martin Blais2856e5f2006-05-26 12:03:27 +00001746 {
1747 PyErr_Format(StructError,
Martin Blaisaf2ae722006-06-04 13:49:49 +00001748 "pack_into requires exactly %zd arguments",
Martin Blais2856e5f2006-05-26 12:03:27 +00001749 (soself->s_len + 2));
1750 return NULL;
1751 }
1752
1753 /* Extract a writable memory buffer from the first argument */
Tim Petersc2b550e2006-05-31 14:28:07 +00001754 if ( PyObject_AsWriteBuffer(PyTuple_GET_ITEM(args, 0),
1755 (void**)&buffer, &buffer_len) == -1 ) {
Martin Blais2856e5f2006-05-26 12:03:27 +00001756 return NULL;
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001757 }
1758 assert( buffer_len >= 0 );
Martin Blais2856e5f2006-05-26 12:03:27 +00001759
1760 /* Extract the offset from the first argument */
Martin Blaisaf2ae722006-06-04 13:49:49 +00001761 offset = PyInt_AsSsize_t(PyTuple_GET_ITEM(args, 1));
Benjamin Peterson02252482008-09-30 02:11:07 +00001762 if (offset == -1 && PyErr_Occurred())
1763 return NULL;
Martin Blais2856e5f2006-05-26 12:03:27 +00001764
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001765 /* Support negative offsets. */
Martin Blais2856e5f2006-05-26 12:03:27 +00001766 if (offset < 0)
1767 offset += buffer_len;
1768
1769 /* Check boundaries */
1770 if (offset < 0 || (buffer_len - offset) < soself->s_size) {
1771 PyErr_Format(StructError,
Martin Blaisaf2ae722006-06-04 13:49:49 +00001772 "pack_into requires a buffer of at least %zd bytes",
Martin Blais2856e5f2006-05-26 12:03:27 +00001773 soself->s_size);
1774 return NULL;
1775 }
Tim Petersc2b550e2006-05-31 14:28:07 +00001776
Martin Blais2856e5f2006-05-26 12:03:27 +00001777 /* Call the guts */
1778 if ( s_pack_internal(soself, args, 2, buffer + offset) != 0 ) {
1779 return NULL;
1780 }
1781
Georg Brandlc26025c2006-05-28 21:42:54 +00001782 Py_RETURN_NONE;
Bob Ippolito232f3c92006-05-23 19:12:41 +00001783}
1784
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001785static PyObject *
1786s_get_format(PyStructObject *self, void *unused)
1787{
1788 Py_INCREF(self->s_format);
1789 return self->s_format;
1790}
1791
1792static PyObject *
1793s_get_size(PyStructObject *self, void *unused)
1794{
1795 return PyInt_FromSsize_t(self->s_size);
1796}
Bob Ippolito232f3c92006-05-23 19:12:41 +00001797
1798/* List of functions */
1799
1800static struct PyMethodDef s_methods[] = {
Martin Blaisaf2ae722006-06-04 13:49:49 +00001801 {"pack", s_pack, METH_VARARGS, s_pack__doc__},
1802 {"pack_into", s_pack_into, METH_VARARGS, s_pack_into__doc__},
1803 {"unpack", s_unpack, METH_O, s_unpack__doc__},
Neal Norwitza84dcd72007-05-22 07:16:44 +00001804 {"unpack_from", (PyCFunction)s_unpack_from, METH_VARARGS|METH_KEYWORDS,
Tim Peters5ec2e852006-06-04 15:49:07 +00001805 s_unpack_from__doc__},
Bob Ippolito232f3c92006-05-23 19:12:41 +00001806 {NULL, NULL} /* sentinel */
1807};
1808
1809PyDoc_STRVAR(s__doc__, "Compiled struct object");
1810
1811#define OFF(x) offsetof(PyStructObject, x)
1812
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001813static PyGetSetDef s_getsetlist[] = {
Bob Ippolito1fcdc232006-05-27 12:11:36 +00001814 {"format", (getter)s_get_format, (setter)NULL, "struct format string", NULL},
1815 {"size", (getter)s_get_size, (setter)NULL, "struct size in bytes", NULL},
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001816 {NULL} /* sentinel */
Bob Ippolito232f3c92006-05-23 19:12:41 +00001817};
1818
Bob Ippolito232f3c92006-05-23 19:12:41 +00001819static
1820PyTypeObject PyStructType = {
Martin v. Löwis68192102007-07-21 06:55:02 +00001821 PyVarObject_HEAD_INIT(NULL, 0)
Bob Ippolito232f3c92006-05-23 19:12:41 +00001822 "Struct",
1823 sizeof(PyStructObject),
1824 0,
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001825 (destructor)s_dealloc, /* tp_dealloc */
Bob Ippolito232f3c92006-05-23 19:12:41 +00001826 0, /* tp_print */
1827 0, /* tp_getattr */
1828 0, /* tp_setattr */
1829 0, /* tp_compare */
1830 0, /* tp_repr */
1831 0, /* tp_as_number */
1832 0, /* tp_as_sequence */
1833 0, /* tp_as_mapping */
1834 0, /* tp_hash */
1835 0, /* tp_call */
1836 0, /* tp_str */
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001837 PyObject_GenericGetAttr, /* tp_getattro */
1838 PyObject_GenericSetAttr, /* tp_setattro */
Bob Ippolito232f3c92006-05-23 19:12:41 +00001839 0, /* tp_as_buffer */
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001840 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_WEAKREFS,/* tp_flags */
1841 s__doc__, /* tp_doc */
Bob Ippolito232f3c92006-05-23 19:12:41 +00001842 0, /* tp_traverse */
1843 0, /* tp_clear */
1844 0, /* tp_richcompare */
1845 offsetof(PyStructObject, weakreflist), /* tp_weaklistoffset */
1846 0, /* tp_iter */
1847 0, /* tp_iternext */
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001848 s_methods, /* tp_methods */
1849 NULL, /* tp_members */
1850 s_getsetlist, /* tp_getset */
Bob Ippolito232f3c92006-05-23 19:12:41 +00001851 0, /* tp_base */
1852 0, /* tp_dict */
1853 0, /* tp_descr_get */
1854 0, /* tp_descr_set */
1855 0, /* tp_dictoffset */
Bob Ippolitoaa70a172006-05-26 20:25:23 +00001856 s_init, /* tp_init */
1857 PyType_GenericAlloc,/* tp_alloc */
1858 s_new, /* tp_new */
1859 PyObject_Del, /* tp_free */
Bob Ippolito232f3c92006-05-23 19:12:41 +00001860};
1861
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001862
1863/* ---- Standalone functions ---- */
1864
1865#define MAXCACHE 100
Christian Heimes76d19f62008-01-04 02:54:42 +00001866static PyObject *cache = NULL;
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001867
1868static PyObject *
1869cache_struct(PyObject *fmt)
1870{
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001871 PyObject * s_object;
1872
1873 if (cache == NULL) {
1874 cache = PyDict_New();
1875 if (cache == NULL)
1876 return NULL;
1877 }
1878
1879 s_object = PyDict_GetItem(cache, fmt);
1880 if (s_object != NULL) {
1881 Py_INCREF(s_object);
1882 return s_object;
1883 }
1884
1885 s_object = PyObject_CallFunctionObjArgs((PyObject *)(&PyStructType), fmt, NULL);
1886 if (s_object != NULL) {
1887 if (PyDict_Size(cache) >= MAXCACHE)
1888 PyDict_Clear(cache);
1889 /* Attempt to cache the result */
1890 if (PyDict_SetItem(cache, fmt, s_object) == -1)
1891 PyErr_Clear();
1892 }
1893 return s_object;
1894}
1895
Christian Heimes76d19f62008-01-04 02:54:42 +00001896PyDoc_STRVAR(clearcache_doc,
1897"Clear the internal cache.");
1898
1899static PyObject *
1900clearcache(PyObject *self)
1901{
Raymond Hettinger18e08e52008-01-18 00:10:42 +00001902 Py_CLEAR(cache);
Christian Heimes76d19f62008-01-04 02:54:42 +00001903 Py_RETURN_NONE;
1904}
1905
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00001906PyDoc_STRVAR(calcsize_doc,
1907"Return size of C struct described by format string fmt.");
1908
1909static PyObject *
1910calcsize(PyObject *self, PyObject *fmt)
1911{
1912 Py_ssize_t n;
1913 PyObject *s_object = cache_struct(fmt);
1914 if (s_object == NULL)
1915 return NULL;
1916 n = ((PyStructObject *)s_object)->s_size;
1917 Py_DECREF(s_object);
1918 return PyInt_FromSsize_t(n);
1919}
1920
1921PyDoc_STRVAR(pack_doc,
1922"Return string containing values v1, v2, ... packed according to fmt.");
1923
1924static PyObject *
1925pack(PyObject *self, PyObject *args)
1926{
1927 PyObject *s_object, *fmt, *newargs, *result;
1928 Py_ssize_t n = PyTuple_GET_SIZE(args);
1929
1930 if (n == 0) {
1931 PyErr_SetString(PyExc_TypeError, "missing format argument");
1932 return NULL;
1933 }
1934 fmt = PyTuple_GET_ITEM(args, 0);
1935 newargs = PyTuple_GetSlice(args, 1, n);
1936 if (newargs == NULL)
1937 return NULL;
1938
1939 s_object = cache_struct(fmt);
1940 if (s_object == NULL) {
1941 Py_DECREF(newargs);
1942 return NULL;
1943 }
1944 result = s_pack(s_object, newargs);
1945 Py_DECREF(newargs);
1946 Py_DECREF(s_object);
1947 return result;
1948}
1949
1950PyDoc_STRVAR(pack_into_doc,
1951"Pack the values v1, v2, ... according to fmt.\n\
1952Write the packed bytes into the writable buffer buf starting at offset.");
1953
1954static PyObject *
1955pack_into(PyObject *self, PyObject *args)
1956{
1957 PyObject *s_object, *fmt, *newargs, *result;
1958 Py_ssize_t n = PyTuple_GET_SIZE(args);
1959
1960 if (n == 0) {
1961 PyErr_SetString(PyExc_TypeError, "missing format argument");
1962 return NULL;
1963 }
1964 fmt = PyTuple_GET_ITEM(args, 0);
1965 newargs = PyTuple_GetSlice(args, 1, n);
1966 if (newargs == NULL)
1967 return NULL;
1968
1969 s_object = cache_struct(fmt);
1970 if (s_object == NULL) {
1971 Py_DECREF(newargs);
1972 return NULL;
1973 }
1974 result = s_pack_into(s_object, newargs);
1975 Py_DECREF(newargs);
1976 Py_DECREF(s_object);
1977 return result;
1978}
1979
1980PyDoc_STRVAR(unpack_doc,
1981"Unpack the string containing packed C structure data, according to fmt.\n\
1982Requires len(string) == calcsize(fmt).");
1983
1984static PyObject *
1985unpack(PyObject *self, PyObject *args)
1986{
1987 PyObject *s_object, *fmt, *inputstr, *result;
1988
1989 if (!PyArg_UnpackTuple(args, "unpack", 2, 2, &fmt, &inputstr))
1990 return NULL;
1991
1992 s_object = cache_struct(fmt);
1993 if (s_object == NULL)
1994 return NULL;
1995 result = s_unpack(s_object, inputstr);
1996 Py_DECREF(s_object);
1997 return result;
1998}
1999
2000PyDoc_STRVAR(unpack_from_doc,
2001"Unpack the buffer, containing packed C structure data, according to\n\
2002fmt, starting at offset. Requires len(buffer[offset:]) >= calcsize(fmt).");
2003
2004static PyObject *
2005unpack_from(PyObject *self, PyObject *args, PyObject *kwds)
2006{
2007 PyObject *s_object, *fmt, *newargs, *result;
2008 Py_ssize_t n = PyTuple_GET_SIZE(args);
2009
2010 if (n == 0) {
2011 PyErr_SetString(PyExc_TypeError, "missing format argument");
2012 return NULL;
2013 }
2014 fmt = PyTuple_GET_ITEM(args, 0);
2015 newargs = PyTuple_GetSlice(args, 1, n);
2016 if (newargs == NULL)
2017 return NULL;
2018
2019 s_object = cache_struct(fmt);
2020 if (s_object == NULL) {
2021 Py_DECREF(newargs);
2022 return NULL;
2023 }
2024 result = s_unpack_from(s_object, newargs, kwds);
2025 Py_DECREF(newargs);
2026 Py_DECREF(s_object);
2027 return result;
2028}
2029
2030static struct PyMethodDef module_functions[] = {
Christian Heimes76d19f62008-01-04 02:54:42 +00002031 {"_clearcache", (PyCFunction)clearcache, METH_NOARGS, clearcache_doc},
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00002032 {"calcsize", calcsize, METH_O, calcsize_doc},
2033 {"pack", pack, METH_VARARGS, pack_doc},
2034 {"pack_into", pack_into, METH_VARARGS, pack_into_doc},
2035 {"unpack", unpack, METH_VARARGS, unpack_doc},
2036 {"unpack_from", (PyCFunction)unpack_from,
2037 METH_VARARGS|METH_KEYWORDS, unpack_from_doc},
2038 {NULL, NULL} /* sentinel */
2039};
2040
2041
Bob Ippolito232f3c92006-05-23 19:12:41 +00002042/* Module initialization */
2043
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00002044PyDoc_STRVAR(module_doc,
Mark Dickinson9b125532009-10-27 17:00:03 +00002045"Functions to convert between Python values and C structs represented\n\
2046as Python strings. It uses format strings (explained below) as compact\n\
2047descriptions of the lay-out of the C structs and the intended conversion\n\
2048to/from Python values.\n\
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00002049\n\
2050The optional first format char indicates byte order, size and alignment:\n\
Mark Dickinson9b125532009-10-27 17:00:03 +00002051 @: native order, size & alignment (default)\n\
2052 =: native order, std. size & alignment\n\
2053 <: little-endian, std. size & alignment\n\
2054 >: big-endian, std. size & alignment\n\
2055 !: same as >\n\
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00002056\n\
2057The remaining chars indicate types of args and must match exactly;\n\
2058these can be preceded by a decimal repeat count:\n\
2059 x: pad byte (no data); c:char; b:signed byte; B:unsigned byte;\n\
Mark Dickinson9b125532009-10-27 17:00:03 +00002060 ?: _Bool (requires C99; if not available, char is used instead)\n\
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00002061 h:short; H:unsigned short; i:int; I:unsigned int;\n\
2062 l:long; L:unsigned long; f:float; d:double.\n\
2063Special cases (preceding decimal count indicates length):\n\
2064 s:string (array of char); p: pascal string (with count byte).\n\
2065Special case (only available in native format):\n\
2066 P:an integer type that is wide enough to hold a pointer.\n\
2067Special case (not in native mode unless 'long long' in platform C):\n\
2068 q:long long; Q:unsigned long long\n\
2069Whitespace between formats is ignored.\n\
2070\n\
2071The variable struct.error is an exception raised on errors.\n");
2072
Bob Ippolito232f3c92006-05-23 19:12:41 +00002073PyMODINIT_FUNC
2074init_struct(void)
2075{
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00002076 PyObject *ver, *m;
2077
Gregory P. Smithdd96db62008-06-09 04:58:54 +00002078 ver = PyString_FromString("0.2");
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00002079 if (ver == NULL)
2080 return;
2081
2082 m = Py_InitModule3("_struct", module_functions, module_doc);
Bob Ippolito232f3c92006-05-23 19:12:41 +00002083 if (m == NULL)
2084 return;
2085
Christian Heimese93237d2007-12-19 02:37:44 +00002086 Py_TYPE(&PyStructType) = &PyType_Type;
Bob Ippolito3fc2bb92006-05-25 19:03:19 +00002087 if (PyType_Ready(&PyStructType) < 0)
2088 return;
2089
Bob Ippolito4182a752006-05-30 17:37:54 +00002090#ifdef PY_STRUCT_OVERFLOW_MASKING
Bob Ippolito2fd39772006-05-29 22:55:48 +00002091 if (pyint_zero == NULL) {
2092 pyint_zero = PyInt_FromLong(0);
2093 if (pyint_zero == NULL)
2094 return;
2095 }
2096 if (pylong_ulong_mask == NULL) {
2097#if (SIZEOF_LONG == 4)
2098 pylong_ulong_mask = PyLong_FromString("FFFFFFFF", NULL, 16);
2099#else
2100 pylong_ulong_mask = PyLong_FromString("FFFFFFFFFFFFFFFF", NULL, 16);
2101#endif
2102 if (pylong_ulong_mask == NULL)
2103 return;
2104 }
2105
Tim Petersc2b550e2006-05-31 14:28:07 +00002106#else
Bob Ippolito4182a752006-05-30 17:37:54 +00002107 /* This speed trick can't be used until overflow masking goes away, because
2108 native endian always raises exceptions instead of overflow masking. */
Tim Petersc2b550e2006-05-31 14:28:07 +00002109
Bob Ippolitoa99865b2006-05-25 19:56:56 +00002110 /* Check endian and swap in faster functions */
2111 {
2112 int one = 1;
2113 formatdef *native = native_table;
2114 formatdef *other, *ptr;
2115 if ((int)*(unsigned char*)&one)
2116 other = lilendian_table;
2117 else
2118 other = bigendian_table;
Bob Ippolito964e02a2006-05-25 21:09:45 +00002119 /* Scan through the native table, find a matching
2120 entry in the endian table and swap in the
2121 native implementations whenever possible
2122 (64-bit platforms may not have "standard" sizes) */
Bob Ippolitoa99865b2006-05-25 19:56:56 +00002123 while (native->format != '\0' && other->format != '\0') {
2124 ptr = other;
2125 while (ptr->format != '\0') {
2126 if (ptr->format == native->format) {
Bob Ippolito964e02a2006-05-25 21:09:45 +00002127 /* Match faster when formats are
2128 listed in the same order */
Bob Ippolitoa99865b2006-05-25 19:56:56 +00002129 if (ptr == other)
2130 other++;
Tim Petersc2b550e2006-05-31 14:28:07 +00002131 /* Only use the trick if the
Bob Ippolito964e02a2006-05-25 21:09:45 +00002132 size matches */
2133 if (ptr->size != native->size)
2134 break;
2135 /* Skip float and double, could be
2136 "unknown" float format */
2137 if (ptr->format == 'd' || ptr->format == 'f')
2138 break;
2139 ptr->pack = native->pack;
2140 ptr->unpack = native->unpack;
Bob Ippolitoa99865b2006-05-25 19:56:56 +00002141 break;
2142 }
2143 ptr++;
2144 }
2145 native++;
2146 }
2147 }
Bob Ippolito2fd39772006-05-29 22:55:48 +00002148#endif
Tim Petersc2b550e2006-05-31 14:28:07 +00002149
Bob Ippolito232f3c92006-05-23 19:12:41 +00002150 /* Add some symbolic constants to the module */
2151 if (StructError == NULL) {
2152 StructError = PyErr_NewException("struct.error", NULL, NULL);
2153 if (StructError == NULL)
2154 return;
2155 }
Bob Ippolito04ab9942006-05-25 19:33:38 +00002156
Bob Ippolito232f3c92006-05-23 19:12:41 +00002157 Py_INCREF(StructError);
2158 PyModule_AddObject(m, "error", StructError);
Bob Ippolito04ab9942006-05-25 19:33:38 +00002159
Bob Ippolito232f3c92006-05-23 19:12:41 +00002160 Py_INCREF((PyObject*)&PyStructType);
2161 PyModule_AddObject(m, "Struct", (PyObject*)&PyStructType);
Tim Petersc2b550e2006-05-31 14:28:07 +00002162
Raymond Hettinger2f6621c2008-01-04 00:01:15 +00002163 PyModule_AddObject(m, "__version__", ver);
2164
Bob Ippolito2fd39772006-05-29 22:55:48 +00002165 PyModule_AddIntConstant(m, "_PY_STRUCT_RANGE_CHECKING", 1);
Bob Ippolito4182a752006-05-30 17:37:54 +00002166#ifdef PY_STRUCT_OVERFLOW_MASKING
2167 PyModule_AddIntConstant(m, "_PY_STRUCT_OVERFLOW_MASKING", 1);
Bob Ippolito2fd39772006-05-29 22:55:48 +00002168#endif
Bob Ippolitoe6c9f982006-08-04 23:59:21 +00002169#ifdef PY_STRUCT_FLOAT_COERCE
2170 PyModule_AddIntConstant(m, "_PY_STRUCT_FLOAT_COERCE", 1);
2171#endif
2172
Bob Ippolito232f3c92006-05-23 19:12:41 +00002173}