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_FLOAT_COERCE is defined, the struct module will allow float
21 arguments for integer formats with a warning for backwards
24 #define PY_STRUCT_FLOAT_COERCE 1
26 #ifdef PY_STRUCT_FLOAT_COERCE
27 #define FLOAT_COERCE "integer argument expected, got float"
31 /* The translation function for each format character is table driven */
32 typedef struct _formatdef
{
36 PyObject
* (*unpack
)(const char *,
37 const struct _formatdef
*);
38 int (*pack
)(char *, PyObject
*,
39 const struct _formatdef
*);
42 typedef struct _formatcode
{
43 const struct _formatdef
*fmtdef
;
48 /* Struct object interface */
56 PyObject
*weakreflist
; /* List of weak references */
60 #define PyStruct_Check(op) PyObject_TypeCheck(op, &PyStructType)
61 #define PyStruct_CheckExact(op) (Py_TYPE(op) == &PyStructType)
66 static PyObject
*StructError
;
69 /* Define various structs to figure out the alignments of types */
72 typedef struct { char c
; short x
; } st_short
;
73 typedef struct { char c
; int x
; } st_int
;
74 typedef struct { char c
; long x
; } st_long
;
75 typedef struct { char c
; float x
; } st_float
;
76 typedef struct { char c
; double x
; } st_double
;
77 typedef struct { char c
; void *x
; } st_void_p
;
79 #define SHORT_ALIGN (sizeof(st_short) - sizeof(short))
80 #define INT_ALIGN (sizeof(st_int) - sizeof(int))
81 #define LONG_ALIGN (sizeof(st_long) - sizeof(long))
82 #define FLOAT_ALIGN (sizeof(st_float) - sizeof(float))
83 #define DOUBLE_ALIGN (sizeof(st_double) - sizeof(double))
84 #define VOID_P_ALIGN (sizeof(st_void_p) - sizeof(void *))
86 /* We can't support q and Q in native mode unless the compiler does;
87 in std mode, they're 8 bytes on all platforms. */
89 typedef struct { char c
; PY_LONG_LONG x
; } s_long_long
;
90 #define LONG_LONG_ALIGN (sizeof(s_long_long) - sizeof(PY_LONG_LONG))
94 #define BOOL_TYPE _Bool
95 typedef struct { char c
; _Bool x
; } s_bool
;
96 #define BOOL_ALIGN (sizeof(s_bool) - sizeof(BOOL_TYPE))
98 #define BOOL_TYPE char
102 #define STRINGIFY(x) #x
105 #pragma options align=reset
108 static char *integer_codes
= "bBhHiIlLqQ";
110 /* Helper to get a PyLongObject by hook or by crook. Caller should decref. */
113 get_pylong(PyObject
*v
)
117 return PyLong_FromLong(PyInt_AS_LONG(v
));
118 if (PyLong_Check(v
)) {
122 #ifdef PY_STRUCT_FLOAT_COERCE
123 if (PyFloat_Check(v
)) {
124 if (PyErr_WarnEx(PyExc_DeprecationWarning
, FLOAT_COERCE
, 2)<0)
126 return PyNumber_Long(v
);
129 PyErr_SetString(StructError
,
130 "cannot convert argument to long");
134 /* Helper to convert a Python object to a C long. Sets an exception
135 (struct.error for an inconvertible type, OverflowError for
136 out-of-range values) and returns -1 on error. */
139 get_long(PyObject
*v
, long *p
)
146 assert(PyLong_Check(v
));
147 x
= PyLong_AsLong(v
);
149 if (x
== (long)-1 && PyErr_Occurred())
155 /* Same, but handling unsigned long */
158 get_ulong(PyObject
*v
, unsigned long *p
)
165 assert(PyLong_Check(v
));
166 x
= PyLong_AsUnsignedLong(v
);
168 if (x
== (unsigned long)-1 && PyErr_Occurred())
174 #ifdef HAVE_LONG_LONG
176 /* Same, but handling native long long. */
179 get_longlong(PyObject
*v
, PY_LONG_LONG
*p
)
186 assert(PyLong_Check(v
));
187 x
= PyLong_AsLongLong(v
);
189 if (x
== (PY_LONG_LONG
)-1 && PyErr_Occurred())
195 /* Same, but handling native unsigned long long. */
198 get_ulonglong(PyObject
*v
, unsigned PY_LONG_LONG
*p
)
200 unsigned PY_LONG_LONG x
;
205 assert(PyLong_Check(v
));
206 x
= PyLong_AsUnsignedLongLong(v
);
208 if (x
== (unsigned PY_LONG_LONG
)-1 && PyErr_Occurred())
216 /* Floating point helpers */
219 unpack_float(const char *p
, /* start of 4-byte string */
220 int le
) /* true for little-endian, false for big-endian */
224 x
= _PyFloat_Unpack4((unsigned char *)p
, le
);
225 if (x
== -1.0 && PyErr_Occurred())
227 return PyFloat_FromDouble(x
);
231 unpack_double(const char *p
, /* start of 8-byte string */
232 int le
) /* true for little-endian, false for big-endian */
236 x
= _PyFloat_Unpack8((unsigned char *)p
, le
);
237 if (x
== -1.0 && PyErr_Occurred())
239 return PyFloat_FromDouble(x
);
242 /* Helper to format the range error exceptions */
244 _range_error(const formatdef
*f
, int is_unsigned
)
246 /* ulargest is the largest unsigned value with f->size bytes.
247 * Note that the simpler:
248 * ((size_t)1 << (f->size * 8)) - 1
249 * doesn't work when f->size == sizeof(size_t) because C doesn't
250 * define what happens when a left shift count is >= the number of
251 * bits in the integer being shifted; e.g., on some boxes it doesn't
252 * shift at all when they're equal.
254 const size_t ulargest
= (size_t)-1 >> ((SIZEOF_SIZE_T
- f
->size
)*8);
255 assert(f
->size
>= 1 && f
->size
<= SIZEOF_SIZE_T
);
257 PyErr_Format(StructError
,
258 "'%c' format requires 0 <= number <= %zu",
262 const Py_ssize_t largest
= (Py_ssize_t
)(ulargest
>> 1);
263 PyErr_Format(StructError
,
264 "'%c' format requires %zd <= number <= %zd",
274 /* A large number of small routines follow, with names of the form
278 [bln] distiguishes among big-endian, little-endian and native.
279 [pu] distiguishes between pack (to struct) and unpack (from struct).
280 TYPE is one of char, byte, ubyte, etc.
283 /* Native mode routines. ****************************************************/
285 In all n[up]_<type> routines handling types larger than 1 byte, there is
286 *no* guarantee that the p pointer is properly aligned for each type,
287 therefore memcpy is called. An intermediate variable is used to
288 compensate for big-endian architectures.
289 Normally both the intermediate variable and the memcpy call will be
290 skipped by C optimisation in little-endian architectures (gcc >= 2.91
294 nu_char(const char *p
, const formatdef
*f
)
296 return PyString_FromStringAndSize(p
, 1);
300 nu_byte(const char *p
, const formatdef
*f
)
302 return PyInt_FromLong((long) *(signed char *)p
);
306 nu_ubyte(const char *p
, const formatdef
*f
)
308 return PyInt_FromLong((long) *(unsigned char *)p
);
312 nu_short(const char *p
, const formatdef
*f
)
315 memcpy((char *)&x
, p
, sizeof x
);
316 return PyInt_FromLong((long)x
);
320 nu_ushort(const char *p
, const formatdef
*f
)
323 memcpy((char *)&x
, p
, sizeof x
);
324 return PyInt_FromLong((long)x
);
328 nu_int(const char *p
, const formatdef
*f
)
331 memcpy((char *)&x
, p
, sizeof x
);
332 return PyInt_FromLong((long)x
);
336 nu_uint(const char *p
, const formatdef
*f
)
339 memcpy((char *)&x
, p
, sizeof x
);
340 #if (SIZEOF_LONG > SIZEOF_INT)
341 return PyInt_FromLong((long)x
);
343 if (x
<= ((unsigned int)LONG_MAX
))
344 return PyInt_FromLong((long)x
);
345 return PyLong_FromUnsignedLong((unsigned long)x
);
350 nu_long(const char *p
, const formatdef
*f
)
353 memcpy((char *)&x
, p
, sizeof x
);
354 return PyInt_FromLong(x
);
358 nu_ulong(const char *p
, const formatdef
*f
)
361 memcpy((char *)&x
, p
, sizeof x
);
363 return PyInt_FromLong((long)x
);
364 return PyLong_FromUnsignedLong(x
);
367 /* Native mode doesn't support q or Q unless the platform C supports
368 long long (or, on Windows, __int64). */
370 #ifdef HAVE_LONG_LONG
373 nu_longlong(const char *p
, const formatdef
*f
)
376 memcpy((char *)&x
, p
, sizeof x
);
377 if (x
>= LONG_MIN
&& x
<= LONG_MAX
)
378 return PyInt_FromLong(Py_SAFE_DOWNCAST(x
, PY_LONG_LONG
, long));
379 return PyLong_FromLongLong(x
);
383 nu_ulonglong(const char *p
, const formatdef
*f
)
385 unsigned PY_LONG_LONG x
;
386 memcpy((char *)&x
, p
, sizeof x
);
388 return PyInt_FromLong(Py_SAFE_DOWNCAST(x
, unsigned PY_LONG_LONG
, long));
389 return PyLong_FromUnsignedLongLong(x
);
395 nu_bool(const char *p
, const formatdef
*f
)
398 memcpy((char *)&x
, p
, sizeof x
);
399 return PyBool_FromLong(x
!= 0);
404 nu_float(const char *p
, const formatdef
*f
)
407 memcpy((char *)&x
, p
, sizeof x
);
408 return PyFloat_FromDouble((double)x
);
412 nu_double(const char *p
, const formatdef
*f
)
415 memcpy((char *)&x
, p
, sizeof x
);
416 return PyFloat_FromDouble(x
);
420 nu_void_p(const char *p
, const formatdef
*f
)
423 memcpy((char *)&x
, p
, sizeof x
);
424 return PyLong_FromVoidPtr(x
);
428 np_byte(char *p
, PyObject
*v
, const formatdef
*f
)
431 if (get_long(v
, &x
) < 0)
433 if (x
< -128 || x
> 127){
434 PyErr_SetString(StructError
,
435 "byte format requires -128 <= number <= 127");
443 np_ubyte(char *p
, PyObject
*v
, const formatdef
*f
)
446 if (get_long(v
, &x
) < 0)
448 if (x
< 0 || x
> 255){
449 PyErr_SetString(StructError
,
450 "ubyte format requires 0 <= number <= 255");
458 np_char(char *p
, PyObject
*v
, const formatdef
*f
)
460 if (!PyString_Check(v
) || PyString_Size(v
) != 1) {
461 PyErr_SetString(StructError
,
462 "char format require string of length 1");
465 *p
= *PyString_AsString(v
);
470 np_short(char *p
, PyObject
*v
, const formatdef
*f
)
474 if (get_long(v
, &x
) < 0)
476 if (x
< SHRT_MIN
|| x
> SHRT_MAX
){
477 PyErr_SetString(StructError
,
478 "short format requires " STRINGIFY(SHRT_MIN
)
479 " <= number <= " STRINGIFY(SHRT_MAX
));
483 memcpy(p
, (char *)&y
, sizeof y
);
488 np_ushort(char *p
, PyObject
*v
, const formatdef
*f
)
492 if (get_long(v
, &x
) < 0)
494 if (x
< 0 || x
> USHRT_MAX
){
495 PyErr_SetString(StructError
,
496 "ushort format requires 0 <= number <= " STRINGIFY(USHRT_MAX
));
499 y
= (unsigned short)x
;
500 memcpy(p
, (char *)&y
, sizeof y
);
505 np_int(char *p
, PyObject
*v
, const formatdef
*f
)
509 if (get_long(v
, &x
) < 0)
511 #if (SIZEOF_LONG > SIZEOF_INT)
512 if ((x
< ((long)INT_MIN
)) || (x
> ((long)INT_MAX
)))
513 return _range_error(f
, 0);
516 memcpy(p
, (char *)&y
, sizeof y
);
521 np_uint(char *p
, PyObject
*v
, const formatdef
*f
)
525 if (get_ulong(v
, &x
) < 0)
528 #if (SIZEOF_LONG > SIZEOF_INT)
529 if (x
> ((unsigned long)UINT_MAX
))
530 return _range_error(f
, 1);
532 memcpy(p
, (char *)&y
, sizeof y
);
537 np_long(char *p
, PyObject
*v
, const formatdef
*f
)
540 if (get_long(v
, &x
) < 0)
542 memcpy(p
, (char *)&x
, sizeof x
);
547 np_ulong(char *p
, PyObject
*v
, const formatdef
*f
)
550 if (get_ulong(v
, &x
) < 0)
552 memcpy(p
, (char *)&x
, sizeof x
);
556 #ifdef HAVE_LONG_LONG
559 np_longlong(char *p
, PyObject
*v
, const formatdef
*f
)
562 if (get_longlong(v
, &x
) < 0)
564 memcpy(p
, (char *)&x
, sizeof x
);
569 np_ulonglong(char *p
, PyObject
*v
, const formatdef
*f
)
571 unsigned PY_LONG_LONG x
;
572 if (get_ulonglong(v
, &x
) < 0)
574 memcpy(p
, (char *)&x
, sizeof x
);
581 np_bool(char *p
, PyObject
*v
, const formatdef
*f
)
584 y
= PyObject_IsTrue(v
);
585 memcpy(p
, (char *)&y
, sizeof y
);
590 np_float(char *p
, PyObject
*v
, const formatdef
*f
)
592 float x
= (float)PyFloat_AsDouble(v
);
593 if (x
== -1 && PyErr_Occurred()) {
594 PyErr_SetString(StructError
,
595 "required argument is not a float");
598 memcpy(p
, (char *)&x
, sizeof x
);
603 np_double(char *p
, PyObject
*v
, const formatdef
*f
)
605 double x
= PyFloat_AsDouble(v
);
606 if (x
== -1 && PyErr_Occurred()) {
607 PyErr_SetString(StructError
,
608 "required argument is not a float");
611 memcpy(p
, (char *)&x
, sizeof(double));
616 np_void_p(char *p
, PyObject
*v
, const formatdef
*f
)
623 assert(PyLong_Check(v
));
624 x
= PyLong_AsVoidPtr(v
);
626 if (x
== NULL
&& PyErr_Occurred())
628 memcpy(p
, (char *)&x
, sizeof x
);
632 static formatdef native_table
[] = {
633 {'x', sizeof(char), 0, NULL
},
634 {'b', sizeof(char), 0, nu_byte
, np_byte
},
635 {'B', sizeof(char), 0, nu_ubyte
, np_ubyte
},
636 {'c', sizeof(char), 0, nu_char
, np_char
},
637 {'s', sizeof(char), 0, NULL
},
638 {'p', sizeof(char), 0, NULL
},
639 {'h', sizeof(short), SHORT_ALIGN
, nu_short
, np_short
},
640 {'H', sizeof(short), SHORT_ALIGN
, nu_ushort
, np_ushort
},
641 {'i', sizeof(int), INT_ALIGN
, nu_int
, np_int
},
642 {'I', sizeof(int), INT_ALIGN
, nu_uint
, np_uint
},
643 {'l', sizeof(long), LONG_ALIGN
, nu_long
, np_long
},
644 {'L', sizeof(long), LONG_ALIGN
, nu_ulong
, np_ulong
},
645 #ifdef HAVE_LONG_LONG
646 {'q', sizeof(PY_LONG_LONG
), LONG_LONG_ALIGN
, nu_longlong
, np_longlong
},
647 {'Q', sizeof(PY_LONG_LONG
), LONG_LONG_ALIGN
, nu_ulonglong
,np_ulonglong
},
649 {'?', sizeof(BOOL_TYPE
), BOOL_ALIGN
, nu_bool
, np_bool
},
650 {'f', sizeof(float), FLOAT_ALIGN
, nu_float
, np_float
},
651 {'d', sizeof(double), DOUBLE_ALIGN
, nu_double
, np_double
},
652 {'P', sizeof(void *), VOID_P_ALIGN
, nu_void_p
, np_void_p
},
656 /* Big-endian routines. *****************************************************/
659 bu_int(const char *p
, const formatdef
*f
)
662 Py_ssize_t i
= f
->size
;
663 const unsigned char *bytes
= (const unsigned char *)p
;
665 x
= (x
<<8) | *bytes
++;
667 /* Extend the sign bit. */
668 if (SIZEOF_LONG
> f
->size
)
669 x
|= -(x
& (1L << ((8 * f
->size
) - 1)));
670 return PyInt_FromLong(x
);
674 bu_uint(const char *p
, const formatdef
*f
)
677 Py_ssize_t i
= f
->size
;
678 const unsigned char *bytes
= (const unsigned char *)p
;
680 x
= (x
<<8) | *bytes
++;
683 return PyInt_FromLong((long)x
);
684 return PyLong_FromUnsignedLong(x
);
688 bu_longlong(const char *p
, const formatdef
*f
)
690 #ifdef HAVE_LONG_LONG
692 Py_ssize_t i
= f
->size
;
693 const unsigned char *bytes
= (const unsigned char *)p
;
695 x
= (x
<<8) | *bytes
++;
697 /* Extend the sign bit. */
698 if (SIZEOF_LONG_LONG
> f
->size
)
699 x
|= -(x
& ((PY_LONG_LONG
)1 << ((8 * f
->size
) - 1)));
700 if (x
>= LONG_MIN
&& x
<= LONG_MAX
)
701 return PyInt_FromLong(Py_SAFE_DOWNCAST(x
, PY_LONG_LONG
, long));
702 return PyLong_FromLongLong(x
);
704 return _PyLong_FromByteArray((const unsigned char *)p
,
706 0, /* little-endian */
712 bu_ulonglong(const char *p
, const formatdef
*f
)
714 #ifdef HAVE_LONG_LONG
715 unsigned PY_LONG_LONG x
= 0;
716 Py_ssize_t i
= f
->size
;
717 const unsigned char *bytes
= (const unsigned char *)p
;
719 x
= (x
<<8) | *bytes
++;
722 return PyInt_FromLong(Py_SAFE_DOWNCAST(x
, unsigned PY_LONG_LONG
, long));
723 return PyLong_FromUnsignedLongLong(x
);
725 return _PyLong_FromByteArray((const unsigned char *)p
,
727 0, /* little-endian */
733 bu_float(const char *p
, const formatdef
*f
)
735 return unpack_float(p
, 0);
739 bu_double(const char *p
, const formatdef
*f
)
741 return unpack_double(p
, 0);
745 bu_bool(const char *p
, const formatdef
*f
)
748 memcpy((char *)&x
, p
, sizeof x
);
749 return PyBool_FromLong(x
!= 0);
753 bp_int(char *p
, PyObject
*v
, const formatdef
*f
)
757 if (get_long(v
, &x
) < 0)
760 if (i
!= SIZEOF_LONG
) {
761 if ((i
== 2) && (x
< -32768 || x
> 32767))
762 return _range_error(f
, 0);
763 #if (SIZEOF_LONG != 4)
764 else if ((i
== 4) && (x
< -2147483648L || x
> 2147483647L))
765 return _range_error(f
, 0);
776 bp_uint(char *p
, PyObject
*v
, const formatdef
*f
)
780 if (get_ulong(v
, &x
) < 0)
783 if (i
!= SIZEOF_LONG
) {
784 unsigned long maxint
= 1;
785 maxint
<<= (unsigned long)(i
* 8);
787 return _range_error(f
, 1);
797 bp_longlong(char *p
, PyObject
*v
, const formatdef
*f
)
803 res
= _PyLong_AsByteArray((PyLongObject
*)v
,
806 0, /* little_endian */
813 bp_ulonglong(char *p
, PyObject
*v
, const formatdef
*f
)
819 res
= _PyLong_AsByteArray((PyLongObject
*)v
,
822 0, /* little_endian */
829 bp_float(char *p
, PyObject
*v
, const formatdef
*f
)
831 double x
= PyFloat_AsDouble(v
);
832 if (x
== -1 && PyErr_Occurred()) {
833 PyErr_SetString(StructError
,
834 "required argument is not a float");
837 return _PyFloat_Pack4(x
, (unsigned char *)p
, 0);
841 bp_double(char *p
, PyObject
*v
, const formatdef
*f
)
843 double x
= PyFloat_AsDouble(v
);
844 if (x
== -1 && PyErr_Occurred()) {
845 PyErr_SetString(StructError
,
846 "required argument is not a float");
849 return _PyFloat_Pack8(x
, (unsigned char *)p
, 0);
853 bp_bool(char *p
, PyObject
*v
, const formatdef
*f
)
856 y
= PyObject_IsTrue(v
);
857 memcpy(p
, (char *)&y
, sizeof y
);
861 static formatdef bigendian_table
[] = {
863 {'b', 1, 0, nu_byte
, np_byte
},
864 {'B', 1, 0, nu_ubyte
, np_ubyte
},
865 {'c', 1, 0, nu_char
, np_char
},
868 {'h', 2, 0, bu_int
, bp_int
},
869 {'H', 2, 0, bu_uint
, bp_uint
},
870 {'i', 4, 0, bu_int
, bp_int
},
871 {'I', 4, 0, bu_uint
, bp_uint
},
872 {'l', 4, 0, bu_int
, bp_int
},
873 {'L', 4, 0, bu_uint
, bp_uint
},
874 {'q', 8, 0, bu_longlong
, bp_longlong
},
875 {'Q', 8, 0, bu_ulonglong
, bp_ulonglong
},
876 {'?', 1, 0, bu_bool
, bp_bool
},
877 {'f', 4, 0, bu_float
, bp_float
},
878 {'d', 8, 0, bu_double
, bp_double
},
882 /* Little-endian routines. *****************************************************/
885 lu_int(const char *p
, const formatdef
*f
)
888 Py_ssize_t i
= f
->size
;
889 const unsigned char *bytes
= (const unsigned char *)p
;
891 x
= (x
<<8) | bytes
[--i
];
893 /* Extend the sign bit. */
894 if (SIZEOF_LONG
> f
->size
)
895 x
|= -(x
& (1L << ((8 * f
->size
) - 1)));
896 return PyInt_FromLong(x
);
900 lu_uint(const char *p
, const formatdef
*f
)
903 Py_ssize_t i
= f
->size
;
904 const unsigned char *bytes
= (const unsigned char *)p
;
906 x
= (x
<<8) | bytes
[--i
];
909 return PyInt_FromLong((long)x
);
910 return PyLong_FromUnsignedLong((long)x
);
914 lu_longlong(const char *p
, const formatdef
*f
)
916 #ifdef HAVE_LONG_LONG
918 Py_ssize_t i
= f
->size
;
919 const unsigned char *bytes
= (const unsigned char *)p
;
921 x
= (x
<<8) | bytes
[--i
];
923 /* Extend the sign bit. */
924 if (SIZEOF_LONG_LONG
> f
->size
)
925 x
|= -(x
& ((PY_LONG_LONG
)1 << ((8 * f
->size
) - 1)));
926 if (x
>= LONG_MIN
&& x
<= LONG_MAX
)
927 return PyInt_FromLong(Py_SAFE_DOWNCAST(x
, PY_LONG_LONG
, long));
928 return PyLong_FromLongLong(x
);
930 return _PyLong_FromByteArray((const unsigned char *)p
,
932 1, /* little-endian */
938 lu_ulonglong(const char *p
, const formatdef
*f
)
940 #ifdef HAVE_LONG_LONG
941 unsigned PY_LONG_LONG x
= 0;
942 Py_ssize_t i
= f
->size
;
943 const unsigned char *bytes
= (const unsigned char *)p
;
945 x
= (x
<<8) | bytes
[--i
];
948 return PyInt_FromLong(Py_SAFE_DOWNCAST(x
, unsigned PY_LONG_LONG
, long));
949 return PyLong_FromUnsignedLongLong(x
);
951 return _PyLong_FromByteArray((const unsigned char *)p
,
953 1, /* little-endian */
959 lu_float(const char *p
, const formatdef
*f
)
961 return unpack_float(p
, 1);
965 lu_double(const char *p
, const formatdef
*f
)
967 return unpack_double(p
, 1);
971 lp_int(char *p
, PyObject
*v
, const formatdef
*f
)
975 if (get_long(v
, &x
) < 0)
978 if (i
!= SIZEOF_LONG
) {
979 if ((i
== 2) && (x
< -32768 || x
> 32767))
980 return _range_error(f
, 0);
981 #if (SIZEOF_LONG != 4)
982 else if ((i
== 4) && (x
< -2147483648L || x
> 2147483647L))
983 return _range_error(f
, 0);
994 lp_uint(char *p
, PyObject
*v
, const formatdef
*f
)
998 if (get_ulong(v
, &x
) < 0)
1001 if (i
!= SIZEOF_LONG
) {
1002 unsigned long maxint
= 1;
1003 maxint
<<= (unsigned long)(i
* 8);
1005 return _range_error(f
, 1);
1015 lp_longlong(char *p
, PyObject
*v
, const formatdef
*f
)
1021 res
= _PyLong_AsByteArray((PyLongObject
*)v
,
1024 1, /* little_endian */
1031 lp_ulonglong(char *p
, PyObject
*v
, const formatdef
*f
)
1037 res
= _PyLong_AsByteArray((PyLongObject
*)v
,
1040 1, /* little_endian */
1047 lp_float(char *p
, PyObject
*v
, const formatdef
*f
)
1049 double x
= PyFloat_AsDouble(v
);
1050 if (x
== -1 && PyErr_Occurred()) {
1051 PyErr_SetString(StructError
,
1052 "required argument is not a float");
1055 return _PyFloat_Pack4(x
, (unsigned char *)p
, 1);
1059 lp_double(char *p
, PyObject
*v
, const formatdef
*f
)
1061 double x
= PyFloat_AsDouble(v
);
1062 if (x
== -1 && PyErr_Occurred()) {
1063 PyErr_SetString(StructError
,
1064 "required argument is not a float");
1067 return _PyFloat_Pack8(x
, (unsigned char *)p
, 1);
1070 static formatdef lilendian_table
[] = {
1072 {'b', 1, 0, nu_byte
, np_byte
},
1073 {'B', 1, 0, nu_ubyte
, np_ubyte
},
1074 {'c', 1, 0, nu_char
, np_char
},
1077 {'h', 2, 0, lu_int
, lp_int
},
1078 {'H', 2, 0, lu_uint
, lp_uint
},
1079 {'i', 4, 0, lu_int
, lp_int
},
1080 {'I', 4, 0, lu_uint
, lp_uint
},
1081 {'l', 4, 0, lu_int
, lp_int
},
1082 {'L', 4, 0, lu_uint
, lp_uint
},
1083 {'q', 8, 0, lu_longlong
, lp_longlong
},
1084 {'Q', 8, 0, lu_ulonglong
, lp_ulonglong
},
1085 {'?', 1, 0, bu_bool
, bp_bool
}, /* Std rep not endian dep,
1086 but potentially different from native rep -- reuse bx_bool funcs. */
1087 {'f', 4, 0, lu_float
, lp_float
},
1088 {'d', 8, 0, lu_double
, lp_double
},
1093 static const formatdef
*
1094 whichtable(char **pfmt
)
1096 const char *fmt
= (*pfmt
)++; /* May be backed out of later */
1099 return lilendian_table
;
1101 case '!': /* Network byte order is big-endian */
1102 return bigendian_table
;
1103 case '=': { /* Host byte order -- different from native in aligment! */
1105 char *p
= (char *) &n
;
1107 return lilendian_table
;
1109 return bigendian_table
;
1112 --*pfmt
; /* Back out of pointer increment */
1115 return native_table
;
1120 /* Get the table entry for a format code */
1122 static const formatdef
*
1123 getentry(int c
, const formatdef
*f
)
1125 for (; f
->format
!= '\0'; f
++) {
1126 if (f
->format
== c
) {
1130 PyErr_SetString(StructError
, "bad char in struct format");
1135 /* Align a size according to a format code */
1138 align(Py_ssize_t size
, char c
, const formatdef
*e
)
1140 if (e
->format
== c
) {
1142 size
= ((size
+ e
->alignment
- 1)
1151 /* calculate the size of a format string */
1154 prepare_s(PyStructObject
*self
)
1163 Py_ssize_t size
, len
, num
, itemsize
, x
;
1165 fmt
= PyString_AS_STRING(self
->s_format
);
1167 f
= whichtable((char **)&fmt
);
1172 while ((c
= *s
++) != '\0') {
1173 if (isspace(Py_CHARMASK(c
)))
1175 if ('0' <= c
&& c
<= '9') {
1177 while ('0' <= (c
= *s
++) && c
<= '9') {
1178 x
= num
*10 + (c
- '0');
1182 "overflow in item count");
1198 case 's': /* fall through */
1199 case 'p': len
++; break;
1201 default: len
+= num
; break;
1205 size
= align(size
, c
, e
);
1208 if (x
/itemsize
!= num
|| size
< 0) {
1209 PyErr_SetString(StructError
,
1210 "total struct size too long");
1215 /* check for overflow */
1216 if ((len
+ 1) > (PY_SSIZE_T_MAX
/ sizeof(formatcode
))) {
1221 self
->s_size
= size
;
1223 codes
= PyMem_MALLOC((len
+ 1) * sizeof(formatcode
));
1224 if (codes
== NULL
) {
1228 self
->s_codes
= codes
;
1232 while ((c
= *s
++) != '\0') {
1233 if (isspace(Py_CHARMASK(c
)))
1235 if ('0' <= c
&& c
<= '9') {
1237 while ('0' <= (c
= *s
++) && c
<= '9')
1238 num
= num
*10 + (c
- '0');
1247 size
= align(size
, c
, e
);
1248 if (c
== 's' || c
== 'p') {
1249 codes
->offset
= size
;
1254 } else if (c
== 'x') {
1257 while (--num
>= 0) {
1258 codes
->offset
= size
;
1259 codes
->size
= e
->size
;
1266 codes
->fmtdef
= NULL
;
1267 codes
->offset
= size
;
1274 s_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
1278 assert(type
!= NULL
&& type
->tp_alloc
!= NULL
);
1280 self
= type
->tp_alloc(type
, 0);
1282 PyStructObject
*s
= (PyStructObject
*)self
;
1284 s
->s_format
= Py_None
;
1293 s_init(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
1295 PyStructObject
*soself
= (PyStructObject
*)self
;
1296 PyObject
*o_format
= NULL
;
1298 static char *kwlist
[] = {"format", 0};
1300 assert(PyStruct_Check(self
));
1302 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "S:Struct", kwlist
,
1306 Py_INCREF(o_format
);
1307 Py_CLEAR(soself
->s_format
);
1308 soself
->s_format
= o_format
;
1310 ret
= prepare_s(soself
);
1315 s_dealloc(PyStructObject
*s
)
1317 if (s
->weakreflist
!= NULL
)
1318 PyObject_ClearWeakRefs((PyObject
*)s
);
1319 if (s
->s_codes
!= NULL
) {
1320 PyMem_FREE(s
->s_codes
);
1322 Py_XDECREF(s
->s_format
);
1323 Py_TYPE(s
)->tp_free((PyObject
*)s
);
1327 s_unpack_internal(PyStructObject
*soself
, char *startfrom
) {
1330 PyObject
*result
= PyTuple_New(soself
->s_len
);
1334 for (code
= soself
->s_codes
; code
->fmtdef
!= NULL
; code
++) {
1336 const formatdef
*e
= code
->fmtdef
;
1337 const char *res
= startfrom
+ code
->offset
;
1338 if (e
->format
== 's') {
1339 v
= PyString_FromStringAndSize(res
, code
->size
);
1340 } else if (e
->format
== 'p') {
1341 Py_ssize_t n
= *(unsigned char*)res
;
1342 if (n
>= code
->size
)
1344 v
= PyString_FromStringAndSize(res
+ 1, n
);
1346 v
= e
->unpack(res
, e
);
1350 PyTuple_SET_ITEM(result
, i
++, v
);
1360 PyDoc_STRVAR(s_unpack__doc__
,
1361 "S.unpack(str) -> (v1, v2, ...)\n\
1363 Return tuple containing values unpacked according to this Struct's format.\n\
1364 Requires len(str) == self.size. See struct.__doc__ for more on format\n\
1368 s_unpack(PyObject
*self
, PyObject
*inputstr
)
1372 PyObject
*args
=NULL
, *result
;
1373 PyStructObject
*soself
= (PyStructObject
*)self
;
1374 assert(PyStruct_Check(self
));
1375 assert(soself
->s_codes
!= NULL
);
1376 if (inputstr
== NULL
)
1378 if (PyString_Check(inputstr
) &&
1379 PyString_GET_SIZE(inputstr
) == soself
->s_size
) {
1380 return s_unpack_internal(soself
, PyString_AS_STRING(inputstr
));
1382 args
= PyTuple_Pack(1, inputstr
);
1385 if (!PyArg_ParseTuple(args
, "s#:unpack", &start
, &len
))
1387 if (soself
->s_size
!= len
)
1389 result
= s_unpack_internal(soself
, start
);
1395 PyErr_Format(StructError
,
1396 "unpack requires a string argument of length %zd",
1401 PyDoc_STRVAR(s_unpack_from__doc__
,
1402 "S.unpack_from(buffer[, offset]) -> (v1, v2, ...)\n\
1404 Return tuple containing values unpacked according to this Struct's format.\n\
1405 Unlike unpack, unpack_from can unpack values from any object supporting\n\
1406 the buffer API, not just str. Requires len(buffer[offset:]) >= self.size.\n\
1407 See struct.__doc__ for more on format strings.");
1410 s_unpack_from(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
1412 static char *kwlist
[] = {"buffer", "offset", 0};
1413 #if (PY_VERSION_HEX < 0x02050000)
1414 static char *fmt
= "z#|i:unpack_from";
1416 static char *fmt
= "z#|n:unpack_from";
1418 Py_ssize_t buffer_len
= 0, offset
= 0;
1419 char *buffer
= NULL
;
1420 PyStructObject
*soself
= (PyStructObject
*)self
;
1421 assert(PyStruct_Check(self
));
1422 assert(soself
->s_codes
!= NULL
);
1424 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, fmt
, kwlist
,
1425 &buffer
, &buffer_len
, &offset
))
1428 if (buffer
== NULL
) {
1429 PyErr_Format(StructError
,
1430 "unpack_from requires a buffer argument");
1435 offset
+= buffer_len
;
1437 if (offset
< 0 || (buffer_len
- offset
) < soself
->s_size
) {
1438 PyErr_Format(StructError
,
1439 "unpack_from requires a buffer of at least %zd bytes",
1443 return s_unpack_internal(soself
, buffer
+ offset
);
1448 * Guts of the pack function.
1450 * Takes a struct object, a tuple of arguments, and offset in that tuple of
1451 * argument for where to start processing the arguments for packing, and a
1452 * character buffer for writing the packed string. The caller must insure
1453 * that the buffer may contain the required length for packing the arguments.
1454 * 0 is returned on success, 1 is returned if there is an error.
1458 s_pack_internal(PyStructObject
*soself
, PyObject
*args
, int offset
, char* buf
)
1461 /* XXX(nnorwitz): why does i need to be a local? can we use
1462 the offset parameter or do we need the wider width? */
1465 memset(buf
, '\0', soself
->s_size
);
1467 for (code
= soself
->s_codes
; code
->fmtdef
!= NULL
; code
++) {
1469 PyObject
*v
= PyTuple_GET_ITEM(args
, i
++);
1470 const formatdef
*e
= code
->fmtdef
;
1471 char *res
= buf
+ code
->offset
;
1472 if (e
->format
== 's') {
1473 if (!PyString_Check(v
)) {
1474 PyErr_SetString(StructError
,
1475 "argument for 's' must "
1479 n
= PyString_GET_SIZE(v
);
1483 memcpy(res
, PyString_AS_STRING(v
), n
);
1484 } else if (e
->format
== 'p') {
1485 if (!PyString_Check(v
)) {
1486 PyErr_SetString(StructError
,
1487 "argument for 'p' must "
1491 n
= PyString_GET_SIZE(v
);
1492 if (n
> (code
->size
- 1))
1495 memcpy(res
+ 1, PyString_AS_STRING(v
), n
);
1498 *res
= Py_SAFE_DOWNCAST(n
, Py_ssize_t
, unsigned char);
1499 } else if (e
->pack(res
, v
, e
) < 0) {
1500 if (strchr(integer_codes
, e
->format
) != NULL
&&
1501 PyErr_ExceptionMatches(PyExc_OverflowError
))
1502 PyErr_Format(StructError
,
1503 "integer out of range for "
1515 PyDoc_STRVAR(s_pack__doc__
,
1516 "S.pack(v1, v2, ...) -> string\n\
1518 Return a string containing values v1, v2, ... packed according to this\n\
1519 Struct's format. See struct.__doc__ for more on format strings.");
1522 s_pack(PyObject
*self
, PyObject
*args
)
1524 PyStructObject
*soself
;
1527 /* Validate arguments. */
1528 soself
= (PyStructObject
*)self
;
1529 assert(PyStruct_Check(self
));
1530 assert(soself
->s_codes
!= NULL
);
1531 if (PyTuple_GET_SIZE(args
) != soself
->s_len
)
1533 PyErr_Format(StructError
,
1534 "pack requires exactly %zd arguments", soself
->s_len
);
1538 /* Allocate a new string */
1539 result
= PyString_FromStringAndSize((char *)NULL
, soself
->s_size
);
1544 if ( s_pack_internal(soself
, args
, 0, PyString_AS_STRING(result
)) != 0 ) {
1552 PyDoc_STRVAR(s_pack_into__doc__
,
1553 "S.pack_into(buffer, offset, v1, v2, ...)\n\
1555 Pack the values v1, v2, ... according to this Struct's format, write \n\
1556 the packed bytes into the writable buffer buf starting at offset. Note\n\
1557 that the offset is not an optional argument. See struct.__doc__ for \n\
1558 more on format strings.");
1561 s_pack_into(PyObject
*self
, PyObject
*args
)
1563 PyStructObject
*soself
;
1565 Py_ssize_t buffer_len
, offset
;
1567 /* Validate arguments. +1 is for the first arg as buffer. */
1568 soself
= (PyStructObject
*)self
;
1569 assert(PyStruct_Check(self
));
1570 assert(soself
->s_codes
!= NULL
);
1571 if (PyTuple_GET_SIZE(args
) != (soself
->s_len
+ 2))
1573 PyErr_Format(StructError
,
1574 "pack_into requires exactly %zd arguments",
1575 (soself
->s_len
+ 2));
1579 /* Extract a writable memory buffer from the first argument */
1580 if ( PyObject_AsWriteBuffer(PyTuple_GET_ITEM(args
, 0),
1581 (void**)&buffer
, &buffer_len
) == -1 ) {
1584 assert( buffer_len
>= 0 );
1586 /* Extract the offset from the first argument */
1587 offset
= PyInt_AsSsize_t(PyTuple_GET_ITEM(args
, 1));
1588 if (offset
== -1 && PyErr_Occurred())
1591 /* Support negative offsets. */
1593 offset
+= buffer_len
;
1595 /* Check boundaries */
1596 if (offset
< 0 || (buffer_len
- offset
) < soself
->s_size
) {
1597 PyErr_Format(StructError
,
1598 "pack_into requires a buffer of at least %zd bytes",
1604 if ( s_pack_internal(soself
, args
, 2, buffer
+ offset
) != 0 ) {
1612 s_get_format(PyStructObject
*self
, void *unused
)
1614 Py_INCREF(self
->s_format
);
1615 return self
->s_format
;
1619 s_get_size(PyStructObject
*self
, void *unused
)
1621 return PyInt_FromSsize_t(self
->s_size
);
1624 /* List of functions */
1626 static struct PyMethodDef s_methods
[] = {
1627 {"pack", s_pack
, METH_VARARGS
, s_pack__doc__
},
1628 {"pack_into", s_pack_into
, METH_VARARGS
, s_pack_into__doc__
},
1629 {"unpack", s_unpack
, METH_O
, s_unpack__doc__
},
1630 {"unpack_from", (PyCFunction
)s_unpack_from
, METH_VARARGS
|METH_KEYWORDS
,
1631 s_unpack_from__doc__
},
1632 {NULL
, NULL
} /* sentinel */
1635 PyDoc_STRVAR(s__doc__
, "Compiled struct object");
1637 #define OFF(x) offsetof(PyStructObject, x)
1639 static PyGetSetDef s_getsetlist
[] = {
1640 {"format", (getter
)s_get_format
, (setter
)NULL
, "struct format string", NULL
},
1641 {"size", (getter
)s_get_size
, (setter
)NULL
, "struct size in bytes", NULL
},
1642 {NULL
} /* sentinel */
1646 PyTypeObject PyStructType
= {
1647 PyVarObject_HEAD_INIT(NULL
, 0)
1649 sizeof(PyStructObject
),
1651 (destructor
)s_dealloc
, /* tp_dealloc */
1657 0, /* tp_as_number */
1658 0, /* tp_as_sequence */
1659 0, /* tp_as_mapping */
1663 PyObject_GenericGetAttr
, /* tp_getattro */
1664 PyObject_GenericSetAttr
, /* tp_setattro */
1665 0, /* tp_as_buffer */
1666 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
| Py_TPFLAGS_HAVE_WEAKREFS
,/* tp_flags */
1667 s__doc__
, /* tp_doc */
1668 0, /* tp_traverse */
1670 0, /* tp_richcompare */
1671 offsetof(PyStructObject
, weakreflist
), /* tp_weaklistoffset */
1673 0, /* tp_iternext */
1674 s_methods
, /* tp_methods */
1675 NULL
, /* tp_members */
1676 s_getsetlist
, /* tp_getset */
1679 0, /* tp_descr_get */
1680 0, /* tp_descr_set */
1681 0, /* tp_dictoffset */
1682 s_init
, /* tp_init */
1683 PyType_GenericAlloc
,/* tp_alloc */
1685 PyObject_Del
, /* tp_free */
1689 /* ---- Standalone functions ---- */
1691 #define MAXCACHE 100
1692 static PyObject
*cache
= NULL
;
1695 cache_struct(PyObject
*fmt
)
1697 PyObject
* s_object
;
1699 if (cache
== NULL
) {
1700 cache
= PyDict_New();
1705 s_object
= PyDict_GetItem(cache
, fmt
);
1706 if (s_object
!= NULL
) {
1707 Py_INCREF(s_object
);
1711 s_object
= PyObject_CallFunctionObjArgs((PyObject
*)(&PyStructType
), fmt
, NULL
);
1712 if (s_object
!= NULL
) {
1713 if (PyDict_Size(cache
) >= MAXCACHE
)
1714 PyDict_Clear(cache
);
1715 /* Attempt to cache the result */
1716 if (PyDict_SetItem(cache
, fmt
, s_object
) == -1)
1722 PyDoc_STRVAR(clearcache_doc
,
1723 "Clear the internal cache.");
1726 clearcache(PyObject
*self
)
1732 PyDoc_STRVAR(calcsize_doc
,
1733 "Return size of C struct described by format string fmt.");
1736 calcsize(PyObject
*self
, PyObject
*fmt
)
1739 PyObject
*s_object
= cache_struct(fmt
);
1740 if (s_object
== NULL
)
1742 n
= ((PyStructObject
*)s_object
)->s_size
;
1743 Py_DECREF(s_object
);
1744 return PyInt_FromSsize_t(n
);
1747 PyDoc_STRVAR(pack_doc
,
1748 "Return string containing values v1, v2, ... packed according to fmt.");
1751 pack(PyObject
*self
, PyObject
*args
)
1753 PyObject
*s_object
, *fmt
, *newargs
, *result
;
1754 Py_ssize_t n
= PyTuple_GET_SIZE(args
);
1757 PyErr_SetString(PyExc_TypeError
, "missing format argument");
1760 fmt
= PyTuple_GET_ITEM(args
, 0);
1761 newargs
= PyTuple_GetSlice(args
, 1, n
);
1762 if (newargs
== NULL
)
1765 s_object
= cache_struct(fmt
);
1766 if (s_object
== NULL
) {
1770 result
= s_pack(s_object
, newargs
);
1772 Py_DECREF(s_object
);
1776 PyDoc_STRVAR(pack_into_doc
,
1777 "Pack the values v1, v2, ... according to fmt.\n\
1778 Write the packed bytes into the writable buffer buf starting at offset.");
1781 pack_into(PyObject
*self
, PyObject
*args
)
1783 PyObject
*s_object
, *fmt
, *newargs
, *result
;
1784 Py_ssize_t n
= PyTuple_GET_SIZE(args
);
1787 PyErr_SetString(PyExc_TypeError
, "missing format argument");
1790 fmt
= PyTuple_GET_ITEM(args
, 0);
1791 newargs
= PyTuple_GetSlice(args
, 1, n
);
1792 if (newargs
== NULL
)
1795 s_object
= cache_struct(fmt
);
1796 if (s_object
== NULL
) {
1800 result
= s_pack_into(s_object
, newargs
);
1802 Py_DECREF(s_object
);
1806 PyDoc_STRVAR(unpack_doc
,
1807 "Unpack the string containing packed C structure data, according to fmt.\n\
1808 Requires len(string) == calcsize(fmt).");
1811 unpack(PyObject
*self
, PyObject
*args
)
1813 PyObject
*s_object
, *fmt
, *inputstr
, *result
;
1815 if (!PyArg_UnpackTuple(args
, "unpack", 2, 2, &fmt
, &inputstr
))
1818 s_object
= cache_struct(fmt
);
1819 if (s_object
== NULL
)
1821 result
= s_unpack(s_object
, inputstr
);
1822 Py_DECREF(s_object
);
1826 PyDoc_STRVAR(unpack_from_doc
,
1827 "Unpack the buffer, containing packed C structure data, according to\n\
1828 fmt, starting at offset. Requires len(buffer[offset:]) >= calcsize(fmt).");
1831 unpack_from(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
1833 PyObject
*s_object
, *fmt
, *newargs
, *result
;
1834 Py_ssize_t n
= PyTuple_GET_SIZE(args
);
1837 PyErr_SetString(PyExc_TypeError
, "missing format argument");
1840 fmt
= PyTuple_GET_ITEM(args
, 0);
1841 newargs
= PyTuple_GetSlice(args
, 1, n
);
1842 if (newargs
== NULL
)
1845 s_object
= cache_struct(fmt
);
1846 if (s_object
== NULL
) {
1850 result
= s_unpack_from(s_object
, newargs
, kwds
);
1852 Py_DECREF(s_object
);
1856 static struct PyMethodDef module_functions
[] = {
1857 {"_clearcache", (PyCFunction
)clearcache
, METH_NOARGS
, clearcache_doc
},
1858 {"calcsize", calcsize
, METH_O
, calcsize_doc
},
1859 {"pack", pack
, METH_VARARGS
, pack_doc
},
1860 {"pack_into", pack_into
, METH_VARARGS
, pack_into_doc
},
1861 {"unpack", unpack
, METH_VARARGS
, unpack_doc
},
1862 {"unpack_from", (PyCFunction
)unpack_from
,
1863 METH_VARARGS
|METH_KEYWORDS
, unpack_from_doc
},
1864 {NULL
, NULL
} /* sentinel */
1868 /* Module initialization */
1870 PyDoc_STRVAR(module_doc
,
1871 "Functions to convert between Python values and C structs represented\n\
1872 as Python strings. It uses format strings (explained below) as compact\n\
1873 descriptions of the lay-out of the C structs and the intended conversion\n\
1874 to/from Python values.\n\
1876 The optional first format char indicates byte order, size and alignment:\n\
1877 @: native order, size & alignment (default)\n\
1878 =: native order, std. size & alignment\n\
1879 <: little-endian, std. size & alignment\n\
1880 >: big-endian, std. size & alignment\n\
1883 The remaining chars indicate types of args and must match exactly;\n\
1884 these can be preceded by a decimal repeat count:\n\
1885 x: pad byte (no data); c:char; b:signed byte; B:unsigned byte;\n\
1886 ?: _Bool (requires C99; if not available, char is used instead)\n\
1887 h:short; H:unsigned short; i:int; I:unsigned int;\n\
1888 l:long; L:unsigned long; f:float; d:double.\n\
1889 Special cases (preceding decimal count indicates length):\n\
1890 s:string (array of char); p: pascal string (with count byte).\n\
1891 Special case (only available in native format):\n\
1892 P:an integer type that is wide enough to hold a pointer.\n\
1893 Special case (not in native mode unless 'long long' in platform C):\n\
1894 q:long long; Q:unsigned long long\n\
1895 Whitespace between formats is ignored.\n\
1897 The variable struct.error is an exception raised on errors.\n");
1904 ver
= PyString_FromString("0.2");
1908 m
= Py_InitModule3("_struct", module_functions
, module_doc
);
1912 Py_TYPE(&PyStructType
) = &PyType_Type
;
1913 if (PyType_Ready(&PyStructType
) < 0)
1916 /* This speed trick can't be used until overflow masking goes
1917 away, because native endian always raises exceptions
1918 instead of overflow masking. */
1920 /* Check endian and swap in faster functions */
1923 formatdef
*native
= native_table
;
1924 formatdef
*other
, *ptr
;
1925 if ((int)*(unsigned char*)&one
)
1926 other
= lilendian_table
;
1928 other
= bigendian_table
;
1929 /* Scan through the native table, find a matching
1930 entry in the endian table and swap in the
1931 native implementations whenever possible
1932 (64-bit platforms may not have "standard" sizes) */
1933 while (native
->format
!= '\0' && other
->format
!= '\0') {
1935 while (ptr
->format
!= '\0') {
1936 if (ptr
->format
== native
->format
) {
1937 /* Match faster when formats are
1938 listed in the same order */
1941 /* Only use the trick if the
1943 if (ptr
->size
!= native
->size
)
1945 /* Skip float and double, could be
1946 "unknown" float format */
1947 if (ptr
->format
== 'd' || ptr
->format
== 'f')
1949 ptr
->pack
= native
->pack
;
1950 ptr
->unpack
= native
->unpack
;
1959 /* Add some symbolic constants to the module */
1960 if (StructError
== NULL
) {
1961 StructError
= PyErr_NewException("struct.error", NULL
, NULL
);
1962 if (StructError
== NULL
)
1966 Py_INCREF(StructError
);
1967 PyModule_AddObject(m
, "error", StructError
);
1969 Py_INCREF((PyObject
*)&PyStructType
);
1970 PyModule_AddObject(m
, "Struct", (PyObject
*)&PyStructType
);
1972 PyModule_AddObject(m
, "__version__", ver
);
1974 PyModule_AddIntConstant(m
, "_PY_STRUCT_RANGE_CHECKING", 1);
1975 #ifdef PY_STRUCT_FLOAT_COERCE
1976 PyModule_AddIntConstant(m
, "_PY_STRUCT_FLOAT_COERCE", 1);