1 /* struct module -- pack values into and (out of) strings */
3 /* New version supporting byte order, alignment and size options,
4 character strings, and unsigned numbers */
6 #define PY_SSIZE_T_CLEAN
10 #include "structmember.h"
13 static PyTypeObject PyStructType;
15 /* compatibility macros */
16 #if (PY_VERSION_HEX < 0x02050000)
17 typedef int Py_ssize_t;
20 /* If PY_STRUCT_OVERFLOW_MASKING is defined, the struct module will wrap all input
21 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
27 #define PY_STRUCT_OVERFLOW_MASKING 1
29 #ifdef PY_STRUCT_OVERFLOW_MASKING
30 static PyObject *pylong_ulong_mask = NULL;
31 static PyObject *pyint_zero = NULL;
34 /* If PY_STRUCT_FLOAT_COERCE is defined, the struct module will allow float
35 arguments for integer formats with a warning for backwards
38 #define PY_STRUCT_FLOAT_COERCE 1
40 #ifdef PY_STRUCT_FLOAT_COERCE
41 #define FLOAT_COERCE "integer argument expected, got float"
45 /* The translation function for each format character is table driven */
46 typedef struct _formatdef {
50 PyObject* (*unpack)(const char *,
51 const struct _formatdef *);
52 int (*pack)(char *, PyObject *,
53 const struct _formatdef *);
56 typedef struct _formatcode {
57 const struct _formatdef *fmtdef;
62 /* Struct object interface */
70 PyObject *weakreflist; /* List of weak references */
74 #define PyStruct_Check(op) PyObject_TypeCheck(op, &PyStructType)
75 #define PyStruct_CheckExact(op) (Py_TYPE(op) == &PyStructType)
80 static PyObject *StructError;
83 /* Define various structs to figure out the alignments of types */
86 typedef struct { char c; short x; } st_short;
87 typedef struct { char c; int x; } st_int;
88 typedef struct { char c; long x; } st_long;
89 typedef struct { char c; float x; } st_float;
90 typedef struct { char c; double x; } st_double;
91 typedef struct { char c; void *x; } st_void_p;
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 *))
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
103 typedef struct { char c; PY_LONG_LONG x; } s_long_long;
104 #define LONG_LONG_ALIGN (sizeof(s_long_long) - sizeof(PY_LONG_LONG))
108 #define BOOL_TYPE _Bool
109 typedef struct { char c; _Bool x; } s_bool;
110 #define BOOL_ALIGN (sizeof(s_bool) - sizeof(BOOL_TYPE))
112 #define BOOL_TYPE char
116 #define STRINGIFY(x) #x
119 #pragma options align=reset
122 /* Helper to get a PyLongObject by hook or by crook. Caller should decref. */
125 get_pylong(PyObject *v)
131 return PyLong_FromLong(PyInt_AS_LONG(v));
132 if (PyLong_Check(v)) {
136 m = Py_TYPE(v)->tp_as_number;
137 if (m != NULL && m->nb_long != NULL) {
145 PyErr_SetString(StructError,
146 "cannot convert argument to long");
150 /* Helper routine to get a Python integer and raise the appropriate error
154 get_long(PyObject *v, long *p)
156 long x = PyInt_AsLong(v);
157 if (x == -1 && PyErr_Occurred()) {
158 #ifdef PY_STRUCT_FLOAT_COERCE
159 if (PyFloat_Check(v)) {
163 if (PyErr_WarnEx(PyExc_DeprecationWarning, FLOAT_COERCE, 2) < 0)
168 res = get_long(o, p);
173 if (PyErr_ExceptionMatches(PyExc_TypeError))
174 PyErr_SetString(StructError,
175 "required argument is not an integer");
183 /* Same, but handling unsigned long */
185 #ifndef PY_STRUCT_OVERFLOW_MASKING
188 get_ulong(PyObject *v, unsigned long *p)
190 if (PyLong_Check(v)) {
191 unsigned long x = PyLong_AsUnsignedLong(v);
192 if (x == (unsigned long)(-1) && PyErr_Occurred())
197 if (get_long(v, (long *)p) < 0)
199 if (((long)*p) < 0) {
200 PyErr_SetString(StructError,
201 "unsigned argument is < 0");
207 #endif /* PY_STRUCT_OVERFLOW_MASKING */
209 #ifdef HAVE_LONG_LONG
211 /* Same, but handling native long long. */
214 get_longlong(PyObject *v, PY_LONG_LONG *p)
221 assert(PyLong_Check(v));
222 x = PyLong_AsLongLong(v);
224 if (x == (PY_LONG_LONG)-1 && PyErr_Occurred())
230 /* Same, but handling native unsigned long long. */
233 get_ulonglong(PyObject *v, unsigned PY_LONG_LONG *p)
235 unsigned PY_LONG_LONG x;
240 assert(PyLong_Check(v));
241 x = PyLong_AsUnsignedLongLong(v);
243 if (x == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred())
251 #ifdef PY_STRUCT_OVERFLOW_MASKING
253 /* Helper routine to get a Python integer and raise the appropriate error
256 #define INT_OVERFLOW "struct integer overflow masking is deprecated"
259 get_wrapped_long(PyObject *v, long *p)
261 if (get_long(v, p) < 0) {
262 if (PyLong_Check(v) &&
263 PyErr_ExceptionMatches(PyExc_OverflowError)) {
267 #ifdef PY_STRUCT_FLOAT_COERCE
268 if (PyFloat_Check(v)) {
272 if (PyErr_WarnEx(PyExc_DeprecationWarning, FLOAT_COERCE, 2) < 0)
277 res = get_wrapped_long(o, p);
282 if (PyErr_WarnEx(PyExc_DeprecationWarning, INT_OVERFLOW, 2) < 0)
284 wrapped = PyNumber_And(v, pylong_ulong_mask);
287 x = (long)PyLong_AsUnsignedLong(wrapped);
289 if (x == -1 && PyErr_Occurred())
300 get_wrapped_ulong(PyObject *v, unsigned long *p)
302 long x = (long)PyLong_AsUnsignedLong(v);
303 if (x == -1 && PyErr_Occurred()) {
306 #ifdef PY_STRUCT_FLOAT_COERCE
307 if (PyFloat_Check(v)) {
311 if (PyErr_WarnEx(PyExc_DeprecationWarning, FLOAT_COERCE, 2) < 0)
316 res = get_wrapped_ulong(o, p);
321 wrapped = PyNumber_And(v, pylong_ulong_mask);
324 if (PyErr_WarnEx(PyExc_DeprecationWarning, INT_OVERFLOW, 2) < 0) {
328 x = (long)PyLong_AsUnsignedLong(wrapped);
330 if (x == -1 && PyErr_Occurred())
333 *p = (unsigned long)x;
337 #define RANGE_ERROR(x, f, flag, mask) \
339 if (_range_error(f, flag) < 0) \
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)
353 /* Floating point helpers */
356 unpack_float(const char *p, /* start of 4-byte string */
357 int le) /* true for little-endian, false for big-endian */
361 x = _PyFloat_Unpack4((unsigned char *)p, le);
362 if (x == -1.0 && PyErr_Occurred())
364 return PyFloat_FromDouble(x);
368 unpack_double(const char *p, /* start of 8-byte string */
369 int le) /* true for little-endian, false for big-endian */
373 x = _PyFloat_Unpack8((unsigned char *)p, le);
374 if (x == -1.0 && PyErr_Occurred())
376 return PyFloat_FromDouble(x);
379 /* Helper to format the range error exceptions */
381 _range_error(const formatdef *f, int is_unsigned)
383 /* 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.
391 const size_t ulargest = (size_t)-1 >> ((SIZEOF_SIZE_T - f->size)*8);
392 assert(f->size >= 1 && f->size <= SIZEOF_SIZE_T);
394 PyErr_Format(StructError,
395 "'%c' format requires 0 <= number <= %zu",
399 const Py_ssize_t largest = (Py_ssize_t)(ulargest >> 1);
400 PyErr_Format(StructError,
401 "'%c' format requires %zd <= number <= %zd",
406 #ifdef PY_STRUCT_OVERFLOW_MASKING
408 PyObject *ptype, *pvalue, *ptraceback;
411 PyErr_Fetch(&ptype, &pvalue, &ptraceback);
412 assert(pvalue != NULL);
413 msg = PyObject_Str(pvalue);
416 Py_XDECREF(ptraceback);
419 rval = PyErr_WarnEx(PyExc_DeprecationWarning,
420 PyString_AS_STRING(msg), 2);
431 /* A large number of small routines follow, with names of the form
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.
440 /* Native mode routines. ****************************************************/
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
451 nu_char(const char *p, const formatdef *f)
453 return PyString_FromStringAndSize(p, 1);
457 nu_byte(const char *p, const formatdef *f)
459 return PyInt_FromLong((long) *(signed char *)p);
463 nu_ubyte(const char *p, const formatdef *f)
465 return PyInt_FromLong((long) *(unsigned char *)p);
469 nu_short(const char *p, const formatdef *f)
472 memcpy((char *)&x, p, sizeof x);
473 return PyInt_FromLong((long)x);
477 nu_ushort(const char *p, const formatdef *f)
480 memcpy((char *)&x, p, sizeof x);
481 return PyInt_FromLong((long)x);
485 nu_int(const char *p, const formatdef *f)
488 memcpy((char *)&x, p, sizeof x);
489 return PyInt_FromLong((long)x);
493 nu_uint(const char *p, const formatdef *f)
496 memcpy((char *)&x, p, sizeof x);
497 #if (SIZEOF_LONG > SIZEOF_INT)
498 return PyInt_FromLong((long)x);
500 if (x <= ((unsigned int)LONG_MAX))
501 return PyInt_FromLong((long)x);
502 return PyLong_FromUnsignedLong((unsigned long)x);
507 nu_long(const char *p, const formatdef *f)
510 memcpy((char *)&x, p, sizeof x);
511 return PyInt_FromLong(x);
515 nu_ulong(const char *p, const formatdef *f)
518 memcpy((char *)&x, p, sizeof x);
520 return PyInt_FromLong((long)x);
521 return PyLong_FromUnsignedLong(x);
524 /* Native mode doesn't support q or Q unless the platform C supports
525 long long (or, on Windows, __int64). */
527 #ifdef HAVE_LONG_LONG
530 nu_longlong(const char *p, const formatdef *f)
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);
540 nu_ulonglong(const char *p, const formatdef *f)
542 unsigned PY_LONG_LONG x;
543 memcpy((char *)&x, p, sizeof x);
545 return PyInt_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long));
546 return PyLong_FromUnsignedLongLong(x);
552 nu_bool(const char *p, const formatdef *f)
555 memcpy((char *)&x, p, sizeof x);
556 return PyBool_FromLong(x != 0);
561 nu_float(const char *p, const formatdef *f)
564 memcpy((char *)&x, p, sizeof x);
565 return PyFloat_FromDouble((double)x);
569 nu_double(const char *p, const formatdef *f)
572 memcpy((char *)&x, p, sizeof x);
573 return PyFloat_FromDouble(x);
577 nu_void_p(const char *p, const formatdef *f)
580 memcpy((char *)&x, p, sizeof x);
581 return PyLong_FromVoidPtr(x);
585 np_byte(char *p, PyObject *v, const formatdef *f)
588 if (get_long(v, &x) < 0)
590 if (x < -128 || x > 127){
591 PyErr_SetString(StructError,
592 "byte format requires -128 <= number <= 127");
600 np_ubyte(char *p, PyObject *v, const formatdef *f)
603 if (get_long(v, &x) < 0)
605 if (x < 0 || x > 255){
606 PyErr_SetString(StructError,
607 "ubyte format requires 0 <= number <= 255");
615 np_char(char *p, PyObject *v, const formatdef *f)
617 if (!PyString_Check(v) || PyString_Size(v) != 1) {
618 PyErr_SetString(StructError,
619 "char format require string of length 1");
622 *p = *PyString_AsString(v);
627 np_short(char *p, PyObject *v, const formatdef *f)
631 if (get_long(v, &x) < 0)
633 if (x < SHRT_MIN || x > SHRT_MAX){
634 PyErr_SetString(StructError,
635 "short format requires " STRINGIFY(SHRT_MIN)
636 " <= number <= " STRINGIFY(SHRT_MAX));
640 memcpy(p, (char *)&y, sizeof y);
645 np_ushort(char *p, PyObject *v, const formatdef *f)
649 if (get_long(v, &x) < 0)
651 if (x < 0 || x > USHRT_MAX){
652 PyErr_SetString(StructError,
653 "ushort format requires 0 <= number <= " STRINGIFY(USHRT_MAX));
656 y = (unsigned short)x;
657 memcpy(p, (char *)&y, sizeof y);
662 np_int(char *p, PyObject *v, const formatdef *f)
666 if (get_long(v, &x) < 0)
668 #if (SIZEOF_LONG > SIZEOF_INT)
669 if ((x < ((long)INT_MIN)) || (x > ((long)INT_MAX)))
670 RANGE_ERROR(x, f, 0, -1);
673 memcpy(p, (char *)&y, sizeof y);
678 np_uint(char *p, PyObject *v, const formatdef *f)
682 if (get_wrapped_ulong(v, &x) < 0)
685 #if (SIZEOF_LONG > SIZEOF_INT)
686 if (x > ((unsigned long)UINT_MAX))
687 RANGE_ERROR(y, f, 1, -1);
689 memcpy(p, (char *)&y, sizeof y);
694 np_long(char *p, PyObject *v, const formatdef *f)
697 if (get_long(v, &x) < 0)
699 memcpy(p, (char *)&x, sizeof x);
704 np_ulong(char *p, PyObject *v, const formatdef *f)
707 if (get_wrapped_ulong(v, &x) < 0)
709 memcpy(p, (char *)&x, sizeof x);
713 #ifdef HAVE_LONG_LONG
716 np_longlong(char *p, PyObject *v, const formatdef *f)
719 if (get_longlong(v, &x) < 0)
721 memcpy(p, (char *)&x, sizeof x);
726 np_ulonglong(char *p, PyObject *v, const formatdef *f)
728 unsigned PY_LONG_LONG x;
729 if (get_ulonglong(v, &x) < 0)
731 memcpy(p, (char *)&x, sizeof x);
738 np_bool(char *p, PyObject *v, const formatdef *f)
741 y = PyObject_IsTrue(v);
742 memcpy(p, (char *)&y, sizeof y);
747 np_float(char *p, PyObject *v, const formatdef *f)
749 float x = (float)PyFloat_AsDouble(v);
750 if (x == -1 && PyErr_Occurred()) {
751 PyErr_SetString(StructError,
752 "required argument is not a float");
755 memcpy(p, (char *)&x, sizeof x);
760 np_double(char *p, PyObject *v, const formatdef *f)
762 double x = PyFloat_AsDouble(v);
763 if (x == -1 && PyErr_Occurred()) {
764 PyErr_SetString(StructError,
765 "required argument is not a float");
768 memcpy(p, (char *)&x, sizeof(double));
773 np_void_p(char *p, PyObject *v, const formatdef *f)
780 assert(PyLong_Check(v));
781 x = PyLong_AsVoidPtr(v);
783 if (x == NULL && PyErr_Occurred())
785 memcpy(p, (char *)&x, sizeof x);
789 static 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},
802 #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},
806 {'?', 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},
813 /* Big-endian routines. *****************************************************/
816 bu_int(const char *p, const formatdef *f)
819 Py_ssize_t i = f->size;
820 const unsigned char *bytes = (const unsigned char *)p;
822 x = (x<<8) | *bytes++;
824 /* Extend the sign bit. */
825 if (SIZEOF_LONG > f->size)
826 x |= -(x & (1L << ((8 * f->size) - 1)));
827 return PyInt_FromLong(x);
831 bu_uint(const char *p, const formatdef *f)
834 Py_ssize_t i = f->size;
835 const unsigned char *bytes = (const unsigned char *)p;
837 x = (x<<8) | *bytes++;
840 return PyInt_FromLong((long)x);
841 return PyLong_FromUnsignedLong(x);
845 bu_longlong(const char *p, const formatdef *f)
847 #ifdef HAVE_LONG_LONG
849 Py_ssize_t i = f->size;
850 const unsigned char *bytes = (const unsigned char *)p;
852 x = (x<<8) | *bytes++;
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);
861 return _PyLong_FromByteArray((const unsigned char *)p,
863 0, /* little-endian */
869 bu_ulonglong(const char *p, const formatdef *f)
871 #ifdef HAVE_LONG_LONG
872 unsigned PY_LONG_LONG x = 0;
873 Py_ssize_t i = f->size;
874 const unsigned char *bytes = (const unsigned char *)p;
876 x = (x<<8) | *bytes++;
879 return PyInt_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long));
880 return PyLong_FromUnsignedLongLong(x);
882 return _PyLong_FromByteArray((const unsigned char *)p,
884 0, /* little-endian */
890 bu_float(const char *p, const formatdef *f)
892 return unpack_float(p, 0);
896 bu_double(const char *p, const formatdef *f)
898 return unpack_double(p, 0);
902 bu_bool(const char *p, const formatdef *f)
905 memcpy((char *)&x, p, sizeof x);
906 return PyBool_FromLong(x != 0);
910 bp_int(char *p, PyObject *v, const formatdef *f)
914 if (get_wrapped_long(v, &x) < 0)
917 if (i != SIZEOF_LONG) {
918 if ((i == 2) && (x < -32768 || x > 32767))
919 RANGE_ERROR(x, f, 0, 0xffffL);
920 #if (SIZEOF_LONG != 4)
921 else if ((i == 4) && (x < -2147483648L || x > 2147483647L))
922 RANGE_ERROR(x, f, 0, 0xffffffffL);
924 #ifdef PY_STRUCT_OVERFLOW_MASKING
925 else if ((i == 1) && (x < -128 || x > 127))
926 RANGE_ERROR(x, f, 0, 0xffL);
937 bp_uint(char *p, PyObject *v, const formatdef *f)
941 if (get_wrapped_ulong(v, &x) < 0)
944 if (i != SIZEOF_LONG) {
945 unsigned long maxint = 1;
946 maxint <<= (unsigned long)(i * 8);
948 RANGE_ERROR(x, f, 1, maxint - 1);
958 bp_longlong(char *p, PyObject *v, const formatdef *f)
964 res = _PyLong_AsByteArray((PyLongObject *)v,
967 0, /* little_endian */
974 bp_ulonglong(char *p, PyObject *v, const formatdef *f)
980 res = _PyLong_AsByteArray((PyLongObject *)v,
983 0, /* little_endian */
990 bp_float(char *p, PyObject *v, const formatdef *f)
992 double x = PyFloat_AsDouble(v);
993 if (x == -1 && PyErr_Occurred()) {
994 PyErr_SetString(StructError,
995 "required argument is not a float");
998 return _PyFloat_Pack4(x, (unsigned char *)p, 0);
1002 bp_double(char *p, PyObject *v, const formatdef *f)
1004 double x = PyFloat_AsDouble(v);
1005 if (x == -1 && PyErr_Occurred()) {
1006 PyErr_SetString(StructError,
1007 "required argument is not a float");
1010 return _PyFloat_Pack8(x, (unsigned char *)p, 0);
1014 bp_bool(char *p, PyObject *v, const formatdef *f)
1017 y = PyObject_IsTrue(v);
1018 memcpy(p, (char *)&y, sizeof y);
1022 static formatdef bigendian_table[] = {
1024 #ifdef PY_STRUCT_OVERFLOW_MASKING
1025 /* Native packers do range checking without overflow masking. */
1026 {'b', 1, 0, nu_byte, bp_int},
1027 {'B', 1, 0, nu_ubyte, bp_uint},
1029 {'b', 1, 0, nu_byte, np_byte},
1030 {'B', 1, 0, nu_ubyte, np_ubyte},
1032 {'c', 1, 0, nu_char, np_char},
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},
1049 /* Little-endian routines. *****************************************************/
1052 lu_int(const char *p, const formatdef *f)
1055 Py_ssize_t i = f->size;
1056 const unsigned char *bytes = (const unsigned char *)p;
1058 x = (x<<8) | bytes[--i];
1060 /* Extend the sign bit. */
1061 if (SIZEOF_LONG > f->size)
1062 x |= -(x & (1L << ((8 * f->size) - 1)));
1063 return PyInt_FromLong(x);
1067 lu_uint(const char *p, const formatdef *f)
1069 unsigned long x = 0;
1070 Py_ssize_t i = f->size;
1071 const unsigned char *bytes = (const unsigned char *)p;
1073 x = (x<<8) | bytes[--i];
1076 return PyInt_FromLong((long)x);
1077 return PyLong_FromUnsignedLong((long)x);
1081 lu_longlong(const char *p, const formatdef *f)
1083 #ifdef HAVE_LONG_LONG
1085 Py_ssize_t i = f->size;
1086 const unsigned char *bytes = (const unsigned char *)p;
1088 x = (x<<8) | bytes[--i];
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);
1097 return _PyLong_FromByteArray((const unsigned char *)p,
1099 1, /* little-endian */
1105 lu_ulonglong(const char *p, const formatdef *f)
1107 #ifdef HAVE_LONG_LONG
1108 unsigned PY_LONG_LONG x = 0;
1109 Py_ssize_t i = f->size;
1110 const unsigned char *bytes = (const unsigned char *)p;
1112 x = (x<<8) | bytes[--i];
1115 return PyInt_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long));
1116 return PyLong_FromUnsignedLongLong(x);
1118 return _PyLong_FromByteArray((const unsigned char *)p,
1120 1, /* little-endian */
1126 lu_float(const char *p, const formatdef *f)
1128 return unpack_float(p, 1);
1132 lu_double(const char *p, const formatdef *f)
1134 return unpack_double(p, 1);
1138 lp_int(char *p, PyObject *v, const formatdef *f)
1142 if (get_wrapped_long(v, &x) < 0)
1145 if (i != SIZEOF_LONG) {
1146 if ((i == 2) && (x < -32768 || x > 32767))
1147 RANGE_ERROR(x, f, 0, 0xffffL);
1148 #if (SIZEOF_LONG != 4)
1149 else if ((i == 4) && (x < -2147483648L || x > 2147483647L))
1150 RANGE_ERROR(x, f, 0, 0xffffffffL);
1152 #ifdef PY_STRUCT_OVERFLOW_MASKING
1153 else if ((i == 1) && (x < -128 || x > 127))
1154 RANGE_ERROR(x, f, 0, 0xffL);
1165 lp_uint(char *p, PyObject *v, const formatdef *f)
1169 if (get_wrapped_ulong(v, &x) < 0)
1172 if (i != SIZEOF_LONG) {
1173 unsigned long maxint = 1;
1174 maxint <<= (unsigned long)(i * 8);
1176 RANGE_ERROR(x, f, 1, maxint - 1);
1186 lp_longlong(char *p, PyObject *v, const formatdef *f)
1192 res = _PyLong_AsByteArray((PyLongObject*)v,
1195 1, /* little_endian */
1202 lp_ulonglong(char *p, PyObject *v, const formatdef *f)
1208 res = _PyLong_AsByteArray((PyLongObject*)v,
1211 1, /* little_endian */
1218 lp_float(char *p, PyObject *v, const formatdef *f)
1220 double x = PyFloat_AsDouble(v);
1221 if (x == -1 && PyErr_Occurred()) {
1222 PyErr_SetString(StructError,
1223 "required argument is not a float");
1226 return _PyFloat_Pack4(x, (unsigned char *)p, 1);
1230 lp_double(char *p, PyObject *v, const formatdef *f)
1232 double x = PyFloat_AsDouble(v);
1233 if (x == -1 && PyErr_Occurred()) {
1234 PyErr_SetString(StructError,
1235 "required argument is not a float");
1238 return _PyFloat_Pack8(x, (unsigned char *)p, 1);
1241 static formatdef lilendian_table[] = {
1243 #ifdef PY_STRUCT_OVERFLOW_MASKING
1244 /* Native packers do range checking without overflow masking. */
1245 {'b', 1, 0, nu_byte, lp_int},
1246 {'B', 1, 0, nu_ubyte, lp_uint},
1248 {'b', 1, 0, nu_byte, np_byte},
1249 {'B', 1, 0, nu_ubyte, np_ubyte},
1251 {'c', 1, 0, nu_char, np_char},
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},
1270 static const formatdef *
1271 whichtable(char **pfmt)
1273 const char *fmt = (*pfmt)++; /* May be backed out of later */
1276 return lilendian_table;
1278 case '!': /* Network byte order is big-endian */
1279 return bigendian_table;
1280 case '=': { /* Host byte order -- different from native in aligment! */
1282 char *p = (char *) &n;
1284 return lilendian_table;
1286 return bigendian_table;
1289 --*pfmt; /* Back out of pointer increment */
1292 return native_table;
1297 /* Get the table entry for a format code */
1299 static const formatdef *
1300 getentry(int c, const formatdef *f)
1302 for (; f->format != '\0'; f++) {
1303 if (f->format == c) {
1307 PyErr_SetString(StructError, "bad char in struct format");
1312 /* Align a size according to a format code */
1315 align(Py_ssize_t size, char c, const formatdef *e)
1317 if (e->format == c) {
1319 size = ((size + e->alignment - 1)
1328 /* calculate the size of a format string */
1331 prepare_s(PyStructObject *self)
1340 Py_ssize_t size, len, num, itemsize, x;
1342 fmt = PyString_AS_STRING(self->s_format);
1344 f = whichtable((char **)&fmt);
1349 while ((c = *s++) != '\0') {
1350 if (isspace(Py_CHARMASK(c)))
1352 if ('0' <= c && c <= '9') {
1354 while ('0' <= (c = *s++) && c <= '9') {
1355 x = num*10 + (c - '0');
1359 "overflow in item count");
1375 case 's': /* fall through */
1376 case 'p': len++; break;
1378 default: len += num; break;
1382 size = align(size, c, e);
1385 if (x/itemsize != num || size < 0) {
1386 PyErr_SetString(StructError,
1387 "total struct size too long");
1392 /* check for overflow */
1393 if ((len + 1) > (PY_SSIZE_T_MAX / sizeof(formatcode))) {
1398 self->s_size = size;
1400 codes = PyMem_MALLOC((len + 1) * sizeof(formatcode));
1401 if (codes == NULL) {
1405 self->s_codes = codes;
1409 while ((c = *s++) != '\0') {
1410 if (isspace(Py_CHARMASK(c)))
1412 if ('0' <= c && c <= '9') {
1414 while ('0' <= (c = *s++) && c <= '9')
1415 num = num*10 + (c - '0');
1424 size = align(size, c, e);
1425 if (c == 's' || c == 'p') {
1426 codes->offset = size;
1431 } else if (c == 'x') {
1434 while (--num >= 0) {
1435 codes->offset = size;
1436 codes->size = e->size;
1443 codes->fmtdef = NULL;
1444 codes->offset = size;
1451 s_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1455 assert(type != NULL && type->tp_alloc != NULL);
1457 self = type->tp_alloc(type, 0);
1459 PyStructObject *s = (PyStructObject*)self;
1461 s->s_format = Py_None;
1470 s_init(PyObject *self, PyObject *args, PyObject *kwds)
1472 PyStructObject *soself = (PyStructObject *)self;
1473 PyObject *o_format = NULL;
1475 static char *kwlist[] = {"format", 0};
1477 assert(PyStruct_Check(self));
1479 if (!PyArg_ParseTupleAndKeywords(args, kwds, "S:Struct", kwlist,
1483 Py_INCREF(o_format);
1484 Py_CLEAR(soself->s_format);
1485 soself->s_format = o_format;
1487 ret = prepare_s(soself);
1492 s_dealloc(PyStructObject *s)
1494 if (s->weakreflist != NULL)
1495 PyObject_ClearWeakRefs((PyObject *)s);
1496 if (s->s_codes != NULL) {
1497 PyMem_FREE(s->s_codes);
1499 Py_XDECREF(s->s_format);
1500 Py_TYPE(s)->tp_free((PyObject *)s);
1504 s_unpack_internal(PyStructObject *soself, char *startfrom) {
1507 PyObject *result = PyTuple_New(soself->s_len);
1511 for (code = soself->s_codes; code->fmtdef != NULL; code++) {
1513 const formatdef *e = code->fmtdef;
1514 const char *res = startfrom + code->offset;
1515 if (e->format == 's') {
1516 v = PyString_FromStringAndSize(res, code->size);
1517 } else if (e->format == 'p') {
1518 Py_ssize_t n = *(unsigned char*)res;
1519 if (n >= code->size)
1521 v = PyString_FromStringAndSize(res + 1, n);
1523 v = e->unpack(res, e);
1527 PyTuple_SET_ITEM(result, i++, v);
1537 PyDoc_STRVAR(s_unpack__doc__,
1538 "S.unpack(str) -> (v1, v2, ...)\n\
1540 Return tuple containing values unpacked according to this Struct's format.\n\
1541 Requires len(str) == self.size. See struct.__doc__ for more on format\n\
1545 s_unpack(PyObject *self, PyObject *inputstr)
1549 PyObject *args=NULL, *result;
1550 PyStructObject *soself = (PyStructObject *)self;
1551 assert(PyStruct_Check(self));
1552 assert(soself->s_codes != NULL);
1553 if (inputstr == NULL)
1555 if (PyString_Check(inputstr) &&
1556 PyString_GET_SIZE(inputstr) == soself->s_size) {
1557 return s_unpack_internal(soself, PyString_AS_STRING(inputstr));
1559 args = PyTuple_Pack(1, inputstr);
1562 if (!PyArg_ParseTuple(args, "s#:unpack", &start, &len))
1564 if (soself->s_size != len)
1566 result = s_unpack_internal(soself, start);
1572 PyErr_Format(StructError,
1573 "unpack requires a string argument of length %zd",
1578 PyDoc_STRVAR(s_unpack_from__doc__,
1579 "S.unpack_from(buffer[, offset]) -> (v1, v2, ...)\n\
1581 Return tuple containing values unpacked according to this Struct's format.\n\
1582 Unlike unpack, unpack_from can unpack values from any object supporting\n\
1583 the buffer API, not just str. Requires len(buffer[offset:]) >= self.size.\n\
1584 See struct.__doc__ for more on format strings.");
1587 s_unpack_from(PyObject *self, PyObject *args, PyObject *kwds)
1589 static char *kwlist[] = {"buffer", "offset", 0};
1590 #if (PY_VERSION_HEX < 0x02050000)
1591 static char *fmt = "z#|i:unpack_from";
1593 static char *fmt = "z#|n:unpack_from";
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);
1601 if (!PyArg_ParseTupleAndKeywords(args, kwds, fmt, kwlist,
1602 &buffer, &buffer_len, &offset))
1605 if (buffer == NULL) {
1606 PyErr_Format(StructError,
1607 "unpack_from requires a buffer argument");
1612 offset += buffer_len;
1614 if (offset < 0 || (buffer_len - offset) < soself->s_size) {
1615 PyErr_Format(StructError,
1616 "unpack_from requires a buffer of at least %zd bytes",
1620 return s_unpack_internal(soself, buffer + offset);
1625 * Guts of the pack function.
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.
1635 s_pack_internal(PyStructObject *soself, PyObject *args, int offset, char* buf)
1638 /* XXX(nnorwitz): why does i need to be a local? can we use
1639 the offset parameter or do we need the wider width? */
1642 memset(buf, '\0', soself->s_size);
1644 for (code = soself->s_codes; code->fmtdef != NULL; code++) {
1646 PyObject *v = PyTuple_GET_ITEM(args, i++);
1647 const formatdef *e = code->fmtdef;
1648 char *res = buf + code->offset;
1649 if (e->format == 's') {
1650 if (!PyString_Check(v)) {
1651 PyErr_SetString(StructError,
1652 "argument for 's' must be a string");
1655 n = PyString_GET_SIZE(v);
1659 memcpy(res, PyString_AS_STRING(v), n);
1660 } else if (e->format == 'p') {
1661 if (!PyString_Check(v)) {
1662 PyErr_SetString(StructError,
1663 "argument for 'p' must be a string");
1666 n = PyString_GET_SIZE(v);
1667 if (n > (code->size - 1))
1670 memcpy(res + 1, PyString_AS_STRING(v), n);
1673 *res = Py_SAFE_DOWNCAST(n, Py_ssize_t, unsigned char);
1675 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");
1689 PyDoc_STRVAR(s_pack__doc__,
1690 "S.pack(v1, v2, ...) -> string\n\
1692 Return a string containing values v1, v2, ... packed according to this\n\
1693 Struct's format. See struct.__doc__ for more on format strings.");
1696 s_pack(PyObject *self, PyObject *args)
1698 PyStructObject *soself;
1701 /* Validate arguments. */
1702 soself = (PyStructObject *)self;
1703 assert(PyStruct_Check(self));
1704 assert(soself->s_codes != NULL);
1705 if (PyTuple_GET_SIZE(args) != soself->s_len)
1707 PyErr_Format(StructError,
1708 "pack requires exactly %zd arguments", soself->s_len);
1712 /* Allocate a new string */
1713 result = PyString_FromStringAndSize((char *)NULL, soself->s_size);
1718 if ( s_pack_internal(soself, args, 0, PyString_AS_STRING(result)) != 0 ) {
1726 PyDoc_STRVAR(s_pack_into__doc__,
1727 "S.pack_into(buffer, offset, v1, v2, ...)\n\
1729 Pack the values v1, v2, ... according to this Struct's format, write \n\
1730 the packed bytes into the writable buffer buf starting at offset. Note\n\
1731 that the offset is not an optional argument. See struct.__doc__ for \n\
1732 more on format strings.");
1735 s_pack_into(PyObject *self, PyObject *args)
1737 PyStructObject *soself;
1739 Py_ssize_t buffer_len, offset;
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);
1745 if (PyTuple_GET_SIZE(args) != (soself->s_len + 2))
1747 PyErr_Format(StructError,
1748 "pack_into requires exactly %zd arguments",
1749 (soself->s_len + 2));
1753 /* Extract a writable memory buffer from the first argument */
1754 if ( PyObject_AsWriteBuffer(PyTuple_GET_ITEM(args, 0),
1755 (void**)&buffer, &buffer_len) == -1 ) {
1758 assert( buffer_len >= 0 );
1760 /* Extract the offset from the first argument */
1761 offset = PyInt_AsSsize_t(PyTuple_GET_ITEM(args, 1));
1762 if (offset == -1 && PyErr_Occurred())
1765 /* Support negative offsets. */
1767 offset += buffer_len;
1769 /* Check boundaries */
1770 if (offset < 0 || (buffer_len - offset) < soself->s_size) {
1771 PyErr_Format(StructError,
1772 "pack_into requires a buffer of at least %zd bytes",
1778 if ( s_pack_internal(soself, args, 2, buffer + offset) != 0 ) {
1786 s_get_format(PyStructObject *self, void *unused)
1788 Py_INCREF(self->s_format);
1789 return self->s_format;
1793 s_get_size(PyStructObject *self, void *unused)
1795 return PyInt_FromSsize_t(self->s_size);
1798 /* List of functions */
1800 static struct PyMethodDef s_methods[] = {
1801 {"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__},
1804 {"unpack_from", (PyCFunction)s_unpack_from, METH_VARARGS|METH_KEYWORDS,
1805 s_unpack_from__doc__},
1806 {NULL, NULL} /* sentinel */
1809 PyDoc_STRVAR(s__doc__, "Compiled struct object");
1811 #define OFF(x) offsetof(PyStructObject, x)
1813 static PyGetSetDef s_getsetlist[] = {
1814 {"format", (getter)s_get_format, (setter)NULL, "struct format string", NULL},
1815 {"size", (getter)s_get_size, (setter)NULL, "struct size in bytes", NULL},
1816 {NULL} /* sentinel */
1820 PyTypeObject PyStructType = {
1821 PyVarObject_HEAD_INIT(NULL, 0)
1823 sizeof(PyStructObject),
1825 (destructor)s_dealloc, /* tp_dealloc */
1831 0, /* tp_as_number */
1832 0, /* tp_as_sequence */
1833 0, /* tp_as_mapping */
1837 PyObject_GenericGetAttr, /* tp_getattro */
1838 PyObject_GenericSetAttr, /* tp_setattro */
1839 0, /* tp_as_buffer */
1840 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_WEAKREFS,/* tp_flags */
1841 s__doc__, /* tp_doc */
1842 0, /* tp_traverse */
1844 0, /* tp_richcompare */
1845 offsetof(PyStructObject, weakreflist), /* tp_weaklistoffset */
1847 0, /* tp_iternext */
1848 s_methods, /* tp_methods */
1849 NULL, /* tp_members */
1850 s_getsetlist, /* tp_getset */
1853 0, /* tp_descr_get */
1854 0, /* tp_descr_set */
1855 0, /* tp_dictoffset */
1856 s_init, /* tp_init */
1857 PyType_GenericAlloc,/* tp_alloc */
1859 PyObject_Del, /* tp_free */
1863 /* ---- Standalone functions ---- */
1865 #define MAXCACHE 100
1866 static PyObject *cache = NULL;
1869 cache_struct(PyObject *fmt)
1871 PyObject * s_object;
1873 if (cache == NULL) {
1874 cache = PyDict_New();
1879 s_object = PyDict_GetItem(cache, fmt);
1880 if (s_object != NULL) {
1881 Py_INCREF(s_object);
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)
1896 PyDoc_STRVAR(clearcache_doc,
1897 "Clear the internal cache.");
1900 clearcache(PyObject *self)
1906 PyDoc_STRVAR(calcsize_doc,
1907 "Return size of C struct described by format string fmt.");
1910 calcsize(PyObject *self, PyObject *fmt)
1913 PyObject *s_object = cache_struct(fmt);
1914 if (s_object == NULL)
1916 n = ((PyStructObject *)s_object)->s_size;
1917 Py_DECREF(s_object);
1918 return PyInt_FromSsize_t(n);
1921 PyDoc_STRVAR(pack_doc,
1922 "Return string containing values v1, v2, ... packed according to fmt.");
1925 pack(PyObject *self, PyObject *args)
1927 PyObject *s_object, *fmt, *newargs, *result;
1928 Py_ssize_t n = PyTuple_GET_SIZE(args);
1931 PyErr_SetString(PyExc_TypeError, "missing format argument");
1934 fmt = PyTuple_GET_ITEM(args, 0);
1935 newargs = PyTuple_GetSlice(args, 1, n);
1936 if (newargs == NULL)
1939 s_object = cache_struct(fmt);
1940 if (s_object == NULL) {
1944 result = s_pack(s_object, newargs);
1946 Py_DECREF(s_object);
1950 PyDoc_STRVAR(pack_into_doc,
1951 "Pack the values v1, v2, ... according to fmt.\n\
1952 Write the packed bytes into the writable buffer buf starting at offset.");
1955 pack_into(PyObject *self, PyObject *args)
1957 PyObject *s_object, *fmt, *newargs, *result;
1958 Py_ssize_t n = PyTuple_GET_SIZE(args);
1961 PyErr_SetString(PyExc_TypeError, "missing format argument");
1964 fmt = PyTuple_GET_ITEM(args, 0);
1965 newargs = PyTuple_GetSlice(args, 1, n);
1966 if (newargs == NULL)
1969 s_object = cache_struct(fmt);
1970 if (s_object == NULL) {
1974 result = s_pack_into(s_object, newargs);
1976 Py_DECREF(s_object);
1980 PyDoc_STRVAR(unpack_doc,
1981 "Unpack the string containing packed C structure data, according to fmt.\n\
1982 Requires len(string) == calcsize(fmt).");
1985 unpack(PyObject *self, PyObject *args)
1987 PyObject *s_object, *fmt, *inputstr, *result;
1989 if (!PyArg_UnpackTuple(args, "unpack", 2, 2, &fmt, &inputstr))
1992 s_object = cache_struct(fmt);
1993 if (s_object == NULL)
1995 result = s_unpack(s_object, inputstr);
1996 Py_DECREF(s_object);
2000 PyDoc_STRVAR(unpack_from_doc,
2001 "Unpack the buffer, containing packed C structure data, according to\n\
2002 fmt, starting at offset. Requires len(buffer[offset:]) >= calcsize(fmt).");
2005 unpack_from(PyObject *self, PyObject *args, PyObject *kwds)
2007 PyObject *s_object, *fmt, *newargs, *result;
2008 Py_ssize_t n = PyTuple_GET_SIZE(args);
2011 PyErr_SetString(PyExc_TypeError, "missing format argument");
2014 fmt = PyTuple_GET_ITEM(args, 0);
2015 newargs = PyTuple_GetSlice(args, 1, n);
2016 if (newargs == NULL)
2019 s_object = cache_struct(fmt);
2020 if (s_object == NULL) {
2024 result = s_unpack_from(s_object, newargs, kwds);
2026 Py_DECREF(s_object);
2030 static struct PyMethodDef module_functions[] = {
2031 {"_clearcache", (PyCFunction)clearcache, METH_NOARGS, clearcache_doc},
2032 {"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 */
2042 /* Module initialization */
2044 PyDoc_STRVAR(module_doc,
2045 "Functions to convert between Python values and C structs.\n\
2046 Python strings are used to hold the data representing the C struct\n\
2047 and also as format strings to describe the layout of data in the C struct.\n\
2049 The optional first format char indicates byte order, size and alignment:\n\
2050 @: native order, size & alignment (default)\n\
2051 =: native order, std. size & alignment\n\
2052 <: little-endian, std. size & alignment\n\
2053 >: big-endian, std. size & alignment\n\
2056 The remaining chars indicate types of args and must match exactly;\n\
2057 these can be preceded by a decimal repeat count:\n\
2058 x: pad byte (no data); c:char; b:signed byte; B:unsigned byte;\n\
2059 h:short; H:unsigned short; i:int; I:unsigned int;\n\
2060 l:long; L:unsigned long; f:float; d:double.\n\
2061 Special cases (preceding decimal count indicates length):\n\
2062 s:string (array of char); p: pascal string (with count byte).\n\
2063 Special case (only available in native format):\n\
2064 P:an integer type that is wide enough to hold a pointer.\n\
2065 Special case (not in native mode unless 'long long' in platform C):\n\
2066 q:long long; Q:unsigned long long\n\
2067 Whitespace between formats is ignored.\n\
2069 The variable struct.error is an exception raised on errors.\n");
2076 ver = PyString_FromString("0.2");
2080 m = Py_InitModule3("_struct", module_functions, module_doc);
2084 Py_TYPE(&PyStructType) = &PyType_Type;
2085 if (PyType_Ready(&PyStructType) < 0)
2088 #ifdef PY_STRUCT_OVERFLOW_MASKING
2089 if (pyint_zero == NULL) {
2090 pyint_zero = PyInt_FromLong(0);
2091 if (pyint_zero == NULL)
2094 if (pylong_ulong_mask == NULL) {
2095 #if (SIZEOF_LONG == 4)
2096 pylong_ulong_mask = PyLong_FromString("FFFFFFFF", NULL, 16);
2098 pylong_ulong_mask = PyLong_FromString("FFFFFFFFFFFFFFFF", NULL, 16);
2100 if (pylong_ulong_mask == NULL)
2105 /* This speed trick can't be used until overflow masking goes away, because
2106 native endian always raises exceptions instead of overflow masking. */
2108 /* Check endian and swap in faster functions */
2111 formatdef *native = native_table;
2112 formatdef *other, *ptr;
2113 if ((int)*(unsigned char*)&one)
2114 other = lilendian_table;
2116 other = bigendian_table;
2117 /* Scan through the native table, find a matching
2118 entry in the endian table and swap in the
2119 native implementations whenever possible
2120 (64-bit platforms may not have "standard" sizes) */
2121 while (native->format != '\0' && other->format != '\0') {
2123 while (ptr->format != '\0') {
2124 if (ptr->format == native->format) {
2125 /* Match faster when formats are
2126 listed in the same order */
2129 /* Only use the trick if the
2131 if (ptr->size != native->size)
2133 /* Skip float and double, could be
2134 "unknown" float format */
2135 if (ptr->format == 'd' || ptr->format == 'f')
2137 ptr->pack = native->pack;
2138 ptr->unpack = native->unpack;
2148 /* Add some symbolic constants to the module */
2149 if (StructError == NULL) {
2150 StructError = PyErr_NewException("struct.error", NULL, NULL);
2151 if (StructError == NULL)
2155 Py_INCREF(StructError);
2156 PyModule_AddObject(m, "error", StructError);
2158 Py_INCREF((PyObject*)&PyStructType);
2159 PyModule_AddObject(m, "Struct", (PyObject*)&PyStructType);
2161 PyModule_AddObject(m, "__version__", ver);
2163 PyModule_AddIntConstant(m, "_PY_STRUCT_RANGE_CHECKING", 1);
2164 #ifdef PY_STRUCT_OVERFLOW_MASKING
2165 PyModule_AddIntConstant(m, "_PY_STRUCT_OVERFLOW_MASKING", 1);
2167 #ifdef PY_STRUCT_FLOAT_COERCE
2168 PyModule_AddIntConstant(m, "_PY_STRUCT_FLOAT_COERCE", 1);