home *** CD-ROM | disk | FTP | other *** search
/ AmigActive 15 / AACD15.ISO / AACD / Programming / Python2 / Python20_source / Modules / structmodule.c < prev    next >
Encoding:
C/C++ Source or Header  |  2000-10-25  |  24.9 KB  |  1,272 lines

  1.  
  2. /* struct module -- pack values into and (out of) strings */
  3.  
  4. /* New version supporting byte order, alignment and size options,
  5.    character strings, and unsigned numbers */
  6.  
  7. static char struct__doc__[] = "\
  8. Functions to convert between Python values and C structs.\n\
  9. Python strings are used to hold the data representing the C struct\n\
  10. and also as format strings to describe the layout of data in the C struct.\n\
  11. \n\
  12. The optional first format char indicates byte ordering and alignment:\n\
  13.  @: native w/native alignment(default)\n\
  14.  =: native w/standard alignment\n\
  15.  <: little-endian, std. alignment\n\
  16.  >: big-endian, std. alignment\n\
  17.  !: network, std (same as >)\n\
  18. \n\
  19. The remaining chars indicate types of args and must match exactly;\n\
  20. these can be preceded by a decimal repeat count:\n\
  21.  x: pad byte (no data); c:char; b:signed byte; B:unsigned byte;\n\
  22.  h:short; H:unsigned short; i:int; I:unsigned int;\n\
  23.  l:long; L:unsigned long; f:float; d:double.\n\
  24. Special cases (preceding decimal count indicates length):\n\
  25.  s:string (array of char); p: pascal string (w. count byte).\n\
  26. Special case (only available in native format):\n\
  27.  P:an integer type that is wide enough to hold a pointer.\n\
  28. Whitespace between formats is ignored.\n\
  29. \n\
  30. The variable struct.error is an exception raised on errors.";
  31.  
  32. #include "Python.h"
  33.  
  34. #include <ctype.h>
  35.  
  36.  
  37. /* Exception */
  38.  
  39. static PyObject *StructError;
  40.  
  41.  
  42. /* Define various structs to figure out the alignments of types */
  43.  
  44. #ifdef __MWERKS__
  45. /*
  46. ** XXXX We have a problem here. There are no unique alignment rules
  47. ** on the PowerPC mac. 
  48. */
  49. #ifdef __powerc
  50. #pragma options align=mac68k
  51. #endif
  52. #endif /* __MWERKS__ */
  53.  
  54. typedef struct { char c; short x; } s_short;
  55. typedef struct { char c; int x; } s_int;
  56. typedef struct { char c; long x; } s_long;
  57. typedef struct { char c; float x; } s_float;
  58. typedef struct { char c; double x; } s_double;
  59. typedef struct { char c; void *x; } s_void_p;
  60.  
  61. #define SHORT_ALIGN (sizeof(s_short) - sizeof(short))
  62. #define INT_ALIGN (sizeof(s_int) - sizeof(int))
  63. #define LONG_ALIGN (sizeof(s_long) - sizeof(long))
  64. #define FLOAT_ALIGN (sizeof(s_float) - sizeof(float))
  65. #define DOUBLE_ALIGN (sizeof(s_double) - sizeof(double))
  66. #define VOID_P_ALIGN (sizeof(s_void_p) - sizeof(void *))
  67.  
  68. #define STRINGIFY(x)    #x
  69.  
  70. #ifdef __powerc
  71. #pragma options align=reset
  72. #endif
  73.  
  74. /* Helper routine to get a Python integer and raise the appropriate error
  75.    if it isn't one */
  76.  
  77. static int
  78. get_long(PyObject *v, long *p)
  79. {
  80.     long x = PyInt_AsLong(v);
  81.     if (x == -1 && PyErr_Occurred()) {
  82.         if (PyErr_ExceptionMatches(PyExc_TypeError))
  83.             PyErr_SetString(StructError,
  84.                     "required argument is not an integer");
  85.         return -1;
  86.     }
  87.     *p = x;
  88.     return 0;
  89. }
  90.  
  91.  
  92. /* Same, but handling unsigned long */
  93.  
  94. static int
  95. get_ulong(PyObject *v, unsigned long *p)
  96. {
  97.     if (PyLong_Check(v)) {
  98.         unsigned long x = PyLong_AsUnsignedLong(v);
  99.         if (x == (unsigned long)(-1) && PyErr_Occurred())
  100.             return -1;
  101.         *p = x;
  102.         return 0;
  103.     }
  104.     else {
  105.         return get_long(v, (long *)p);
  106.     }
  107. }
  108.  
  109.  
  110. /* Floating point helpers */
  111.  
  112. /* These use ANSI/IEEE Standard 754-1985 (Standard for Binary Floating
  113.    Point Arithmetic).  See the following URL:
  114.    http://www.psc.edu/general/software/packages/ieee/ieee.html */
  115.  
  116. /* XXX Inf/NaN are not handled quite right (but underflow is!) */
  117.  
  118. static int
  119. pack_float(double x, /* The number to pack */
  120.            char *p,  /* Where to pack the high order byte */
  121.            int incr) /* 1 for big-endian; -1 for little-endian */
  122. {
  123.     int s;
  124.     int e;
  125.     double f;
  126.     long fbits;
  127.  
  128.     if (x < 0) {
  129.         s = 1;
  130.         x = -x;
  131.     }
  132.     else
  133.         s = 0;
  134.  
  135.     f = frexp(x, &e);
  136.  
  137.     /* Normalize f to be in the range [1.0, 2.0) */
  138.     if (0.5 <= f && f < 1.0) {
  139.         f *= 2.0;
  140.         e--;
  141.     }
  142.     else if (f == 0.0) {
  143.         e = 0;
  144.     }
  145.     else {
  146.         PyErr_SetString(PyExc_SystemError,
  147.                 "frexp() result out of range");
  148.         return -1;
  149.     }
  150.  
  151.     if (e >= 128) {
  152.         /* XXX 128 itself is reserved for Inf/NaN */
  153.         PyErr_SetString(PyExc_OverflowError,
  154.                 "float too large to pack with f format");
  155.         return -1;
  156.     }
  157.     else if (e < -126) {
  158.         /* Gradual underflow */
  159.         f = ldexp(f, 126 + e);
  160.         e = 0;
  161.     }
  162.     else if (!(e == 0 && f == 0.0)) {
  163.         e += 127;
  164.         f -= 1.0; /* Get rid of leading 1 */
  165.     }
  166.  
  167.     f *= 8388608.0; /* 2**23 */
  168.     fbits = (long) floor(f + 0.5); /* Round */
  169.  
  170.     /* First byte */
  171.     *p = (s<<7) | (e>>1);
  172.     p += incr;
  173.  
  174.     /* Second byte */
  175.     *p = (char) (((e&1)<<7) | (fbits>>16));
  176.     p += incr;
  177.  
  178.     /* Third byte */
  179.     *p = (fbits>>8) & 0xFF;
  180.     p += incr;
  181.  
  182.     /* Fourth byte */
  183.     *p = fbits&0xFF;
  184.  
  185.     /* Done */
  186.     return 0;
  187. }
  188.  
  189. static int
  190. pack_double(double x, /* The number to pack */
  191.             char *p,  /* Where to pack the high order byte */
  192.             int incr) /* 1 for big-endian; -1 for little-endian */
  193. {
  194.     int s;
  195.     int e;
  196.     double f;
  197.     long fhi, flo;
  198.  
  199.     if (x < 0) {
  200.         s = 1;
  201.         x = -x;
  202.     }
  203.     else
  204.         s = 0;
  205.  
  206.     f = frexp(x, &e);
  207.  
  208.     /* Normalize f to be in the range [1.0, 2.0) */
  209.     if (0.5 <= f && f < 1.0) {
  210.         f *= 2.0;
  211.         e--;
  212.     }
  213.     else if (f == 0.0) {
  214.         e = 0;
  215.     }
  216.     else {
  217.         PyErr_SetString(PyExc_SystemError,
  218.                 "frexp() result out of range");
  219.         return -1;
  220.     }
  221.  
  222.     if (e >= 1024) {
  223.         /* XXX 1024 itself is reserved for Inf/NaN */
  224.         PyErr_SetString(PyExc_OverflowError,
  225.                 "float too large to pack with d format");
  226.         return -1;
  227.     }
  228.     else if (e < -1022) {
  229.         /* Gradual underflow */
  230.         f = ldexp(f, 1022 + e);
  231.         e = 0;
  232.     }
  233.     else if (!(e == 0 && f == 0.0)) {
  234.         e += 1023;
  235.         f -= 1.0; /* Get rid of leading 1 */
  236.     }
  237.  
  238.     /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
  239.     f *= 268435456.0; /* 2**28 */
  240.     fhi = (long) floor(f); /* Truncate */
  241.     f -= (double)fhi;
  242.     f *= 16777216.0; /* 2**24 */
  243.     flo = (long) floor(f + 0.5); /* Round */
  244.  
  245.     /* First byte */
  246.     *p = (s<<7) | (e>>4);
  247.     p += incr;
  248.  
  249.     /* Second byte */
  250.     *p = (char) (((e&0xF)<<4) | (fhi>>24));
  251.     p += incr;
  252.  
  253.     /* Third byte */
  254.     *p = (fhi>>16) & 0xFF;
  255.     p += incr;
  256.  
  257.     /* Fourth byte */
  258.     *p = (fhi>>8) & 0xFF;
  259.     p += incr;
  260.  
  261.     /* Fifth byte */
  262.     *p = fhi & 0xFF;
  263.     p += incr;
  264.  
  265.     /* Sixth byte */
  266.     *p = (flo>>16) & 0xFF;
  267.     p += incr;
  268.  
  269.     /* Seventh byte */
  270.     *p = (flo>>8) & 0xFF;
  271.     p += incr;
  272.  
  273.     /* Eighth byte */
  274.     *p = flo & 0xFF;
  275.     p += incr;
  276.  
  277.     /* Done */
  278.     return 0;
  279. }
  280.  
  281. static PyObject *
  282. unpack_float(const char *p,  /* Where the high order byte is */
  283.              int incr)       /* 1 for big-endian; -1 for little-endian */
  284. {
  285.     int s;
  286.     int e;
  287.     long f;
  288.     double x;
  289.  
  290.     /* First byte */
  291.     s = (*p>>7) & 1;
  292.     e = (*p & 0x7F) << 1;
  293.     p += incr;
  294.  
  295.     /* Second byte */
  296.     e |= (*p>>7) & 1;
  297.     f = (*p & 0x7F) << 16;
  298.     p += incr;
  299.  
  300.     /* Third byte */
  301.     f |= (*p & 0xFF) << 8;
  302.     p += incr;
  303.  
  304.     /* Fourth byte */
  305.     f |= *p & 0xFF;
  306.  
  307.     x = (double)f / 8388608.0;
  308.  
  309.     /* XXX This sadly ignores Inf/NaN issues */
  310.     if (e == 0)
  311.         e = -126;
  312.     else {
  313.         x += 1.0;
  314.         e -= 127;
  315.     }
  316.     x = ldexp(x, e);
  317.  
  318.     if (s)
  319.         x = -x;
  320.  
  321.     return PyFloat_FromDouble(x);
  322. }
  323.  
  324. static PyObject *
  325. unpack_double(const char *p,  /* Where the high order byte is */
  326.               int incr)       /* 1 for big-endian; -1 for little-endian */
  327. {
  328.     int s;
  329.     int e;
  330.     long fhi, flo;
  331.     double x;
  332.  
  333.     /* First byte */
  334.     s = (*p>>7) & 1;
  335.     e = (*p & 0x7F) << 4;
  336.     p += incr;
  337.  
  338.     /* Second byte */
  339.     e |= (*p>>4) & 0xF;
  340.     fhi = (*p & 0xF) << 24;
  341.     p += incr;
  342.  
  343.     /* Third byte */
  344.     fhi |= (*p & 0xFF) << 16;
  345.     p += incr;
  346.  
  347.     /* Fourth byte */
  348.     fhi |= (*p & 0xFF) << 8;
  349.     p += incr;
  350.  
  351.     /* Fifth byte */
  352.     fhi |= *p & 0xFF;
  353.     p += incr;
  354.  
  355.     /* Sixth byte */
  356.     flo = (*p & 0xFF) << 16;
  357.     p += incr;
  358.  
  359.     /* Seventh byte */
  360.     flo |= (*p & 0xFF) << 8;
  361.     p += incr;
  362.  
  363.     /* Eighth byte */
  364.     flo |= *p & 0xFF;
  365.     p += incr;
  366.  
  367.     x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
  368.     x /= 268435456.0; /* 2**28 */
  369.  
  370.     /* XXX This sadly ignores Inf/NaN */
  371.     if (e == 0)
  372.         e = -1022;
  373.     else {
  374.         x += 1.0;
  375.         e -= 1023;
  376.     }
  377.     x = ldexp(x, e);
  378.  
  379.     if (s)
  380.         x = -x;
  381.  
  382.     return PyFloat_FromDouble(x);
  383. }
  384.  
  385.  
  386. /* The translation function for each format character is table driven */
  387.  
  388. typedef struct _formatdef {
  389.     char format;
  390.     int size;
  391.     int alignment;
  392.     PyObject* (*unpack)(const char *,
  393.                 const struct _formatdef *);
  394.     int (*pack)(char *, PyObject *,
  395.             const struct _formatdef *);
  396. } formatdef;
  397.  
  398. static PyObject *
  399. nu_char(const char *p, const formatdef *f)
  400. {
  401.     return PyString_FromStringAndSize(p, 1);
  402. }
  403.  
  404. static PyObject *
  405. nu_byte(const char *p, const formatdef *f)
  406. {
  407.     return PyInt_FromLong((long) *(signed char *)p);
  408. }
  409.  
  410. static PyObject *
  411. nu_ubyte(const char *p, const formatdef *f)
  412. {
  413.     return PyInt_FromLong((long) *(unsigned char *)p);
  414. }
  415.  
  416. static PyObject *
  417. nu_short(const char *p, const formatdef *f)
  418. {
  419.     return PyInt_FromLong((long) *(short *)p);
  420. }
  421.  
  422. static PyObject *
  423. nu_ushort(const char *p, const formatdef *f)
  424. {
  425.     return PyInt_FromLong((long) *(unsigned short *)p);
  426. }
  427.  
  428. static PyObject *
  429. nu_int(const char *p, const formatdef *f)
  430. {
  431.     return PyInt_FromLong((long) *(int *)p);
  432. }
  433.  
  434. static PyObject *
  435. nu_uint(const char *p, const formatdef *f)
  436. {
  437.     unsigned int x = *(unsigned int *)p;
  438.     return PyLong_FromUnsignedLong((unsigned long)x);
  439. }
  440.  
  441. static PyObject *
  442. nu_long(const char *p, const formatdef *f)
  443. {
  444.     return PyInt_FromLong(*(long *)p);
  445. }
  446.  
  447. static PyObject *
  448. nu_ulong(const char *p, const formatdef *f)
  449. {
  450.     return PyLong_FromUnsignedLong(*(unsigned long *)p);
  451. }
  452.  
  453. static PyObject *
  454. nu_float(const char *p, const formatdef *f)
  455. {
  456.     float x;
  457.     memcpy((char *)&x, p, sizeof(float));
  458.     return PyFloat_FromDouble((double)x);
  459. }
  460.  
  461. static PyObject *
  462. nu_double(const char *p, const formatdef *f)
  463. {
  464.     double x;
  465.     memcpy((char *)&x, p, sizeof(double));
  466.     return PyFloat_FromDouble(x);
  467. }
  468.  
  469. static PyObject *
  470. nu_void_p(const char *p, const formatdef *f)
  471. {
  472.     return PyLong_FromVoidPtr(*(void **)p);
  473. }
  474.  
  475. static int
  476. np_byte(char *p, PyObject *v, const formatdef *f)
  477. {
  478.     long x;
  479.     if (get_long(v, &x) < 0)
  480.         return -1;
  481.     if (x < -128 || x > 127){
  482.         PyErr_SetString(StructError,
  483.                 "byte format requires -128<=number<=127");
  484.         return -1;
  485.     }
  486.     *p = (char)x;
  487.     return 0;
  488. }
  489.  
  490. static int
  491. np_ubyte(char *p, PyObject *v, const formatdef *f)
  492. {
  493.     long x;
  494.     if (get_long(v, &x) < 0)
  495.         return -1;
  496.     if (x < 0 || x > 255){
  497.         PyErr_SetString(StructError,
  498.                 "ubyte format requires 0<=number<=255");
  499.         return -1;
  500.     }
  501.     *p = (char)x;
  502.     return 0;
  503. }
  504.  
  505. static int
  506. np_char(char *p, PyObject *v, const formatdef *f)
  507. {
  508.     if (!PyString_Check(v) || PyString_Size(v) != 1) {
  509.         PyErr_SetString(StructError,
  510.                 "char format require string of length 1");
  511.         return -1;
  512.     }
  513.     *p = *PyString_AsString(v);
  514.     return 0;
  515. }
  516.  
  517. static int
  518. np_short(char *p, PyObject *v, const formatdef *f)
  519. {
  520.     long x;
  521.     if (get_long(v, &x) < 0)
  522.         return -1;
  523.     if (x < SHRT_MIN || x > SHRT_MAX){
  524.         PyErr_SetString(StructError,
  525.                 "short format requires " STRINGIFY(SHRT_MIN)
  526.                                 "<=number<=" STRINGIFY(SHRT_MAX));
  527.         return -1;
  528.     }
  529.     * (short *)p = (short)x;
  530.     return 0;
  531. }
  532.  
  533. static int
  534. np_ushort(char *p, PyObject *v, const formatdef *f)
  535. {
  536.     long x;
  537.     if (get_long(v, &x) < 0)
  538.         return -1;
  539.     if (x < 0 || x > USHRT_MAX){
  540.         PyErr_SetString(StructError,
  541.                 "short format requires 0<=number<=" STRINGIFY(USHRT_MAX));
  542.         return -1;
  543.     }
  544.     * (unsigned short *)p = (unsigned short)x;
  545.     return 0;
  546. }
  547.  
  548. static int
  549. np_int(char *p, PyObject *v, const formatdef *f)
  550. {
  551.     long x;
  552.     if (get_long(v, &x) < 0)
  553.         return -1;
  554.     * (int *)p = x;
  555.     return 0;
  556. }
  557.  
  558. static int
  559. np_uint(char *p, PyObject *v, const formatdef *f)
  560. {
  561.     unsigned long x;
  562.     if (get_ulong(v, &x) < 0)
  563.         return -1;
  564.     * (unsigned int *)p = x;
  565.     return 0;
  566. }
  567.  
  568. static int
  569. np_long(char *p, PyObject *v, const formatdef *f)
  570. {
  571.     long x;
  572.     if (get_long(v, &x) < 0)
  573.         return -1;
  574.     * (long *)p = x;
  575.     return 0;
  576. }
  577.  
  578. static int
  579. np_ulong(char *p, PyObject *v, const formatdef *f)
  580. {
  581.     unsigned long x;
  582.     if (get_ulong(v, &x) < 0)
  583.         return -1;
  584.     * (unsigned long *)p = x;
  585.     return 0;
  586. }
  587.  
  588. static int
  589. np_float(char *p, PyObject *v, const formatdef *f)
  590. {
  591.     float x = (float)PyFloat_AsDouble(v);
  592.     if (x == -1 && PyErr_Occurred()) {
  593.         PyErr_SetString(StructError,
  594.                 "required argument is not a float");
  595.         return -1;
  596.     }
  597.     memcpy(p, (char *)&x, sizeof(float));
  598.     return 0;
  599. }
  600.  
  601. static int
  602. np_double(char *p, PyObject *v, const formatdef *f)
  603. {
  604.     double x = PyFloat_AsDouble(v);
  605.     if (x == -1 && PyErr_Occurred()) {
  606.         PyErr_SetString(StructError,
  607.                 "required argument is not a float");
  608.         return -1;
  609.     }
  610.     memcpy(p, (char *)&x, sizeof(double));
  611.     return 0;
  612. }
  613.  
  614. static int
  615. np_void_p(char *p, PyObject *v, const formatdef *f)
  616. {
  617.     void *x = PyLong_AsVoidPtr(v);
  618.     if (x == NULL && PyErr_Occurred()) {
  619.         /* ### hrm. PyLong_AsVoidPtr raises SystemError */
  620.         if (PyErr_ExceptionMatches(PyExc_TypeError))
  621.             PyErr_SetString(StructError,
  622.                     "required argument is not an integer");
  623.         return -1;
  624.     }
  625.     *(void **)p = x;
  626.     return 0;
  627. }
  628.  
  629. static formatdef native_table[] = {
  630.     {'x',    sizeof(char),    0,        NULL},
  631.     {'b',    sizeof(char),    0,        nu_byte,    np_byte},
  632.     {'B',    sizeof(char),    0,        nu_ubyte,    np_ubyte},
  633.     {'c',    sizeof(char),    0,        nu_char,    np_char},
  634.     {'s',    sizeof(char),    0,        NULL},
  635.     {'p',    sizeof(char),    0,        NULL},
  636.     {'h',    sizeof(short),    SHORT_ALIGN,    nu_short,    np_short},
  637.     {'H',    sizeof(short),    SHORT_ALIGN,    nu_ushort,    np_ushort},
  638.     {'i',    sizeof(int),    INT_ALIGN,    nu_int,        np_int},
  639.     {'I',    sizeof(int),    INT_ALIGN,    nu_uint,    np_uint},
  640.     {'l',    sizeof(long),    LONG_ALIGN,    nu_long,    np_long},
  641.     {'L',    sizeof(long),    LONG_ALIGN,    nu_ulong,    np_ulong},
  642.     {'f',    sizeof(float),    FLOAT_ALIGN,    nu_float,    np_float},
  643.     {'d',    sizeof(double),    DOUBLE_ALIGN,    nu_double,    np_double},
  644.     {'P',    sizeof(void *),    VOID_P_ALIGN,    nu_void_p,    np_void_p},
  645.     {0}
  646. };
  647.  
  648. static PyObject *
  649. bu_int(const char *p, const formatdef *f)
  650. {
  651.     long x = 0;
  652.     int i = f->size;
  653.     do {
  654.         x = (x<<8) | (*p++ & 0xFF);
  655.     } while (--i > 0);
  656.     i = 8*(sizeof(long) - f->size);
  657.     if (i) {
  658.         x <<= i;
  659.         x >>= i;
  660.     }
  661.     return PyInt_FromLong(x);
  662. }
  663.  
  664. static PyObject *
  665. bu_uint(const char *p, const formatdef *f)
  666. {
  667.     unsigned long x = 0;
  668.     int i = f->size;
  669.     do {
  670.         x = (x<<8) | (*p++ & 0xFF);
  671.     } while (--i > 0);
  672.     if (f->size >= 4)
  673.         return PyLong_FromUnsignedLong(x);
  674.     else
  675.         return PyInt_FromLong((long)x);
  676. }
  677.  
  678. static PyObject *
  679. bu_float(const char *p, const formatdef *f)
  680. {
  681.     return unpack_float(p, 1);
  682. }
  683.  
  684. static PyObject *
  685. bu_double(const char *p, const formatdef *f)
  686. {
  687.     return unpack_double(p, 1);
  688. }
  689.  
  690. static int
  691. bp_int(char *p, PyObject *v, const formatdef *f)
  692. {
  693.     long x;
  694.     int i;
  695.     if (get_long(v, &x) < 0)
  696.         return -1;
  697.     i = f->size;
  698.     do {
  699.         p[--i] = (char)x;
  700.         x >>= 8;
  701.     } while (i > 0);
  702.     return 0;
  703. }
  704.  
  705. static int
  706. bp_uint(char *p, PyObject *v, const formatdef *f)
  707. {
  708.     unsigned long x;
  709.     int i;
  710.     if (get_ulong(v, &x) < 0)
  711.         return -1;
  712.     i = f->size;
  713.     do {
  714.         p[--i] = (char)x;
  715.         x >>= 8;
  716.     } while (i > 0);
  717.     return 0;
  718. }
  719.  
  720. static int
  721. bp_float(char *p, PyObject *v, const formatdef *f)
  722. {
  723.     double x = PyFloat_AsDouble(v);
  724.     if (x == -1 && PyErr_Occurred()) {
  725.         PyErr_SetString(StructError,
  726.                 "required argument is not a float");
  727.         return -1;
  728.     }
  729.     return pack_float(x, p, 1);
  730. }
  731.  
  732. static int
  733. bp_double(char *p, PyObject *v, const formatdef *f)
  734. {
  735.     double x = PyFloat_AsDouble(v);
  736.     if (x == -1 && PyErr_Occurred()) {
  737.         PyErr_SetString(StructError,
  738.                 "required argument is not a float");
  739.         return -1;
  740.     }
  741.     return pack_double(x, p, 1);
  742. }
  743.  
  744. static formatdef bigendian_table[] = {
  745.     {'x',    1,        0,        NULL},
  746.     {'b',    1,        0,        bu_int,        bp_int},
  747.     {'B',    1,        0,        bu_uint,    bp_int},
  748.     {'c',    1,        0,        nu_char,    np_char},
  749.     {'s',    1,        0,        NULL},
  750.     {'p',    1,        0,        NULL},
  751.     {'h',    2,        0,        bu_int,        bp_int},
  752.     {'H',    2,        0,        bu_uint,    bp_uint},
  753.     {'i',    4,        0,        bu_int,        bp_int},
  754.     {'I',    4,        0,        bu_uint,    bp_uint},
  755.     {'l',    4,        0,        bu_int,        bp_int},
  756.     {'L',    4,        0,        bu_uint,    bp_uint},
  757.     {'f',    4,        0,        bu_float,    bp_float},
  758.     {'d',    8,        0,        bu_double,    bp_double},
  759.     {0}
  760. };
  761.  
  762. static PyObject *
  763. lu_int(const char *p, const formatdef *f)
  764. {
  765.     long x = 0;
  766.     int i = f->size;
  767.     do {
  768.         x = (x<<8) | (p[--i] & 0xFF);
  769.     } while (i > 0);
  770.     i = 8*(sizeof(long) - f->size);
  771.     if (i) {
  772.         x <<= i;
  773.         x >>= i;
  774.     }
  775.     return PyInt_FromLong(x);
  776. }
  777.  
  778. static PyObject *
  779. lu_uint(const char *p, const formatdef *f)
  780. {
  781.     unsigned long x = 0;
  782.     int i = f->size;
  783.     do {
  784.         x = (x<<8) | (p[--i] & 0xFF);
  785.     } while (i > 0);
  786.     if (f->size >= 4)
  787.         return PyLong_FromUnsignedLong(x);
  788.     else
  789.         return PyInt_FromLong((long)x);
  790. }
  791.  
  792. static PyObject *
  793. lu_float(const char *p, const formatdef *f)
  794. {
  795.     return unpack_float(p+3, -1);
  796. }
  797.  
  798. static PyObject *
  799. lu_double(const char *p, const formatdef *f)
  800. {
  801.     return unpack_double(p+7, -1);
  802. }
  803.  
  804. static int
  805. lp_int(char *p, PyObject *v, const formatdef *f)
  806. {
  807.     long x;
  808.     int i;
  809.     if (get_long(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.  
  819. static int
  820. lp_uint(char *p, PyObject *v, const formatdef *f)
  821. {
  822.     unsigned long x;
  823.     int i;
  824.     if (get_ulong(v, &x) < 0)
  825.         return -1;
  826.     i = f->size;
  827.     do {
  828.         *p++ = (char)x;
  829.         x >>= 8;
  830.     } while (--i > 0);
  831.     return 0;
  832. }
  833.  
  834. static int
  835. lp_float(char *p, PyObject *v, const formatdef *f)
  836. {
  837.     double x = PyFloat_AsDouble(v);
  838.     if (x == -1 && PyErr_Occurred()) {
  839.         PyErr_SetString(StructError,
  840.                 "required argument is not a float");
  841.         return -1;
  842.     }
  843.     return pack_float(x, p+3, -1);
  844. }
  845.  
  846. static int
  847. lp_double(char *p, PyObject *v, const formatdef *f)
  848. {
  849.     double x = PyFloat_AsDouble(v);
  850.     if (x == -1 && PyErr_Occurred()) {
  851.         PyErr_SetString(StructError,
  852.                 "required argument is not a float");
  853.         return -1;
  854.     }
  855.     return pack_double(x, p+7, -1);
  856. }
  857.  
  858. static formatdef lilendian_table[] = {
  859.     {'x',    1,        0,        NULL},
  860.     {'b',    1,        0,        lu_int,        lp_int},
  861.     {'B',    1,        0,        lu_uint,    lp_int},
  862.     {'c',    1,        0,        nu_char,    np_char},
  863.     {'s',    1,        0,        NULL},
  864.     {'p',    1,        0,        NULL},
  865.     {'h',    2,        0,        lu_int,        lp_int},
  866.     {'H',    2,        0,        lu_uint,    lp_uint},
  867.     {'i',    4,        0,        lu_int,        lp_int},
  868.     {'I',    4,        0,        lu_uint,    lp_uint},
  869.     {'l',    4,        0,        lu_int,        lp_int},
  870.     {'L',    4,        0,        lu_uint,    lp_uint},
  871.     {'f',    4,        0,        lu_float,    lp_float},
  872.     {'d',    8,        0,        lu_double,    lp_double},
  873.     {0}
  874. };
  875.  
  876.  
  877. static const formatdef *
  878. whichtable(char **pfmt)
  879. {
  880.     const char *fmt = (*pfmt)++; /* May be backed out of later */
  881.     switch (*fmt) {
  882.     case '<':
  883.         return lilendian_table;
  884.     case '>':
  885.     case '!': /* Network byte order is big-endian */
  886.         return bigendian_table;
  887.     case '=': { /* Host byte order -- different from native in aligment! */
  888.         int n = 1;
  889.         char *p = (char *) &n;
  890.         if (*p == 1)
  891.             return lilendian_table;
  892.         else
  893.             return bigendian_table;
  894.     }
  895.     default:
  896.         --*pfmt; /* Back out of pointer increment */
  897.         /* Fall through */
  898.     case '@':
  899.         return native_table;
  900.     }
  901. }
  902.  
  903.  
  904. /* Get the table entry for a format code */
  905.  
  906. static const formatdef *
  907. getentry(int c, const formatdef *f)
  908. {
  909.     for (; f->format != '\0'; f++) {
  910.         if (f->format == c) {
  911.             return f;
  912.         }
  913.     }
  914.     PyErr_SetString(StructError, "bad char in struct format");
  915.     return NULL;
  916. }
  917.  
  918.  
  919. /* Align a size according to a format code */
  920.  
  921. static int
  922. align(int size, int c, const formatdef *e)
  923. {
  924.     if (e->format == c) {
  925.         if (e->alignment) {
  926.             size = ((size + e->alignment - 1)
  927.                 / e->alignment)
  928.                 * e->alignment;
  929.         }
  930.     }
  931.     return size;
  932. }
  933.  
  934.  
  935. /* calculate the size of a format string */
  936.  
  937. static int
  938. calcsize(const char *fmt, const formatdef *f)
  939. {
  940.     const formatdef *e;
  941.     const char *s;
  942.     char c;
  943.     int size,  num, itemsize, x;
  944.  
  945.     s = fmt;
  946.     size = 0;
  947.     while ((c = *s++) != '\0') {
  948.         if (isspace((int)c))
  949.             continue;
  950.         if ('0' <= c && c <= '9') {
  951.             num = c - '0';
  952.             while ('0' <= (c = *s++) && c <= '9') {
  953.                 x = num*10 + (c - '0');
  954.                 if (x/10 != num) {
  955.                     PyErr_SetString(
  956.                         StructError,
  957.                         "overflow in item count");
  958.                     return -1;
  959.                 }
  960.                 num = x;
  961.             }
  962.             if (c == '\0')
  963.                 break;
  964.         }
  965.         else
  966.             num = 1;
  967.         
  968.         e = getentry(c, f);
  969.         if (e == NULL)
  970.             return -1;
  971.         itemsize = e->size;
  972.         size = align(size, c, e);
  973.         x = num * itemsize;
  974.         size += x;
  975.         if (x/itemsize != num || size < 0) {
  976.             PyErr_SetString(StructError,
  977.                                         "total struct size too long");
  978.             return -1;
  979.         }
  980.     }
  981.  
  982.     return size;
  983. }
  984.  
  985.  
  986. static char calcsize__doc__[] = "\
  987. calcsize(fmt) -> int\n\
  988. Return size of C struct described by format string fmt.\n\
  989. See struct.__doc__ for more on format strings.";
  990.  
  991. static PyObject *
  992. struct_calcsize(PyObject *self, PyObject *args)
  993. {
  994.     char *fmt;
  995.     const formatdef *f;
  996.     int size;
  997.  
  998.     if (!PyArg_ParseTuple(args, "s:calcsize", &fmt))
  999.         return NULL;
  1000.     f = whichtable(&fmt);
  1001.     size = calcsize(fmt, f);
  1002.     if (size < 0)
  1003.         return NULL;
  1004.     return PyInt_FromLong((long)size);
  1005. }
  1006.  
  1007.  
  1008. static char pack__doc__[] = "\
  1009. pack(fmt, v1, v2, ...) -> string\n\
  1010. Return string containing values v1, v2, ... packed according to fmt.\n\
  1011. See struct.__doc__ for more on format strings.";
  1012.  
  1013. static PyObject *
  1014. struct_pack(PyObject *self, PyObject *args)
  1015. {
  1016.     const formatdef *f, *e;
  1017.     PyObject *format, *result, *v;
  1018.     char *fmt;
  1019.     int size, num;
  1020.     int i, n;
  1021.     char *s, *res, *restart, *nres;
  1022.     char c;
  1023.  
  1024.     if (args == NULL || !PyTuple_Check(args) ||
  1025.         (n = PyTuple_Size(args)) < 1)
  1026.         {
  1027.         PyErr_SetString(PyExc_TypeError, 
  1028.             "struct.pack requires at least one argument");
  1029.         return NULL;
  1030.     }
  1031.     format = PyTuple_GetItem(args, 0);
  1032.     if (!PyArg_Parse(format, "s", &fmt))
  1033.         return NULL;
  1034.     f = whichtable(&fmt);
  1035.     size = calcsize(fmt, f);
  1036.     if (size < 0)
  1037.         return NULL;
  1038.     result = PyString_FromStringAndSize((char *)NULL, size);
  1039.     if (result == NULL)
  1040.         return NULL;
  1041.  
  1042.     s = fmt;
  1043.     i = 1;
  1044.     res = restart = PyString_AsString(result);
  1045.  
  1046.     while ((c = *s++) != '\0') {
  1047.         if (isspace((int)c))
  1048.             continue;
  1049.         if ('0' <= c && c <= '9') {
  1050.             num = c - '0';
  1051.             while ('0' <= (c = *s++) && c <= '9')
  1052.                    num = num*10 + (c - '0');
  1053.             if (c == '\0')
  1054.                 break;
  1055.         }
  1056.         else
  1057.             num = 1;
  1058.  
  1059.         e = getentry(c, f);
  1060.         if (e == NULL)
  1061.             goto fail;
  1062.         nres = restart + align((int)(res-restart), c, e);
  1063.         /* Fill padd bytes with zeros */
  1064.         while (res < nres)
  1065.             *res++ = '\0';
  1066.         if (num == 0 && c != 's')
  1067.             continue;
  1068.         do {
  1069.             if (c == 'x') {
  1070.                 /* doesn't consume arguments */
  1071.                 memset(res, '\0', num);
  1072.                 res += num;
  1073.                 break;
  1074.             }
  1075.             if (i >= n) {
  1076.                 PyErr_SetString(StructError,
  1077.                     "insufficient arguments to pack");
  1078.                 goto fail;
  1079.                 }
  1080.             v = PyTuple_GetItem(args, i++);
  1081.             if (v == NULL)
  1082.                 goto fail;
  1083.             if (c == 's') {
  1084.                 /* num is string size, not repeat count */
  1085.                 int n;
  1086.                 if (!PyString_Check(v)) {
  1087.                     PyErr_SetString(StructError,
  1088.                       "argument for 's' must be a string");
  1089.                     goto fail;
  1090.                 }
  1091.                 n = PyString_Size(v);
  1092.                 if (n > num)
  1093.                     n = num;
  1094.                 if (n > 0)
  1095.                     memcpy(res, PyString_AsString(v), n);
  1096.                 if (n < num)
  1097.                     memset(res+n, '\0', num-n);
  1098.                 res += num;
  1099.                 break;
  1100.             }
  1101.             else if (c == 'p') {
  1102.                 /* num is string size + 1,
  1103.                    to fit in the count byte */
  1104.                 int n;
  1105.                 num--; /* now num is max string size */
  1106.                 if (!PyString_Check(v)) {
  1107.                     PyErr_SetString(StructError,
  1108.                       "argument for 'p' must be a string");
  1109.                     goto fail;
  1110.                 }
  1111.                 n = PyString_Size(v);
  1112.                 if (n > num)
  1113.                     n = num;
  1114.                 if (n > 0)
  1115.                     memcpy(res+1, PyString_AsString(v), n);
  1116.                 if (n < num)
  1117.                     /* no real need, just to be nice */
  1118.                     memset(res+1+n, '\0', num-n);
  1119.                 *res++ = n; /* store the length byte */
  1120.                 res += num;
  1121.                 break;
  1122.             }
  1123.             else {
  1124.                 if (e->pack(res, v, e) < 0)
  1125.                     goto fail;
  1126.                 res += e->size;
  1127.             }
  1128.         } while (--num > 0);
  1129.     }
  1130.  
  1131.     if (i < n) {
  1132.         PyErr_SetString(StructError,
  1133.                 "too many arguments for pack format");
  1134.         goto fail;
  1135.     }
  1136.  
  1137.     return result;
  1138.  
  1139.  fail:
  1140.     Py_DECREF(result);
  1141.     return NULL;
  1142. }
  1143.  
  1144.  
  1145. static char unpack__doc__[] = "\
  1146. unpack(fmt, string) -> (v1, v2, ...)\n\
  1147. Unpack the string, containing packed C structure data, according\n\
  1148. to fmt.  Requires len(string)==calcsize(fmt).\n\
  1149. See struct.__doc__ for more on format strings.";
  1150.  
  1151. static PyObject *
  1152. struct_unpack(PyObject *self, PyObject *args)
  1153. {
  1154.     const formatdef *f, *e;
  1155.     char *str, *start, *fmt, *s;
  1156.     char c;
  1157.     int len, size, num;
  1158.     PyObject *res, *v;
  1159.  
  1160.     if (!PyArg_ParseTuple(args, "ss#:unpack", &fmt, &start, &len))
  1161.         return NULL;
  1162.     f = whichtable(&fmt);
  1163.     size = calcsize(fmt, f);
  1164.     if (size < 0)
  1165.         return NULL;
  1166.     if (size != len) {
  1167.         PyErr_SetString(StructError,
  1168.                 "unpack str size does not match format");
  1169.         return NULL;
  1170.     }
  1171.     res = PyList_New(0);
  1172.     if (res == NULL)
  1173.         return NULL;
  1174.     str = start;
  1175.     s = fmt;
  1176.     while ((c = *s++) != '\0') {
  1177.         if (isspace((int)c))
  1178.             continue;
  1179.         if ('0' <= c && c <= '9') {
  1180.             num = c - '0';
  1181.             while ('0' <= (c = *s++) && c <= '9')
  1182.                    num = num*10 + (c - '0');
  1183.             if (c == '\0')
  1184.                 break;
  1185.         }
  1186.         else
  1187.             num = 1;
  1188.  
  1189.         e = getentry(c, f);
  1190.         if (e == NULL)
  1191.             goto fail;
  1192.         str = start + align((int)(str-start), c, e);
  1193.         if (num == 0 && c != 's')
  1194.             continue;
  1195.  
  1196.         do {
  1197.             if (c == 'x') {
  1198.                 str += num;
  1199.                 break;
  1200.             }
  1201.             if (c == 's') {
  1202.                 /* num is string size, not repeat count */
  1203.                 v = PyString_FromStringAndSize(str, num);
  1204.                 if (v == NULL)
  1205.                     goto fail;
  1206.                 str += num;
  1207.                 num = 0;
  1208.             }
  1209.             else if (c == 'p') {
  1210.                 /* num is string buffer size,
  1211.                    not repeat count */
  1212.                 int n = *(unsigned char*)str;
  1213.                 /* first byte (unsigned) is string size */
  1214.                 if (n >= num)
  1215.                     n = num-1;
  1216.                 v = PyString_FromStringAndSize(str+1, n);
  1217.                 if (v == NULL)
  1218.                     goto fail;
  1219.                 str += num;
  1220.                 num = 0;
  1221.             }
  1222.             else {
  1223.                 v = e->unpack(str, e);
  1224.                 if (v == NULL)
  1225.                     goto fail;
  1226.                 str += e->size;
  1227.             }
  1228.             if (v == NULL || PyList_Append(res, v) < 0)
  1229.                 goto fail;
  1230.             Py_DECREF(v);
  1231.         } while (--num > 0);
  1232.     }
  1233.  
  1234.     v = PyList_AsTuple(res);
  1235.     Py_DECREF(res);
  1236.     return v;
  1237.  
  1238.  fail:
  1239.     Py_DECREF(res);
  1240.     return NULL;
  1241. }
  1242.  
  1243.  
  1244. /* List of functions */
  1245.  
  1246. static PyMethodDef struct_methods[] = {
  1247.     {"calcsize",    struct_calcsize,    METH_VARARGS, calcsize__doc__},
  1248.     {"pack",    struct_pack,        METH_VARARGS, pack__doc__},
  1249.     {"unpack",    struct_unpack,        METH_VARARGS, unpack__doc__},
  1250.     {NULL,        NULL}        /* sentinel */
  1251. };
  1252.  
  1253.  
  1254. /* Module initialization */
  1255.  
  1256. DL_EXPORT(void)
  1257. initstruct(void)
  1258. {
  1259.     PyObject *m, *d;
  1260.  
  1261.     /* Create the module and add the functions */
  1262.     m = Py_InitModule4("struct", struct_methods, struct__doc__,
  1263.                (PyObject*)NULL, PYTHON_API_VERSION);
  1264.  
  1265.     /* Add some symbolic constants to the module */
  1266.     d = PyModule_GetDict(m);
  1267.     StructError = PyErr_NewException("struct.error", NULL, NULL);
  1268.     if (StructError == NULL)
  1269.         return;
  1270.     PyDict_SetItemString(d, "error", StructError);
  1271. }
  1272.