home *** CD-ROM | disk | FTP | other *** search
/ Celestin Apprentice 7 / Apprentice-Release7.iso / Source Code / C / Applications / Python 1.4 / Python 1.4 source / Objects / stringobject.c < prev    next >
Encoding:
C/C++ Source or Header  |  1996-10-28  |  19.6 KB  |  931 lines  |  [TEXT/CWIE]

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