blob: 838e4e46058a56a738d6554404333101ae81cb32 [file] [log] [blame]
Bob Ippolito232f3c92006-05-23 19:12:41 +00001/* struct module -- pack values into and (out of) strings */
2
3/* New version supporting byte order, alignment and size options,
4 character strings, and unsigned numbers */
5
6#include "Python.h"
7#include "structseq.h"
8#include "structmember.h"
9#include <ctype.h>
10
11
12/* compatibility macros */
13#if (PY_VERSION_HEX < 0x02050000)
14typedef int Py_ssize_t;
15#endif
16
17
18
19/* The translation function for each format character is table driven */
20
21typedef struct _formatdef {
22 char format;
23 int size;
24 int alignment;
25 PyObject* (*unpack)(const char *,
26 const struct _formatdef *);
27 int (*pack)(char *, PyObject *,
28 const struct _formatdef *);
29} formatdef;
30
31typedef struct _formatcode {
32 const struct _formatdef *fmtdef;
33 int offset;
34 int repeat;
35} formatcode;
36
37/* Struct object interface */
38
39typedef struct {
40 PyObject_HEAD
41 int s_size;
42 int s_len;
43 formatcode *s_codes;
44 PyObject *s_format;
45 PyObject *weakreflist; /* List of weak references */
46} PyStructObject;
47
48PyAPI_DATA(PyTypeObject) PyStruct_Type;
49
50#define PyStruct_Check(op) PyObject_TypeCheck(op, &PyStruct_Type)
51#define PyStruct_CheckExact(op) ((op)->ob_type == &PyStruct_Type)
52
53
54/* Exception */
55
56static PyObject *StructError;
57
58
59/* Define various structs to figure out the alignments of types */
60
61
62typedef struct { char c; short x; } st_short;
63typedef struct { char c; int x; } st_int;
64typedef struct { char c; long x; } st_long;
65typedef struct { char c; float x; } st_float;
66typedef struct { char c; double x; } st_double;
67typedef struct { char c; void *x; } st_void_p;
68
69#define SHORT_ALIGN (sizeof(st_short) - sizeof(short))
70#define INT_ALIGN (sizeof(st_int) - sizeof(int))
71#define LONG_ALIGN (sizeof(st_long) - sizeof(long))
72#define FLOAT_ALIGN (sizeof(st_float) - sizeof(float))
73#define DOUBLE_ALIGN (sizeof(st_double) - sizeof(double))
74#define VOID_P_ALIGN (sizeof(st_void_p) - sizeof(void *))
75
76/* We can't support q and Q in native mode unless the compiler does;
77 in std mode, they're 8 bytes on all platforms. */
78#ifdef HAVE_LONG_LONG
79typedef struct { char c; PY_LONG_LONG x; } s_long_long;
80#define LONG_LONG_ALIGN (sizeof(s_long_long) - sizeof(PY_LONG_LONG))
81#endif
82
83#define STRINGIFY(x) #x
84
85#ifdef __powerc
86#pragma options align=reset
87#endif
88
89/* Helper to get a PyLongObject by hook or by crook. Caller should decref. */
90
91static PyObject *
92get_pylong(PyObject *v)
93{
94 PyNumberMethods *m;
95
96 assert(v != NULL);
97 if (PyInt_Check(v))
98 return PyLong_FromLong(PyInt_AS_LONG(v));
99 if (PyLong_Check(v)) {
100 Py_INCREF(v);
101 return v;
102 }
103 m = v->ob_type->tp_as_number;
104 if (m != NULL && m->nb_long != NULL) {
105 v = m->nb_long(v);
106 if (v == NULL)
107 return NULL;
108 if (PyLong_Check(v))
109 return v;
110 Py_DECREF(v);
111 }
112 PyErr_SetString(StructError,
113 "cannot convert argument to long");
114 return NULL;
115}
116
117/* Helper routine to get a Python integer and raise the appropriate error
118 if it isn't one */
119
120static int
121get_long(PyObject *v, long *p)
122{
123 long x = PyInt_AsLong(v);
124 if (x == -1 && PyErr_Occurred()) {
125 if (PyErr_ExceptionMatches(PyExc_TypeError))
126 PyErr_SetString(StructError,
127 "required argument is not an integer");
128 return -1;
129 }
130 *p = x;
131 return 0;
132}
133
134
135/* Same, but handling unsigned long */
136
137static int
138get_ulong(PyObject *v, unsigned long *p)
139{
140 if (PyLong_Check(v)) {
141 unsigned long x = PyLong_AsUnsignedLong(v);
142 if (x == (unsigned long)(-1) && PyErr_Occurred())
143 return -1;
144 *p = x;
145 return 0;
146 }
147 else {
148 return get_long(v, (long *)p);
149 }
150}
151
152#ifdef HAVE_LONG_LONG
153
154/* Same, but handling native long long. */
155
156static int
157get_longlong(PyObject *v, PY_LONG_LONG *p)
158{
159 PY_LONG_LONG x;
160
161 v = get_pylong(v);
162 if (v == NULL)
163 return -1;
164 assert(PyLong_Check(v));
165 x = PyLong_AsLongLong(v);
166 Py_DECREF(v);
167 if (x == (PY_LONG_LONG)-1 && PyErr_Occurred())
168 return -1;
169 *p = x;
170 return 0;
171}
172
173/* Same, but handling native unsigned long long. */
174
175static int
176get_ulonglong(PyObject *v, unsigned PY_LONG_LONG *p)
177{
178 unsigned PY_LONG_LONG x;
179
180 v = get_pylong(v);
181 if (v == NULL)
182 return -1;
183 assert(PyLong_Check(v));
184 x = PyLong_AsUnsignedLongLong(v);
185 Py_DECREF(v);
186 if (x == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred())
187 return -1;
188 *p = x;
189 return 0;
190}
191
192#endif
193
194/* Floating point helpers */
195
196static PyObject *
197unpack_float(const char *p, /* start of 4-byte string */
198 int le) /* true for little-endian, false for big-endian */
199{
200 double x;
201
202 x = _PyFloat_Unpack4((unsigned char *)p, le);
203 if (x == -1.0 && PyErr_Occurred())
204 return NULL;
205 return PyFloat_FromDouble(x);
206}
207
208static PyObject *
209unpack_double(const char *p, /* start of 8-byte string */
210 int le) /* true for little-endian, false for big-endian */
211{
212 double x;
213
214 x = _PyFloat_Unpack8((unsigned char *)p, le);
215 if (x == -1.0 && PyErr_Occurred())
216 return NULL;
217 return PyFloat_FromDouble(x);
218}
219
220
221/* A large number of small routines follow, with names of the form
222
223 [bln][up]_TYPE
224
225 [bln] distiguishes among big-endian, little-endian and native.
226 [pu] distiguishes between pack (to struct) and unpack (from struct).
227 TYPE is one of char, byte, ubyte, etc.
228*/
229
230/* Native mode routines. ****************************************************/
231/* NOTE:
232 In all n[up]_<type> routines handling types larger than 1 byte, there is
233 *no* guarantee that the p pointer is properly aligned for each type,
234 therefore memcpy is called. An intermediate variable is used to
235 compensate for big-endian architectures.
236 Normally both the intermediate variable and the memcpy call will be
237 skipped by C optimisation in little-endian architectures (gcc >= 2.91
238 does this). */
239
240static PyObject *
241nu_char(const char *p, const formatdef *f)
242{
243 return PyString_FromStringAndSize(p, 1);
244}
245
246static PyObject *
247nu_byte(const char *p, const formatdef *f)
248{
249 return PyInt_FromLong((long) *(signed char *)p);
250}
251
252static PyObject *
253nu_ubyte(const char *p, const formatdef *f)
254{
255 return PyInt_FromLong((long) *(unsigned char *)p);
256}
257
258static PyObject *
259nu_short(const char *p, const formatdef *f)
260{
261 short x;
262 memcpy((char *)&x, p, sizeof x);
263 return PyInt_FromLong((long)x);
264}
265
266static PyObject *
267nu_ushort(const char *p, const formatdef *f)
268{
269 unsigned short x;
270 memcpy((char *)&x, p, sizeof x);
271 return PyInt_FromLong((long)x);
272}
273
274static PyObject *
275nu_int(const char *p, const formatdef *f)
276{
277 int x;
278 memcpy((char *)&x, p, sizeof x);
279 return PyInt_FromLong((long)x);
280}
281
282static PyObject *
283nu_uint(const char *p, const formatdef *f)
284{
285 unsigned int x;
286 memcpy((char *)&x, p, sizeof x);
287 return PyLong_FromUnsignedLong((unsigned long)x);
288}
289
290static PyObject *
291nu_long(const char *p, const formatdef *f)
292{
293 long x;
294 memcpy((char *)&x, p, sizeof x);
295 return PyInt_FromLong(x);
296}
297
298static PyObject *
299nu_ulong(const char *p, const formatdef *f)
300{
301 unsigned long x;
302 memcpy((char *)&x, p, sizeof x);
303 return PyLong_FromUnsignedLong(x);
304}
305
306/* Native mode doesn't support q or Q unless the platform C supports
307 long long (or, on Windows, __int64). */
308
309#ifdef HAVE_LONG_LONG
310
311static PyObject *
312nu_longlong(const char *p, const formatdef *f)
313{
314 PY_LONG_LONG x;
315 memcpy((char *)&x, p, sizeof x);
316 return PyLong_FromLongLong(x);
317}
318
319static PyObject *
320nu_ulonglong(const char *p, const formatdef *f)
321{
322 unsigned PY_LONG_LONG x;
323 memcpy((char *)&x, p, sizeof x);
324 return PyLong_FromUnsignedLongLong(x);
325}
326
327#endif
328
329static PyObject *
330nu_float(const char *p, const formatdef *f)
331{
332 float x;
333 memcpy((char *)&x, p, sizeof x);
334 return PyFloat_FromDouble((double)x);
335}
336
337static PyObject *
338nu_double(const char *p, const formatdef *f)
339{
340 double x;
341 memcpy((char *)&x, p, sizeof x);
342 return PyFloat_FromDouble(x);
343}
344
345static PyObject *
346nu_void_p(const char *p, const formatdef *f)
347{
348 void *x;
349 memcpy((char *)&x, p, sizeof x);
350 return PyLong_FromVoidPtr(x);
351}
352
353static int
354np_byte(char *p, PyObject *v, const formatdef *f)
355{
356 long x;
357 if (get_long(v, &x) < 0)
358 return -1;
359 if (x < -128 || x > 127){
360 PyErr_SetString(StructError,
361 "byte format requires -128<=number<=127");
362 return -1;
363 }
364 *p = (char)x;
365 return 0;
366}
367
368static int
369np_ubyte(char *p, PyObject *v, const formatdef *f)
370{
371 long x;
372 if (get_long(v, &x) < 0)
373 return -1;
374 if (x < 0 || x > 255){
375 PyErr_SetString(StructError,
376 "ubyte format requires 0<=number<=255");
377 return -1;
378 }
379 *p = (char)x;
380 return 0;
381}
382
383static int
384np_char(char *p, PyObject *v, const formatdef *f)
385{
386 if (!PyString_Check(v) || PyString_Size(v) != 1) {
387 PyErr_SetString(StructError,
388 "char format require string of length 1");
389 return -1;
390 }
391 *p = *PyString_AsString(v);
392 return 0;
393}
394
395static int
396np_short(char *p, PyObject *v, const formatdef *f)
397{
398 long x;
399 short y;
400 if (get_long(v, &x) < 0)
401 return -1;
402 if (x < SHRT_MIN || x > SHRT_MAX){
403 PyErr_SetString(StructError,
404 "short format requires " STRINGIFY(SHRT_MIN)
405 "<=number<=" STRINGIFY(SHRT_MAX));
406 return -1;
407 }
408 y = (short)x;
409 memcpy(p, (char *)&y, sizeof y);
410 return 0;
411}
412
413static int
414np_ushort(char *p, PyObject *v, const formatdef *f)
415{
416 long x;
417 unsigned short y;
418 if (get_long(v, &x) < 0)
419 return -1;
420 if (x < 0 || x > USHRT_MAX){
421 PyErr_SetString(StructError,
422 "short format requires 0<=number<=" STRINGIFY(USHRT_MAX));
423 return -1;
424 }
425 y = (unsigned short)x;
426 memcpy(p, (char *)&y, sizeof y);
427 return 0;
428}
429
430static int
431np_int(char *p, PyObject *v, const formatdef *f)
432{
433 long x;
434 int y;
435 if (get_long(v, &x) < 0)
436 return -1;
437 y = (int)x;
438 memcpy(p, (char *)&y, sizeof y);
439 return 0;
440}
441
442static int
443np_uint(char *p, PyObject *v, const formatdef *f)
444{
445 unsigned long x;
446 unsigned int y;
447 if (get_ulong(v, &x) < 0)
448 return -1;
449 y = (unsigned int)x;
450 memcpy(p, (char *)&y, sizeof y);
451 return 0;
452}
453
454static int
455np_long(char *p, PyObject *v, const formatdef *f)
456{
457 long x;
458 if (get_long(v, &x) < 0)
459 return -1;
460 memcpy(p, (char *)&x, sizeof x);
461 return 0;
462}
463
464static int
465np_ulong(char *p, PyObject *v, const formatdef *f)
466{
467 unsigned long x;
468 if (get_ulong(v, &x) < 0)
469 return -1;
470 memcpy(p, (char *)&x, sizeof x);
471 return 0;
472}
473
474#ifdef HAVE_LONG_LONG
475
476static int
477np_longlong(char *p, PyObject *v, const formatdef *f)
478{
479 PY_LONG_LONG x;
480 if (get_longlong(v, &x) < 0)
481 return -1;
482 memcpy(p, (char *)&x, sizeof x);
483 return 0;
484}
485
486static int
487np_ulonglong(char *p, PyObject *v, const formatdef *f)
488{
489 unsigned PY_LONG_LONG x;
490 if (get_ulonglong(v, &x) < 0)
491 return -1;
492 memcpy(p, (char *)&x, sizeof x);
493 return 0;
494}
495#endif
496
497static int
498np_float(char *p, PyObject *v, const formatdef *f)
499{
500 float x = (float)PyFloat_AsDouble(v);
501 if (x == -1 && PyErr_Occurred()) {
502 PyErr_SetString(StructError,
503 "required argument is not a float");
504 return -1;
505 }
506 memcpy(p, (char *)&x, sizeof x);
507 return 0;
508}
509
510static int
511np_double(char *p, PyObject *v, const formatdef *f)
512{
513 double x = PyFloat_AsDouble(v);
514 if (x == -1 && PyErr_Occurred()) {
515 PyErr_SetString(StructError,
516 "required argument is not a float");
517 return -1;
518 }
519 memcpy(p, (char *)&x, sizeof(double));
520 return 0;
521}
522
523static int
524np_void_p(char *p, PyObject *v, const formatdef *f)
525{
526 void *x;
527
528 v = get_pylong(v);
529 if (v == NULL)
530 return -1;
531 assert(PyLong_Check(v));
532 x = PyLong_AsVoidPtr(v);
533 Py_DECREF(v);
534 if (x == NULL && PyErr_Occurred())
535 return -1;
536 memcpy(p, (char *)&x, sizeof x);
537 return 0;
538}
539
540static formatdef native_table[] = {
541 {'x', sizeof(char), 0, NULL},
542 {'b', sizeof(char), 0, nu_byte, np_byte},
543 {'B', sizeof(char), 0, nu_ubyte, np_ubyte},
544 {'c', sizeof(char), 0, nu_char, np_char},
545 {'s', sizeof(char), 0, NULL},
546 {'p', sizeof(char), 0, NULL},
547 {'h', sizeof(short), SHORT_ALIGN, nu_short, np_short},
548 {'H', sizeof(short), SHORT_ALIGN, nu_ushort, np_ushort},
549 {'i', sizeof(int), INT_ALIGN, nu_int, np_int},
550 {'I', sizeof(int), INT_ALIGN, nu_uint, np_uint},
551 {'l', sizeof(long), LONG_ALIGN, nu_long, np_long},
552 {'L', sizeof(long), LONG_ALIGN, nu_ulong, np_ulong},
553 {'f', sizeof(float), FLOAT_ALIGN, nu_float, np_float},
554 {'d', sizeof(double), DOUBLE_ALIGN, nu_double, np_double},
555 {'P', sizeof(void *), VOID_P_ALIGN, nu_void_p, np_void_p},
556#ifdef HAVE_LONG_LONG
557 {'q', sizeof(PY_LONG_LONG), LONG_LONG_ALIGN, nu_longlong, np_longlong},
558 {'Q', sizeof(PY_LONG_LONG), LONG_LONG_ALIGN, nu_ulonglong,np_ulonglong},
559#endif
560 {0}
561};
562
563/* Big-endian routines. *****************************************************/
564
565static PyObject *
566bu_int(const char *p, const formatdef *f)
567{
568 long x = 0;
569 int i = f->size;
570 do {
571 x = (x<<8) | (*p++ & 0xFF);
572 } while (--i > 0);
573 /* Extend the sign bit. */
574 if (SIZEOF_LONG > f->size)
575 x |= -(x & (1L << (8*f->size - 1)));
576 return PyInt_FromLong(x);
577}
578
579static PyObject *
580bu_uint(const char *p, const formatdef *f)
581{
582 unsigned long x = 0;
583 int i = f->size;
584 do {
585 x = (x<<8) | (*p++ & 0xFF);
586 } while (--i > 0);
587 if (f->size >= 4)
588 return PyLong_FromUnsignedLong(x);
589 else
590 return PyInt_FromLong((long)x);
591}
592
593static PyObject *
594bu_longlong(const char *p, const formatdef *f)
595{
596 return _PyLong_FromByteArray((const unsigned char *)p,
597 8,
598 0, /* little-endian */
599 1 /* signed */);
600}
601
602static PyObject *
603bu_ulonglong(const char *p, const formatdef *f)
604{
605 return _PyLong_FromByteArray((const unsigned char *)p,
606 8,
607 0, /* little-endian */
608 0 /* signed */);
609}
610
611static PyObject *
612bu_float(const char *p, const formatdef *f)
613{
614 return unpack_float(p, 0);
615}
616
617static PyObject *
618bu_double(const char *p, const formatdef *f)
619{
620 return unpack_double(p, 0);
621}
622
623static int
624bp_int(char *p, PyObject *v, const formatdef *f)
625{
626 long x;
627 int i;
628 if (get_long(v, &x) < 0)
629 return -1;
630 i = f->size;
631 do {
632 p[--i] = (char)x;
633 x >>= 8;
634 } while (i > 0);
635 return 0;
636}
637
638static int
639bp_uint(char *p, PyObject *v, const formatdef *f)
640{
641 unsigned long x;
642 int i;
643 if (get_ulong(v, &x) < 0)
644 return -1;
645 i = f->size;
646 do {
647 p[--i] = (char)x;
648 x >>= 8;
649 } while (i > 0);
650 return 0;
651}
652
653static int
654bp_longlong(char *p, PyObject *v, const formatdef *f)
655{
656 int res;
657 v = get_pylong(v);
658 if (v == NULL)
659 return -1;
660 res = _PyLong_AsByteArray((PyLongObject *)v,
661 (unsigned char *)p,
662 8,
663 0, /* little_endian */
664 1 /* signed */);
665 Py_DECREF(v);
666 return res;
667}
668
669static int
670bp_ulonglong(char *p, PyObject *v, const formatdef *f)
671{
672 int res;
673 v = get_pylong(v);
674 if (v == NULL)
675 return -1;
676 res = _PyLong_AsByteArray((PyLongObject *)v,
677 (unsigned char *)p,
678 8,
679 0, /* little_endian */
680 0 /* signed */);
681 Py_DECREF(v);
682 return res;
683}
684
685static int
686bp_float(char *p, PyObject *v, const formatdef *f)
687{
688 double x = PyFloat_AsDouble(v);
689 if (x == -1 && PyErr_Occurred()) {
690 PyErr_SetString(StructError,
691 "required argument is not a float");
692 return -1;
693 }
694 return _PyFloat_Pack4(x, (unsigned char *)p, 0);
695}
696
697static int
698bp_double(char *p, PyObject *v, const formatdef *f)
699{
700 double x = PyFloat_AsDouble(v);
701 if (x == -1 && PyErr_Occurred()) {
702 PyErr_SetString(StructError,
703 "required argument is not a float");
704 return -1;
705 }
706 return _PyFloat_Pack8(x, (unsigned char *)p, 0);
707}
708
709static formatdef bigendian_table[] = {
710 {'x', 1, 0, NULL},
711 {'b', 1, 0, bu_int, bp_int},
712 {'B', 1, 0, bu_uint, bp_int},
713 {'c', 1, 0, nu_char, np_char},
714 {'s', 1, 0, NULL},
715 {'p', 1, 0, NULL},
716 {'h', 2, 0, bu_int, bp_int},
717 {'H', 2, 0, bu_uint, bp_uint},
718 {'i', 4, 0, bu_int, bp_int},
719 {'I', 4, 0, bu_uint, bp_uint},
720 {'l', 4, 0, bu_int, bp_int},
721 {'L', 4, 0, bu_uint, bp_uint},
722 {'q', 8, 0, bu_longlong, bp_longlong},
723 {'Q', 8, 0, bu_ulonglong, bp_ulonglong},
724 {'f', 4, 0, bu_float, bp_float},
725 {'d', 8, 0, bu_double, bp_double},
726 {0}
727};
728
729/* Little-endian routines. *****************************************************/
730
731static PyObject *
732lu_int(const char *p, const formatdef *f)
733{
734 long x = 0;
735 int i = f->size;
736 do {
737 x = (x<<8) | (p[--i] & 0xFF);
738 } while (i > 0);
739 /* Extend the sign bit. */
740 if (SIZEOF_LONG > f->size)
741 x |= -(x & (1L << (8*f->size - 1)));
742 return PyInt_FromLong(x);
743}
744
745static PyObject *
746lu_uint(const char *p, const formatdef *f)
747{
748 unsigned long x = 0;
749 int i = f->size;
750 do {
751 x = (x<<8) | (p[--i] & 0xFF);
752 } while (i > 0);
753 if (f->size >= 4)
754 return PyLong_FromUnsignedLong(x);
755 else
756 return PyInt_FromLong((long)x);
757}
758
759static PyObject *
760lu_longlong(const char *p, const formatdef *f)
761{
762 return _PyLong_FromByteArray((const unsigned char *)p,
763 8,
764 1, /* little-endian */
765 1 /* signed */);
766}
767
768static PyObject *
769lu_ulonglong(const char *p, const formatdef *f)
770{
771 return _PyLong_FromByteArray((const unsigned char *)p,
772 8,
773 1, /* little-endian */
774 0 /* signed */);
775}
776
777static PyObject *
778lu_float(const char *p, const formatdef *f)
779{
780 return unpack_float(p, 1);
781}
782
783static PyObject *
784lu_double(const char *p, const formatdef *f)
785{
786 return unpack_double(p, 1);
787}
788
789static int
790lp_int(char *p, PyObject *v, const formatdef *f)
791{
792 long x;
793 int i;
794 if (get_long(v, &x) < 0)
795 return -1;
796 i = f->size;
797 do {
798 *p++ = (char)x;
799 x >>= 8;
800 } while (--i > 0);
801 return 0;
802}
803
804static int
805lp_uint(char *p, PyObject *v, const formatdef *f)
806{
807 unsigned long x;
808 int i;
809 if (get_ulong(v, &x) < 0)
810 return -1;
811 i = f->size;
812 do {
813 *p++ = (char)x;
814 x >>= 8;
815 } while (--i > 0);
816 return 0;
817}
818
819static int
820lp_longlong(char *p, PyObject *v, const formatdef *f)
821{
822 int res;
823 v = get_pylong(v);
824 if (v == NULL)
825 return -1;
826 res = _PyLong_AsByteArray((PyLongObject*)v,
827 (unsigned char *)p,
828 8,
829 1, /* little_endian */
830 1 /* signed */);
831 Py_DECREF(v);
832 return res;
833}
834
835static int
836lp_ulonglong(char *p, PyObject *v, const formatdef *f)
837{
838 int res;
839 v = get_pylong(v);
840 if (v == NULL)
841 return -1;
842 res = _PyLong_AsByteArray((PyLongObject*)v,
843 (unsigned char *)p,
844 8,
845 1, /* little_endian */
846 0 /* signed */);
847 Py_DECREF(v);
848 return res;
849}
850
851static int
852lp_float(char *p, PyObject *v, const formatdef *f)
853{
854 double x = PyFloat_AsDouble(v);
855 if (x == -1 && PyErr_Occurred()) {
856 PyErr_SetString(StructError,
857 "required argument is not a float");
858 return -1;
859 }
860 return _PyFloat_Pack4(x, (unsigned char *)p, 1);
861}
862
863static int
864lp_double(char *p, PyObject *v, const formatdef *f)
865{
866 double x = PyFloat_AsDouble(v);
867 if (x == -1 && PyErr_Occurred()) {
868 PyErr_SetString(StructError,
869 "required argument is not a float");
870 return -1;
871 }
872 return _PyFloat_Pack8(x, (unsigned char *)p, 1);
873}
874
875static formatdef lilendian_table[] = {
876 {'x', 1, 0, NULL},
877 {'b', 1, 0, lu_int, lp_int},
878 {'B', 1, 0, lu_uint, lp_int},
879 {'c', 1, 0, nu_char, np_char},
880 {'s', 1, 0, NULL},
881 {'p', 1, 0, NULL},
882 {'h', 2, 0, lu_int, lp_int},
883 {'H', 2, 0, lu_uint, lp_uint},
884 {'i', 4, 0, lu_int, lp_int},
885 {'I', 4, 0, lu_uint, lp_uint},
886 {'l', 4, 0, lu_int, lp_int},
887 {'L', 4, 0, lu_uint, lp_uint},
888 {'q', 8, 0, lu_longlong, lp_longlong},
889 {'Q', 8, 0, lu_ulonglong, lp_ulonglong},
890 {'f', 4, 0, lu_float, lp_float},
891 {'d', 8, 0, lu_double, lp_double},
892 {0}
893};
894
895
896static const formatdef *
897whichtable(char **pfmt)
898{
899 const char *fmt = (*pfmt)++; /* May be backed out of later */
900 switch (*fmt) {
901 case '<':
902 return lilendian_table;
903 case '>':
904 case '!': /* Network byte order is big-endian */
905 return bigendian_table;
906 case '=': { /* Host byte order -- different from native in aligment! */
907 int n = 1;
908 char *p = (char *) &n;
909 if (*p == 1)
910 return lilendian_table;
911 else
912 return bigendian_table;
913 }
914 default:
915 --*pfmt; /* Back out of pointer increment */
916 /* Fall through */
917 case '@':
918 return native_table;
919 }
920}
921
922
923/* Get the table entry for a format code */
924
925static const formatdef *
926getentry(int c, const formatdef *f)
927{
928 for (; f->format != '\0'; f++) {
929 if (f->format == c) {
930 return f;
931 }
932 }
933 PyErr_SetString(StructError, "bad char in struct format");
934 return NULL;
935}
936
937
938/* Align a size according to a format code */
939
940static int
941align(int size, int c, const formatdef *e)
942{
943 if (e->format == c) {
944 if (e->alignment) {
945 size = ((size + e->alignment - 1)
946 / e->alignment)
947 * e->alignment;
948 }
949 }
950 return size;
951}
952
953
954/* calculate the size of a format string */
955
956static int
957prepare_s(PyStructObject *self)
958{
959 const formatdef *f;
960 const formatdef *e;
961 formatcode *codes;
962
963 const char *s;
964 const char *fmt;
965 char c;
966 int size, len, numcodes, num, itemsize, x;
967
968 fmt = PyString_AS_STRING(self->s_format);
969
970 f = whichtable((char **)&fmt);
971
972 s = fmt;
973 size = 0;
974 len = 0;
975 numcodes = 0;
976 while ((c = *s++) != '\0') {
977 if (isspace(Py_CHARMASK(c)))
978 continue;
979 if ('0' <= c && c <= '9') {
980 num = c - '0';
981 while ('0' <= (c = *s++) && c <= '9') {
982 x = num*10 + (c - '0');
983 if (x/10 != num) {
984 PyErr_SetString(
985 StructError,
986 "overflow in item count");
987 return -1;
988 }
989 num = x;
990 }
991 if (c == '\0')
992 break;
993 }
994 else
995 num = 1;
996
997 e = getentry(c, f);
998 if (e == NULL)
999 return -1;
1000
1001 switch (c) {
1002 case 's': /* fall through */
1003 case 'p': len++; break;
1004 case 'x': break;
1005 default: len += num; break;
1006 }
1007 if (c != 'x') numcodes++;
1008
1009 itemsize = e->size;
1010 size = align(size, c, e);
1011 x = num * itemsize;
1012 size += x;
1013 if (x/itemsize != num || size < 0) {
1014 PyErr_SetString(StructError,
1015 "total struct size too long");
1016 return -1;
1017 }
1018 }
1019
1020 self->s_size = size;
1021 self->s_len = len;
1022 codes = PyMem_MALLOC((numcodes + 1) * sizeof(formatcode));
1023 if (codes == NULL) {
1024 PyErr_NoMemory();
1025 return -1;
1026 }
1027 self->s_codes = codes;
1028
1029 s = fmt;
1030 size = 0;
1031 while ((c = *s++) != '\0') {
1032 if (isspace(Py_CHARMASK(c)))
1033 continue;
1034 if ('0' <= c && c <= '9') {
1035 num = c - '0';
1036 while ('0' <= (c = *s++) && c <= '9')
1037 num = num*10 + (c - '0');
1038 if (c == '\0')
1039 break;
1040 }
1041 else
1042 num = 1;
1043
1044 e = getentry(c, f);
1045
1046 size = align(size, c, e);
1047 if (c != 'x') {
1048 codes->offset = size;
1049 codes->repeat = num;
1050 codes->fmtdef = e;
1051 codes++;
1052 }
1053 size += num * e->size;
1054 }
1055 codes->fmtdef = NULL;
1056 codes->offset = -1;
1057 codes->repeat = -1;
1058
1059 return 0;
1060}
1061
1062static PyObject *
1063s_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1064{
1065 PyObject *self;
1066 static PyObject *not_yet_string;
1067
1068 assert(type != NULL && type->tp_alloc != NULL);
1069
1070 self = type->tp_alloc(type, 0);
1071 if (self != NULL) {
1072 PyStructObject *s = (PyStructObject*)self;
1073 Py_INCREF(Py_None);
1074 s->s_format = Py_None;
1075 s->s_codes = NULL;
1076 s->s_size = -1;
1077 s->s_len = -1;
1078 }
1079 return self;
1080}
1081
1082static int
1083s_init(PyObject *self, PyObject *args, PyObject *kwds)
1084{
1085 PyStructObject *soself = (PyStructObject *)self;
1086 PyObject *o_format = NULL;
1087 int ret = 0;
1088 static char *kwlist[] = {"format", 0};
1089
1090 assert(PyStruct_Check(self));
1091
1092 if (!PyArg_ParseTupleAndKeywords(args, kwds, "S:Struct", kwlist,
1093 &o_format))
1094 return -1;
1095
1096 Py_INCREF(o_format);
1097 Py_XDECREF(soself->s_format);
1098 soself->s_format = o_format;
1099
1100 ret = prepare_s(soself);
1101 return ret;
1102}
1103
1104static void
1105s_dealloc(PyStructObject *s)
1106{
1107 int sts = 0;
1108 if (s->weakreflist != NULL)
1109 PyObject_ClearWeakRefs((PyObject *)s);
1110 if (s->s_codes != NULL) {
1111 PyMem_FREE(s->s_codes);
1112 }
1113 Py_XDECREF(s->s_format);
1114 s->ob_type->tp_free((PyObject *)s);
1115}
1116
1117PyDoc_STRVAR(s_unpack__doc__,
1118"unpack(str) -> (v1, v2, ...)\n\
1119\n\
1120Return tuple containing values unpacked according to this Struct's format.\n\
1121Requires len(str) == self.size. See struct.__doc__ for more on format\n\
1122strings.");
1123
1124static PyObject *
1125s_unpack(PyObject *self, PyObject *inputstr)
1126{
1127 PyStructObject *soself;
1128 PyObject *result;
1129 char *restart;
1130 formatcode *code;
1131 Py_ssize_t i;
1132
1133 soself = (PyStructObject *)self;
1134 assert(PyStruct_Check(self));
1135 assert(soself->s_codes != NULL);
1136 if (inputstr == NULL || !PyString_Check(inputstr) ||
1137 PyString_GET_SIZE(inputstr) != soself->s_size) {
1138 PyErr_Format(StructError,
1139 "unpack requires a string argument of length %d", soself->s_size);
1140 return NULL;
1141 }
1142 result = PyTuple_New(soself->s_len);
1143 if (result == NULL)
1144 return NULL;
1145
1146
1147 restart = PyString_AS_STRING(inputstr);
1148 i = 0;
1149 for (code = soself->s_codes; code->fmtdef != NULL; code++) {
1150 Py_ssize_t n;
1151 PyObject *v;
1152 const formatdef *e = code->fmtdef;
1153 const char *res = restart + code->offset;
1154 if (e->format == 's') {
1155 v = PyString_FromStringAndSize(res, code->repeat);
1156 if (v == NULL)
1157 goto fail;
1158 PyTuple_SET_ITEM(result, i++, v);
1159 } else if (e->format == 'p') {
1160 n = *(unsigned char*)res;
1161 if (n >= code->repeat)
1162 n = code->repeat - 1;
1163 v = PyString_FromStringAndSize(res + 1, n);
1164 if (v == NULL)
1165 goto fail;
1166 PyTuple_SET_ITEM(result, i++, v);
1167 } else {
1168 for (n = 0; n < code->repeat; n++) {
1169 v = e->unpack(res, e);
1170 if (v == NULL)
1171 goto fail;
1172 PyTuple_SET_ITEM(result, i++, v);
1173 res += e->size;
1174 }
1175 }
1176 }
1177
1178 return result;
1179fail:
1180 Py_DECREF(result);
1181 return NULL;
1182};
1183
1184
1185PyDoc_STRVAR(s_pack__doc__,
1186"pack(v1, v2, ...) -> string\n\
1187\n\
1188Return a string containing values v1, v2, ... packed according to this\n\
1189Struct's format. See struct.__doc__ for more on format strings.");
1190
1191static PyObject *
1192s_pack(PyObject *self, PyObject *args)
1193{
1194 PyStructObject *soself;
1195 PyObject *result;
1196 char *restart;
1197 formatcode *code;
1198 Py_ssize_t i;
1199
1200 soself = (PyStructObject *)self;
1201 assert(PyStruct_Check(self));
1202 assert(soself->s_codes != NULL);
1203 if (args == NULL || !PyTuple_Check(args) ||
1204 PyTuple_GET_SIZE(args) != soself->s_len)
1205 {
1206 PyErr_Format(StructError,
1207 "pack requires exactly %d arguments", soself->s_len);
1208 return NULL;
1209 }
1210
1211 result = PyString_FromStringAndSize((char *)NULL, soself->s_size);
1212 if (result == NULL)
1213 return NULL;
1214
1215 restart = PyString_AS_STRING(result);
1216 memset(restart, '\0', soself->s_size);
1217 i = 0;
1218 for (code = soself->s_codes; code->fmtdef != NULL; code++) {
1219 Py_ssize_t n;
1220 PyObject *v;
1221 const formatdef *e = code->fmtdef;
1222 char *res = restart + code->offset;
1223 if (e->format == 's') {
1224 v = PyTuple_GET_ITEM(args, i++);
1225 if (!PyString_Check(v)) {
1226 PyErr_SetString(StructError,
1227 "argument for 's' must be a string");
1228 goto fail;
1229 }
1230 n = PyString_GET_SIZE(v);
1231 if (n > code->repeat)
1232 n = code->repeat;
1233 if (n > 0)
1234 memcpy(res, PyString_AS_STRING(v), n);
1235 } else if (e->format == 'p') {
1236 v = PyTuple_GET_ITEM(args, i++);
1237 if (!PyString_Check(v)) {
1238 PyErr_SetString(StructError,
1239 "argument for 'p' must be a string");
1240 goto fail;
1241 }
1242 n = PyString_GET_SIZE(v);
1243 if (n > (code->repeat - 1))
1244 n = code->repeat - 1;
1245 if (n > 0)
1246 memcpy(res + 1, PyString_AS_STRING(v), n);
1247 if (n > 255)
1248 n = 255;
1249 *res = Py_SAFE_DOWNCAST(n, Py_ssize_t, unsigned char);
1250 } else {
1251 for (n = 0; n < code->repeat; n++) {
1252 v = PyTuple_GET_ITEM(args, i++);
1253 if (e->pack(res, v, e) < 0)
1254 goto fail;
1255 res += e->size;
1256 }
1257 }
1258 }
1259
1260 return result;
1261
1262fail:
1263 Py_DECREF(result);
1264 return NULL;
1265
1266}
1267
1268
1269/* List of functions */
1270
1271static struct PyMethodDef s_methods[] = {
1272 {"pack", s_pack, METH_VARARGS, s_pack__doc__},
1273 {"unpack", s_unpack, METH_O, s_unpack__doc__},
1274 {NULL, NULL} /* sentinel */
1275};
1276
1277PyDoc_STRVAR(s__doc__, "Compiled struct object");
1278
1279#define OFF(x) offsetof(PyStructObject, x)
1280
1281static PyMemberDef s_memberlist[] = {
1282 {"format", T_OBJECT, OFF(s_format), RO,
1283 "struct format string"},
1284 {"size", T_INT, OFF(s_size), RO,
1285 "struct size in bytes"},
1286 {"_len", T_INT, OFF(s_len), RO,
1287 "number of items expected in tuple"},
1288 {NULL} /* Sentinel */
1289};
1290
1291
1292static
1293PyTypeObject PyStructType = {
1294 PyObject_HEAD_INIT(&PyType_Type)
1295 0,
1296 "Struct",
1297 sizeof(PyStructObject),
1298 0,
1299 (destructor)s_dealloc, /* tp_dealloc */
1300 0, /* tp_print */
1301 0, /* tp_getattr */
1302 0, /* tp_setattr */
1303 0, /* tp_compare */
1304 0, /* tp_repr */
1305 0, /* tp_as_number */
1306 0, /* tp_as_sequence */
1307 0, /* tp_as_mapping */
1308 0, /* tp_hash */
1309 0, /* tp_call */
1310 0, /* tp_str */
1311 PyObject_GenericGetAttr, /* tp_getattro */
1312 PyObject_GenericSetAttr, /* tp_setattro */
1313 0, /* tp_as_buffer */
1314 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
1315 s__doc__, /* tp_doc */
1316 0, /* tp_traverse */
1317 0, /* tp_clear */
1318 0, /* tp_richcompare */
1319 offsetof(PyStructObject, weakreflist), /* tp_weaklistoffset */
1320 0, /* tp_iter */
1321 0, /* tp_iternext */
1322 s_methods, /* tp_methods */
1323 s_memberlist, /* tp_members */
1324 0, /* tp_getset */
1325 0, /* tp_base */
1326 0, /* tp_dict */
1327 0, /* tp_descr_get */
1328 0, /* tp_descr_set */
1329 0, /* tp_dictoffset */
1330 s_init, /* tp_init */
1331 PyType_GenericAlloc, /* tp_alloc */
1332 s_new, /* tp_new */
1333 PyObject_Del, /* tp_free */
1334};
1335
1336/* Module initialization */
1337
1338PyMODINIT_FUNC
1339init_struct(void)
1340{
1341 PyObject *m = Py_InitModule("_struct", NULL);
1342 if (m == NULL)
1343 return;
1344
1345 /* Add some symbolic constants to the module */
1346 if (StructError == NULL) {
1347 StructError = PyErr_NewException("struct.error", NULL, NULL);
1348 if (StructError == NULL)
1349 return;
1350 }
1351 Py_INCREF(StructError);
1352 PyModule_AddObject(m, "error", StructError);
1353 Py_INCREF((PyObject*)&PyStructType);
1354 PyModule_AddObject(m, "Struct", (PyObject*)&PyStructType);
1355}