1 /* struct module -- pack values into and (out of) bytes objects */
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 /* The translation function for each format character is table driven */
16 typedef struct _formatdef
{
20 PyObject
* (*unpack
)(const char *,
21 const struct _formatdef
*);
22 int (*pack
)(char *, PyObject
*,
23 const struct _formatdef
*);
26 typedef struct _formatcode
{
27 const struct _formatdef
*fmtdef
;
32 /* Struct object interface */
40 PyObject
*weakreflist
; /* List of weak references */
44 #define PyStruct_Check(op) PyObject_TypeCheck(op, &PyStructType)
45 #define PyStruct_CheckExact(op) (Py_TYPE(op) == &PyStructType)
50 static PyObject
*StructError
;
53 /* Define various structs to figure out the alignments of types */
56 typedef struct { char c
; short x
; } st_short
;
57 typedef struct { char c
; int x
; } st_int
;
58 typedef struct { char c
; long x
; } st_long
;
59 typedef struct { char c
; float x
; } st_float
;
60 typedef struct { char c
; double x
; } st_double
;
61 typedef struct { char c
; void *x
; } st_void_p
;
63 #define SHORT_ALIGN (sizeof(st_short) - sizeof(short))
64 #define INT_ALIGN (sizeof(st_int) - sizeof(int))
65 #define LONG_ALIGN (sizeof(st_long) - sizeof(long))
66 #define FLOAT_ALIGN (sizeof(st_float) - sizeof(float))
67 #define DOUBLE_ALIGN (sizeof(st_double) - sizeof(double))
68 #define VOID_P_ALIGN (sizeof(st_void_p) - sizeof(void *))
70 /* We can't support q and Q in native mode unless the compiler does;
71 in std mode, they're 8 bytes on all platforms. */
73 typedef struct { char c
; PY_LONG_LONG x
; } s_long_long
;
74 #define LONG_LONG_ALIGN (sizeof(s_long_long) - sizeof(PY_LONG_LONG))
78 #define BOOL_TYPE _Bool
79 typedef struct { char c
; _Bool x
; } s_bool
;
80 #define BOOL_ALIGN (sizeof(s_bool) - sizeof(BOOL_TYPE))
82 #define BOOL_TYPE char
86 #define STRINGIFY(x) #x
89 #pragma options align=reset
92 /* Helper to get a PyLongObject. Caller should decref. */
95 get_pylong(PyObject
*v
)
98 if (!PyLong_Check(v
)) {
99 PyErr_SetString(StructError
,
100 "required argument is not an integer");
108 /* Helper routine to get a C long and raise the appropriate error if it isn't
112 get_long(PyObject
*v
, long *p
)
116 if (!PyLong_Check(v
)) {
117 PyErr_SetString(StructError
,
118 "required argument is not an integer");
121 x
= PyLong_AsLong(v
);
122 if (x
== -1 && PyErr_Occurred()) {
123 if (PyErr_ExceptionMatches(PyExc_OverflowError
))
124 PyErr_SetString(StructError
,
125 "argument out of range");
133 /* Same, but handling unsigned long */
136 get_ulong(PyObject
*v
, unsigned long *p
)
140 if (!PyLong_Check(v
)) {
141 PyErr_SetString(StructError
,
142 "required argument is not an integer");
145 x
= PyLong_AsUnsignedLong(v
);
146 if (x
== (unsigned long)-1 && PyErr_Occurred()) {
147 if (PyErr_ExceptionMatches(PyExc_OverflowError
))
148 PyErr_SetString(StructError
,
149 "argument out of range");
156 #ifdef HAVE_LONG_LONG
158 /* Same, but handling native long long. */
161 get_longlong(PyObject
*v
, PY_LONG_LONG
*p
)
164 if (!PyLong_Check(v
)) {
165 PyErr_SetString(StructError
,
166 "required argument is not an integer");
169 x
= PyLong_AsLongLong(v
);
170 if (x
== -1 && PyErr_Occurred()) {
171 if (PyErr_ExceptionMatches(PyExc_OverflowError
))
172 PyErr_SetString(StructError
,
173 "argument out of range");
180 /* Same, but handling native unsigned long long. */
183 get_ulonglong(PyObject
*v
, unsigned PY_LONG_LONG
*p
)
185 unsigned PY_LONG_LONG x
;
186 if (!PyLong_Check(v
)) {
187 PyErr_SetString(StructError
,
188 "required argument is not an integer");
191 x
= PyLong_AsUnsignedLongLong(v
);
192 if (x
== -1 && PyErr_Occurred()) {
193 if (PyErr_ExceptionMatches(PyExc_OverflowError
))
194 PyErr_SetString(StructError
,
195 "argument out of range");
205 #define RANGE_ERROR(x, f, flag, mask) return _range_error(f, flag)
208 /* Floating point helpers */
211 unpack_float(const char *p
, /* start of 4-byte string */
212 int le
) /* true for little-endian, false for big-endian */
216 x
= _PyFloat_Unpack4((unsigned char *)p
, le
);
217 if (x
== -1.0 && PyErr_Occurred())
219 return PyFloat_FromDouble(x
);
223 unpack_double(const char *p
, /* start of 8-byte string */
224 int le
) /* true for little-endian, false for big-endian */
228 x
= _PyFloat_Unpack8((unsigned char *)p
, le
);
229 if (x
== -1.0 && PyErr_Occurred())
231 return PyFloat_FromDouble(x
);
234 /* Helper to format the range error exceptions */
236 _range_error(const formatdef
*f
, int is_unsigned
)
238 /* ulargest is the largest unsigned value with f->size bytes.
239 * Note that the simpler:
240 * ((size_t)1 << (f->size * 8)) - 1
241 * doesn't work when f->size == sizeof(size_t) because C doesn't
242 * define what happens when a left shift count is >= the number of
243 * bits in the integer being shifted; e.g., on some boxes it doesn't
244 * shift at all when they're equal.
246 const size_t ulargest
= (size_t)-1 >> ((SIZEOF_SIZE_T
- f
->size
)*8);
247 assert(f
->size
>= 1 && f
->size
<= SIZEOF_SIZE_T
);
249 PyErr_Format(StructError
,
250 "'%c' format requires 0 <= number <= %zu",
254 const Py_ssize_t largest
= (Py_ssize_t
)(ulargest
>> 1);
255 PyErr_Format(StructError
,
256 "'%c' format requires %zd <= number <= %zd",
267 /* A large number of small routines follow, with names of the form
271 [bln] distiguishes among big-endian, little-endian and native.
272 [pu] distiguishes between pack (to struct) and unpack (from struct).
273 TYPE is one of char, byte, ubyte, etc.
276 /* Native mode routines. ****************************************************/
278 In all n[up]_<type> routines handling types larger than 1 byte, there is
279 *no* guarantee that the p pointer is properly aligned for each type,
280 therefore memcpy is called. An intermediate variable is used to
281 compensate for big-endian architectures.
282 Normally both the intermediate variable and the memcpy call will be
283 skipped by C optimisation in little-endian architectures (gcc >= 2.91
287 nu_char(const char *p
, const formatdef
*f
)
289 return PyBytes_FromStringAndSize(p
, 1);
293 nu_byte(const char *p
, const formatdef
*f
)
295 return PyLong_FromLong((long) *(signed char *)p
);
299 nu_ubyte(const char *p
, const formatdef
*f
)
301 return PyLong_FromLong((long) *(unsigned char *)p
);
305 nu_short(const char *p
, const formatdef
*f
)
308 memcpy((char *)&x
, p
, sizeof x
);
309 return PyLong_FromLong((long)x
);
313 nu_ushort(const char *p
, const formatdef
*f
)
316 memcpy((char *)&x
, p
, sizeof x
);
317 return PyLong_FromLong((long)x
);
321 nu_int(const char *p
, const formatdef
*f
)
324 memcpy((char *)&x
, p
, sizeof x
);
325 return PyLong_FromLong((long)x
);
329 nu_uint(const char *p
, const formatdef
*f
)
332 memcpy((char *)&x
, p
, sizeof x
);
333 #if (SIZEOF_LONG > SIZEOF_INT)
334 return PyLong_FromLong((long)x
);
336 if (x
<= ((unsigned int)LONG_MAX
))
337 return PyLong_FromLong((long)x
);
338 return PyLong_FromUnsignedLong((unsigned long)x
);
343 nu_long(const char *p
, const formatdef
*f
)
346 memcpy((char *)&x
, p
, sizeof x
);
347 return PyLong_FromLong(x
);
351 nu_ulong(const char *p
, const formatdef
*f
)
354 memcpy((char *)&x
, p
, sizeof x
);
356 return PyLong_FromLong((long)x
);
357 return PyLong_FromUnsignedLong(x
);
360 /* Native mode doesn't support q or Q unless the platform C supports
361 long long (or, on Windows, __int64). */
363 #ifdef HAVE_LONG_LONG
366 nu_longlong(const char *p
, const formatdef
*f
)
369 memcpy((char *)&x
, p
, sizeof x
);
370 if (x
>= LONG_MIN
&& x
<= LONG_MAX
)
371 return PyLong_FromLong(Py_SAFE_DOWNCAST(x
, PY_LONG_LONG
, long));
372 return PyLong_FromLongLong(x
);
376 nu_ulonglong(const char *p
, const formatdef
*f
)
378 unsigned PY_LONG_LONG x
;
379 memcpy((char *)&x
, p
, sizeof x
);
381 return PyLong_FromLong(Py_SAFE_DOWNCAST(x
, unsigned PY_LONG_LONG
, long));
382 return PyLong_FromUnsignedLongLong(x
);
388 nu_bool(const char *p
, const formatdef
*f
)
391 memcpy((char *)&x
, p
, sizeof x
);
392 return PyBool_FromLong(x
!= 0);
397 nu_float(const char *p
, const formatdef
*f
)
400 memcpy((char *)&x
, p
, sizeof x
);
401 return PyFloat_FromDouble((double)x
);
405 nu_double(const char *p
, const formatdef
*f
)
408 memcpy((char *)&x
, p
, sizeof x
);
409 return PyFloat_FromDouble(x
);
413 nu_void_p(const char *p
, const formatdef
*f
)
416 memcpy((char *)&x
, p
, sizeof x
);
417 return PyLong_FromVoidPtr(x
);
421 np_byte(char *p
, PyObject
*v
, const formatdef
*f
)
424 if (get_long(v
, &x
) < 0)
426 if (x
< -128 || x
> 127){
427 PyErr_SetString(StructError
,
428 "byte format requires -128 <= number <= 127");
436 np_ubyte(char *p
, PyObject
*v
, const formatdef
*f
)
439 if (get_long(v
, &x
) < 0)
441 if (x
< 0 || x
> 255){
442 PyErr_SetString(StructError
,
443 "ubyte format requires 0 <= number <= 255");
451 np_char(char *p
, PyObject
*v
, const formatdef
*f
)
453 if (PyUnicode_Check(v
)) {
454 v
= _PyUnicode_AsDefaultEncodedString(v
, NULL
);
458 if (!PyBytes_Check(v
) || PyBytes_Size(v
) != 1) {
459 PyErr_SetString(StructError
,
460 "char format requires bytes or string of length 1");
463 *p
= *PyBytes_AsString(v
);
468 np_short(char *p
, PyObject
*v
, const formatdef
*f
)
472 if (get_long(v
, &x
) < 0)
474 if (x
< SHRT_MIN
|| x
> SHRT_MAX
){
475 PyErr_SetString(StructError
,
476 "short format requires " STRINGIFY(SHRT_MIN
)
477 " <= number <= " STRINGIFY(SHRT_MAX
));
481 memcpy(p
, (char *)&y
, sizeof y
);
486 np_ushort(char *p
, PyObject
*v
, const formatdef
*f
)
490 if (get_long(v
, &x
) < 0)
492 if (x
< 0 || x
> USHRT_MAX
){
493 PyErr_SetString(StructError
,
494 "short format requires 0 <= number <= " STRINGIFY(USHRT_MAX
));
497 y
= (unsigned short)x
;
498 memcpy(p
, (char *)&y
, sizeof y
);
503 np_int(char *p
, PyObject
*v
, const formatdef
*f
)
507 if (get_long(v
, &x
) < 0)
509 #if (SIZEOF_LONG > SIZEOF_INT)
510 if ((x
< ((long)INT_MIN
)) || (x
> ((long)INT_MAX
)))
511 RANGE_ERROR(x
, f
, 0, -1);
514 memcpy(p
, (char *)&y
, sizeof y
);
519 np_uint(char *p
, PyObject
*v
, const formatdef
*f
)
523 if (get_ulong(v
, &x
) < 0)
526 #if (SIZEOF_LONG > SIZEOF_INT)
527 if (x
> ((unsigned long)UINT_MAX
))
528 RANGE_ERROR(y
, f
, 1, -1);
530 memcpy(p
, (char *)&y
, sizeof y
);
535 np_long(char *p
, PyObject
*v
, const formatdef
*f
)
538 if (get_long(v
, &x
) < 0)
540 memcpy(p
, (char *)&x
, sizeof x
);
545 np_ulong(char *p
, PyObject
*v
, const formatdef
*f
)
548 if (get_ulong(v
, &x
) < 0)
550 memcpy(p
, (char *)&x
, sizeof x
);
554 #ifdef HAVE_LONG_LONG
557 np_longlong(char *p
, PyObject
*v
, const formatdef
*f
)
560 if (get_longlong(v
, &x
) < 0)
562 memcpy(p
, (char *)&x
, sizeof x
);
567 np_ulonglong(char *p
, PyObject
*v
, const formatdef
*f
)
569 unsigned PY_LONG_LONG x
;
570 if (get_ulonglong(v
, &x
) < 0)
572 memcpy(p
, (char *)&x
, sizeof x
);
579 np_bool(char *p
, PyObject
*v
, const formatdef
*f
)
582 y
= PyObject_IsTrue(v
);
583 memcpy(p
, (char *)&y
, sizeof y
);
588 np_float(char *p
, PyObject
*v
, const formatdef
*f
)
590 float x
= (float)PyFloat_AsDouble(v
);
591 if (x
== -1 && PyErr_Occurred()) {
592 PyErr_SetString(StructError
,
593 "required argument is not a float");
596 memcpy(p
, (char *)&x
, sizeof x
);
601 np_double(char *p
, PyObject
*v
, const formatdef
*f
)
603 double x
= PyFloat_AsDouble(v
);
604 if (x
== -1 && PyErr_Occurred()) {
605 PyErr_SetString(StructError
,
606 "required argument is not a float");
609 memcpy(p
, (char *)&x
, sizeof(double));
614 np_void_p(char *p
, PyObject
*v
, const formatdef
*f
)
621 assert(PyLong_Check(v
));
622 x
= PyLong_AsVoidPtr(v
);
624 if (x
== NULL
&& PyErr_Occurred())
626 memcpy(p
, (char *)&x
, sizeof x
);
630 static formatdef native_table
[] = {
631 {'x', sizeof(char), 0, NULL
},
632 {'b', sizeof(char), 0, nu_byte
, np_byte
},
633 {'B', sizeof(char), 0, nu_ubyte
, np_ubyte
},
634 {'c', sizeof(char), 0, nu_char
, np_char
},
635 {'s', sizeof(char), 0, NULL
},
636 {'p', sizeof(char), 0, NULL
},
637 {'h', sizeof(short), SHORT_ALIGN
, nu_short
, np_short
},
638 {'H', sizeof(short), SHORT_ALIGN
, nu_ushort
, np_ushort
},
639 {'i', sizeof(int), INT_ALIGN
, nu_int
, np_int
},
640 {'I', sizeof(int), INT_ALIGN
, nu_uint
, np_uint
},
641 {'l', sizeof(long), LONG_ALIGN
, nu_long
, np_long
},
642 {'L', sizeof(long), LONG_ALIGN
, nu_ulong
, np_ulong
},
643 #ifdef HAVE_LONG_LONG
644 {'q', sizeof(PY_LONG_LONG
), LONG_LONG_ALIGN
, nu_longlong
, np_longlong
},
645 {'Q', sizeof(PY_LONG_LONG
), LONG_LONG_ALIGN
, nu_ulonglong
,np_ulonglong
},
647 {'?', sizeof(BOOL_TYPE
), BOOL_ALIGN
, nu_bool
, np_bool
},
648 {'f', sizeof(float), FLOAT_ALIGN
, nu_float
, np_float
},
649 {'d', sizeof(double), DOUBLE_ALIGN
, nu_double
, np_double
},
650 {'P', sizeof(void *), VOID_P_ALIGN
, nu_void_p
, np_void_p
},
654 /* Big-endian routines. *****************************************************/
657 bu_int(const char *p
, const formatdef
*f
)
660 Py_ssize_t i
= f
->size
;
661 const unsigned char *bytes
= (const unsigned char *)p
;
663 x
= (x
<<8) | *bytes
++;
665 /* Extend the sign bit. */
666 if (SIZEOF_LONG
> f
->size
)
667 x
|= -(x
& (1L << ((8 * f
->size
) - 1)));
668 return PyLong_FromLong(x
);
672 bu_uint(const char *p
, const formatdef
*f
)
675 Py_ssize_t i
= f
->size
;
676 const unsigned char *bytes
= (const unsigned char *)p
;
678 x
= (x
<<8) | *bytes
++;
681 return PyLong_FromLong((long)x
);
682 return PyLong_FromUnsignedLong(x
);
686 bu_longlong(const char *p
, const formatdef
*f
)
688 #ifdef HAVE_LONG_LONG
690 Py_ssize_t i
= f
->size
;
691 const unsigned char *bytes
= (const unsigned char *)p
;
693 x
= (x
<<8) | *bytes
++;
695 /* Extend the sign bit. */
696 if (SIZEOF_LONG_LONG
> f
->size
)
697 x
|= -(x
& ((PY_LONG_LONG
)1 << ((8 * f
->size
) - 1)));
698 if (x
>= LONG_MIN
&& x
<= LONG_MAX
)
699 return PyLong_FromLong(Py_SAFE_DOWNCAST(x
, PY_LONG_LONG
, long));
700 return PyLong_FromLongLong(x
);
702 return _PyLong_FromByteArray((const unsigned char *)p
,
704 0, /* little-endian */
710 bu_ulonglong(const char *p
, const formatdef
*f
)
712 #ifdef HAVE_LONG_LONG
713 unsigned PY_LONG_LONG x
= 0;
714 Py_ssize_t i
= f
->size
;
715 const unsigned char *bytes
= (const unsigned char *)p
;
717 x
= (x
<<8) | *bytes
++;
720 return PyLong_FromLong(Py_SAFE_DOWNCAST(x
, unsigned PY_LONG_LONG
, long));
721 return PyLong_FromUnsignedLongLong(x
);
723 return _PyLong_FromByteArray((const unsigned char *)p
,
725 0, /* little-endian */
731 bu_float(const char *p
, const formatdef
*f
)
733 return unpack_float(p
, 0);
737 bu_double(const char *p
, const formatdef
*f
)
739 return unpack_double(p
, 0);
743 bu_bool(const char *p
, const formatdef
*f
)
746 memcpy((char *)&x
, p
, sizeof x
);
747 return PyBool_FromLong(x
!= 0);
751 bp_int(char *p
, PyObject
*v
, const formatdef
*f
)
755 if (get_long(v
, &x
) < 0)
758 if (i
!= SIZEOF_LONG
) {
759 if ((i
== 2) && (x
< -32768 || x
> 32767))
760 RANGE_ERROR(x
, f
, 0, 0xffffL
);
761 #if (SIZEOF_LONG != 4)
762 else if ((i
== 4) && (x
< -2147483648L || x
> 2147483647L))
763 RANGE_ERROR(x
, f
, 0, 0xffffffffL
);
774 bp_uint(char *p
, PyObject
*v
, const formatdef
*f
)
778 if (get_ulong(v
, &x
) < 0)
781 if (i
!= SIZEOF_LONG
) {
782 unsigned long maxint
= 1;
783 maxint
<<= (unsigned long)(i
* 8);
785 RANGE_ERROR(x
, f
, 1, maxint
- 1);
795 bp_longlong(char *p
, PyObject
*v
, const formatdef
*f
)
801 res
= _PyLong_AsByteArray((PyLongObject
*)v
,
804 0, /* little_endian */
811 bp_ulonglong(char *p
, PyObject
*v
, const formatdef
*f
)
817 res
= _PyLong_AsByteArray((PyLongObject
*)v
,
820 0, /* little_endian */
827 bp_float(char *p
, PyObject
*v
, const formatdef
*f
)
829 double x
= PyFloat_AsDouble(v
);
830 if (x
== -1 && PyErr_Occurred()) {
831 PyErr_SetString(StructError
,
832 "required argument is not a float");
835 return _PyFloat_Pack4(x
, (unsigned char *)p
, 0);
839 bp_double(char *p
, PyObject
*v
, const formatdef
*f
)
841 double x
= PyFloat_AsDouble(v
);
842 if (x
== -1 && PyErr_Occurred()) {
843 PyErr_SetString(StructError
,
844 "required argument is not a float");
847 return _PyFloat_Pack8(x
, (unsigned char *)p
, 0);
851 bp_bool(char *p
, PyObject
*v
, const formatdef
*f
)
854 y
= PyObject_IsTrue(v
);
855 memcpy(p
, (char *)&y
, sizeof y
);
859 static formatdef bigendian_table
[] = {
861 {'b', 1, 0, nu_byte
, np_byte
},
862 {'B', 1, 0, nu_ubyte
, np_ubyte
},
863 {'c', 1, 0, nu_char
, np_char
},
866 {'h', 2, 0, bu_int
, bp_int
},
867 {'H', 2, 0, bu_uint
, bp_uint
},
868 {'i', 4, 0, bu_int
, bp_int
},
869 {'I', 4, 0, bu_uint
, bp_uint
},
870 {'l', 4, 0, bu_int
, bp_int
},
871 {'L', 4, 0, bu_uint
, bp_uint
},
872 {'q', 8, 0, bu_longlong
, bp_longlong
},
873 {'Q', 8, 0, bu_ulonglong
, bp_ulonglong
},
874 {'?', 1, 0, bu_bool
, bp_bool
},
875 {'f', 4, 0, bu_float
, bp_float
},
876 {'d', 8, 0, bu_double
, bp_double
},
880 /* Little-endian routines. *****************************************************/
883 lu_int(const char *p
, const formatdef
*f
)
886 Py_ssize_t i
= f
->size
;
887 const unsigned char *bytes
= (const unsigned char *)p
;
889 x
= (x
<<8) | bytes
[--i
];
891 /* Extend the sign bit. */
892 if (SIZEOF_LONG
> f
->size
)
893 x
|= -(x
& (1L << ((8 * f
->size
) - 1)));
894 return PyLong_FromLong(x
);
898 lu_uint(const char *p
, const formatdef
*f
)
901 Py_ssize_t i
= f
->size
;
902 const unsigned char *bytes
= (const unsigned char *)p
;
904 x
= (x
<<8) | bytes
[--i
];
907 return PyLong_FromLong((long)x
);
908 return PyLong_FromUnsignedLong((long)x
);
912 lu_longlong(const char *p
, const formatdef
*f
)
914 #ifdef HAVE_LONG_LONG
916 Py_ssize_t i
= f
->size
;
917 const unsigned char *bytes
= (const unsigned char *)p
;
919 x
= (x
<<8) | bytes
[--i
];
921 /* Extend the sign bit. */
922 if (SIZEOF_LONG_LONG
> f
->size
)
923 x
|= -(x
& ((PY_LONG_LONG
)1 << ((8 * f
->size
) - 1)));
924 if (x
>= LONG_MIN
&& x
<= LONG_MAX
)
925 return PyLong_FromLong(Py_SAFE_DOWNCAST(x
, PY_LONG_LONG
, long));
926 return PyLong_FromLongLong(x
);
928 return _PyLong_FromByteArray((const unsigned char *)p
,
930 1, /* little-endian */
936 lu_ulonglong(const char *p
, const formatdef
*f
)
938 #ifdef HAVE_LONG_LONG
939 unsigned PY_LONG_LONG x
= 0;
940 Py_ssize_t i
= f
->size
;
941 const unsigned char *bytes
= (const unsigned char *)p
;
943 x
= (x
<<8) | bytes
[--i
];
946 return PyLong_FromLong(Py_SAFE_DOWNCAST(x
, unsigned PY_LONG_LONG
, long));
947 return PyLong_FromUnsignedLongLong(x
);
949 return _PyLong_FromByteArray((const unsigned char *)p
,
951 1, /* little-endian */
957 lu_float(const char *p
, const formatdef
*f
)
959 return unpack_float(p
, 1);
963 lu_double(const char *p
, const formatdef
*f
)
965 return unpack_double(p
, 1);
969 lp_int(char *p
, PyObject
*v
, const formatdef
*f
)
973 if (get_long(v
, &x
) < 0)
976 if (i
!= SIZEOF_LONG
) {
977 if ((i
== 2) && (x
< -32768 || x
> 32767))
978 RANGE_ERROR(x
, f
, 0, 0xffffL
);
979 #if (SIZEOF_LONG != 4)
980 else if ((i
== 4) && (x
< -2147483648L || x
> 2147483647L))
981 RANGE_ERROR(x
, f
, 0, 0xffffffffL
);
992 lp_uint(char *p
, PyObject
*v
, const formatdef
*f
)
996 if (get_ulong(v
, &x
) < 0)
999 if (i
!= SIZEOF_LONG
) {
1000 unsigned long maxint
= 1;
1001 maxint
<<= (unsigned long)(i
* 8);
1003 RANGE_ERROR(x
, f
, 1, maxint
- 1);
1013 lp_longlong(char *p
, PyObject
*v
, const formatdef
*f
)
1019 res
= _PyLong_AsByteArray((PyLongObject
*)v
,
1022 1, /* little_endian */
1029 lp_ulonglong(char *p
, PyObject
*v
, const formatdef
*f
)
1035 res
= _PyLong_AsByteArray((PyLongObject
*)v
,
1038 1, /* little_endian */
1045 lp_float(char *p
, PyObject
*v
, const formatdef
*f
)
1047 double x
= PyFloat_AsDouble(v
);
1048 if (x
== -1 && PyErr_Occurred()) {
1049 PyErr_SetString(StructError
,
1050 "required argument is not a float");
1053 return _PyFloat_Pack4(x
, (unsigned char *)p
, 1);
1057 lp_double(char *p
, PyObject
*v
, const formatdef
*f
)
1059 double x
= PyFloat_AsDouble(v
);
1060 if (x
== -1 && PyErr_Occurred()) {
1061 PyErr_SetString(StructError
,
1062 "required argument is not a float");
1065 return _PyFloat_Pack8(x
, (unsigned char *)p
, 1);
1068 static formatdef lilendian_table
[] = {
1070 {'b', 1, 0, nu_byte
, np_byte
},
1071 {'B', 1, 0, nu_ubyte
, np_ubyte
},
1072 {'c', 1, 0, nu_char
, np_char
},
1075 {'h', 2, 0, lu_int
, lp_int
},
1076 {'H', 2, 0, lu_uint
, lp_uint
},
1077 {'i', 4, 0, lu_int
, lp_int
},
1078 {'I', 4, 0, lu_uint
, lp_uint
},
1079 {'l', 4, 0, lu_int
, lp_int
},
1080 {'L', 4, 0, lu_uint
, lp_uint
},
1081 {'q', 8, 0, lu_longlong
, lp_longlong
},
1082 {'Q', 8, 0, lu_ulonglong
, lp_ulonglong
},
1083 {'?', 1, 0, bu_bool
, bp_bool
}, /* Std rep not endian dep,
1084 but potentially different from native rep -- reuse bx_bool funcs. */
1085 {'f', 4, 0, lu_float
, lp_float
},
1086 {'d', 8, 0, lu_double
, lp_double
},
1091 static const formatdef
*
1092 whichtable(char **pfmt
)
1094 const char *fmt
= (*pfmt
)++; /* May be backed out of later */
1097 return lilendian_table
;
1099 case '!': /* Network byte order is big-endian */
1100 return bigendian_table
;
1101 case '=': { /* Host byte order -- different from native in aligment! */
1103 char *p
= (char *) &n
;
1105 return lilendian_table
;
1107 return bigendian_table
;
1110 --*pfmt
; /* Back out of pointer increment */
1113 return native_table
;
1118 /* Get the table entry for a format code */
1120 static const formatdef
*
1121 getentry(int c
, const formatdef
*f
)
1123 for (; f
->format
!= '\0'; f
++) {
1124 if (f
->format
== c
) {
1128 PyErr_SetString(StructError
, "bad char in struct format");
1133 /* Align a size according to a format code */
1136 align(Py_ssize_t size
, char c
, const formatdef
*e
)
1138 if (e
->format
== c
) {
1140 size
= ((size
+ e
->alignment
- 1)
1149 /* calculate the size of a format string */
1152 prepare_s(PyStructObject
*self
)
1161 Py_ssize_t size
, len
, num
, itemsize
, x
;
1163 fmt
= PyBytes_AS_STRING(self
->s_format
);
1165 f
= whichtable((char **)&fmt
);
1170 while ((c
= *s
++) != '\0') {
1171 if (isspace(Py_CHARMASK(c
)))
1173 if ('0' <= c
&& c
<= '9') {
1175 while ('0' <= (c
= *s
++) && c
<= '9') {
1176 x
= num
*10 + (c
- '0');
1180 "overflow in item count");
1196 case 's': /* fall through */
1197 case 'p': len
++; break;
1199 default: len
+= num
; break;
1203 size
= align(size
, c
, e
);
1206 if (x
/itemsize
!= num
|| size
< 0) {
1207 PyErr_SetString(StructError
,
1208 "total struct size too long");
1213 /* check for overflow */
1214 if ((len
+ 1) > (PY_SSIZE_T_MAX
/ sizeof(formatcode
))) {
1219 self
->s_size
= size
;
1221 codes
= PyMem_MALLOC((len
+ 1) * sizeof(formatcode
));
1222 if (codes
== NULL
) {
1226 self
->s_codes
= codes
;
1230 while ((c
= *s
++) != '\0') {
1231 if (isspace(Py_CHARMASK(c
)))
1233 if ('0' <= c
&& c
<= '9') {
1235 while ('0' <= (c
= *s
++) && c
<= '9')
1236 num
= num
*10 + (c
- '0');
1245 size
= align(size
, c
, e
);
1246 if (c
== 's' || c
== 'p') {
1247 codes
->offset
= size
;
1252 } else if (c
== 'x') {
1255 while (--num
>= 0) {
1256 codes
->offset
= size
;
1257 codes
->size
= e
->size
;
1264 codes
->fmtdef
= NULL
;
1265 codes
->offset
= size
;
1272 s_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
1276 assert(type
!= NULL
&& type
->tp_alloc
!= NULL
);
1278 self
= type
->tp_alloc(type
, 0);
1280 PyStructObject
*s
= (PyStructObject
*)self
;
1282 s
->s_format
= Py_None
;
1291 s_init(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
1293 PyStructObject
*soself
= (PyStructObject
*)self
;
1294 PyObject
*o_format
= NULL
;
1296 static char *kwlist
[] = {"format", 0};
1298 assert(PyStruct_Check(self
));
1300 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "O:Struct", kwlist
,
1304 if (PyUnicode_Check(o_format
)) {
1305 o_format
= PyUnicode_AsASCIIString(o_format
);
1306 if (o_format
== NULL
)
1309 /* XXX support buffer interface, too */
1311 Py_INCREF(o_format
);
1314 if (!PyBytes_Check(o_format
)) {
1315 Py_DECREF(o_format
);
1316 PyErr_Format(PyExc_TypeError
,
1317 "Struct() argument 1 must be bytes, not %.200s",
1318 Py_TYPE(o_format
)->tp_name
);
1322 Py_CLEAR(soself
->s_format
);
1323 soself
->s_format
= o_format
;
1325 ret
= prepare_s(soself
);
1330 s_dealloc(PyStructObject
*s
)
1332 if (s
->weakreflist
!= NULL
)
1333 PyObject_ClearWeakRefs((PyObject
*)s
);
1334 if (s
->s_codes
!= NULL
) {
1335 PyMem_FREE(s
->s_codes
);
1337 Py_XDECREF(s
->s_format
);
1338 Py_TYPE(s
)->tp_free((PyObject
*)s
);
1342 s_unpack_internal(PyStructObject
*soself
, char *startfrom
) {
1345 PyObject
*result
= PyTuple_New(soself
->s_len
);
1349 for (code
= soself
->s_codes
; code
->fmtdef
!= NULL
; code
++) {
1351 const formatdef
*e
= code
->fmtdef
;
1352 const char *res
= startfrom
+ code
->offset
;
1353 if (e
->format
== 's') {
1354 v
= PyBytes_FromStringAndSize(res
, code
->size
);
1355 } else if (e
->format
== 'p') {
1356 Py_ssize_t n
= *(unsigned char*)res
;
1357 if (n
>= code
->size
)
1359 v
= PyBytes_FromStringAndSize(res
+ 1, n
);
1361 v
= e
->unpack(res
, e
);
1365 PyTuple_SET_ITEM(result
, i
++, v
);
1375 PyDoc_STRVAR(s_unpack__doc__
,
1376 "S.unpack(buffer) -> (v1, v2, ...)\n\
1378 Return tuple containing values unpacked according to this Struct's format.\n\
1379 Requires len(buffer) == self.size. See struct.__doc__ for more on format\n\
1383 s_unpack(PyObject
*self
, PyObject
*input
)
1387 PyStructObject
*soself
= (PyStructObject
*)self
;
1389 assert(PyStruct_Check(self
));
1390 assert(soself
->s_codes
!= NULL
);
1391 if (PyObject_GetBuffer(input
, &vbuf
, PyBUF_SIMPLE
) < 0)
1393 if (vbuf
.len
!= soself
->s_size
) {
1394 PyErr_Format(StructError
,
1395 "unpack requires a bytes argument of length %zd",
1397 PyBuffer_Release(&vbuf
);
1400 result
= s_unpack_internal(soself
, vbuf
.buf
);
1401 PyBuffer_Release(&vbuf
);
1405 PyDoc_STRVAR(s_unpack_from__doc__
,
1406 "S.unpack_from(buffer[, offset]) -> (v1, v2, ...)\n\
1408 Return tuple containing values unpacked according to this Struct's format.\n\
1409 Unlike unpack, unpack_from can unpack values from any object supporting\n\
1410 the buffer API, not just str. Requires len(buffer[offset:]) >= self.size.\n\
1411 See struct.__doc__ for more on format strings.");
1414 s_unpack_from(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
1416 static char *kwlist
[] = {"buffer", "offset", 0};
1419 Py_ssize_t offset
= 0;
1422 PyStructObject
*soself
= (PyStructObject
*)self
;
1424 assert(PyStruct_Check(self
));
1425 assert(soself
->s_codes
!= NULL
);
1427 if (!PyArg_ParseTupleAndKeywords(args
, kwds
,
1428 "O|n:unpack_from", kwlist
,
1431 if (PyObject_GetBuffer(input
, &vbuf
, PyBUF_SIMPLE
) < 0)
1435 if (offset
< 0 || vbuf
.len
- offset
< soself
->s_size
) {
1436 PyErr_Format(StructError
,
1437 "unpack_from requires a buffer of at least %zd bytes",
1439 PyBuffer_Release(&vbuf
);
1442 result
= s_unpack_internal(soself
, (char*)vbuf
.buf
+ offset
);
1443 PyBuffer_Release(&vbuf
);
1449 * Guts of the pack function.
1451 * Takes a struct object, a tuple of arguments, and offset in that tuple of
1452 * argument for where to start processing the arguments for packing, and a
1453 * character buffer for writing the packed string. The caller must insure
1454 * that the buffer may contain the required length for packing the arguments.
1455 * 0 is returned on success, 1 is returned if there is an error.
1459 s_pack_internal(PyStructObject
*soself
, PyObject
*args
, int offset
, char* buf
)
1462 /* XXX(nnorwitz): why does i need to be a local? can we use
1463 the offset parameter or do we need the wider width? */
1466 memset(buf
, '\0', soself
->s_size
);
1468 for (code
= soself
->s_codes
; code
->fmtdef
!= NULL
; code
++) {
1470 PyObject
*v
= PyTuple_GET_ITEM(args
, i
++);
1471 const formatdef
*e
= code
->fmtdef
;
1472 char *res
= buf
+ code
->offset
;
1473 if (e
->format
== 's') {
1476 if (PyUnicode_Check(v
)) {
1477 v
= _PyUnicode_AsDefaultEncodedString(v
, NULL
);
1481 isstring
= PyBytes_Check(v
);
1482 if (!isstring
&& !PyByteArray_Check(v
)) {
1483 PyErr_SetString(StructError
,
1484 "argument for 's' must be a bytes or string");
1488 n
= PyBytes_GET_SIZE(v
);
1489 p
= PyBytes_AS_STRING(v
);
1492 n
= PyByteArray_GET_SIZE(v
);
1493 p
= PyByteArray_AS_STRING(v
);
1499 } else if (e
->format
== 'p') {
1502 if (PyUnicode_Check(v
)) {
1503 v
= _PyUnicode_AsDefaultEncodedString(v
, NULL
);
1507 isstring
= PyBytes_Check(v
);
1508 if (!isstring
&& !PyByteArray_Check(v
)) {
1509 PyErr_SetString(StructError
,
1510 "argument for 'p' must be a bytes or string");
1514 n
= PyBytes_GET_SIZE(v
);
1515 p
= PyBytes_AS_STRING(v
);
1518 n
= PyByteArray_GET_SIZE(v
);
1519 p
= PyByteArray_AS_STRING(v
);
1521 if (n
> (code
->size
- 1))
1524 memcpy(res
+ 1, p
, n
);
1527 *res
= Py_SAFE_DOWNCAST(n
, Py_ssize_t
, unsigned char);
1529 if (e
->pack(res
, v
, e
) < 0) {
1530 if (PyLong_Check(v
) && PyErr_ExceptionMatches(PyExc_OverflowError
))
1531 PyErr_SetString(StructError
,
1532 "long too large to convert to int");
1543 PyDoc_STRVAR(s_pack__doc__
,
1544 "S.pack(v1, v2, ...) -> bytes\n\
1546 Return a bytes containing values v1, v2, ... packed according to this\n\
1547 Struct's format. See struct.__doc__ for more on format strings.");
1550 s_pack(PyObject
*self
, PyObject
*args
)
1552 PyStructObject
*soself
;
1555 /* Validate arguments. */
1556 soself
= (PyStructObject
*)self
;
1557 assert(PyStruct_Check(self
));
1558 assert(soself
->s_codes
!= NULL
);
1559 if (PyTuple_GET_SIZE(args
) != soself
->s_len
)
1561 PyErr_Format(StructError
,
1562 "pack requires exactly %zd arguments", soself
->s_len
);
1566 /* Allocate a new string */
1567 result
= PyBytes_FromStringAndSize((char *)NULL
, soself
->s_size
);
1572 if ( s_pack_internal(soself
, args
, 0, PyBytes_AS_STRING(result
)) != 0 ) {
1580 PyDoc_STRVAR(s_pack_into__doc__
,
1581 "S.pack_into(buffer, offset, v1, v2, ...)\n\
1583 Pack the values v1, v2, ... according to this Struct's format, write \n\
1584 the packed bytes into the writable buffer buf starting at offset. Note\n\
1585 that the offset is not an optional argument. See struct.__doc__ for \n\
1586 more on format strings.");
1589 s_pack_into(PyObject
*self
, PyObject
*args
)
1591 PyStructObject
*soself
;
1593 Py_ssize_t buffer_len
, offset
;
1595 /* Validate arguments. +1 is for the first arg as buffer. */
1596 soself
= (PyStructObject
*)self
;
1597 assert(PyStruct_Check(self
));
1598 assert(soself
->s_codes
!= NULL
);
1599 if (PyTuple_GET_SIZE(args
) != (soself
->s_len
+ 2))
1601 PyErr_Format(StructError
,
1602 "pack_into requires exactly %zd arguments",
1603 (soself
->s_len
+ 2));
1607 /* Extract a writable memory buffer from the first argument */
1608 if ( PyObject_AsWriteBuffer(PyTuple_GET_ITEM(args
, 0),
1609 (void**)&buffer
, &buffer_len
) == -1 ) {
1612 assert( buffer_len
>= 0 );
1614 /* Extract the offset from the first argument */
1615 offset
= PyNumber_AsSsize_t(PyTuple_GET_ITEM(args
, 1), PyExc_IndexError
);
1616 if (offset
== -1 && PyErr_Occurred())
1619 /* Support negative offsets. */
1621 offset
+= buffer_len
;
1623 /* Check boundaries */
1624 if (offset
< 0 || (buffer_len
- offset
) < soself
->s_size
) {
1625 PyErr_Format(StructError
,
1626 "pack_into requires a buffer of at least %zd bytes",
1632 if ( s_pack_internal(soself
, args
, 2, buffer
+ offset
) != 0 ) {
1640 s_get_format(PyStructObject
*self
, void *unused
)
1642 Py_INCREF(self
->s_format
);
1643 return self
->s_format
;
1647 s_get_size(PyStructObject
*self
, void *unused
)
1649 return PyLong_FromSsize_t(self
->s_size
);
1652 /* List of functions */
1654 static struct PyMethodDef s_methods
[] = {
1655 {"pack", s_pack
, METH_VARARGS
, s_pack__doc__
},
1656 {"pack_into", s_pack_into
, METH_VARARGS
, s_pack_into__doc__
},
1657 {"unpack", s_unpack
, METH_O
, s_unpack__doc__
},
1658 {"unpack_from", (PyCFunction
)s_unpack_from
, METH_VARARGS
|METH_KEYWORDS
,
1659 s_unpack_from__doc__
},
1660 {NULL
, NULL
} /* sentinel */
1663 PyDoc_STRVAR(s__doc__
, "Compiled struct object");
1665 #define OFF(x) offsetof(PyStructObject, x)
1667 static PyGetSetDef s_getsetlist
[] = {
1668 {"format", (getter
)s_get_format
, (setter
)NULL
, "struct format string", NULL
},
1669 {"size", (getter
)s_get_size
, (setter
)NULL
, "struct size in bytes", NULL
},
1670 {NULL
} /* sentinel */
1674 PyTypeObject PyStructType
= {
1675 PyVarObject_HEAD_INIT(NULL
, 0)
1677 sizeof(PyStructObject
),
1679 (destructor
)s_dealloc
, /* tp_dealloc */
1683 0, /* tp_reserved */
1685 0, /* tp_as_number */
1686 0, /* tp_as_sequence */
1687 0, /* tp_as_mapping */
1691 PyObject_GenericGetAttr
, /* tp_getattro */
1692 PyObject_GenericSetAttr
, /* tp_setattro */
1693 0, /* tp_as_buffer */
1694 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
, /* tp_flags */
1695 s__doc__
, /* tp_doc */
1696 0, /* tp_traverse */
1698 0, /* tp_richcompare */
1699 offsetof(PyStructObject
, weakreflist
), /* tp_weaklistoffset */
1701 0, /* tp_iternext */
1702 s_methods
, /* tp_methods */
1703 NULL
, /* tp_members */
1704 s_getsetlist
, /* tp_getset */
1707 0, /* tp_descr_get */
1708 0, /* tp_descr_set */
1709 0, /* tp_dictoffset */
1710 s_init
, /* tp_init */
1711 PyType_GenericAlloc
,/* tp_alloc */
1713 PyObject_Del
, /* tp_free */
1717 /* ---- Standalone functions ---- */
1719 #define MAXCACHE 100
1720 static PyObject
*cache
= NULL
;
1723 cache_struct(PyObject
*fmt
)
1725 PyObject
* s_object
;
1727 if (cache
== NULL
) {
1728 cache
= PyDict_New();
1733 s_object
= PyDict_GetItem(cache
, fmt
);
1734 if (s_object
!= NULL
) {
1735 Py_INCREF(s_object
);
1739 s_object
= PyObject_CallFunctionObjArgs((PyObject
*)(&PyStructType
), fmt
, NULL
);
1740 if (s_object
!= NULL
) {
1741 if (PyDict_Size(cache
) >= MAXCACHE
)
1742 PyDict_Clear(cache
);
1743 /* Attempt to cache the result */
1744 if (PyDict_SetItem(cache
, fmt
, s_object
) == -1)
1750 PyDoc_STRVAR(clearcache_doc
,
1751 "Clear the internal cache.");
1754 clearcache(PyObject
*self
)
1760 PyDoc_STRVAR(calcsize_doc
,
1761 "Return size of C struct described by format string fmt.");
1764 calcsize(PyObject
*self
, PyObject
*fmt
)
1767 PyObject
*s_object
= cache_struct(fmt
);
1768 if (s_object
== NULL
)
1770 n
= ((PyStructObject
*)s_object
)->s_size
;
1771 Py_DECREF(s_object
);
1772 return PyLong_FromSsize_t(n
);
1775 PyDoc_STRVAR(pack_doc
,
1776 "Return bytes containing values v1, v2, ... packed according to fmt.");
1779 pack(PyObject
*self
, PyObject
*args
)
1781 PyObject
*s_object
, *fmt
, *newargs
, *result
;
1782 Py_ssize_t n
= PyTuple_GET_SIZE(args
);
1785 PyErr_SetString(PyExc_TypeError
, "missing format argument");
1788 fmt
= PyTuple_GET_ITEM(args
, 0);
1789 newargs
= PyTuple_GetSlice(args
, 1, n
);
1790 if (newargs
== NULL
)
1793 s_object
= cache_struct(fmt
);
1794 if (s_object
== NULL
) {
1798 result
= s_pack(s_object
, newargs
);
1800 Py_DECREF(s_object
);
1804 PyDoc_STRVAR(pack_into_doc
,
1805 "Pack the values v1, v2, ... according to fmt.\n\
1806 Write the packed bytes into the writable buffer buf starting at offset.");
1809 pack_into(PyObject
*self
, PyObject
*args
)
1811 PyObject
*s_object
, *fmt
, *newargs
, *result
;
1812 Py_ssize_t n
= PyTuple_GET_SIZE(args
);
1815 PyErr_SetString(PyExc_TypeError
, "missing format argument");
1818 fmt
= PyTuple_GET_ITEM(args
, 0);
1819 newargs
= PyTuple_GetSlice(args
, 1, n
);
1820 if (newargs
== NULL
)
1823 s_object
= cache_struct(fmt
);
1824 if (s_object
== NULL
) {
1828 result
= s_pack_into(s_object
, newargs
);
1830 Py_DECREF(s_object
);
1834 PyDoc_STRVAR(unpack_doc
,
1835 "Unpack the bytes containing packed C structure data, according to fmt.\n\
1836 Requires len(bytes) == calcsize(fmt).");
1839 unpack(PyObject
*self
, PyObject
*args
)
1841 PyObject
*s_object
, *fmt
, *inputstr
, *result
;
1843 if (!PyArg_UnpackTuple(args
, "unpack", 2, 2, &fmt
, &inputstr
))
1846 s_object
= cache_struct(fmt
);
1847 if (s_object
== NULL
)
1849 result
= s_unpack(s_object
, inputstr
);
1850 Py_DECREF(s_object
);
1854 PyDoc_STRVAR(unpack_from_doc
,
1855 "Unpack the buffer, containing packed C structure data, according to\n\
1856 fmt, starting at offset. Requires len(buffer[offset:]) >= calcsize(fmt).");
1859 unpack_from(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
1861 PyObject
*s_object
, *fmt
, *newargs
, *result
;
1862 Py_ssize_t n
= PyTuple_GET_SIZE(args
);
1865 PyErr_SetString(PyExc_TypeError
, "missing format argument");
1868 fmt
= PyTuple_GET_ITEM(args
, 0);
1869 newargs
= PyTuple_GetSlice(args
, 1, n
);
1870 if (newargs
== NULL
)
1873 s_object
= cache_struct(fmt
);
1874 if (s_object
== NULL
) {
1878 result
= s_unpack_from(s_object
, newargs
, kwds
);
1880 Py_DECREF(s_object
);
1884 static struct PyMethodDef module_functions
[] = {
1885 {"_clearcache", (PyCFunction
)clearcache
, METH_NOARGS
, clearcache_doc
},
1886 {"calcsize", calcsize
, METH_O
, calcsize_doc
},
1887 {"pack", pack
, METH_VARARGS
, pack_doc
},
1888 {"pack_into", pack_into
, METH_VARARGS
, pack_into_doc
},
1889 {"unpack", unpack
, METH_VARARGS
, unpack_doc
},
1890 {"unpack_from", (PyCFunction
)unpack_from
,
1891 METH_VARARGS
|METH_KEYWORDS
, unpack_from_doc
},
1892 {NULL
, NULL
} /* sentinel */
1896 /* Module initialization */
1898 PyDoc_STRVAR(module_doc
,
1899 "Functions to convert between Python values and C structs.\n\
1900 Python bytes objects are used to hold the data representing the C struct\n\
1901 and also as format strings to describe the layout of data in the C struct.\n\
1903 The optional first format char indicates byte order, size and alignment:\n\
1904 @: native order, size & alignment (default)\n\
1905 =: native order, std. size & alignment\n\
1906 <: little-endian, std. size & alignment\n\
1907 >: big-endian, std. size & alignment\n\
1910 The remaining chars indicate types of args and must match exactly;\n\
1911 these can be preceded by a decimal repeat count:\n\
1912 x: pad byte (no data); c:char; b:signed byte; B:unsigned byte;\n\
1913 h:short; H:unsigned short; i:int; I:unsigned int;\n\
1914 l:long; L:unsigned long; f:float; d:double.\n\
1915 Special cases (preceding decimal count indicates length):\n\
1916 s:string (array of char); p: pascal string (with count byte).\n\
1917 Special case (only available in native format):\n\
1918 P:an integer type that is wide enough to hold a pointer.\n\
1919 Special case (not in native mode unless 'long long' in platform C):\n\
1920 q:long long; Q:unsigned long long\n\
1921 Whitespace between formats is ignored.\n\
1923 The variable struct.error is an exception raised on errors.\n");
1926 static struct PyModuleDef _structmodule
= {
1927 PyModuleDef_HEAD_INIT
,
1939 PyInit__struct(void)
1943 ver
= PyBytes_FromString("0.3");
1947 m
= PyModule_Create(&_structmodule
);
1951 Py_TYPE(&PyStructType
) = &PyType_Type
;
1952 if (PyType_Ready(&PyStructType
) < 0)
1955 /* Check endian and swap in faster functions */
1958 formatdef
*native
= native_table
;
1959 formatdef
*other
, *ptr
;
1960 if ((int)*(unsigned char*)&one
)
1961 other
= lilendian_table
;
1963 other
= bigendian_table
;
1964 /* Scan through the native table, find a matching
1965 entry in the endian table and swap in the
1966 native implementations whenever possible
1967 (64-bit platforms may not have "standard" sizes) */
1968 while (native
->format
!= '\0' && other
->format
!= '\0') {
1970 while (ptr
->format
!= '\0') {
1971 if (ptr
->format
== native
->format
) {
1972 /* Match faster when formats are
1973 listed in the same order */
1976 /* Only use the trick if the
1978 if (ptr
->size
!= native
->size
)
1980 /* Skip float and double, could be
1981 "unknown" float format */
1982 if (ptr
->format
== 'd' || ptr
->format
== 'f')
1984 ptr
->pack
= native
->pack
;
1985 ptr
->unpack
= native
->unpack
;
1994 /* Add some symbolic constants to the module */
1995 if (StructError
== NULL
) {
1996 StructError
= PyErr_NewException("struct.error", NULL
, NULL
);
1997 if (StructError
== NULL
)
2001 Py_INCREF(StructError
);
2002 PyModule_AddObject(m
, "error", StructError
);
2004 Py_INCREF((PyObject
*)&PyStructType
);
2005 PyModule_AddObject(m
, "Struct", (PyObject
*)&PyStructType
);
2007 PyModule_AddObject(m
, "__version__", ver
);