home *** CD-ROM | disk | FTP | other *** search
/ linuxmafia.com 2016 / linuxmafia.com.tar / linuxmafia.com / pub / palmos / pippy-0.6beta-src.tar.gz / pippy-0.6beta-src.tar / pippy-0.6beta-src / src / Objects / stringobject.c < prev    next >
C/C++ Source or Header  |  2000-12-21  |  49KB  |  2,228 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 "Python.h"
  35. #include "other/stringobject_c.h"
  36.  
  37. #include "mymath.h"
  38. #include <ctype.h>
  39.  
  40. #ifdef COUNT_ALLOCS
  41. int null_strings, one_strings;
  42. #endif
  43.  
  44. #ifdef HAVE_LIMITS_H
  45. #include <limits.h>
  46. #else
  47. #ifndef UCHAR_MAX
  48. #define UCHAR_MAX 255
  49. #endif
  50. #endif
  51.  
  52. #ifndef DONT_SHARE_SHORT_STRINGS
  53. static PyStringObject *characters[UCHAR_MAX + 1];
  54. static PyStringObject *nullstring;
  55. #endif
  56.  
  57. /*
  58.    Newsizedstringobject() and newstringobject() try in certain cases
  59.    to share string objects.  When the size of the string is zero,
  60.    these routines always return a pointer to the same string object;
  61.    when the size is one, they return a pointer to an already existing
  62.    object if the contents of the string is known.  For
  63.    newstringobject() this is always the case, for
  64.    newsizedstringobject() this is the case when the first argument in
  65.    not NULL.
  66.    A common practice to allocate a string and then fill it in or
  67.    change it must be done carefully.  It is only allowed to change the
  68.    contents of the string if the obect was gotten from
  69.    newsizedstringobject() with a NULL first argument, because in the
  70.    future these routines may try to do even more sharing of objects.
  71. */
  72. PyObject *
  73. PyString_FromStringAndSize(str, size)
  74.     const char *str;
  75.     int size;
  76. {
  77.     register PyStringObject *op;
  78. #ifndef DONT_SHARE_SHORT_STRINGS
  79.     if (size == 0 && (op = nullstring) != NULL) {
  80. #ifdef COUNT_ALLOCS
  81.         null_strings++;
  82. #endif
  83.         Py_INCREF(op);
  84.         return (PyObject *)op;
  85.     }
  86.     if (size == 1 && str != NULL &&
  87.         (op = characters[*str & UCHAR_MAX]) != NULL)
  88.     {
  89. #ifdef COUNT_ALLOCS
  90.         one_strings++;
  91. #endif
  92.         Py_INCREF(op);
  93.         return (PyObject *)op;
  94.     }
  95. #endif /* DONT_SHARE_SHORT_STRINGS */
  96.     op = (PyStringObject *)
  97.         malloc(sizeof(PyStringObject) + size * sizeof(char));
  98.     if (op == NULL)
  99.         return PyErr_NoMemory();
  100.     op->ob_type = &PyString_Type;
  101.     op->ob_size = size;
  102. #ifdef CACHE_HASH
  103.     op->ob_shash = -1;
  104. #endif
  105. #ifdef INTERN_STRINGS
  106.     op->ob_sinterned = NULL;
  107. #endif
  108.     _Py_NewReference((PyObject *)op);
  109.     if (str != NULL)
  110.         memcpy(op->ob_sval, str, size);
  111.     op->ob_sval[size] = '\0';
  112. #ifndef DONT_SHARE_SHORT_STRINGS
  113.     if (size == 0) {
  114.         nullstring = op;
  115.         Py_INCREF(op);
  116.     } else if (size == 1 && str != NULL) {
  117.         characters[*str & UCHAR_MAX] = op;
  118.         Py_INCREF(op);
  119.     }
  120. #endif
  121.     return (PyObject *) op;
  122. }
  123.  
  124. PyObject *
  125. PyString_FromString(str)
  126.     const char *str;
  127. {
  128.     register unsigned int size = strlen(str);
  129.     register PyStringObject *op;
  130. #ifndef DONT_SHARE_SHORT_STRINGS
  131.     if (size == 0 && (op = nullstring) != NULL) {
  132. #ifdef COUNT_ALLOCS
  133.         null_strings++;
  134. #endif
  135.         Py_INCREF(op);
  136.         return (PyObject *)op;
  137.     }
  138.     if (size == 1 && (op = characters[*str & UCHAR_MAX]) != NULL) {
  139. #ifdef COUNT_ALLOCS
  140.         one_strings++;
  141. #endif
  142.         Py_INCREF(op);
  143.         return (PyObject *)op;
  144.     }
  145. #endif /* DONT_SHARE_SHORT_STRINGS */
  146.     op = (PyStringObject *)
  147.         malloc(sizeof(PyStringObject) + size * sizeof(char));
  148.     if (op == NULL)
  149.         return PyErr_NoMemory();
  150.     op->ob_type = &PyString_Type;
  151.     op->ob_size = size;
  152. #ifdef CACHE_HASH
  153.     op->ob_shash = -1;
  154. #endif
  155. #ifdef INTERN_STRINGS
  156.     op->ob_sinterned = NULL;
  157. #endif
  158.     _Py_NewReference((PyObject *)op);
  159.     strcpy(op->ob_sval, str);
  160. #ifndef DONT_SHARE_SHORT_STRINGS
  161.     if (size == 0) {
  162.         nullstring = op;
  163.         Py_INCREF(op);
  164.     } else if (size == 1) {
  165.         characters[*str & UCHAR_MAX] = op;
  166.         Py_INCREF(op);
  167.     }
  168. #endif
  169.     return (PyObject *) op;
  170. }
  171.  
  172. static void
  173. string_dealloc(op)
  174.     PyObject *op;
  175. {
  176.     PyMem_DEL(op);
  177. }
  178.  
  179. int
  180. PyString_Size(op)
  181.     register PyObject *op;
  182. {
  183.     if (!PyString_Check(op)) {
  184.         PyErr_BadInternalCall();
  185.         return -1;
  186.     }
  187.     return ((PyStringObject *)op) -> ob_size;
  188. }
  189.  
  190. /*const*/ char *
  191. PyString_AsString(op)
  192.     register PyObject *op;
  193. {
  194.     if (!PyString_Check(op)) {
  195.         PyErr_BadInternalCall();
  196.         return NULL;
  197.     }
  198.     return ((PyStringObject *)op) -> ob_sval;
  199. }
  200.  
  201. /* Methods */
  202.  
  203. static int
  204. string_print(op, fp, flags)
  205.     PyStringObject *op;
  206.     FILE *fp;
  207.     int flags;
  208. {
  209.     int i;
  210.     char c;
  211.     int quote;
  212.     /* XXX Ought to check for interrupts when writing long strings */
  213.     if (flags & Py_PRINT_RAW) {
  214.         fwrite(op->ob_sval, 1, (int) op->ob_size, fp);
  215.         return 0;
  216.     }
  217.  
  218.     /* figure out which quote to use; single is prefered */
  219.     quote = '\'';
  220.     if (strchr(op->ob_sval, '\'') && !strchr(op->ob_sval, '"'))
  221.         quote = '"';
  222.  
  223.     fputc(quote, fp);
  224.     for (i = 0; i < op->ob_size; i++) {
  225.         c = op->ob_sval[i];
  226.         if (c == quote || c == '\\')
  227.             fprintf(fp, "\\%c", c);
  228.         else if (c < ' ' || c >= 0177)
  229.             fprintf(fp, "\\%03o", c & 0377);
  230.         else
  231.             fputc(c, fp);
  232.     }
  233.     fputc(quote, fp);
  234.     return 0;
  235. }
  236.  
  237. static PyObject *
  238. string_repr(op)
  239.     register PyStringObject *op;
  240. {
  241.     /* XXX overflow? */
  242.     int newsize = 2 + 4 * op->ob_size * sizeof(char);
  243.     PyObject *v = PyString_FromStringAndSize((char *)NULL, newsize);
  244.     if (v == NULL) {
  245.         return NULL;
  246.     }
  247.     else {
  248.         register int i;
  249.         register char c;
  250.         register char *p;
  251.         int quote;
  252.  
  253.         /* figure out which quote to use; single is prefered */
  254.         quote = '\'';
  255.         if (strchr(op->ob_sval, '\'') && !strchr(op->ob_sval, '"'))
  256.             quote = '"';
  257.  
  258.         p = ((PyStringObject *)v)->ob_sval;
  259.         *p++ = quote;
  260.         for (i = 0; i < op->ob_size; i++) {
  261.             c = op->ob_sval[i];
  262.             if (c == quote || c == '\\')
  263.                 *p++ = '\\', *p++ = c;
  264.             else if (c < ' ' || c >= 0177) {
  265.                 sprintf(p, "\\%03o", c & 0377);
  266.                 while (*p != '\0')
  267.                     p++;
  268.             }
  269.             else
  270.                 *p++ = c;
  271.         }
  272.         *p++ = quote;
  273.         *p = '\0';
  274.         _PyString_Resize(
  275.             &v, (int) (p - ((PyStringObject *)v)->ob_sval));
  276.         return v;
  277.     }
  278. }
  279.  
  280. static int
  281. string_length(a)
  282.     PyStringObject *a;
  283. {
  284.     return a->ob_size;
  285. }
  286.  
  287. static PyObject *
  288. string_concat(a, bb)
  289.     register PyStringObject *a;
  290.     register PyObject *bb;
  291. {
  292.     register unsigned int size;
  293.     register PyStringObject *op;
  294.     if (!PyString_Check(bb)) {
  295.         PyErr_BadArgument();
  296.         return NULL;
  297.     }
  298. #define b ((PyStringObject *)bb)
  299.     /* Optimize cases with empty left or right operand */
  300.     if (a->ob_size == 0) {
  301.         Py_INCREF(bb);
  302.         return bb;
  303.     }
  304.     if (b->ob_size == 0) {
  305.         Py_INCREF(a);
  306.         return (PyObject *)a;
  307.     }
  308.     size = a->ob_size + b->ob_size;
  309.     op = (PyStringObject *)
  310.         malloc(sizeof(PyStringObject) + size * sizeof(char));
  311.     if (op == NULL)
  312.         return PyErr_NoMemory();
  313.     op->ob_type = &PyString_Type;
  314.     op->ob_size = size;
  315. #ifdef CACHE_HASH
  316.     op->ob_shash = -1;
  317. #endif
  318. #ifdef INTERN_STRINGS
  319.     op->ob_sinterned = NULL;
  320. #endif
  321.     _Py_NewReference((PyObject *)op);
  322.     memcpy(op->ob_sval, a->ob_sval, (int) a->ob_size);
  323.     memcpy(op->ob_sval + a->ob_size, b->ob_sval, (int) b->ob_size);
  324.     op->ob_sval[size] = '\0';
  325.     return (PyObject *) op;
  326. #undef b
  327. }
  328.  
  329. static PyObject *
  330. string_repeat(a, n)
  331.     register PyStringObject *a;
  332.     register int n;
  333. {
  334.     register int i;
  335.     register int size;
  336.     register PyStringObject *op;
  337.     if (n < 0)
  338.         n = 0;
  339.     size = a->ob_size * n;
  340.     if (size == a->ob_size) {
  341.         Py_INCREF(a);
  342.         return (PyObject *)a;
  343.     }
  344.     op = (PyStringObject *)
  345.         malloc(sizeof(PyStringObject) + size * sizeof(char));
  346.     if (op == NULL)
  347.         return PyErr_NoMemory();
  348.     op->ob_type = &PyString_Type;
  349.     op->ob_size = size;
  350. #ifdef CACHE_HASH
  351.     op->ob_shash = -1;
  352. #endif
  353. #ifdef INTERN_STRINGS
  354.     op->ob_sinterned = NULL;
  355. #endif
  356.     _Py_NewReference((PyObject *)op);
  357.     for (i = 0; i < size; i += a->ob_size)
  358.         memcpy(op->ob_sval+i, a->ob_sval, (int) a->ob_size);
  359.     op->ob_sval[size] = '\0';
  360.     return (PyObject *) op;
  361. }
  362.  
  363. /* String slice a[i:j] consists of characters a[i] ... a[j-1] */
  364.  
  365. static PyObject *
  366. string_slice(a, i, j)
  367.     register PyStringObject *a;
  368.     register int i, j; /* May be negative! */
  369. {
  370.     if (i < 0)
  371.         i = 0;
  372.     if (j < 0)
  373.         j = 0; /* Avoid signed/unsigned bug in next line */
  374.     if (j > a->ob_size)
  375.         j = a->ob_size;
  376.     if (i == 0 && j == a->ob_size) { /* It's the same as a */
  377.         Py_INCREF(a);
  378.         return (PyObject *)a;
  379.     }
  380.     if (j < i)
  381.         j = i;
  382.     return PyString_FromStringAndSize(a->ob_sval + i, (int) (j-i));
  383. }
  384.  
  385. static int
  386. string_contains(a, el)
  387. PyObject *a, *el;
  388. {
  389.     register char *s, *end;
  390.     register char c;
  391.     if (!PyString_Check(el) || PyString_Size(el) != 1) {
  392.         PyErr_SetString(PyExc_TypeError,
  393.                 "string member test needs char left operand");
  394.         return -1;
  395.     }
  396.     c = PyString_AsString(el)[0];
  397.     s = PyString_AsString(a);
  398.     end = s + PyString_Size(a);
  399.     while (s < end) {
  400.         if (c == *s++)
  401.             return 1;
  402.     }
  403.     return 0;
  404. }
  405.  
  406. static PyObject *
  407. string_item(a, i)
  408.     PyStringObject *a;
  409.     register int i;
  410. {
  411.     int c;
  412.     PyObject *v;
  413.     if (i < 0 || i >= a->ob_size) {
  414.         PyErr_SetString(PyExc_IndexError, "string index out of range");
  415.         return NULL;
  416.     }
  417.     c = a->ob_sval[i] & UCHAR_MAX;
  418. #ifndef DONT_SHARE_SHORT_STRINGS
  419.     v = (PyObject *) characters[c];
  420. #ifdef COUNT_ALLOCS
  421.     if (v != NULL)
  422.         one_strings++;
  423. #endif
  424.     if (v == NULL) {
  425.         v = PyString_FromStringAndSize((char *)NULL, 1);
  426.         if (v == NULL)
  427.             return NULL;
  428.         characters[c] = (PyStringObject *) v;
  429.         ((PyStringObject *)v)->ob_sval[0] = c;
  430.     }
  431. #else 
  432.     v = PyString_FromStringAndSize((char *)NULL, 1);
  433.     if (v == NULL)
  434.         return NULL;
  435.     ((PyStringObject *)v)->ob_sval[0] = c;
  436. #endif /* !DONT_SHARE_SHORT_STRINGS */
  437.  
  438.     Py_INCREF(v);
  439.     return v;
  440. }
  441.  
  442. static int
  443. string_compare(a, b)
  444.     PyStringObject *a, *b;
  445. {
  446.     int len_a = a->ob_size, len_b = b->ob_size;
  447.     int min_len = (len_a < len_b) ? len_a : len_b;
  448.     int cmp;
  449.     if (min_len > 0) {
  450.         cmp = Py_CHARMASK(*a->ob_sval) - Py_CHARMASK(*b->ob_sval);
  451.         if (cmp == 0)
  452.             cmp = memcmp(a->ob_sval, b->ob_sval, min_len);
  453.         if (cmp != 0)
  454.             return cmp;
  455.     }
  456.     return (len_a < len_b) ? -1 : (len_a > len_b) ? 1 : 0;
  457. }
  458.  
  459. static long
  460. string_hash(a)
  461.     PyStringObject *a;
  462. {
  463.     register int len;
  464.     register unsigned char *p;
  465.     register long x;
  466.  
  467. #ifdef CACHE_HASH
  468.     if (a->ob_shash != -1)
  469.         return a->ob_shash;
  470. #ifdef INTERN_STRINGS
  471.     if (a->ob_sinterned != NULL)
  472.         return (a->ob_shash =
  473.             ((PyStringObject *)(a->ob_sinterned))->ob_shash);
  474. #endif
  475. #endif
  476.     len = a->ob_size;
  477.     p = (unsigned char *) a->ob_sval;
  478.     x = *p << 7;
  479.     while (--len >= 0)
  480.         x = (1000003*x) ^ *p++;
  481.     x ^= a->ob_size;
  482.     if (x == -1)
  483.         x = -2;
  484. #ifdef CACHE_HASH
  485.     a->ob_shash = x;
  486. #endif
  487.     return x;
  488. }
  489.  
  490. static int
  491. string_buffer_getreadbuf(self, index, ptr)
  492.     PyStringObject *self;
  493.     int index;
  494.     const void **ptr;
  495. {
  496.     if ( index != 0 ) {
  497.         PyErr_SetString(PyExc_SystemError,
  498.                 "accessing non-existent string segment");
  499.         return -1;
  500.     }
  501.     *ptr = (void *)self->ob_sval;
  502.     return self->ob_size;
  503. }
  504.  
  505. static int
  506. string_buffer_getwritebuf(self, index, ptr)
  507.     PyStringObject *self;
  508.     int index;
  509.     const void **ptr;
  510. {
  511.     PyErr_SetString(PyExc_TypeError,
  512.             "Cannot use string as modifiable buffer");
  513.     return -1;
  514. }
  515.  
  516. static int
  517. string_buffer_getsegcount(self, lenp)
  518.     PyStringObject *self;
  519.     int *lenp;
  520. {
  521.     if ( lenp )
  522.         *lenp = self->ob_size;
  523.     return 1;
  524. }
  525.  
  526. static int
  527. string_buffer_getcharbuf(self, index, ptr)
  528.     PyStringObject *self;
  529.     int index;
  530.     const char **ptr;
  531. {
  532.     if ( index != 0 ) {
  533.         PyErr_SetString(PyExc_SystemError,
  534.                 "accessing non-existent string segment");
  535.         return -1;
  536.     }
  537.     *ptr = self->ob_sval;
  538.     return self->ob_size;
  539. }
  540.  
  541. static PySequenceMethods string_as_sequence = {
  542.     (inquiry)string_length, /*sq_length*/
  543.     (binaryfunc)string_concat, /*sq_concat*/
  544.     (intargfunc)string_repeat, /*sq_repeat*/
  545.     (intargfunc)string_item, /*sq_item*/
  546.     (intintargfunc)string_slice, /*sq_slice*/
  547.     0,        /*sq_ass_item*/
  548.     0,        /*sq_ass_slice*/
  549.     (objobjproc)string_contains /*sq_contains*/
  550. };
  551.  
  552. static PyBufferProcs string_as_buffer = {
  553.     (getreadbufferproc)string_buffer_getreadbuf,
  554.     (getwritebufferproc)string_buffer_getwritebuf,
  555.     (getsegcountproc)string_buffer_getsegcount,
  556.     (getcharbufferproc)string_buffer_getcharbuf,
  557. };
  558.  
  559.  
  560.  
  561. #define LEFTSTRIP 0
  562. #define RIGHTSTRIP 1
  563. #define BOTHSTRIP 2
  564.  
  565.  
  566. static PyObject *
  567. split_whitespace(s, len, maxsplit)
  568.     char *s;
  569.     int len;
  570.     int maxsplit;
  571. {
  572.     int i = 0, j, err;
  573.     int countsplit = 0;
  574.     PyObject* item;
  575.     PyObject *list = PyList_New(0);
  576.  
  577.     if (list == NULL)
  578.         return NULL;
  579.  
  580.     while (i < len) {
  581.         while (i < len && isspace(Py_CHARMASK(s[i]))) {
  582.             i = i+1;
  583.         }
  584.         j = i;
  585.         while (i < len && !isspace(Py_CHARMASK(s[i]))) {
  586.             i = i+1;
  587.         }
  588.         if (j < i) {
  589.             item = PyString_FromStringAndSize(s+j, (int)(i-j));
  590.             if (item == NULL)
  591.                 goto finally;
  592.  
  593.             err = PyList_Append(list, item);
  594.             Py_DECREF(item);
  595.             if (err < 0)
  596.                 goto finally;
  597.  
  598.             countsplit++;
  599.             while (i < len && isspace(Py_CHARMASK(s[i]))) {
  600.                 i = i+1;
  601.             }
  602.             if (maxsplit && (countsplit >= maxsplit) && i < len) {
  603.                 item = PyString_FromStringAndSize(
  604.                                         s+i, (int)(len - i));
  605.                 if (item == NULL)
  606.                     goto finally;
  607.  
  608.                 err = PyList_Append(list, item);
  609.                 Py_DECREF(item);
  610.                 if (err < 0)
  611.                     goto finally;
  612.  
  613.                 i = len;
  614.             }
  615.         }
  616.     }
  617.     return list;
  618.   finally:
  619.     Py_DECREF(list);
  620.     return NULL;
  621. }
  622.  
  623.  
  624. DEF_DOC(split__doc__,
  625. "S.split([sep [,maxsplit]]) -> list of strings\n\
  626. \n\
  627. Return a list of the words in the string S, using sep as the\n\
  628. delimiter string.  If maxsplit is nonzero, splits into at most\n\
  629. maxsplit words If sep is not specified, any whitespace string\n\
  630. is a separator.  Maxsplit defaults to 0.");
  631.  
  632. static PyObject *
  633. string_split(self, args)
  634.     PyStringObject *self;
  635.     PyObject *args;
  636. {
  637.     int len = PyString_GET_SIZE(self), n, i, j, err;
  638.     int splitcount, maxsplit;
  639.     char *s = PyString_AS_STRING(self), *sub;
  640.     PyObject *list, *item;
  641.  
  642.     sub = NULL;
  643.     n = 0;
  644.     splitcount = 0;
  645.     maxsplit = 0;
  646.     if (!PyArg_ParseTuple(args, "|z#i:split", &sub, &n, &maxsplit))
  647.         return NULL;
  648.     if (sub == NULL)
  649.         return split_whitespace(s, len, maxsplit);
  650.     if (n == 0) {
  651.         PyErr_SetString(PyExc_ValueError, "empty separator");
  652.         return NULL;
  653.     }
  654.  
  655.     list = PyList_New(0);
  656.     if (list == NULL)
  657.         return NULL;
  658.  
  659.     i = j = 0;
  660.     while (i+n <= len) {
  661.         if (s[i] == sub[0] && (n == 1 || memcmp(s+i, sub, n) == 0)) {
  662.             item = PyString_FromStringAndSize(s+j, (int)(i-j));
  663.             if (item == NULL)
  664.                 goto fail;
  665.             err = PyList_Append(list, item);
  666.             Py_DECREF(item);
  667.             if (err < 0)
  668.                 goto fail;
  669.             i = j = i + n;
  670.             splitcount++;
  671.             if (maxsplit && (splitcount >= maxsplit))
  672.                 break;
  673.         }
  674.         else
  675.             i++;
  676.     }
  677.     item = PyString_FromStringAndSize(s+j, (int)(len-j));
  678.     if (item == NULL)
  679.         goto fail;
  680.     err = PyList_Append(list, item);
  681.     Py_DECREF(item);
  682.     if (err < 0)
  683.         goto fail;
  684.  
  685.     return list;
  686.  
  687.  fail:
  688.     Py_DECREF(list);
  689.     return NULL;
  690. }
  691.  
  692.  
  693. DEF_DOC(join__doc__,
  694. "S.join(sequence) -> string\n\
  695. \n\
  696. Return a string which is the concatenation of the string representation\n\
  697. of every element in the sequence.  The separator between elements is S.");
  698.  
  699. static PyObject *
  700. string_join(self, args)
  701.     PyStringObject *self;
  702.     PyObject *args;
  703. {
  704.     char *sep = PyString_AS_STRING(self);
  705.     int seplen = PyString_GET_SIZE(self);
  706.     PyObject *res = NULL;
  707.     int reslen = 0;
  708.     char *p;
  709.     int seqlen = 0;
  710.     int sz = 100;
  711.     int i, slen;
  712.     PyObject *seq;
  713.  
  714.     if (!PyArg_ParseTuple(args, "O:join", &seq))
  715.         return NULL;
  716.  
  717.     seqlen = PySequence_Length(seq);
  718.     if (seqlen < 0 && PyErr_Occurred())
  719.         return NULL;
  720.  
  721.     if (seqlen == 1) {
  722.         /* Optimization if there's only one item */
  723.         PyObject *item = PySequence_GetItem(seq, 0);
  724.         PyObject *stritem = PyObject_Str(item);
  725.         Py_DECREF(item);
  726.         return stritem;
  727.     }
  728.     if (!(res = PyString_FromStringAndSize((char*)NULL, sz)))
  729.         return NULL;
  730.     p = PyString_AsString(res);
  731.  
  732.     /* optimize for lists.  all others (tuples and arbitrary sequences)
  733.      * just use the abstract interface.
  734.      */
  735.     if (PyList_Check(seq)) {
  736.         for (i = 0; i < seqlen; i++) {
  737.             PyObject *item = PyList_GET_ITEM(seq, i);
  738.             PyObject *sitem = PyObject_Str(item);
  739.             if (!sitem)
  740.                 goto finally;
  741.             slen = PyString_GET_SIZE(sitem);
  742.             while (reslen + slen + seplen >= sz) {
  743.                 if (_PyString_Resize(&res, sz*2)) {
  744.                     Py_DECREF(sitem);
  745.                     goto finally;
  746.                 }
  747.                 sz *= 2;
  748.                 p = PyString_AsString(res) + reslen;
  749.             }
  750.             if (i > 0) {
  751.                 memcpy(p, sep, seplen);
  752.                 p += seplen;
  753.                 reslen += seplen;
  754.             }
  755.             memcpy(p, PyString_AS_STRING(sitem), slen);
  756.             Py_DECREF(sitem);
  757.             p += slen;
  758.             reslen += slen;
  759.         }
  760.     }
  761.     else {
  762.         for (i = 0; i < seqlen; i++) {
  763.             PyObject *item = PySequence_GetItem(seq, i);
  764.             PyObject *sitem;
  765.  
  766.             if (!item)
  767.                 goto finally;
  768.             sitem = PyObject_Str(item);
  769.             Py_DECREF(item);
  770.             if (!sitem)
  771.                 goto finally;
  772.  
  773.             slen = PyString_GET_SIZE(sitem);
  774.             while (reslen + slen + seplen >= sz) {
  775.                 if (_PyString_Resize(&res, sz*2)) {
  776.                     Py_DECREF(sitem);
  777.                     goto finally;
  778.                 }
  779.                 sz *= 2;
  780.                 p = PyString_AsString(res) + reslen;
  781.             }
  782.             if (i > 0) {
  783.                 memcpy(p, sep, seplen);
  784.                 p += seplen;
  785.                 reslen += seplen;
  786.             }
  787.             memcpy(p, PyString_AS_STRING(sitem), slen);
  788.             Py_DECREF(sitem);
  789.             p += slen;
  790.             reslen += slen;
  791.         }
  792.     }
  793.     if (_PyString_Resize(&res, reslen))
  794.         goto finally;
  795.     return res;
  796.  
  797.   finally:
  798.     Py_DECREF(res);
  799.     return NULL;
  800. }
  801.  
  802.  
  803.  
  804. static long
  805. string_find_internal(self, args)
  806.     PyStringObject *self;
  807.     PyObject *args;
  808. {
  809.     char *s = PyString_AS_STRING(self), *sub;
  810.     int len = PyString_GET_SIZE(self);
  811.     int n, i = 0, last = INT_MAX;
  812.  
  813.     if (!PyArg_ParseTuple(args, "t#|ii:find", &sub, &n, &i, &last))
  814.         return -2;
  815.  
  816.     if (last > len)
  817.         last = len;
  818.     if (last < 0)
  819.         last += len;
  820.     if (last < 0)
  821.         last = 0;
  822.     if (i < 0)
  823.         i += len;
  824.     if (i < 0)
  825.         i = 0;
  826.  
  827.     if (n == 0 && i <= last)
  828.         return (long)i;
  829.  
  830.     last -= n;
  831.     for (; i <= last; ++i)
  832.         if (s[i] == sub[0] &&
  833.             (n == 1 || memcmp(&s[i+1], &sub[1], n-1) == 0))
  834.             return (long)i;
  835.  
  836.     return -1;
  837. }
  838.  
  839.  
  840. DEF_DOC(find__doc__,
  841. "S.find(sub [,start [,end]]) -> int\n\
  842. \n\
  843. Return the lowest index in S where substring sub is found,\n\
  844. such that sub is contained within s[start,end].  Optional\n\
  845. arguments start and end are interpreted as in slice notation.\n\
  846. \n\
  847. Return -1 on failure.");
  848.  
  849. static PyObject *
  850. string_find(self, args)
  851.     PyStringObject *self;
  852.     PyObject *args;
  853. {
  854.     long result = string_find_internal(self, args);
  855.     if (result == -2)
  856.         return NULL;
  857.     return PyInt_FromLong(result);
  858. }
  859.  
  860.  
  861. DEF_DOC(index__doc__,
  862. "S.index(sub [,start [,end]]) -> int\n\
  863. \n\
  864. Like S.find() but raise ValueError when the substring is not found.");
  865.  
  866. static PyObject *
  867. string_index(self, args)
  868.     PyStringObject *self;
  869.     PyObject *args;
  870. {
  871.     long result = string_find_internal(self, args);
  872.     if (result == -2)
  873.         return NULL;
  874.     if (result == -1) {
  875.         PyErr_SetString(PyExc_ValueError,
  876.                 "substring not found in string.index");
  877.         return NULL;
  878.     }
  879.     return PyInt_FromLong(result);
  880. }
  881.  
  882.  
  883. static long
  884. string_rfind_internal(self, args)
  885.     PyStringObject *self;
  886.     PyObject *args;
  887. {
  888.     char *s = PyString_AS_STRING(self), *sub;
  889.     int len = PyString_GET_SIZE(self), n, j;
  890.     int i = 0, last = INT_MAX;
  891.  
  892.     if (!PyArg_ParseTuple(args, "t#|ii:rfind", &sub, &n, &i, &last))
  893.         return -2;
  894.  
  895.     if (last > len)
  896.         last = len;
  897.     if (last < 0)
  898.         last += len;
  899.     if (last < 0)
  900.         last = 0;
  901.     if (i < 0)
  902.         i += len;
  903.     if (i < 0)
  904.         i = 0;
  905.  
  906.     if (n == 0 && i <= last)
  907.         return (long)last;
  908.  
  909.     for (j = last-n; j >= i; --j)
  910.         if (s[j] == sub[0] &&
  911.             (n == 1 || memcmp(&s[j+1], &sub[1], n-1) == 0))
  912.             return (long)j;
  913.  
  914.     return -1;
  915. }
  916.  
  917.  
  918. DEF_DOC(rfind__doc__,
  919. "S.rfind(sub [,start [,end]]) -> int\n\
  920. \n\
  921. Return the highest index in S where substring sub is found,\n\
  922. such that sub is contained within s[start,end].  Optional\n\
  923. arguments start and end are interpreted as in slice notation.\n\
  924. \n\
  925. Return -1 on failure.");
  926.  
  927. static PyObject *
  928. string_rfind(self, args)
  929.     PyStringObject *self;
  930.     PyObject *args;
  931. {
  932.     long result = string_rfind_internal(self, args);
  933.     if (result == -2)
  934.         return NULL;
  935.     return PyInt_FromLong(result);
  936. }
  937.  
  938.  
  939. DEF_DOC(rindex__doc__,
  940. "S.rindex(sub [,start [,end]]) -> int\n\
  941. \n\
  942. Like S.rfind() but raise ValueError when the substring is not found.");
  943.  
  944. static PyObject *
  945. string_rindex(self, args)
  946.     PyStringObject *self;
  947.     PyObject *args;
  948. {
  949.     long result = string_rfind_internal(self, args);
  950.     if (result == -2)
  951.         return NULL;
  952.     if (result == -1) {
  953.         PyErr_SetString(PyExc_ValueError,
  954.                 "substring not found in string.rindex");
  955.         return NULL;
  956.     }
  957.     return PyInt_FromLong(result);
  958. }
  959.  
  960.  
  961. static PyObject *
  962. do_strip(self, args, striptype)
  963.     PyStringObject *self;
  964.     PyObject *args;
  965.     int striptype;
  966. {
  967.     char *s = PyString_AS_STRING(self);
  968.     int len = PyString_GET_SIZE(self), i, j;
  969.  
  970.     if (!PyArg_ParseTuple(args, ":strip"))
  971.         return NULL;
  972.  
  973.     i = 0;
  974.     if (striptype != RIGHTSTRIP) {
  975.         while (i < len && isspace(Py_CHARMASK(s[i]))) {
  976.             i++;
  977.         }
  978.     }
  979.  
  980.     j = len;
  981.     if (striptype != LEFTSTRIP) {
  982.         do {
  983.             j--;
  984.         } while (j >= i && isspace(Py_CHARMASK(s[j])));
  985.         j++;
  986.     }
  987.  
  988.     if (i == 0 && j == len) {
  989.         Py_INCREF(self);
  990.         return (PyObject*)self;
  991.     }
  992.     else
  993.         return PyString_FromStringAndSize(s+i, j-i);
  994. }
  995.  
  996.  
  997. DEF_DOC(strip__doc__,
  998. "S.strip() -> string\n\
  999. \n\
  1000. Return a copy of the string S with leading and trailing\n\
  1001. whitespace removed.");
  1002.  
  1003. static PyObject *
  1004. string_strip(self, args)
  1005.     PyStringObject *self;
  1006.     PyObject *args;
  1007. {
  1008.     return do_strip(self, args, BOTHSTRIP);
  1009. }
  1010.  
  1011.  
  1012. DEF_DOC(lstrip__doc__,
  1013. "S.lstrip() -> string\n\
  1014. \n\
  1015. Return a copy of the string S with leading whitespace removed.");
  1016.  
  1017. static PyObject *
  1018. string_lstrip(self, args)
  1019.     PyStringObject *self;
  1020.     PyObject *args;
  1021. {
  1022.     return do_strip(self, args, LEFTSTRIP);
  1023. }
  1024.  
  1025.  
  1026. DEF_DOC(rstrip__doc__,
  1027. "S.rstrip() -> string\n\
  1028. \n\
  1029. Return a copy of the string S with trailing whitespace removed.");
  1030.  
  1031. static PyObject *
  1032. string_rstrip(self, args)
  1033.     PyStringObject *self;
  1034.     PyObject *args;
  1035. {
  1036.     return do_strip(self, args, RIGHTSTRIP);
  1037. }
  1038.  
  1039.  
  1040. DEF_DOC(lower__doc__,
  1041. "S.lower() -> string\n\
  1042. \n\
  1043. Return a copy of the string S converted to lowercase.");
  1044.  
  1045. static PyObject *
  1046. string_lower(self, args)
  1047.     PyStringObject *self;
  1048.     PyObject *args;
  1049. {
  1050.     char *s = PyString_AS_STRING(self), *s_new;
  1051.     int i, n = PyString_GET_SIZE(self);
  1052.     PyObject *new;
  1053.  
  1054.     if (!PyArg_ParseTuple(args, ":lower"))
  1055.         return NULL;
  1056.     new = PyString_FromStringAndSize(NULL, n);
  1057.     if (new == NULL)
  1058.         return NULL;
  1059.     s_new = PyString_AsString(new);
  1060.     for (i = 0; i < n; i++) {
  1061.         int c = Py_CHARMASK(*s++);
  1062.         if (isupper(c)) {
  1063.             *s_new = tolower(c);
  1064.         } else
  1065.             *s_new = c;
  1066.         s_new++;
  1067.     }
  1068.     return new;
  1069. }
  1070.  
  1071.  
  1072. DEF_DOC(upper__doc__,
  1073. "S.upper() -> string\n\
  1074. \n\
  1075. Return a copy of the string S converted to uppercase.");
  1076.  
  1077. static PyObject *
  1078. string_upper(self, args)
  1079.     PyStringObject *self;
  1080.     PyObject *args;
  1081. {
  1082.     char *s = PyString_AS_STRING(self), *s_new;
  1083.     int i, n = PyString_GET_SIZE(self);
  1084.     PyObject *new;
  1085.  
  1086.     if (!PyArg_ParseTuple(args, ":upper"))
  1087.         return NULL;
  1088.     new = PyString_FromStringAndSize(NULL, n);
  1089.     if (new == NULL)
  1090.         return NULL;
  1091.     s_new = PyString_AsString(new);
  1092.     for (i = 0; i < n; i++) {
  1093.         int c = Py_CHARMASK(*s++);
  1094.         if (islower(c)) {
  1095.             *s_new = toupper(c);
  1096.         } else
  1097.             *s_new = c;
  1098.         s_new++;
  1099.     }
  1100.     return new;
  1101. }
  1102.  
  1103.  
  1104. DEF_DOC(capitalize__doc__,
  1105. "S.capitalize() -> string\n\
  1106. \n\
  1107. Return a copy of the string S with only its first character\n\
  1108. capitalized.");
  1109.  
  1110. static PyObject *
  1111. string_capitalize(self, args)
  1112.     PyStringObject *self;
  1113.     PyObject *args;
  1114. {
  1115.     char *s = PyString_AS_STRING(self), *s_new;
  1116.     int i, n = PyString_GET_SIZE(self);
  1117.     PyObject *new;
  1118.  
  1119.     if (!PyArg_ParseTuple(args, ":capitalize"))
  1120.         return NULL;
  1121.     new = PyString_FromStringAndSize(NULL, n);
  1122.     if (new == NULL)
  1123.         return NULL;
  1124.     s_new = PyString_AsString(new);
  1125.     if (0 < n) {
  1126.         int c = Py_CHARMASK(*s++);
  1127.         if (islower(c))
  1128.             *s_new = toupper(c);
  1129.         else
  1130.             *s_new = c;
  1131.         s_new++;
  1132.     }
  1133.     for (i = 1; i < n; i++) {
  1134.         int c = Py_CHARMASK(*s++);
  1135.         if (isupper(c))
  1136.             *s_new = tolower(c);
  1137.         else
  1138.             *s_new = c;
  1139.         s_new++;
  1140.     }
  1141.     return new;
  1142. }
  1143.  
  1144.  
  1145. DEF_DOC(count__doc__,
  1146. "S.count(sub[, start[, end]]) -> int\n\
  1147. \n\
  1148. Return the number of occurrences of substring sub in string\n\
  1149. S[start:end].  Optional arguments start and end are\n\
  1150. interpreted as in slice notation.");
  1151.  
  1152. static PyObject *
  1153. string_count(self, args)
  1154.     PyStringObject *self;
  1155.     PyObject *args;
  1156. {
  1157.     char *s = PyString_AS_STRING(self), *sub;
  1158.     int len = PyString_GET_SIZE(self), n;
  1159.     int i = 0, last = INT_MAX;
  1160.     int m, r;
  1161.  
  1162.     if (!PyArg_ParseTuple(args, "t#|ii:count", &sub, &n, &i, &last))
  1163.         return NULL;
  1164.     if (last > len)
  1165.         last = len;
  1166.     if (last < 0)
  1167.         last += len;
  1168.     if (last < 0)
  1169.         last = 0;
  1170.     if (i < 0)
  1171.         i += len;
  1172.     if (i < 0)
  1173.         i = 0;
  1174.     m = last + 1 - n;
  1175.     if (n == 0)
  1176.         return PyInt_FromLong((long) (m-i));
  1177.  
  1178.     r = 0;
  1179.     while (i < m) {
  1180.         if (!memcmp(s+i, sub, n)) {
  1181.             r++;
  1182.             i += n;
  1183.         } else {
  1184.             i++;
  1185.         }
  1186.     }
  1187.     return PyInt_FromLong((long) r);
  1188. }
  1189.  
  1190.  
  1191. DEF_DOC(swapcase__doc__,
  1192. "S.swapcase() -> string\n\
  1193. \n\
  1194. Return a copy of the string S with upper case characters\n\
  1195. converted to lowercase and vice versa.");
  1196.  
  1197. static PyObject *
  1198. string_swapcase(self, args)
  1199.     PyStringObject *self;
  1200.     PyObject *args;
  1201. {
  1202.     char *s = PyString_AS_STRING(self), *s_new;
  1203.     int i, n = PyString_GET_SIZE(self);
  1204.     PyObject *new;
  1205.  
  1206.     if (!PyArg_ParseTuple(args, ":swapcase"))
  1207.         return NULL;
  1208.     new = PyString_FromStringAndSize(NULL, n);
  1209.     if (new == NULL)
  1210.         return NULL;
  1211.     s_new = PyString_AsString(new);
  1212.     for (i = 0; i < n; i++) {
  1213.         int c = Py_CHARMASK(*s++);
  1214.         if (islower(c)) {
  1215.             *s_new = toupper(c);
  1216.         }
  1217.         else if (isupper(c)) {
  1218.             *s_new = tolower(c);
  1219.         }
  1220.         else
  1221.             *s_new = c;
  1222.         s_new++;
  1223.     }
  1224.     return new;
  1225. }
  1226.  
  1227.  
  1228. DEF_DOC(translate__doc__,
  1229. "S.translate(table [,deletechars]) -> string\n\
  1230. \n\
  1231. Return a copy of the string S, where all characters occurring\n\
  1232. in the optional argument deletechars are removed, and the\n\
  1233. remaining characters have been mapped through the given\n\
  1234. translation table, which must be a string of length 256.");
  1235.  
  1236. static PyObject *
  1237. string_translate(self, args)
  1238.     PyStringObject *self;
  1239.     PyObject *args;
  1240. {
  1241.     register char *input, *table, *output;
  1242.     register int i, c, changed = 0;
  1243.     PyObject *input_obj = (PyObject*)self;
  1244.     char *table1, *output_start, *del_table=NULL;
  1245.     int inlen, tablen, dellen = 0;
  1246.     PyObject *result;
  1247.     int trans_table[256];
  1248.  
  1249.     if (!PyArg_ParseTuple(args, "t#|t#:translate",
  1250.                   &table1, &tablen, &del_table, &dellen))
  1251.         return NULL;
  1252.     if (tablen != 256) {
  1253.         PyErr_SetString(PyExc_ValueError,
  1254.                   "translation table must be 256 characters long");
  1255.         return NULL;
  1256.     }
  1257.  
  1258.     table = table1;
  1259.     inlen = PyString_Size(input_obj);
  1260.     result = PyString_FromStringAndSize((char *)NULL, inlen);
  1261.     if (result == NULL)
  1262.         return NULL;
  1263.     output_start = output = PyString_AsString(result);
  1264.     input = PyString_AsString(input_obj);
  1265.  
  1266.     if (dellen == 0) {
  1267.         /* If no deletions are required, use faster code */
  1268.         for (i = inlen; --i >= 0; ) {
  1269.             c = Py_CHARMASK(*input++);
  1270.             if (Py_CHARMASK((*output++ = table[c])) != c)
  1271.                 changed = 1;
  1272.         }
  1273.         if (changed)
  1274.             return result;
  1275.         Py_DECREF(result);
  1276.         Py_INCREF(input_obj);
  1277.         return input_obj;
  1278.     }
  1279.  
  1280.     for (i = 0; i < 256; i++)
  1281.         trans_table[i] = Py_CHARMASK(table[i]);
  1282.  
  1283.     for (i = 0; i < dellen; i++)
  1284.         trans_table[(int) Py_CHARMASK(del_table[i])] = -1;
  1285.  
  1286.     for (i = inlen; --i >= 0; ) {
  1287.         c = Py_CHARMASK(*input++);
  1288.         if (trans_table[c] != -1)
  1289.             if (Py_CHARMASK(*output++ = (char)trans_table[c]) == c)
  1290.                 continue;
  1291.         changed = 1;
  1292.     }
  1293.     if (!changed) {
  1294.         Py_DECREF(result);
  1295.         Py_INCREF(input_obj);
  1296.         return input_obj;
  1297.     }
  1298.     /* Fix the size of the resulting string */
  1299.     if (inlen > 0 &&_PyString_Resize(&result, output-output_start))
  1300.         return NULL;
  1301.     return result;
  1302. }
  1303.  
  1304.  
  1305. /* What follows is used for implementing replace().  Perry Stoll. */
  1306.  
  1307. /*
  1308.   mymemfind
  1309.  
  1310.   strstr replacement for arbitrary blocks of memory.
  1311.  
  1312.   Locates the first occurance in the memory pointed to by MEM of the
  1313.   contents of memory pointed to by PAT.  Returns the index into MEM if
  1314.   found, or -1 if not found.  If len of PAT is greater than length of
  1315.   MEM, the function returns -1.
  1316. */
  1317. static int 
  1318. mymemfind(mem, len, pat, pat_len)
  1319.     char *mem;
  1320.     int len;
  1321.     char *pat;
  1322.     int pat_len;
  1323. {
  1324.     register int ii;
  1325.  
  1326.     /* pattern can not occur in the last pat_len-1 chars */
  1327.     len -= pat_len;
  1328.  
  1329.     for (ii = 0; ii <= len; ii++) {
  1330.         if (mem[ii] == pat[0] &&
  1331.             (pat_len == 1 ||
  1332.              memcmp(&mem[ii+1], &pat[1], pat_len-1) == 0)) {
  1333.             return ii;
  1334.         }
  1335.     }
  1336.     return -1;
  1337. }
  1338.  
  1339. /*
  1340.   mymemcnt
  1341.  
  1342.    Return the number of distinct times PAT is found in MEM.
  1343.    meaning mem=1111 and pat==11 returns 2.
  1344.            mem=11111 and pat==11 also return 2.
  1345.  */
  1346. static int 
  1347. mymemcnt(mem, len, pat, pat_len)
  1348.     char *mem;
  1349.     int len;
  1350.     char *pat;
  1351.     int pat_len;
  1352. {
  1353.     register int offset = 0;
  1354.     int nfound = 0;
  1355.  
  1356.     while (len >= 0) {
  1357.         offset = mymemfind(mem, len, pat, pat_len);
  1358.         if (offset == -1)
  1359.             break;
  1360.         mem += offset + pat_len;
  1361.         len -= offset + pat_len;
  1362.         nfound++;
  1363.     }
  1364.     return nfound;
  1365. }
  1366.  
  1367. /*
  1368.    mymemreplace
  1369.  
  1370.    Return a string in which all occurences of PAT in memory STR are
  1371.    replaced with SUB.
  1372.  
  1373.    If length of PAT is less than length of STR or there are no occurences
  1374.    of PAT in STR, then the original string is returned. Otherwise, a new
  1375.    string is allocated here and returned.
  1376.  
  1377.    on return, out_len is:
  1378.        the length of output string, or
  1379.        -1 if the input string is returned, or
  1380.        unchanged if an error occurs (no memory).
  1381.  
  1382.    return value is:
  1383.        the new string allocated locally, or
  1384.        NULL if an error occurred.
  1385. */
  1386. static char *
  1387. mymemreplace(str, len, pat, pat_len, sub, sub_len, count, out_len)
  1388.     char *str;
  1389.     int len;     /* input string  */
  1390.     char *pat;
  1391.     int pat_len; /* pattern string to find */
  1392.     char *sub;
  1393.     int sub_len; /* substitution string */
  1394.     int count;   /* number of replacements, 0 == all */
  1395.     int *out_len;
  1396.  
  1397. {
  1398.     char *out_s;
  1399.     char *new_s;
  1400.     int nfound, offset, new_len;
  1401.  
  1402.     if (len == 0 || pat_len > len)
  1403.         goto return_same;
  1404.  
  1405.     /* find length of output string */
  1406.     nfound = mymemcnt(str, len, pat, pat_len);
  1407.     if (count > 0)
  1408.         nfound = nfound > count ? count : nfound;
  1409.     if (nfound == 0)
  1410.         goto return_same;
  1411.     new_len = len + nfound*(sub_len - pat_len);
  1412.  
  1413.     new_s = (char *)malloc(new_len);
  1414.     if (new_s == NULL) return NULL;
  1415.  
  1416.     *out_len = new_len;
  1417.     out_s = new_s;
  1418.  
  1419.     while (len > 0) {
  1420.         /* find index of next instance of pattern */
  1421.         offset = mymemfind(str, len, pat, pat_len);
  1422.         /* if not found,  break out of loop */
  1423.         if (offset == -1) break;
  1424.  
  1425.         /* copy non matching part of input string */
  1426.         memcpy(new_s, str, offset); /* copy part of str before pat */
  1427.         str += offset + pat_len; /* move str past pattern */
  1428.         len -= offset + pat_len; /* reduce length of str remaining */
  1429.  
  1430.         /* copy substitute into the output string */
  1431.         new_s += offset; /* move new_s to dest for sub string */
  1432.         memcpy(new_s, sub, sub_len); /* copy substring into new_s */
  1433.         new_s += sub_len; /* offset new_s past sub string */
  1434.  
  1435.         /* break when we've done count replacements */
  1436.         if (--count == 0) break;
  1437.     }
  1438.     /* copy any remaining values into output string */
  1439.     if (len > 0)
  1440.         memcpy(new_s, str, len);
  1441.     return out_s;
  1442.  
  1443.   return_same:
  1444.     *out_len = -1;
  1445.     return str;
  1446. }
  1447.  
  1448.  
  1449. DEF_DOC(replace__doc__,
  1450. "S.replace (old, new[, maxsplit]) -> string\n\
  1451. \n\
  1452. Return a copy of string S with all occurrences of substring\n\
  1453. old replaced by new.  If the optional argument maxsplit is\n\
  1454. given, only the first maxsplit occurrences are replaced.");
  1455.  
  1456. static PyObject *
  1457. string_replace(self, args)
  1458.     PyStringObject *self;
  1459.     PyObject *args;
  1460. {
  1461.     char *str = PyString_AS_STRING(self), *pat,*sub,*new_s;
  1462.     int len = PyString_GET_SIZE(self), pat_len,sub_len,out_len;
  1463.     int count = 0;
  1464.     PyObject *new;
  1465.  
  1466.     if (!PyArg_ParseTuple(args, "t#t#|i:replace",
  1467.                   &pat, &pat_len, &sub, &sub_len, &count))
  1468.         return NULL;
  1469.     if (pat_len <= 0) {
  1470.         PyErr_SetString(PyExc_ValueError, "empty pattern string");
  1471.         return NULL;
  1472.     }
  1473.     new_s = mymemreplace(str,len,pat,pat_len,sub,sub_len,count,&out_len);
  1474.     if (new_s == NULL) {
  1475.         PyErr_NoMemory();
  1476.         return NULL;
  1477.     }
  1478.     if (out_len == -1) {
  1479.         /* we're returning another reference to self */
  1480.         new = (PyObject*)self;
  1481.         Py_INCREF(new);
  1482.     }
  1483.     else {
  1484.         new = PyString_FromStringAndSize(new_s, out_len);
  1485.         free(new_s);
  1486.     }
  1487.     return new;
  1488. }
  1489.  
  1490.  
  1491. DEF_DOC(startswith__doc__,
  1492. "S.startswith(prefix[, start[, end]]) -> int\n\
  1493. \n\
  1494. Return 1 if S starts with the specified prefix, otherwise return 0.  With\n\
  1495. optional start, test S beginning at that position.  With optional end, stop\n\
  1496. comparing S at that position.");
  1497.  
  1498. static PyObject *
  1499. string_startswith(self, args)
  1500.     PyStringObject *self;
  1501.     PyObject *args;
  1502. {
  1503.     char* str = PyString_AS_STRING(self);
  1504.     int len = PyString_GET_SIZE(self);
  1505.     char* prefix;
  1506.     int plen;
  1507.     int start = 0;
  1508.     int end = -1;
  1509.  
  1510.     if (!PyArg_ParseTuple(args, "t#|ii:startswith", &prefix, &plen, &start, &end))
  1511.         return NULL;
  1512.  
  1513.     /* adopt Java semantics for index out of range.  it is legal for
  1514.      * offset to be == plen, but this only returns true if prefix is
  1515.      * the empty string.
  1516.      */
  1517.     if (start < 0 || start+plen > len)
  1518.         return PyInt_FromLong(0);
  1519.  
  1520.     if (!memcmp(str+start, prefix, plen)) {
  1521.         /* did the match end after the specified end? */
  1522.         if (end < 0)
  1523.             return PyInt_FromLong(1);
  1524.         else if (end - start < plen)
  1525.             return PyInt_FromLong(0);
  1526.         else
  1527.             return PyInt_FromLong(1);
  1528.     }
  1529.     else return PyInt_FromLong(0);
  1530. }
  1531.  
  1532.  
  1533. DEF_DOC(endswith__doc__,
  1534. "S.endswith(suffix[, start[, end]]) -> int\n\
  1535. \n\
  1536. Return 1 if S ends with the specified suffix, otherwise return 0.  With\n\
  1537. optional start, test S beginning at that position.  With optional end, stop\n\
  1538. comparing S at that position.");
  1539.  
  1540. static PyObject *
  1541. string_endswith(self, args)
  1542.     PyStringObject *self;
  1543.     PyObject *args;
  1544. {
  1545.     char* str = PyString_AS_STRING(self);
  1546.     int len = PyString_GET_SIZE(self);
  1547.     char* suffix;
  1548.     int plen;
  1549.     int start = 0;
  1550.     int end = -1;
  1551.     int lower, upper;
  1552.  
  1553.     if (!PyArg_ParseTuple(args, "t#|ii:endswith", &suffix, &plen, &start, &end))
  1554.         return NULL;
  1555.  
  1556.     if (start < 0 || start > len || plen > len)
  1557.         return PyInt_FromLong(0);
  1558.  
  1559.     upper = (end >= 0 && end <= len) ? end : len;
  1560.     lower = (upper - plen) > start ? (upper - plen) : start;
  1561.  
  1562.     if (upper-lower >= plen && !memcmp(str+lower, suffix, plen))
  1563.         return PyInt_FromLong(1);
  1564.     else return PyInt_FromLong(0);
  1565. }
  1566.  
  1567.  
  1568.  
  1569. static PyMethodDef 
  1570. string_methods[] = {
  1571.     /* counterparts of the obsolete stropmodule functions */
  1572.     {"capitalize", (PyCFunction)string_capitalize, 1, USE_DOC(capitalize__doc__)},
  1573.     {"count",      (PyCFunction)string_count,      1, USE_DOC(count__doc__)},
  1574.     {"endswith",   (PyCFunction)string_endswith,   1, USE_DOC(endswith__doc__)},
  1575.     {"find",       (PyCFunction)string_find,       1, USE_DOC(find__doc__)},
  1576.     {"index",      (PyCFunction)string_index,      1, USE_DOC(index__doc__)},
  1577.     {"join",       (PyCFunction)string_join,       1, USE_DOC(join__doc__)},
  1578.     {"lstrip",     (PyCFunction)string_lstrip,     1, USE_DOC(lstrip__doc__)},
  1579.     {"lower",      (PyCFunction)string_lower,      1, USE_DOC(lower__doc__)},
  1580.     /* maketrans */
  1581.     {"replace",     (PyCFunction)string_replace,     1, USE_DOC(replace__doc__)},
  1582.     {"rfind",       (PyCFunction)string_rfind,       1, USE_DOC(rfind__doc__)},
  1583.     {"rindex",      (PyCFunction)string_rindex,      1, USE_DOC(rindex__doc__)},
  1584.     {"rstrip",      (PyCFunction)string_rstrip,      1, USE_DOC(rstrip__doc__)},
  1585.     {"split",       (PyCFunction)string_split,       1, USE_DOC(split__doc__)},
  1586.     {"startswith",  (PyCFunction)string_startswith,  1, USE_DOC(startswith__doc__)},
  1587.     {"strip",       (PyCFunction)string_strip,       1, USE_DOC(strip__doc__)},
  1588.     {"swapcase",    (PyCFunction)string_swapcase,    1, USE_DOC(swapcase__doc__)},
  1589.     {"translate",   (PyCFunction)string_translate,   1, USE_DOC(translate__doc__)},
  1590.     {"upper",       (PyCFunction)string_upper,       1, USE_DOC(upper__doc__)},
  1591.     /* TBD */
  1592. /*     {"ljust"        (PyCFunction)string_ljust,       1, ljust__doc__}, */
  1593. /*     {"rjust"        (PyCFunction)string_rjust,       1, rjust__doc__}, */
  1594. /*     {"center"       (PyCFunction)string_center,      1, center__doc__}, */
  1595. /*     {"zfill"        (PyCFunction)string_zfill,       1, zfill__doc__}, */
  1596. /*     {"expandtabs"   (PyCFunction)string_expandtabs,  1, ljust__doc__}, */
  1597. /*     {"capwords"     (PyCFunction)string_capwords,    1, capwords__doc__}, */
  1598.     {NULL,     NULL}             /* sentinel */
  1599. };
  1600.  
  1601. static PyObject *
  1602. string_getattr(s, name)
  1603.     PyStringObject *s;
  1604.     char *name;
  1605. {
  1606.     return Py_FindMethod(string_methods, (PyObject*)s, name);
  1607. }
  1608.  
  1609.  
  1610. PyTypeObject PyString_Type = {
  1611.     PyObject_HEAD_INIT(&PyType_Type)
  1612.     0,
  1613.     "string",
  1614.     sizeof(PyStringObject),
  1615.     sizeof(char),
  1616.     (destructor)string_dealloc, /*tp_dealloc*/
  1617.     (printfunc)string_print, /*tp_print*/
  1618.     (getattrfunc)string_getattr,        /*tp_getattr*/
  1619.     0,        /*tp_setattr*/
  1620.     (cmpfunc)string_compare, /*tp_compare*/
  1621.     (reprfunc)string_repr, /*tp_repr*/
  1622.     0,        /*tp_as_number*/
  1623.     &string_as_sequence,    /*tp_as_sequence*/
  1624.     0,        /*tp_as_mapping*/
  1625.     (hashfunc)string_hash, /*tp_hash*/
  1626.     0,        /*tp_call*/
  1627.     0,        /*tp_str*/
  1628.     0,        /*tp_getattro*/
  1629.     0,        /*tp_setattro*/
  1630.     &string_as_buffer,    /*tp_as_buffer*/
  1631.     Py_TPFLAGS_DEFAULT,    /*tp_flags*/
  1632.     0,        /*tp_doc*/
  1633. };
  1634.  
  1635. void
  1636. PyString_Concat(pv, w)
  1637.     register PyObject **pv;
  1638.     register PyObject *w;
  1639. {
  1640.     register PyObject *v;
  1641.     if (*pv == NULL)
  1642.         return;
  1643.     if (w == NULL || !PyString_Check(*pv)) {
  1644.         Py_DECREF(*pv);
  1645.         *pv = NULL;
  1646.         return;
  1647.     }
  1648.     v = string_concat((PyStringObject *) *pv, w);
  1649.     Py_DECREF(*pv);
  1650.     *pv = v;
  1651. }
  1652.  
  1653. void
  1654. PyString_ConcatAndDel(pv, w)
  1655.     register PyObject **pv;
  1656.     register PyObject *w;
  1657. {
  1658.     PyString_Concat(pv, w);
  1659.     Py_XDECREF(w);
  1660. }
  1661.  
  1662.  
  1663. /* The following function breaks the notion that strings are immutable:
  1664.    it changes the size of a string.  We get away with this only if there
  1665.    is only one module referencing the object.  You can also think of it
  1666.    as creating a new string object and destroying the old one, only
  1667.    more efficiently.  In any case, don't use this if the string may
  1668.    already be known to some other part of the code... */
  1669.  
  1670. int
  1671. _PyString_Resize(pv, newsize)
  1672.     PyObject **pv;
  1673.     int newsize;
  1674. {
  1675.     register PyObject *v;
  1676.     register PyStringObject *sv;
  1677.     v = *pv;
  1678.     if (!PyString_Check(v) || v->ob_refcnt != 1) {
  1679.         *pv = 0;
  1680.         Py_DECREF(v);
  1681.         PyErr_BadInternalCall();
  1682.         return -1;
  1683.     }
  1684.     /* XXX UNREF/NEWREF interface should be more symmetrical */
  1685. #ifdef Py_REF_DEBUG
  1686.     --_Py_RefTotal;
  1687. #endif
  1688.     _Py_ForgetReference(v);
  1689.     *pv = (PyObject *)
  1690.         realloc((char *)v,
  1691.             sizeof(PyStringObject) + newsize * sizeof(char));
  1692.     if (*pv == NULL) {
  1693.         PyMem_DEL(v);
  1694.         PyErr_NoMemory();
  1695.         return -1;
  1696.     }
  1697.     _Py_NewReference(*pv);
  1698.     sv = (PyStringObject *) *pv;
  1699.     sv->ob_size = newsize;
  1700.     sv->ob_sval[newsize] = '\0';
  1701.     return 0;
  1702. }
  1703.  
  1704. /* Helpers for formatstring */
  1705.  
  1706. static PyObject *
  1707. getnextarg(args, arglen, p_argidx)
  1708.     PyObject *args;
  1709.     int arglen;
  1710.     int *p_argidx;
  1711. {
  1712.     int argidx = *p_argidx;
  1713.     if (argidx < arglen) {
  1714.         (*p_argidx)++;
  1715.         if (arglen < 0)
  1716.             return args;
  1717.         else
  1718.             return PyTuple_GetItem(args, argidx);
  1719.     }
  1720.     PyErr_SetString(PyExc_TypeError,
  1721.             "not enough arguments for format string");
  1722.     return NULL;
  1723. }
  1724.  
  1725. #define F_LJUST (1<<0)
  1726. #define F_SIGN    (1<<1)
  1727. #define F_BLANK (1<<2)
  1728. #define F_ALT    (1<<3)
  1729. #define F_ZERO    (1<<4)
  1730.  
  1731. #ifndef WITHOUT_FLOAT
  1732. static int
  1733. formatfloat(buf, flags, prec, type, v)
  1734.     char *buf;
  1735.     int flags;
  1736.     int prec;
  1737.     int type;
  1738.     PyObject *v;
  1739. {
  1740.     char fmt[20];
  1741.     double x;
  1742.     if (!PyArg_Parse(v, "d;float argument required", &x))
  1743.         return -1;
  1744.     if (prec < 0)
  1745.         prec = 6;
  1746.     if (prec > 50)
  1747.         prec = 50; /* Arbitrary limitation */
  1748.     if (type == 'f' && fabs(x)/1e25 >= 1e25)
  1749.         type = 'g';
  1750.     sprintf(fmt, "%%%s.%d%c", (flags&F_ALT) ? "#" : "", prec, type);
  1751.     sprintf(buf, fmt, x);
  1752.     return strlen(buf);
  1753. }
  1754. #endif /* WITHOUT_FLOAT */
  1755.  
  1756. static int
  1757. formatint(buf, flags, prec, type, v)
  1758.     char *buf;
  1759.     int flags;
  1760.     int prec;
  1761.     int type;
  1762.     PyObject *v;
  1763. {
  1764.     char fmt[20];
  1765.     long x;
  1766.     if (!PyArg_Parse(v, "l;int argument required", &x))
  1767.         return -1;
  1768.     if (prec < 0)
  1769.         prec = 1;
  1770.     sprintf(fmt, "%%%s.%dl%c", (flags&F_ALT) ? "#" : "", prec, type);
  1771.     sprintf(buf, fmt, x);
  1772.     return strlen(buf);
  1773. }
  1774.  
  1775. static int
  1776. formatchar(buf, v)
  1777.     char *buf;
  1778.     PyObject *v;
  1779. {
  1780.     if (PyString_Check(v)) {
  1781.         if (!PyArg_Parse(v, "c;%c requires int or char", &buf[0]))
  1782.             return -1;
  1783.     }
  1784.     else {
  1785.         if (!PyArg_Parse(v, "b;%c requires int or char", &buf[0]))
  1786.             return -1;
  1787.     }
  1788.     buf[1] = '\0';
  1789.     return 1;
  1790. }
  1791.  
  1792.  
  1793. /* fmt%(v1,v2,...) is roughly equivalent to sprintf(fmt, v1, v2, ...) */
  1794.  
  1795. PyObject *
  1796. PyString_Format(format, args)
  1797.     PyObject *format;
  1798.     PyObject *args;
  1799. {
  1800.     char *fmt, *res;
  1801.     int fmtcnt, rescnt, reslen, arglen, argidx;
  1802.     int args_owned = 0;
  1803.     PyObject *result;
  1804.     PyObject *dict = NULL;
  1805.     if (format == NULL || !PyString_Check(format) || args == NULL) {
  1806.         PyErr_BadInternalCall();
  1807.         return NULL;
  1808.     }
  1809.     fmt = PyString_AsString(format);
  1810.     fmtcnt = PyString_Size(format);
  1811.     reslen = rescnt = fmtcnt + 100;
  1812.     result = PyString_FromStringAndSize((char *)NULL, reslen);
  1813.     if (result == NULL)
  1814.         return NULL;
  1815.     res = PyString_AsString(result);
  1816.     if (PyTuple_Check(args)) {
  1817.         arglen = PyTuple_Size(args);
  1818.         argidx = 0;
  1819.     }
  1820.     else {
  1821.         arglen = -1;
  1822.         argidx = -2;
  1823.     }
  1824.     if (args->ob_type->tp_as_mapping)
  1825.         dict = args;
  1826.     while (--fmtcnt >= 0) {
  1827.         if (*fmt != '%') {
  1828.             if (--rescnt < 0) {
  1829.                 rescnt = fmtcnt + 100;
  1830.                 reslen += rescnt;
  1831.                 if (_PyString_Resize(&result, reslen) < 0)
  1832.                     return NULL;
  1833.                 res = PyString_AsString(result)
  1834.                     + reslen - rescnt;
  1835.                 --rescnt;
  1836.             }
  1837.             *res++ = *fmt++;
  1838.         }
  1839.         else {
  1840.             /* Got a format specifier */
  1841.             int flags = 0;
  1842.             int width = -1;
  1843.             int prec = -1;
  1844.             int size = 0;
  1845.             int c = '\0';
  1846.             int fill;
  1847.             PyObject *v = NULL;
  1848.             PyObject *temp = NULL;
  1849.             char *buf;
  1850.             int sign;
  1851.             int len;
  1852.             char tmpbuf[120]; /* For format{float,int,char}() */
  1853.             fmt++;
  1854.             if (*fmt == '(') {
  1855.                 char *keystart;
  1856.                 int keylen;
  1857.                 PyObject *key;
  1858.                 int pcount = 1;
  1859.  
  1860.                 if (dict == NULL) {
  1861.                     PyErr_SetString(PyExc_TypeError,
  1862.                          "format requires a mapping"); 
  1863.                     goto error;
  1864.                 }
  1865.                 ++fmt;
  1866.                 --fmtcnt;
  1867.                 keystart = fmt;
  1868.                 /* Skip over balanced parentheses */
  1869.                 while (pcount > 0 && --fmtcnt >= 0) {
  1870.                     if (*fmt == ')')
  1871.                         --pcount;
  1872.                     else if (*fmt == '(')
  1873.                         ++pcount;
  1874.                     fmt++;
  1875.                 }
  1876.                 keylen = fmt - keystart - 1;
  1877.                 if (fmtcnt < 0 || pcount > 0) {
  1878.                     PyErr_SetString(PyExc_ValueError,
  1879.                            "incomplete format key");
  1880.                     goto error;
  1881.                 }
  1882.                 key = PyString_FromStringAndSize(keystart,
  1883.                                  keylen);
  1884.                 if (key == NULL)
  1885.                     goto error;
  1886.                 if (args_owned) {
  1887.                     Py_DECREF(args);
  1888.                     args_owned = 0;
  1889.                 }
  1890.                 args = PyObject_GetItem(dict, key);
  1891.                 Py_DECREF(key);
  1892.                 if (args == NULL) {
  1893.                     goto error;
  1894.                 }
  1895.                 args_owned = 1;
  1896.                 arglen = -1;
  1897.                 argidx = -2;
  1898.             }
  1899.             while (--fmtcnt >= 0) {
  1900.                 switch (c = *fmt++) {
  1901.                 case '-': flags |= F_LJUST; continue;
  1902.                 case '+': flags |= F_SIGN; continue;
  1903.                 case ' ': flags |= F_BLANK; continue;
  1904.                 case '#': flags |= F_ALT; continue;
  1905.                 case '0': flags |= F_ZERO; continue;
  1906.                 }
  1907.                 break;
  1908.             }
  1909.             if (c == '*') {
  1910.                 v = getnextarg(args, arglen, &argidx);
  1911.                 if (v == NULL)
  1912.                     goto error;
  1913.                 if (!PyInt_Check(v)) {
  1914.                     PyErr_SetString(PyExc_TypeError,
  1915.                             "* wants int");
  1916.                     goto error;
  1917.                 }
  1918.                 width = PyInt_AsLong(v);
  1919.                 if (width < 0) {
  1920.                     flags |= F_LJUST;
  1921.                     width = -width;
  1922.                 }
  1923.                 if (--fmtcnt >= 0)
  1924.                     c = *fmt++;
  1925.             }
  1926.             else if (c >= 0 && isdigit(c)) {
  1927.                 width = c - '0';
  1928.                 while (--fmtcnt >= 0) {
  1929.                     c = Py_CHARMASK(*fmt++);
  1930.                     if (!isdigit(c))
  1931.                         break;
  1932.                     if ((width*10) / 10 != width) {
  1933.                         PyErr_SetString(
  1934.                             PyExc_ValueError,
  1935.                             "width too big");
  1936.                         goto error;
  1937.                     }
  1938.                     width = width*10 + (c - '0');
  1939.                 }
  1940.             }
  1941.             if (c == '.') {
  1942.                 prec = 0;
  1943.                 if (--fmtcnt >= 0)
  1944.                     c = *fmt++;
  1945.                 if (c == '*') {
  1946.                     v = getnextarg(args, arglen, &argidx);
  1947.                     if (v == NULL)
  1948.                         goto error;
  1949.                     if (!PyInt_Check(v)) {
  1950.                         PyErr_SetString(
  1951.                             PyExc_TypeError,
  1952.                             "* wants int");
  1953.                         goto error;
  1954.                     }
  1955.                     prec = PyInt_AsLong(v);
  1956.                     if (prec < 0)
  1957.                         prec = 0;
  1958.                     if (--fmtcnt >= 0)
  1959.                         c = *fmt++;
  1960.                 }
  1961.                 else if (c >= 0 && isdigit(c)) {
  1962.                     prec = c - '0';
  1963.                     while (--fmtcnt >= 0) {
  1964.                         c = Py_CHARMASK(*fmt++);
  1965.                         if (!isdigit(c))
  1966.                             break;
  1967.                         if ((prec*10) / 10 != prec) {
  1968.                             PyErr_SetString(
  1969.                                 PyExc_ValueError,
  1970.                                 "prec too big");
  1971.                             goto error;
  1972.                         }
  1973.                         prec = prec*10 + (c - '0');
  1974.                     }
  1975.                 }
  1976.             } /* prec */
  1977.             if (fmtcnt >= 0) {
  1978.                 if (c == 'h' || c == 'l' || c == 'L') {
  1979.                     size = c;
  1980.                     if (--fmtcnt >= 0)
  1981.                         c = *fmt++;
  1982.                 }
  1983.             }
  1984.             if (fmtcnt < 0) {
  1985.                 PyErr_SetString(PyExc_ValueError,
  1986.                         "incomplete format");
  1987.                 goto error;
  1988.             }
  1989.             if (c != '%') {
  1990.                 v = getnextarg(args, arglen, &argidx);
  1991.                 if (v == NULL)
  1992.                     goto error;
  1993.             }
  1994.             sign = 0;
  1995.             fill = ' ';
  1996.             switch (c) {
  1997.             case '%':
  1998.                 buf = "%";
  1999.                 len = 1;
  2000.                 break;
  2001.             case 's':
  2002.                 temp = PyObject_Str(v);
  2003.                 if (temp == NULL)
  2004.                     goto error;
  2005.                 if (!PyString_Check(temp)) {
  2006.                     PyErr_SetString(PyExc_TypeError,
  2007.                       "%s argument has non-string str()");
  2008.                     goto error;
  2009.                 }
  2010.                 buf = PyString_AsString(temp);
  2011.                 len = PyString_Size(temp);
  2012.                 if (prec >= 0 && len > prec)
  2013.                     len = prec;
  2014.                 break;
  2015.             case 'i':
  2016.             case 'd':
  2017.             case 'u':
  2018.             case 'o':
  2019.             case 'x':
  2020.             case 'X':
  2021.                 if (c == 'i')
  2022.                     c = 'd';
  2023.                 buf = tmpbuf;
  2024.                 len = formatint(buf, flags, prec, c, v);
  2025.                 if (len < 0)
  2026.                     goto error;
  2027.                 sign = (c == 'd');
  2028.                 if (flags&F_ZERO) {
  2029.                     fill = '0';
  2030.                     if ((flags&F_ALT) &&
  2031.                         (c == 'x' || c == 'X') &&
  2032.                         buf[0] == '0' && buf[1] == c) {
  2033.                         *res++ = *buf++;
  2034.                         *res++ = *buf++;
  2035.                         rescnt -= 2;
  2036.                         len -= 2;
  2037.                         width -= 2;
  2038.                         if (width < 0)
  2039.                             width = 0;
  2040.                     }
  2041.                 }
  2042.                 break;
  2043.             case 'e':
  2044.             case 'E':
  2045.             case 'f':
  2046.             case 'g':
  2047.             case 'G':
  2048. #ifndef WITHOUT_FLOAT
  2049.                 buf = tmpbuf;
  2050.                 len = formatfloat(buf, flags, prec, c, v);
  2051.                 if (len < 0)
  2052.                     goto error;
  2053.                 sign = 1;
  2054.                 if (flags&F_ZERO)
  2055.                     fill = '0';
  2056.                 break;
  2057. #else /* !WITHOUT_FLOAT */
  2058.                 PyErr_SetString(PyExc_MissingFeatureError,
  2059.                     "Float objects are not provided in this python build");
  2060.                 goto error;
  2061. #endif /* !WITHOUT_FLOAT */
  2062.             case 'c':
  2063.                 buf = tmpbuf;
  2064.                 len = formatchar(buf, v);
  2065.                 if (len < 0)
  2066.                     goto error;
  2067.                 break;
  2068.             default:
  2069.                 PyErr_Format(PyExc_ValueError,
  2070.                 "unsupported format character '%c' (0x%x)",
  2071.                     c, c);
  2072.                 goto error;
  2073.             }
  2074.             if (sign) {
  2075.                 if (*buf == '-' || *buf == '+') {
  2076.                     sign = *buf++;
  2077.                     len--;
  2078.                 }
  2079.                 else if (flags & F_SIGN)
  2080.                     sign = '+';
  2081.                 else if (flags & F_BLANK)
  2082.                     sign = ' ';
  2083.                 else
  2084.                     sign = '\0';
  2085.             }
  2086.             if (width < len)
  2087.                 width = len;
  2088.             if (rescnt < width + (sign != '\0')) {
  2089.                 reslen -= rescnt;
  2090.                 rescnt = width + fmtcnt + 100;
  2091.                 reslen += rescnt;
  2092.                 if (_PyString_Resize(&result, reslen) < 0)
  2093.                     return NULL;
  2094.                 res = PyString_AsString(result)
  2095.                     + reslen - rescnt;
  2096.             }
  2097.             if (sign) {
  2098.                 if (fill != ' ')
  2099.                     *res++ = sign;
  2100.                 rescnt--;
  2101.                 if (width > len)
  2102.                     width--;
  2103.             }
  2104.             if (width > len && !(flags&F_LJUST)) {
  2105.                 do {
  2106.                     --rescnt;
  2107.                     *res++ = fill;
  2108.                 } while (--width > len);
  2109.             }
  2110.             if (sign && fill == ' ')
  2111.                 *res++ = sign;
  2112.             memcpy(res, buf, len);
  2113.             res += len;
  2114.             rescnt -= len;
  2115.             while (--width >= len) {
  2116.                 --rescnt;
  2117.                 *res++ = ' ';
  2118.             }
  2119.                         if (dict && (argidx < arglen) && c != '%') {
  2120.                                 PyErr_SetString(PyExc_TypeError,
  2121.                                            "not all arguments converted");
  2122.                                 goto error;
  2123.                         }
  2124.             Py_XDECREF(temp);
  2125.         } /* '%' */
  2126.     } /* until end */
  2127.     if (argidx < arglen && !dict) {
  2128.         PyErr_SetString(PyExc_TypeError,
  2129.                 "not all arguments converted");
  2130.         goto error;
  2131.     }
  2132.     if (args_owned) {
  2133.         Py_DECREF(args);
  2134.     }
  2135.     _PyString_Resize(&result, reslen - rescnt);
  2136.     return result;
  2137.  error:
  2138.     Py_DECREF(result);
  2139.     if (args_owned) {
  2140.         Py_DECREF(args);
  2141.     }
  2142.     return NULL;
  2143. }
  2144.  
  2145.  
  2146. #ifdef INTERN_STRINGS
  2147.  
  2148. static PyObject *interned;
  2149.  
  2150. void
  2151. PyString_InternInPlace(p)
  2152.     PyObject **p;
  2153. {
  2154.     register PyStringObject *s = (PyStringObject *)(*p);
  2155.     PyObject *t;
  2156.     if (s == NULL || !PyString_Check(s))
  2157.         Py_FatalError("PyString_InternInPlace: strings only please!");
  2158.     if ((t = s->ob_sinterned) != NULL) {
  2159.         if (t == (PyObject *)s)
  2160.             return;
  2161.         Py_INCREF(t);
  2162.         *p = t;
  2163.         Py_DECREF(s);
  2164.         return;
  2165.     }
  2166.     if (interned == NULL) {
  2167.         interned = PyDict_New();
  2168.         if (interned == NULL)
  2169.             return;
  2170.     }
  2171.     if ((t = PyDict_GetItem(interned, (PyObject *)s)) != NULL) {
  2172.         Py_INCREF(t);
  2173.         *p = s->ob_sinterned = t;
  2174.         Py_DECREF(s);
  2175.         return;
  2176.     }
  2177.     t = (PyObject *)s;
  2178.     if (PyDict_SetItem(interned, t, t) == 0) {
  2179.         s->ob_sinterned = t;
  2180.         return;
  2181.     }
  2182.     PyErr_Clear();
  2183. }
  2184.  
  2185.  
  2186. PyObject *
  2187. PyString_InternFromString(cp)
  2188.     const char *cp;
  2189. {
  2190.     PyObject *s = PyString_FromString(cp);
  2191.     if (s == NULL)
  2192.         return NULL;
  2193.     PyString_InternInPlace(&s);
  2194.     return s;
  2195. }
  2196.  
  2197. #endif
  2198.  
  2199. void
  2200. PyString_Fini()
  2201. {
  2202. #ifndef DONT_SHARE_SHORT_STRINGS
  2203.     int i;
  2204.     for (i = 0; i < UCHAR_MAX + 1; i++) {
  2205.         Py_XDECREF(characters[i]);
  2206.         characters[i] = NULL;
  2207.     }
  2208.     Py_XDECREF(nullstring);
  2209.     nullstring = NULL;
  2210. #endif
  2211. #ifdef INTERN_STRINGS
  2212.     if (interned) {
  2213.         int pos, changed;
  2214.         PyObject *key, *value;
  2215.         do {
  2216.             changed = 0;
  2217.             pos = 0;
  2218.             while (PyDict_Next(interned, &pos, &key, &value)) {
  2219.                 if (key->ob_refcnt == 2 && key == value) {
  2220.                     PyDict_DelItem(interned, key);
  2221.                     changed = 1;
  2222.                 }
  2223.             }
  2224.         } while (changed);
  2225.     }
  2226. #endif
  2227. }
  2228.