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
187 get_ulong(PyObject
*v
, unsigned long *p
)
189 if (PyLong_Check(v
)) {
190 unsigned long x
= PyLong_AsUnsignedLong(v
);
191 if (x
== (unsigned long)(-1) && PyErr_Occurred())
196 if (get_long(v
, (long *)p
) < 0)
198 if (((long)*p
) < 0) {
199 PyErr_SetString(StructError
,
200 "unsigned argument is < 0");
205 #endif /* PY_STRUCT_OVERFLOW_MASKING */
207 #ifdef HAVE_LONG_LONG
209 /* Same, but handling native long long. */
212 get_longlong(PyObject
*v
, PY_LONG_LONG
*p
)
219 assert(PyLong_Check(v
));
220 x
= PyLong_AsLongLong(v
);
222 if (x
== (PY_LONG_LONG
)-1 && PyErr_Occurred())
228 /* Same, but handling native unsigned long long. */
231 get_ulonglong(PyObject
*v
, unsigned PY_LONG_LONG
*p
)
233 unsigned PY_LONG_LONG x
;
238 assert(PyLong_Check(v
));
239 x
= PyLong_AsUnsignedLongLong(v
);
241 if (x
== (unsigned PY_LONG_LONG
)-1 && PyErr_Occurred())
249 #ifdef PY_STRUCT_OVERFLOW_MASKING
251 /* Helper routine to get a Python integer and raise the appropriate error
254 #define INT_OVERFLOW "struct integer overflow masking is deprecated"
257 get_wrapped_long(PyObject
*v
, long *p
)
259 if (get_long(v
, p
) < 0) {
260 if (PyLong_Check(v
) &&
261 PyErr_ExceptionMatches(PyExc_OverflowError
)) {
265 #ifdef PY_STRUCT_FLOAT_COERCE
266 if (PyFloat_Check(v
)) {
270 if (PyErr_WarnEx(PyExc_DeprecationWarning
, FLOAT_COERCE
, 2) < 0)
275 res
= get_wrapped_long(o
, p
);
280 if (PyErr_WarnEx(PyExc_DeprecationWarning
, INT_OVERFLOW
, 2) < 0)
282 wrapped
= PyNumber_And(v
, pylong_ulong_mask
);
285 x
= (long)PyLong_AsUnsignedLong(wrapped
);
287 if (x
== -1 && PyErr_Occurred())
298 get_wrapped_ulong(PyObject
*v
, unsigned long *p
)
300 long x
= (long)PyLong_AsUnsignedLong(v
);
301 if (x
== -1 && PyErr_Occurred()) {
304 #ifdef PY_STRUCT_FLOAT_COERCE
305 if (PyFloat_Check(v
)) {
309 if (PyErr_WarnEx(PyExc_DeprecationWarning
, FLOAT_COERCE
, 2) < 0)
314 res
= get_wrapped_ulong(o
, p
);
319 wrapped
= PyNumber_And(v
, pylong_ulong_mask
);
322 if (PyErr_WarnEx(PyExc_DeprecationWarning
, INT_OVERFLOW
, 2) < 0) {
326 x
= (long)PyLong_AsUnsignedLong(wrapped
);
328 if (x
== -1 && PyErr_Occurred())
331 *p
= (unsigned long)x
;
335 #define RANGE_ERROR(x, f, flag, mask) \
337 if (_range_error(f, flag) < 0) \
345 #define get_wrapped_long get_long
346 #define get_wrapped_ulong get_ulong
347 #define RANGE_ERROR(x, f, flag, mask) return _range_error(f, flag)
351 /* Floating point helpers */
354 unpack_float(const char *p
, /* start of 4-byte string */
355 int le
) /* true for little-endian, false for big-endian */
359 x
= _PyFloat_Unpack4((unsigned char *)p
, le
);
360 if (x
== -1.0 && PyErr_Occurred())
362 return PyFloat_FromDouble(x
);
366 unpack_double(const char *p
, /* start of 8-byte string */
367 int le
) /* true for little-endian, false for big-endian */
371 x
= _PyFloat_Unpack8((unsigned char *)p
, le
);
372 if (x
== -1.0 && PyErr_Occurred())
374 return PyFloat_FromDouble(x
);
377 /* Helper to format the range error exceptions */
379 _range_error(const formatdef
*f
, int is_unsigned
)
381 /* ulargest is the largest unsigned value with f->size bytes.
382 * Note that the simpler:
383 * ((size_t)1 << (f->size * 8)) - 1
384 * doesn't work when f->size == sizeof(size_t) because C doesn't
385 * define what happens when a left shift count is >= the number of
386 * bits in the integer being shifted; e.g., on some boxes it doesn't
387 * shift at all when they're equal.
389 const size_t ulargest
= (size_t)-1 >> ((SIZEOF_SIZE_T
- f
->size
)*8);
390 assert(f
->size
>= 1 && f
->size
<= SIZEOF_SIZE_T
);
392 PyErr_Format(StructError
,
393 "'%c' format requires 0 <= number <= %zu",
397 const Py_ssize_t largest
= (Py_ssize_t
)(ulargest
>> 1);
398 PyErr_Format(StructError
,
399 "'%c' format requires %zd <= number <= %zd",
404 #ifdef PY_STRUCT_OVERFLOW_MASKING
406 PyObject
*ptype
, *pvalue
, *ptraceback
;
409 PyErr_Fetch(&ptype
, &pvalue
, &ptraceback
);
410 assert(pvalue
!= NULL
);
411 msg
= PyObject_Str(pvalue
);
414 Py_XDECREF(ptraceback
);
417 rval
= PyErr_WarnEx(PyExc_DeprecationWarning
,
418 PyString_AS_STRING(msg
), 2);
429 /* A large number of small routines follow, with names of the form
433 [bln] distiguishes among big-endian, little-endian and native.
434 [pu] distiguishes between pack (to struct) and unpack (from struct).
435 TYPE is one of char, byte, ubyte, etc.
438 /* Native mode routines. ****************************************************/
440 In all n[up]_<type> routines handling types larger than 1 byte, there is
441 *no* guarantee that the p pointer is properly aligned for each type,
442 therefore memcpy is called. An intermediate variable is used to
443 compensate for big-endian architectures.
444 Normally both the intermediate variable and the memcpy call will be
445 skipped by C optimisation in little-endian architectures (gcc >= 2.91
449 nu_char(const char *p
, const formatdef
*f
)
451 return PyString_FromStringAndSize(p
, 1);
455 nu_byte(const char *p
, const formatdef
*f
)
457 return PyInt_FromLong((long) *(signed char *)p
);
461 nu_ubyte(const char *p
, const formatdef
*f
)
463 return PyInt_FromLong((long) *(unsigned char *)p
);
467 nu_short(const char *p
, const formatdef
*f
)
470 memcpy((char *)&x
, p
, sizeof x
);
471 return PyInt_FromLong((long)x
);
475 nu_ushort(const char *p
, const formatdef
*f
)
478 memcpy((char *)&x
, p
, sizeof x
);
479 return PyInt_FromLong((long)x
);
483 nu_int(const char *p
, const formatdef
*f
)
486 memcpy((char *)&x
, p
, sizeof x
);
487 return PyInt_FromLong((long)x
);
491 nu_uint(const char *p
, const formatdef
*f
)
494 memcpy((char *)&x
, p
, sizeof x
);
495 #if (SIZEOF_LONG > SIZEOF_INT)
496 return PyInt_FromLong((long)x
);
498 if (x
<= ((unsigned int)LONG_MAX
))
499 return PyInt_FromLong((long)x
);
500 return PyLong_FromUnsignedLong((unsigned long)x
);
505 nu_long(const char *p
, const formatdef
*f
)
508 memcpy((char *)&x
, p
, sizeof x
);
509 return PyInt_FromLong(x
);
513 nu_ulong(const char *p
, const formatdef
*f
)
516 memcpy((char *)&x
, p
, sizeof x
);
518 return PyInt_FromLong((long)x
);
519 return PyLong_FromUnsignedLong(x
);
522 /* Native mode doesn't support q or Q unless the platform C supports
523 long long (or, on Windows, __int64). */
525 #ifdef HAVE_LONG_LONG
528 nu_longlong(const char *p
, const formatdef
*f
)
531 memcpy((char *)&x
, p
, sizeof x
);
532 if (x
>= LONG_MIN
&& x
<= LONG_MAX
)
533 return PyInt_FromLong(Py_SAFE_DOWNCAST(x
, PY_LONG_LONG
, long));
534 return PyLong_FromLongLong(x
);
538 nu_ulonglong(const char *p
, const formatdef
*f
)
540 unsigned PY_LONG_LONG x
;
541 memcpy((char *)&x
, p
, sizeof x
);
543 return PyInt_FromLong(Py_SAFE_DOWNCAST(x
, unsigned PY_LONG_LONG
, long));
544 return PyLong_FromUnsignedLongLong(x
);
550 nu_bool(const char *p
, const formatdef
*f
)
553 memcpy((char *)&x
, p
, sizeof x
);
554 return PyBool_FromLong(x
!= 0);
559 nu_float(const char *p
, const formatdef
*f
)
562 memcpy((char *)&x
, p
, sizeof x
);
563 return PyFloat_FromDouble((double)x
);
567 nu_double(const char *p
, const formatdef
*f
)
570 memcpy((char *)&x
, p
, sizeof x
);
571 return PyFloat_FromDouble(x
);
575 nu_void_p(const char *p
, const formatdef
*f
)
578 memcpy((char *)&x
, p
, sizeof x
);
579 return PyLong_FromVoidPtr(x
);
583 np_byte(char *p
, PyObject
*v
, const formatdef
*f
)
586 if (get_long(v
, &x
) < 0)
588 if (x
< -128 || x
> 127){
589 PyErr_SetString(StructError
,
590 "byte format requires -128 <= number <= 127");
598 np_ubyte(char *p
, PyObject
*v
, const formatdef
*f
)
601 if (get_long(v
, &x
) < 0)
603 if (x
< 0 || x
> 255){
604 PyErr_SetString(StructError
,
605 "ubyte format requires 0 <= number <= 255");
613 np_char(char *p
, PyObject
*v
, const formatdef
*f
)
615 if (!PyString_Check(v
) || PyString_Size(v
) != 1) {
616 PyErr_SetString(StructError
,
617 "char format require string of length 1");
620 *p
= *PyString_AsString(v
);
625 np_short(char *p
, PyObject
*v
, const formatdef
*f
)
629 if (get_long(v
, &x
) < 0)
631 if (x
< SHRT_MIN
|| x
> SHRT_MAX
){
632 PyErr_SetString(StructError
,
633 "short format requires " STRINGIFY(SHRT_MIN
)
634 " <= number <= " STRINGIFY(SHRT_MAX
));
638 memcpy(p
, (char *)&y
, sizeof y
);
643 np_ushort(char *p
, PyObject
*v
, const formatdef
*f
)
647 if (get_long(v
, &x
) < 0)
649 if (x
< 0 || x
> USHRT_MAX
){
650 PyErr_SetString(StructError
,
651 "short format requires 0 <= number <= " STRINGIFY(USHRT_MAX
));
654 y
= (unsigned short)x
;
655 memcpy(p
, (char *)&y
, sizeof y
);
660 np_int(char *p
, PyObject
*v
, const formatdef
*f
)
664 if (get_long(v
, &x
) < 0)
666 #if (SIZEOF_LONG > SIZEOF_INT)
667 if ((x
< ((long)INT_MIN
)) || (x
> ((long)INT_MAX
)))
668 RANGE_ERROR(x
, f
, 0, -1);
671 memcpy(p
, (char *)&y
, sizeof y
);
676 np_uint(char *p
, PyObject
*v
, const formatdef
*f
)
680 if (get_wrapped_ulong(v
, &x
) < 0)
683 #if (SIZEOF_LONG > SIZEOF_INT)
684 if (x
> ((unsigned long)UINT_MAX
))
685 RANGE_ERROR(y
, f
, 1, -1);
687 memcpy(p
, (char *)&y
, sizeof y
);
692 np_long(char *p
, PyObject
*v
, const formatdef
*f
)
695 if (get_long(v
, &x
) < 0)
697 memcpy(p
, (char *)&x
, sizeof x
);
702 np_ulong(char *p
, PyObject
*v
, const formatdef
*f
)
705 if (get_wrapped_ulong(v
, &x
) < 0)
707 memcpy(p
, (char *)&x
, sizeof x
);
711 #ifdef HAVE_LONG_LONG
714 np_longlong(char *p
, PyObject
*v
, const formatdef
*f
)
717 if (get_longlong(v
, &x
) < 0)
719 memcpy(p
, (char *)&x
, sizeof x
);
724 np_ulonglong(char *p
, PyObject
*v
, const formatdef
*f
)
726 unsigned PY_LONG_LONG x
;
727 if (get_ulonglong(v
, &x
) < 0)
729 memcpy(p
, (char *)&x
, sizeof x
);
736 np_bool(char *p
, PyObject
*v
, const formatdef
*f
)
739 y
= PyObject_IsTrue(v
);
740 memcpy(p
, (char *)&y
, sizeof y
);
745 np_float(char *p
, PyObject
*v
, const formatdef
*f
)
747 float x
= (float)PyFloat_AsDouble(v
);
748 if (x
== -1 && PyErr_Occurred()) {
749 PyErr_SetString(StructError
,
750 "required argument is not a float");
753 memcpy(p
, (char *)&x
, sizeof x
);
758 np_double(char *p
, PyObject
*v
, const formatdef
*f
)
760 double x
= PyFloat_AsDouble(v
);
761 if (x
== -1 && PyErr_Occurred()) {
762 PyErr_SetString(StructError
,
763 "required argument is not a float");
766 memcpy(p
, (char *)&x
, sizeof(double));
771 np_void_p(char *p
, PyObject
*v
, const formatdef
*f
)
778 assert(PyLong_Check(v
));
779 x
= PyLong_AsVoidPtr(v
);
781 if (x
== NULL
&& PyErr_Occurred())
783 memcpy(p
, (char *)&x
, sizeof x
);
787 static formatdef native_table
[] = {
788 {'x', sizeof(char), 0, NULL
},
789 {'b', sizeof(char), 0, nu_byte
, np_byte
},
790 {'B', sizeof(char), 0, nu_ubyte
, np_ubyte
},
791 {'c', sizeof(char), 0, nu_char
, np_char
},
792 {'s', sizeof(char), 0, NULL
},
793 {'p', sizeof(char), 0, NULL
},
794 {'h', sizeof(short), SHORT_ALIGN
, nu_short
, np_short
},
795 {'H', sizeof(short), SHORT_ALIGN
, nu_ushort
, np_ushort
},
796 {'i', sizeof(int), INT_ALIGN
, nu_int
, np_int
},
797 {'I', sizeof(int), INT_ALIGN
, nu_uint
, np_uint
},
798 {'l', sizeof(long), LONG_ALIGN
, nu_long
, np_long
},
799 {'L', sizeof(long), LONG_ALIGN
, nu_ulong
, np_ulong
},
800 #ifdef HAVE_LONG_LONG
801 {'q', sizeof(PY_LONG_LONG
), LONG_LONG_ALIGN
, nu_longlong
, np_longlong
},
802 {'Q', sizeof(PY_LONG_LONG
), LONG_LONG_ALIGN
, nu_ulonglong
,np_ulonglong
},
804 {'?', sizeof(BOOL_TYPE
), BOOL_ALIGN
, nu_bool
, np_bool
},
805 {'f', sizeof(float), FLOAT_ALIGN
, nu_float
, np_float
},
806 {'d', sizeof(double), DOUBLE_ALIGN
, nu_double
, np_double
},
807 {'P', sizeof(void *), VOID_P_ALIGN
, nu_void_p
, np_void_p
},
811 /* Big-endian routines. *****************************************************/
814 bu_int(const char *p
, const formatdef
*f
)
817 Py_ssize_t i
= f
->size
;
818 const unsigned char *bytes
= (const unsigned char *)p
;
820 x
= (x
<<8) | *bytes
++;
822 /* Extend the sign bit. */
823 if (SIZEOF_LONG
> f
->size
)
824 x
|= -(x
& (1L << ((8 * f
->size
) - 1)));
825 return PyInt_FromLong(x
);
829 bu_uint(const char *p
, const formatdef
*f
)
832 Py_ssize_t i
= f
->size
;
833 const unsigned char *bytes
= (const unsigned char *)p
;
835 x
= (x
<<8) | *bytes
++;
838 return PyInt_FromLong((long)x
);
839 return PyLong_FromUnsignedLong(x
);
843 bu_longlong(const char *p
, const formatdef
*f
)
845 #ifdef HAVE_LONG_LONG
847 Py_ssize_t i
= f
->size
;
848 const unsigned char *bytes
= (const unsigned char *)p
;
850 x
= (x
<<8) | *bytes
++;
852 /* Extend the sign bit. */
853 if (SIZEOF_LONG_LONG
> f
->size
)
854 x
|= -(x
& ((PY_LONG_LONG
)1 << ((8 * f
->size
) - 1)));
855 if (x
>= LONG_MIN
&& x
<= LONG_MAX
)
856 return PyInt_FromLong(Py_SAFE_DOWNCAST(x
, PY_LONG_LONG
, long));
857 return PyLong_FromLongLong(x
);
859 return _PyLong_FromByteArray((const unsigned char *)p
,
861 0, /* little-endian */
867 bu_ulonglong(const char *p
, const formatdef
*f
)
869 #ifdef HAVE_LONG_LONG
870 unsigned PY_LONG_LONG x
= 0;
871 Py_ssize_t i
= f
->size
;
872 const unsigned char *bytes
= (const unsigned char *)p
;
874 x
= (x
<<8) | *bytes
++;
877 return PyInt_FromLong(Py_SAFE_DOWNCAST(x
, unsigned PY_LONG_LONG
, long));
878 return PyLong_FromUnsignedLongLong(x
);
880 return _PyLong_FromByteArray((const unsigned char *)p
,
882 0, /* little-endian */
888 bu_float(const char *p
, const formatdef
*f
)
890 return unpack_float(p
, 0);
894 bu_double(const char *p
, const formatdef
*f
)
896 return unpack_double(p
, 0);
900 bu_bool(const char *p
, const formatdef
*f
)
903 memcpy((char *)&x
, p
, sizeof x
);
904 return PyBool_FromLong(x
!= 0);
908 bp_int(char *p
, PyObject
*v
, const formatdef
*f
)
912 if (get_wrapped_long(v
, &x
) < 0)
915 if (i
!= SIZEOF_LONG
) {
916 if ((i
== 2) && (x
< -32768 || x
> 32767))
917 RANGE_ERROR(x
, f
, 0, 0xffffL
);
918 #if (SIZEOF_LONG != 4)
919 else if ((i
== 4) && (x
< -2147483648L || x
> 2147483647L))
920 RANGE_ERROR(x
, f
, 0, 0xffffffffL
);
922 #ifdef PY_STRUCT_OVERFLOW_MASKING
923 else if ((i
== 1) && (x
< -128 || x
> 127))
924 RANGE_ERROR(x
, f
, 0, 0xffL
);
935 bp_uint(char *p
, PyObject
*v
, const formatdef
*f
)
939 if (get_wrapped_ulong(v
, &x
) < 0)
942 if (i
!= SIZEOF_LONG
) {
943 unsigned long maxint
= 1;
944 maxint
<<= (unsigned long)(i
* 8);
946 RANGE_ERROR(x
, f
, 1, maxint
- 1);
956 bp_longlong(char *p
, PyObject
*v
, const formatdef
*f
)
962 res
= _PyLong_AsByteArray((PyLongObject
*)v
,
965 0, /* little_endian */
972 bp_ulonglong(char *p
, PyObject
*v
, const formatdef
*f
)
978 res
= _PyLong_AsByteArray((PyLongObject
*)v
,
981 0, /* little_endian */
988 bp_float(char *p
, PyObject
*v
, const formatdef
*f
)
990 double x
= PyFloat_AsDouble(v
);
991 if (x
== -1 && PyErr_Occurred()) {
992 PyErr_SetString(StructError
,
993 "required argument is not a float");
996 return _PyFloat_Pack4(x
, (unsigned char *)p
, 0);
1000 bp_double(char *p
, PyObject
*v
, const formatdef
*f
)
1002 double x
= PyFloat_AsDouble(v
);
1003 if (x
== -1 && PyErr_Occurred()) {
1004 PyErr_SetString(StructError
,
1005 "required argument is not a float");
1008 return _PyFloat_Pack8(x
, (unsigned char *)p
, 0);
1012 bp_bool(char *p
, PyObject
*v
, const formatdef
*f
)
1015 y
= PyObject_IsTrue(v
);
1016 memcpy(p
, (char *)&y
, sizeof y
);
1020 static formatdef bigendian_table
[] = {
1022 #ifdef PY_STRUCT_OVERFLOW_MASKING
1023 /* Native packers do range checking without overflow masking. */
1024 {'b', 1, 0, nu_byte
, bp_int
},
1025 {'B', 1, 0, nu_ubyte
, bp_uint
},
1027 {'b', 1, 0, nu_byte
, np_byte
},
1028 {'B', 1, 0, nu_ubyte
, np_ubyte
},
1030 {'c', 1, 0, nu_char
, np_char
},
1033 {'h', 2, 0, bu_int
, bp_int
},
1034 {'H', 2, 0, bu_uint
, bp_uint
},
1035 {'i', 4, 0, bu_int
, bp_int
},
1036 {'I', 4, 0, bu_uint
, bp_uint
},
1037 {'l', 4, 0, bu_int
, bp_int
},
1038 {'L', 4, 0, bu_uint
, bp_uint
},
1039 {'q', 8, 0, bu_longlong
, bp_longlong
},
1040 {'Q', 8, 0, bu_ulonglong
, bp_ulonglong
},
1041 {'?', 1, 0, bu_bool
, bp_bool
},
1042 {'f', 4, 0, bu_float
, bp_float
},
1043 {'d', 8, 0, bu_double
, bp_double
},
1047 /* Little-endian routines. *****************************************************/
1050 lu_int(const char *p
, const formatdef
*f
)
1053 Py_ssize_t i
= f
->size
;
1054 const unsigned char *bytes
= (const unsigned char *)p
;
1056 x
= (x
<<8) | bytes
[--i
];
1058 /* Extend the sign bit. */
1059 if (SIZEOF_LONG
> f
->size
)
1060 x
|= -(x
& (1L << ((8 * f
->size
) - 1)));
1061 return PyInt_FromLong(x
);
1065 lu_uint(const char *p
, const formatdef
*f
)
1067 unsigned long x
= 0;
1068 Py_ssize_t i
= f
->size
;
1069 const unsigned char *bytes
= (const unsigned char *)p
;
1071 x
= (x
<<8) | bytes
[--i
];
1074 return PyInt_FromLong((long)x
);
1075 return PyLong_FromUnsignedLong((long)x
);
1079 lu_longlong(const char *p
, const formatdef
*f
)
1081 #ifdef HAVE_LONG_LONG
1083 Py_ssize_t i
= f
->size
;
1084 const unsigned char *bytes
= (const unsigned char *)p
;
1086 x
= (x
<<8) | bytes
[--i
];
1088 /* Extend the sign bit. */
1089 if (SIZEOF_LONG_LONG
> f
->size
)
1090 x
|= -(x
& ((PY_LONG_LONG
)1 << ((8 * f
->size
) - 1)));
1091 if (x
>= LONG_MIN
&& x
<= LONG_MAX
)
1092 return PyInt_FromLong(Py_SAFE_DOWNCAST(x
, PY_LONG_LONG
, long));
1093 return PyLong_FromLongLong(x
);
1095 return _PyLong_FromByteArray((const unsigned char *)p
,
1097 1, /* little-endian */
1103 lu_ulonglong(const char *p
, const formatdef
*f
)
1105 #ifdef HAVE_LONG_LONG
1106 unsigned PY_LONG_LONG x
= 0;
1107 Py_ssize_t i
= f
->size
;
1108 const unsigned char *bytes
= (const unsigned char *)p
;
1110 x
= (x
<<8) | bytes
[--i
];
1113 return PyInt_FromLong(Py_SAFE_DOWNCAST(x
, unsigned PY_LONG_LONG
, long));
1114 return PyLong_FromUnsignedLongLong(x
);
1116 return _PyLong_FromByteArray((const unsigned char *)p
,
1118 1, /* little-endian */
1124 lu_float(const char *p
, const formatdef
*f
)
1126 return unpack_float(p
, 1);
1130 lu_double(const char *p
, const formatdef
*f
)
1132 return unpack_double(p
, 1);
1136 lp_int(char *p
, PyObject
*v
, const formatdef
*f
)
1140 if (get_wrapped_long(v
, &x
) < 0)
1143 if (i
!= SIZEOF_LONG
) {
1144 if ((i
== 2) && (x
< -32768 || x
> 32767))
1145 RANGE_ERROR(x
, f
, 0, 0xffffL
);
1146 #if (SIZEOF_LONG != 4)
1147 else if ((i
== 4) && (x
< -2147483648L || x
> 2147483647L))
1148 RANGE_ERROR(x
, f
, 0, 0xffffffffL
);
1150 #ifdef PY_STRUCT_OVERFLOW_MASKING
1151 else if ((i
== 1) && (x
< -128 || x
> 127))
1152 RANGE_ERROR(x
, f
, 0, 0xffL
);
1163 lp_uint(char *p
, PyObject
*v
, const formatdef
*f
)
1167 if (get_wrapped_ulong(v
, &x
) < 0)
1170 if (i
!= SIZEOF_LONG
) {
1171 unsigned long maxint
= 1;
1172 maxint
<<= (unsigned long)(i
* 8);
1174 RANGE_ERROR(x
, f
, 1, maxint
- 1);
1184 lp_longlong(char *p
, PyObject
*v
, const formatdef
*f
)
1190 res
= _PyLong_AsByteArray((PyLongObject
*)v
,
1193 1, /* little_endian */
1200 lp_ulonglong(char *p
, PyObject
*v
, const formatdef
*f
)
1206 res
= _PyLong_AsByteArray((PyLongObject
*)v
,
1209 1, /* little_endian */
1216 lp_float(char *p
, PyObject
*v
, const formatdef
*f
)
1218 double x
= PyFloat_AsDouble(v
);
1219 if (x
== -1 && PyErr_Occurred()) {
1220 PyErr_SetString(StructError
,
1221 "required argument is not a float");
1224 return _PyFloat_Pack4(x
, (unsigned char *)p
, 1);
1228 lp_double(char *p
, PyObject
*v
, const formatdef
*f
)
1230 double x
= PyFloat_AsDouble(v
);
1231 if (x
== -1 && PyErr_Occurred()) {
1232 PyErr_SetString(StructError
,
1233 "required argument is not a float");
1236 return _PyFloat_Pack8(x
, (unsigned char *)p
, 1);
1239 static formatdef lilendian_table
[] = {
1241 #ifdef PY_STRUCT_OVERFLOW_MASKING
1242 /* Native packers do range checking without overflow masking. */
1243 {'b', 1, 0, nu_byte
, lp_int
},
1244 {'B', 1, 0, nu_ubyte
, lp_uint
},
1246 {'b', 1, 0, nu_byte
, np_byte
},
1247 {'B', 1, 0, nu_ubyte
, np_ubyte
},
1249 {'c', 1, 0, nu_char
, np_char
},
1252 {'h', 2, 0, lu_int
, lp_int
},
1253 {'H', 2, 0, lu_uint
, lp_uint
},
1254 {'i', 4, 0, lu_int
, lp_int
},
1255 {'I', 4, 0, lu_uint
, lp_uint
},
1256 {'l', 4, 0, lu_int
, lp_int
},
1257 {'L', 4, 0, lu_uint
, lp_uint
},
1258 {'q', 8, 0, lu_longlong
, lp_longlong
},
1259 {'Q', 8, 0, lu_ulonglong
, lp_ulonglong
},
1260 {'?', 1, 0, bu_bool
, bp_bool
}, /* Std rep not endian dep,
1261 but potentially different from native rep -- reuse bx_bool funcs. */
1262 {'f', 4, 0, lu_float
, lp_float
},
1263 {'d', 8, 0, lu_double
, lp_double
},
1268 static const formatdef
*
1269 whichtable(char **pfmt
)
1271 const char *fmt
= (*pfmt
)++; /* May be backed out of later */
1274 return lilendian_table
;
1276 case '!': /* Network byte order is big-endian */
1277 return bigendian_table
;
1278 case '=': { /* Host byte order -- different from native in aligment! */
1280 char *p
= (char *) &n
;
1282 return lilendian_table
;
1284 return bigendian_table
;
1287 --*pfmt
; /* Back out of pointer increment */
1290 return native_table
;
1295 /* Get the table entry for a format code */
1297 static const formatdef
*
1298 getentry(int c
, const formatdef
*f
)
1300 for (; f
->format
!= '\0'; f
++) {
1301 if (f
->format
== c
) {
1305 PyErr_SetString(StructError
, "bad char in struct format");
1310 /* Align a size according to a format code */
1313 align(Py_ssize_t size
, char c
, const formatdef
*e
)
1315 if (e
->format
== c
) {
1317 size
= ((size
+ e
->alignment
- 1)
1326 /* calculate the size of a format string */
1329 prepare_s(PyStructObject
*self
)
1338 Py_ssize_t size
, len
, num
, itemsize
, x
;
1340 fmt
= PyString_AS_STRING(self
->s_format
);
1342 f
= whichtable((char **)&fmt
);
1347 while ((c
= *s
++) != '\0') {
1348 if (isspace(Py_CHARMASK(c
)))
1350 if ('0' <= c
&& c
<= '9') {
1352 while ('0' <= (c
= *s
++) && c
<= '9') {
1353 x
= num
*10 + (c
- '0');
1357 "overflow in item count");
1373 case 's': /* fall through */
1374 case 'p': len
++; break;
1376 default: len
+= num
; break;
1380 size
= align(size
, c
, e
);
1383 if (x
/itemsize
!= num
|| size
< 0) {
1384 PyErr_SetString(StructError
,
1385 "total struct size too long");
1390 /* check for overflow */
1391 if ((len
+ 1) > (PY_SSIZE_T_MAX
/ sizeof(formatcode
))) {
1396 self
->s_size
= size
;
1398 codes
= PyMem_MALLOC((len
+ 1) * sizeof(formatcode
));
1399 if (codes
== NULL
) {
1403 self
->s_codes
= codes
;
1407 while ((c
= *s
++) != '\0') {
1408 if (isspace(Py_CHARMASK(c
)))
1410 if ('0' <= c
&& c
<= '9') {
1412 while ('0' <= (c
= *s
++) && c
<= '9')
1413 num
= num
*10 + (c
- '0');
1422 size
= align(size
, c
, e
);
1423 if (c
== 's' || c
== 'p') {
1424 codes
->offset
= size
;
1429 } else if (c
== 'x') {
1432 while (--num
>= 0) {
1433 codes
->offset
= size
;
1434 codes
->size
= e
->size
;
1441 codes
->fmtdef
= NULL
;
1442 codes
->offset
= size
;
1449 s_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
1453 assert(type
!= NULL
&& type
->tp_alloc
!= NULL
);
1455 self
= type
->tp_alloc(type
, 0);
1457 PyStructObject
*s
= (PyStructObject
*)self
;
1459 s
->s_format
= Py_None
;
1468 s_init(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
1470 PyStructObject
*soself
= (PyStructObject
*)self
;
1471 PyObject
*o_format
= NULL
;
1473 static char *kwlist
[] = {"format", 0};
1475 assert(PyStruct_Check(self
));
1477 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "S:Struct", kwlist
,
1481 Py_INCREF(o_format
);
1482 Py_CLEAR(soself
->s_format
);
1483 soself
->s_format
= o_format
;
1485 ret
= prepare_s(soself
);
1490 s_dealloc(PyStructObject
*s
)
1492 if (s
->weakreflist
!= NULL
)
1493 PyObject_ClearWeakRefs((PyObject
*)s
);
1494 if (s
->s_codes
!= NULL
) {
1495 PyMem_FREE(s
->s_codes
);
1497 Py_XDECREF(s
->s_format
);
1498 Py_TYPE(s
)->tp_free((PyObject
*)s
);
1502 s_unpack_internal(PyStructObject
*soself
, char *startfrom
) {
1505 PyObject
*result
= PyTuple_New(soself
->s_len
);
1509 for (code
= soself
->s_codes
; code
->fmtdef
!= NULL
; code
++) {
1511 const formatdef
*e
= code
->fmtdef
;
1512 const char *res
= startfrom
+ code
->offset
;
1513 if (e
->format
== 's') {
1514 v
= PyString_FromStringAndSize(res
, code
->size
);
1515 } else if (e
->format
== 'p') {
1516 Py_ssize_t n
= *(unsigned char*)res
;
1517 if (n
>= code
->size
)
1519 v
= PyString_FromStringAndSize(res
+ 1, n
);
1521 v
= e
->unpack(res
, e
);
1525 PyTuple_SET_ITEM(result
, i
++, v
);
1535 PyDoc_STRVAR(s_unpack__doc__
,
1536 "S.unpack(str) -> (v1, v2, ...)\n\
1538 Return tuple containing values unpacked according to this Struct's format.\n\
1539 Requires len(str) == self.size. See struct.__doc__ for more on format\n\
1543 s_unpack(PyObject
*self
, PyObject
*inputstr
)
1547 PyObject
*args
=NULL
, *result
;
1548 PyStructObject
*soself
= (PyStructObject
*)self
;
1549 assert(PyStruct_Check(self
));
1550 assert(soself
->s_codes
!= NULL
);
1551 if (inputstr
== NULL
)
1553 if (PyString_Check(inputstr
) &&
1554 PyString_GET_SIZE(inputstr
) == soself
->s_size
) {
1555 return s_unpack_internal(soself
, PyString_AS_STRING(inputstr
));
1557 args
= PyTuple_Pack(1, inputstr
);
1560 if (!PyArg_ParseTuple(args
, "s#:unpack", &start
, &len
))
1562 if (soself
->s_size
!= len
)
1564 result
= s_unpack_internal(soself
, start
);
1570 PyErr_Format(StructError
,
1571 "unpack requires a string argument of length %zd",
1576 PyDoc_STRVAR(s_unpack_from__doc__
,
1577 "S.unpack_from(buffer[, offset]) -> (v1, v2, ...)\n\
1579 Return tuple containing values unpacked according to this Struct's format.\n\
1580 Unlike unpack, unpack_from can unpack values from any object supporting\n\
1581 the buffer API, not just str. Requires len(buffer[offset:]) >= self.size.\n\
1582 See struct.__doc__ for more on format strings.");
1585 s_unpack_from(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
1587 static char *kwlist
[] = {"buffer", "offset", 0};
1588 #if (PY_VERSION_HEX < 0x02050000)
1589 static char *fmt
= "z#|i:unpack_from";
1591 static char *fmt
= "z#|n:unpack_from";
1593 Py_ssize_t buffer_len
= 0, offset
= 0;
1594 char *buffer
= NULL
;
1595 PyStructObject
*soself
= (PyStructObject
*)self
;
1596 assert(PyStruct_Check(self
));
1597 assert(soself
->s_codes
!= NULL
);
1599 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, fmt
, kwlist
,
1600 &buffer
, &buffer_len
, &offset
))
1603 if (buffer
== NULL
) {
1604 PyErr_Format(StructError
,
1605 "unpack_from requires a buffer argument");
1610 offset
+= buffer_len
;
1612 if (offset
< 0 || (buffer_len
- offset
) < soself
->s_size
) {
1613 PyErr_Format(StructError
,
1614 "unpack_from requires a buffer of at least %zd bytes",
1618 return s_unpack_internal(soself
, buffer
+ offset
);
1623 * Guts of the pack function.
1625 * Takes a struct object, a tuple of arguments, and offset in that tuple of
1626 * argument for where to start processing the arguments for packing, and a
1627 * character buffer for writing the packed string. The caller must insure
1628 * that the buffer may contain the required length for packing the arguments.
1629 * 0 is returned on success, 1 is returned if there is an error.
1633 s_pack_internal(PyStructObject
*soself
, PyObject
*args
, int offset
, char* buf
)
1636 /* XXX(nnorwitz): why does i need to be a local? can we use
1637 the offset parameter or do we need the wider width? */
1640 memset(buf
, '\0', soself
->s_size
);
1642 for (code
= soself
->s_codes
; code
->fmtdef
!= NULL
; code
++) {
1644 PyObject
*v
= PyTuple_GET_ITEM(args
, i
++);
1645 const formatdef
*e
= code
->fmtdef
;
1646 char *res
= buf
+ code
->offset
;
1647 if (e
->format
== 's') {
1648 if (!PyString_Check(v
)) {
1649 PyErr_SetString(StructError
,
1650 "argument for 's' must be a string");
1653 n
= PyString_GET_SIZE(v
);
1657 memcpy(res
, PyString_AS_STRING(v
), n
);
1658 } else if (e
->format
== 'p') {
1659 if (!PyString_Check(v
)) {
1660 PyErr_SetString(StructError
,
1661 "argument for 'p' must be a string");
1664 n
= PyString_GET_SIZE(v
);
1665 if (n
> (code
->size
- 1))
1668 memcpy(res
+ 1, PyString_AS_STRING(v
), n
);
1671 *res
= Py_SAFE_DOWNCAST(n
, Py_ssize_t
, unsigned char);
1673 if (e
->pack(res
, v
, e
) < 0) {
1674 if (PyLong_Check(v
) && PyErr_ExceptionMatches(PyExc_OverflowError
))
1675 PyErr_SetString(StructError
,
1676 "long too large to convert to int");
1687 PyDoc_STRVAR(s_pack__doc__
,
1688 "S.pack(v1, v2, ...) -> string\n\
1690 Return a string containing values v1, v2, ... packed according to this\n\
1691 Struct's format. See struct.__doc__ for more on format strings.");
1694 s_pack(PyObject
*self
, PyObject
*args
)
1696 PyStructObject
*soself
;
1699 /* Validate arguments. */
1700 soself
= (PyStructObject
*)self
;
1701 assert(PyStruct_Check(self
));
1702 assert(soself
->s_codes
!= NULL
);
1703 if (PyTuple_GET_SIZE(args
) != soself
->s_len
)
1705 PyErr_Format(StructError
,
1706 "pack requires exactly %zd arguments", soself
->s_len
);
1710 /* Allocate a new string */
1711 result
= PyString_FromStringAndSize((char *)NULL
, soself
->s_size
);
1716 if ( s_pack_internal(soself
, args
, 0, PyString_AS_STRING(result
)) != 0 ) {
1724 PyDoc_STRVAR(s_pack_into__doc__
,
1725 "S.pack_into(buffer, offset, v1, v2, ...)\n\
1727 Pack the values v1, v2, ... according to this Struct's format, write \n\
1728 the packed bytes into the writable buffer buf starting at offset. Note\n\
1729 that the offset is not an optional argument. See struct.__doc__ for \n\
1730 more on format strings.");
1733 s_pack_into(PyObject
*self
, PyObject
*args
)
1735 PyStructObject
*soself
;
1737 Py_ssize_t buffer_len
, offset
;
1739 /* Validate arguments. +1 is for the first arg as buffer. */
1740 soself
= (PyStructObject
*)self
;
1741 assert(PyStruct_Check(self
));
1742 assert(soself
->s_codes
!= NULL
);
1743 if (PyTuple_GET_SIZE(args
) != (soself
->s_len
+ 2))
1745 PyErr_Format(StructError
,
1746 "pack_into requires exactly %zd arguments",
1747 (soself
->s_len
+ 2));
1751 /* Extract a writable memory buffer from the first argument */
1752 if ( PyObject_AsWriteBuffer(PyTuple_GET_ITEM(args
, 0),
1753 (void**)&buffer
, &buffer_len
) == -1 ) {
1756 assert( buffer_len
>= 0 );
1758 /* Extract the offset from the first argument */
1759 offset
= PyInt_AsSsize_t(PyTuple_GET_ITEM(args
, 1));
1760 if (offset
== -1 && PyErr_Occurred())
1763 /* Support negative offsets. */
1765 offset
+= buffer_len
;
1767 /* Check boundaries */
1768 if (offset
< 0 || (buffer_len
- offset
) < soself
->s_size
) {
1769 PyErr_Format(StructError
,
1770 "pack_into requires a buffer of at least %zd bytes",
1776 if ( s_pack_internal(soself
, args
, 2, buffer
+ offset
) != 0 ) {
1784 s_get_format(PyStructObject
*self
, void *unused
)
1786 Py_INCREF(self
->s_format
);
1787 return self
->s_format
;
1791 s_get_size(PyStructObject
*self
, void *unused
)
1793 return PyInt_FromSsize_t(self
->s_size
);
1796 /* List of functions */
1798 static struct PyMethodDef s_methods
[] = {
1799 {"pack", s_pack
, METH_VARARGS
, s_pack__doc__
},
1800 {"pack_into", s_pack_into
, METH_VARARGS
, s_pack_into__doc__
},
1801 {"unpack", s_unpack
, METH_O
, s_unpack__doc__
},
1802 {"unpack_from", (PyCFunction
)s_unpack_from
, METH_VARARGS
|METH_KEYWORDS
,
1803 s_unpack_from__doc__
},
1804 {NULL
, NULL
} /* sentinel */
1807 PyDoc_STRVAR(s__doc__
, "Compiled struct object");
1809 #define OFF(x) offsetof(PyStructObject, x)
1811 static PyGetSetDef s_getsetlist
[] = {
1812 {"format", (getter
)s_get_format
, (setter
)NULL
, "struct format string", NULL
},
1813 {"size", (getter
)s_get_size
, (setter
)NULL
, "struct size in bytes", NULL
},
1814 {NULL
} /* sentinel */
1818 PyTypeObject PyStructType
= {
1819 PyVarObject_HEAD_INIT(NULL
, 0)
1821 sizeof(PyStructObject
),
1823 (destructor
)s_dealloc
, /* tp_dealloc */
1829 0, /* tp_as_number */
1830 0, /* tp_as_sequence */
1831 0, /* tp_as_mapping */
1835 PyObject_GenericGetAttr
, /* tp_getattro */
1836 PyObject_GenericSetAttr
, /* tp_setattro */
1837 0, /* tp_as_buffer */
1838 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
| Py_TPFLAGS_HAVE_WEAKREFS
,/* tp_flags */
1839 s__doc__
, /* tp_doc */
1840 0, /* tp_traverse */
1842 0, /* tp_richcompare */
1843 offsetof(PyStructObject
, weakreflist
), /* tp_weaklistoffset */
1845 0, /* tp_iternext */
1846 s_methods
, /* tp_methods */
1847 NULL
, /* tp_members */
1848 s_getsetlist
, /* tp_getset */
1851 0, /* tp_descr_get */
1852 0, /* tp_descr_set */
1853 0, /* tp_dictoffset */
1854 s_init
, /* tp_init */
1855 PyType_GenericAlloc
,/* tp_alloc */
1857 PyObject_Del
, /* tp_free */
1861 /* ---- Standalone functions ---- */
1863 #define MAXCACHE 100
1864 static PyObject
*cache
= NULL
;
1867 cache_struct(PyObject
*fmt
)
1869 PyObject
* s_object
;
1871 if (cache
== NULL
) {
1872 cache
= PyDict_New();
1877 s_object
= PyDict_GetItem(cache
, fmt
);
1878 if (s_object
!= NULL
) {
1879 Py_INCREF(s_object
);
1883 s_object
= PyObject_CallFunctionObjArgs((PyObject
*)(&PyStructType
), fmt
, NULL
);
1884 if (s_object
!= NULL
) {
1885 if (PyDict_Size(cache
) >= MAXCACHE
)
1886 PyDict_Clear(cache
);
1887 /* Attempt to cache the result */
1888 if (PyDict_SetItem(cache
, fmt
, s_object
) == -1)
1894 PyDoc_STRVAR(clearcache_doc
,
1895 "Clear the internal cache.");
1898 clearcache(PyObject
*self
)
1904 PyDoc_STRVAR(calcsize_doc
,
1905 "Return size of C struct described by format string fmt.");
1908 calcsize(PyObject
*self
, PyObject
*fmt
)
1911 PyObject
*s_object
= cache_struct(fmt
);
1912 if (s_object
== NULL
)
1914 n
= ((PyStructObject
*)s_object
)->s_size
;
1915 Py_DECREF(s_object
);
1916 return PyInt_FromSsize_t(n
);
1919 PyDoc_STRVAR(pack_doc
,
1920 "Return string containing values v1, v2, ... packed according to fmt.");
1923 pack(PyObject
*self
, PyObject
*args
)
1925 PyObject
*s_object
, *fmt
, *newargs
, *result
;
1926 Py_ssize_t n
= PyTuple_GET_SIZE(args
);
1929 PyErr_SetString(PyExc_TypeError
, "missing format argument");
1932 fmt
= PyTuple_GET_ITEM(args
, 0);
1933 newargs
= PyTuple_GetSlice(args
, 1, n
);
1934 if (newargs
== NULL
)
1937 s_object
= cache_struct(fmt
);
1938 if (s_object
== NULL
) {
1942 result
= s_pack(s_object
, newargs
);
1944 Py_DECREF(s_object
);
1948 PyDoc_STRVAR(pack_into_doc
,
1949 "Pack the values v1, v2, ... according to fmt.\n\
1950 Write the packed bytes into the writable buffer buf starting at offset.");
1953 pack_into(PyObject
*self
, PyObject
*args
)
1955 PyObject
*s_object
, *fmt
, *newargs
, *result
;
1956 Py_ssize_t n
= PyTuple_GET_SIZE(args
);
1959 PyErr_SetString(PyExc_TypeError
, "missing format argument");
1962 fmt
= PyTuple_GET_ITEM(args
, 0);
1963 newargs
= PyTuple_GetSlice(args
, 1, n
);
1964 if (newargs
== NULL
)
1967 s_object
= cache_struct(fmt
);
1968 if (s_object
== NULL
) {
1972 result
= s_pack_into(s_object
, newargs
);
1974 Py_DECREF(s_object
);
1978 PyDoc_STRVAR(unpack_doc
,
1979 "Unpack the string containing packed C structure data, according to fmt.\n\
1980 Requires len(string) == calcsize(fmt).");
1983 unpack(PyObject
*self
, PyObject
*args
)
1985 PyObject
*s_object
, *fmt
, *inputstr
, *result
;
1987 if (!PyArg_UnpackTuple(args
, "unpack", 2, 2, &fmt
, &inputstr
))
1990 s_object
= cache_struct(fmt
);
1991 if (s_object
== NULL
)
1993 result
= s_unpack(s_object
, inputstr
);
1994 Py_DECREF(s_object
);
1998 PyDoc_STRVAR(unpack_from_doc
,
1999 "Unpack the buffer, containing packed C structure data, according to\n\
2000 fmt, starting at offset. Requires len(buffer[offset:]) >= calcsize(fmt).");
2003 unpack_from(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
2005 PyObject
*s_object
, *fmt
, *newargs
, *result
;
2006 Py_ssize_t n
= PyTuple_GET_SIZE(args
);
2009 PyErr_SetString(PyExc_TypeError
, "missing format argument");
2012 fmt
= PyTuple_GET_ITEM(args
, 0);
2013 newargs
= PyTuple_GetSlice(args
, 1, n
);
2014 if (newargs
== NULL
)
2017 s_object
= cache_struct(fmt
);
2018 if (s_object
== NULL
) {
2022 result
= s_unpack_from(s_object
, newargs
, kwds
);
2024 Py_DECREF(s_object
);
2028 static struct PyMethodDef module_functions
[] = {
2029 {"_clearcache", (PyCFunction
)clearcache
, METH_NOARGS
, clearcache_doc
},
2030 {"calcsize", calcsize
, METH_O
, calcsize_doc
},
2031 {"pack", pack
, METH_VARARGS
, pack_doc
},
2032 {"pack_into", pack_into
, METH_VARARGS
, pack_into_doc
},
2033 {"unpack", unpack
, METH_VARARGS
, unpack_doc
},
2034 {"unpack_from", (PyCFunction
)unpack_from
,
2035 METH_VARARGS
|METH_KEYWORDS
, unpack_from_doc
},
2036 {NULL
, NULL
} /* sentinel */
2040 /* Module initialization */
2042 PyDoc_STRVAR(module_doc
,
2043 "Functions to convert between Python values and C structs.\n\
2044 Python strings are used to hold the data representing the C struct\n\
2045 and also as format strings to describe the layout of data in the C struct.\n\
2047 The optional first format char indicates byte order, size and alignment:\n\
2048 @: native order, size & alignment (default)\n\
2049 =: native order, std. size & alignment\n\
2050 <: little-endian, std. size & alignment\n\
2051 >: big-endian, std. size & alignment\n\
2054 The remaining chars indicate types of args and must match exactly;\n\
2055 these can be preceded by a decimal repeat count:\n\
2056 x: pad byte (no data); c:char; b:signed byte; B:unsigned byte;\n\
2057 h:short; H:unsigned short; i:int; I:unsigned int;\n\
2058 l:long; L:unsigned long; f:float; d:double.\n\
2059 Special cases (preceding decimal count indicates length):\n\
2060 s:string (array of char); p: pascal string (with count byte).\n\
2061 Special case (only available in native format):\n\
2062 P:an integer type that is wide enough to hold a pointer.\n\
2063 Special case (not in native mode unless 'long long' in platform C):\n\
2064 q:long long; Q:unsigned long long\n\
2065 Whitespace between formats is ignored.\n\
2067 The variable struct.error is an exception raised on errors.\n");
2074 ver
= PyString_FromString("0.2");
2078 m
= Py_InitModule3("_struct", module_functions
, module_doc
);
2082 Py_TYPE(&PyStructType
) = &PyType_Type
;
2083 if (PyType_Ready(&PyStructType
) < 0)
2086 #ifdef PY_STRUCT_OVERFLOW_MASKING
2087 if (pyint_zero
== NULL
) {
2088 pyint_zero
= PyInt_FromLong(0);
2089 if (pyint_zero
== NULL
)
2092 if (pylong_ulong_mask
== NULL
) {
2093 #if (SIZEOF_LONG == 4)
2094 pylong_ulong_mask
= PyLong_FromString("FFFFFFFF", NULL
, 16);
2096 pylong_ulong_mask
= PyLong_FromString("FFFFFFFFFFFFFFFF", NULL
, 16);
2098 if (pylong_ulong_mask
== NULL
)
2103 /* This speed trick can't be used until overflow masking goes away, because
2104 native endian always raises exceptions instead of overflow masking. */
2106 /* Check endian and swap in faster functions */
2109 formatdef
*native
= native_table
;
2110 formatdef
*other
, *ptr
;
2111 if ((int)*(unsigned char*)&one
)
2112 other
= lilendian_table
;
2114 other
= bigendian_table
;
2115 /* Scan through the native table, find a matching
2116 entry in the endian table and swap in the
2117 native implementations whenever possible
2118 (64-bit platforms may not have "standard" sizes) */
2119 while (native
->format
!= '\0' && other
->format
!= '\0') {
2121 while (ptr
->format
!= '\0') {
2122 if (ptr
->format
== native
->format
) {
2123 /* Match faster when formats are
2124 listed in the same order */
2127 /* Only use the trick if the
2129 if (ptr
->size
!= native
->size
)
2131 /* Skip float and double, could be
2132 "unknown" float format */
2133 if (ptr
->format
== 'd' || ptr
->format
== 'f')
2135 ptr
->pack
= native
->pack
;
2136 ptr
->unpack
= native
->unpack
;
2146 /* Add some symbolic constants to the module */
2147 if (StructError
== NULL
) {
2148 StructError
= PyErr_NewException("struct.error", NULL
, NULL
);
2149 if (StructError
== NULL
)
2153 Py_INCREF(StructError
);
2154 PyModule_AddObject(m
, "error", StructError
);
2156 Py_INCREF((PyObject
*)&PyStructType
);
2157 PyModule_AddObject(m
, "Struct", (PyObject
*)&PyStructType
);
2159 PyModule_AddObject(m
, "__version__", ver
);
2161 PyModule_AddIntConstant(m
, "_PY_STRUCT_RANGE_CHECKING", 1);
2162 #ifdef PY_STRUCT_OVERFLOW_MASKING
2163 PyModule_AddIntConstant(m
, "_PY_STRUCT_OVERFLOW_MASKING", 1);
2165 #ifdef PY_STRUCT_FLOAT_COERCE
2166 PyModule_AddIntConstant(m
, "_PY_STRUCT_FLOAT_COERCE", 1);