home *** CD-ROM | disk | FTP | other *** search
/ Big Green CD 8 / BGCD_8_Dev.iso / OPENSTEP / Languages / Python / python-14-src / Objects / stringobject.c < prev    next >
Encoding:
C/C++ Source or Header  |  1997-01-17  |  19.6 KB  |  930 lines

  1. /***********************************************************
  2. Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam,
  3. The Netherlands.
  4.  
  5.                         All Rights Reserved
  6.  
  7. Permission to use, copy, modify, and distribute this software and its
  8. documentation for any purpose and without fee is hereby granted,
  9. provided that the above copyright notice appear in all copies and that
  10. both that copyright notice and this permission notice appear in
  11. supporting documentation, and that the names of Stichting Mathematisch
  12. Centrum or CWI or Corporation for National Research Initiatives or
  13. CNRI not be used in advertising or publicity pertaining to
  14. distribution of the software without specific, written prior
  15. permission.
  16.  
  17. While CWI is the initial source for this software, a modified version
  18. is made available by the Corporation for National Research Initiatives
  19. (CNRI) at the Internet address ftp://ftp.python.org.
  20.  
  21. STICHTING MATHEMATISCH CENTRUM AND CNRI DISCLAIM ALL WARRANTIES WITH
  22. REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF
  23. MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH
  24. CENTRUM OR CNRI BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
  25. DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
  26. PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  27. TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  28. PERFORMANCE OF THIS SOFTWARE.
  29.  
  30. ******************************************************************/
  31.  
  32. /* String object implementation */
  33.  
  34. #include "allobjects.h"
  35. #include "myctype.h"
  36.  
  37. #ifdef COUNT_ALLOCS
  38. int null_strings, one_strings;
  39. #endif
  40.  
  41. #ifdef HAVE_LIMITS_H
  42. #include <limits.h>
  43. #else
  44. #ifndef UCHAR_MAX
  45. #define UCHAR_MAX 255
  46. #endif
  47. #endif
  48.  
  49. static stringobject *characters[UCHAR_MAX + 1];
  50. #ifndef DONT_SHARE_SHORT_STRINGS
  51. static stringobject *nullstring;
  52. #endif
  53.  
  54. /*
  55.    Newsizedstringobject() and newstringobject() try in certain cases
  56.    to share string objects.  When the size of the string is zero,
  57.    these routines always return a pointer to the same string object;
  58.    when the size is one, they return a pointer to an already existing
  59.    object if the contents of the string is known.  For
  60.    newstringobject() this is always the case, for
  61.    newsizedstringobject() this is the case when the first argument in
  62.    not NULL.
  63.    A common practice to allocate a string and then fill it in or
  64.    change it must be done carefully.  It is only allowed to change the
  65.    contents of the string if the obect was gotten from
  66.    newsizedstringobject() with a NULL first argument, because in the
  67.    future these routines may try to do even more sharing of objects.
  68. */
  69. object *
  70. newsizedstringobject(str, size)
  71.     char *str;
  72.     int size;
  73. {
  74.     register stringobject *op;
  75. #ifndef DONT_SHARE_SHORT_STRINGS
  76.     if (size == 0 && (op = nullstring) != NULL) {
  77. #ifdef COUNT_ALLOCS
  78.         null_strings++;
  79. #endif
  80.         INCREF(op);
  81.         return (object *)op;
  82.     }
  83.     if (size == 1 && str != NULL && (op = characters[*str & UCHAR_MAX]) != NULL) {
  84. #ifdef COUNT_ALLOCS
  85.         one_strings++;
  86. #endif
  87.         INCREF(op);
  88.         return (object *)op;
  89.     }
  90. #endif /* DONT_SHARE_SHORT_STRINGS */
  91.     op = (stringobject *)
  92.         malloc(sizeof(stringobject) + size * sizeof(char));
  93.     if (op == NULL)
  94.         return err_nomem();
  95.     op->ob_type = &Stringtype;
  96.     op->ob_size = size;
  97. #ifdef CACHE_HASH
  98.     op->ob_shash = -1;
  99. #endif
  100.     NEWREF(op);
  101.     if (str != NULL)
  102.         memcpy(op->ob_sval, str, size);
  103.     op->ob_sval[size] = '\0';
  104. #ifndef DONT_SHARE_SHORT_STRINGS
  105.     if (size == 0) {
  106.         nullstring = op;
  107.         INCREF(op);
  108.     } else if (size == 1 && str != NULL) {
  109.         characters[*str & UCHAR_MAX] = op;
  110.         INCREF(op);
  111.     }
  112. #endif
  113.     return (object *) op;
  114. }
  115.  
  116. object *
  117. newstringobject(str)
  118.     char *str;
  119. {
  120.     register unsigned int size = strlen(str);
  121.     register stringobject *op;
  122. #ifndef DONT_SHARE_SHORT_STRINGS
  123.     if (size == 0 && (op = nullstring) != NULL) {
  124. #ifdef COUNT_ALLOCS
  125.         null_strings++;
  126. #endif
  127.         INCREF(op);
  128.         return (object *)op;
  129.     }
  130.     if (size == 1 && (op = characters[*str & UCHAR_MAX]) != NULL) {
  131. #ifdef COUNT_ALLOCS
  132.         one_strings++;
  133. #endif
  134.         INCREF(op);
  135.         return (object *)op;
  136.     }
  137. #endif /* DONT_SHARE_SHORT_STRINGS */
  138.     op = (stringobject *)
  139.         malloc(sizeof(stringobject) + size * sizeof(char));
  140.     if (op == NULL)
  141.         return err_nomem();
  142.     op->ob_type = &Stringtype;
  143.     op->ob_size = size;
  144. #ifdef CACHE_HASH
  145.     op->ob_shash = -1;
  146. #endif
  147.     NEWREF(op);
  148.     strcpy(op->ob_sval, str);
  149. #ifndef DONT_SHARE_SHORT_STRINGS
  150.     if (size == 0) {
  151.         nullstring = op;
  152.         INCREF(op);
  153.     } else if (size == 1) {
  154.         characters[*str & UCHAR_MAX] = op;
  155.         INCREF(op);
  156.     }
  157. #endif
  158.     return (object *) op;
  159. }
  160.  
  161. static void
  162. string_dealloc(op)
  163.     object *op;
  164. {
  165.     DEL(op);
  166. }
  167.  
  168. int
  169. getstringsize(op)
  170.     register object *op;
  171. {
  172.     if (!is_stringobject(op)) {
  173.         err_badcall();
  174.         return -1;
  175.     }
  176.     return ((stringobject *)op) -> ob_size;
  177. }
  178.  
  179. /*const*/ char *
  180. getstringvalue(op)
  181.     register object *op;
  182. {
  183.     if (!is_stringobject(op)) {
  184.         err_badcall();
  185.         return NULL;
  186.     }
  187.     return ((stringobject *)op) -> ob_sval;
  188. }
  189.  
  190. /* Methods */
  191.  
  192. static int
  193. string_print(op, fp, flags)
  194.     stringobject *op;
  195.     FILE *fp;
  196.     int flags;
  197. {
  198.     int i;
  199.     char c;
  200.     int quote;
  201.     /* XXX Ought to check for interrupts when writing long strings */
  202.     if (flags & PRINT_RAW) {
  203.         fwrite(op->ob_sval, 1, (int) op->ob_size, fp);
  204.         return 0;
  205.     }
  206.  
  207.     /* figure out which quote to use; single is prefered */
  208.     quote = '\'';
  209.     if (strchr(op->ob_sval, '\'') && !strchr(op->ob_sval, '"'))
  210.         quote = '"';
  211.  
  212.     fputc(quote, fp);
  213.     for (i = 0; i < op->ob_size; i++) {
  214.         c = op->ob_sval[i];
  215.         if (c == quote || c == '\\')
  216.             fprintf(fp, "\\%c", c);
  217.         else if (c < ' ' || c >= 0177)
  218.             fprintf(fp, "\\%03o", c & 0377);
  219.         else
  220.             fputc(c, fp);
  221.     }
  222.     fputc(quote, fp);
  223.     return 0;
  224. }
  225.  
  226. static object *
  227. string_repr(op)
  228.     register stringobject *op;
  229. {
  230.     /* XXX overflow? */
  231.     int newsize = 2 + 4 * op->ob_size * sizeof(char);
  232.     object *v = newsizedstringobject((char *)NULL, newsize);
  233.     if (v == NULL) {
  234.         return NULL;
  235.     }
  236.     else {
  237.         register int i;
  238.         register char c;
  239.         register char *p;
  240.         int quote;
  241.  
  242.         /* figure out which quote to use; single is prefered */
  243.         quote = '\'';
  244.         if (strchr(op->ob_sval, '\'') && !strchr(op->ob_sval, '"'))
  245.             quote = '"';
  246.  
  247.         p = ((stringobject *)v)->ob_sval;
  248.         *p++ = quote;
  249.         for (i = 0; i < op->ob_size; i++) {
  250.             c = op->ob_sval[i];
  251.             if (c == quote || c == '\\')
  252.                 *p++ = '\\', *p++ = c;
  253.             else if (c < ' ' || c >= 0177) {
  254.                 sprintf(p, "\\%03o", c & 0377);
  255.                 while (*p != '\0')
  256.                     p++;
  257.             }
  258.             else
  259.                 *p++ = c;
  260.         }
  261.         *p++ = quote;
  262.         *p = '\0';
  263.         resizestring(&v, (int) (p - ((stringobject *)v)->ob_sval));
  264.         return v;
  265.     }
  266. }
  267.  
  268. static int
  269. string_length(a)
  270.     stringobject *a;
  271. {
  272.     return a->ob_size;
  273. }
  274.  
  275. static object *
  276. string_concat(a, bb)
  277.     register stringobject *a;
  278.     register object *bb;
  279. {
  280.     register unsigned int size;
  281.     register stringobject *op;
  282.     if (!is_stringobject(bb)) {
  283.         err_badarg();
  284.         return NULL;
  285.     }
  286. #define b ((stringobject *)bb)
  287.     /* Optimize cases with empty left or right operand */
  288.     if (a->ob_size == 0) {
  289.         INCREF(bb);
  290.         return bb;
  291.     }
  292.     if (b->ob_size == 0) {
  293.         INCREF(a);
  294.         return (object *)a;
  295.     }
  296.     size = a->ob_size + b->ob_size;
  297.     op = (stringobject *)
  298.         malloc(sizeof(stringobject) + size * sizeof(char));
  299.     if (op == NULL)
  300.         return err_nomem();
  301.     op->ob_type = &Stringtype;
  302.     op->ob_size = size;
  303. #ifdef CACHE_HASH
  304.     op->ob_shash = -1;
  305. #endif
  306.     NEWREF(op);
  307.     memcpy(op->ob_sval, a->ob_sval, (int) a->ob_size);
  308.     memcpy(op->ob_sval + a->ob_size, b->ob_sval, (int) b->ob_size);
  309.     op->ob_sval[size] = '\0';
  310.     return (object *) op;
  311. #undef b
  312. }
  313.  
  314. static object *
  315. string_repeat(a, n)
  316.     register stringobject *a;
  317.     register int n;
  318. {
  319.     register int i;
  320.     register unsigned int size;
  321.     register stringobject *op;
  322.     if (n < 0)
  323.         n = 0;
  324.     size = a->ob_size * n;
  325.     if (size == a->ob_size) {
  326.         INCREF(a);
  327.         return (object *)a;
  328.     }
  329.     op = (stringobject *)
  330.         malloc(sizeof(stringobject) + size * sizeof(char));
  331.     if (op == NULL)
  332.         return err_nomem();
  333.     op->ob_type = &Stringtype;
  334.     op->ob_size = size;
  335. #ifdef CACHE_HASH
  336.     op->ob_shash = -1;
  337. #endif
  338.     NEWREF(op);
  339.     for (i = 0; i < size; i += a->ob_size)
  340.         memcpy(op->ob_sval+i, a->ob_sval, (int) a->ob_size);
  341.     op->ob_sval[size] = '\0';
  342.     return (object *) op;
  343. }
  344.  
  345. /* String slice a[i:j] consists of characters a[i] ... a[j-1] */
  346.  
  347. static object *
  348. string_slice(a, i, j)
  349.     register stringobject *a;
  350.     register int i, j; /* May be negative! */
  351. {
  352.     if (i < 0)
  353.         i = 0;
  354.     if (j < 0)
  355.         j = 0; /* Avoid signed/unsigned bug in next line */
  356.     if (j > a->ob_size)
  357.         j = a->ob_size;
  358.     if (i == 0 && j == a->ob_size) { /* It's the same as a */
  359.         INCREF(a);
  360.         return (object *)a;
  361.     }
  362.     if (j < i)
  363.         j = i;
  364.     return newsizedstringobject(a->ob_sval + i, (int) (j-i));
  365. }
  366.  
  367. static object *
  368. string_item(a, i)
  369.     stringobject *a;
  370.     register int i;
  371. {
  372.     int c;
  373.     object *v;
  374.     if (i < 0 || i >= a->ob_size) {
  375.         err_setstr(IndexError, "string index out of range");
  376.         return NULL;
  377.     }
  378.     c = a->ob_sval[i] & UCHAR_MAX;
  379.     v = (object *) characters[c];
  380. #ifdef COUNT_ALLOCS
  381.     if (v != NULL)
  382.         one_strings++;
  383. #endif
  384.     if (v == NULL) {
  385.         v = newsizedstringobject((char *)NULL, 1);
  386.         if (v == NULL)
  387.             return NULL;
  388.         characters[c] = (stringobject *) v;
  389.         ((stringobject *)v)->ob_sval[0] = c;
  390.     }
  391.     INCREF(v);
  392.     return v;
  393. }
  394.  
  395. static int
  396. string_compare(a, b)
  397.     stringobject *a, *b;
  398. {
  399.     int len_a = a->ob_size, len_b = b->ob_size;
  400.     int min_len = (len_a < len_b) ? len_a : len_b;
  401.     int cmp;
  402.     if (min_len > 0) {
  403.         cmp = Py_CHARMASK(*a->ob_sval) - Py_CHARMASK(*b->ob_sval);
  404.         if (cmp == 0)
  405.             cmp = memcmp(a->ob_sval, b->ob_sval, min_len);
  406.         if (cmp != 0)
  407.             return cmp;
  408.     }
  409.     return (len_a < len_b) ? -1 : (len_a > len_b) ? 1 : 0;
  410. }
  411.  
  412. static long
  413. string_hash(a)
  414.     stringobject *a;
  415. {
  416.     register int len;
  417.     register unsigned char *p;
  418.     register long x;
  419.  
  420. #ifdef CACHE_HASH
  421.     if (a->ob_shash != -1)
  422.         return a->ob_shash;
  423. #endif
  424.     len = a->ob_size;
  425.     p = (unsigned char *) a->ob_sval;
  426.     x = *p << 7;
  427.     while (--len >= 0)
  428.         x = (1000003*x) ^ *p++;
  429.     x ^= a->ob_size;
  430.     if (x == -1)
  431.         x = -2;
  432. #ifdef CACHE_HASH
  433.     a->ob_shash = x;
  434. #endif
  435.     return x;
  436. }
  437.  
  438. static sequence_methods string_as_sequence = {
  439.     (inquiry)string_length, /*sq_length*/
  440.     (binaryfunc)string_concat, /*sq_concat*/
  441.     (intargfunc)string_repeat, /*sq_repeat*/
  442.     (intargfunc)string_item, /*sq_item*/
  443.     (intintargfunc)string_slice, /*sq_slice*/
  444.     0,        /*sq_ass_item*/
  445.     0,        /*sq_ass_slice*/
  446. };
  447.  
  448. typeobject Stringtype = {
  449.     OB_HEAD_INIT(&Typetype)
  450.     0,
  451.     "string",
  452.     sizeof(stringobject),
  453.     sizeof(char),
  454.     (destructor)string_dealloc, /*tp_dealloc*/
  455.     (printfunc)string_print, /*tp_print*/
  456.     0,        /*tp_getattr*/
  457.     0,        /*tp_setattr*/
  458.     (cmpfunc)string_compare, /*tp_compare*/
  459.     (reprfunc)string_repr, /*tp_repr*/
  460.     0,        /*tp_as_number*/
  461.     &string_as_sequence,    /*tp_as_sequence*/
  462.     0,        /*tp_as_mapping*/
  463.     (hashfunc)string_hash, /*tp_hash*/
  464. };
  465.  
  466. void
  467. joinstring(pv, w)
  468.     register object **pv;
  469.     register object *w;
  470. {
  471.     register object *v;
  472.     if (*pv == NULL)
  473.         return;
  474.     if (w == NULL || !is_stringobject(*pv)) {
  475.         DECREF(*pv);
  476.         *pv = NULL;
  477.         return;
  478.     }
  479.     v = string_concat((stringobject *) *pv, w);
  480.     DECREF(*pv);
  481.     *pv = v;
  482. }
  483.  
  484. void
  485. joinstring_decref(pv, w)
  486.     register object **pv;
  487.     register object *w;
  488. {
  489.     joinstring(pv, w);
  490.     XDECREF(w);
  491. }
  492.  
  493.  
  494. /* The following function breaks the notion that strings are immutable:
  495.    it changes the size of a string.  We get away with this only if there
  496.    is only one module referencing the object.  You can also think of it
  497.    as creating a new string object and destroying the old one, only
  498.    more efficiently.  In any case, don't use this if the string may
  499.    already be known to some other part of the code... */
  500.  
  501. int
  502. resizestring(pv, newsize)
  503.     object **pv;
  504.     int newsize;
  505. {
  506.     register object *v;
  507.     register stringobject *sv;
  508.     v = *pv;
  509.     if (!is_stringobject(v) || v->ob_refcnt != 1) {
  510.         *pv = 0;
  511.         DECREF(v);
  512.         err_badcall();
  513.         return -1;
  514.     }
  515.     /* XXX UNREF/NEWREF interface should be more symmetrical */
  516. #ifdef Py_REF_DEBUG
  517.     --_Py_RefTotal;
  518. #endif
  519.     UNREF(v);
  520.     *pv = (object *)
  521.         realloc((char *)v,
  522.             sizeof(stringobject) + newsize * sizeof(char));
  523.     if (*pv == NULL) {
  524.         DEL(v);
  525.         err_nomem();
  526.         return -1;
  527.     }
  528.     NEWREF(*pv);
  529.     sv = (stringobject *) *pv;
  530.     sv->ob_size = newsize;
  531.     sv->ob_sval[newsize] = '\0';
  532.     return 0;
  533. }
  534.  
  535. /* Helpers for formatstring */
  536.  
  537. static object *
  538. getnextarg(args, arglen, p_argidx)
  539.     object *args;
  540.     int arglen;
  541.     int *p_argidx;
  542. {
  543.     int argidx = *p_argidx;
  544.     if (argidx < arglen) {
  545.         (*p_argidx)++;
  546.         if (arglen < 0)
  547.             return args;
  548.         else
  549.             return gettupleitem(args, argidx);
  550.     }
  551.     err_setstr(TypeError, "not enough arguments for format string");
  552.     return NULL;
  553. }
  554.  
  555. #define F_LJUST (1<<0)
  556. #define F_SIGN    (1<<1)
  557. #define F_BLANK (1<<2)
  558. #define F_ALT    (1<<3)
  559. #define F_ZERO    (1<<4)
  560.  
  561. extern double fabs PROTO((double));
  562.  
  563. static char *
  564. formatfloat(flags, prec, type, v)
  565.     int flags;
  566.     int prec;
  567.     int type;
  568.     object *v;
  569. {
  570.     char fmt[20];
  571.     static char buf[120];
  572.     double x;
  573.     if (!getargs(v, "d;float argument required", &x))
  574.         return NULL;
  575.     if (prec < 0)
  576.         prec = 6;
  577.     if (prec > 50)
  578.         prec = 50; /* Arbitrary limitation */
  579.     if (type == 'f' && fabs(x)/1e25 >= 1e25)
  580.         type = 'g';
  581.     sprintf(fmt, "%%%s.%d%c", (flags&F_ALT) ? "#" : "", prec, type);
  582.     sprintf(buf, fmt, x);
  583.     return buf;
  584. }
  585.  
  586. static char *
  587. formatint(flags, prec, type, v)
  588.     int flags;
  589.     int prec;
  590.     int type;
  591.     object *v;
  592. {
  593.     char fmt[20];
  594.     static char buf[50];
  595.     long x;
  596.     if (!getargs(v, "l;int argument required", &x))
  597.         return NULL;
  598.     if (prec < 0)
  599.         prec = 1;
  600.     sprintf(fmt, "%%%s.%dl%c", (flags&F_ALT) ? "#" : "", prec, type);
  601.     sprintf(buf, fmt, x);
  602.     return buf;
  603. }
  604.  
  605. static char *
  606. formatchar(v)
  607.     object *v;
  608. {
  609.     static char buf[2];
  610.     if (is_stringobject(v)) {
  611.         if (!getargs(v, "c;%c requires int or char", &buf[0]))
  612.             return NULL;
  613.     }
  614.     else {
  615.         if (!getargs(v, "b;%c requires int or char", &buf[0]))
  616.             return NULL;
  617.     }
  618.     buf[1] = '\0';
  619.     return buf;
  620. }
  621.  
  622.  
  623. /* fmt%(v1,v2,...) is roughly equivalent to sprintf(fmt, v1, v2, ...) */
  624.  
  625. object *
  626. formatstring(format, args)
  627.     object *format;
  628.     object *args;
  629. {
  630.     char *fmt, *res;
  631.     int fmtcnt, rescnt, reslen, arglen, argidx;
  632.     int args_owned = 0;
  633.     object *result;
  634.     object *dict = NULL;
  635.     if (format == NULL || !is_stringobject(format) || args == NULL) {
  636.         err_badcall();
  637.         return NULL;
  638.     }
  639.     fmt = getstringvalue(format);
  640.     fmtcnt = getstringsize(format);
  641.     reslen = rescnt = fmtcnt + 100;
  642.     result = newsizedstringobject((char *)NULL, reslen);
  643.     if (result == NULL)
  644.         return NULL;
  645.     res = getstringvalue(result);
  646.     if (is_tupleobject(args)) {
  647.         arglen = gettuplesize(args);
  648.         argidx = 0;
  649.     }
  650.     else {
  651.         arglen = -1;
  652.         argidx = -2;
  653.     }
  654.     if (args->ob_type->tp_as_mapping)
  655.         dict = args;
  656.     while (--fmtcnt >= 0) {
  657.         if (*fmt != '%') {
  658.             if (--rescnt < 0) {
  659.                 rescnt = fmtcnt + 100;
  660.                 reslen += rescnt;
  661.                 if (resizestring(&result, reslen) < 0)
  662.                     return NULL;
  663.                 res = getstringvalue(result) + reslen - rescnt;
  664.                 --rescnt;
  665.             }
  666.             *res++ = *fmt++;
  667.         }
  668.         else {
  669.             /* Got a format specifier */
  670.             int flags = 0;
  671.             char *fmtstart = fmt++;
  672.             int width = -1;
  673.             int prec = -1;
  674.             int size = 0;
  675.             int c = '\0';
  676.             int fill;
  677.             object *v;
  678.             object *temp = NULL;
  679.             char *buf;
  680.             int sign;
  681.             int len;
  682.             if (*fmt == '(') {
  683.                 char *keystart;
  684.                 int keylen;
  685.                 object *key;
  686.  
  687.                 if (dict == NULL) {
  688.                     err_setstr(TypeError,
  689.                          "format requires a mapping"); 
  690.                     goto error;
  691.                 }
  692.                 ++fmt;
  693.                 --fmtcnt;
  694.                 keystart = fmt;
  695.                 while (--fmtcnt >= 0 && *fmt != ')')
  696.                     fmt++;
  697.                 keylen = fmt - keystart;
  698.                 ++fmt;
  699.                 if (fmtcnt < 0) {
  700.                     err_setstr(ValueError,
  701.                            "incomplete format key");
  702.                     goto error;
  703.                 }
  704.                 key = newsizedstringobject(keystart, keylen);
  705.                 if (key == NULL)
  706.                     goto error;
  707.                 if (args_owned) {
  708.                     DECREF(args);
  709.                     args_owned = 0;
  710.                 }
  711.                 args = PyObject_GetItem(dict, key);
  712.                 DECREF(key);
  713.                 if (args == NULL) {
  714.                     goto error;
  715.                 }
  716.                 args_owned = 1;
  717.                 arglen = -1;
  718.                 argidx = -2;
  719.             }
  720.             while (--fmtcnt >= 0) {
  721.                 switch (c = *fmt++) {
  722.                 case '-': flags |= F_LJUST; continue;
  723.                 case '+': flags |= F_SIGN; continue;
  724.                 case ' ': flags |= F_BLANK; continue;
  725.                 case '#': flags |= F_ALT; continue;
  726.                 case '0': flags |= F_ZERO; continue;
  727.                 }
  728.                 break;
  729.             }
  730.             if (c == '*') {
  731.                 v = getnextarg(args, arglen, &argidx);
  732.                 if (v == NULL)
  733.                     goto error;
  734.                 if (!is_intobject(v)) {
  735.                     err_setstr(TypeError, "* wants int");
  736.                     goto error;
  737.                 }
  738.                 width = getintvalue(v);
  739.                 if (width < 0)
  740.                     width = 0;
  741.                 if (--fmtcnt >= 0)
  742.                     c = *fmt++;
  743.             }
  744.             else if (c >= 0 && isdigit(c)) {
  745.                 width = c - '0';
  746.                 while (--fmtcnt >= 0) {
  747.                     c = Py_CHARMASK(*fmt++);
  748.                     if (!isdigit(c))
  749.                         break;
  750.                     if ((width*10) / 10 != width) {
  751.                         err_setstr(ValueError,
  752.                                "width too big");
  753.                         goto error;
  754.                     }
  755.                     width = width*10 + (c - '0');
  756.                 }
  757.             }
  758.             if (c == '.') {
  759.                 prec = 0;
  760.                 if (--fmtcnt >= 0)
  761.                     c = *fmt++;
  762.                 if (c == '*') {
  763.                     v = getnextarg(args, arglen, &argidx);
  764.                     if (v == NULL)
  765.                         goto error;
  766.                     if (!is_intobject(v)) {
  767.                         err_setstr(TypeError,
  768.                                "* wants int");
  769.                         goto error;
  770.                     }
  771.                     prec = getintvalue(v);
  772.                     if (prec < 0)
  773.                         prec = 0;
  774.                     if (--fmtcnt >= 0)
  775.                         c = *fmt++;
  776.                 }
  777.                 else if (c >= 0 && isdigit(c)) {
  778.                     prec = c - '0';
  779.                     while (--fmtcnt >= 0) {
  780.                         c = Py_CHARMASK(*fmt++);
  781.                         if (!isdigit(c))
  782.                             break;
  783.                         if ((prec*10) / 10 != prec) {
  784.                             err_setstr(ValueError,
  785.                                 "prec too big");
  786.                             goto error;
  787.                         }
  788.                         prec = prec*10 + (c - '0');
  789.                     }
  790.                 }
  791.             } /* prec */
  792.             if (fmtcnt >= 0) {
  793.                 if (c == 'h' || c == 'l' || c == 'L') {
  794.                     size = c;
  795.                     if (--fmtcnt >= 0)
  796.                         c = *fmt++;
  797.                 }
  798.             }
  799.             if (fmtcnt < 0) {
  800.                 err_setstr(ValueError, "incomplete format");
  801.                 goto error;
  802.             }
  803.             if (c != '%') {
  804.                 v = getnextarg(args, arglen, &argidx);
  805.                 if (v == NULL)
  806.                     goto error;
  807.             }
  808.             sign = 0;
  809.             fill = ' ';
  810.             switch (c) {
  811.             case '%':
  812.                 buf = "%";
  813.                 len = 1;
  814.                 break;
  815.             case 's':
  816.                 temp = strobject(v);
  817.                 if (temp == NULL)
  818.                     goto error;
  819.                 buf = getstringvalue(temp);
  820.                 len = getstringsize(temp);
  821.                 if (prec >= 0 && len > prec)
  822.                     len = prec;
  823.                 break;
  824.             case 'i':
  825.             case 'd':
  826.             case 'u':
  827.             case 'o':
  828.             case 'x':
  829.             case 'X':
  830.                 if (c == 'i')
  831.                     c = 'd';
  832.                 buf = formatint(flags, prec, c, v);
  833.                 if (buf == NULL)
  834.                     goto error;
  835.                 len = strlen(buf);
  836.                 sign = (c == 'd');
  837.                 if (flags&F_ZERO)
  838.                     fill = '0';
  839.                 break;
  840.             case 'e':
  841.             case 'E':
  842.             case 'f':
  843.             case 'g':
  844.             case 'G':
  845.                 buf = formatfloat(flags, prec, c, v);
  846.                 if (buf == NULL)
  847.                     goto error;
  848.                 len = strlen(buf);
  849.                 sign = 1;
  850.                 if (flags&F_ZERO)
  851.                     fill = '0';
  852.                 break;
  853.             case 'c':
  854.                 buf = formatchar(v);
  855.                 if (buf == NULL)
  856.                     goto error;
  857.                 len = 1;
  858.                 break;
  859.             default:
  860.                 err_setstr(ValueError,
  861.                        "unsupported format character");
  862.                 goto error;
  863.             }
  864.             if (sign) {
  865.                 if (*buf == '-' || *buf == '+') {
  866.                     sign = *buf++;
  867.                     len--;
  868.                 }
  869.                 else if (flags & F_SIGN)
  870.                     sign = '+';
  871.                 else if (flags & F_BLANK)
  872.                     sign = ' ';
  873.                 else
  874.                     sign = '\0';
  875.             }
  876.             if (width < len)
  877.                 width = len;
  878.             if (rescnt < width + (sign != '\0')) {
  879.                 reslen -= rescnt;
  880.                 rescnt = width + fmtcnt + 100;
  881.                 reslen += rescnt;
  882.                 if (resizestring(&result, reslen) < 0)
  883.                     return NULL;
  884.                 res = getstringvalue(result) + reslen - rescnt;
  885.             }
  886.             if (sign) {
  887.                 if (fill != ' ')
  888.                     *res++ = sign;
  889.                 rescnt--;
  890.                 if (width > len)
  891.                     width--;
  892.             }
  893.             if (width > len && !(flags&F_LJUST)) {
  894.                 do {
  895.                     --rescnt;
  896.                     *res++ = fill;
  897.                 } while (--width > len);
  898.             }
  899.             if (sign && fill == ' ')
  900.                 *res++ = sign;
  901.             memcpy(res, buf, len);
  902.             res += len;
  903.             rescnt -= len;
  904.             while (--width >= len) {
  905.                 --rescnt;
  906.                 *res++ = ' ';
  907.             }
  908.                         if (dict && (argidx < arglen) && c != '%') {
  909.                                 err_setstr(TypeError,
  910.                                            "not all arguments converted");
  911.                                 goto error;
  912.                         }
  913.             XDECREF(temp);
  914.         } /* '%' */
  915.     } /* until end */
  916.     if (argidx < arglen && !dict) {
  917.         err_setstr(TypeError, "not all arguments converted");
  918.         goto error;
  919.     }
  920.     if (args_owned)
  921.         DECREF(args);
  922.     resizestring(&result, reslen - rescnt);
  923.     return result;
  924.  error:
  925.     DECREF(result);
  926.     if (args_owned)
  927.         DECREF(args);
  928.     return NULL;
  929. }
  930.