Ignore:
Timestamp:
Mar 19, 2014, 11:11:30 AM (11 years ago)
Author:
dmik
Message:

python: Update vendor to 2.7.6.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • python/vendor/current/Objects/stringobject.c

    r2 r388  
    55#include "Python.h"
    66#include <ctype.h>
     7#include <stddef.h>
    78
    89#ifdef COUNT_ALLOCS
    9 int null_strings, one_strings;
     10Py_ssize_t null_strings, one_strings;
    1011#endif
    1112
     
    2324static PyObject *interned;
    2425
     26/* PyStringObject_SIZE gives the basic size of a string; any memory allocation
     27   for a string of length n should request PyStringObject_SIZE + n bytes.
     28
     29   Using PyStringObject_SIZE instead of sizeof(PyStringObject) saves
     30   3 bytes per string allocation on a typical system.
     31*/
     32#define PyStringObject_SIZE (offsetof(PyStringObject, ob_sval) + 1)
     33
    2534/*
    26    For both PyString_FromString() and PyString_FromStringAndSize(), the
    27    parameter `size' denotes number of characters to allocate, not counting any
    28    null terminating character.
    29 
    3035   For PyString_FromString(), the parameter `str' points to a null-terminated
    3136   string containing exactly `size' bytes.
     
    4449   The PyObject member `op->ob_size', which denotes the number of "extra
    4550   items" in a variable-size object, will contain the number of bytes
    46    allocated for string data, not counting the null terminating character.  It
    47    is therefore equal to the equal to the `size' parameter (for
     51   allocated for string data, not counting the null terminating character.
     52   It is therefore equal to the `size' parameter (for
    4853   PyString_FromStringAndSize()) or the length of the string in the `str'
    4954   parameter (for PyString_FromString()).
     
    5257PyString_FromStringAndSize(const char *str, Py_ssize_t size)
    5358{
    54         register PyStringObject *op;
    55         if (size < 0) {
    56                 PyErr_SetString(PyExc_SystemError,
    57                     "Negative size passed to PyString_FromStringAndSize");
    58                 return NULL;
    59         }
    60         if (size == 0 && (op = nullstring) != NULL) {
     59    register PyStringObject *op;
     60    if (size < 0) {
     61        PyErr_SetString(PyExc_SystemError,
     62            "Negative size passed to PyString_FromStringAndSize");
     63        return NULL;
     64    }
     65    if (size == 0 && (op = nullstring) != NULL) {
    6166#ifdef COUNT_ALLOCS
    62                 null_strings++;
     67        null_strings++;
    6368#endif
    64                 Py_INCREF(op);
    65                 return (PyObject *)op;
    66         }
    67         if (size == 1 && str != NULL &&
    68             (op = characters[*str & UCHAR_MAX]) != NULL)
    69         {
     69        Py_INCREF(op);
     70        return (PyObject *)op;
     71    }
     72    if (size == 1 && str != NULL &&
     73        (op = characters[*str & UCHAR_MAX]) != NULL)
     74    {
    7075#ifdef COUNT_ALLOCS
    71                 one_strings++;
     76        one_strings++;
    7277#endif
    73                 Py_INCREF(op);
    74                 return (PyObject *)op;
    75         }
    76 
    77         if (size > PY_SSIZE_T_MAX - sizeof(PyStringObject)) {
    78                 PyErr_SetString(PyExc_OverflowError, "string is too large");
    79                 return NULL;
    80         }
    81 
    82         /* Inline PyObject_NewVar */
    83         op = (PyStringObject *)PyObject_MALLOC(sizeof(PyStringObject) + size);
    84         if (op == NULL)
    85                 return PyErr_NoMemory();
    86         PyObject_INIT_VAR(op, &PyString_Type, size);
    87         op->ob_shash = -1;
    88         op->ob_sstate = SSTATE_NOT_INTERNED;
    89         if (str != NULL)
    90                 Py_MEMCPY(op->ob_sval, str, size);
    91         op->ob_sval[size] = '\0';
    92         /* share short strings */
    93         if (size == 0) {
    94                 PyObject *t = (PyObject *)op;
    95                 PyString_InternInPlace(&t);
    96                 op = (PyStringObject *)t;
    97                 nullstring = op;
    98                 Py_INCREF(op);
    99         } else if (size == 1 && str != NULL) {
    100                 PyObject *t = (PyObject *)op;
    101                 PyString_InternInPlace(&t);
    102                 op = (PyStringObject *)t;
    103                 characters[*str & UCHAR_MAX] = op;
    104                 Py_INCREF(op);
    105         }
    106         return (PyObject *) op;
     78        Py_INCREF(op);
     79        return (PyObject *)op;
     80    }
     81
     82    if (size > PY_SSIZE_T_MAX - PyStringObject_SIZE) {
     83        PyErr_SetString(PyExc_OverflowError, "string is too large");
     84        return NULL;
     85    }
     86
     87    /* Inline PyObject_NewVar */
     88    op = (PyStringObject *)PyObject_MALLOC(PyStringObject_SIZE + size);
     89    if (op == NULL)
     90        return PyErr_NoMemory();
     91    PyObject_INIT_VAR(op, &PyString_Type, size);
     92    op->ob_shash = -1;
     93    op->ob_sstate = SSTATE_NOT_INTERNED;
     94    if (str != NULL)
     95        Py_MEMCPY(op->ob_sval, str, size);
     96    op->ob_sval[size] = '\0';
     97    /* share short strings */
     98    if (size == 0) {
     99        PyObject *t = (PyObject *)op;
     100        PyString_InternInPlace(&t);
     101        op = (PyStringObject *)t;
     102        nullstring = op;
     103        Py_INCREF(op);
     104    } else if (size == 1 && str != NULL) {
     105        PyObject *t = (PyObject *)op;
     106        PyString_InternInPlace(&t);
     107        op = (PyStringObject *)t;
     108        characters[*str & UCHAR_MAX] = op;
     109        Py_INCREF(op);
     110    }
     111    return (PyObject *) op;
    107112}
    108113
     
    110115PyString_FromString(const char *str)
    111116{
    112         register size_t size;
    113         register PyStringObject *op;
    114 
    115         assert(str != NULL);
    116         size = strlen(str);
    117         if (size > PY_SSIZE_T_MAX - sizeof(PyStringObject)) {
    118                 PyErr_SetString(PyExc_OverflowError,
    119                         "string is too long for a Python string");
    120                 return NULL;
    121         }
    122         if (size == 0 && (op = nullstring) != NULL) {
     117    register size_t size;
     118    register PyStringObject *op;
     119
     120    assert(str != NULL);
     121    size = strlen(str);
     122    if (size > PY_SSIZE_T_MAX - PyStringObject_SIZE) {
     123        PyErr_SetString(PyExc_OverflowError,
     124            "string is too long for a Python string");
     125        return NULL;
     126    }
     127    if (size == 0 && (op = nullstring) != NULL) {
    123128#ifdef COUNT_ALLOCS
    124                 null_strings++;
     129        null_strings++;
    125130#endif
    126                 Py_INCREF(op);
    127                 return (PyObject *)op;
    128         }
    129         if (size == 1 && (op = characters[*str & UCHAR_MAX]) != NULL) {
     131        Py_INCREF(op);
     132        return (PyObject *)op;
     133    }
     134    if (size == 1 && (op = characters[*str & UCHAR_MAX]) != NULL) {
    130135#ifdef COUNT_ALLOCS
    131                 one_strings++;
     136        one_strings++;
    132137#endif
    133                 Py_INCREF(op);
    134                 return (PyObject *)op;
    135         }
    136 
    137         /* Inline PyObject_NewVar */
    138         op = (PyStringObject *)PyObject_MALLOC(sizeof(PyStringObject) + size);
    139         if (op == NULL)
    140                 return PyErr_NoMemory();
    141         PyObject_INIT_VAR(op, &PyString_Type, size);
    142         op->ob_shash = -1;
    143         op->ob_sstate = SSTATE_NOT_INTERNED;
    144         Py_MEMCPY(op->ob_sval, str, size+1);
    145         /* share short strings */
    146         if (size == 0) {
    147                 PyObject *t = (PyObject *)op;
    148                 PyString_InternInPlace(&t);
    149                 op = (PyStringObject *)t;
    150                 nullstring = op;
    151                 Py_INCREF(op);
    152         } else if (size == 1) {
    153                 PyObject *t = (PyObject *)op;
    154                 PyString_InternInPlace(&t);
    155                 op = (PyStringObject *)t;
    156                 characters[*str & UCHAR_MAX] = op;
    157                 Py_INCREF(op);
    158         }
    159         return (PyObject *) op;
     138        Py_INCREF(op);
     139        return (PyObject *)op;
     140    }
     141
     142    /* Inline PyObject_NewVar */
     143    op = (PyStringObject *)PyObject_MALLOC(PyStringObject_SIZE + size);
     144    if (op == NULL)
     145        return PyErr_NoMemory();
     146    PyObject_INIT_VAR(op, &PyString_Type, size);
     147    op->ob_shash = -1;
     148    op->ob_sstate = SSTATE_NOT_INTERNED;
     149    Py_MEMCPY(op->ob_sval, str, size+1);
     150    /* share short strings */
     151    if (size == 0) {
     152        PyObject *t = (PyObject *)op;
     153        PyString_InternInPlace(&t);
     154        op = (PyStringObject *)t;
     155        nullstring = op;
     156        Py_INCREF(op);
     157    } else if (size == 1) {
     158        PyObject *t = (PyObject *)op;
     159        PyString_InternInPlace(&t);
     160        op = (PyStringObject *)t;
     161        characters[*str & UCHAR_MAX] = op;
     162        Py_INCREF(op);
     163    }
     164    return (PyObject *) op;
    160165}
    161166
     
    163168PyString_FromFormatV(const char *format, va_list vargs)
    164169{
    165         va_list count;
    166         Py_ssize_t n = 0;
    167         const char* f;
    168         char *s;
    169         PyObject* string;
     170    va_list count;
     171    Py_ssize_t n = 0;
     172    const char* f;
     173    char *s;
     174    PyObject* string;
    170175
    171176#ifdef VA_LIST_IS_ARRAY
    172         Py_MEMCPY(count, vargs, sizeof(va_list));
     177    Py_MEMCPY(count, vargs, sizeof(va_list));
    173178#else
    174179#ifdef  __va_copy
    175         __va_copy(count, vargs);
     180    __va_copy(count, vargs);
    176181#else
    177         count = vargs;
     182    count = vargs;
    178183#endif
    179184#endif
    180         /* step 1: figure out how large a buffer we need */
    181         for (f = format; *f; f++) {
    182                 if (*f == '%') {
    183                         const char* p = f;
    184                         while (*++f && *f != '%' && !isalpha(Py_CHARMASK(*f)))
    185                                 ;
    186 
    187                         /* skip the 'l' or 'z' in {%ld, %zd, %lu, %zu} since
    188                          * they don't affect the amount of space we reserve.
    189                          */
    190                         if ((*f == 'l' || *f == 'z') &&
    191                                         (f[1] == 'd' || f[1] == 'u'))
    192                                 ++f;
    193 
    194                         switch (*f) {
    195                         case 'c':
    196                                 (void)va_arg(count, int);
    197                                 /* fall through... */
    198                         case '%':
    199                                 n++;
    200                                 break;
    201                         case 'd': case 'u': case 'i': case 'x':
    202                                 (void) va_arg(count, int);
    203                                 /* 20 bytes is enough to hold a 64-bit
    204                                    integer.  Decimal takes the most space.
    205                                    This isn't enough for octal. */
    206                                 n += 20;
    207                                 break;
    208                         case 's':
    209                                 s = va_arg(count, char*);
    210                                 n += strlen(s);
    211                                 break;
    212                         case 'p':
    213                                 (void) va_arg(count, int);
    214                                 /* maximum 64-bit pointer representation:
    215                                  * 0xffffffffffffffff
    216                                  * so 19 characters is enough.
    217                                  * XXX I count 18 -- what's the extra for?
    218                                  */
    219                                 n += 19;
    220                                 break;
    221                         default:
    222                                 /* if we stumble upon an unknown
    223                                    formatting code, copy the rest of
    224                                    the format string to the output
    225                                    string. (we cannot just skip the
    226                                    code, since there's no way to know
    227                                    what's in the argument list) */
    228                                 n += strlen(p);
    229                                 goto expand;
    230                         }
    231                 } else
    232                         n++;
    233         }
     185    /* step 1: figure out how large a buffer we need */
     186    for (f = format; *f; f++) {
     187        if (*f == '%') {
     188#ifdef HAVE_LONG_LONG
     189            int longlongflag = 0;
     190#endif
     191            const char* p = f;
     192            while (*++f && *f != '%' && !isalpha(Py_CHARMASK(*f)))
     193                ;
     194
     195            /* skip the 'l' or 'z' in {%ld, %zd, %lu, %zu} since
     196             * they don't affect the amount of space we reserve.
     197             */
     198            if (*f == 'l') {
     199                if (f[1] == 'd' || f[1] == 'u') {
     200                    ++f;
     201                }
     202#ifdef HAVE_LONG_LONG
     203                else if (f[1] == 'l' &&
     204                         (f[2] == 'd' || f[2] == 'u')) {
     205                    longlongflag = 1;
     206                    f += 2;
     207                }
     208#endif
     209            }
     210            else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u')) {
     211                ++f;
     212            }
     213
     214            switch (*f) {
     215            case 'c':
     216                (void)va_arg(count, int);
     217                /* fall through... */
     218            case '%':
     219                n++;
     220                break;
     221            case 'd': case 'u': case 'i': case 'x':
     222                (void) va_arg(count, int);
     223#ifdef HAVE_LONG_LONG
     224                /* Need at most
     225                   ceil(log10(256)*SIZEOF_LONG_LONG) digits,
     226                   plus 1 for the sign.  53/22 is an upper
     227                   bound for log10(256). */
     228                if (longlongflag)
     229                    n += 2 + (SIZEOF_LONG_LONG*53-1) / 22;
     230                else
     231#endif
     232                    /* 20 bytes is enough to hold a 64-bit
     233                       integer.  Decimal takes the most
     234                       space.  This isn't enough for
     235                       octal. */
     236                    n += 20;
     237
     238                break;
     239            case 's':
     240                s = va_arg(count, char*);
     241                n += strlen(s);
     242                break;
     243            case 'p':
     244                (void) va_arg(count, int);
     245                /* maximum 64-bit pointer representation:
     246                 * 0xffffffffffffffff
     247                 * so 19 characters is enough.
     248                 * XXX I count 18 -- what's the extra for?
     249                 */
     250                n += 19;
     251                break;
     252            default:
     253                /* if we stumble upon an unknown
     254                   formatting code, copy the rest of
     255                   the format string to the output
     256                   string. (we cannot just skip the
     257                   code, since there's no way to know
     258                   what's in the argument list) */
     259                n += strlen(p);
     260                goto expand;
     261            }
     262        } else
     263            n++;
     264    }
    234265 expand:
    235         /* step 2: fill the buffer */
    236         /* Since we've analyzed how much space we need for the worst case,
    237            use sprintf directly instead of the slower PyOS_snprintf. */
    238         string = PyString_FromStringAndSize(NULL, n);
    239         if (!string)
    240                 return NULL;
    241 
    242         s = PyString_AsString(string);
    243 
    244         for (f = format; *f; f++) {
    245                 if (*f == '%') {
    246                         const char* p = f++;
    247                         Py_ssize_t i;
    248                         int longflag = 0;
    249                         int size_tflag = 0;
    250                         /* parse the width.precision part (we're only
    251                            interested in the precision value, if any) */
    252                         n = 0;
    253                         while (isdigit(Py_CHARMASK(*f)))
    254                                 n = (n*10) + *f++ - '0';
    255                         if (*f == '.') {
    256                                 f++;
    257                                 n = 0;
    258                                 while (isdigit(Py_CHARMASK(*f)))
    259                                         n = (n*10) + *f++ - '0';
    260                         }
    261                         while (*f && *f != '%' && !isalpha(Py_CHARMASK(*f)))
    262                                 f++;
    263                         /* handle the long flag, but only for %ld and %lu.
    264                            others can be added when necessary. */
    265                         if (*f == 'l' && (f[1] == 'd' || f[1] == 'u')) {
    266                                 longflag = 1;
    267                                 ++f;
    268                         }
    269                         /* handle the size_t flag. */
    270                         if (*f == 'z' && (f[1] == 'd' || f[1] == 'u')) {
    271                                 size_tflag = 1;
    272                                 ++f;
    273                         }
    274 
    275                         switch (*f) {
    276                         case 'c':
    277                                 *s++ = va_arg(vargs, int);
    278                                 break;
    279                         case 'd':
    280                                 if (longflag)
    281                                         sprintf(s, "%ld", va_arg(vargs, long));
    282                                 else if (size_tflag)
    283                                         sprintf(s, "%" PY_FORMAT_SIZE_T "d",
    284                                                 va_arg(vargs, Py_ssize_t));
    285                                 else
    286                                         sprintf(s, "%d", va_arg(vargs, int));
    287                                 s += strlen(s);
    288                                 break;
    289                         case 'u':
    290                                 if (longflag)
    291                                         sprintf(s, "%lu",
    292                                                 va_arg(vargs, unsigned long));
    293                                 else if (size_tflag)
    294                                         sprintf(s, "%" PY_FORMAT_SIZE_T "u",
    295                                                 va_arg(vargs, size_t));
    296                                 else
    297                                         sprintf(s, "%u",
    298                                                 va_arg(vargs, unsigned int));
    299                                 s += strlen(s);
    300                                 break;
    301                         case 'i':
    302                                 sprintf(s, "%i", va_arg(vargs, int));
    303                                 s += strlen(s);
    304                                 break;
    305                         case 'x':
    306                                 sprintf(s, "%x", va_arg(vargs, int));
    307                                 s += strlen(s);
    308                                 break;
    309                         case 's':
    310                                 p = va_arg(vargs, char*);
    311                                 i = strlen(p);
    312                                 if (n > 0 && i > n)
    313                                         i = n;
    314                                 Py_MEMCPY(s, p, i);
    315                                 s += i;
    316                                 break;
    317                         case 'p':
    318                                 sprintf(s, "%p", va_arg(vargs, void*));
    319                                 /* %p is ill-defined:  ensure leading 0x. */
    320                                 if (s[1] == 'X')
    321                                         s[1] = 'x';
    322                                 else if (s[1] != 'x') {
    323                                         memmove(s+2, s, strlen(s)+1);
    324                                         s[0] = '0';
    325                                         s[1] = 'x';
    326                                 }
    327                                 s += strlen(s);
    328                                 break;
    329                         case '%':
    330                                 *s++ = '%';
    331                                 break;
    332                         default:
    333                                 strcpy(s, p);
    334                                 s += strlen(s);
    335                                 goto end;
    336                         }
    337                 } else
    338                         *s++ = *f;
    339         }
     266    /* step 2: fill the buffer */
     267    /* Since we've analyzed how much space we need for the worst case,
     268       use sprintf directly instead of the slower PyOS_snprintf. */
     269    string = PyString_FromStringAndSize(NULL, n);
     270    if (!string)
     271        return NULL;
     272
     273    s = PyString_AsString(string);
     274
     275    for (f = format; *f; f++) {
     276        if (*f == '%') {
     277            const char* p = f++;
     278            Py_ssize_t i;
     279            int longflag = 0;
     280#ifdef HAVE_LONG_LONG
     281            int longlongflag = 0;
     282#endif
     283            int size_tflag = 0;
     284            /* parse the width.precision part (we're only
     285               interested in the precision value, if any) */
     286            n = 0;
     287            while (isdigit(Py_CHARMASK(*f)))
     288                n = (n*10) + *f++ - '0';
     289            if (*f == '.') {
     290                f++;
     291                n = 0;
     292                while (isdigit(Py_CHARMASK(*f)))
     293                    n = (n*10) + *f++ - '0';
     294            }
     295            while (*f && *f != '%' && !isalpha(Py_CHARMASK(*f)))
     296                f++;
     297            /* Handle %ld, %lu, %lld and %llu. */
     298            if (*f == 'l') {
     299                if (f[1] == 'd' || f[1] == 'u') {
     300                    longflag = 1;
     301                    ++f;
     302                }
     303#ifdef HAVE_LONG_LONG
     304                else if (f[1] == 'l' &&
     305                         (f[2] == 'd' || f[2] == 'u')) {
     306                    longlongflag = 1;
     307                    f += 2;
     308                }
     309#endif
     310            }
     311            /* handle the size_t flag. */
     312            else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u')) {
     313                size_tflag = 1;
     314                ++f;
     315            }
     316
     317            switch (*f) {
     318            case 'c':
     319                *s++ = va_arg(vargs, int);
     320                break;
     321            case 'd':
     322                if (longflag)
     323                    sprintf(s, "%ld", va_arg(vargs, long));
     324#ifdef HAVE_LONG_LONG
     325                else if (longlongflag)
     326                    sprintf(s, "%" PY_FORMAT_LONG_LONG "d",
     327                        va_arg(vargs, PY_LONG_LONG));
     328#endif
     329                else if (size_tflag)
     330                    sprintf(s, "%" PY_FORMAT_SIZE_T "d",
     331                        va_arg(vargs, Py_ssize_t));
     332                else
     333                    sprintf(s, "%d", va_arg(vargs, int));
     334                s += strlen(s);
     335                break;
     336            case 'u':
     337                if (longflag)
     338                    sprintf(s, "%lu",
     339                        va_arg(vargs, unsigned long));
     340#ifdef HAVE_LONG_LONG
     341                else if (longlongflag)
     342                    sprintf(s, "%" PY_FORMAT_LONG_LONG "u",
     343                        va_arg(vargs, PY_LONG_LONG));
     344#endif
     345                else if (size_tflag)
     346                    sprintf(s, "%" PY_FORMAT_SIZE_T "u",
     347                        va_arg(vargs, size_t));
     348                else
     349                    sprintf(s, "%u",
     350                        va_arg(vargs, unsigned int));
     351                s += strlen(s);
     352                break;
     353            case 'i':
     354                sprintf(s, "%i", va_arg(vargs, int));
     355                s += strlen(s);
     356                break;
     357            case 'x':
     358                sprintf(s, "%x", va_arg(vargs, int));
     359                s += strlen(s);
     360                break;
     361            case 's':
     362                p = va_arg(vargs, char*);
     363                i = strlen(p);
     364                if (n > 0 && i > n)
     365                    i = n;
     366                Py_MEMCPY(s, p, i);
     367                s += i;
     368                break;
     369            case 'p':
     370                sprintf(s, "%p", va_arg(vargs, void*));
     371                /* %p is ill-defined:  ensure leading 0x. */
     372                if (s[1] == 'X')
     373                    s[1] = 'x';
     374                else if (s[1] != 'x') {
     375                    memmove(s+2, s, strlen(s)+1);
     376                    s[0] = '0';
     377                    s[1] = 'x';
     378                }
     379                s += strlen(s);
     380                break;
     381            case '%':
     382                *s++ = '%';
     383                break;
     384            default:
     385                strcpy(s, p);
     386                s += strlen(s);
     387                goto end;
     388            }
     389        } else
     390            *s++ = *f;
     391    }
    340392
    341393 end:
    342         _PyString_Resize(&string, s - PyString_AS_STRING(string));
    343         return string;
     394    if (_PyString_Resize(&string, s - PyString_AS_STRING(string)))
     395        return NULL;
     396    return string;
    344397}
    345398
     
    347400PyString_FromFormat(const char *format, ...)
    348401{
    349         PyObject* ret;
    350         va_list vargs;
     402    PyObject* ret;
     403    va_list vargs;
    351404
    352405#ifdef HAVE_STDARG_PROTOTYPES
    353         va_start(vargs, format);
     406    va_start(vargs, format);
    354407#else
    355         va_start(vargs);
     408    va_start(vargs);
    356409#endif
    357         ret = PyString_FromFormatV(format, vargs);
    358         va_end(vargs);
    359         return ret;
     410    ret = PyString_FromFormatV(format, vargs);
     411    va_end(vargs);
     412    return ret;
    360413}
    361414
    362415
    363416PyObject *PyString_Decode(const char *s,
    364                           Py_ssize_t size,
    365                           const char *encoding,
    366                           const char *errors)
     417                          Py_ssize_t size,
     418                          const char *encoding,
     419                          const char *errors)
    367420{
    368421    PyObject *v, *str;
     
    370423    str = PyString_FromStringAndSize(s, size);
    371424    if (str == NULL)
    372         return NULL;
     425        return NULL;
    373426    v = PyString_AsDecodedString(str, encoding, errors);
    374427    Py_DECREF(str);
     
    377430
    378431PyObject *PyString_AsDecodedObject(PyObject *str,
    379                                    const char *encoding,
    380                                    const char *errors)
     432                                   const char *encoding,
     433                                   const char *errors)
    381434{
    382435    PyObject *v;
     
    389442    if (encoding == NULL) {
    390443#ifdef Py_USING_UNICODE
    391         encoding = PyUnicode_GetDefaultEncoding();
     444        encoding = PyUnicode_GetDefaultEncoding();
    392445#else
    393         PyErr_SetString(PyExc_ValueError, "no encoding specified");
    394         goto onError;
     446        PyErr_SetString(PyExc_ValueError, "no encoding specified");
     447        goto onError;
    395448#endif
    396449    }
     
    408461
    409462PyObject *PyString_AsDecodedString(PyObject *str,
    410                                    const char *encoding,
    411                                    const char *errors)
     463                                   const char *encoding,
     464                                   const char *errors)
    412465{
    413466    PyObject *v;
     
    420473    /* Convert Unicode to a string using the default encoding */
    421474    if (PyUnicode_Check(v)) {
    422         PyObject *temp = v;
    423         v = PyUnicode_AsEncodedString(v, NULL, NULL);
    424         Py_DECREF(temp);
    425         if (v == NULL)
    426             goto onError;
     475        PyObject *temp = v;
     476        v = PyUnicode_AsEncodedString(v, NULL, NULL);
     477        Py_DECREF(temp);
     478        if (v == NULL)
     479            goto onError;
    427480    }
    428481#endif
     
    442495
    443496PyObject *PyString_Encode(const char *s,
    444                           Py_ssize_t size,
    445                           const char *encoding,
    446                           const char *errors)
     497                          Py_ssize_t size,
     498                          const char *encoding,
     499                          const char *errors)
    447500{
    448501    PyObject *v, *str;
     
    450503    str = PyString_FromStringAndSize(s, size);
    451504    if (str == NULL)
    452         return NULL;
     505        return NULL;
    453506    v = PyString_AsEncodedString(str, encoding, errors);
    454507    Py_DECREF(str);
     
    457510
    458511PyObject *PyString_AsEncodedObject(PyObject *str,
    459                                    const char *encoding,
    460                                    const char *errors)
     512                                   const char *encoding,
     513                                   const char *errors)
    461514{
    462515    PyObject *v;
     
    469522    if (encoding == NULL) {
    470523#ifdef Py_USING_UNICODE
    471         encoding = PyUnicode_GetDefaultEncoding();
     524        encoding = PyUnicode_GetDefaultEncoding();
    472525#else
    473         PyErr_SetString(PyExc_ValueError, "no encoding specified");
    474         goto onError;
     526        PyErr_SetString(PyExc_ValueError, "no encoding specified");
     527        goto onError;
    475528#endif
    476529    }
     
    488541
    489542PyObject *PyString_AsEncodedString(PyObject *str,
    490                                    const char *encoding,
    491                                    const char *errors)
     543                                   const char *encoding,
     544                                   const char *errors)
    492545{
    493546    PyObject *v;
     
    500553    /* Convert Unicode to a string using the default encoding */
    501554    if (PyUnicode_Check(v)) {
    502         PyObject *temp = v;
    503         v = PyUnicode_AsEncodedString(v, NULL, NULL);
    504         Py_DECREF(temp);
    505         if (v == NULL)
    506             goto onError;
     555        PyObject *temp = v;
     556        v = PyUnicode_AsEncodedString(v, NULL, NULL);
     557        Py_DECREF(temp);
     558        if (v == NULL)
     559            goto onError;
    507560    }
    508561#endif
     
    524577string_dealloc(PyObject *op)
    525578{
    526         switch (PyString_CHECK_INTERNED(op)) {
    527                 case SSTATE_NOT_INTERNED:
    528                         break;
    529 
    530                 case SSTATE_INTERNED_MORTAL:
    531                         /* revive dead object temporarily for DelItem */
    532                         Py_REFCNT(op) = 3;
    533                         if (PyDict_DelItem(interned, op) != 0)
    534                                 Py_FatalError(
    535                                         "deletion of interned string failed");
    536                         break;
    537 
    538                 case SSTATE_INTERNED_IMMORTAL:
    539                         Py_FatalError("Immortal interned string died.");
    540 
    541                 default:
    542                         Py_FatalError("Inconsistent interned string state.");
    543         }
    544         Py_TYPE(op)->tp_free(op);
     579    switch (PyString_CHECK_INTERNED(op)) {
     580        case SSTATE_NOT_INTERNED:
     581            break;
     582
     583        case SSTATE_INTERNED_MORTAL:
     584            /* revive dead object temporarily for DelItem */
     585            Py_REFCNT(op) = 3;
     586            if (PyDict_DelItem(interned, op) != 0)
     587                Py_FatalError(
     588                    "deletion of interned string failed");
     589            break;
     590
     591        case SSTATE_INTERNED_IMMORTAL:
     592            Py_FatalError("Immortal interned string died.");
     593
     594        default:
     595            Py_FatalError("Inconsistent interned string state.");
     596    }
     597    Py_TYPE(op)->tp_free(op);
    545598}
    546599
     
    551604
    552605PyObject *PyString_DecodeEscape(const char *s,
    553                                 Py_ssize_t len,
    554                                 const char *errors,
    555                                 Py_ssize_t unicode,
    556                                 const char *recode_encoding)
    557 {
    558         int c;
    559         char *p, *buf;
    560         const char *end;
    561         PyObject *v;
    562         Py_ssize_t newlen = recode_encoding ? 4*len:len;
    563         v = PyString_FromStringAndSize((char *)NULL, newlen);
    564         if (v == NULL)
    565                 return NULL;
    566         p = buf = PyString_AsString(v);
    567         end = s + len;
    568         while (s < end) {
    569                 if (*s != '\\') {
    570                   non_esc:
     606                                Py_ssize_t len,
     607                                const char *errors,
     608                                Py_ssize_t unicode,
     609                                const char *recode_encoding)
     610{
     611    int c;
     612    char *p, *buf;
     613    const char *end;
     614    PyObject *v;
     615    Py_ssize_t newlen = recode_encoding ? 4*len:len;
     616    v = PyString_FromStringAndSize((char *)NULL, newlen);
     617    if (v == NULL)
     618        return NULL;
     619    p = buf = PyString_AsString(v);
     620    end = s + len;
     621    while (s < end) {
     622        if (*s != '\\') {
     623          non_esc:
    571624#ifdef Py_USING_UNICODE
    572                         if (recode_encoding && (*s & 0x80)) {
    573                                 PyObject *u, *w;
    574                                 char *r;
    575                                 const char* t;
    576                                 Py_ssize_t rn;
    577                                 t = s;
    578                                 /* Decode non-ASCII bytes as UTF-8. */
    579                                 while (t < end && (*t & 0x80)) t++;
    580                                 u = PyUnicode_DecodeUTF8(s, t - s, errors);
    581                                 if(!u) goto failed;
    582 
    583                                 /* Recode them in target encoding. */
    584                                 w = PyUnicode_AsEncodedString(
    585                                         u, recode_encoding, errors);
    586                                 Py_DECREF(u);
    587                                 if (!w) goto failed;
    588 
    589                                 /* Append bytes to output buffer. */
    590                                 assert(PyString_Check(w));
    591                                 r = PyString_AS_STRING(w);
    592                                 rn = PyString_GET_SIZE(w);
    593                                 Py_MEMCPY(p, r, rn);
    594                                 p += rn;
    595                                 Py_DECREF(w);
    596                                 s = t;
    597                         } else {
    598                                 *p++ = *s++;
    599                         }
     625            if (recode_encoding && (*s & 0x80)) {
     626                PyObject *u, *w;
     627                char *r;
     628                const char* t;
     629                Py_ssize_t rn;
     630                t = s;
     631                /* Decode non-ASCII bytes as UTF-8. */
     632                while (t < end && (*t & 0x80)) t++;
     633                u = PyUnicode_DecodeUTF8(s, t - s, errors);
     634                if(!u) goto failed;
     635
     636                /* Recode them in target encoding. */
     637                w = PyUnicode_AsEncodedString(
     638                    u, recode_encoding, errors);
     639                Py_DECREF(u);
     640                if (!w)                 goto failed;
     641
     642                /* Append bytes to output buffer. */
     643                assert(PyString_Check(w));
     644                r = PyString_AS_STRING(w);
     645                rn = PyString_GET_SIZE(w);
     646                Py_MEMCPY(p, r, rn);
     647                p += rn;
     648                Py_DECREF(w);
     649                s = t;
     650            } else {
     651                *p++ = *s++;
     652            }
    600653#else
    601                         *p++ = *s++;
     654            *p++ = *s++;
    602655#endif
    603                         continue;
    604                 }
    605                 s++;
    606                 if (s==end) {
    607                         PyErr_SetString(PyExc_ValueError,
    608                                         "Trailing \\ in string");
    609                         goto failed;
    610                 }
    611                 switch (*s++) {
    612                 /* XXX This assumes ASCII! */
    613                 case '\n': break;
    614                 case '\\': *p++ = '\\'; break;
    615                 case '\'': *p++ = '\''; break;
    616                 case '\"': *p++ = '\"'; break;
    617                 case 'b': *p++ = '\b'; break;
    618                 case 'f': *p++ = '\014'; break; /* FF */
    619                 case 't': *p++ = '\t'; break;
    620                 case 'n': *p++ = '\n'; break;
    621                 case 'r': *p++ = '\r'; break;
    622                 case 'v': *p++ = '\013'; break; /* VT */
    623                 case 'a': *p++ = '\007'; break; /* BEL, not classic C */
    624                 case '0': case '1': case '2': case '3':
    625                 case '4': case '5': case '6': case '7':
    626                         c = s[-1] - '0';
    627                         if (s < end && '0' <= *s && *s <= '7') {
    628                                 c = (c<<3) + *s++ - '0';
    629                                 if (s < end && '0' <= *s && *s <= '7')
    630                                         c = (c<<3) + *s++ - '0';
    631                         }
    632                         *p++ = c;
    633                         break;
    634                 case 'x':
    635                         if (s+1 < end &&
    636                             isxdigit(Py_CHARMASK(s[0])) &&
    637                             isxdigit(Py_CHARMASK(s[1])))
    638                         {
    639                                 unsigned int x = 0;
    640                                 c = Py_CHARMASK(*s);
    641                                 s++;
    642                                 if (isdigit(c))
    643                                         x = c - '0';
    644                                 else if (islower(c))
    645                                         x = 10 + c - 'a';
    646                                 else
    647                                         x = 10 + c - 'A';
    648                                 x = x << 4;
    649                                 c = Py_CHARMASK(*s);
    650                                 s++;
    651                                 if (isdigit(c))
    652                                         x += c - '0';
    653                                 else if (islower(c))
    654                                         x += 10 + c - 'a';
    655                                 else
    656                                         x += 10 + c - 'A';
    657                                 *p++ = x;
    658                                 break;
    659                         }
    660                         if (!errors || strcmp(errors, "strict") == 0) {
    661                                 PyErr_SetString(PyExc_ValueError,
    662                                                 "invalid \\x escape");
    663                                 goto failed;
    664                         }
    665                         if (strcmp(errors, "replace") == 0) {
    666                                 *p++ = '?';
    667                         } else if (strcmp(errors, "ignore") == 0)
    668                                 /* do nothing */;
    669                         else {
    670                                 PyErr_Format(PyExc_ValueError,
    671                                              "decoding error; "
    672                                              "unknown error handling code: %.400s",
    673                                              errors);
    674                                 goto failed;
    675                         }
     656            continue;
     657        }
     658        s++;
     659        if (s==end) {
     660            PyErr_SetString(PyExc_ValueError,
     661                            "Trailing \\ in string");
     662            goto failed;
     663        }
     664        switch (*s++) {
     665        /* XXX This assumes ASCII! */
     666        case '\n': break;
     667        case '\\': *p++ = '\\'; break;
     668        case '\'': *p++ = '\''; break;
     669        case '\"': *p++ = '\"'; break;
     670        case 'b': *p++ = '\b'; break;
     671        case 'f': *p++ = '\014'; break; /* FF */
     672        case 't': *p++ = '\t'; break;
     673        case 'n': *p++ = '\n'; break;
     674        case 'r': *p++ = '\r'; break;
     675        case 'v': *p++ = '\013'; break; /* VT */
     676        case 'a': *p++ = '\007'; break; /* BEL, not classic C */
     677        case '0': case '1': case '2': case '3':
     678        case '4': case '5': case '6': case '7':
     679            c = s[-1] - '0';
     680            if (s < end && '0' <= *s && *s <= '7') {
     681                c = (c<<3) + *s++ - '0';
     682                if (s < end && '0' <= *s && *s <= '7')
     683                    c = (c<<3) + *s++ - '0';
     684            }
     685            *p++ = c;
     686            break;
     687        case 'x':
     688            if (s+1 < end &&
     689                isxdigit(Py_CHARMASK(s[0])) &&
     690                isxdigit(Py_CHARMASK(s[1])))
     691            {
     692                unsigned int x = 0;
     693                c = Py_CHARMASK(*s);
     694                s++;
     695                if (isdigit(c))
     696                    x = c - '0';
     697                else if (islower(c))
     698                    x = 10 + c - 'a';
     699                else
     700                    x = 10 + c - 'A';
     701                x = x << 4;
     702                c = Py_CHARMASK(*s);
     703                s++;
     704                if (isdigit(c))
     705                    x += c - '0';
     706                else if (islower(c))
     707                    x += 10 + c - 'a';
     708                else
     709                    x += 10 + c - 'A';
     710                *p++ = x;
     711                break;
     712            }
     713            if (!errors || strcmp(errors, "strict") == 0) {
     714                PyErr_SetString(PyExc_ValueError,
     715                                "invalid \\x escape");
     716                goto failed;
     717            }
     718            if (strcmp(errors, "replace") == 0) {
     719                *p++ = '?';
     720            } else if (strcmp(errors, "ignore") == 0)
     721                /* do nothing */;
     722            else {
     723                PyErr_Format(PyExc_ValueError,
     724                             "decoding error; "
     725                             "unknown error handling code: %.400s",
     726                             errors);
     727                goto failed;
     728            }
     729            /* skip \x */
     730            if (s < end && isxdigit(Py_CHARMASK(s[0])))
     731                s++; /* and a hexdigit */
     732            break;
    676733#ifndef Py_USING_UNICODE
    677                 case 'u':
    678                 case 'U':
    679                 case 'N':
    680                         if (unicode) {
    681                                 PyErr_SetString(PyExc_ValueError,
    682                                           "Unicode escapes not legal "
    683                                           "when Unicode disabled");
    684                                 goto failed;
    685                         }
     734        case 'u':
     735        case 'U':
     736        case 'N':
     737            if (unicode) {
     738                PyErr_SetString(PyExc_ValueError,
     739                          "Unicode escapes not legal "
     740                          "when Unicode disabled");
     741                goto failed;
     742            }
    686743#endif
    687                 default:
    688                         *p++ = '\\';
    689                         s--;
    690                         goto non_esc; /* an arbitry number of unescaped
    691                                         UTF-8 bytes may follow. */
    692                 }
    693         }
    694         if (p-buf < newlen)
    695                 _PyString_Resize(&v, p - buf);
    696         return v;
     744        default:
     745            *p++ = '\\';
     746            s--;
     747            goto non_esc; /* an arbitrary number of unescaped
     748                            UTF-8 bytes may follow. */
     749        }
     750    }
     751    if (p-buf < newlen && _PyString_Resize(&v, p - buf))
     752        goto failed;
     753    return v;
    697754  failed:
    698         Py_DECREF(v);
    699         return NULL;
     755    Py_DECREF(v);
     756    return NULL;
    700757}
    701758
     
    706763string_getsize(register PyObject *op)
    707764{
    708         char *s;
    709         Py_ssize_t len;
    710         if (PyString_AsStringAndSize(op, &s, &len))
    711                 return -1;
    712         return len;
     765    char *s;
     766    Py_ssize_t len;
     767    if (PyString_AsStringAndSize(op, &s, &len))
     768        return -1;
     769    return len;
    713770}
    714771
     
    716773string_getbuffer(register PyObject *op)
    717774{
    718         char *s;
    719         Py_ssize_t len;
    720         if (PyString_AsStringAndSize(op, &s, &len))
    721                 return NULL;
    722         return s;
     775    char *s;
     776    Py_ssize_t len;
     777    if (PyString_AsStringAndSize(op, &s, &len))
     778        return NULL;
     779    return s;
    723780}
    724781
     
    726783PyString_Size(register PyObject *op)
    727784{
    728         if (!PyString_Check(op))
    729                 return string_getsize(op);
    730         return Py_SIZE(op);
     785    if (!PyString_Check(op))
     786        return string_getsize(op);
     787    return Py_SIZE(op);
    731788}
    732789
     
    734791PyString_AsString(register PyObject *op)
    735792{
    736         if (!PyString_Check(op))
    737                 return string_getbuffer(op);
    738         return ((PyStringObject *)op) -> ob_sval;
     793    if (!PyString_Check(op))
     794        return string_getbuffer(op);
     795    return ((PyStringObject *)op) -> ob_sval;
    739796}
    740797
    741798int
    742799PyString_AsStringAndSize(register PyObject *obj,
    743                         register char **s,
    744                         register Py_ssize_t *len)
    745 {
    746         if (s == NULL) {
    747                 PyErr_BadInternalCall();
    748                 return -1;
    749         }
    750 
    751         if (!PyString_Check(obj)) {
     800                        register char **s,
     801                        register Py_ssize_t *len)
     802{
     803    if (s == NULL) {
     804        PyErr_BadInternalCall();
     805        return -1;
     806    }
     807
     808    if (!PyString_Check(obj)) {
    752809#ifdef Py_USING_UNICODE
    753                 if (PyUnicode_Check(obj)) {
    754                         obj = _PyUnicode_AsDefaultEncodedString(obj, NULL);
    755                         if (obj == NULL)
    756                                 return -1;
    757                 }
    758                 else
     810        if (PyUnicode_Check(obj)) {
     811            obj = _PyUnicode_AsDefaultEncodedString(obj, NULL);
     812            if (obj == NULL)
     813                return -1;
     814        }
     815        else
    759816#endif
    760                 {
    761                         PyErr_Format(PyExc_TypeError,
    762                                      "expected string or Unicode object, "
    763                                      "%.200s found", Py_TYPE(obj)->tp_name);
    764                         return -1;
    765                 }
    766         }
    767 
    768         *s = PyString_AS_STRING(obj);
    769         if (len != NULL)
    770                 *len = PyString_GET_SIZE(obj);
    771         else if (strlen(*s) != (size_t)PyString_GET_SIZE(obj)) {
    772                 PyErr_SetString(PyExc_TypeError,
    773                                 "expected string without null bytes");
    774                 return -1;
    775         }
    776         return 0;
     817        {
     818            PyErr_Format(PyExc_TypeError,
     819                         "expected string or Unicode object, "
     820                         "%.200s found", Py_TYPE(obj)->tp_name);
     821            return -1;
     822        }
     823    }
     824
     825    *s = PyString_AS_STRING(obj);
     826    if (len != NULL)
     827        *len = PyString_GET_SIZE(obj);
     828    else if (strlen(*s) != (size_t)PyString_GET_SIZE(obj)) {
     829        PyErr_SetString(PyExc_TypeError,
     830                        "expected string without null bytes");
     831        return -1;
     832    }
     833    return 0;
    777834}
    778835
     
    786843#include "stringlib/find.h"
    787844#include "stringlib/partition.h"
     845#include "stringlib/split.h"
    788846
    789847#define _Py_InsertThousandsGrouping _PyString_InsertThousandsGrouping
     
    795853string_print(PyStringObject *op, FILE *fp, int flags)
    796854{
    797         Py_ssize_t i, str_len;
    798         char c;
    799         int quote;
    800 
    801         /* XXX Ought to check for interrupts when writing long strings */
    802         if (! PyString_CheckExact(op)) {
    803                 int ret;
    804                 /* A str subclass may have its own __str__ method. */
    805                 op = (PyStringObject *) PyObject_Str((PyObject *)op);
    806                 if (op == NULL)
    807                         return -1;
    808                 ret = string_print(op, fp, flags);
    809                 Py_DECREF(op);
    810                 return ret;
    811         }
    812         if (flags & Py_PRINT_RAW) {
    813                 char *data = op->ob_sval;
    814                 Py_ssize_t size = Py_SIZE(op);
    815                 Py_BEGIN_ALLOW_THREADS
    816                 while (size > INT_MAX) {
    817                         /* Very long strings cannot be written atomically.
    818                         * But don't write exactly INT_MAX bytes at a time
    819                         * to avoid memory aligment issues.
    820                         */
    821                         const int chunk_size = INT_MAX & ~0x3FFF;
    822                         fwrite(data, 1, chunk_size, fp);
    823                         data += chunk_size;
    824                         size -= chunk_size;
    825                 }
     855    Py_ssize_t i, str_len;
     856    char c;
     857    int quote;
     858
     859    /* XXX Ought to check for interrupts when writing long strings */
     860    if (! PyString_CheckExact(op)) {
     861        int ret;
     862        /* A str subclass may have its own __str__ method. */
     863        op = (PyStringObject *) PyObject_Str((PyObject *)op);
     864        if (op == NULL)
     865            return -1;
     866        ret = string_print(op, fp, flags);
     867        Py_DECREF(op);
     868        return ret;
     869    }
     870    if (flags & Py_PRINT_RAW) {
     871        char *data = op->ob_sval;
     872        Py_ssize_t size = Py_SIZE(op);
     873        Py_BEGIN_ALLOW_THREADS
     874        while (size > INT_MAX) {
     875            /* Very long strings cannot be written atomically.
     876            * But don't write exactly INT_MAX bytes at a time
     877            * to avoid memory aligment issues.
     878            */
     879            const int chunk_size = INT_MAX & ~0x3FFF;
     880            fwrite(data, 1, chunk_size, fp);
     881            data += chunk_size;
     882            size -= chunk_size;
     883        }
    826884#ifdef __VMS
    827                 if (size) fwrite(data, (int)size, 1, fp);
     885        if (size) fwrite(data, (size_t)size, 1, fp);
    828886#else
    829                 fwrite(data, 1, (int)size, fp);
     887        fwrite(data, 1, (size_t)size, fp);
    830888#endif
    831                 Py_END_ALLOW_THREADS
    832                 return 0;
    833         }
    834 
    835         /* figure out which quote to use; single is preferred */
    836         quote = '\'';
    837         if (memchr(op->ob_sval, '\'', Py_SIZE(op)) &&
    838             !memchr(op->ob_sval, '"', Py_SIZE(op)))
    839                 quote = '"';
    840 
    841         str_len = Py_SIZE(op);
    842         Py_BEGIN_ALLOW_THREADS
    843         fputc(quote, fp);
    844         for (i = 0; i < str_len; i++) {
    845                 /* Since strings are immutable and the caller should have a
    846                 reference, accessing the interal buffer should not be an issue
    847                 with the GIL released. */
    848                 c = op->ob_sval[i];
    849                 if (c == quote || c == '\\')
    850                         fprintf(fp, "\\%c", c);
    851                 else if (c == '\t')
    852                         fprintf(fp, "\\t");
    853                 else if (c == '\n')
    854                         fprintf(fp, "\\n");
    855                 else if (c == '\r')
    856                         fprintf(fp, "\\r");
    857                 else if (c < ' ' || c >= 0x7f)
    858                         fprintf(fp, "\\x%02x", c & 0xff);
    859                 else
    860                         fputc(c, fp);
    861         }
    862         fputc(quote, fp);
    863         Py_END_ALLOW_THREADS
    864         return 0;
     889        Py_END_ALLOW_THREADS
     890        return 0;
     891    }
     892
     893    /* figure out which quote to use; single is preferred */
     894    quote = '\'';
     895    if (memchr(op->ob_sval, '\'', Py_SIZE(op)) &&
     896        !memchr(op->ob_sval, '"', Py_SIZE(op)))
     897        quote = '"';
     898
     899    str_len = Py_SIZE(op);
     900    Py_BEGIN_ALLOW_THREADS
     901    fputc(quote, fp);
     902    for (i = 0; i < str_len; i++) {
     903        /* Since strings are immutable and the caller should have a
     904        reference, accessing the interal buffer should not be an issue
     905        with the GIL released. */
     906        c = op->ob_sval[i];
     907        if (c == quote || c == '\\')
     908            fprintf(fp, "\\%c", c);
     909        else if (c == '\t')
     910            fprintf(fp, "\\t");
     911        else if (c == '\n')
     912            fprintf(fp, "\\n");
     913        else if (c == '\r')
     914            fprintf(fp, "\\r");
     915        else if (c < ' ' || c >= 0x7f)
     916            fprintf(fp, "\\x%02x", c & 0xff);
     917        else
     918            fputc(c, fp);
     919    }
     920    fputc(quote, fp);
     921    Py_END_ALLOW_THREADS
     922    return 0;
    865923}
    866924
     
    868926PyString_Repr(PyObject *obj, int smartquotes)
    869927{
    870         register PyStringObject* op = (PyStringObject*) obj;
    871         size_t newsize = 2 + 4 * Py_SIZE(op);
    872         PyObject *v;
    873         if (newsize > PY_SSIZE_T_MAX || newsize / 4 != Py_SIZE(op)) {
    874                 PyErr_SetString(PyExc_OverflowError,
    875                         "string is too large to make repr");
    876                 return NULL;
    877         }
    878         v = PyString_FromStringAndSize((char *)NULL, newsize);
    879         if (v == NULL) {
    880                 return NULL;
    881         }
    882         else {
    883                 register Py_ssize_t i;
    884                 register char c;
    885                 register char *p;
    886                 int quote;
    887 
    888                 /* figure out which quote to use; single is preferred */
    889                 quote = '\'';
    890                 if (smartquotes &&
    891                     memchr(op->ob_sval, '\'', Py_SIZE(op)) &&
    892                     !memchr(op->ob_sval, '"', Py_SIZE(op)))
    893                         quote = '"';
    894 
    895                 p = PyString_AS_STRING(v);
    896                 *p++ = quote;
    897                 for (i = 0; i < Py_SIZE(op); i++) {
    898                         /* There's at least enough room for a hex escape
    899                            and a closing quote. */
    900                         assert(newsize - (p - PyString_AS_STRING(v)) >= 5);
    901                         c = op->ob_sval[i];
    902                         if (c == quote || c == '\\')
    903                                 *p++ = '\\', *p++ = c;
    904                         else if (c == '\t')
    905                                 *p++ = '\\', *p++ = 't';
    906                         else if (c == '\n')
    907                                 *p++ = '\\', *p++ = 'n';
    908                         else if (c == '\r')
    909                                 *p++ = '\\', *p++ = 'r';
    910                         else if (c < ' ' || c >= 0x7f) {
    911                                 /* For performance, we don't want to call
    912                                    PyOS_snprintf here (extra layers of
    913                                    function call). */
    914                                 sprintf(p, "\\x%02x", c & 0xff);
    915                                 p += 4;
    916                         }
    917                         else
    918                                 *p++ = c;
    919                 }
    920                 assert(newsize - (p - PyString_AS_STRING(v)) >= 1);
    921                 *p++ = quote;
    922                 *p = '\0';
    923                 _PyString_Resize(
    924                         &v, (p - PyString_AS_STRING(v)));
    925                 return v;
    926         }
     928    register PyStringObject* op = (PyStringObject*) obj;
     929    size_t newsize = 2 + 4 * Py_SIZE(op);
     930    PyObject *v;
     931    if (newsize > PY_SSIZE_T_MAX || newsize / 4 != Py_SIZE(op)) {
     932        PyErr_SetString(PyExc_OverflowError,
     933            "string is too large to make repr");
     934        return NULL;
     935    }
     936    v = PyString_FromStringAndSize((char *)NULL, newsize);
     937    if (v == NULL) {
     938        return NULL;
     939    }
     940    else {
     941        register Py_ssize_t i;
     942        register char c;
     943        register char *p;
     944        int quote;
     945
     946        /* figure out which quote to use; single is preferred */
     947        quote = '\'';
     948        if (smartquotes &&
     949            memchr(op->ob_sval, '\'', Py_SIZE(op)) &&
     950            !memchr(op->ob_sval, '"', Py_SIZE(op)))
     951            quote = '"';
     952
     953        p = PyString_AS_STRING(v);
     954        *p++ = quote;
     955        for (i = 0; i < Py_SIZE(op); i++) {
     956            /* There's at least enough room for a hex escape
     957               and a closing quote. */
     958            assert(newsize - (p - PyString_AS_STRING(v)) >= 5);
     959            c = op->ob_sval[i];
     960            if (c == quote || c == '\\')
     961                *p++ = '\\', *p++ = c;
     962            else if (c == '\t')
     963                *p++ = '\\', *p++ = 't';
     964            else if (c == '\n')
     965                *p++ = '\\', *p++ = 'n';
     966            else if (c == '\r')
     967                *p++ = '\\', *p++ = 'r';
     968            else if (c < ' ' || c >= 0x7f) {
     969                /* For performance, we don't want to call
     970                   PyOS_snprintf here (extra layers of
     971                   function call). */
     972                sprintf(p, "\\x%02x", c & 0xff);
     973                p += 4;
     974            }
     975            else
     976                *p++ = c;
     977        }
     978        assert(newsize - (p - PyString_AS_STRING(v)) >= 1);
     979        *p++ = quote;
     980        *p = '\0';
     981        if (_PyString_Resize(&v, (p - PyString_AS_STRING(v))))
     982            return NULL;
     983        return v;
     984    }
    927985}
    928986
     
    930988string_repr(PyObject *op)
    931989{
    932         return PyString_Repr(op, 1);
     990    return PyString_Repr(op, 1);
    933991}
    934992
     
    936994string_str(PyObject *s)
    937995{
    938         assert(PyString_Check(s));
    939         if (PyString_CheckExact(s)) {
    940                 Py_INCREF(s);
    941                 return s;
    942         }
    943         else {
    944                 /* Subtype -- return genuine string with the same value. */
    945                 PyStringObject *t = (PyStringObject *) s;
    946                 return PyString_FromStringAndSize(t->ob_sval, Py_SIZE(t));
    947         }
     996    assert(PyString_Check(s));
     997    if (PyString_CheckExact(s)) {
     998        Py_INCREF(s);
     999        return s;
     1000    }
     1001    else {
     1002        /* Subtype -- return genuine string with the same value. */
     1003        PyStringObject *t = (PyStringObject *) s;
     1004        return PyString_FromStringAndSize(t->ob_sval, Py_SIZE(t));
     1005    }
    9481006}
    9491007
     
    9511009string_length(PyStringObject *a)
    9521010{
    953         return Py_SIZE(a);
     1011    return Py_SIZE(a);
    9541012}
    9551013
     
    9571015string_concat(register PyStringObject *a, register PyObject *bb)
    9581016{
    959         register Py_ssize_t size;
    960         register PyStringObject *op;
    961         if (!PyString_Check(bb)) {
     1017    register Py_ssize_t size;
     1018    register PyStringObject *op;
     1019    if (!PyString_Check(bb)) {
    9621020#ifdef Py_USING_UNICODE
    963                 if (PyUnicode_Check(bb))
    964                     return PyUnicode_Concat((PyObject *)a, bb);
     1021        if (PyUnicode_Check(bb))
     1022            return PyUnicode_Concat((PyObject *)a, bb);
    9651023#endif
    966                 if (PyByteArray_Check(bb))
    967                     return PyByteArray_Concat((PyObject *)a, bb);
    968                 PyErr_Format(PyExc_TypeError,
    969                              "cannot concatenate 'str' and '%.200s' objects",
    970                              Py_TYPE(bb)->tp_name);
    971                 return NULL;
    972         }
     1024        if (PyByteArray_Check(bb))
     1025            return PyByteArray_Concat((PyObject *)a, bb);
     1026        PyErr_Format(PyExc_TypeError,
     1027                     "cannot concatenate 'str' and '%.200s' objects",
     1028                     Py_TYPE(bb)->tp_name);
     1029        return NULL;
     1030    }
    9731031#define b ((PyStringObject *)bb)
    974         /* Optimize cases with empty left or right operand */
    975         if ((Py_SIZE(a) == 0 || Py_SIZE(b) == 0) &&
    976             PyString_CheckExact(a) && PyString_CheckExact(b)) {
    977                 if (Py_SIZE(a) == 0) {
    978                         Py_INCREF(bb);
    979                         return bb;
    980                 }
    981                 Py_INCREF(a);
    982                 return (PyObject *)a;
    983         }
    984         size = Py_SIZE(a) + Py_SIZE(b);
    985         /* Check that string sizes are not negative, to prevent an
    986            overflow in cases where we are passed incorrectly-created
    987            strings with negative lengths (due to a bug in other code).
    988         */
    989         if (Py_SIZE(a) < 0 || Py_SIZE(b) < 0 ||
    990             Py_SIZE(a) > PY_SSIZE_T_MAX - Py_SIZE(b)) {
    991                 PyErr_SetString(PyExc_OverflowError,
    992                                 "strings are too large to concat");
    993                 return NULL;
    994         }
    995          
    996         /* Inline PyObject_NewVar */
    997         if (size > PY_SSIZE_T_MAX - sizeof(PyStringObject)) {
    998                 PyErr_SetString(PyExc_OverflowError,
    999                                 "strings are too large to concat");
    1000                 return NULL;
    1001         }
    1002         op = (PyStringObject *)PyObject_MALLOC(sizeof(PyStringObject) + size);
    1003         if (op == NULL)
    1004                 return PyErr_NoMemory();
    1005         PyObject_INIT_VAR(op, &PyString_Type, size);
    1006         op->ob_shash = -1;
    1007         op->ob_sstate = SSTATE_NOT_INTERNED;
    1008         Py_MEMCPY(op->ob_sval, a->ob_sval, Py_SIZE(a));
    1009         Py_MEMCPY(op->ob_sval + Py_SIZE(a), b->ob_sval, Py_SIZE(b));
    1010         op->ob_sval[size] = '\0';
    1011         return (PyObject *) op;
     1032    /* Optimize cases with empty left or right operand */
     1033    if ((Py_SIZE(a) == 0 || Py_SIZE(b) == 0) &&
     1034        PyString_CheckExact(a) && PyString_CheckExact(b)) {
     1035        if (Py_SIZE(a) == 0) {
     1036            Py_INCREF(bb);
     1037            return bb;
     1038        }
     1039        Py_INCREF(a);
     1040        return (PyObject *)a;
     1041    }
     1042    size = Py_SIZE(a) + Py_SIZE(b);
     1043    /* Check that string sizes are not negative, to prevent an
     1044       overflow in cases where we are passed incorrectly-created
     1045       strings with negative lengths (due to a bug in other code).
     1046    */
     1047    if (Py_SIZE(a) < 0 || Py_SIZE(b) < 0 ||
     1048        Py_SIZE(a) > PY_SSIZE_T_MAX - Py_SIZE(b)) {
     1049        PyErr_SetString(PyExc_OverflowError,
     1050                        "strings are too large to concat");
     1051        return NULL;
     1052    }
     1053
     1054    /* Inline PyObject_NewVar */
     1055    if (size > PY_SSIZE_T_MAX - PyStringObject_SIZE) {
     1056        PyErr_SetString(PyExc_OverflowError,
     1057                        "strings are too large to concat");
     1058        return NULL;
     1059    }
     1060    op = (PyStringObject *)PyObject_MALLOC(PyStringObject_SIZE + size);
     1061    if (op == NULL)
     1062        return PyErr_NoMemory();
     1063    PyObject_INIT_VAR(op, &PyString_Type, size);
     1064    op->ob_shash = -1;
     1065    op->ob_sstate = SSTATE_NOT_INTERNED;
     1066    Py_MEMCPY(op->ob_sval, a->ob_sval, Py_SIZE(a));
     1067    Py_MEMCPY(op->ob_sval + Py_SIZE(a), b->ob_sval, Py_SIZE(b));
     1068    op->ob_sval[size] = '\0';
     1069    return (PyObject *) op;
    10121070#undef b
    10131071}
     
    10161074string_repeat(register PyStringObject *a, register Py_ssize_t n)
    10171075{
    1018         register Py_ssize_t i;
    1019         register Py_ssize_t j;
    1020         register Py_ssize_t size;
    1021         register PyStringObject *op;
    1022         size_t nbytes;
    1023         if (n < 0)
    1024                 n = 0;
    1025         /* watch out for overflows:  the size can overflow int,
    1026          * and the # of bytes needed can overflow size_t
    1027          */
    1028         size = Py_SIZE(a) * n;
    1029         if (n && size / n != Py_SIZE(a)) {
    1030                 PyErr_SetString(PyExc_OverflowError,
    1031                         "repeated string is too long");
    1032                 return NULL;
    1033         }
    1034         if (size == Py_SIZE(a) && PyString_CheckExact(a)) {
    1035                 Py_INCREF(a);
    1036                 return (PyObject *)a;
    1037         }
    1038         nbytes = (size_t)size;
    1039         if (nbytes + sizeof(PyStringObject) <= nbytes) {
    1040                 PyErr_SetString(PyExc_OverflowError,
    1041                         "repeated string is too long");
    1042                 return NULL;
    1043         }
    1044         op = (PyStringObject *)
    1045                 PyObject_MALLOC(sizeof(PyStringObject) + nbytes);
    1046         if (op == NULL)
    1047                 return PyErr_NoMemory();
    1048         PyObject_INIT_VAR(op, &PyString_Type, size);
    1049         op->ob_shash = -1;
    1050         op->ob_sstate = SSTATE_NOT_INTERNED;
    1051         op->ob_sval[size] = '\0';
    1052         if (Py_SIZE(a) == 1 && n > 0) {
    1053                 memset(op->ob_sval, a->ob_sval[0] , n);
    1054                 return (PyObject *) op;
    1055         }
    1056         i = 0;
    1057         if (i < size) {
    1058                 Py_MEMCPY(op->ob_sval, a->ob_sval, Py_SIZE(a));
    1059                 i = Py_SIZE(a);
    1060         }
    1061         while (i < size) {
    1062                 j = (i <= size-i)  ?  i  :  size-i;
    1063                 Py_MEMCPY(op->ob_sval+i, op->ob_sval, j);
    1064                 i += j;
    1065         }
    1066         return (PyObject *) op;
     1076    register Py_ssize_t i;
     1077    register Py_ssize_t j;
     1078    register Py_ssize_t size;
     1079    register PyStringObject *op;
     1080    size_t nbytes;
     1081    if (n < 0)
     1082        n = 0;
     1083    /* watch out for overflows:  the size can overflow int,
     1084     * and the # of bytes needed can overflow size_t
     1085     */
     1086    size = Py_SIZE(a) * n;
     1087    if (n && size / n != Py_SIZE(a)) {
     1088        PyErr_SetString(PyExc_OverflowError,
     1089            "repeated string is too long");
     1090        return NULL;
     1091    }
     1092    if (size == Py_SIZE(a) && PyString_CheckExact(a)) {
     1093        Py_INCREF(a);
     1094        return (PyObject *)a;
     1095    }
     1096    nbytes = (size_t)size;
     1097    if (nbytes + PyStringObject_SIZE <= nbytes) {
     1098        PyErr_SetString(PyExc_OverflowError,
     1099            "repeated string is too long");
     1100        return NULL;
     1101    }
     1102    op = (PyStringObject *)PyObject_MALLOC(PyStringObject_SIZE + nbytes);
     1103    if (op == NULL)
     1104        return PyErr_NoMemory();
     1105    PyObject_INIT_VAR(op, &PyString_Type, size);
     1106    op->ob_shash = -1;
     1107    op->ob_sstate = SSTATE_NOT_INTERNED;
     1108    op->ob_sval[size] = '\0';
     1109    if (Py_SIZE(a) == 1 && n > 0) {
     1110        memset(op->ob_sval, a->ob_sval[0] , n);
     1111        return (PyObject *) op;
     1112    }
     1113    i = 0;
     1114    if (i < size) {
     1115        Py_MEMCPY(op->ob_sval, a->ob_sval, Py_SIZE(a));
     1116        i = Py_SIZE(a);
     1117    }
     1118    while (i < size) {
     1119        j = (i <= size-i)  ?  i  :  size-i;
     1120        Py_MEMCPY(op->ob_sval+i, op->ob_sval, j);
     1121        i += j;
     1122    }
     1123    return (PyObject *) op;
    10671124}
    10681125
     
    10711128static PyObject *
    10721129string_slice(register PyStringObject *a, register Py_ssize_t i,
    1073              register Py_ssize_t j)
     1130             register Py_ssize_t j)
    10741131     /* j -- may be negative! */
    10751132{
    1076         if (i < 0)
    1077                 i = 0;
    1078         if (j < 0)
    1079                 j = 0; /* Avoid signed/unsigned bug in next line */
    1080         if (j > Py_SIZE(a))
    1081                 j = Py_SIZE(a);
    1082         if (i == 0 && j == Py_SIZE(a) && PyString_CheckExact(a)) {
    1083                 /* It's the same as a */
    1084                 Py_INCREF(a);
    1085                 return (PyObject *)a;
    1086         }
    1087         if (j < i)
    1088                 j = i;
    1089         return PyString_FromStringAndSize(a->ob_sval + i, j-i);
     1133    if (i < 0)
     1134        i = 0;
     1135    if (j < 0)
     1136        j = 0; /* Avoid signed/unsigned bug in next line */
     1137    if (j > Py_SIZE(a))
     1138        j = Py_SIZE(a);
     1139    if (i == 0 && j == Py_SIZE(a) && PyString_CheckExact(a)) {
     1140        /* It's the same as a */
     1141        Py_INCREF(a);
     1142        return (PyObject *)a;
     1143    }
     1144    if (j < i)
     1145        j = i;
     1146    return PyString_FromStringAndSize(a->ob_sval + i, j-i);
    10901147}
    10911148
     
    10931150string_contains(PyObject *str_obj, PyObject *sub_obj)
    10941151{
    1095         if (!PyString_CheckExact(sub_obj)) {
     1152    if (!PyString_CheckExact(sub_obj)) {
    10961153#ifdef Py_USING_UNICODE
    1097                 if (PyUnicode_Check(sub_obj))
    1098                         return PyUnicode_Contains(str_obj, sub_obj);
     1154        if (PyUnicode_Check(sub_obj))
     1155            return PyUnicode_Contains(str_obj, sub_obj);
    10991156#endif
    1100                 if (!PyString_Check(sub_obj)) {
    1101                         PyErr_Format(PyExc_TypeError,
    1102                             "'in <string>' requires string as left operand, "
    1103                             "not %.200s", Py_TYPE(sub_obj)->tp_name);
    1104                         return -1;
    1105                 }
    1106         }
    1107 
    1108         return stringlib_contains_obj(str_obj, sub_obj);
     1157        if (!PyString_Check(sub_obj)) {
     1158            PyErr_Format(PyExc_TypeError,
     1159                "'in <string>' requires string as left operand, "
     1160                "not %.200s", Py_TYPE(sub_obj)->tp_name);
     1161            return -1;
     1162        }
     1163    }
     1164
     1165    return stringlib_contains_obj(str_obj, sub_obj);
    11091166}
    11101167
     
    11121169string_item(PyStringObject *a, register Py_ssize_t i)
    11131170{
    1114         char pchar;
    1115         PyObject *v;
    1116         if (i < 0 || i >= Py_SIZE(a)) {
    1117                 PyErr_SetString(PyExc_IndexError, "string index out of range");
    1118                 return NULL;
    1119         }
    1120         pchar = a->ob_sval[i];
    1121         v = (PyObject *)characters[pchar & UCHAR_MAX];
    1122         if (v == NULL)
    1123                 v = PyString_FromStringAndSize(&pchar, 1);
    1124         else {
     1171    char pchar;
     1172    PyObject *v;
     1173    if (i < 0 || i >= Py_SIZE(a)) {
     1174        PyErr_SetString(PyExc_IndexError, "string index out of range");
     1175        return NULL;
     1176    }
     1177    pchar = a->ob_sval[i];
     1178    v = (PyObject *)characters[pchar & UCHAR_MAX];
     1179    if (v == NULL)
     1180        v = PyString_FromStringAndSize(&pchar, 1);
     1181    else {
    11251182#ifdef COUNT_ALLOCS
    1126                 one_strings++;
     1183        one_strings++;
    11271184#endif
    1128                 Py_INCREF(v);
    1129         }
    1130         return v;
     1185        Py_INCREF(v);
     1186    }
     1187    return v;
    11311188}
    11321189
     
    11341191string_richcompare(PyStringObject *a, PyStringObject *b, int op)
    11351192{
    1136         int c;
    1137         Py_ssize_t len_a, len_b;
    1138         Py_ssize_t min_len;
    1139         PyObject *result;
    1140 
    1141         /* Make sure both arguments are strings. */
    1142         if (!(PyString_Check(a) && PyString_Check(b))) {
    1143                 result = Py_NotImplemented;
    1144                 goto out;
    1145         }
    1146         if (a == b) {
    1147                 switch (op) {
    1148                 case Py_EQ:case Py_LE:case Py_GE:
    1149                         result = Py_True;
    1150                         goto out;
    1151                 case Py_NE:case Py_LT:case Py_GT:
    1152                         result = Py_False;
    1153                         goto out;
    1154                 }
    1155         }
    1156         if (op == Py_EQ) {
    1157                 /* Supporting Py_NE here as well does not save
    1158                    much time, since Py_NE is rarely used.  */
    1159                 if (Py_SIZE(a) == Py_SIZE(b)
    1160                     && (a->ob_sval[0] == b->ob_sval[0]
    1161                         && memcmp(a->ob_sval, b->ob_sval, Py_SIZE(a)) == 0)) {
    1162                         result = Py_True;
    1163                 } else {
    1164                         result = Py_False;
    1165                 }
    1166                 goto out;
    1167         }
    1168         len_a = Py_SIZE(a); len_b = Py_SIZE(b);
    1169         min_len = (len_a < len_b) ? len_a : len_b;
    1170         if (min_len > 0) {
    1171                 c = Py_CHARMASK(*a->ob_sval) - Py_CHARMASK(*b->ob_sval);
    1172                 if (c==0)
    1173                         c = memcmp(a->ob_sval, b->ob_sval, min_len);
    1174         } else
    1175                 c = 0;
    1176         if (c == 0)
    1177                 c = (len_a < len_b) ? -1 : (len_a > len_b) ? 1 : 0;
    1178         switch (op) {
    1179         case Py_LT: c = c <  0; break;
    1180         case Py_LE: c = c <= 0; break;
    1181         case Py_EQ: assert(0);  break; /* unreachable */
    1182         case Py_NE: c = c != 0; break;
    1183         case Py_GT: c = c >  0; break;
    1184         case Py_GE: c = c >= 0; break;
    1185         default:
    1186                 result = Py_NotImplemented;
    1187                 goto out;
    1188         }
    1189         result = c ? Py_True : Py_False;
     1193    int c;
     1194    Py_ssize_t len_a, len_b;
     1195    Py_ssize_t min_len;
     1196    PyObject *result;
     1197
     1198    /* Make sure both arguments are strings. */
     1199    if (!(PyString_Check(a) && PyString_Check(b))) {
     1200        result = Py_NotImplemented;
     1201        goto out;
     1202    }
     1203    if (a == b) {
     1204        switch (op) {
     1205        case Py_EQ:case Py_LE:case Py_GE:
     1206            result = Py_True;
     1207            goto out;
     1208        case Py_NE:case Py_LT:case Py_GT:
     1209            result = Py_False;
     1210            goto out;
     1211        }
     1212    }
     1213    if (op == Py_EQ) {
     1214        /* Supporting Py_NE here as well does not save
     1215           much time, since Py_NE is rarely used.  */
     1216        if (Py_SIZE(a) == Py_SIZE(b)
     1217            && (a->ob_sval[0] == b->ob_sval[0]
     1218            && memcmp(a->ob_sval, b->ob_sval, Py_SIZE(a)) == 0)) {
     1219            result = Py_True;
     1220        } else {
     1221            result = Py_False;
     1222        }
     1223        goto out;
     1224    }
     1225    len_a = Py_SIZE(a); len_b = Py_SIZE(b);
     1226    min_len = (len_a < len_b) ? len_a : len_b;
     1227    if (min_len > 0) {
     1228        c = Py_CHARMASK(*a->ob_sval) - Py_CHARMASK(*b->ob_sval);
     1229        if (c==0)
     1230            c = memcmp(a->ob_sval, b->ob_sval, min_len);
     1231    } else
     1232        c = 0;
     1233    if (c == 0)
     1234        c = (len_a < len_b) ? -1 : (len_a > len_b) ? 1 : 0;
     1235    switch (op) {
     1236    case Py_LT: c = c <  0; break;
     1237    case Py_LE: c = c <= 0; break;
     1238    case Py_EQ: assert(0);  break; /* unreachable */
     1239    case Py_NE: c = c != 0; break;
     1240    case Py_GT: c = c >  0; break;
     1241    case Py_GE: c = c >= 0; break;
     1242    default:
     1243        result = Py_NotImplemented;
     1244        goto out;
     1245    }
     1246    result = c ? Py_True : Py_False;
    11901247  out:
    1191         Py_INCREF(result);
    1192         return result;
     1248    Py_INCREF(result);
     1249    return result;
    11931250}
    11941251
     
    11961253_PyString_Eq(PyObject *o1, PyObject *o2)
    11971254{
    1198         PyStringObject *a = (PyStringObject*) o1;
    1199         PyStringObject *b = (PyStringObject*) o2;
    1200         return Py_SIZE(a) == Py_SIZE(b)
    1201           && *a->ob_sval == *b->ob_sval
    1202           && memcmp(a->ob_sval, b->ob_sval, Py_SIZE(a)) == 0;
     1255    PyStringObject *a = (PyStringObject*) o1;
     1256    PyStringObject *b = (PyStringObject*) o2;
     1257    return Py_SIZE(a) == Py_SIZE(b)
     1258      && memcmp(a->ob_sval, b->ob_sval, Py_SIZE(a)) == 0;
    12031259}
    12041260
     
    12061262string_hash(PyStringObject *a)
    12071263{
    1208         register Py_ssize_t len;
    1209         register unsigned char *p;
    1210         register long x;
    1211 
    1212         if (a->ob_shash != -1)
    1213                 return a->ob_shash;
    1214         len = Py_SIZE(a);
    1215         p = (unsigned char *) a->ob_sval;
    1216         x = *p << 7;
    1217         while (--len >= 0)
    1218                 x = (1000003*x) ^ *p++;
    1219         x ^= Py_SIZE(a);
    1220         if (x == -1)
    1221                 x = -2;
    1222         a->ob_shash = x;
    1223         return x;
     1264    register Py_ssize_t len;
     1265    register unsigned char *p;
     1266    register long x;
     1267
     1268#ifdef Py_DEBUG
     1269    assert(_Py_HashSecret_Initialized);
     1270#endif
     1271    if (a->ob_shash != -1)
     1272        return a->ob_shash;
     1273    len = Py_SIZE(a);
     1274    /*
     1275      We make the hash of the empty string be 0, rather than using
     1276      (prefix ^ suffix), since this slightly obfuscates the hash secret
     1277    */
     1278    if (len == 0) {
     1279        a->ob_shash = 0;
     1280        return 0;
     1281    }
     1282    p = (unsigned char *) a->ob_sval;
     1283    x = _Py_HashSecret.prefix;
     1284    x ^= *p << 7;
     1285    while (--len >= 0)
     1286        x = (1000003*x) ^ *p++;
     1287    x ^= Py_SIZE(a);
     1288    x ^= _Py_HashSecret.suffix;
     1289    if (x == -1)
     1290        x = -2;
     1291    a->ob_shash = x;
     1292    return x;
    12241293}
    12251294
     
    12271296string_subscript(PyStringObject* self, PyObject* item)
    12281297{
    1229         if (PyIndex_Check(item)) {
    1230                 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
    1231                 if (i == -1 && PyErr_Occurred())
    1232                         return NULL;
    1233                 if (i < 0)
    1234                         i += PyString_GET_SIZE(self);
    1235                 return string_item(self, i);
    1236         }
    1237         else if (PySlice_Check(item)) {
    1238                 Py_ssize_t start, stop, step, slicelength, cur, i;
    1239                 char* source_buf;
    1240                 char* result_buf;
    1241                 PyObject* result;
    1242 
    1243                 if (PySlice_GetIndicesEx((PySliceObject*)item,
    1244                                 PyString_GET_SIZE(self),
    1245                                 &start, &stop, &step, &slicelength) < 0) {
    1246                         return NULL;
    1247                 }
    1248 
    1249                 if (slicelength <= 0) {
    1250                         return PyString_FromStringAndSize("", 0);
    1251                 }
    1252                 else if (start == 0 && step == 1 &&
    1253                         slicelength == PyString_GET_SIZE(self) &&
    1254                         PyString_CheckExact(self)) {
    1255                         Py_INCREF(self);
    1256                         return (PyObject *)self;
    1257                 }
    1258                 else if (step == 1) {
    1259                         return PyString_FromStringAndSize(
    1260                                 PyString_AS_STRING(self) + start,
    1261                                 slicelength);
    1262                 }
    1263                 else {
    1264                         source_buf = PyString_AsString((PyObject*)self);
    1265                         result_buf = (char *)PyMem_Malloc(slicelength);
    1266                         if (result_buf == NULL)
    1267                                 return PyErr_NoMemory();
    1268 
    1269                         for (cur = start, i = 0; i < slicelength;
    1270                              cur += step, i++) {
    1271                                 result_buf[i] = source_buf[cur];
    1272                         }
    1273 
    1274                         result = PyString_FromStringAndSize(result_buf,
    1275                                                             slicelength);
    1276                         PyMem_Free(result_buf);
    1277                         return result;
    1278                 }
    1279         }
    1280         else {
    1281                 PyErr_Format(PyExc_TypeError,
    1282                              "string indices must be integers, not %.200s",
    1283                              Py_TYPE(item)->tp_name);
    1284                 return NULL;
    1285         }
     1298    if (PyIndex_Check(item)) {
     1299        Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
     1300        if (i == -1 && PyErr_Occurred())
     1301            return NULL;
     1302        if (i < 0)
     1303            i += PyString_GET_SIZE(self);
     1304        return string_item(self, i);
     1305    }
     1306    else if (PySlice_Check(item)) {
     1307        Py_ssize_t start, stop, step, slicelength, cur, i;
     1308        char* source_buf;
     1309        char* result_buf;
     1310        PyObject* result;
     1311
     1312        if (PySlice_GetIndicesEx((PySliceObject*)item,
     1313                        PyString_GET_SIZE(self),
     1314                        &start, &stop, &step, &slicelength) < 0) {
     1315            return NULL;
     1316        }
     1317
     1318        if (slicelength <= 0) {
     1319            return PyString_FromStringAndSize("", 0);
     1320        }
     1321        else if (start == 0 && step == 1 &&
     1322                slicelength == PyString_GET_SIZE(self) &&
     1323                PyString_CheckExact(self)) {
     1324            Py_INCREF(self);
     1325            return (PyObject *)self;
     1326        }
     1327        else if (step == 1) {
     1328            return PyString_FromStringAndSize(
     1329                PyString_AS_STRING(self) + start,
     1330                slicelength);
     1331        }
     1332        else {
     1333            source_buf = PyString_AsString((PyObject*)self);
     1334            result_buf = (char *)PyMem_Malloc(slicelength);
     1335            if (result_buf == NULL)
     1336                return PyErr_NoMemory();
     1337
     1338            for (cur = start, i = 0; i < slicelength;
     1339                 cur += step, i++) {
     1340                result_buf[i] = source_buf[cur];
     1341            }
     1342
     1343            result = PyString_FromStringAndSize(result_buf,
     1344                                                slicelength);
     1345            PyMem_Free(result_buf);
     1346            return result;
     1347        }
     1348    }
     1349    else {
     1350        PyErr_Format(PyExc_TypeError,
     1351                     "string indices must be integers, not %.200s",
     1352                     Py_TYPE(item)->tp_name);
     1353        return NULL;
     1354    }
    12861355}
    12871356
     
    12891358string_buffer_getreadbuf(PyStringObject *self, Py_ssize_t index, const void **ptr)
    12901359{
    1291         if ( index != 0 ) {
    1292                 PyErr_SetString(PyExc_SystemError,
    1293                                 "accessing non-existent string segment");
    1294                 return -1;
    1295         }
    1296         *ptr = (void *)self->ob_sval;
    1297         return Py_SIZE(self);
     1360    if ( index != 0 ) {
     1361        PyErr_SetString(PyExc_SystemError,
     1362                        "accessing non-existent string segment");
     1363        return -1;
     1364    }
     1365    *ptr = (void *)self->ob_sval;
     1366    return Py_SIZE(self);
    12981367}
    12991368
     
    13011370string_buffer_getwritebuf(PyStringObject *self, Py_ssize_t index, const void **ptr)
    13021371{
    1303         PyErr_SetString(PyExc_TypeError,
    1304                         "Cannot use string as modifiable buffer");
    1305         return -1;
     1372    PyErr_SetString(PyExc_TypeError,
     1373                    "Cannot use string as modifiable buffer");
     1374    return -1;
    13061375}
    13071376
     
    13091378string_buffer_getsegcount(PyStringObject *self, Py_ssize_t *lenp)
    13101379{
    1311         if ( lenp )
    1312                 *lenp = Py_SIZE(self);
    1313         return 1;
     1380    if ( lenp )
     1381        *lenp = Py_SIZE(self);
     1382    return 1;
    13141383}
    13151384
     
    13171386string_buffer_getcharbuf(PyStringObject *self, Py_ssize_t index, const char **ptr)
    13181387{
    1319         if ( index != 0 ) {
    1320                 PyErr_SetString(PyExc_SystemError,
    1321                                 "accessing non-existent string segment");
    1322                 return -1;
    1323         }
    1324         *ptr = self->ob_sval;
    1325         return Py_SIZE(self);
     1388    if ( index != 0 ) {
     1389        PyErr_SetString(PyExc_SystemError,
     1390                        "accessing non-existent string segment");
     1391        return -1;
     1392    }
     1393    *ptr = self->ob_sval;
     1394    return Py_SIZE(self);
    13261395}
    13271396
     
    13291398string_buffer_getbuffer(PyStringObject *self, Py_buffer *view, int flags)
    13301399{
    1331         return PyBuffer_FillInfo(view, (PyObject*)self,
    1332                                 (void *)self->ob_sval, Py_SIZE(self),
    1333                                 1, flags);
     1400    return PyBuffer_FillInfo(view, (PyObject*)self,
     1401                            (void *)self->ob_sval, Py_SIZE(self),
     1402                            1, flags);
    13341403}
    13351404
    13361405static PySequenceMethods string_as_sequence = {
    1337         (lenfunc)string_length, /*sq_length*/
    1338         (binaryfunc)string_concat, /*sq_concat*/
    1339         (ssizeargfunc)string_repeat, /*sq_repeat*/
    1340         (ssizeargfunc)string_item, /*sq_item*/
    1341         (ssizessizeargfunc)string_slice, /*sq_slice*/
    1342         0,              /*sq_ass_item*/
    1343         0,              /*sq_ass_slice*/
    1344         (objobjproc)string_contains /*sq_contains*/
     1406    (lenfunc)string_length, /*sq_length*/
     1407    (binaryfunc)string_concat, /*sq_concat*/
     1408    (ssizeargfunc)string_repeat, /*sq_repeat*/
     1409    (ssizeargfunc)string_item, /*sq_item*/
     1410    (ssizessizeargfunc)string_slice, /*sq_slice*/
     1411    0,                  /*sq_ass_item*/
     1412    0,                  /*sq_ass_slice*/
     1413    (objobjproc)string_contains /*sq_contains*/
    13451414};
    13461415
    13471416static PyMappingMethods string_as_mapping = {
    1348         (lenfunc)string_length,
    1349         (binaryfunc)string_subscript,
    1350         0,
     1417    (lenfunc)string_length,
     1418    (binaryfunc)string_subscript,
     1419    0,
    13511420};
    13521421
    13531422static PyBufferProcs string_as_buffer = {
    1354         (readbufferproc)string_buffer_getreadbuf,
    1355         (writebufferproc)string_buffer_getwritebuf,
    1356         (segcountproc)string_buffer_getsegcount,
    1357         (charbufferproc)string_buffer_getcharbuf,
    1358         (getbufferproc)string_buffer_getbuffer,
    1359         0, /* XXX */
     1423    (readbufferproc)string_buffer_getreadbuf,
     1424    (writebufferproc)string_buffer_getwritebuf,
     1425    (segcountproc)string_buffer_getsegcount,
     1426    (charbufferproc)string_buffer_getcharbuf,
     1427    (getbufferproc)string_buffer_getbuffer,
     1428    0, /* XXX */
    13601429};
    13611430
     
    13701439
    13711440#define STRIPNAME(i) (stripformat[i]+3)
    1372 
    1373 
    1374 /* Don't call if length < 2 */
    1375 #define Py_STRING_MATCH(target, offset, pattern, length)        \
    1376   (target[offset] == pattern[0] &&                              \
    1377    target[offset+length-1] == pattern[length-1] &&              \
    1378    !memcmp(target+offset+1, pattern+1, length-2) )
    1379 
    1380 
    1381 /* Overallocate the initial list to reduce the number of reallocs for small
    1382    split sizes.  Eg, "A A A A A A A A A A".split() (10 elements) has three
    1383    resizes, to sizes 4, 8, then 16.  Most observed string splits are for human
    1384    text (roughly 11 words per line) and field delimited data (usually 1-10
    1385    fields).  For large strings the split algorithms are bandwidth limited
    1386    so increasing the preallocation likely will not improve things.*/
    1387 
    1388 #define MAX_PREALLOC 12
    1389 
    1390 /* 5 splits gives 6 elements */
    1391 #define PREALLOC_SIZE(maxsplit) \
    1392         (maxsplit >= MAX_PREALLOC ? MAX_PREALLOC : maxsplit+1)
    1393 
    1394 #define SPLIT_APPEND(data, left, right)                         \
    1395         str = PyString_FromStringAndSize((data) + (left),       \
    1396                                          (right) - (left));     \
    1397         if (str == NULL)                                        \
    1398                 goto onError;                                   \
    1399         if (PyList_Append(list, str)) {                         \
    1400                 Py_DECREF(str);                                 \
    1401                 goto onError;                                   \
    1402         }                                                       \
    1403         else                                                    \
    1404                 Py_DECREF(str);
    1405 
    1406 #define SPLIT_ADD(data, left, right) {                          \
    1407         str = PyString_FromStringAndSize((data) + (left),       \
    1408                                          (right) - (left));     \
    1409         if (str == NULL)                                        \
    1410                 goto onError;                                   \
    1411         if (count < MAX_PREALLOC) {                             \
    1412                 PyList_SET_ITEM(list, count, str);              \
    1413         } else {                                                \
    1414                 if (PyList_Append(list, str)) {                 \
    1415                         Py_DECREF(str);                         \
    1416                         goto onError;                           \
    1417                 }                                               \
    1418                 else                                            \
    1419                         Py_DECREF(str);                         \
    1420         }                                                       \
    1421         count++; }
    1422 
    1423 /* Always force the list to the expected size. */
    1424 #define FIX_PREALLOC_SIZE(list) Py_SIZE(list) = count
    1425 
    1426 #define SKIP_SPACE(s, i, len)    { while (i<len &&  isspace(Py_CHARMASK(s[i]))) i++; }
    1427 #define SKIP_NONSPACE(s, i, len) { while (i<len && !isspace(Py_CHARMASK(s[i]))) i++; }
    1428 #define RSKIP_SPACE(s, i)        { while (i>=0  &&  isspace(Py_CHARMASK(s[i]))) i--; }
    1429 #define RSKIP_NONSPACE(s, i)     { while (i>=0  && !isspace(Py_CHARMASK(s[i]))) i--; }
    1430 
    1431 Py_LOCAL_INLINE(PyObject *)
    1432 split_whitespace(PyStringObject *self, Py_ssize_t len, Py_ssize_t maxsplit)
    1433 {
    1434         const char *s = PyString_AS_STRING(self);
    1435         Py_ssize_t i, j, count=0;
    1436         PyObject *str;
    1437         PyObject *list = PyList_New(PREALLOC_SIZE(maxsplit));
    1438 
    1439         if (list == NULL)
    1440                 return NULL;
    1441 
    1442         i = j = 0;
    1443 
    1444         while (maxsplit-- > 0) {
    1445                 SKIP_SPACE(s, i, len);
    1446                 if (i==len) break;
    1447                 j = i; i++;
    1448                 SKIP_NONSPACE(s, i, len);
    1449                 if (j == 0 && i == len && PyString_CheckExact(self)) {
    1450                         /* No whitespace in self, so just use it as list[0] */
    1451                         Py_INCREF(self);
    1452                         PyList_SET_ITEM(list, 0, (PyObject *)self);
    1453                         count++;
    1454                         break;
    1455                 }
    1456                 SPLIT_ADD(s, j, i);
    1457         }
    1458 
    1459         if (i < len) {
    1460                 /* Only occurs when maxsplit was reached */
    1461                 /* Skip any remaining whitespace and copy to end of string */
    1462                 SKIP_SPACE(s, i, len);
    1463                 if (i != len)
    1464                         SPLIT_ADD(s, i, len);
    1465         }
    1466         FIX_PREALLOC_SIZE(list);
    1467         return list;
    1468   onError:
    1469         Py_DECREF(list);
    1470         return NULL;
    1471 }
    1472 
    1473 Py_LOCAL_INLINE(PyObject *)
    1474 split_char(PyStringObject *self, Py_ssize_t len, char ch, Py_ssize_t maxcount)
    1475 {
    1476         const char *s = PyString_AS_STRING(self);
    1477         register Py_ssize_t i, j, count=0;
    1478         PyObject *str;
    1479         PyObject *list = PyList_New(PREALLOC_SIZE(maxcount));
    1480 
    1481         if (list == NULL)
    1482                 return NULL;
    1483 
    1484         i = j = 0;
    1485         while ((j < len) && (maxcount-- > 0)) {
    1486                 for(; j<len; j++) {
    1487                         /* I found that using memchr makes no difference */
    1488                         if (s[j] == ch) {
    1489                                 SPLIT_ADD(s, i, j);
    1490                                 i = j = j + 1;
    1491                                 break;
    1492                         }
    1493                 }
    1494         }
    1495         if (i == 0 && count == 0 && PyString_CheckExact(self)) {
    1496                 /* ch not in self, so just use self as list[0] */
    1497                 Py_INCREF(self);
    1498                 PyList_SET_ITEM(list, 0, (PyObject *)self);
    1499                 count++;
    1500         }
    1501         else if (i <= len) {
    1502                 SPLIT_ADD(s, i, len);
    1503         }
    1504         FIX_PREALLOC_SIZE(list);
    1505         return list;
    1506 
    1507   onError:
    1508         Py_DECREF(list);
    1509         return NULL;
    1510 }
    15111441
    15121442PyDoc_STRVAR(split__doc__,
     
    15221452string_split(PyStringObject *self, PyObject *args)
    15231453{
    1524         Py_ssize_t len = PyString_GET_SIZE(self), n, i, j;
    1525         Py_ssize_t maxsplit = -1, count=0;
    1526         const char *s = PyString_AS_STRING(self), *sub;
    1527         PyObject *list, *str, *subobj = Py_None;
    1528 #ifdef USE_FAST
    1529         Py_ssize_t pos;
     1454    Py_ssize_t len = PyString_GET_SIZE(self), n;
     1455    Py_ssize_t maxsplit = -1;
     1456    const char *s = PyString_AS_STRING(self), *sub;
     1457    PyObject *subobj = Py_None;
     1458
     1459    if (!PyArg_ParseTuple(args, "|On:split", &subobj, &maxsplit))
     1460        return NULL;
     1461    if (maxsplit < 0)
     1462        maxsplit = PY_SSIZE_T_MAX;
     1463    if (subobj == Py_None)
     1464        return stringlib_split_whitespace((PyObject*) self, s, len, maxsplit);
     1465    if (PyString_Check(subobj)) {
     1466        sub = PyString_AS_STRING(subobj);
     1467        n = PyString_GET_SIZE(subobj);
     1468    }
     1469#ifdef Py_USING_UNICODE
     1470    else if (PyUnicode_Check(subobj))
     1471        return PyUnicode_Split((PyObject *)self, subobj, maxsplit);
    15301472#endif
    1531 
    1532         if (!PyArg_ParseTuple(args, "|On:split", &subobj, &maxsplit))
    1533                 return NULL;
    1534         if (maxsplit < 0)
    1535                 maxsplit = PY_SSIZE_T_MAX;
    1536         if (subobj == Py_None)
    1537                 return split_whitespace(self, len, maxsplit);
    1538         if (PyString_Check(subobj)) {
    1539                 sub = PyString_AS_STRING(subobj);
    1540                 n = PyString_GET_SIZE(subobj);
    1541         }
    1542 #ifdef Py_USING_UNICODE
    1543         else if (PyUnicode_Check(subobj))
    1544                 return PyUnicode_Split((PyObject *)self, subobj, maxsplit);
    1545 #endif
    1546         else if (PyObject_AsCharBuffer(subobj, &sub, &n))
    1547                 return NULL;
    1548 
    1549         if (n == 0) {
    1550                 PyErr_SetString(PyExc_ValueError, "empty separator");
    1551                 return NULL;
    1552         }
    1553         else if (n == 1)
    1554                 return split_char(self, len, sub[0], maxsplit);
    1555 
    1556         list = PyList_New(PREALLOC_SIZE(maxsplit));
    1557         if (list == NULL)
    1558                 return NULL;
    1559 
    1560 #ifdef USE_FAST
    1561         i = j = 0;
    1562         while (maxsplit-- > 0) {
    1563                 pos = fastsearch(s+i, len-i, sub, n, FAST_SEARCH);
    1564                 if (pos < 0)
    1565                         break;
    1566                 j = i+pos;
    1567                 SPLIT_ADD(s, i, j);
    1568                 i = j + n;
    1569         }
    1570 #else
    1571         i = j = 0;
    1572         while ((j+n <= len) && (maxsplit-- > 0)) {
    1573                 for (; j+n <= len; j++) {
    1574                         if (Py_STRING_MATCH(s, j, sub, n)) {
    1575                                 SPLIT_ADD(s, i, j);
    1576                                 i = j = j + n;
    1577                                 break;
    1578                         }
    1579                 }
    1580         }
    1581 #endif
    1582         SPLIT_ADD(s, i, len);
    1583         FIX_PREALLOC_SIZE(list);
    1584         return list;
    1585 
    1586  onError:
    1587         Py_DECREF(list);
    1588         return NULL;
     1473    else if (PyObject_AsCharBuffer(subobj, &sub, &n))
     1474        return NULL;
     1475
     1476    return stringlib_split((PyObject*) self, s, len, sub, n, maxsplit);
    15891477}
    15901478
     
    15991487string_partition(PyStringObject *self, PyObject *sep_obj)
    16001488{
    1601         const char *sep;
    1602         Py_ssize_t sep_len;
    1603 
    1604         if (PyString_Check(sep_obj)) {
    1605                 sep = PyString_AS_STRING(sep_obj);
    1606                 sep_len = PyString_GET_SIZE(sep_obj);
    1607         }
     1489    const char *sep;
     1490    Py_ssize_t sep_len;
     1491
     1492    if (PyString_Check(sep_obj)) {
     1493        sep = PyString_AS_STRING(sep_obj);
     1494        sep_len = PyString_GET_SIZE(sep_obj);
     1495    }
    16081496#ifdef Py_USING_UNICODE
    1609         else if (PyUnicode_Check(sep_obj))
    1610                 return PyUnicode_Partition((PyObject *) self, sep_obj);
     1497    else if (PyUnicode_Check(sep_obj))
     1498        return PyUnicode_Partition((PyObject *) self, sep_obj);
    16111499#endif
    1612         else if (PyObject_AsCharBuffer(sep_obj, &sep, &sep_len))
    1613                 return NULL;
    1614 
    1615         return stringlib_partition(
    1616                 (PyObject*) self,
    1617                 PyString_AS_STRING(self), PyString_GET_SIZE(self),
    1618                 sep_obj, sep, sep_len
    1619                 );
     1500    else if (PyObject_AsCharBuffer(sep_obj, &sep, &sep_len))
     1501        return NULL;
     1502
     1503    return stringlib_partition(
     1504        (PyObject*) self,
     1505        PyString_AS_STRING(self), PyString_GET_SIZE(self),
     1506        sep_obj, sep, sep_len
     1507        );
    16201508}
    16211509
     
    16301518string_rpartition(PyStringObject *self, PyObject *sep_obj)
    16311519{
    1632         const char *sep;
    1633         Py_ssize_t sep_len;
    1634 
    1635         if (PyString_Check(sep_obj)) {
    1636                 sep = PyString_AS_STRING(sep_obj);
    1637                 sep_len = PyString_GET_SIZE(sep_obj);
    1638         }
     1520    const char *sep;
     1521    Py_ssize_t sep_len;
     1522
     1523    if (PyString_Check(sep_obj)) {
     1524        sep = PyString_AS_STRING(sep_obj);
     1525        sep_len = PyString_GET_SIZE(sep_obj);
     1526    }
    16391527#ifdef Py_USING_UNICODE
    1640         else if (PyUnicode_Check(sep_obj))
    1641                 return PyUnicode_RPartition((PyObject *) self, sep_obj);
     1528    else if (PyUnicode_Check(sep_obj))
     1529        return PyUnicode_RPartition((PyObject *) self, sep_obj);
    16421530#endif
    1643         else if (PyObject_AsCharBuffer(sep_obj, &sep, &sep_len))
    1644                 return NULL;
    1645 
    1646         return stringlib_rpartition(
    1647                 (PyObject*) self,
    1648                 PyString_AS_STRING(self), PyString_GET_SIZE(self),
    1649                 sep_obj, sep, sep_len
    1650                 );
    1651 }
    1652 
    1653 Py_LOCAL_INLINE(PyObject *)
    1654 rsplit_whitespace(PyStringObject *self, Py_ssize_t len, Py_ssize_t maxsplit)
    1655 {
    1656         const char *s = PyString_AS_STRING(self);
    1657         Py_ssize_t i, j, count=0;
    1658         PyObject *str;
    1659         PyObject *list = PyList_New(PREALLOC_SIZE(maxsplit));
    1660 
    1661         if (list == NULL)
    1662                 return NULL;
    1663 
    1664         i = j = len-1;
    1665 
    1666         while (maxsplit-- > 0) {
    1667                 RSKIP_SPACE(s, i);
    1668                 if (i<0) break;
    1669                 j = i; i--;
    1670                 RSKIP_NONSPACE(s, i);
    1671                 if (j == len-1 && i < 0 && PyString_CheckExact(self)) {
    1672                         /* No whitespace in self, so just use it as list[0] */
    1673                         Py_INCREF(self);
    1674                         PyList_SET_ITEM(list, 0, (PyObject *)self);
    1675                         count++;
    1676                         break;
    1677                 }
    1678                 SPLIT_ADD(s, i + 1, j + 1);
    1679         }
    1680         if (i >= 0) {
    1681                 /* Only occurs when maxsplit was reached */
    1682                 /* Skip any remaining whitespace and copy to beginning of string */
    1683                 RSKIP_SPACE(s, i);
    1684                 if (i >= 0)
    1685                         SPLIT_ADD(s, 0, i + 1);
    1686 
    1687         }
    1688         FIX_PREALLOC_SIZE(list);
    1689         if (PyList_Reverse(list) < 0)
    1690                 goto onError;
    1691         return list;
    1692   onError:
    1693         Py_DECREF(list);
    1694         return NULL;
    1695 }
    1696 
    1697 Py_LOCAL_INLINE(PyObject *)
    1698 rsplit_char(PyStringObject *self, Py_ssize_t len, char ch, Py_ssize_t maxcount)
    1699 {
    1700         const char *s = PyString_AS_STRING(self);
    1701         register Py_ssize_t i, j, count=0;
    1702         PyObject *str;
    1703         PyObject *list = PyList_New(PREALLOC_SIZE(maxcount));
    1704 
    1705         if (list == NULL)
    1706                 return NULL;
    1707 
    1708         i = j = len - 1;
    1709         while ((i >= 0) && (maxcount-- > 0)) {
    1710                 for (; i >= 0; i--) {
    1711                         if (s[i] == ch) {
    1712                                 SPLIT_ADD(s, i + 1, j + 1);
    1713                                 j = i = i - 1;
    1714                                 break;
    1715                         }
    1716                 }
    1717         }
    1718         if (i < 0 && count == 0 && PyString_CheckExact(self)) {
    1719                 /* ch not in self, so just use self as list[0] */
    1720                 Py_INCREF(self);
    1721                 PyList_SET_ITEM(list, 0, (PyObject *)self);
    1722                 count++;
    1723         }
    1724         else if (j >= -1) {
    1725                 SPLIT_ADD(s, 0, j + 1);
    1726         }
    1727         FIX_PREALLOC_SIZE(list);
    1728         if (PyList_Reverse(list) < 0)
    1729                 goto onError;
    1730         return list;
    1731 
    1732  onError:
    1733         Py_DECREF(list);
    1734         return NULL;
     1531    else if (PyObject_AsCharBuffer(sep_obj, &sep, &sep_len))
     1532        return NULL;
     1533
     1534    return stringlib_rpartition(
     1535        (PyObject*) self,
     1536        PyString_AS_STRING(self), PyString_GET_SIZE(self),
     1537        sep_obj, sep, sep_len
     1538        );
    17351539}
    17361540
     
    17471551string_rsplit(PyStringObject *self, PyObject *args)
    17481552{
    1749         Py_ssize_t len = PyString_GET_SIZE(self), n, i, j;
    1750         Py_ssize_t maxsplit = -1, count=0;
    1751         const char *s, *sub;
    1752         PyObject *list, *str, *subobj = Py_None;
    1753 
    1754         if (!PyArg_ParseTuple(args, "|On:rsplit", &subobj, &maxsplit))
    1755                 return NULL;
    1756         if (maxsplit < 0)
    1757                 maxsplit = PY_SSIZE_T_MAX;
    1758         if (subobj == Py_None)
    1759                 return rsplit_whitespace(self, len, maxsplit);
    1760         if (PyString_Check(subobj)) {
    1761                 sub = PyString_AS_STRING(subobj);
    1762                 n = PyString_GET_SIZE(subobj);
    1763         }
     1553    Py_ssize_t len = PyString_GET_SIZE(self), n;
     1554    Py_ssize_t maxsplit = -1;
     1555    const char *s = PyString_AS_STRING(self), *sub;
     1556    PyObject *subobj = Py_None;
     1557
     1558    if (!PyArg_ParseTuple(args, "|On:rsplit", &subobj, &maxsplit))
     1559        return NULL;
     1560    if (maxsplit < 0)
     1561        maxsplit = PY_SSIZE_T_MAX;
     1562    if (subobj == Py_None)
     1563        return stringlib_rsplit_whitespace((PyObject*) self, s, len, maxsplit);
     1564    if (PyString_Check(subobj)) {
     1565        sub = PyString_AS_STRING(subobj);
     1566        n = PyString_GET_SIZE(subobj);
     1567    }
    17641568#ifdef Py_USING_UNICODE
    1765         else if (PyUnicode_Check(subobj))
    1766                 return PyUnicode_RSplit((PyObject *)self, subobj, maxsplit);
     1569    else if (PyUnicode_Check(subobj))
     1570        return PyUnicode_RSplit((PyObject *)self, subobj, maxsplit);
    17671571#endif
    1768         else if (PyObject_AsCharBuffer(subobj, &sub, &n))
    1769                 return NULL;
    1770 
    1771         if (n == 0) {
    1772                 PyErr_SetString(PyExc_ValueError, "empty separator");
    1773                 return NULL;
    1774         }
    1775         else if (n == 1)
    1776                 return rsplit_char(self, len, sub[0], maxsplit);
    1777 
    1778         list = PyList_New(PREALLOC_SIZE(maxsplit));
    1779         if (list == NULL)
    1780                 return NULL;
    1781 
    1782         j = len;
    1783         i = j - n;
    1784 
    1785         s = PyString_AS_STRING(self);
    1786         while ( (i >= 0) && (maxsplit-- > 0) ) {
    1787                 for (; i>=0; i--) {
    1788                         if (Py_STRING_MATCH(s, i, sub, n)) {
    1789                                 SPLIT_ADD(s, i + n, j);
    1790                                 j = i;
    1791                                 i -= n;
    1792                                 break;
    1793                         }
    1794                 }
    1795         }
    1796         SPLIT_ADD(s, 0, j);
    1797         FIX_PREALLOC_SIZE(list);
    1798         if (PyList_Reverse(list) < 0)
    1799                 goto onError;
    1800         return list;
    1801 
    1802 onError:
    1803         Py_DECREF(list);
    1804         return NULL;
     1572    else if (PyObject_AsCharBuffer(subobj, &sub, &n))
     1573        return NULL;
     1574
     1575    return stringlib_rsplit((PyObject*) self, s, len, sub, n, maxsplit);
    18051576}
    18061577
     
    18151586string_join(PyStringObject *self, PyObject *orig)
    18161587{
    1817         char *sep = PyString_AS_STRING(self);
    1818         const Py_ssize_t seplen = PyString_GET_SIZE(self);
    1819         PyObject *res = NULL;
    1820         char *p;
    1821         Py_ssize_t seqlen = 0;
    1822         size_t sz = 0;
    1823         Py_ssize_t i;
    1824         PyObject *seq, *item;
    1825 
    1826         seq = PySequence_Fast(orig, "");
    1827         if (seq == NULL) {
    1828                 return NULL;
    1829         }
    1830 
    1831         seqlen = PySequence_Size(seq);
    1832         if (seqlen == 0) {
    1833                 Py_DECREF(seq);
    1834                 return PyString_FromString("");
    1835         }
    1836         if (seqlen == 1) {
    1837                 item = PySequence_Fast_GET_ITEM(seq, 0);
    1838                 if (PyString_CheckExact(item) || PyUnicode_CheckExact(item)) {
    1839                         Py_INCREF(item);
    1840                         Py_DECREF(seq);
    1841                         return item;
    1842                 }
    1843         }
    1844 
    1845         /* There are at least two things to join, or else we have a subclass
    1846         * of the builtin types in the sequence.
    1847         * Do a pre-pass to figure out the total amount of space we'll
    1848         * need (sz), see whether any argument is absurd, and defer to
    1849         * the Unicode join if appropriate.
    1850         */
    1851         for (i = 0; i < seqlen; i++) {
    1852                 const size_t old_sz = sz;
    1853                 item = PySequence_Fast_GET_ITEM(seq, i);
    1854                 if (!PyString_Check(item)){
     1588    char *sep = PyString_AS_STRING(self);
     1589    const Py_ssize_t seplen = PyString_GET_SIZE(self);
     1590    PyObject *res = NULL;
     1591    char *p;
     1592    Py_ssize_t seqlen = 0;
     1593    size_t sz = 0;
     1594    Py_ssize_t i;
     1595    PyObject *seq, *item;
     1596
     1597    seq = PySequence_Fast(orig, "");
     1598    if (seq == NULL) {
     1599        return NULL;
     1600    }
     1601
     1602    seqlen = PySequence_Size(seq);
     1603    if (seqlen == 0) {
     1604        Py_DECREF(seq);
     1605        return PyString_FromString("");
     1606    }
     1607    if (seqlen == 1) {
     1608        item = PySequence_Fast_GET_ITEM(seq, 0);
     1609        if (PyString_CheckExact(item) || PyUnicode_CheckExact(item)) {
     1610            Py_INCREF(item);
     1611            Py_DECREF(seq);
     1612            return item;
     1613        }
     1614    }
     1615
     1616    /* There are at least two things to join, or else we have a subclass
     1617    * of the builtin types in the sequence.
     1618    * Do a pre-pass to figure out the total amount of space we'll
     1619    * need (sz), see whether any argument is absurd, and defer to
     1620    * the Unicode join if appropriate.
     1621    */
     1622    for (i = 0; i < seqlen; i++) {
     1623        const size_t old_sz = sz;
     1624        item = PySequence_Fast_GET_ITEM(seq, i);
     1625        if (!PyString_Check(item)){
    18551626#ifdef Py_USING_UNICODE
    1856                         if (PyUnicode_Check(item)) {
    1857                                 /* Defer to Unicode join.
    1858                                 * CAUTION:  There's no gurantee that the
    1859                                 * original sequence can be iterated over
    1860                                 * again, so we must pass seq here.
    1861                                 */
    1862                                 PyObject *result;
    1863                                 result = PyUnicode_Join((PyObject *)self, seq);
    1864                                 Py_DECREF(seq);
    1865                                 return result;
    1866                         }
     1627            if (PyUnicode_Check(item)) {
     1628                /* Defer to Unicode join.
     1629                * CAUTION:  There's no gurantee that the
     1630                * original sequence can be iterated over
     1631                * again, so we must pass seq here.
     1632                */
     1633                PyObject *result;
     1634                result = PyUnicode_Join((PyObject *)self, seq);
     1635                Py_DECREF(seq);
     1636                return result;
     1637            }
    18671638#endif
    1868                         PyErr_Format(PyExc_TypeError,
    1869                                      "sequence item %zd: expected string,"
    1870                                      " %.80s found",
    1871                                      i, Py_TYPE(item)->tp_name);
    1872                         Py_DECREF(seq);
    1873                         return NULL;
    1874                 }
    1875                 sz += PyString_GET_SIZE(item);
    1876                 if (i != 0)
    1877                         sz += seplen;
    1878                 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
    1879                         PyErr_SetString(PyExc_OverflowError,
    1880                                 "join() result is too long for a Python string");
    1881                         Py_DECREF(seq);
    1882                         return NULL;
    1883                 }
    1884         }
    1885 
    1886         /* Allocate result space. */
    1887         res = PyString_FromStringAndSize((char*)NULL, sz);
    1888         if (res == NULL) {
    1889                 Py_DECREF(seq);
    1890                 return NULL;
    1891         }
    1892 
    1893         /* Catenate everything. */
    1894         p = PyString_AS_STRING(res);
    1895         for (i = 0; i < seqlen; ++i) {
    1896                 size_t n;
    1897                 item = PySequence_Fast_GET_ITEM(seq, i);
    1898                 n = PyString_GET_SIZE(item);
    1899                 Py_MEMCPY(p, PyString_AS_STRING(item), n);
    1900                 p += n;
    1901                 if (i < seqlen - 1) {
    1902                         Py_MEMCPY(p, sep, seplen);
    1903                         p += seplen;
    1904                 }
    1905         }
    1906 
    1907         Py_DECREF(seq);
    1908         return res;
     1639            PyErr_Format(PyExc_TypeError,
     1640                         "sequence item %zd: expected string,"
     1641                         " %.80s found",
     1642                         i, Py_TYPE(item)->tp_name);
     1643            Py_DECREF(seq);
     1644            return NULL;
     1645        }
     1646        sz += PyString_GET_SIZE(item);
     1647        if (i != 0)
     1648            sz += seplen;
     1649        if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
     1650            PyErr_SetString(PyExc_OverflowError,
     1651                "join() result is too long for a Python string");
     1652            Py_DECREF(seq);
     1653            return NULL;
     1654        }
     1655    }
     1656
     1657    /* Allocate result space. */
     1658    res = PyString_FromStringAndSize((char*)NULL, sz);
     1659    if (res == NULL) {
     1660        Py_DECREF(seq);
     1661        return NULL;
     1662    }
     1663
     1664    /* Catenate everything. */
     1665    p = PyString_AS_STRING(res);
     1666    for (i = 0; i < seqlen; ++i) {
     1667        size_t n;
     1668        item = PySequence_Fast_GET_ITEM(seq, i);
     1669        n = PyString_GET_SIZE(item);
     1670        Py_MEMCPY(p, PyString_AS_STRING(item), n);
     1671        p += n;
     1672        if (i < seqlen - 1) {
     1673            Py_MEMCPY(p, sep, seplen);
     1674            p += seplen;
     1675        }
     1676    }
     1677
     1678    Py_DECREF(seq);
     1679    return res;
    19091680}
    19101681
     
    19121683_PyString_Join(PyObject *sep, PyObject *x)
    19131684{
    1914         assert(sep != NULL && PyString_Check(sep));
    1915         assert(x != NULL);
    1916         return string_join((PyStringObject *)sep, x);
    1917 }
    1918 
    1919 Py_LOCAL_INLINE(void)
    1920 string_adjust_indices(Py_ssize_t *start, Py_ssize_t *end, Py_ssize_t len)
    1921 {
    1922         if (*end > len)
    1923                 *end = len;
    1924         else if (*end < 0)
    1925                 *end += len;
    1926         if (*end < 0)
    1927                 *end = 0;
    1928         if (*start < 0)
    1929                 *start += len;
    1930         if (*start < 0)
    1931                 *start = 0;
    1932 }
     1685    assert(sep != NULL && PyString_Check(sep));
     1686    assert(x != NULL);
     1687    return string_join((PyStringObject *)sep, x);
     1688}
     1689
     1690/* helper macro to fixup start/end slice values */
     1691#define ADJUST_INDICES(start, end, len)         \
     1692    if (end > len)                          \
     1693        end = len;                          \
     1694    else if (end < 0) {                     \
     1695        end += len;                         \
     1696        if (end < 0)                        \
     1697        end = 0;                        \
     1698    }                                       \
     1699    if (start < 0) {                        \
     1700        start += len;                       \
     1701        if (start < 0)                      \
     1702        start = 0;                      \
     1703    }
    19331704
    19341705Py_LOCAL_INLINE(Py_ssize_t)
    19351706string_find_internal(PyStringObject *self, PyObject *args, int dir)
    19361707{
    1937         PyObject *subobj;
    1938         const char *sub;
    1939         Py_ssize_t sub_len;
    1940         Py_ssize_t start=0, end=PY_SSIZE_T_MAX;
    1941         PyObject *obj_start=Py_None, *obj_end=Py_None;
    1942 
    1943         if (!PyArg_ParseTuple(args, "O|OO:find/rfind/index/rindex", &subobj,
    1944                 &obj_start, &obj_end))
    1945                 return -2;
    1946         /* To support None in "start" and "end" arguments, meaning
    1947            the same as if they were not passed.
    1948         */
    1949         if (obj_start != Py_None)
    1950                 if (!_PyEval_SliceIndex(obj_start, &start))
    1951                 return -2;
    1952         if (obj_end != Py_None)
    1953                 if (!_PyEval_SliceIndex(obj_end, &end))
    1954                 return -2;
    1955 
    1956         if (PyString_Check(subobj)) {
    1957                 sub = PyString_AS_STRING(subobj);
    1958                 sub_len = PyString_GET_SIZE(subobj);
    1959         }
     1708    PyObject *subobj;
     1709    const char *sub;
     1710    Py_ssize_t sub_len;
     1711    Py_ssize_t start=0, end=PY_SSIZE_T_MAX;
     1712
     1713    if (!stringlib_parse_args_finds("find/rfind/index/rindex",
     1714                                    args, &subobj, &start, &end))
     1715        return -2;
     1716
     1717    if (PyString_Check(subobj)) {
     1718        sub = PyString_AS_STRING(subobj);
     1719        sub_len = PyString_GET_SIZE(subobj);
     1720    }
    19601721#ifdef Py_USING_UNICODE
    1961         else if (PyUnicode_Check(subobj))
    1962                 return PyUnicode_Find(
    1963                         (PyObject *)self, subobj, start, end, dir);
     1722    else if (PyUnicode_Check(subobj))
     1723        return PyUnicode_Find(
     1724            (PyObject *)self, subobj, start, end, dir);
    19641725#endif
    1965         else if (PyObject_AsCharBuffer(subobj, &sub, &sub_len))
    1966                 /* XXX - the "expected a character buffer object" is pretty
    1967                    confusing for a non-expert.  remap to something else ? */
    1968                 return -2;
    1969 
    1970         if (dir > 0)
    1971                 return stringlib_find_slice(
    1972                         PyString_AS_STRING(self), PyString_GET_SIZE(self),
    1973                         sub, sub_len, start, end);
    1974         else
    1975                 return stringlib_rfind_slice(
    1976                         PyString_AS_STRING(self), PyString_GET_SIZE(self),
    1977                         sub, sub_len, start, end);
     1726    else if (PyObject_AsCharBuffer(subobj, &sub, &sub_len))
     1727        /* XXX - the "expected a character buffer object" is pretty
     1728           confusing for a non-expert.  remap to something else ? */
     1729        return -2;
     1730
     1731    if (dir > 0)
     1732        return stringlib_find_slice(
     1733            PyString_AS_STRING(self), PyString_GET_SIZE(self),
     1734            sub, sub_len, start, end);
     1735    else
     1736        return stringlib_rfind_slice(
     1737            PyString_AS_STRING(self), PyString_GET_SIZE(self),
     1738            sub, sub_len, start, end);
    19781739}
    19791740
     
    19831744\n\
    19841745Return the lowest index in S where substring sub is found,\n\
    1985 such that sub is contained within s[start:end].  Optional\n\
     1746such that sub is contained within S[start:end].  Optional\n\
    19861747arguments start and end are interpreted as in slice notation.\n\
    19871748\n\
     
    19911752string_find(PyStringObject *self, PyObject *args)
    19921753{
    1993         Py_ssize_t result = string_find_internal(self, args, +1);
    1994         if (result == -2)
    1995                 return NULL;
    1996         return PyInt_FromSsize_t(result);
     1754    Py_ssize_t result = string_find_internal(self, args, +1);
     1755    if (result == -2)
     1756        return NULL;
     1757    return PyInt_FromSsize_t(result);
    19971758}
    19981759
     
    20061767string_index(PyStringObject *self, PyObject *args)
    20071768{
    2008         Py_ssize_t result = string_find_internal(self, args, +1);
    2009         if (result == -2)
    2010                 return NULL;
    2011         if (result == -1) {
    2012                 PyErr_SetString(PyExc_ValueError,
    2013                                 "substring not found");
    2014                 return NULL;
    2015         }
    2016         return PyInt_FromSsize_t(result);
     1769    Py_ssize_t result = string_find_internal(self, args, +1);
     1770    if (result == -2)
     1771        return NULL;
     1772    if (result == -1) {
     1773        PyErr_SetString(PyExc_ValueError,
     1774                        "substring not found");
     1775        return NULL;
     1776    }
     1777    return PyInt_FromSsize_t(result);
    20171778}
    20181779
     
    20221783\n\
    20231784Return the highest index in S where substring sub is found,\n\
    2024 such that sub is contained within s[start:end].  Optional\n\
     1785such that sub is contained within S[start:end].  Optional\n\
    20251786arguments start and end are interpreted as in slice notation.\n\
    20261787\n\
     
    20301791string_rfind(PyStringObject *self, PyObject *args)
    20311792{
    2032         Py_ssize_t result = string_find_internal(self, args, -1);
    2033         if (result == -2)
    2034                 return NULL;
    2035         return PyInt_FromSsize_t(result);
     1793    Py_ssize_t result = string_find_internal(self, args, -1);
     1794    if (result == -2)
     1795        return NULL;
     1796    return PyInt_FromSsize_t(result);
    20361797}
    20371798
     
    20451806string_rindex(PyStringObject *self, PyObject *args)
    20461807{
    2047         Py_ssize_t result = string_find_internal(self, args, -1);
    2048         if (result == -2)
    2049                 return NULL;
    2050         if (result == -1) {
    2051                 PyErr_SetString(PyExc_ValueError,
    2052                                 "substring not found");
    2053                 return NULL;
    2054         }
    2055         return PyInt_FromSsize_t(result);
     1808    Py_ssize_t result = string_find_internal(self, args, -1);
     1809    if (result == -2)
     1810        return NULL;
     1811    if (result == -1) {
     1812        PyErr_SetString(PyExc_ValueError,
     1813                        "substring not found");
     1814        return NULL;
     1815    }
     1816    return PyInt_FromSsize_t(result);
    20561817}
    20571818
     
    20601821do_xstrip(PyStringObject *self, int striptype, PyObject *sepobj)
    20611822{
    2062         char *s = PyString_AS_STRING(self);
    2063         Py_ssize_t len = PyString_GET_SIZE(self);
    2064         char *sep = PyString_AS_STRING(sepobj);
    2065         Py_ssize_t seplen = PyString_GET_SIZE(sepobj);
    2066         Py_ssize_t i, j;
    2067 
    2068         i = 0;
    2069         if (striptype != RIGHTSTRIP) {
    2070                 while (i < len && memchr(sep, Py_CHARMASK(s[i]), seplen)) {
    2071                         i++;
    2072                 }
    2073         }
    2074 
    2075         j = len;
    2076         if (striptype != LEFTSTRIP) {
    2077                 do {
    2078                         j--;
    2079                 } while (j >= i && memchr(sep, Py_CHARMASK(s[j]), seplen));
    2080                 j++;
    2081         }
    2082 
    2083         if (i == 0 && j == len && PyString_CheckExact(self)) {
    2084                 Py_INCREF(self);
    2085                 return (PyObject*)self;
    2086         }
    2087         else
    2088                 return PyString_FromStringAndSize(s+i, j-i);
     1823    char *s = PyString_AS_STRING(self);
     1824    Py_ssize_t len = PyString_GET_SIZE(self);
     1825    char *sep = PyString_AS_STRING(sepobj);
     1826    Py_ssize_t seplen = PyString_GET_SIZE(sepobj);
     1827    Py_ssize_t i, j;
     1828
     1829    i = 0;
     1830    if (striptype != RIGHTSTRIP) {
     1831        while (i < len && memchr(sep, Py_CHARMASK(s[i]), seplen)) {
     1832            i++;
     1833        }
     1834    }
     1835
     1836    j = len;
     1837    if (striptype != LEFTSTRIP) {
     1838        do {
     1839            j--;
     1840        } while (j >= i && memchr(sep, Py_CHARMASK(s[j]), seplen));
     1841        j++;
     1842    }
     1843
     1844    if (i == 0 && j == len && PyString_CheckExact(self)) {
     1845        Py_INCREF(self);
     1846        return (PyObject*)self;
     1847    }
     1848    else
     1849        return PyString_FromStringAndSize(s+i, j-i);
    20891850}
    20901851
     
    20931854do_strip(PyStringObject *self, int striptype)
    20941855{
    2095         char *s = PyString_AS_STRING(self);
    2096         Py_ssize_t len = PyString_GET_SIZE(self), i, j;
    2097 
    2098         i = 0;
    2099         if (striptype != RIGHTSTRIP) {
    2100                 while (i < len && isspace(Py_CHARMASK(s[i]))) {
    2101                         i++;
    2102                 }
    2103         }
    2104 
    2105         j = len;
    2106         if (striptype != LEFTSTRIP) {
    2107                 do {
    2108                         j--;
    2109                 } while (j >= i && isspace(Py_CHARMASK(s[j])));
    2110                 j++;
    2111         }
    2112 
    2113         if (i == 0 && j == len && PyString_CheckExact(self)) {
    2114                 Py_INCREF(self);
    2115                 return (PyObject*)self;
    2116         }
    2117         else
    2118                 return PyString_FromStringAndSize(s+i, j-i);
     1856    char *s = PyString_AS_STRING(self);
     1857    Py_ssize_t len = PyString_GET_SIZE(self), i, j;
     1858
     1859    i = 0;
     1860    if (striptype != RIGHTSTRIP) {
     1861        while (i < len && isspace(Py_CHARMASK(s[i]))) {
     1862            i++;
     1863        }
     1864    }
     1865
     1866    j = len;
     1867    if (striptype != LEFTSTRIP) {
     1868        do {
     1869            j--;
     1870        } while (j >= i && isspace(Py_CHARMASK(s[j])));
     1871        j++;
     1872    }
     1873
     1874    if (i == 0 && j == len && PyString_CheckExact(self)) {
     1875        Py_INCREF(self);
     1876        return (PyObject*)self;
     1877    }
     1878    else
     1879        return PyString_FromStringAndSize(s+i, j-i);
    21191880}
    21201881
     
    21231884do_argstrip(PyStringObject *self, int striptype, PyObject *args)
    21241885{
    2125         PyObject *sep = NULL;
    2126 
    2127         if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
    2128                 return NULL;
    2129 
    2130         if (sep != NULL && sep != Py_None) {
    2131                 if (PyString_Check(sep))
    2132                         return do_xstrip(self, striptype, sep);
     1886    PyObject *sep = NULL;
     1887
     1888    if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
     1889        return NULL;
     1890
     1891    if (sep != NULL && sep != Py_None) {
     1892        if (PyString_Check(sep))
     1893            return do_xstrip(self, striptype, sep);
    21331894#ifdef Py_USING_UNICODE
    2134                 else if (PyUnicode_Check(sep)) {
    2135                         PyObject *uniself = PyUnicode_FromObject((PyObject *)self);
    2136                         PyObject *res;
    2137                         if (uniself==NULL)
    2138                                 return NULL;
    2139                         res = _PyUnicode_XStrip((PyUnicodeObject *)uniself,
    2140                                 striptype, sep);
    2141                         Py_DECREF(uniself);
    2142                         return res;
    2143                 }
     1895        else if (PyUnicode_Check(sep)) {
     1896            PyObject *uniself = PyUnicode_FromObject((PyObject *)self);
     1897            PyObject *res;
     1898            if (uniself==NULL)
     1899                return NULL;
     1900            res = _PyUnicode_XStrip((PyUnicodeObject *)uniself,
     1901                striptype, sep);
     1902            Py_DECREF(uniself);
     1903            return res;
     1904        }
    21441905#endif
    2145                 PyErr_Format(PyExc_TypeError,
     1906        PyErr_Format(PyExc_TypeError,
    21461907#ifdef Py_USING_UNICODE
    2147                              "%s arg must be None, str or unicode",
     1908                     "%s arg must be None, str or unicode",
    21481909#else
    2149                              "%s arg must be None or str",
     1910                     "%s arg must be None or str",
    21501911#endif
    2151                              STRIPNAME(striptype));
    2152                 return NULL;
    2153         }
    2154 
    2155         return do_strip(self, striptype);
     1912                     STRIPNAME(striptype));
     1913        return NULL;
     1914    }
     1915
     1916    return do_strip(self, striptype);
    21561917}
    21571918
     
    21681929string_strip(PyStringObject *self, PyObject *args)
    21691930{
    2170         if (PyTuple_GET_SIZE(args) == 0)
    2171                 return do_strip(self, BOTHSTRIP); /* Common case */
    2172         else
    2173                 return do_argstrip(self, BOTHSTRIP, args);
     1931    if (PyTuple_GET_SIZE(args) == 0)
     1932        return do_strip(self, BOTHSTRIP); /* Common case */
     1933    else
     1934        return do_argstrip(self, BOTHSTRIP, args);
    21741935}
    21751936
     
    21851946string_lstrip(PyStringObject *self, PyObject *args)
    21861947{
    2187         if (PyTuple_GET_SIZE(args) == 0)
    2188                 return do_strip(self, LEFTSTRIP); /* Common case */
    2189         else
    2190                 return do_argstrip(self, LEFTSTRIP, args);
     1948    if (PyTuple_GET_SIZE(args) == 0)
     1949        return do_strip(self, LEFTSTRIP); /* Common case */
     1950    else
     1951        return do_argstrip(self, LEFTSTRIP, args);
    21911952}
    21921953
     
    22021963string_rstrip(PyStringObject *self, PyObject *args)
    22031964{
    2204         if (PyTuple_GET_SIZE(args) == 0)
    2205                 return do_strip(self, RIGHTSTRIP); /* Common case */
    2206         else
    2207                 return do_argstrip(self, RIGHTSTRIP, args);
     1965    if (PyTuple_GET_SIZE(args) == 0)
     1966        return do_strip(self, RIGHTSTRIP); /* Common case */
     1967    else
     1968        return do_argstrip(self, RIGHTSTRIP, args);
    22081969}
    22091970
     
    22221983string_lower(PyStringObject *self)
    22231984{
    2224         char *s;
    2225         Py_ssize_t i, n = PyString_GET_SIZE(self);
    2226         PyObject *newobj;
    2227 
    2228         newobj = PyString_FromStringAndSize(NULL, n);
    2229         if (!newobj)
    2230                 return NULL;
    2231 
    2232         s = PyString_AS_STRING(newobj);
    2233 
    2234         Py_MEMCPY(s, PyString_AS_STRING(self), n);
    2235 
    2236         for (i = 0; i < n; i++) {
    2237                 int c = Py_CHARMASK(s[i]);
    2238                 if (isupper(c))
    2239                         s[i] = _tolower(c);
    2240         }
    2241 
    2242         return newobj;
     1985    char *s;
     1986    Py_ssize_t i, n = PyString_GET_SIZE(self);
     1987    PyObject *newobj;
     1988
     1989    newobj = PyString_FromStringAndSize(NULL, n);
     1990    if (!newobj)
     1991        return NULL;
     1992
     1993    s = PyString_AS_STRING(newobj);
     1994
     1995    Py_MEMCPY(s, PyString_AS_STRING(self), n);
     1996
     1997    for (i = 0; i < n; i++) {
     1998        int c = Py_CHARMASK(s[i]);
     1999        if (isupper(c))
     2000            s[i] = _tolower(c);
     2001    }
     2002
     2003    return newobj;
    22432004}
    22442005
     
    22552016string_upper(PyStringObject *self)
    22562017{
    2257         char *s;
    2258         Py_ssize_t i, n = PyString_GET_SIZE(self);
    2259         PyObject *newobj;
    2260 
    2261         newobj = PyString_FromStringAndSize(NULL, n);
    2262         if (!newobj)
    2263                 return NULL;
    2264 
    2265         s = PyString_AS_STRING(newobj);
    2266 
    2267         Py_MEMCPY(s, PyString_AS_STRING(self), n);
    2268 
    2269         for (i = 0; i < n; i++) {
    2270                 int c = Py_CHARMASK(s[i]);
    2271                 if (islower(c))
    2272                         s[i] = _toupper(c);
    2273         }
    2274 
    2275         return newobj;
     2018    char *s;
     2019    Py_ssize_t i, n = PyString_GET_SIZE(self);
     2020    PyObject *newobj;
     2021
     2022    newobj = PyString_FromStringAndSize(NULL, n);
     2023    if (!newobj)
     2024        return NULL;
     2025
     2026    s = PyString_AS_STRING(newobj);
     2027
     2028    Py_MEMCPY(s, PyString_AS_STRING(self), n);
     2029
     2030    for (i = 0; i < n; i++) {
     2031        int c = Py_CHARMASK(s[i]);
     2032        if (islower(c))
     2033            s[i] = _toupper(c);
     2034    }
     2035
     2036    return newobj;
    22762037}
    22772038
     
    22852046string_title(PyStringObject *self)
    22862047{
    2287         char *s = PyString_AS_STRING(self), *s_new;
    2288         Py_ssize_t i, n = PyString_GET_SIZE(self);
    2289         int previous_is_cased = 0;
    2290         PyObject *newobj;
    2291 
    2292         newobj = PyString_FromStringAndSize(NULL, n);
    2293         if (newobj == NULL)
    2294                 return NULL;
    2295         s_new = PyString_AsString(newobj);
    2296         for (i = 0; i < n; i++) {
    2297                 int c = Py_CHARMASK(*s++);
    2298                 if (islower(c)) {
    2299                         if (!previous_is_cased)
    2300                             c = toupper(c);
    2301                         previous_is_cased = 1;
    2302                 } else if (isupper(c)) {
    2303                         if (previous_is_cased)
    2304                             c = tolower(c);
    2305                         previous_is_cased = 1;
    2306                 } else
    2307                         previous_is_cased = 0;
    2308                 *s_new++ = c;
    2309         }
    2310         return newobj;
     2048    char *s = PyString_AS_STRING(self), *s_new;
     2049    Py_ssize_t i, n = PyString_GET_SIZE(self);
     2050    int previous_is_cased = 0;
     2051    PyObject *newobj;
     2052
     2053    newobj = PyString_FromStringAndSize(NULL, n);
     2054    if (newobj == NULL)
     2055        return NULL;
     2056    s_new = PyString_AsString(newobj);
     2057    for (i = 0; i < n; i++) {
     2058        int c = Py_CHARMASK(*s++);
     2059        if (islower(c)) {
     2060            if (!previous_is_cased)
     2061                c = toupper(c);
     2062            previous_is_cased = 1;
     2063        } else if (isupper(c)) {
     2064            if (previous_is_cased)
     2065                c = tolower(c);
     2066            previous_is_cased = 1;
     2067        } else
     2068            previous_is_cased = 0;
     2069        *s_new++ = c;
     2070    }
     2071    return newobj;
    23112072}
    23122073
     
    23202081string_capitalize(PyStringObject *self)
    23212082{
    2322         char *s = PyString_AS_STRING(self), *s_new;
    2323         Py_ssize_t i, n = PyString_GET_SIZE(self);
    2324         PyObject *newobj;
    2325 
    2326         newobj = PyString_FromStringAndSize(NULL, n);
    2327         if (newobj == NULL)
    2328                 return NULL;
    2329         s_new = PyString_AsString(newobj);
    2330         if (0 < n) {
    2331                 int c = Py_CHARMASK(*s++);
    2332                 if (islower(c))
    2333                         *s_new = toupper(c);
    2334                 else
    2335                         *s_new = c;
    2336                 s_new++;
    2337         }
    2338         for (i = 1; i < n; i++) {
    2339                 int c = Py_CHARMASK(*s++);
    2340                 if (isupper(c))
    2341                         *s_new = tolower(c);
    2342                 else
    2343                         *s_new = c;
    2344                 s_new++;
    2345         }
    2346         return newobj;
     2083    char *s = PyString_AS_STRING(self), *s_new;
     2084    Py_ssize_t i, n = PyString_GET_SIZE(self);
     2085    PyObject *newobj;
     2086
     2087    newobj = PyString_FromStringAndSize(NULL, n);
     2088    if (newobj == NULL)
     2089        return NULL;
     2090    s_new = PyString_AsString(newobj);
     2091    if (0 < n) {
     2092        int c = Py_CHARMASK(*s++);
     2093        if (islower(c))
     2094            *s_new = toupper(c);
     2095        else
     2096            *s_new = c;
     2097        s_new++;
     2098    }
     2099    for (i = 1; i < n; i++) {
     2100        int c = Py_CHARMASK(*s++);
     2101        if (isupper(c))
     2102            *s_new = tolower(c);
     2103        else
     2104            *s_new = c;
     2105        s_new++;
     2106    }
     2107    return newobj;
    23472108}
    23482109
     
    23582119string_count(PyStringObject *self, PyObject *args)
    23592120{
    2360         PyObject *sub_obj;
    2361         const char *str = PyString_AS_STRING(self), *sub;
    2362         Py_ssize_t sub_len;
    2363         Py_ssize_t start = 0, end = PY_SSIZE_T_MAX;
    2364 
    2365         if (!PyArg_ParseTuple(args, "O|O&O&:count", &sub_obj,
    2366                 _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
    2367                 return NULL;
    2368 
    2369         if (PyString_Check(sub_obj)) {
    2370                 sub = PyString_AS_STRING(sub_obj);
    2371                 sub_len = PyString_GET_SIZE(sub_obj);
    2372         }
     2121    PyObject *sub_obj;
     2122    const char *str = PyString_AS_STRING(self), *sub;
     2123    Py_ssize_t sub_len;
     2124    Py_ssize_t start = 0, end = PY_SSIZE_T_MAX;
     2125
     2126    if (!stringlib_parse_args_finds("count", args, &sub_obj, &start, &end))
     2127        return NULL;
     2128
     2129    if (PyString_Check(sub_obj)) {
     2130        sub = PyString_AS_STRING(sub_obj);
     2131        sub_len = PyString_GET_SIZE(sub_obj);
     2132    }
    23732133#ifdef Py_USING_UNICODE
    2374         else if (PyUnicode_Check(sub_obj)) {
    2375                 Py_ssize_t count;
    2376                 count = PyUnicode_Count((PyObject *)self, sub_obj, start, end);
    2377                 if (count == -1)
    2378                         return NULL;
    2379                 else
    2380                         return PyInt_FromSsize_t(count);
    2381         }
     2134    else if (PyUnicode_Check(sub_obj)) {
     2135        Py_ssize_t count;
     2136        count = PyUnicode_Count((PyObject *)self, sub_obj, start, end);
     2137        if (count == -1)
     2138            return NULL;
     2139        else
     2140            return PyInt_FromSsize_t(count);
     2141    }
    23822142#endif
    2383         else if (PyObject_AsCharBuffer(sub_obj, &sub, &sub_len))
    2384                 return NULL;
    2385 
    2386         string_adjust_indices(&start, &end, PyString_GET_SIZE(self));
    2387 
    2388         return PyInt_FromSsize_t(
    2389                 stringlib_count(str + start, end - start, sub, sub_len)
    2390                 );
     2143    else if (PyObject_AsCharBuffer(sub_obj, &sub, &sub_len))
     2144        return NULL;
     2145
     2146    ADJUST_INDICES(start, end, PyString_GET_SIZE(self));
     2147
     2148    return PyInt_FromSsize_t(
     2149        stringlib_count(str + start, end - start, sub, sub_len, PY_SSIZE_T_MAX)
     2150        );
    23912151}
    23922152
     
    24002160string_swapcase(PyStringObject *self)
    24012161{
    2402         char *s = PyString_AS_STRING(self), *s_new;
    2403         Py_ssize_t i, n = PyString_GET_SIZE(self);
    2404         PyObject *newobj;
    2405 
    2406         newobj = PyString_FromStringAndSize(NULL, n);
    2407         if (newobj == NULL)
    2408                 return NULL;
    2409         s_new = PyString_AsString(newobj);
    2410         for (i = 0; i < n; i++) {
    2411                 int c = Py_CHARMASK(*s++);
    2412                 if (islower(c)) {
    2413                         *s_new = toupper(c);
    2414                 }
    2415                 else if (isupper(c)) {
    2416                         *s_new = tolower(c);
    2417                 }
    2418                 else
    2419                         *s_new = c;
    2420                 s_new++;
    2421         }
    2422         return newobj;
     2162    char *s = PyString_AS_STRING(self), *s_new;
     2163    Py_ssize_t i, n = PyString_GET_SIZE(self);
     2164    PyObject *newobj;
     2165
     2166    newobj = PyString_FromStringAndSize(NULL, n);
     2167    if (newobj == NULL)
     2168        return NULL;
     2169    s_new = PyString_AsString(newobj);
     2170    for (i = 0; i < n; i++) {
     2171        int c = Py_CHARMASK(*s++);
     2172        if (islower(c)) {
     2173            *s_new = toupper(c);
     2174        }
     2175        else if (isupper(c)) {
     2176            *s_new = tolower(c);
     2177        }
     2178        else
     2179            *s_new = c;
     2180        s_new++;
     2181    }
     2182    return newobj;
    24232183}
    24242184
     
    24302190in the optional argument deletechars are removed, and the\n\
    24312191remaining characters have been mapped through the given\n\
    2432 translation table, which must be a string of length 256.");
     2192translation table, which must be a string of length 256 or None.\n\
     2193If the table argument is None, no translation is applied and\n\
     2194the operation simply removes the characters in deletechars.");
    24332195
    24342196static PyObject *
    24352197string_translate(PyStringObject *self, PyObject *args)
    24362198{
    2437         register char *input, *output;
    2438         const char *table;
    2439         register Py_ssize_t i, c, changed = 0;
    2440         PyObject *input_obj = (PyObject*)self;
    2441         const char *output_start, *del_table=NULL;
    2442         Py_ssize_t inlen, tablen, dellen = 0;
    2443         PyObject *result;
    2444         int trans_table[256];
    2445         PyObject *tableobj, *delobj = NULL;
    2446 
    2447         if (!PyArg_UnpackTuple(args, "translate", 1, 2,
    2448                               &tableobj, &delobj))
    2449                 return NULL;
    2450 
    2451         if (PyString_Check(tableobj)) {
    2452                 table = PyString_AS_STRING(tableobj);
    2453                 tablen = PyString_GET_SIZE(tableobj);
    2454         }
    2455         else if (tableobj == Py_None) {
    2456                 table = NULL;
    2457                 tablen = 256;
    2458         }
     2199    register char *input, *output;
     2200    const char *table;
     2201    register Py_ssize_t i, c, changed = 0;
     2202    PyObject *input_obj = (PyObject*)self;
     2203    const char *output_start, *del_table=NULL;
     2204    Py_ssize_t inlen, tablen, dellen = 0;
     2205    PyObject *result;
     2206    int trans_table[256];
     2207    PyObject *tableobj, *delobj = NULL;
     2208
     2209    if (!PyArg_UnpackTuple(args, "translate", 1, 2,
     2210                          &tableobj, &delobj))
     2211        return NULL;
     2212
     2213    if (PyString_Check(tableobj)) {
     2214        table = PyString_AS_STRING(tableobj);
     2215        tablen = PyString_GET_SIZE(tableobj);
     2216    }
     2217    else if (tableobj == Py_None) {
     2218        table = NULL;
     2219        tablen = 256;
     2220    }
    24592221#ifdef Py_USING_UNICODE
    2460         else if (PyUnicode_Check(tableobj)) {
    2461                 /* Unicode .translate() does not support the deletechars
    2462                    parameter; instead a mapping to None will cause characters
    2463                    to be deleted. */
    2464                 if (delobj != NULL) {
    2465                         PyErr_SetString(PyExc_TypeError,
    2466                         "deletions are implemented differently for unicode");
    2467                         return NULL;
    2468                 }
    2469                 return PyUnicode_Translate((PyObject *)self, tableobj, NULL);
    2470         }
     2222    else if (PyUnicode_Check(tableobj)) {
     2223        /* Unicode .translate() does not support the deletechars
     2224           parameter; instead a mapping to None will cause characters
     2225           to be deleted. */
     2226        if (delobj != NULL) {
     2227            PyErr_SetString(PyExc_TypeError,
     2228            "deletions are implemented differently for unicode");
     2229            return NULL;
     2230        }
     2231        return PyUnicode_Translate((PyObject *)self, tableobj, NULL);
     2232    }
    24712233#endif
    2472         else if (PyObject_AsCharBuffer(tableobj, &table, &tablen))
    2473                 return NULL;
    2474 
    2475         if (tablen != 256) {
    2476                 PyErr_SetString(PyExc_ValueError,
    2477                   "translation table must be 256 characters long");
    2478                 return NULL;
    2479         }
    2480 
    2481         if (delobj != NULL) {
    2482                 if (PyString_Check(delobj)) {
    2483                         del_table = PyString_AS_STRING(delobj);
    2484                         dellen = PyString_GET_SIZE(delobj);
    2485                 }
     2234    else if (PyObject_AsCharBuffer(tableobj, &table, &tablen))
     2235        return NULL;
     2236
     2237    if (tablen != 256) {
     2238        PyErr_SetString(PyExc_ValueError,
     2239          "translation table must be 256 characters long");
     2240        return NULL;
     2241    }
     2242
     2243    if (delobj != NULL) {
     2244        if (PyString_Check(delobj)) {
     2245            del_table = PyString_AS_STRING(delobj);
     2246            dellen = PyString_GET_SIZE(delobj);
     2247        }
    24862248#ifdef Py_USING_UNICODE
    2487                 else if (PyUnicode_Check(delobj)) {
    2488                         PyErr_SetString(PyExc_TypeError,
    2489                         "deletions are implemented differently for unicode");
    2490                         return NULL;
    2491                 }
     2249        else if (PyUnicode_Check(delobj)) {
     2250            PyErr_SetString(PyExc_TypeError,
     2251            "deletions are implemented differently for unicode");
     2252            return NULL;
     2253        }
    24922254#endif
    2493                 else if (PyObject_AsCharBuffer(delobj, &del_table, &dellen))
    2494                         return NULL;
    2495         }
    2496         else {
    2497                 del_table = NULL;
    2498                 dellen = 0;
    2499         }
    2500 
    2501         inlen = PyString_GET_SIZE(input_obj);
    2502         result = PyString_FromStringAndSize((char *)NULL, inlen);
    2503         if (result == NULL)
    2504                 return NULL;
    2505         output_start = output = PyString_AsString(result);
    2506         input = PyString_AS_STRING(input_obj);
    2507 
    2508         if (dellen == 0 && table != NULL) {
    2509                 /* If no deletions are required, use faster code */
    2510                 for (i = inlen; --i >= 0; ) {
    2511                         c = Py_CHARMASK(*input++);
    2512                         if (Py_CHARMASK((*output++ = table[c])) != c)
    2513                                 changed = 1;
    2514                 }
    2515                 if (changed || !PyString_CheckExact(input_obj))
    2516                         return result;
    2517                 Py_DECREF(result);
    2518                 Py_INCREF(input_obj);
    2519                 return input_obj;
    2520         }
    2521 
    2522         if (table == NULL) {
    2523                 for (i = 0; i < 256; i++)
    2524                         trans_table[i] = Py_CHARMASK(i);
    2525         } else {
    2526                 for (i = 0; i < 256; i++)
    2527                         trans_table[i] = Py_CHARMASK(table[i]);
    2528         }
    2529 
    2530         for (i = 0; i < dellen; i++)
    2531                 trans_table[(int) Py_CHARMASK(del_table[i])] = -1;
    2532 
    2533         for (i = inlen; --i >= 0; ) {
    2534                 c = Py_CHARMASK(*input++);
    2535                 if (trans_table[c] != -1)
    2536                         if (Py_CHARMASK(*output++ = (char)trans_table[c]) == c)
    2537                                 continue;
    2538                 changed = 1;
    2539         }
    2540         if (!changed && PyString_CheckExact(input_obj)) {
    2541                 Py_DECREF(result);
    2542                 Py_INCREF(input_obj);
    2543                 return input_obj;
    2544         }
    2545         /* Fix the size of the resulting string */
    2546         if (inlen > 0)
    2547                 _PyString_Resize(&result, output - output_start);
    2548         return result;
    2549 }
    2550 
    2551 
    2552 #define FORWARD 1
    2553 #define REVERSE -1
     2255        else if (PyObject_AsCharBuffer(delobj, &del_table, &dellen))
     2256            return NULL;
     2257    }
     2258    else {
     2259        del_table = NULL;
     2260        dellen = 0;
     2261    }
     2262
     2263    inlen = PyString_GET_SIZE(input_obj);
     2264    result = PyString_FromStringAndSize((char *)NULL, inlen);
     2265    if (result == NULL)
     2266        return NULL;
     2267    output_start = output = PyString_AsString(result);
     2268    input = PyString_AS_STRING(input_obj);
     2269
     2270    if (dellen == 0 && table != NULL) {
     2271        /* If no deletions are required, use faster code */
     2272        for (i = inlen; --i >= 0; ) {
     2273            c = Py_CHARMASK(*input++);
     2274            if (Py_CHARMASK((*output++ = table[c])) != c)
     2275                changed = 1;
     2276        }
     2277        if (changed || !PyString_CheckExact(input_obj))
     2278            return result;
     2279        Py_DECREF(result);
     2280        Py_INCREF(input_obj);
     2281        return input_obj;
     2282    }
     2283
     2284    if (table == NULL) {
     2285        for (i = 0; i < 256; i++)
     2286            trans_table[i] = Py_CHARMASK(i);
     2287    } else {
     2288        for (i = 0; i < 256; i++)
     2289            trans_table[i] = Py_CHARMASK(table[i]);
     2290    }
     2291
     2292    for (i = 0; i < dellen; i++)
     2293        trans_table[(int) Py_CHARMASK(del_table[i])] = -1;
     2294
     2295    for (i = inlen; --i >= 0; ) {
     2296        c = Py_CHARMASK(*input++);
     2297        if (trans_table[c] != -1)
     2298            if (Py_CHARMASK(*output++ = (char)trans_table[c]) == c)
     2299                continue;
     2300        changed = 1;
     2301    }
     2302    if (!changed && PyString_CheckExact(input_obj)) {
     2303        Py_DECREF(result);
     2304        Py_INCREF(input_obj);
     2305        return input_obj;
     2306    }
     2307    /* Fix the size of the resulting string */
     2308    if (inlen > 0 && _PyString_Resize(&result, output - output_start))
     2309        return NULL;
     2310    return result;
     2311}
     2312
    25542313
    25552314/* find and count characters and substrings */
    25562315
    2557 #define findchar(target, target_len, c)                         \
     2316#define findchar(target, target_len, c)                         \
    25582317  ((char *)memchr((const void *)(target), c, target_len))
    25592318
     
    25632322return_self(PyStringObject *self)
    25642323{
    2565         if (PyString_CheckExact(self)) {
    2566                 Py_INCREF(self);
    2567                 return self;
    2568         }
    2569         return (PyStringObject *)PyString_FromStringAndSize(
    2570                 PyString_AS_STRING(self),
    2571                 PyString_GET_SIZE(self));
     2324    if (PyString_CheckExact(self)) {
     2325        Py_INCREF(self);
     2326        return self;
     2327    }
     2328    return (PyStringObject *)PyString_FromStringAndSize(
     2329        PyString_AS_STRING(self),
     2330        PyString_GET_SIZE(self));
    25722331}
    25732332
    25742333Py_LOCAL_INLINE(Py_ssize_t)
    2575 countchar(const char *target, int target_len, char c, Py_ssize_t maxcount)
    2576 {
    2577         Py_ssize_t count=0;
    2578         const char *start=target;
    2579         const char *end=target+target_len;
    2580 
    2581         while ( (start=findchar(start, end-start, c)) != NULL ) {
    2582                 count++;
    2583                 if (count >= maxcount)
    2584                         break;
    2585                 start += 1;
    2586         }
    2587         return count;
    2588 }
    2589 
    2590 Py_LOCAL(Py_ssize_t)
    2591 findstring(const char *target, Py_ssize_t target_len,
    2592            const char *pattern, Py_ssize_t pattern_len,
    2593            Py_ssize_t start,
    2594            Py_ssize_t end,
    2595            int direction)
    2596 {
    2597         if (start < 0) {
    2598                 start += target_len;
    2599                 if (start < 0)
    2600                         start = 0;
    2601         }
    2602         if (end > target_len) {
    2603                 end = target_len;
    2604         } else if (end < 0) {
    2605                 end += target_len;
    2606                 if (end < 0)
    2607                         end = 0;
    2608         }
    2609 
    2610         /* zero-length substrings always match at the first attempt */
    2611         if (pattern_len == 0)
    2612                 return (direction > 0) ? start : end;
    2613 
    2614         end -= pattern_len;
    2615 
    2616         if (direction < 0) {
    2617                 for (; end >= start; end--)
    2618                         if (Py_STRING_MATCH(target, end, pattern, pattern_len))
    2619                                 return end;
    2620         } else {
    2621                 for (; start <= end; start++)
    2622                         if (Py_STRING_MATCH(target, start, pattern, pattern_len))
    2623                                 return start;
    2624         }
    2625         return -1;
    2626 }
    2627 
    2628 Py_LOCAL_INLINE(Py_ssize_t)
    2629 countstring(const char *target, Py_ssize_t target_len,
    2630             const char *pattern, Py_ssize_t pattern_len,
    2631             Py_ssize_t start,
    2632             Py_ssize_t end,
    2633             int direction, Py_ssize_t maxcount)
    2634 {
    2635         Py_ssize_t count=0;
    2636 
    2637         if (start < 0) {
    2638                 start += target_len;
    2639                 if (start < 0)
    2640                         start = 0;
    2641         }
    2642         if (end > target_len) {
    2643                 end = target_len;
    2644         } else if (end < 0) {
    2645                 end += target_len;
    2646                 if (end < 0)
    2647                         end = 0;
    2648         }
    2649 
    2650         /* zero-length substrings match everywhere */
    2651         if (pattern_len == 0 || maxcount == 0) {
    2652                 if (target_len+1 < maxcount)
    2653                         return target_len+1;
    2654                 return maxcount;
    2655         }
    2656 
    2657         end -= pattern_len;
    2658         if (direction < 0) {
    2659                 for (; (end >= start); end--)
    2660                         if (Py_STRING_MATCH(target, end, pattern, pattern_len)) {
    2661                                 count++;
    2662                                 if (--maxcount <= 0) break;
    2663                                 end -= pattern_len-1;
    2664                         }
    2665         } else {
    2666                 for (; (start <= end); start++)
    2667                         if (Py_STRING_MATCH(target, start, pattern, pattern_len)) {
    2668                                 count++;
    2669                                 if (--maxcount <= 0)
    2670                                         break;
    2671                                 start += pattern_len-1;
    2672                         }
    2673         }
    2674         return count;
     2334countchar(const char *target, Py_ssize_t target_len, char c, Py_ssize_t maxcount)
     2335{
     2336    Py_ssize_t count=0;
     2337    const char *start=target;
     2338    const char *end=target+target_len;
     2339
     2340    while ( (start=findchar(start, end-start, c)) != NULL ) {
     2341        count++;
     2342        if (count >= maxcount)
     2343            break;
     2344        start += 1;
     2345    }
     2346    return count;
    26752347}
    26762348
     
    26812353Py_LOCAL(PyStringObject *)
    26822354replace_interleave(PyStringObject *self,
    2683                    const char *to_s, Py_ssize_t to_len,
    2684                    Py_ssize_t maxcount)
    2685 {
    2686         char *self_s, *result_s;
    2687         Py_ssize_t self_len, result_len;
    2688         Py_ssize_t count, i, product;
    2689         PyStringObject *result;
    2690 
    2691         self_len = PyString_GET_SIZE(self);
    2692 
    2693         /* 1 at the end plus 1 after every character */
    2694         count = self_len+1;
    2695         if (maxcount < count)
    2696                 count = maxcount;
    2697 
    2698         /* Check for overflow */
    2699         /*   result_len = count * to_len + self_len; */
    2700         product = count * to_len;
    2701         if (product / to_len != count) {
    2702                 PyErr_SetString(PyExc_OverflowError,
    2703                                 "replace string is too long");
    2704                 return NULL;
    2705         }
    2706         result_len = product + self_len;
    2707         if (result_len < 0) {
    2708                 PyErr_SetString(PyExc_OverflowError,
    2709                                 "replace string is too long");
    2710                 return NULL;
    2711         }
    2712  
    2713         if (! (result = (PyStringObject *)
    2714                          PyString_FromStringAndSize(NULL, result_len)) )
    2715                 return NULL;
    2716 
    2717         self_s = PyString_AS_STRING(self);
    2718         result_s = PyString_AS_STRING(result);
    2719 
    2720         /* TODO: special case single character, which doesn't need memcpy */
    2721 
    2722         /* Lay the first one down (guaranteed this will occur) */
    2723         Py_MEMCPY(result_s, to_s, to_len);
    2724         result_s += to_len;
    2725         count -= 1;
    2726  
    2727         for (i=0; i<count; i++) {
    2728                 *result_s++ = *self_s++;
    2729                 Py_MEMCPY(result_s, to_s, to_len);
    2730                 result_s += to_len;
    2731         }
    2732 
    2733         /* Copy the rest of the original string */
    2734         Py_MEMCPY(result_s, self_s, self_len-i);
    2735 
    2736         return result;
     2355                   const char *to_s, Py_ssize_t to_len,
     2356                   Py_ssize_t maxcount)
     2357{
     2358    char *self_s, *result_s;
     2359    Py_ssize_t self_len, result_len;
     2360    Py_ssize_t count, i, product;
     2361    PyStringObject *result;
     2362
     2363    self_len = PyString_GET_SIZE(self);
     2364
     2365    /* 1 at the end plus 1 after every character */
     2366    count = self_len+1;
     2367    if (maxcount < count)
     2368        count = maxcount;
     2369
     2370    /* Check for overflow */
     2371    /*   result_len = count * to_len + self_len; */
     2372    product = count * to_len;
     2373    if (product / to_len != count) {
     2374        PyErr_SetString(PyExc_OverflowError,
     2375                        "replace string is too long");
     2376        return NULL;
     2377    }
     2378    result_len = product + self_len;
     2379    if (result_len < 0) {
     2380        PyErr_SetString(PyExc_OverflowError,
     2381                        "replace string is too long");
     2382        return NULL;
     2383    }
     2384
     2385    if (! (result = (PyStringObject *)
     2386                     PyString_FromStringAndSize(NULL, result_len)) )
     2387        return NULL;
     2388
     2389    self_s = PyString_AS_STRING(self);
     2390    result_s = PyString_AS_STRING(result);
     2391
     2392    /* TODO: special case single character, which doesn't need memcpy */
     2393
     2394    /* Lay the first one down (guaranteed this will occur) */
     2395    Py_MEMCPY(result_s, to_s, to_len);
     2396    result_s += to_len;
     2397    count -= 1;
     2398
     2399    for (i=0; i<count; i++) {
     2400        *result_s++ = *self_s++;
     2401        Py_MEMCPY(result_s, to_s, to_len);
     2402        result_s += to_len;
     2403    }
     2404
     2405    /* Copy the rest of the original string */
     2406    Py_MEMCPY(result_s, self_s, self_len-i);
     2407
     2408    return result;
    27372409}
    27382410
     
    27412413Py_LOCAL(PyStringObject *)
    27422414replace_delete_single_character(PyStringObject *self,
    2743                                 char from_c, Py_ssize_t maxcount)
    2744 {
    2745         char *self_s, *result_s;
    2746         char *start, *next, *end;
    2747         Py_ssize_t self_len, result_len;
    2748         Py_ssize_t count;
    2749         PyStringObject *result;
    2750 
    2751         self_len = PyString_GET_SIZE(self);
    2752         self_s = PyString_AS_STRING(self);
    2753 
    2754         count = countchar(self_s, self_len, from_c, maxcount);
    2755         if (count == 0) {
    2756                 return return_self(self);
    2757         }
    2758  
    2759         result_len = self_len - count;  /* from_len == 1 */
    2760         assert(result_len>=0);
    2761 
    2762         if ( (result = (PyStringObject *)
    2763                         PyString_FromStringAndSize(NULL, result_len)) == NULL)
    2764                 return NULL;
    2765         result_s = PyString_AS_STRING(result);
    2766 
    2767         start = self_s;
    2768         end = self_s + self_len;
    2769         while (count-- > 0) {
    2770                 next = findchar(start, end-start, from_c);
    2771                 if (next == NULL)
    2772                         break;
    2773                 Py_MEMCPY(result_s, start, next-start);
    2774                 result_s += (next-start);
    2775                 start = next+1;
    2776         }
    2777         Py_MEMCPY(result_s, start, end-start);
    2778 
    2779         return result;
     2415                                char from_c, Py_ssize_t maxcount)
     2416{
     2417    char *self_s, *result_s;
     2418    char *start, *next, *end;
     2419    Py_ssize_t self_len, result_len;
     2420    Py_ssize_t count;
     2421    PyStringObject *result;
     2422
     2423    self_len = PyString_GET_SIZE(self);
     2424    self_s = PyString_AS_STRING(self);
     2425
     2426    count = countchar(self_s, self_len, from_c, maxcount);
     2427    if (count == 0) {
     2428        return return_self(self);
     2429    }
     2430
     2431    result_len = self_len - count;  /* from_len == 1 */
     2432    assert(result_len>=0);
     2433
     2434    if ( (result = (PyStringObject *)
     2435                    PyString_FromStringAndSize(NULL, result_len)) == NULL)
     2436        return NULL;
     2437    result_s = PyString_AS_STRING(result);
     2438
     2439    start = self_s;
     2440    end = self_s + self_len;
     2441    while (count-- > 0) {
     2442        next = findchar(start, end-start, from_c);
     2443        if (next == NULL)
     2444            break;
     2445        Py_MEMCPY(result_s, start, next-start);
     2446        result_s += (next-start);
     2447        start = next+1;
     2448    }
     2449    Py_MEMCPY(result_s, start, end-start);
     2450
     2451    return result;
    27802452}
    27812453
     
    27842456Py_LOCAL(PyStringObject *)
    27852457replace_delete_substring(PyStringObject *self,
    2786                          const char *from_s, Py_ssize_t from_len,
    2787                          Py_ssize_t maxcount) {
    2788         char *self_s, *result_s;
    2789         char *start, *next, *end;
    2790         Py_ssize_t self_len, result_len;
    2791         Py_ssize_t count, offset;
    2792         PyStringObject *result;
    2793 
    2794         self_len = PyString_GET_SIZE(self);
    2795         self_s = PyString_AS_STRING(self);
    2796 
    2797         count = countstring(self_s, self_len,
    2798                             from_s, from_len,
    2799                             0, self_len, 1,
    2800                             maxcount);
    2801 
    2802         if (count == 0) {
    2803                 /* no matches */
    2804                 return return_self(self);
    2805         }
    2806 
    2807         result_len = self_len - (count * from_len);
    2808         assert (result_len>=0);
    2809 
    2810         if ( (result = (PyStringObject *)
    2811               PyString_FromStringAndSize(NULL, result_len)) == NULL )
    2812                 return NULL;
    2813 
    2814         result_s = PyString_AS_STRING(result);
    2815 
    2816         start = self_s;
    2817         end = self_s + self_len;
    2818         while (count-- > 0) {
    2819                 offset = findstring(start, end-start,
    2820                                     from_s, from_len,
    2821                                     0, end-start, FORWARD);
    2822                 if (offset == -1)
    2823                         break;
    2824                 next = start + offset;
    2825 
    2826                 Py_MEMCPY(result_s, start, next-start);
    2827 
    2828                 result_s += (next-start);
    2829                 start = next+from_len;
    2830         }
    2831         Py_MEMCPY(result_s, start, end-start);
    2832         return result;
     2458                         const char *from_s, Py_ssize_t from_len,
     2459                         Py_ssize_t maxcount) {
     2460    char *self_s, *result_s;
     2461    char *start, *next, *end;
     2462    Py_ssize_t self_len, result_len;
     2463    Py_ssize_t count, offset;
     2464    PyStringObject *result;
     2465
     2466    self_len = PyString_GET_SIZE(self);
     2467    self_s = PyString_AS_STRING(self);
     2468
     2469    count = stringlib_count(self_s, self_len,
     2470                            from_s, from_len,
     2471                            maxcount);
     2472
     2473    if (count == 0) {
     2474        /* no matches */
     2475        return return_self(self);
     2476    }
     2477
     2478    result_len = self_len - (count * from_len);
     2479    assert (result_len>=0);
     2480
     2481    if ( (result = (PyStringObject *)
     2482          PyString_FromStringAndSize(NULL, result_len)) == NULL )
     2483        return NULL;
     2484
     2485    result_s = PyString_AS_STRING(result);
     2486
     2487    start = self_s;
     2488    end = self_s + self_len;
     2489    while (count-- > 0) {
     2490        offset = stringlib_find(start, end-start,
     2491                                from_s, from_len,
     2492                                0);
     2493        if (offset == -1)
     2494            break;
     2495        next = start + offset;
     2496
     2497        Py_MEMCPY(result_s, start, next-start);
     2498
     2499        result_s += (next-start);
     2500        start = next+from_len;
     2501    }
     2502    Py_MEMCPY(result_s, start, end-start);
     2503    return result;
    28332504}
    28342505
     
    28362507Py_LOCAL(PyStringObject *)
    28372508replace_single_character_in_place(PyStringObject *self,
    2838                                   char from_c, char to_c,
    2839                                   Py_ssize_t maxcount)
    2840 {
    2841         char *self_s, *result_s, *start, *end, *next;
    2842         Py_ssize_t self_len;
    2843         PyStringObject *result;
    2844 
    2845         /* The result string will be the same size */
    2846         self_s = PyString_AS_STRING(self);
    2847         self_len = PyString_GET_SIZE(self);
    2848 
    2849         next = findchar(self_s, self_len, from_c);
    2850 
    2851         if (next == NULL) {
    2852                 /* No matches; return the original string */
    2853                 return return_self(self);
    2854         }
    2855 
    2856         /* Need to make a new string */
    2857         result = (PyStringObject *) PyString_FromStringAndSize(NULL, self_len);
    2858         if (result == NULL)
    2859                 return NULL;
    2860         result_s = PyString_AS_STRING(result);
    2861         Py_MEMCPY(result_s, self_s, self_len);
    2862 
    2863         /* change everything in-place, starting with this one */
    2864         start =  result_s + (next-self_s);
    2865         *start = to_c;
    2866         start++;
    2867         end = result_s + self_len;
    2868 
    2869         while (--maxcount > 0) {
    2870                 next = findchar(start, end-start, from_c);
    2871                 if (next == NULL)
    2872                         break;
    2873                 *next = to_c;
    2874                 start = next+1;
    2875         }
    2876 
    2877         return result;
     2509                                  char from_c, char to_c,
     2510                                  Py_ssize_t maxcount)
     2511{
     2512    char *self_s, *result_s, *start, *end, *next;
     2513    Py_ssize_t self_len;
     2514    PyStringObject *result;
     2515
     2516    /* The result string will be the same size */
     2517    self_s = PyString_AS_STRING(self);
     2518    self_len = PyString_GET_SIZE(self);
     2519
     2520    next = findchar(self_s, self_len, from_c);
     2521
     2522    if (next == NULL) {
     2523        /* No matches; return the original string */
     2524        return return_self(self);
     2525    }
     2526
     2527    /* Need to make a new string */
     2528    result = (PyStringObject *) PyString_FromStringAndSize(NULL, self_len);
     2529    if (result == NULL)
     2530        return NULL;
     2531    result_s = PyString_AS_STRING(result);
     2532    Py_MEMCPY(result_s, self_s, self_len);
     2533
     2534    /* change everything in-place, starting with this one */
     2535    start =  result_s + (next-self_s);
     2536    *start = to_c;
     2537    start++;
     2538    end = result_s + self_len;
     2539
     2540    while (--maxcount > 0) {
     2541        next = findchar(start, end-start, from_c);
     2542        if (next == NULL)
     2543            break;
     2544        *next = to_c;
     2545        start = next+1;
     2546    }
     2547
     2548    return result;
    28782549}
    28792550
     
    28812552Py_LOCAL(PyStringObject *)
    28822553replace_substring_in_place(PyStringObject *self,
    2883                            const char *from_s, Py_ssize_t from_len,
    2884                            const char *to_s, Py_ssize_t to_len,
    2885                            Py_ssize_t maxcount)
    2886 {
    2887         char *result_s, *start, *end;
    2888         char *self_s;
    2889         Py_ssize_t self_len, offset;
    2890         PyStringObject *result;
    2891 
    2892         /* The result string will be the same size */
    2893 
    2894         self_s = PyString_AS_STRING(self);
    2895         self_len = PyString_GET_SIZE(self);
    2896 
    2897         offset = findstring(self_s, self_len,
    2898                             from_s, from_len,
    2899                             0, self_len, FORWARD);
    2900         if (offset == -1) {
    2901                 /* No matches; return the original string */
    2902                 return return_self(self);
    2903         }
    2904 
    2905         /* Need to make a new string */
    2906         result = (PyStringObject *) PyString_FromStringAndSize(NULL, self_len);
    2907         if (result == NULL)
    2908                 return NULL;
    2909         result_s = PyString_AS_STRING(result);
    2910         Py_MEMCPY(result_s, self_s, self_len);
    2911 
    2912         /* change everything in-place, starting with this one */
    2913         start =  result_s + offset;
    2914         Py_MEMCPY(start, to_s, from_len);
    2915         start += from_len;
    2916         end = result_s + self_len;
    2917 
    2918         while ( --maxcount > 0) {
    2919                 offset = findstring(start, end-start,
    2920                                     from_s, from_len,
    2921                                     0, end-start, FORWARD);
    2922                 if (offset==-1)
    2923                         break;
    2924                 Py_MEMCPY(start+offset, to_s, from_len);
    2925                 start += offset+from_len;
    2926         }
    2927 
    2928         return result;
     2554                           const char *from_s, Py_ssize_t from_len,
     2555                           const char *to_s, Py_ssize_t to_len,
     2556                           Py_ssize_t maxcount)
     2557{
     2558    char *result_s, *start, *end;
     2559    char *self_s;
     2560    Py_ssize_t self_len, offset;
     2561    PyStringObject *result;
     2562
     2563    /* The result string will be the same size */
     2564
     2565    self_s = PyString_AS_STRING(self);
     2566    self_len = PyString_GET_SIZE(self);
     2567
     2568    offset = stringlib_find(self_s, self_len,
     2569                            from_s, from_len,
     2570                            0);
     2571    if (offset == -1) {
     2572        /* No matches; return the original string */
     2573        return return_self(self);
     2574    }
     2575
     2576    /* Need to make a new string */
     2577    result = (PyStringObject *) PyString_FromStringAndSize(NULL, self_len);
     2578    if (result == NULL)
     2579        return NULL;
     2580    result_s = PyString_AS_STRING(result);
     2581    Py_MEMCPY(result_s, self_s, self_len);
     2582
     2583    /* change everything in-place, starting with this one */
     2584    start =  result_s + offset;
     2585    Py_MEMCPY(start, to_s, from_len);
     2586    start += from_len;
     2587    end = result_s + self_len;
     2588
     2589    while ( --maxcount > 0) {
     2590        offset = stringlib_find(start, end-start,
     2591                                from_s, from_len,
     2592                                0);
     2593        if (offset==-1)
     2594            break;
     2595        Py_MEMCPY(start+offset, to_s, from_len);
     2596        start += offset+from_len;
     2597    }
     2598
     2599    return result;
    29292600}
    29302601
     
    29322603Py_LOCAL(PyStringObject *)
    29332604replace_single_character(PyStringObject *self,
    2934                         char from_c,
    2935                         const char *to_s, Py_ssize_t to_len,
    2936                         Py_ssize_t maxcount)
    2937 {
    2938         char *self_s, *result_s;
    2939         char *start, *next, *end;
    2940         Py_ssize_t self_len, result_len;
    2941         Py_ssize_t count, product;
    2942         PyStringObject *result;
    2943 
    2944         self_s = PyString_AS_STRING(self);
    2945         self_len = PyString_GET_SIZE(self);
    2946 
    2947         count = countchar(self_s, self_len, from_c, maxcount);
    2948         if (count == 0) {
    2949                 /* no matches, return unchanged */
    2950                 return return_self(self);
    2951         }
    2952 
    2953         /* use the difference between current and new, hence the "-1" */
    2954         /*   result_len = self_len + count * (to_len-1)  */
    2955         product = count * (to_len-1);
    2956         if (product / (to_len-1) != count) {
    2957                 PyErr_SetString(PyExc_OverflowError, "replace string is too long");
    2958                 return NULL;
    2959         }
    2960         result_len = self_len + product;
    2961         if (result_len < 0) {
    2962                 PyErr_SetString(PyExc_OverflowError, "replace string is too long");
    2963                 return NULL;
    2964         }
    2965 
    2966         if ( (result = (PyStringObject *)
    2967               PyString_FromStringAndSize(NULL, result_len)) == NULL)
    2968                 return NULL;
    2969         result_s = PyString_AS_STRING(result);
    2970 
    2971         start = self_s;
    2972         end = self_s + self_len;
    2973         while (count-- > 0) {
    2974                 next = findchar(start, end-start, from_c);
    2975                 if (next == NULL)
    2976                         break;
    2977 
    2978                 if (next == start) {
    2979                         /* replace with the 'to' */
    2980                         Py_MEMCPY(result_s, to_s, to_len);
    2981                         result_s += to_len;
    2982                         start += 1;
    2983                 } else {
    2984                         /* copy the unchanged old then the 'to' */
    2985                         Py_MEMCPY(result_s, start, next-start);
    2986                         result_s += (next-start);
    2987                         Py_MEMCPY(result_s, to_s, to_len);
    2988                         result_s += to_len;
    2989                         start = next+1;
    2990                 }
    2991         }
    2992         /* Copy the remainder of the remaining string */
    2993         Py_MEMCPY(result_s, start, end-start);
    2994 
    2995         return result;
     2605                        char from_c,
     2606                        const char *to_s, Py_ssize_t to_len,
     2607                        Py_ssize_t maxcount)
     2608{
     2609    char *self_s, *result_s;
     2610    char *start, *next, *end;
     2611    Py_ssize_t self_len, result_len;
     2612    Py_ssize_t count, product;
     2613    PyStringObject *result;
     2614
     2615    self_s = PyString_AS_STRING(self);
     2616    self_len = PyString_GET_SIZE(self);
     2617
     2618    count = countchar(self_s, self_len, from_c, maxcount);
     2619    if (count == 0) {
     2620        /* no matches, return unchanged */
     2621        return return_self(self);
     2622    }
     2623
     2624    /* use the difference between current and new, hence the "-1" */
     2625    /*   result_len = self_len + count * (to_len-1)  */
     2626    product = count * (to_len-1);
     2627    if (product / (to_len-1) != count) {
     2628        PyErr_SetString(PyExc_OverflowError, "replace string is too long");
     2629        return NULL;
     2630    }
     2631    result_len = self_len + product;
     2632    if (result_len < 0) {
     2633        PyErr_SetString(PyExc_OverflowError, "replace string is too long");
     2634        return NULL;
     2635    }
     2636
     2637    if ( (result = (PyStringObject *)
     2638          PyString_FromStringAndSize(NULL, result_len)) == NULL)
     2639        return NULL;
     2640    result_s = PyString_AS_STRING(result);
     2641
     2642    start = self_s;
     2643    end = self_s + self_len;
     2644    while (count-- > 0) {
     2645        next = findchar(start, end-start, from_c);
     2646        if (next == NULL)
     2647            break;
     2648
     2649        if (next == start) {
     2650            /* replace with the 'to' */
     2651            Py_MEMCPY(result_s, to_s, to_len);
     2652            result_s += to_len;
     2653            start += 1;
     2654        } else {
     2655            /* copy the unchanged old then the 'to' */
     2656            Py_MEMCPY(result_s, start, next-start);
     2657            result_s += (next-start);
     2658            Py_MEMCPY(result_s, to_s, to_len);
     2659            result_s += to_len;
     2660            start = next+1;
     2661        }
     2662    }
     2663    /* Copy the remainder of the remaining string */
     2664    Py_MEMCPY(result_s, start, end-start);
     2665
     2666    return result;
    29962667}
    29972668
     
    29992670Py_LOCAL(PyStringObject *)
    30002671replace_substring(PyStringObject *self,
    3001                   const char *from_s, Py_ssize_t from_len,
    3002                   const char *to_s, Py_ssize_t to_len,
    3003                   Py_ssize_t maxcount) {
    3004         char *self_s, *result_s;
    3005         char *start, *next, *end;
    3006         Py_ssize_t self_len, result_len;
    3007         Py_ssize_t count, offset, product;
    3008         PyStringObject *result;
    3009 
    3010         self_s = PyString_AS_STRING(self);
    3011         self_len = PyString_GET_SIZE(self);
    3012 
    3013         count = countstring(self_s, self_len,
    3014                             from_s, from_len,
    3015                             0, self_len, FORWARD, maxcount);
    3016         if (count == 0) {
    3017                 /* no matches, return unchanged */
    3018                 return return_self(self);
    3019         }
    3020 
    3021         /* Check for overflow */
    3022         /*    result_len = self_len + count * (to_len-from_len) */
    3023         product = count * (to_len-from_len);
    3024         if (product / (to_len-from_len) != count) {
    3025                 PyErr_SetString(PyExc_OverflowError, "replace string is too long");
    3026                 return NULL;
    3027         }
    3028         result_len = self_len + product;
    3029         if (result_len < 0) {
    3030                 PyErr_SetString(PyExc_OverflowError, "replace string is too long");
    3031                 return NULL;
    3032         }
    3033 
    3034         if ( (result = (PyStringObject *)
    3035               PyString_FromStringAndSize(NULL, result_len)) == NULL)
    3036                 return NULL;
    3037         result_s = PyString_AS_STRING(result);
    3038 
    3039         start = self_s;
    3040         end = self_s + self_len;
    3041         while (count-- > 0) {
    3042                 offset = findstring(start, end-start,
    3043                                     from_s, from_len,
    3044                                     0, end-start, FORWARD);
    3045                 if (offset == -1)
    3046                         break;
    3047                 next = start+offset;
    3048                 if (next == start) {
    3049                         /* replace with the 'to' */
    3050                         Py_MEMCPY(result_s, to_s, to_len);
    3051                         result_s += to_len;
    3052                         start += from_len;
    3053                 } else {
    3054                         /* copy the unchanged old then the 'to' */
    3055                         Py_MEMCPY(result_s, start, next-start);
    3056                         result_s += (next-start);
    3057                         Py_MEMCPY(result_s, to_s, to_len);
    3058                         result_s += to_len;
    3059                         start = next+from_len;
    3060                 }
    3061         }
    3062         /* Copy the remainder of the remaining string */
    3063         Py_MEMCPY(result_s, start, end-start);
    3064 
    3065         return result;
     2672                  const char *from_s, Py_ssize_t from_len,
     2673                  const char *to_s, Py_ssize_t to_len,
     2674                  Py_ssize_t maxcount) {
     2675    char *self_s, *result_s;
     2676    char *start, *next, *end;
     2677    Py_ssize_t self_len, result_len;
     2678    Py_ssize_t count, offset, product;
     2679    PyStringObject *result;
     2680
     2681    self_s = PyString_AS_STRING(self);
     2682    self_len = PyString_GET_SIZE(self);
     2683
     2684    count = stringlib_count(self_s, self_len,
     2685                            from_s, from_len,
     2686                            maxcount);
     2687
     2688    if (count == 0) {
     2689        /* no matches, return unchanged */
     2690        return return_self(self);
     2691    }
     2692
     2693    /* Check for overflow */
     2694    /*    result_len = self_len + count * (to_len-from_len) */
     2695    product = count * (to_len-from_len);
     2696    if (product / (to_len-from_len) != count) {
     2697        PyErr_SetString(PyExc_OverflowError, "replace string is too long");
     2698        return NULL;
     2699    }
     2700    result_len = self_len + product;
     2701    if (result_len < 0) {
     2702        PyErr_SetString(PyExc_OverflowError, "replace string is too long");
     2703        return NULL;
     2704    }
     2705
     2706    if ( (result = (PyStringObject *)
     2707          PyString_FromStringAndSize(NULL, result_len)) == NULL)
     2708        return NULL;
     2709    result_s = PyString_AS_STRING(result);
     2710
     2711    start = self_s;
     2712    end = self_s + self_len;
     2713    while (count-- > 0) {
     2714        offset = stringlib_find(start, end-start,
     2715                                from_s, from_len,
     2716                                0);
     2717        if (offset == -1)
     2718            break;
     2719        next = start+offset;
     2720        if (next == start) {
     2721            /* replace with the 'to' */
     2722            Py_MEMCPY(result_s, to_s, to_len);
     2723            result_s += to_len;
     2724            start += from_len;
     2725        } else {
     2726            /* copy the unchanged old then the 'to' */
     2727            Py_MEMCPY(result_s, start, next-start);
     2728            result_s += (next-start);
     2729            Py_MEMCPY(result_s, to_s, to_len);
     2730            result_s += to_len;
     2731            start = next+from_len;
     2732        }
     2733    }
     2734    /* Copy the remainder of the remaining string */
     2735    Py_MEMCPY(result_s, start, end-start);
     2736
     2737    return result;
    30662738}
    30672739
     
    30692741Py_LOCAL(PyStringObject *)
    30702742replace(PyStringObject *self,
    3071         const char *from_s, Py_ssize_t from_len,
    3072         const char *to_s, Py_ssize_t to_len,
    3073         Py_ssize_t maxcount)
    3074 {
    3075         if (maxcount < 0) {
    3076                 maxcount = PY_SSIZE_T_MAX;
    3077         } else if (maxcount == 0 || PyString_GET_SIZE(self) == 0) {
    3078                 /* nothing to do; return the original string */
    3079                 return return_self(self);
    3080         }
    3081 
    3082         if (maxcount == 0 ||
    3083             (from_len == 0 && to_len == 0)) {
    3084                 /* nothing to do; return the original string */
    3085                 return return_self(self);
    3086         }
    3087 
    3088         /* Handle zero-length special cases */
    3089 
    3090         if (from_len == 0) {
    3091                 /* insert the 'to' string everywhere.   */
    3092                 /*    >>> "Python".replace("", ".")     */
    3093                 /*    '.P.y.t.h.o.n.'                   */
    3094                 return replace_interleave(self, to_s, to_len, maxcount);
    3095         }
    3096 
    3097         /* Except for "".replace("", "A") == "A" there is no way beyond this */
    3098         /* point for an empty self string to generate a non-empty string */
    3099         /* Special case so the remaining code always gets a non-empty string */
    3100         if (PyString_GET_SIZE(self) == 0) {
    3101                 return return_self(self);
    3102         }
    3103 
    3104         if (to_len == 0) {
    3105                 /* delete all occurances of 'from' string */
    3106                 if (from_len == 1) {
    3107                         return replace_delete_single_character(
    3108                                 self, from_s[0], maxcount);
    3109                 } else {
    3110                         return replace_delete_substring(self, from_s, from_len, maxcount);
    3111                 }
    3112         }
    3113 
    3114         /* Handle special case where both strings have the same length */
    3115 
    3116         if (from_len == to_len) {
    3117                 if (from_len == 1) {
    3118                         return replace_single_character_in_place(
    3119                                 self,
    3120                                 from_s[0],
    3121                                 to_s[0],
    3122                                 maxcount);
    3123                 } else {
    3124                         return replace_substring_in_place(
    3125                                 self, from_s, from_len, to_s, to_len, maxcount);
    3126                 }
    3127         }
    3128 
    3129         /* Otherwise use the more generic algorithms */
    3130         if (from_len == 1) {
    3131                 return replace_single_character(self, from_s[0],
    3132                                                 to_s, to_len, maxcount);
    3133         } else {
    3134                 /* len('from')>=2, len('to')>=1 */
    3135                 return replace_substring(self, from_s, from_len, to_s, to_len, maxcount);
    3136         }
     2743    const char *from_s, Py_ssize_t from_len,
     2744    const char *to_s, Py_ssize_t to_len,
     2745    Py_ssize_t maxcount)
     2746{
     2747    if (maxcount < 0) {
     2748        maxcount = PY_SSIZE_T_MAX;
     2749    } else if (maxcount == 0 || PyString_GET_SIZE(self) == 0) {
     2750        /* nothing to do; return the original string */
     2751        return return_self(self);
     2752    }
     2753
     2754    if (maxcount == 0 ||
     2755        (from_len == 0 && to_len == 0)) {
     2756        /* nothing to do; return the original string */
     2757        return return_self(self);
     2758    }
     2759
     2760    /* Handle zero-length special cases */
     2761
     2762    if (from_len == 0) {
     2763        /* insert the 'to' string everywhere.   */
     2764        /*    >>> "Python".replace("", ".")     */
     2765        /*    '.P.y.t.h.o.n.'                   */
     2766        return replace_interleave(self, to_s, to_len, maxcount);
     2767    }
     2768
     2769    /* Except for "".replace("", "A") == "A" there is no way beyond this */
     2770    /* point for an empty self string to generate a non-empty string */
     2771    /* Special case so the remaining code always gets a non-empty string */
     2772    if (PyString_GET_SIZE(self) == 0) {
     2773        return return_self(self);
     2774    }
     2775
     2776    if (to_len == 0) {
     2777        /* delete all occurances of 'from' string */
     2778        if (from_len == 1) {
     2779            return replace_delete_single_character(
     2780                self, from_s[0], maxcount);
     2781        } else {
     2782            return replace_delete_substring(self, from_s, from_len, maxcount);
     2783        }
     2784    }
     2785
     2786    /* Handle special case where both strings have the same length */
     2787
     2788    if (from_len == to_len) {
     2789        if (from_len == 1) {
     2790            return replace_single_character_in_place(
     2791                self,
     2792                from_s[0],
     2793                to_s[0],
     2794                maxcount);
     2795        } else {
     2796            return replace_substring_in_place(
     2797                self, from_s, from_len, to_s, to_len, maxcount);
     2798        }
     2799    }
     2800
     2801    /* Otherwise use the more generic algorithms */
     2802    if (from_len == 1) {
     2803        return replace_single_character(self, from_s[0],
     2804                                        to_s, to_len, maxcount);
     2805    } else {
     2806        /* len('from')>=2, len('to')>=1 */
     2807        return replace_substring(self, from_s, from_len, to_s, to_len, maxcount);
     2808    }
    31372809}
    31382810
    31392811PyDoc_STRVAR(replace__doc__,
    3140 "S.replace (old, new[, count]) -> string\n\
     2812"S.replace(old, new[, count]) -> string\n\
    31412813\n\
    31422814Return a copy of string S with all occurrences of substring\n\
     
    31472819string_replace(PyStringObject *self, PyObject *args)
    31482820{
    3149         Py_ssize_t count = -1;
    3150         PyObject *from, *to;
    3151         const char *from_s, *to_s;
    3152         Py_ssize_t from_len, to_len;
    3153 
    3154         if (!PyArg_ParseTuple(args, "OO|n:replace", &from, &to, &count))
    3155                 return NULL;
    3156 
    3157         if (PyString_Check(from)) {
    3158                 from_s = PyString_AS_STRING(from);
    3159                 from_len = PyString_GET_SIZE(from);
    3160         }
     2821    Py_ssize_t count = -1;
     2822    PyObject *from, *to;
     2823    const char *from_s, *to_s;
     2824    Py_ssize_t from_len, to_len;
     2825
     2826    if (!PyArg_ParseTuple(args, "OO|n:replace", &from, &to, &count))
     2827        return NULL;
     2828
     2829    if (PyString_Check(from)) {
     2830        from_s = PyString_AS_STRING(from);
     2831        from_len = PyString_GET_SIZE(from);
     2832    }
    31612833#ifdef Py_USING_UNICODE
    3162         if (PyUnicode_Check(from))
    3163                 return PyUnicode_Replace((PyObject *)self,
    3164                                         from, to, count);
     2834    if (PyUnicode_Check(from))
     2835        return PyUnicode_Replace((PyObject *)self,
     2836                                from, to, count);
    31652837#endif
    3166         else if (PyObject_AsCharBuffer(from, &from_s, &from_len))
    3167                 return NULL;
    3168 
    3169         if (PyString_Check(to)) {
    3170                 to_s = PyString_AS_STRING(to);
    3171                 to_len = PyString_GET_SIZE(to);
    3172         }
     2838    else if (PyObject_AsCharBuffer(from, &from_s, &from_len))
     2839        return NULL;
     2840
     2841    if (PyString_Check(to)) {
     2842        to_s = PyString_AS_STRING(to);
     2843        to_len = PyString_GET_SIZE(to);
     2844    }
    31732845#ifdef Py_USING_UNICODE
    3174         else if (PyUnicode_Check(to))
    3175                 return PyUnicode_Replace((PyObject *)self,
    3176                                         from, to, count);
     2846    else if (PyUnicode_Check(to))
     2847        return PyUnicode_Replace((PyObject *)self,
     2848                                from, to, count);
    31772849#endif
    3178         else if (PyObject_AsCharBuffer(to, &to_s, &to_len))
    3179                 return NULL;
    3180 
    3181         return (PyObject *)replace((PyStringObject *) self,
    3182                                    from_s, from_len,
    3183                                    to_s, to_len, count);
     2850    else if (PyObject_AsCharBuffer(to, &to_s, &to_len))
     2851        return NULL;
     2852
     2853    return (PyObject *)replace((PyStringObject *) self,
     2854                               from_s, from_len,
     2855                               to_s, to_len, count);
    31842856}
    31852857
     
    31922864Py_LOCAL(int)
    31932865_string_tailmatch(PyStringObject *self, PyObject *substr, Py_ssize_t start,
    3194                   Py_ssize_t end, int direction)
    3195 {
    3196         Py_ssize_t len = PyString_GET_SIZE(self);
    3197         Py_ssize_t slen;
    3198         const char* sub;
    3199         const char* str;
    3200 
    3201         if (PyString_Check(substr)) {
    3202                 sub = PyString_AS_STRING(substr);
    3203                 slen = PyString_GET_SIZE(substr);
    3204         }
     2866                  Py_ssize_t end, int direction)
     2867{
     2868    Py_ssize_t len = PyString_GET_SIZE(self);
     2869    Py_ssize_t slen;
     2870    const char* sub;
     2871    const char* str;
     2872
     2873    if (PyString_Check(substr)) {
     2874        sub = PyString_AS_STRING(substr);
     2875        slen = PyString_GET_SIZE(substr);
     2876    }
    32052877#ifdef Py_USING_UNICODE
    3206         else if (PyUnicode_Check(substr))
    3207                 return PyUnicode_Tailmatch((PyObject *)self,
    3208                                            substr, start, end, direction);
     2878    else if (PyUnicode_Check(substr))
     2879        return PyUnicode_Tailmatch((PyObject *)self,
     2880                                   substr, start, end, direction);
    32092881#endif
    3210         else if (PyObject_AsCharBuffer(substr, &sub, &slen))
    3211                 return -1;
    3212         str = PyString_AS_STRING(self);
    3213 
    3214         string_adjust_indices(&start, &end, len);
    3215 
    3216         if (direction < 0) {
    3217                 /* startswith */
    3218                 if (start+slen > len)
    3219                         return 0;
    3220         } else {
    3221                 /* endswith */
    3222                 if (end-start < slen || start > len)
    3223                         return 0;
    3224 
    3225                 if (end-slen > start)
    3226                         start = end - slen;
    3227         }
    3228         if (end-start >= slen)
    3229                 return ! memcmp(str+start, sub, slen);
    3230         return 0;
     2882    else if (PyObject_AsCharBuffer(substr, &sub, &slen))
     2883        return -1;
     2884    str = PyString_AS_STRING(self);
     2885
     2886    ADJUST_INDICES(start, end, len);
     2887
     2888    if (direction < 0) {
     2889        /* startswith */
     2890        if (start+slen > len)
     2891            return 0;
     2892    } else {
     2893        /* endswith */
     2894        if (end-start < slen || start > len)
     2895            return 0;
     2896
     2897        if (end-slen > start)
     2898            start = end - slen;
     2899    }
     2900    if (end-start >= slen)
     2901        return ! memcmp(str+start, sub, slen);
     2902    return 0;
    32312903}
    32322904
     
    32432915string_startswith(PyStringObject *self, PyObject *args)
    32442916{
    3245         Py_ssize_t start = 0;
    3246         Py_ssize_t end = PY_SSIZE_T_MAX;
    3247         PyObject *subobj;
    3248         int result;
    3249 
    3250         if (!PyArg_ParseTuple(args, "O|O&O&:startswith", &subobj,
    3251                 _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
    3252                 return NULL;
    3253         if (PyTuple_Check(subobj)) {
    3254                 Py_ssize_t i;
    3255                 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
    3256                         result = _string_tailmatch(self,
    3257                                         PyTuple_GET_ITEM(subobj, i),
    3258                                         start, end, -1);
    3259                         if (result == -1)
    3260                                 return NULL;
    3261                         else if (result) {
    3262                                 Py_RETURN_TRUE;
    3263                         }
    3264                 }
    3265                 Py_RETURN_FALSE;
    3266         }
    3267         result = _string_tailmatch(self, subobj, start, end, -1);
    3268         if (result == -1)
    3269                 return NULL;
    3270         else
    3271                 return PyBool_FromLong(result);
     2917    Py_ssize_t start = 0;
     2918    Py_ssize_t end = PY_SSIZE_T_MAX;
     2919    PyObject *subobj;
     2920    int result;
     2921
     2922    if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
     2923        return NULL;
     2924    if (PyTuple_Check(subobj)) {
     2925        Py_ssize_t i;
     2926        for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
     2927            result = _string_tailmatch(self,
     2928                            PyTuple_GET_ITEM(subobj, i),
     2929                            start, end, -1);
     2930            if (result == -1)
     2931                return NULL;
     2932            else if (result) {
     2933                Py_RETURN_TRUE;
     2934            }
     2935        }
     2936        Py_RETURN_FALSE;
     2937    }
     2938    result = _string_tailmatch(self, subobj, start, end, -1);
     2939    if (result == -1) {
     2940        if (PyErr_ExceptionMatches(PyExc_TypeError))
     2941            PyErr_Format(PyExc_TypeError, "startswith first arg must be str, "
     2942                         "unicode, or tuple, not %s", Py_TYPE(subobj)->tp_name);
     2943        return NULL;
     2944    }
     2945    else
     2946        return PyBool_FromLong(result);
    32722947}
    32732948
     
    32842959string_endswith(PyStringObject *self, PyObject *args)
    32852960{
    3286         Py_ssize_t start = 0;
    3287         Py_ssize_t end = PY_SSIZE_T_MAX;
    3288         PyObject *subobj;
    3289         int result;
    3290 
    3291         if (!PyArg_ParseTuple(args, "O|O&O&:endswith", &subobj,
    3292                 _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
    3293                 return NULL;
    3294         if (PyTuple_Check(subobj)) {
    3295                 Py_ssize_t i;
    3296                 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
    3297                         result = _string_tailmatch(self,
    3298                                         PyTuple_GET_ITEM(subobj, i),
    3299                                         start, end, +1);
    3300                         if (result == -1)
    3301                                 return NULL;
    3302                         else if (result) {
    3303                                 Py_RETURN_TRUE;
    3304                         }
    3305                 }
    3306                 Py_RETURN_FALSE;
    3307         }
    3308         result = _string_tailmatch(self, subobj, start, end, +1);
    3309         if (result == -1)
    3310                 return NULL;
    3311         else
    3312                 return PyBool_FromLong(result);
     2961    Py_ssize_t start = 0;
     2962    Py_ssize_t end = PY_SSIZE_T_MAX;
     2963    PyObject *subobj;
     2964    int result;
     2965
     2966    if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
     2967        return NULL;
     2968    if (PyTuple_Check(subobj)) {
     2969        Py_ssize_t i;
     2970        for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
     2971            result = _string_tailmatch(self,
     2972                            PyTuple_GET_ITEM(subobj, i),
     2973                            start, end, +1);
     2974            if (result == -1)
     2975                return NULL;
     2976            else if (result) {
     2977                Py_RETURN_TRUE;
     2978            }
     2979        }
     2980        Py_RETURN_FALSE;
     2981    }
     2982    result = _string_tailmatch(self, subobj, start, end, +1);
     2983    if (result == -1) {
     2984        if (PyErr_ExceptionMatches(PyExc_TypeError))
     2985            PyErr_Format(PyExc_TypeError, "endswith first arg must be str, "
     2986                         "unicode, or tuple, not %s", Py_TYPE(subobj)->tp_name);
     2987        return NULL;
     2988    }
     2989    else
     2990        return PyBool_FromLong(result);
    33132991}
    33142992
     
    33253003
    33263004static PyObject *
    3327 string_encode(PyStringObject *self, PyObject *args)
    3328 {
     3005string_encode(PyStringObject *self, PyObject *args, PyObject *kwargs)
     3006{
     3007    static char *kwlist[] = {"encoding", "errors", 0};
    33293008    char *encoding = NULL;
    33303009    char *errors = NULL;
    33313010    PyObject *v;
    33323011
    3333     if (!PyArg_ParseTuple(args, "|ss:encode", &encoding, &errors))
     3012    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
     3013                                     kwlist, &encoding, &errors))
    33343014        return NULL;
    33353015    v = PyString_AsEncodedObject((PyObject *)self, encoding, errors);
     
    33623042
    33633043static PyObject *
    3364 string_decode(PyStringObject *self, PyObject *args)
    3365 {
     3044string_decode(PyStringObject *self, PyObject *args, PyObject *kwargs)
     3045{
     3046    static char *kwlist[] = {"encoding", "errors", 0};
    33663047    char *encoding = NULL;
    33673048    char *errors = NULL;
    33683049    PyObject *v;
    33693050
    3370     if (!PyArg_ParseTuple(args, "|ss:decode", &encoding, &errors))
     3051    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:decode",
     3052                                     kwlist, &encoding, &errors))
    33713053        return NULL;
    33723054    v = PyString_AsDecodedObject((PyObject *)self, encoding, errors);
     
    34043086
    34053087    if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
    3406         return NULL;
     3088        return NULL;
    34073089
    34083090    /* First pass: determine size of output string */
     
    34113093    e = PyString_AS_STRING(self) + PyString_GET_SIZE(self); /* end of input */
    34123094    for (p = PyString_AS_STRING(self); p < e; p++)
    3413         if (*p == '\t') {
    3414             if (tabsize > 0) {
    3415                 incr = tabsize - (j % tabsize);
    3416                 if (j > PY_SSIZE_T_MAX - incr)
    3417                     goto overflow1;
    3418                 j += incr;
    3419             }
    3420         }
    3421         else {
    3422             if (j > PY_SSIZE_T_MAX - 1)
    3423                 goto overflow1;
    3424             j++;
    3425             if (*p == '\n' || *p == '\r') {
    3426                 if (i > PY_SSIZE_T_MAX - j)
    3427                     goto overflow1;
    3428                 i += j;
    3429                 j = 0;
    3430             }
     3095    if (*p == '\t') {
     3096        if (tabsize > 0) {
     3097            incr = tabsize - (j % tabsize);
     3098            if (j > PY_SSIZE_T_MAX - incr)
     3099                goto overflow1;
     3100            j += incr;
    34313101        }
     3102    }
     3103    else {
     3104        if (j > PY_SSIZE_T_MAX - 1)
     3105            goto overflow1;
     3106        j++;
     3107        if (*p == '\n' || *p == '\r') {
     3108            if (i > PY_SSIZE_T_MAX - j)
     3109                goto overflow1;
     3110            i += j;
     3111            j = 0;
     3112        }
     3113    }
    34323114
    34333115    if (i > PY_SSIZE_T_MAX - j)
    3434         goto overflow1;
     3116        goto overflow1;
    34353117
    34363118    /* Second pass: create output string and fill it */
     
    34443126
    34453127    for (p = PyString_AS_STRING(self); p < e; p++)
    3446         if (*p == '\t') {
    3447             if (tabsize > 0) {
    3448                 i = tabsize - (j % tabsize);
    3449                 j += i;
    3450                 while (i--) {
    3451                     if (q >= qe)
    3452                         goto overflow2;
    3453                     *q++ = ' ';
    3454                 }
    3455             }
    3456         }
    3457         else {
    3458             if (q >= qe)
    3459                 goto overflow2;
    3460             *q++ = *p;
    3461             j++;
    3462             if (*p == '\n' || *p == '\r')
    3463                 j = 0;
     3128    if (*p == '\t') {
     3129        if (tabsize > 0) {
     3130            i = tabsize - (j % tabsize);
     3131            j += i;
     3132            while (i--) {
     3133                if (q >= qe)
     3134                    goto overflow2;
     3135                *q++ = ' ';
     3136            }
    34643137        }
     3138    }
     3139    else {
     3140        if (q >= qe)
     3141            goto overflow2;
     3142        *q++ = *p;
     3143        j++;
     3144        if (*p == '\n' || *p == '\r')
     3145            j = 0;
     3146    }
    34653147
    34663148    return u;
     
    34893171
    34903172    u = PyString_FromStringAndSize(NULL,
    3491                                    left + PyString_GET_SIZE(self) + right);
     3173                                   left + PyString_GET_SIZE(self) + right);
    34923174    if (u) {
    34933175        if (left)
    34943176            memset(PyString_AS_STRING(u), fill, left);
    34953177        Py_MEMCPY(PyString_AS_STRING(u) + left,
    3496                PyString_AS_STRING(self),
    3497                PyString_GET_SIZE(self));
     3178               PyString_AS_STRING(self),
     3179               PyString_GET_SIZE(self));
    34983180        if (right)
    34993181            memset(PyString_AS_STRING(u) + left + PyString_GET_SIZE(self),
    3500                    fill, right);
     3182               fill, right);
    35013183    }
    35023184
     
    36033285        else
    36043286            return PyString_FromStringAndSize(
    3605                 PyString_AS_STRING(self),
    3606                 PyString_GET_SIZE(self)
     3287            PyString_AS_STRING(self),
     3288            PyString_GET_SIZE(self)
    36073289            );
    36083290    }
     
    36403322    /* Shortcut for single character strings */
    36413323    if (PyString_GET_SIZE(self) == 1 &&
    3642         isspace(*p))
    3643         return PyBool_FromLong(1);
     3324        isspace(*p))
     3325        return PyBool_FromLong(1);
    36443326
    36453327    /* Special case for empty strings */
    36463328    if (PyString_GET_SIZE(self) == 0)
    3647         return PyBool_FromLong(0);
     3329        return PyBool_FromLong(0);
    36483330
    36493331    e = p + PyString_GET_SIZE(self);
    36503332    for (; p < e; p++) {
    3651         if (!isspace(*p))
    3652             return PyBool_FromLong(0);
     3333        if (!isspace(*p))
     3334            return PyBool_FromLong(0);
    36533335    }
    36543336    return PyBool_FromLong(1);
     
    36713353    /* Shortcut for single character strings */
    36723354    if (PyString_GET_SIZE(self) == 1 &&
    3673         isalpha(*p))
    3674         return PyBool_FromLong(1);
     3355        isalpha(*p))
     3356        return PyBool_FromLong(1);
    36753357
    36763358    /* Special case for empty strings */
    36773359    if (PyString_GET_SIZE(self) == 0)
    3678         return PyBool_FromLong(0);
     3360        return PyBool_FromLong(0);
    36793361
    36803362    e = p + PyString_GET_SIZE(self);
    36813363    for (; p < e; p++) {
    3682         if (!isalpha(*p))
    3683             return PyBool_FromLong(0);
     3364        if (!isalpha(*p))
     3365            return PyBool_FromLong(0);
    36843366    }
    36853367    return PyBool_FromLong(1);
     
    37023384    /* Shortcut for single character strings */
    37033385    if (PyString_GET_SIZE(self) == 1 &&
    3704         isalnum(*p))
    3705         return PyBool_FromLong(1);
     3386        isalnum(*p))
     3387        return PyBool_FromLong(1);
    37063388
    37073389    /* Special case for empty strings */
    37083390    if (PyString_GET_SIZE(self) == 0)
    3709         return PyBool_FromLong(0);
     3391        return PyBool_FromLong(0);
    37103392
    37113393    e = p + PyString_GET_SIZE(self);
    37123394    for (; p < e; p++) {
    3713         if (!isalnum(*p))
    3714             return PyBool_FromLong(0);
     3395        if (!isalnum(*p))
     3396            return PyBool_FromLong(0);
    37153397    }
    37163398    return PyBool_FromLong(1);
     
    37333415    /* Shortcut for single character strings */
    37343416    if (PyString_GET_SIZE(self) == 1 &&
    3735         isdigit(*p))
    3736         return PyBool_FromLong(1);
     3417        isdigit(*p))
     3418        return PyBool_FromLong(1);
    37373419
    37383420    /* Special case for empty strings */
    37393421    if (PyString_GET_SIZE(self) == 0)
    3740         return PyBool_FromLong(0);
     3422        return PyBool_FromLong(0);
    37413423
    37423424    e = p + PyString_GET_SIZE(self);
    37433425    for (; p < e; p++) {
    3744         if (!isdigit(*p))
    3745             return PyBool_FromLong(0);
     3426        if (!isdigit(*p))
     3427            return PyBool_FromLong(0);
    37463428    }
    37473429    return PyBool_FromLong(1);
     
    37653447    /* Shortcut for single character strings */
    37663448    if (PyString_GET_SIZE(self) == 1)
    3767         return PyBool_FromLong(islower(*p) != 0);
     3449        return PyBool_FromLong(islower(*p) != 0);
    37683450
    37693451    /* Special case for empty strings */
    37703452    if (PyString_GET_SIZE(self) == 0)
    3771         return PyBool_FromLong(0);
     3453        return PyBool_FromLong(0);
    37723454
    37733455    e = p + PyString_GET_SIZE(self);
    37743456    cased = 0;
    37753457    for (; p < e; p++) {
    3776         if (isupper(*p))
    3777             return PyBool_FromLong(0);
    3778         else if (!cased && islower(*p))
    3779             cased = 1;
     3458        if (isupper(*p))
     3459            return PyBool_FromLong(0);
     3460        else if (!cased && islower(*p))
     3461            cased = 1;
    37803462    }
    37813463    return PyBool_FromLong(cased);
     
    37993481    /* Shortcut for single character strings */
    38003482    if (PyString_GET_SIZE(self) == 1)
    3801         return PyBool_FromLong(isupper(*p) != 0);
     3483        return PyBool_FromLong(isupper(*p) != 0);
    38023484
    38033485    /* Special case for empty strings */
    38043486    if (PyString_GET_SIZE(self) == 0)
    3805         return PyBool_FromLong(0);
     3487        return PyBool_FromLong(0);
    38063488
    38073489    e = p + PyString_GET_SIZE(self);
    38083490    cased = 0;
    38093491    for (; p < e; p++) {
    3810         if (islower(*p))
    3811             return PyBool_FromLong(0);
    3812         else if (!cased && isupper(*p))
    3813             cased = 1;
     3492        if (islower(*p))
     3493            return PyBool_FromLong(0);
     3494        else if (!cased && isupper(*p))
     3495            cased = 1;
    38143496    }
    38153497    return PyBool_FromLong(cased);
     
    38353517    /* Shortcut for single character strings */
    38363518    if (PyString_GET_SIZE(self) == 1)
    3837         return PyBool_FromLong(isupper(*p) != 0);
     3519        return PyBool_FromLong(isupper(*p) != 0);
    38383520
    38393521    /* Special case for empty strings */
    38403522    if (PyString_GET_SIZE(self) == 0)
    3841         return PyBool_FromLong(0);
     3523        return PyBool_FromLong(0);
    38423524
    38433525    e = p + PyString_GET_SIZE(self);
     
    38453527    previous_is_cased = 0;
    38463528    for (; p < e; p++) {
    3847         register const unsigned char ch = *p;
    3848 
    3849         if (isupper(ch)) {
    3850             if (previous_is_cased)
    3851                 return PyBool_FromLong(0);
    3852             previous_is_cased = 1;
    3853             cased = 1;
    3854         }
    3855         else if (islower(ch)) {
    3856             if (!previous_is_cased)
    3857                 return PyBool_FromLong(0);
    3858             previous_is_cased = 1;
    3859             cased = 1;
    3860         }
    3861         else
    3862             previous_is_cased = 0;
     3529        register const unsigned char ch = *p;
     3530
     3531        if (isupper(ch)) {
     3532            if (previous_is_cased)
     3533                return PyBool_FromLong(0);
     3534            previous_is_cased = 1;
     3535            cased = 1;
     3536        }
     3537        else if (islower(ch)) {
     3538            if (!previous_is_cased)
     3539                return PyBool_FromLong(0);
     3540            previous_is_cased = 1;
     3541            cased = 1;
     3542        }
     3543        else
     3544            previous_is_cased = 0;
    38633545    }
    38643546    return PyBool_FromLong(cased);
     
    38673549
    38683550PyDoc_STRVAR(splitlines__doc__,
    3869 "S.splitlines([keepends]) -> list of strings\n\
     3551"S.splitlines(keepends=False) -> list of strings\n\
    38703552\n\
    38713553Return a list of the lines in S, breaking at line boundaries.\n\
     
    38763558string_splitlines(PyStringObject *self, PyObject *args)
    38773559{
    3878     register Py_ssize_t i;
    3879     register Py_ssize_t j;
    3880     Py_ssize_t len;
    38813560    int keepends = 0;
    3882     PyObject *list;
    3883     PyObject *str;
    3884     char *data;
    38853561
    38863562    if (!PyArg_ParseTuple(args, "|i:splitlines", &keepends))
    38873563        return NULL;
    38883564
    3889     data = PyString_AS_STRING(self);
    3890     len = PyString_GET_SIZE(self);
    3891 
    3892     /* This does not use the preallocated list because splitlines is
    3893        usually run with hundreds of newlines.  The overhead of
    3894        switching between PyList_SET_ITEM and append causes about a
    3895        2-3% slowdown for that common case.  A smarter implementation
    3896        could move the if check out, so the SET_ITEMs are done first
    3897        and the appends only done when the prealloc buffer is full.
    3898        That's too much work for little gain.*/
    3899 
    3900     list = PyList_New(0);
    3901     if (!list)
    3902         goto onError;
    3903 
    3904     for (i = j = 0; i < len; ) {
    3905         Py_ssize_t eol;
    3906 
    3907         /* Find a line and append it */
    3908         while (i < len && data[i] != '\n' && data[i] != '\r')
    3909             i++;
    3910 
    3911         /* Skip the line break reading CRLF as one line break */
    3912         eol = i;
    3913         if (i < len) {
    3914             if (data[i] == '\r' && i + 1 < len &&
    3915                 data[i+1] == '\n')
    3916                 i += 2;
    3917             else
    3918                 i++;
    3919             if (keepends)
    3920                 eol = i;
    3921         }
    3922         SPLIT_APPEND(data, j, eol);
    3923         j = i;
    3924     }
    3925     if (j < len) {
    3926         SPLIT_APPEND(data, j, len);
    3927     }
    3928 
    3929     return list;
    3930 
    3931  onError:
    3932     Py_XDECREF(list);
    3933     return NULL;
     3565    return stringlib_splitlines(
     3566        (PyObject*) self, PyString_AS_STRING(self), PyString_GET_SIZE(self),
     3567        keepends
     3568    );
    39343569}
    39353570
     
    39403575string_sizeof(PyStringObject *v)
    39413576{
    3942         Py_ssize_t res;
    3943         res = sizeof(PyStringObject) + v->ob_size * v->ob_type->tp_itemsize;
    3944         return PyInt_FromSsize_t(res);
    3945 }
    3946 
    3947 #undef SPLIT_APPEND
    3948 #undef SPLIT_ADD
    3949 #undef MAX_PREALLOC
    3950 #undef PREALLOC_SIZE
     3577    Py_ssize_t res;
     3578    res = PyStringObject_SIZE + PyString_GET_SIZE(v) * Py_TYPE(v)->tp_itemsize;
     3579    return PyInt_FromSsize_t(res);
     3580}
    39513581
    39523582static PyObject *
    39533583string_getnewargs(PyStringObject *v)
    39543584{
    3955         return Py_BuildValue("(s#)", v->ob_sval, Py_SIZE(v));
     3585    return Py_BuildValue("(s#)", v->ob_sval, Py_SIZE(v));
    39563586}
    39573587
     
    39603590
    39613591PyDoc_STRVAR(format__doc__,
    3962 "S.format(*args, **kwargs) -> unicode\n\
     3592"S.format(*args, **kwargs) -> string\n\
    39633593\n\
    3964 ");
     3594Return a formatted version of S, using substitutions from args and kwargs.\n\
     3595The substitutions are identified by braces ('{' and '}').");
    39653596
    39663597static PyObject *
     
    39773608    if (!(PyString_Check(format_spec) || PyUnicode_Check(format_spec))) {
    39783609        PyErr_Format(PyExc_TypeError, "__format__ arg must be str "
    3979                      "or unicode, not %s", Py_TYPE(format_spec)->tp_name);
    3980         goto done;
     3610                     "or unicode, not %s", Py_TYPE(format_spec)->tp_name);
     3611        goto done;
    39813612    }
    39823613    tmp = PyObject_Str(format_spec);
     
    39863617
    39873618    result = _PyBytes_FormatAdvanced(self,
    3988                                      PyString_AS_STRING(format_spec),
    3989                                      PyString_GET_SIZE(format_spec));
     3619                                     PyString_AS_STRING(format_spec),
     3620                                     PyString_GET_SIZE(format_spec));
    39903621done:
    39913622    Py_XDECREF(tmp);
     
    39943625
    39953626PyDoc_STRVAR(p_format__doc__,
    3996 "S.__format__(format_spec) -> unicode\n\
     3627"S.__format__(format_spec) -> string\n\
    39973628\n\
    3998 ");
     3629Return a formatted version of S as described by format_spec.");
    39993630
    40003631
    40013632static PyMethodDef
    40023633string_methods[] = {
    4003         /* Counterparts of the obsolete stropmodule functions; except
    4004            string.maketrans(). */
    4005         {"join", (PyCFunction)string_join, METH_O, join__doc__},
    4006         {"split", (PyCFunction)string_split, METH_VARARGS, split__doc__},
    4007         {"rsplit", (PyCFunction)string_rsplit, METH_VARARGS, rsplit__doc__},
    4008         {"lower", (PyCFunction)string_lower, METH_NOARGS, lower__doc__},
    4009         {"upper", (PyCFunction)string_upper, METH_NOARGS, upper__doc__},
    4010         {"islower", (PyCFunction)string_islower, METH_NOARGS, islower__doc__},
    4011         {"isupper", (PyCFunction)string_isupper, METH_NOARGS, isupper__doc__},
    4012         {"isspace", (PyCFunction)string_isspace, METH_NOARGS, isspace__doc__},
    4013         {"isdigit", (PyCFunction)string_isdigit, METH_NOARGS, isdigit__doc__},
    4014         {"istitle", (PyCFunction)string_istitle, METH_NOARGS, istitle__doc__},
    4015         {"isalpha", (PyCFunction)string_isalpha, METH_NOARGS, isalpha__doc__},
    4016         {"isalnum", (PyCFunction)string_isalnum, METH_NOARGS, isalnum__doc__},
    4017         {"capitalize", (PyCFunction)string_capitalize, METH_NOARGS,
    4018         capitalize__doc__},
    4019         {"count", (PyCFunction)string_count, METH_VARARGS, count__doc__},
    4020         {"endswith", (PyCFunction)string_endswith, METH_VARARGS,
    4021         endswith__doc__},
    4022         {"partition", (PyCFunction)string_partition, METH_O, partition__doc__},
    4023         {"find", (PyCFunction)string_find, METH_VARARGS, find__doc__},
    4024         {"index", (PyCFunction)string_index, METH_VARARGS, index__doc__},
    4025         {"lstrip", (PyCFunction)string_lstrip, METH_VARARGS, lstrip__doc__},
    4026         {"replace", (PyCFunction)string_replace, METH_VARARGS, replace__doc__},
    4027         {"rfind", (PyCFunction)string_rfind, METH_VARARGS, rfind__doc__},
    4028         {"rindex", (PyCFunction)string_rindex, METH_VARARGS, rindex__doc__},
    4029         {"rstrip", (PyCFunction)string_rstrip, METH_VARARGS, rstrip__doc__},
    4030         {"rpartition", (PyCFunction)string_rpartition, METH_O,
    4031         rpartition__doc__},
    4032         {"startswith", (PyCFunction)string_startswith, METH_VARARGS,
    4033         startswith__doc__},
    4034         {"strip", (PyCFunction)string_strip, METH_VARARGS, strip__doc__},
    4035         {"swapcase", (PyCFunction)string_swapcase, METH_NOARGS,
    4036         swapcase__doc__},
    4037         {"translate", (PyCFunction)string_translate, METH_VARARGS,
    4038         translate__doc__},
    4039         {"title", (PyCFunction)string_title, METH_NOARGS, title__doc__},
    4040         {"ljust", (PyCFunction)string_ljust, METH_VARARGS, ljust__doc__},
    4041         {"rjust", (PyCFunction)string_rjust, METH_VARARGS, rjust__doc__},
    4042         {"center", (PyCFunction)string_center, METH_VARARGS, center__doc__},
    4043         {"zfill", (PyCFunction)string_zfill, METH_VARARGS, zfill__doc__},
    4044         {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
    4045         {"__format__", (PyCFunction) string__format__, METH_VARARGS, p_format__doc__},
    4046         {"_formatter_field_name_split", (PyCFunction) formatter_field_name_split, METH_NOARGS},
    4047         {"_formatter_parser", (PyCFunction) formatter_parser, METH_NOARGS},
    4048         {"encode", (PyCFunction)string_encode, METH_VARARGS, encode__doc__},
    4049         {"decode", (PyCFunction)string_decode, METH_VARARGS, decode__doc__},
    4050         {"expandtabs", (PyCFunction)string_expandtabs, METH_VARARGS,
    4051         expandtabs__doc__},
    4052         {"splitlines", (PyCFunction)string_splitlines, METH_VARARGS,
    4053         splitlines__doc__},
    4054         {"__sizeof__", (PyCFunction)string_sizeof, METH_NOARGS,
    4055         sizeof__doc__},
    4056         {"__getnewargs__",      (PyCFunction)string_getnewargs, METH_NOARGS},
    4057         {NULL,     NULL}                     /* sentinel */
     3634    /* Counterparts of the obsolete stropmodule functions; except
     3635       string.maketrans(). */
     3636    {"join", (PyCFunction)string_join, METH_O, join__doc__},
     3637    {"split", (PyCFunction)string_split, METH_VARARGS, split__doc__},
     3638    {"rsplit", (PyCFunction)string_rsplit, METH_VARARGS, rsplit__doc__},
     3639    {"lower", (PyCFunction)string_lower, METH_NOARGS, lower__doc__},
     3640    {"upper", (PyCFunction)string_upper, METH_NOARGS, upper__doc__},
     3641    {"islower", (PyCFunction)string_islower, METH_NOARGS, islower__doc__},
     3642    {"isupper", (PyCFunction)string_isupper, METH_NOARGS, isupper__doc__},
     3643    {"isspace", (PyCFunction)string_isspace, METH_NOARGS, isspace__doc__},
     3644    {"isdigit", (PyCFunction)string_isdigit, METH_NOARGS, isdigit__doc__},
     3645    {"istitle", (PyCFunction)string_istitle, METH_NOARGS, istitle__doc__},
     3646    {"isalpha", (PyCFunction)string_isalpha, METH_NOARGS, isalpha__doc__},
     3647    {"isalnum", (PyCFunction)string_isalnum, METH_NOARGS, isalnum__doc__},
     3648    {"capitalize", (PyCFunction)string_capitalize, METH_NOARGS,
     3649    capitalize__doc__},
     3650    {"count", (PyCFunction)string_count, METH_VARARGS, count__doc__},
     3651    {"endswith", (PyCFunction)string_endswith, METH_VARARGS,
     3652    endswith__doc__},
     3653    {"partition", (PyCFunction)string_partition, METH_O, partition__doc__},
     3654    {"find", (PyCFunction)string_find, METH_VARARGS, find__doc__},
     3655    {"index", (PyCFunction)string_index, METH_VARARGS, index__doc__},
     3656    {"lstrip", (PyCFunction)string_lstrip, METH_VARARGS, lstrip__doc__},
     3657    {"replace", (PyCFunction)string_replace, METH_VARARGS, replace__doc__},
     3658    {"rfind", (PyCFunction)string_rfind, METH_VARARGS, rfind__doc__},
     3659    {"rindex", (PyCFunction)string_rindex, METH_VARARGS, rindex__doc__},
     3660    {"rstrip", (PyCFunction)string_rstrip, METH_VARARGS, rstrip__doc__},
     3661    {"rpartition", (PyCFunction)string_rpartition, METH_O,
     3662    rpartition__doc__},
     3663    {"startswith", (PyCFunction)string_startswith, METH_VARARGS,
     3664    startswith__doc__},
     3665    {"strip", (PyCFunction)string_strip, METH_VARARGS, strip__doc__},
     3666    {"swapcase", (PyCFunction)string_swapcase, METH_NOARGS,
     3667    swapcase__doc__},
     3668    {"translate", (PyCFunction)string_translate, METH_VARARGS,
     3669    translate__doc__},
     3670    {"title", (PyCFunction)string_title, METH_NOARGS, title__doc__},
     3671    {"ljust", (PyCFunction)string_ljust, METH_VARARGS, ljust__doc__},
     3672    {"rjust", (PyCFunction)string_rjust, METH_VARARGS, rjust__doc__},
     3673    {"center", (PyCFunction)string_center, METH_VARARGS, center__doc__},
     3674    {"zfill", (PyCFunction)string_zfill, METH_VARARGS, zfill__doc__},
     3675    {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
     3676    {"__format__", (PyCFunction) string__format__, METH_VARARGS, p_format__doc__},
     3677    {"_formatter_field_name_split", (PyCFunction) formatter_field_name_split, METH_NOARGS},
     3678    {"_formatter_parser", (PyCFunction) formatter_parser, METH_NOARGS},
     3679    {"encode", (PyCFunction)string_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
     3680    {"decode", (PyCFunction)string_decode, METH_VARARGS | METH_KEYWORDS, decode__doc__},
     3681    {"expandtabs", (PyCFunction)string_expandtabs, METH_VARARGS,
     3682    expandtabs__doc__},
     3683    {"splitlines", (PyCFunction)string_splitlines, METH_VARARGS,
     3684    splitlines__doc__},
     3685    {"__sizeof__", (PyCFunction)string_sizeof, METH_NOARGS,
     3686    sizeof__doc__},
     3687    {"__getnewargs__",          (PyCFunction)string_getnewargs, METH_NOARGS},
     3688    {NULL,     NULL}                         /* sentinel */
    40583689};
    40593690
     
    40643695string_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
    40653696{
    4066         PyObject *x = NULL;
    4067         static char *kwlist[] = {"object", 0};
    4068 
    4069         if (type != &PyString_Type)
    4070                 return str_subtype_new(type, args, kwds);
    4071         if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:str", kwlist, &x))
    4072                 return NULL;
    4073         if (x == NULL)
    4074                 return PyString_FromString("");
    4075         return PyObject_Str(x);
     3697    PyObject *x = NULL;
     3698    static char *kwlist[] = {"object", 0};
     3699
     3700    if (type != &PyString_Type)
     3701        return str_subtype_new(type, args, kwds);
     3702    if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:str", kwlist, &x))
     3703        return NULL;
     3704    if (x == NULL)
     3705        return PyString_FromString("");
     3706    return PyObject_Str(x);
    40763707}
    40773708
     
    40793710str_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
    40803711{
    4081         PyObject *tmp, *pnew;
    4082         Py_ssize_t n;
    4083 
    4084         assert(PyType_IsSubtype(type, &PyString_Type));
    4085         tmp = string_new(&PyString_Type, args, kwds);
    4086         if (tmp == NULL)
    4087                 return NULL;
    4088         assert(PyString_CheckExact(tmp));
    4089         n = PyString_GET_SIZE(tmp);
    4090         pnew = type->tp_alloc(type, n);
    4091         if (pnew != NULL) {
    4092                 Py_MEMCPY(PyString_AS_STRING(pnew), PyString_AS_STRING(tmp), n+1);
    4093                 ((PyStringObject *)pnew)->ob_shash =
    4094                         ((PyStringObject *)tmp)->ob_shash;
    4095                 ((PyStringObject *)pnew)->ob_sstate = SSTATE_NOT_INTERNED;
    4096         }
    4097         Py_DECREF(tmp);
    4098         return pnew;
     3712    PyObject *tmp, *pnew;
     3713    Py_ssize_t n;
     3714
     3715    assert(PyType_IsSubtype(type, &PyString_Type));
     3716    tmp = string_new(&PyString_Type, args, kwds);
     3717    if (tmp == NULL)
     3718        return NULL;
     3719    assert(PyString_CheckExact(tmp));
     3720    n = PyString_GET_SIZE(tmp);
     3721    pnew = type->tp_alloc(type, n);
     3722    if (pnew != NULL) {
     3723        Py_MEMCPY(PyString_AS_STRING(pnew), PyString_AS_STRING(tmp), n+1);
     3724        ((PyStringObject *)pnew)->ob_shash =
     3725            ((PyStringObject *)tmp)->ob_shash;
     3726        ((PyStringObject *)pnew)->ob_sstate = SSTATE_NOT_INTERNED;
     3727    }
     3728    Py_DECREF(tmp);
     3729    return pnew;
    40993730}
    41003731
     
    41023733basestring_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
    41033734{
    4104         PyErr_SetString(PyExc_TypeError,
    4105                         "The basestring type cannot be instantiated");
    4106         return NULL;
     3735    PyErr_SetString(PyExc_TypeError,
     3736                    "The basestring type cannot be instantiated");
     3737    return NULL;
    41073738}
    41083739
     
    41103741string_mod(PyObject *v, PyObject *w)
    41113742{
    4112         if (!PyString_Check(v)) {
    4113                 Py_INCREF(Py_NotImplemented);
    4114                 return Py_NotImplemented;
    4115         }
    4116         return PyString_Format(v, w);
     3743    if (!PyString_Check(v)) {
     3744        Py_INCREF(Py_NotImplemented);
     3745        return Py_NotImplemented;
     3746    }
     3747    return PyString_Format(v, w);
    41173748}
    41183749
     
    41213752
    41223753static PyNumberMethods string_as_number = {
    4123         0,                      /*nb_add*/
    4124         0,                      /*nb_subtract*/
    4125         0,                      /*nb_multiply*/
    4126         0,                      /*nb_divide*/
    4127         string_mod,             /*nb_remainder*/
     3754    0,                          /*nb_add*/
     3755    0,                          /*nb_subtract*/
     3756    0,                          /*nb_multiply*/
     3757    0,                          /*nb_divide*/
     3758    string_mod,                 /*nb_remainder*/
    41283759};
    41293760
    41303761
    41313762PyTypeObject PyBaseString_Type = {
    4132         PyVarObject_HEAD_INIT(&PyType_Type, 0)
    4133         "basestring",
    4134         0,
    4135         0,
    4136         0,                                      /* tp_dealloc */
    4137         0,                                      /* tp_print */
    4138         0,                                      /* tp_getattr */
    4139         0,                                      /* tp_setattr */
    4140         0,                                      /* tp_compare */
    4141         0,                                      /* tp_repr */
    4142         0,                                      /* tp_as_number */
    4143         0,                                      /* tp_as_sequence */
    4144         0,                                      /* tp_as_mapping */
    4145         0,                                      /* tp_hash */
    4146         0,                                      /* tp_call */
    4147         0,                                      /* tp_str */
    4148         0,                                      /* tp_getattro */
    4149         0,                                      /* tp_setattro */
    4150         0,                                      /* tp_as_buffer */
    4151         Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
    4152         basestring_doc,                         /* tp_doc */
    4153         0,                                      /* tp_traverse */
    4154         0,                                      /* tp_clear */
    4155         0,                                      /* tp_richcompare */
    4156         0,                                      /* tp_weaklistoffset */
    4157         0,                                      /* tp_iter */
    4158         0,                                      /* tp_iternext */
    4159         0,                                      /* tp_methods */
    4160         0,                                      /* tp_members */
    4161         0,                                      /* tp_getset */
    4162         &PyBaseObject_Type,                     /* tp_base */
    4163         0,                                      /* tp_dict */
    4164         0,                                      /* tp_descr_get */
    4165         0,                                      /* tp_descr_set */
    4166         0,                                      /* tp_dictoffset */
    4167         0,                                      /* tp_init */
    4168         0,                                      /* tp_alloc */
    4169         basestring_new,                         /* tp_new */
    4170         0,                                      /* tp_free */
     3763    PyVarObject_HEAD_INIT(&PyType_Type, 0)
     3764    "basestring",
     3765    0,
     3766    0,
     3767    0,                                          /* tp_dealloc */
     3768    0,                                          /* tp_print */
     3769    0,                                          /* tp_getattr */
     3770    0,                                          /* tp_setattr */
     3771    0,                                          /* tp_compare */
     3772    0,                                          /* tp_repr */
     3773    0,                                          /* tp_as_number */
     3774    0,                                          /* tp_as_sequence */
     3775    0,                                          /* tp_as_mapping */
     3776    0,                                          /* tp_hash */
     3777    0,                                          /* tp_call */
     3778    0,                                          /* tp_str */
     3779    0,                                          /* tp_getattro */
     3780    0,                                          /* tp_setattro */
     3781    0,                                          /* tp_as_buffer */
     3782    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
     3783    basestring_doc,                             /* tp_doc */
     3784    0,                                          /* tp_traverse */
     3785    0,                                          /* tp_clear */
     3786    0,                                          /* tp_richcompare */
     3787    0,                                          /* tp_weaklistoffset */
     3788    0,                                          /* tp_iter */
     3789    0,                                          /* tp_iternext */
     3790    0,                                          /* tp_methods */
     3791    0,                                          /* tp_members */
     3792    0,                                          /* tp_getset */
     3793    &PyBaseObject_Type,                         /* tp_base */
     3794    0,                                          /* tp_dict */
     3795    0,                                          /* tp_descr_get */
     3796    0,                                          /* tp_descr_set */
     3797    0,                                          /* tp_dictoffset */
     3798    0,                                          /* tp_init */
     3799    0,                                          /* tp_alloc */
     3800    basestring_new,                             /* tp_new */
     3801    0,                                          /* tp_free */
    41713802};
    41723803
    41733804PyDoc_STRVAR(string_doc,
    4174 "str(object) -> string\n\
     3805"str(object='') -> string\n\
    41753806\n\
    41763807Return a nice string representation of the object.\n\
     
    41783809
    41793810PyTypeObject PyString_Type = {
    4180         PyVarObject_HEAD_INIT(&PyType_Type, 0)
    4181         "str",
    4182         sizeof(PyStringObject),
    4183         sizeof(char),
    4184         string_dealloc,                         /* tp_dealloc */
    4185         (printfunc)string_print,                /* tp_print */
    4186         0,                                      /* tp_getattr */
    4187         0,                                      /* tp_setattr */
    4188         0,                                      /* tp_compare */
    4189         string_repr,                            /* tp_repr */
    4190         &string_as_number,                      /* tp_as_number */
    4191         &string_as_sequence,                    /* tp_as_sequence */
    4192         &string_as_mapping,                     /* tp_as_mapping */
    4193         (hashfunc)string_hash,                  /* tp_hash */
    4194         0,                                      /* tp_call */
    4195         string_str,                             /* tp_str */
    4196         PyObject_GenericGetAttr,                /* tp_getattro */
    4197         0,                                      /* tp_setattro */
    4198         &string_as_buffer,                      /* tp_as_buffer */
    4199         Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
    4200                 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_STRING_SUBCLASS |
    4201                 Py_TPFLAGS_HAVE_NEWBUFFER,      /* tp_flags */
    4202         string_doc,                             /* tp_doc */
    4203         0,                                      /* tp_traverse */
    4204         0,                                      /* tp_clear */
    4205         (richcmpfunc)string_richcompare,        /* tp_richcompare */
    4206         0,                                      /* tp_weaklistoffset */
    4207         0,                                      /* tp_iter */
    4208         0,                                      /* tp_iternext */
    4209         string_methods,                         /* tp_methods */
    4210         0,                                      /* tp_members */
    4211         0,                                      /* tp_getset */
    4212         &PyBaseString_Type,                     /* tp_base */
    4213         0,                                      /* tp_dict */
    4214         0,                                      /* tp_descr_get */
    4215         0,                                      /* tp_descr_set */
    4216         0,                                      /* tp_dictoffset */
    4217         0,                                      /* tp_init */
    4218         0,                                      /* tp_alloc */
    4219         string_new,                             /* tp_new */
    4220         PyObject_Del,                           /* tp_free */
     3811    PyVarObject_HEAD_INIT(&PyType_Type, 0)
     3812    "str",
     3813    PyStringObject_SIZE,
     3814    sizeof(char),
     3815    string_dealloc,                             /* tp_dealloc */
     3816    (printfunc)string_print,                    /* tp_print */
     3817    0,                                          /* tp_getattr */
     3818    0,                                          /* tp_setattr */
     3819    0,                                          /* tp_compare */
     3820    string_repr,                                /* tp_repr */
     3821    &string_as_number,                          /* tp_as_number */
     3822    &string_as_sequence,                        /* tp_as_sequence */
     3823    &string_as_mapping,                         /* tp_as_mapping */
     3824    (hashfunc)string_hash,                      /* tp_hash */
     3825    0,                                          /* tp_call */
     3826    string_str,                                 /* tp_str */
     3827    PyObject_GenericGetAttr,                    /* tp_getattro */
     3828    0,                                          /* tp_setattro */
     3829    &string_as_buffer,                          /* tp_as_buffer */
     3830    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
     3831        Py_TPFLAGS_BASETYPE | Py_TPFLAGS_STRING_SUBCLASS |
     3832        Py_TPFLAGS_HAVE_NEWBUFFER,              /* tp_flags */
     3833    string_doc,                                 /* tp_doc */
     3834    0,                                          /* tp_traverse */
     3835    0,                                          /* tp_clear */
     3836    (richcmpfunc)string_richcompare,            /* tp_richcompare */
     3837    0,                                          /* tp_weaklistoffset */
     3838    0,                                          /* tp_iter */
     3839    0,                                          /* tp_iternext */
     3840    string_methods,                             /* tp_methods */
     3841    0,                                          /* tp_members */
     3842    0,                                          /* tp_getset */
     3843    &PyBaseString_Type,                         /* tp_base */
     3844    0,                                          /* tp_dict */
     3845    0,                                          /* tp_descr_get */
     3846    0,                                          /* tp_descr_set */
     3847    0,                                          /* tp_dictoffset */
     3848    0,                                          /* tp_init */
     3849    0,                                          /* tp_alloc */
     3850    string_new,                                 /* tp_new */
     3851    PyObject_Del,                               /* tp_free */
    42213852};
    42223853
     
    42243855PyString_Concat(register PyObject **pv, register PyObject *w)
    42253856{
    4226         register PyObject *v;
    4227         if (*pv == NULL)
    4228                 return;
    4229         if (w == NULL || !PyString_Check(*pv)) {
    4230                 Py_DECREF(*pv);
    4231                 *pv = NULL;
    4232                 return;
    4233         }
    4234         v = string_concat((PyStringObject *) *pv, w);
    4235         Py_DECREF(*pv);
    4236         *pv = v;
     3857    register PyObject *v;
     3858    if (*pv == NULL)
     3859        return;
     3860    if (w == NULL || !PyString_Check(*pv)) {
     3861        Py_CLEAR(*pv);
     3862        return;
     3863    }
     3864    v = string_concat((PyStringObject *) *pv, w);
     3865    Py_DECREF(*pv);
     3866    *pv = v;
    42373867}
    42383868
     
    42403870PyString_ConcatAndDel(register PyObject **pv, register PyObject *w)
    42413871{
    4242         PyString_Concat(pv, w);
    4243         Py_XDECREF(w);
     3872    PyString_Concat(pv, w);
     3873    Py_XDECREF(w);
    42443874}
    42453875
     
    42623892_PyString_Resize(PyObject **pv, Py_ssize_t newsize)
    42633893{
    4264         register PyObject *v;
    4265         register PyStringObject *sv;
    4266         v = *pv;
    4267         if (!PyString_Check(v) || Py_REFCNT(v) != 1 || newsize < 0 ||
    4268             PyString_CHECK_INTERNED(v)) {
    4269                 *pv = 0;
    4270                 Py_DECREF(v);
    4271                 PyErr_BadInternalCall();
    4272                 return -1;
    4273         }
    4274         /* XXX UNREF/NEWREF interface should be more symmetrical */
    4275         _Py_DEC_REFTOTAL;
    4276         _Py_ForgetReference(v);
    4277         *pv = (PyObject *)
    4278                 PyObject_REALLOC((char *)v, sizeof(PyStringObject) + newsize);
    4279         if (*pv == NULL) {
    4280                 PyObject_Del(v);
    4281                 PyErr_NoMemory();
    4282                 return -1;
    4283         }
    4284         _Py_NewReference(*pv);
    4285         sv = (PyStringObject *) *pv;
    4286         Py_SIZE(sv) = newsize;
    4287         sv->ob_sval[newsize] = '\0';
    4288         sv->ob_shash = -1;      /* invalidate cached hash value */
    4289         return 0;
     3894    register PyObject *v;
     3895    register PyStringObject *sv;
     3896    v = *pv;
     3897    if (!PyString_Check(v) || Py_REFCNT(v) != 1 || newsize < 0 ||
     3898        PyString_CHECK_INTERNED(v)) {
     3899        *pv = 0;
     3900        Py_DECREF(v);
     3901        PyErr_BadInternalCall();
     3902        return -1;
     3903    }
     3904    /* XXX UNREF/NEWREF interface should be more symmetrical */
     3905    _Py_DEC_REFTOTAL;
     3906    _Py_ForgetReference(v);
     3907    *pv = (PyObject *)
     3908        PyObject_REALLOC((char *)v, PyStringObject_SIZE + newsize);
     3909    if (*pv == NULL) {
     3910        PyObject_Del(v);
     3911        PyErr_NoMemory();
     3912        return -1;
     3913    }
     3914    _Py_NewReference(*pv);
     3915    sv = (PyStringObject *) *pv;
     3916    Py_SIZE(sv) = newsize;
     3917    sv->ob_sval[newsize] = '\0';
     3918    sv->ob_shash = -1;          /* invalidate cached hash value */
     3919    return 0;
    42903920}
    42913921
     
    42953925getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
    42963926{
    4297         Py_ssize_t argidx = *p_argidx;
    4298         if (argidx < arglen) {
    4299                 (*p_argidx)++;
    4300                 if (arglen < 0)
    4301                         return args;
    4302                 else
    4303                         return PyTuple_GetItem(args, argidx);
    4304         }
    4305         PyErr_SetString(PyExc_TypeError,
    4306                         "not enough arguments for format string");
    4307         return NULL;
     3927    Py_ssize_t argidx = *p_argidx;
     3928    if (argidx < arglen) {
     3929        (*p_argidx)++;
     3930        if (arglen < 0)
     3931            return args;
     3932        else
     3933            return PyTuple_GetItem(args, argidx);
     3934    }
     3935    PyErr_SetString(PyExc_TypeError,
     3936                    "not enough arguments for format string");
     3937    return NULL;
    43083938}
    43093939
    43103940/* Format codes
    4311  * F_LJUST      '-'
    4312  * F_SIGN       '+'
    4313  * F_BLANK      ' '
    4314  * F_ALT        '#'
    4315  * F_ZERO       '0'
     3941 * F_LJUST      '-'
     3942 * F_SIGN       '+'
     3943 * F_BLANK      ' '
     3944 * F_ALT        '#'
     3945 * F_ZERO       '0'
    43163946 */
    43173947#define F_LJUST (1<<0)
    4318 #define F_SIGN  (1<<1)
     3948#define F_SIGN  (1<<1)
    43193949#define F_BLANK (1<<2)
    4320 #define F_ALT   (1<<3)
    4321 #define F_ZERO  (1<<4)
    4322 
    4323 Py_LOCAL_INLINE(int)
    4324 formatfloat(char *buf, size_t buflen, int flags,
    4325             int prec, int type, PyObject *v)
    4326 {
    4327         /* fmt = '%#.' + `prec` + `type`
    4328            worst case length = 3 + 10 (len of INT_MAX) + 1 = 14 (use 20)*/
    4329         char fmt[20];
    4330         double x;
    4331         x = PyFloat_AsDouble(v);
    4332         if (x == -1.0 && PyErr_Occurred()) {
    4333                 PyErr_Format(PyExc_TypeError, "float argument required, "
    4334                              "not %.200s", Py_TYPE(v)->tp_name);
    4335                 return -1;
    4336         }
    4337         if (prec < 0)
    4338                 prec = 6;
    4339 #if SIZEOF_INT > 4
    4340         /* make sure that the decimal representation of precision really does
    4341            need at most 10 digits: platforms with sizeof(int) == 8 exist! */
    4342         if (prec > 0x7fffffff) {
    4343                 PyErr_SetString(PyExc_OverflowError,
    4344                                 "outrageously large precision "
    4345                                 "for formatted float");
    4346                 return -1;
    4347         }
    4348 #endif
    4349 
    4350         if (type == 'f' && fabs(x) >= 1e50)
    4351                 type = 'g';
    4352         /* Worst case length calc to ensure no buffer overrun:
    4353 
    4354            'g' formats:
    4355              fmt = %#.<prec>g
    4356              buf = '-' + [0-9]*prec + '.' + 'e+' + (longest exp
    4357                 for any double rep.)
    4358              len = 1 + prec + 1 + 2 + 5 = 9 + prec
    4359 
    4360            'f' formats:
    4361              buf = '-' + [0-9]*x + '.' + [0-9]*prec (with x < 50)
    4362              len = 1 + 50 + 1 + prec = 52 + prec
    4363 
    4364            If prec=0 the effective precision is 1 (the leading digit is
    4365            always given), therefore increase the length by one.
    4366 
    4367         */
    4368         if (((type == 'g' || type == 'G') &&
    4369               buflen <= (size_t)10 + (size_t)prec) ||
    4370             (type == 'f' && buflen <= (size_t)53 + (size_t)prec)) {
    4371                 PyErr_SetString(PyExc_OverflowError,
    4372                         "formatted float is too long (precision too large?)");
    4373                 return -1;
    4374         }
    4375         PyOS_snprintf(fmt, sizeof(fmt), "%%%s.%d%c",
    4376                       (flags&F_ALT) ? "#" : "",
    4377                       prec, type);
    4378         PyOS_ascii_formatd(buf, buflen, fmt, x);
    4379         return (int)strlen(buf);
     3950#define F_ALT   (1<<3)
     3951#define F_ZERO  (1<<4)
     3952
     3953/* Returns a new reference to a PyString object, or NULL on failure. */
     3954
     3955static PyObject *
     3956formatfloat(PyObject *v, int flags, int prec, int type)
     3957{
     3958    char *p;
     3959    PyObject *result;
     3960    double x;
     3961
     3962    x = PyFloat_AsDouble(v);
     3963    if (x == -1.0 && PyErr_Occurred()) {
     3964        PyErr_Format(PyExc_TypeError, "float argument required, "
     3965                     "not %.200s", Py_TYPE(v)->tp_name);
     3966        return NULL;
     3967    }
     3968
     3969    if (prec < 0)
     3970        prec = 6;
     3971
     3972    p = PyOS_double_to_string(x, type, prec,
     3973                              (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL);
     3974
     3975    if (p == NULL)
     3976        return NULL;
     3977    result = PyString_FromStringAndSize(p, strlen(p));
     3978    PyMem_Free(p);
     3979    return result;
    43803980}
    43813981
     
    43933993 *     There will be at least prec digits, zero-filled on the left if
    43943994 *         necessary to get that many.
    4395  * val          object to be converted
    4396  * flags        bitmask of format flags; only F_ALT is looked at
    4397  * prec         minimum number of digits; 0-fill on left if needed
    4398  * type         a character in [duoxX]; u acts the same as d
     3995 * val          object to be converted
     3996 * flags        bitmask of format flags; only F_ALT is looked at
     3997 * prec         minimum number of digits; 0-fill on left if needed
     3998 * type         a character in [duoxX]; u acts the same as d
    43993999 *
    44004000 * CAUTION:  o, x and X conversions on regular ints can never
     
    44034003PyObject*
    44044004_PyString_FormatLong(PyObject *val, int flags, int prec, int type,
    4405                      char **pbuf, int *plen)
    4406 {
    4407         PyObject *result = NULL;
    4408         char *buf;
    4409         Py_ssize_t i;
    4410         int sign;       /* 1 if '-', else 0 */
    4411         int len;        /* number of characters */
    4412         Py_ssize_t llen;
    4413         int numdigits;  /* len == numnondigits + numdigits */
    4414         int numnondigits = 0;
    4415 
    4416         switch (type) {
    4417         case 'd':
    4418         case 'u':
    4419                 result = Py_TYPE(val)->tp_str(val);
    4420                 break;
    4421         case 'o':
    4422                 result = Py_TYPE(val)->tp_as_number->nb_oct(val);
    4423                 break;
    4424         case 'x':
    4425         case 'X':
    4426                 numnondigits = 2;
    4427                 result = Py_TYPE(val)->tp_as_number->nb_hex(val);
    4428                 break;
    4429         default:
    4430                 assert(!"'type' not in [duoxX]");
    4431         }
    4432         if (!result)
    4433                 return NULL;
    4434 
    4435         buf = PyString_AsString(result);
    4436         if (!buf) {
    4437                 Py_DECREF(result);
    4438                 return NULL;
    4439         }
    4440 
    4441         /* To modify the string in-place, there can only be one reference. */
    4442         if (Py_REFCNT(result) != 1) {
    4443                 PyErr_BadInternalCall();
    4444                 return NULL;
    4445         }
    4446         llen = PyString_Size(result);
    4447         if (llen > INT_MAX) {
    4448                 PyErr_SetString(PyExc_ValueError, "string too large in _PyString_FormatLong");
    4449                 return NULL;
    4450         }
    4451         len = (int)llen;
    4452         if (buf[len-1] == 'L') {
    4453                 --len;
    4454                 buf[len] = '\0';
    4455         }
    4456         sign = buf[0] == '-';
    4457         numnondigits += sign;
    4458         numdigits = len - numnondigits;
    4459         assert(numdigits > 0);
    4460 
    4461         /* Get rid of base marker unless F_ALT */
    4462         if ((flags & F_ALT) == 0) {
    4463                 /* Need to skip 0x, 0X or 0. */
    4464                 int skipped = 0;
    4465                 switch (type) {
    4466                 case 'o':
    4467                         assert(buf[sign] == '0');
    4468                         /* If 0 is only digit, leave it alone. */
    4469                         if (numdigits > 1) {
    4470                                 skipped = 1;
    4471                                 --numdigits;
    4472                         }
    4473                         break;
    4474                 case 'x':
    4475                 case 'X':
    4476                         assert(buf[sign] == '0');
    4477                         assert(buf[sign + 1] == 'x');
    4478                         skipped = 2;
    4479                         numnondigits -= 2;
    4480                         break;
    4481                 }
    4482                 if (skipped) {
    4483                         buf += skipped;
    4484                         len -= skipped;
    4485                         if (sign)
    4486                                 buf[0] = '-';
    4487                 }
    4488                 assert(len == numnondigits + numdigits);
    4489                 assert(numdigits > 0);
    4490         }
    4491 
    4492         /* Fill with leading zeroes to meet minimum width. */
    4493         if (prec > numdigits) {
    4494                 PyObject *r1 = PyString_FromStringAndSize(NULL,
    4495                                         numnondigits + prec);
    4496                 char *b1;
    4497                 if (!r1) {
    4498                         Py_DECREF(result);
    4499                         return NULL;
    4500                 }
    4501                 b1 = PyString_AS_STRING(r1);
    4502                 for (i = 0; i < numnondigits; ++i)
    4503                         *b1++ = *buf++;
    4504                 for (i = 0; i < prec - numdigits; i++)
    4505                         *b1++ = '0';
    4506                 for (i = 0; i < numdigits; i++)
    4507                         *b1++ = *buf++;
    4508                 *b1 = '\0';
    4509                 Py_DECREF(result);
    4510                 result = r1;
    4511                 buf = PyString_AS_STRING(result);
    4512                 len = numnondigits + prec;
    4513         }
    4514 
    4515         /* Fix up case for hex conversions. */
    4516         if (type == 'X') {
    4517                 /* Need to convert all lower case letters to upper case.
    4518                    and need to convert 0x to 0X (and -0x to -0X). */
    4519                 for (i = 0; i < len; i++)
    4520                         if (buf[i] >= 'a' && buf[i] <= 'x')
    4521                                 buf[i] -= 'a'-'A';
    4522         }
    4523         *pbuf = buf;
    4524         *plen = len;
    4525         return result;
     4005                     char **pbuf, int *plen)
     4006{
     4007    PyObject *result = NULL;
     4008    char *buf;
     4009    Py_ssize_t i;
     4010    int sign;           /* 1 if '-', else 0 */
     4011    int len;            /* number of characters */
     4012    Py_ssize_t llen;
     4013    int numdigits;      /* len == numnondigits + numdigits */
     4014    int numnondigits = 0;
     4015
     4016    switch (type) {
     4017    case 'd':
     4018    case 'u':
     4019        result = Py_TYPE(val)->tp_str(val);
     4020        break;
     4021    case 'o':
     4022        result = Py_TYPE(val)->tp_as_number->nb_oct(val);
     4023        break;
     4024    case 'x':
     4025    case 'X':
     4026        numnondigits = 2;
     4027        result = Py_TYPE(val)->tp_as_number->nb_hex(val);
     4028        break;
     4029    default:
     4030        assert(!"'type' not in [duoxX]");
     4031    }
     4032    if (!result)
     4033        return NULL;
     4034
     4035    buf = PyString_AsString(result);
     4036    if (!buf) {
     4037        Py_DECREF(result);
     4038        return NULL;
     4039    }
     4040
     4041    /* To modify the string in-place, there can only be one reference. */
     4042    if (Py_REFCNT(result) != 1) {
     4043        PyErr_BadInternalCall();
     4044        return NULL;
     4045    }
     4046    llen = PyString_Size(result);
     4047    if (llen > INT_MAX) {
     4048        PyErr_SetString(PyExc_ValueError, "string too large in _PyString_FormatLong");
     4049        return NULL;
     4050    }
     4051    len = (int)llen;
     4052    if (buf[len-1] == 'L') {
     4053        --len;
     4054        buf[len] = '\0';
     4055    }
     4056    sign = buf[0] == '-';
     4057    numnondigits += sign;
     4058    numdigits = len - numnondigits;
     4059    assert(numdigits > 0);
     4060
     4061    /* Get rid of base marker unless F_ALT */
     4062    if ((flags & F_ALT) == 0) {
     4063        /* Need to skip 0x, 0X or 0. */
     4064        int skipped = 0;
     4065        switch (type) {
     4066        case 'o':
     4067            assert(buf[sign] == '0');
     4068            /* If 0 is only digit, leave it alone. */
     4069            if (numdigits > 1) {
     4070                skipped = 1;
     4071                --numdigits;
     4072            }
     4073            break;
     4074        case 'x':
     4075        case 'X':
     4076            assert(buf[sign] == '0');
     4077            assert(buf[sign + 1] == 'x');
     4078            skipped = 2;
     4079            numnondigits -= 2;
     4080            break;
     4081        }
     4082        if (skipped) {
     4083            buf += skipped;
     4084            len -= skipped;
     4085            if (sign)
     4086                buf[0] = '-';
     4087        }
     4088        assert(len == numnondigits + numdigits);
     4089        assert(numdigits > 0);
     4090    }
     4091
     4092    /* Fill with leading zeroes to meet minimum width. */
     4093    if (prec > numdigits) {
     4094        PyObject *r1 = PyString_FromStringAndSize(NULL,
     4095                                numnondigits + prec);
     4096        char *b1;
     4097        if (!r1) {
     4098            Py_DECREF(result);
     4099            return NULL;
     4100        }
     4101        b1 = PyString_AS_STRING(r1);
     4102        for (i = 0; i < numnondigits; ++i)
     4103            *b1++ = *buf++;
     4104        for (i = 0; i < prec - numdigits; i++)
     4105            *b1++ = '0';
     4106        for (i = 0; i < numdigits; i++)
     4107            *b1++ = *buf++;
     4108        *b1 = '\0';
     4109        Py_DECREF(result);
     4110        result = r1;
     4111        buf = PyString_AS_STRING(result);
     4112        len = numnondigits + prec;
     4113    }
     4114
     4115    /* Fix up case for hex conversions. */
     4116    if (type == 'X') {
     4117        /* Need to convert all lower case letters to upper case.
     4118           and need to convert 0x to 0X (and -0x to -0X). */
     4119        for (i = 0; i < len; i++)
     4120            if (buf[i] >= 'a' && buf[i] <= 'x')
     4121                buf[i] -= 'a'-'A';
     4122    }
     4123    *pbuf = buf;
     4124    *plen = len;
     4125    return result;
    45264126}
    45274127
     
    45304130          int prec, int type, PyObject *v)
    45314131{
    4532         /* fmt = '%#.' + `prec` + 'l' + `type`
    4533            worst case length = 3 + 19 (worst len of INT_MAX on 64-bit machine)
    4534            + 1 + 1 = 24 */
    4535         char fmt[64];   /* plenty big enough! */
    4536         char *sign;
    4537         long x;
    4538 
    4539         x = PyInt_AsLong(v);
    4540         if (x == -1 && PyErr_Occurred()) {
    4541                 PyErr_Format(PyExc_TypeError, "int argument required, not %.200s",
    4542                              Py_TYPE(v)->tp_name);
    4543                 return -1;
    4544         }
    4545         if (x < 0 && type == 'u') {
    4546                 type = 'd';
    4547         }
    4548         if (x < 0 && (type == 'x' || type == 'X' || type == 'o'))
    4549                 sign = "-";
    4550         else
    4551                 sign = "";
    4552         if (prec < 0)
    4553                 prec = 1;
    4554 
    4555         if ((flags & F_ALT) &&
    4556             (type == 'x' || type == 'X')) {
    4557                 /* When converting under %#x or %#X, there are a number
    4558                 * of issues that cause pain:
    4559                 * - when 0 is being converted, the C standard leaves off
    4560                 *   the '0x' or '0X', which is inconsistent with other
    4561                 *   %#x/%#X conversions and inconsistent with Python's
    4562                 *   hex() function
    4563                 * - there are platforms that violate the standard and
    4564                 *   convert 0 with the '0x' or '0X'
    4565                 *   (Metrowerks, Compaq Tru64)
    4566                 * - there are platforms that give '0x' when converting
    4567                 *   under %#X, but convert 0 in accordance with the
    4568                 *   standard (OS/2 EMX)
    4569                 *
    4570                 * We can achieve the desired consistency by inserting our
    4571                 * own '0x' or '0X' prefix, and substituting %x/%X in place
    4572                 * of %#x/%#X.
    4573                 *
    4574                 * Note that this is the same approach as used in
    4575                 * formatint() in unicodeobject.c
    4576                 */
    4577                 PyOS_snprintf(fmt, sizeof(fmt), "%s0%c%%.%dl%c",
    4578                               sign, type, prec, type);
    4579         }
    4580         else {
    4581                 PyOS_snprintf(fmt, sizeof(fmt), "%s%%%s.%dl%c",
    4582                               sign, (flags&F_ALT) ? "#" : "",
    4583                               prec, type);
    4584         }
    4585 
    4586         /* buf = '+'/'-'/'' + '0'/'0x'/'' + '[0-9]'*max(prec, len(x in octal))
    4587         * worst case buf = '-0x' + [0-9]*prec, where prec >= 11
    4588         */
    4589         if (buflen <= 14 || buflen <= (size_t)3 + (size_t)prec) {
    4590                 PyErr_SetString(PyExc_OverflowError,
    4591                     "formatted integer is too long (precision too large?)");
    4592                 return -1;
    4593         }
    4594         if (sign[0])
    4595                 PyOS_snprintf(buf, buflen, fmt, -x);
    4596         else
    4597                 PyOS_snprintf(buf, buflen, fmt, x);
    4598         return (int)strlen(buf);
     4132    /* fmt = '%#.' + `prec` + 'l' + `type`
     4133       worst case length = 3 + 19 (worst len of INT_MAX on 64-bit machine)
     4134       + 1 + 1 = 24 */
     4135    char fmt[64];       /* plenty big enough! */
     4136    char *sign;
     4137    long x;
     4138
     4139    x = PyInt_AsLong(v);
     4140    if (x == -1 && PyErr_Occurred()) {
     4141        PyErr_Format(PyExc_TypeError, "int argument required, not %.200s",
     4142                     Py_TYPE(v)->tp_name);
     4143        return -1;
     4144    }
     4145    if (x < 0 && type == 'u') {
     4146        type = 'd';
     4147    }
     4148    if (x < 0 && (type == 'x' || type == 'X' || type == 'o'))
     4149        sign = "-";
     4150    else
     4151        sign = "";
     4152    if (prec < 0)
     4153        prec = 1;
     4154
     4155    if ((flags & F_ALT) &&
     4156        (type == 'x' || type == 'X')) {
     4157        /* When converting under %#x or %#X, there are a number
     4158        * of issues that cause pain:
     4159        * - when 0 is being converted, the C standard leaves off
     4160        *   the '0x' or '0X', which is inconsistent with other
     4161        *   %#x/%#X conversions and inconsistent with Python's
     4162        *   hex() function
     4163        * - there are platforms that violate the standard and
     4164        *   convert 0 with the '0x' or '0X'
     4165        *   (Metrowerks, Compaq Tru64)
     4166        * - there are platforms that give '0x' when converting
     4167        *   under %#X, but convert 0 in accordance with the
     4168        *   standard (OS/2 EMX)
     4169        *
     4170        * We can achieve the desired consistency by inserting our
     4171        * own '0x' or '0X' prefix, and substituting %x/%X in place
     4172        * of %#x/%#X.
     4173        *
     4174        * Note that this is the same approach as used in
     4175        * formatint() in unicodeobject.c
     4176        */
     4177        PyOS_snprintf(fmt, sizeof(fmt), "%s0%c%%.%dl%c",
     4178                      sign, type, prec, type);
     4179    }
     4180    else {
     4181        PyOS_snprintf(fmt, sizeof(fmt), "%s%%%s.%dl%c",
     4182                      sign, (flags&F_ALT) ? "#" : "",
     4183                      prec, type);
     4184    }
     4185
     4186    /* buf = '+'/'-'/'' + '0'/'0x'/'' + '[0-9]'*max(prec, len(x in octal))
     4187    * worst case buf = '-0x' + [0-9]*prec, where prec >= 11
     4188    */
     4189    if (buflen <= 14 || buflen <= (size_t)3 + (size_t)prec) {
     4190        PyErr_SetString(PyExc_OverflowError,
     4191            "formatted integer is too long (precision too large?)");
     4192        return -1;
     4193    }
     4194    if (sign[0])
     4195        PyOS_snprintf(buf, buflen, fmt, -x);
     4196    else
     4197        PyOS_snprintf(buf, buflen, fmt, x);
     4198    return (int)strlen(buf);
    45994199}
    46004200
     
    46024202formatchar(char *buf, size_t buflen, PyObject *v)
    46034203{
    4604         /* presume that the buffer is at least 2 characters long */
    4605         if (PyString_Check(v)) {
    4606                 if (!PyArg_Parse(v, "c;%c requires int or char", &buf[0]))
    4607                         return -1;
    4608         }
    4609         else {
    4610                 if (!PyArg_Parse(v, "b;%c requires int or char", &buf[0]))
    4611                         return -1;
    4612         }
    4613         buf[1] = '\0';
    4614         return 1;
     4204    /* presume that the buffer is at least 2 characters long */
     4205    if (PyString_Check(v)) {
     4206        if (!PyArg_Parse(v, "c;%c requires int or char", &buf[0]))
     4207            return -1;
     4208    }
     4209    else {
     4210        if (!PyArg_Parse(v, "b;%c requires int or char", &buf[0]))
     4211            return -1;
     4212    }
     4213    buf[1] = '\0';
     4214    return 1;
    46154215}
    46164216
    46174217/* fmt%(v1,v2,...) is roughly equivalent to sprintf(fmt, v1, v2, ...)
    46184218
    4619    FORMATBUFLEN is the length of the buffer in which the floats, ints, &
     4219   FORMATBUFLEN is the length of the buffer in which the ints &
    46204220   chars are formatted. XXX This is a magic number. Each formatting
    46214221   routine does bounds checking to ensure no overflow, but a better
     
    46284228PyString_Format(PyObject *format, PyObject *args)
    46294229{
    4630         char *fmt, *res;
    4631         Py_ssize_t arglen, argidx;
    4632         Py_ssize_t reslen, rescnt, fmtcnt;
    4633         int args_owned = 0;
    4634         PyObject *result, *orig_args;
     4230    char *fmt, *res;
     4231    Py_ssize_t arglen, argidx;
     4232    Py_ssize_t reslen, rescnt, fmtcnt;
     4233    int args_owned = 0;
     4234    PyObject *result, *orig_args;
    46354235#ifdef Py_USING_UNICODE
    4636         PyObject *v, *w;
     4236    PyObject *v, *w;
    46374237#endif
    4638         PyObject *dict = NULL;
    4639         if (format == NULL || !PyString_Check(format) || args == NULL) {
    4640                 PyErr_BadInternalCall();
    4641                 return NULL;
    4642         }
    4643         orig_args = args;
    4644         fmt = PyString_AS_STRING(format);
    4645         fmtcnt = PyString_GET_SIZE(format);
    4646         reslen = rescnt = fmtcnt + 100;
    4647         result = PyString_FromStringAndSize((char *)NULL, reslen);
    4648         if (result == NULL)
    4649                 return NULL;
    4650         res = PyString_AsString(result);
    4651         if (PyTuple_Check(args)) {
    4652                 arglen = PyTuple_GET_SIZE(args);
    4653                 argidx = 0;
    4654         }
    4655         else {
    4656                 arglen = -1;
    4657                 argidx = -2;
    4658         }
    4659         if (Py_TYPE(args)->tp_as_mapping && !PyTuple_Check(args) &&
    4660             !PyObject_TypeCheck(args, &PyBaseString_Type))
    4661                 dict = args;
    4662         while (--fmtcnt >= 0) {
    4663                 if (*fmt != '%') {
    4664                         if (--rescnt < 0) {
    4665                                 rescnt = fmtcnt + 100;
    4666                                 reslen += rescnt;
    4667                                 if (_PyString_Resize(&result, reslen) < 0)
    4668                                         return NULL;
    4669                                 res = PyString_AS_STRING(result)
    4670                                         + reslen - rescnt;
    4671                                 --rescnt;
    4672                         }
    4673                         *res++ = *fmt++;
    4674                 }
    4675                 else {
    4676                         /* Got a format specifier */
    4677                         int flags = 0;
    4678                         Py_ssize_t width = -1;
    4679                         int prec = -1;
    4680                         int c = '\0';
    4681                         int fill;
    4682                         int isnumok;
    4683                         PyObject *v = NULL;
    4684                         PyObject *temp = NULL;
    4685                         char *pbuf;
    4686                         int sign;
    4687                         Py_ssize_t len;
    4688                         char formatbuf[FORMATBUFLEN];
    4689                              /* For format{float,int,char}() */
     4238    PyObject *dict = NULL;
     4239    if (format == NULL || !PyString_Check(format) || args == NULL) {
     4240        PyErr_BadInternalCall();
     4241        return NULL;
     4242    }
     4243    orig_args = args;
     4244    fmt = PyString_AS_STRING(format);
     4245    fmtcnt = PyString_GET_SIZE(format);
     4246    reslen = rescnt = fmtcnt + 100;
     4247    result = PyString_FromStringAndSize((char *)NULL, reslen);
     4248    if (result == NULL)
     4249        return NULL;
     4250    res = PyString_AsString(result);
     4251    if (PyTuple_Check(args)) {
     4252        arglen = PyTuple_GET_SIZE(args);
     4253        argidx = 0;
     4254    }
     4255    else {
     4256        arglen = -1;
     4257        argidx = -2;
     4258    }
     4259    if (Py_TYPE(args)->tp_as_mapping && Py_TYPE(args)->tp_as_mapping->mp_subscript &&
     4260        !PyTuple_Check(args) && !PyObject_TypeCheck(args, &PyBaseString_Type))
     4261        dict = args;
     4262    while (--fmtcnt >= 0) {
     4263        if (*fmt != '%') {
     4264            if (--rescnt < 0) {
     4265                rescnt = fmtcnt + 100;
     4266                reslen += rescnt;
     4267                if (_PyString_Resize(&result, reslen))
     4268                    return NULL;
     4269                res = PyString_AS_STRING(result)
     4270                    + reslen - rescnt;
     4271                --rescnt;
     4272            }
     4273            *res++ = *fmt++;
     4274        }
     4275        else {
     4276            /* Got a format specifier */
     4277            int flags = 0;
     4278            Py_ssize_t width = -1;
     4279            int prec = -1;
     4280            int c = '\0';
     4281            int fill;
     4282            int isnumok;
     4283            PyObject *v = NULL;
     4284            PyObject *temp = NULL;
     4285            char *pbuf;
     4286            int sign;
     4287            Py_ssize_t len;
     4288            char formatbuf[FORMATBUFLEN];
     4289                 /* For format{int,char}() */
    46904290#ifdef Py_USING_UNICODE
    4691                         char *fmt_start = fmt;
    4692                         Py_ssize_t argidx_start = argidx;
     4291            char *fmt_start = fmt;
     4292            Py_ssize_t argidx_start = argidx;
    46934293#endif
    46944294
    4695                         fmt++;
    4696                         if (*fmt == '(') {
    4697                                 char *keystart;
    4698                                 Py_ssize_t keylen;
    4699                                 PyObject *key;
    4700                                 int pcount = 1;
    4701 
    4702                                 if (dict == NULL) {
    4703                                         PyErr_SetString(PyExc_TypeError,
    4704                                                  "format requires a mapping");
    4705                                         goto error;
    4706                                 }
    4707                                 ++fmt;
    4708                                 --fmtcnt;
    4709                                 keystart = fmt;
    4710                                 /* Skip over balanced parentheses */
    4711                                 while (pcount > 0 && --fmtcnt >= 0) {
    4712                                         if (*fmt == ')')
    4713                                                 --pcount;
    4714                                         else if (*fmt == '(')
    4715                                                 ++pcount;
    4716                                         fmt++;
    4717                                 }
    4718                                 keylen = fmt - keystart - 1;
    4719                                 if (fmtcnt < 0 || pcount > 0) {
    4720                                         PyErr_SetString(PyExc_ValueError,
    4721                                                    "incomplete format key");
    4722                                         goto error;
    4723                                 }
    4724                                 key = PyString_FromStringAndSize(keystart,
    4725                                                                  keylen);
    4726                                 if (key == NULL)
    4727                                         goto error;
    4728                                 if (args_owned) {
    4729                                         Py_DECREF(args);
    4730                                         args_owned = 0;
    4731                                 }
    4732                                 args = PyObject_GetItem(dict, key);
    4733                                 Py_DECREF(key);
    4734                                 if (args == NULL) {
    4735                                         goto error;
    4736                                 }
    4737                                 args_owned = 1;
    4738                                 arglen = -1;
    4739                                 argidx = -2;
    4740                         }
    4741                         while (--fmtcnt >= 0) {
    4742                                 switch (c = *fmt++) {
    4743                                 case '-': flags |= F_LJUST; continue;
    4744                                 case '+': flags |= F_SIGN; continue;
    4745                                 case ' ': flags |= F_BLANK; continue;
    4746                                 case '#': flags |= F_ALT; continue;
    4747                                 case '0': flags |= F_ZERO; continue;
    4748                                 }
    4749                                 break;
    4750                         }
    4751                         if (c == '*') {
    4752                                 v = getnextarg(args, arglen, &argidx);
    4753                                 if (v == NULL)
    4754                                         goto error;
    4755                                 if (!PyInt_Check(v)) {
    4756                                         PyErr_SetString(PyExc_TypeError,
    4757                                                         "* wants int");
    4758                                         goto error;
    4759                                 }
    4760                                 width = PyInt_AsLong(v);
    4761                                 if (width < 0) {
    4762                                         flags |= F_LJUST;
    4763                                         width = -width;
    4764                                 }
    4765                                 if (--fmtcnt >= 0)
    4766                                         c = *fmt++;
    4767                         }
    4768                         else if (c >= 0 && isdigit(c)) {
    4769                                 width = c - '0';
    4770                                 while (--fmtcnt >= 0) {
    4771                                         c = Py_CHARMASK(*fmt++);
    4772                                         if (!isdigit(c))
    4773                                                 break;
    4774                                         if ((width*10) / 10 != width) {
    4775                                                 PyErr_SetString(
    4776                                                         PyExc_ValueError,
    4777                                                         "width too big");
    4778                                                 goto error;
    4779                                         }
    4780                                         width = width*10 + (c - '0');
    4781                                 }
    4782                         }
    4783                         if (c == '.') {
    4784                                 prec = 0;
    4785                                 if (--fmtcnt >= 0)
    4786                                         c = *fmt++;
    4787                                 if (c == '*') {
    4788                                         v = getnextarg(args, arglen, &argidx);
    4789                                         if (v == NULL)
    4790                                                 goto error;
    4791                                         if (!PyInt_Check(v)) {
    4792                                                 PyErr_SetString(
    4793                                                         PyExc_TypeError,
    4794                                                         "* wants int");
    4795                                                 goto error;
    4796                                         }
    4797                                         prec = PyInt_AsLong(v);
    4798                                         if (prec < 0)
    4799                                                 prec = 0;
    4800                                         if (--fmtcnt >= 0)
    4801                                                 c = *fmt++;
    4802                                 }
    4803                                 else if (c >= 0 && isdigit(c)) {
    4804                                         prec = c - '0';
    4805                                         while (--fmtcnt >= 0) {
    4806                                                 c = Py_CHARMASK(*fmt++);
    4807                                                 if (!isdigit(c))
    4808                                                         break;
    4809                                                 if ((prec*10) / 10 != prec) {
    4810                                                         PyErr_SetString(
    4811                                                             PyExc_ValueError,
    4812                                                             "prec too big");
    4813                                                         goto error;
    4814                                                 }
    4815                                                 prec = prec*10 + (c - '0');
    4816                                         }
    4817                                 }
    4818                         } /* prec */
    4819                         if (fmtcnt >= 0) {
    4820                                 if (c == 'h' || c == 'l' || c == 'L') {
    4821                                         if (--fmtcnt >= 0)
    4822                                                 c = *fmt++;
    4823                                 }
    4824                         }
    4825                         if (fmtcnt < 0) {
    4826                                 PyErr_SetString(PyExc_ValueError,
    4827                                                 "incomplete format");
    4828                                 goto error;
    4829                         }
    4830                         if (c != '%') {
    4831                                 v = getnextarg(args, arglen, &argidx);
    4832                                 if (v == NULL)
    4833                                         goto error;
    4834                         }
    4835                         sign = 0;
    4836                         fill = ' ';
    4837                         switch (c) {
    4838                         case '%':
    4839                                 pbuf = "%";
    4840                                 len = 1;
    4841                                 break;
    4842                         case 's':
     4295            fmt++;
     4296            if (*fmt == '(') {
     4297                char *keystart;
     4298                Py_ssize_t keylen;
     4299                PyObject *key;
     4300                int pcount = 1;
     4301
     4302                if (dict == NULL) {
     4303                    PyErr_SetString(PyExc_TypeError,
     4304                             "format requires a mapping");
     4305                    goto error;
     4306                }
     4307                ++fmt;
     4308                --fmtcnt;
     4309                keystart = fmt;
     4310                /* Skip over balanced parentheses */
     4311                while (pcount > 0 && --fmtcnt >= 0) {
     4312                    if (*fmt == ')')
     4313                        --pcount;
     4314                    else if (*fmt == '(')
     4315                        ++pcount;
     4316                    fmt++;
     4317                }
     4318                keylen = fmt - keystart - 1;
     4319                if (fmtcnt < 0 || pcount > 0) {
     4320                    PyErr_SetString(PyExc_ValueError,
     4321                               "incomplete format key");
     4322                    goto error;
     4323                }
     4324                key = PyString_FromStringAndSize(keystart,
     4325                                                 keylen);
     4326                if (key == NULL)
     4327                    goto error;
     4328                if (args_owned) {
     4329                    Py_DECREF(args);
     4330                    args_owned = 0;
     4331                }
     4332                args = PyObject_GetItem(dict, key);
     4333                Py_DECREF(key);
     4334                if (args == NULL) {
     4335                    goto error;
     4336                }
     4337                args_owned = 1;
     4338                arglen = -1;
     4339                argidx = -2;
     4340            }
     4341            while (--fmtcnt >= 0) {
     4342                switch (c = *fmt++) {
     4343                case '-': flags |= F_LJUST; continue;
     4344                case '+': flags |= F_SIGN; continue;
     4345                case ' ': flags |= F_BLANK; continue;
     4346                case '#': flags |= F_ALT; continue;
     4347                case '0': flags |= F_ZERO; continue;
     4348                }
     4349                break;
     4350            }
     4351            if (c == '*') {
     4352                v = getnextarg(args, arglen, &argidx);
     4353                if (v == NULL)
     4354                    goto error;
     4355                if (!PyInt_Check(v)) {
     4356                    PyErr_SetString(PyExc_TypeError,
     4357                                    "* wants int");
     4358                    goto error;
     4359                }
     4360                width = PyInt_AsSsize_t(v);
     4361                if (width == -1 && PyErr_Occurred())
     4362                    goto error;
     4363                if (width < 0) {
     4364                    flags |= F_LJUST;
     4365                    width = -width;
     4366                }
     4367                if (--fmtcnt >= 0)
     4368                    c = *fmt++;
     4369            }
     4370            else if (c >= 0 && isdigit(c)) {
     4371                width = c - '0';
     4372                while (--fmtcnt >= 0) {
     4373                    c = Py_CHARMASK(*fmt++);
     4374                    if (!isdigit(c))
     4375                        break;
     4376                    if (width > (PY_SSIZE_T_MAX - ((int)c - '0')) / 10) {
     4377                        PyErr_SetString(
     4378                            PyExc_ValueError,
     4379                            "width too big");
     4380                        goto error;
     4381                    }
     4382                    width = width*10 + (c - '0');
     4383                }
     4384            }
     4385            if (c == '.') {
     4386                prec = 0;
     4387                if (--fmtcnt >= 0)
     4388                    c = *fmt++;
     4389                if (c == '*') {
     4390                    v = getnextarg(args, arglen, &argidx);
     4391                    if (v == NULL)
     4392                        goto error;
     4393                    if (!PyInt_Check(v)) {
     4394                        PyErr_SetString(
     4395                            PyExc_TypeError,
     4396                            "* wants int");
     4397                        goto error;
     4398                    }
     4399                    prec = _PyInt_AsInt(v);
     4400                    if (prec == -1 && PyErr_Occurred())
     4401                        goto error;
     4402                    if (prec < 0)
     4403                        prec = 0;
     4404                    if (--fmtcnt >= 0)
     4405                        c = *fmt++;
     4406                }
     4407                else if (c >= 0 && isdigit(c)) {
     4408                    prec = c - '0';
     4409                    while (--fmtcnt >= 0) {
     4410                        c = Py_CHARMASK(*fmt++);
     4411                        if (!isdigit(c))
     4412                            break;
     4413                        if (prec > (INT_MAX - ((int)c - '0')) / 10) {
     4414                            PyErr_SetString(
     4415                                PyExc_ValueError,
     4416                                "prec too big");
     4417                            goto error;
     4418                        }
     4419                        prec = prec*10 + (c - '0');
     4420                    }
     4421                }
     4422            } /* prec */
     4423            if (fmtcnt >= 0) {
     4424                if (c == 'h' || c == 'l' || c == 'L') {
     4425                    if (--fmtcnt >= 0)
     4426                        c = *fmt++;
     4427                }
     4428            }
     4429            if (fmtcnt < 0) {
     4430                PyErr_SetString(PyExc_ValueError,
     4431                                "incomplete format");
     4432                goto error;
     4433            }
     4434            if (c != '%') {
     4435                v = getnextarg(args, arglen, &argidx);
     4436                if (v == NULL)
     4437                    goto error;
     4438            }
     4439            sign = 0;
     4440            fill = ' ';
     4441            switch (c) {
     4442            case '%':
     4443                pbuf = "%";
     4444                len = 1;
     4445                break;
     4446            case 's':
    48434447#ifdef Py_USING_UNICODE
    4844                                 if (PyUnicode_Check(v)) {
    4845                                         fmt = fmt_start;
    4846                                         argidx = argidx_start;
    4847                                         goto unicode;
    4848                                 }
     4448                if (PyUnicode_Check(v)) {
     4449                    fmt = fmt_start;
     4450                    argidx = argidx_start;
     4451                    goto unicode;
     4452                }
    48494453#endif
    4850                                 temp = _PyObject_Str(v);
     4454                temp = _PyObject_Str(v);
    48514455#ifdef Py_USING_UNICODE
    4852                                 if (temp != NULL && PyUnicode_Check(temp)) {
    4853                                         Py_DECREF(temp);
    4854                                         fmt = fmt_start;
    4855                                         argidx = argidx_start;
    4856                                         goto unicode;
    4857                                 }
     4456                if (temp != NULL && PyUnicode_Check(temp)) {
     4457                    Py_DECREF(temp);
     4458                    fmt = fmt_start;
     4459                    argidx = argidx_start;
     4460                    goto unicode;
     4461                }
    48584462#endif
    4859                                 /* Fall through */
    4860                         case 'r':
    4861                                 if (c == 'r')
    4862                                         temp = PyObject_Repr(v);
    4863                                 if (temp == NULL)
    4864                                         goto error;
    4865                                 if (!PyString_Check(temp)) {
    4866                                         PyErr_SetString(PyExc_TypeError,
    4867                                           "%s argument has non-string str()");
    4868                                         Py_DECREF(temp);
    4869                                         goto error;
    4870                                 }
    4871                                 pbuf = PyString_AS_STRING(temp);
    4872                                 len = PyString_GET_SIZE(temp);
    4873                                 if (prec >= 0 && len > prec)
    4874                                         len = prec;
    4875                                 break;
    4876                         case 'i':
    4877                         case 'd':
    4878                         case 'u':
    4879                         case 'o':
    4880                         case 'x':
    4881                         case 'X':
    4882                                 if (c == 'i')
    4883                                         c = 'd';
    4884                                 isnumok = 0;
    4885                                 if (PyNumber_Check(v)) {
    4886                                         PyObject *iobj=NULL;
    4887 
    4888                                         if (PyInt_Check(v) || (PyLong_Check(v))) {
    4889                                                 iobj = v;
    4890                                                 Py_INCREF(iobj);
    4891                                         }
    4892                                         else {
    4893                                                 iobj = PyNumber_Int(v);
    4894                                                 if (iobj==NULL) iobj = PyNumber_Long(v);
    4895                                         }
    4896                                         if (iobj!=NULL) {
    4897                                                 if (PyInt_Check(iobj)) {
    4898                                                         isnumok = 1;
    4899                                                         pbuf = formatbuf;
    4900                                                         len = formatint(pbuf,
    4901                                                                         sizeof(formatbuf),
    4902                                                                         flags, prec, c, iobj);
    4903                                                         Py_DECREF(iobj);
    4904                                                         if (len < 0)
    4905                                                                 goto error;
    4906                                                         sign = 1;
    4907                                                 }
    4908                                                 else if (PyLong_Check(iobj)) {
    4909                                                         int ilen;
    4910                                                        
    4911                                                         isnumok = 1;
    4912                                                         temp = _PyString_FormatLong(iobj, flags,
    4913                                                                 prec, c, &pbuf, &ilen);
    4914                                                         Py_DECREF(iobj);
    4915                                                         len = ilen;
    4916                                                         if (!temp)
    4917                                                                 goto error;
    4918                                                         sign = 1;
    4919                                                 }
    4920                                                 else {
    4921                                                         Py_DECREF(iobj);
    4922                                                 }
    4923                                         }
    4924                                 }
    4925                                 if (!isnumok) {
    4926                                         PyErr_Format(PyExc_TypeError,
    4927                                             "%%%c format: a number is required, "
    4928                                             "not %.200s", c, Py_TYPE(v)->tp_name);
    4929                                         goto error;
    4930                                 }
    4931                                 if (flags & F_ZERO)
    4932                                         fill = '0';
    4933                                 break;
    4934                         case 'e':
    4935                         case 'E':
    4936                         case 'f':
    4937                         case 'F':
    4938                         case 'g':
    4939                         case 'G':
    4940                                 if (c == 'F')
    4941                                         c = 'f';
    4942                                 pbuf = formatbuf;
    4943                                 len = formatfloat(pbuf, sizeof(formatbuf),
    4944                                                   flags, prec, c, v);
    4945                                 if (len < 0)
    4946                                         goto error;
    4947                                 sign = 1;
    4948                                 if (flags & F_ZERO)
    4949                                         fill = '0';
    4950                                 break;
    4951                         case 'c':
     4463                /* Fall through */
     4464            case 'r':
     4465                if (c == 'r')
     4466                    temp = PyObject_Repr(v);
     4467                if (temp == NULL)
     4468                    goto error;
     4469                if (!PyString_Check(temp)) {
     4470                    PyErr_SetString(PyExc_TypeError,
     4471                      "%s argument has non-string str()");
     4472                    Py_DECREF(temp);
     4473                    goto error;
     4474                }
     4475                pbuf = PyString_AS_STRING(temp);
     4476                len = PyString_GET_SIZE(temp);
     4477                if (prec >= 0 && len > prec)
     4478                    len = prec;
     4479                break;
     4480            case 'i':
     4481            case 'd':
     4482            case 'u':
     4483            case 'o':
     4484            case 'x':
     4485            case 'X':
     4486                if (c == 'i')
     4487                    c = 'd';
     4488                isnumok = 0;
     4489                if (PyNumber_Check(v)) {
     4490                    PyObject *iobj=NULL;
     4491
     4492                    if (PyInt_Check(v) || (PyLong_Check(v))) {
     4493                        iobj = v;
     4494                        Py_INCREF(iobj);
     4495                    }
     4496                    else {
     4497                        iobj = PyNumber_Int(v);
     4498                        if (iobj==NULL) {
     4499                            PyErr_Clear();
     4500                            iobj = PyNumber_Long(v);
     4501                        }
     4502                    }
     4503                    if (iobj!=NULL) {
     4504                        if (PyInt_Check(iobj)) {
     4505                            isnumok = 1;
     4506                            pbuf = formatbuf;
     4507                            len = formatint(pbuf,
     4508                                            sizeof(formatbuf),
     4509                                            flags, prec, c, iobj);
     4510                            Py_DECREF(iobj);
     4511                            if (len < 0)
     4512                                goto error;
     4513                            sign = 1;
     4514                        }
     4515                        else if (PyLong_Check(iobj)) {
     4516                            int ilen;
     4517
     4518                            isnumok = 1;
     4519                            temp = _PyString_FormatLong(iobj, flags,
     4520                                prec, c, &pbuf, &ilen);
     4521                            Py_DECREF(iobj);
     4522                            len = ilen;
     4523                            if (!temp)
     4524                                goto error;
     4525                            sign = 1;
     4526                        }
     4527                        else {
     4528                            Py_DECREF(iobj);
     4529                        }
     4530                    }
     4531                }
     4532                if (!isnumok) {
     4533                    PyErr_Format(PyExc_TypeError,
     4534                        "%%%c format: a number is required, "
     4535                        "not %.200s", c, Py_TYPE(v)->tp_name);
     4536                    goto error;
     4537                }
     4538                if (flags & F_ZERO)
     4539                    fill = '0';
     4540                break;
     4541            case 'e':
     4542            case 'E':
     4543            case 'f':
     4544            case 'F':
     4545            case 'g':
     4546            case 'G':
     4547                temp = formatfloat(v, flags, prec, c);
     4548                if (temp == NULL)
     4549                    goto error;
     4550                pbuf = PyString_AS_STRING(temp);
     4551                len = PyString_GET_SIZE(temp);
     4552                sign = 1;
     4553                if (flags & F_ZERO)
     4554                    fill = '0';
     4555                break;
     4556            case 'c':
    49524557#ifdef Py_USING_UNICODE
    4953                                 if (PyUnicode_Check(v)) {
    4954                                         fmt = fmt_start;
    4955                                         argidx = argidx_start;
    4956                                         goto unicode;
    4957                                 }
     4558                if (PyUnicode_Check(v)) {
     4559                    fmt = fmt_start;
     4560                    argidx = argidx_start;
     4561                    goto unicode;
     4562                }
    49584563#endif
    4959                                 pbuf = formatbuf;
    4960                                 len = formatchar(pbuf, sizeof(formatbuf), v);
    4961                                 if (len < 0)
    4962                                         goto error;
    4963                                 break;
    4964                         default:
    4965                                 PyErr_Format(PyExc_ValueError,
    4966                                   "unsupported format character '%c' (0x%x) "
    4967                                   "at index %zd",
    4968                                   c, c,
    4969                                   (Py_ssize_t)(fmt - 1 -
    4970                                                PyString_AsString(format)));
    4971                                 goto error;
    4972                         }
    4973                         if (sign) {
    4974                                 if (*pbuf == '-' || *pbuf == '+') {
    4975                                         sign = *pbuf++;
    4976                                         len--;
    4977                                 }
    4978                                 else if (flags & F_SIGN)
    4979                                         sign = '+';
    4980                                 else if (flags & F_BLANK)
    4981                                         sign = ' ';
    4982                                 else
    4983                                         sign = 0;
    4984                         }
    4985                         if (width < len)
    4986                                 width = len;
    4987                         if (rescnt - (sign != 0) < width) {
    4988                                 reslen -= rescnt;
    4989                                 rescnt = width + fmtcnt + 100;
    4990                                 reslen += rescnt;
    4991                                 if (reslen < 0) {
    4992                                         Py_DECREF(result);
    4993                                         Py_XDECREF(temp);
    4994                                         return PyErr_NoMemory();
    4995                                 }
    4996                                 if (_PyString_Resize(&result, reslen) < 0) {
    4997                                         Py_XDECREF(temp);
    4998                                         return NULL;
    4999                                 }
    5000                                 res = PyString_AS_STRING(result)
    5001                                         + reslen - rescnt;
    5002                         }
    5003                         if (sign) {
    5004                                 if (fill != ' ')
    5005                                         *res++ = sign;
    5006                                 rescnt--;
    5007                                 if (width > len)
    5008                                         width--;
    5009                         }
    5010                         if ((flags & F_ALT) && (c == 'x' || c == 'X')) {
    5011                                 assert(pbuf[0] == '0');
    5012                                 assert(pbuf[1] == c);
    5013                                 if (fill != ' ') {
    5014                                         *res++ = *pbuf++;
    5015                                         *res++ = *pbuf++;
    5016                                 }
    5017                                 rescnt -= 2;
    5018                                 width -= 2;
    5019                                 if (width < 0)
    5020                                         width = 0;
    5021                                 len -= 2;
    5022                         }
    5023                         if (width > len && !(flags & F_LJUST)) {
    5024                                 do {
    5025                                         --rescnt;
    5026                                         *res++ = fill;
    5027                                 } while (--width > len);
    5028                         }
    5029                         if (fill == ' ') {
    5030                                 if (sign)
    5031                                         *res++ = sign;
    5032                                 if ((flags & F_ALT) &&
    5033                                     (c == 'x' || c == 'X')) {
    5034                                         assert(pbuf[0] == '0');
    5035                                         assert(pbuf[1] == c);
    5036                                         *res++ = *pbuf++;
    5037                                         *res++ = *pbuf++;
    5038                                 }
    5039                         }
    5040                         Py_MEMCPY(res, pbuf, len);
    5041                         res += len;
    5042                         rescnt -= len;
    5043                         while (--width >= len) {
    5044                                 --rescnt;
    5045                                 *res++ = ' ';
    5046                         }
    5047                         if (dict && (argidx < arglen) && c != '%') {
    5048                                 PyErr_SetString(PyExc_TypeError,
    5049                                            "not all arguments converted during string formatting");
    5050                                 Py_XDECREF(temp);
    5051                                 goto error;
    5052                         }
    5053                         Py_XDECREF(temp);
    5054                 } /* '%' */
    5055         } /* until end */
    5056         if (argidx < arglen && !dict) {
    5057                 PyErr_SetString(PyExc_TypeError,
    5058                                 "not all arguments converted during string formatting");
    5059                 goto error;
    5060         }
    5061         if (args_owned) {
    5062                 Py_DECREF(args);
    5063         }
    5064         _PyString_Resize(&result, reslen - rescnt);
    5065         return result;
     4564                pbuf = formatbuf;
     4565                len = formatchar(pbuf, sizeof(formatbuf), v);
     4566                if (len < 0)
     4567                    goto error;
     4568                break;
     4569            default:
     4570                PyErr_Format(PyExc_ValueError,
     4571                  "unsupported format character '%c' (0x%x) "
     4572                  "at index %zd",
     4573                  c, c,
     4574                  (Py_ssize_t)(fmt - 1 -
     4575                               PyString_AsString(format)));
     4576                goto error;
     4577            }
     4578            if (sign) {
     4579                if (*pbuf == '-' || *pbuf == '+') {
     4580                    sign = *pbuf++;
     4581                    len--;
     4582                }
     4583                else if (flags & F_SIGN)
     4584                    sign = '+';
     4585                else if (flags & F_BLANK)
     4586                    sign = ' ';
     4587                else
     4588                    sign = 0;
     4589            }
     4590            if (width < len)
     4591                width = len;
     4592            if (rescnt - (sign != 0) < width) {
     4593                reslen -= rescnt;
     4594                rescnt = width + fmtcnt + 100;
     4595                reslen += rescnt;
     4596                if (reslen < 0) {
     4597                    Py_DECREF(result);
     4598                    Py_XDECREF(temp);
     4599                    return PyErr_NoMemory();
     4600                }
     4601                if (_PyString_Resize(&result, reslen)) {
     4602                    Py_XDECREF(temp);
     4603                    return NULL;
     4604                }
     4605                res = PyString_AS_STRING(result)
     4606                    + reslen - rescnt;
     4607            }
     4608            if (sign) {
     4609                if (fill != ' ')
     4610                    *res++ = sign;
     4611                rescnt--;
     4612                if (width > len)
     4613                    width--;
     4614            }
     4615            if ((flags & F_ALT) && (c == 'x' || c == 'X')) {
     4616                assert(pbuf[0] == '0');
     4617                assert(pbuf[1] == c);
     4618                if (fill != ' ') {
     4619                    *res++ = *pbuf++;
     4620                    *res++ = *pbuf++;
     4621                }
     4622                rescnt -= 2;
     4623                width -= 2;
     4624                if (width < 0)
     4625                    width = 0;
     4626                len -= 2;
     4627            }
     4628            if (width > len && !(flags & F_LJUST)) {
     4629                do {
     4630                    --rescnt;
     4631                    *res++ = fill;
     4632                } while (--width > len);
     4633            }
     4634            if (fill == ' ') {
     4635                if (sign)
     4636                    *res++ = sign;
     4637                if ((flags & F_ALT) &&
     4638                    (c == 'x' || c == 'X')) {
     4639                    assert(pbuf[0] == '0');
     4640                    assert(pbuf[1] == c);
     4641                    *res++ = *pbuf++;
     4642                    *res++ = *pbuf++;
     4643                }
     4644            }
     4645            Py_MEMCPY(res, pbuf, len);
     4646            res += len;
     4647            rescnt -= len;
     4648            while (--width >= len) {
     4649                --rescnt;
     4650                *res++ = ' ';
     4651            }
     4652            if (dict && (argidx < arglen) && c != '%') {
     4653                PyErr_SetString(PyExc_TypeError,
     4654                           "not all arguments converted during string formatting");
     4655                Py_XDECREF(temp);
     4656                goto error;
     4657            }
     4658            Py_XDECREF(temp);
     4659        } /* '%' */
     4660    } /* until end */
     4661    if (argidx < arglen && !dict) {
     4662        PyErr_SetString(PyExc_TypeError,
     4663                        "not all arguments converted during string formatting");
     4664        goto error;
     4665    }
     4666    if (args_owned) {
     4667        Py_DECREF(args);
     4668    }
     4669    if (_PyString_Resize(&result, reslen - rescnt))
     4670        return NULL;
     4671    return result;
    50664672
    50674673#ifdef Py_USING_UNICODE
    50684674 unicode:
    5069         if (args_owned) {
    5070                 Py_DECREF(args);
    5071                 args_owned = 0;
    5072         }
    5073         /* Fiddle args right (remove the first argidx arguments) */
    5074         if (PyTuple_Check(orig_args) && argidx > 0) {
    5075                 PyObject *v;
    5076                 Py_ssize_t n = PyTuple_GET_SIZE(orig_args) - argidx;
    5077                 v = PyTuple_New(n);
    5078                 if (v == NULL)
    5079                         goto error;
    5080                 while (--n >= 0) {
    5081                         PyObject *w = PyTuple_GET_ITEM(orig_args, n + argidx);
    5082                         Py_INCREF(w);
    5083                         PyTuple_SET_ITEM(v, n, w);
    5084                 }
    5085                 args = v;
    5086         } else {
    5087                 Py_INCREF(orig_args);
    5088                 args = orig_args;
    5089         }
    5090         args_owned = 1;
    5091         /* Take what we have of the result and let the Unicode formatting
    5092            function format the rest of the input. */
    5093         rescnt = res - PyString_AS_STRING(result);
    5094         if (_PyString_Resize(&result, rescnt))
    5095                 goto error;
    5096         fmtcnt = PyString_GET_SIZE(format) - \
    5097                 (fmt - PyString_AS_STRING(format));
    5098         format = PyUnicode_Decode(fmt, fmtcnt, NULL, NULL);
    5099         if (format == NULL)
    5100                 goto error;
    5101         v = PyUnicode_Format(format, args);
    5102         Py_DECREF(format);
    5103         if (v == NULL)
    5104                 goto error;
    5105         /* Paste what we have (result) to what the Unicode formatting
    5106            function returned (v) and return the result (or error) */
    5107         w = PyUnicode_Concat(result, v);
    5108         Py_DECREF(result);
    5109         Py_DECREF(v);
    5110         Py_DECREF(args);
    5111         return w;
     4675    if (args_owned) {
     4676        Py_DECREF(args);
     4677        args_owned = 0;
     4678    }
     4679    /* Fiddle args right (remove the first argidx arguments) */
     4680    if (PyTuple_Check(orig_args) && argidx > 0) {
     4681        PyObject *v;
     4682        Py_ssize_t n = PyTuple_GET_SIZE(orig_args) - argidx;
     4683        v = PyTuple_New(n);
     4684        if (v == NULL)
     4685            goto error;
     4686        while (--n >= 0) {
     4687            PyObject *w = PyTuple_GET_ITEM(orig_args, n + argidx);
     4688            Py_INCREF(w);
     4689            PyTuple_SET_ITEM(v, n, w);
     4690        }
     4691        args = v;
     4692    } else {
     4693        Py_INCREF(orig_args);
     4694        args = orig_args;
     4695    }
     4696    args_owned = 1;
     4697    /* Take what we have of the result and let the Unicode formatting
     4698       function format the rest of the input. */
     4699    rescnt = res - PyString_AS_STRING(result);
     4700    if (_PyString_Resize(&result, rescnt))
     4701        goto error;
     4702    fmtcnt = PyString_GET_SIZE(format) - \
     4703            (fmt - PyString_AS_STRING(format));
     4704    format = PyUnicode_Decode(fmt, fmtcnt, NULL, NULL);
     4705    if (format == NULL)
     4706        goto error;
     4707    v = PyUnicode_Format(format, args);
     4708    Py_DECREF(format);
     4709    if (v == NULL)
     4710        goto error;
     4711    /* Paste what we have (result) to what the Unicode formatting
     4712       function returned (v) and return the result (or error) */
     4713    w = PyUnicode_Concat(result, v);
     4714    Py_DECREF(result);
     4715    Py_DECREF(v);
     4716    Py_DECREF(args);
     4717    return w;
    51124718#endif /* Py_USING_UNICODE */
    51134719
    51144720 error:
    5115         Py_DECREF(result);
    5116         if (args_owned) {
    5117                 Py_DECREF(args);
    5118         }
    5119         return NULL;
     4721    Py_DECREF(result);
     4722    if (args_owned) {
     4723        Py_DECREF(args);
     4724    }
     4725    return NULL;
    51204726}
    51214727
     
    51234729PyString_InternInPlace(PyObject **p)
    51244730{
    5125         register PyStringObject *s = (PyStringObject *)(*p);
    5126         PyObject *t;
    5127         if (s == NULL || !PyString_Check(s))
    5128                 Py_FatalError("PyString_InternInPlace: strings only please!");
    5129         /* If it's a string subclass, we don't really know what putting
    5130            it in the interned dict might do. */
    5131         if (!PyString_CheckExact(s))
    5132                 return;
    5133         if (PyString_CHECK_INTERNED(s))
    5134                 return;
    5135         if (interned == NULL) {
    5136                 interned = PyDict_New();
    5137                 if (interned == NULL) {
    5138                         PyErr_Clear(); /* Don't leave an exception */
    5139                         return;
    5140                 }
    5141         }
    5142         t = PyDict_GetItem(interned, (PyObject *)s);
    5143         if (t) {
    5144                 Py_INCREF(t);
    5145                 Py_DECREF(*p);
    5146                 *p = t;
    5147                 return;
    5148         }
    5149 
    5150         if (PyDict_SetItem(interned, (PyObject *)s, (PyObject *)s) < 0) {
    5151                 PyErr_Clear();
    5152                 return;
    5153         }
    5154         /* The two references in interned are not counted by refcnt.
    5155            The string deallocator will take care of this */
    5156         Py_REFCNT(s) -= 2;
    5157         PyString_CHECK_INTERNED(s) = SSTATE_INTERNED_MORTAL;
     4731    register PyStringObject *s = (PyStringObject *)(*p);
     4732    PyObject *t;
     4733    if (s == NULL || !PyString_Check(s))
     4734        Py_FatalError("PyString_InternInPlace: strings only please!");
     4735    /* If it's a string subclass, we don't really know what putting
     4736       it in the interned dict might do. */
     4737    if (!PyString_CheckExact(s))
     4738        return;
     4739    if (PyString_CHECK_INTERNED(s))
     4740        return;
     4741    if (interned == NULL) {
     4742        interned = PyDict_New();
     4743        if (interned == NULL) {
     4744            PyErr_Clear(); /* Don't leave an exception */
     4745            return;
     4746        }
     4747    }
     4748    t = PyDict_GetItem(interned, (PyObject *)s);
     4749    if (t) {
     4750        Py_INCREF(t);
     4751        Py_DECREF(*p);
     4752        *p = t;
     4753        return;
     4754    }
     4755
     4756    if (PyDict_SetItem(interned, (PyObject *)s, (PyObject *)s) < 0) {
     4757        PyErr_Clear();
     4758        return;
     4759    }
     4760    /* The two references in interned are not counted by refcnt.
     4761       The string deallocator will take care of this */
     4762    Py_REFCNT(s) -= 2;
     4763    PyString_CHECK_INTERNED(s) = SSTATE_INTERNED_MORTAL;
    51584764}
    51594765
     
    51614767PyString_InternImmortal(PyObject **p)
    51624768{
    5163         PyString_InternInPlace(p);
    5164         if (PyString_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
    5165                 PyString_CHECK_INTERNED(*p) = SSTATE_INTERNED_IMMORTAL;
    5166                 Py_INCREF(*p);
    5167         }
     4769    PyString_InternInPlace(p);
     4770    if (PyString_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
     4771        PyString_CHECK_INTERNED(*p) = SSTATE_INTERNED_IMMORTAL;
     4772        Py_INCREF(*p);
     4773    }
    51684774}
    51694775
     
    51724778PyString_InternFromString(const char *cp)
    51734779{
    5174         PyObject *s = PyString_FromString(cp);
    5175         if (s == NULL)
    5176                 return NULL;
    5177         PyString_InternInPlace(&s);
    5178         return s;
     4780    PyObject *s = PyString_FromString(cp);
     4781    if (s == NULL)
     4782        return NULL;
     4783    PyString_InternInPlace(&s);
     4784    return s;
    51794785}
    51804786
     
    51824788PyString_Fini(void)
    51834789{
    5184         int i;
    5185         for (i = 0; i < UCHAR_MAX + 1; i++) {
    5186                 Py_XDECREF(characters[i]);
    5187                 characters[i] = NULL;
    5188         }
    5189         Py_XDECREF(nullstring);
    5190         nullstring = NULL;
     4790    int i;
     4791    for (i = 0; i < UCHAR_MAX + 1; i++)
     4792        Py_CLEAR(characters[i]);
     4793    Py_CLEAR(nullstring);
    51914794}
    51924795
    51934796void _Py_ReleaseInternedStrings(void)
    51944797{
    5195         PyObject *keys;
    5196         PyStringObject *s;
    5197         Py_ssize_t i, n;
    5198         Py_ssize_t immortal_size = 0, mortal_size = 0;
    5199 
    5200         if (interned == NULL || !PyDict_Check(interned))
    5201                 return;
    5202         keys = PyDict_Keys(interned);
    5203         if (keys == NULL || !PyList_Check(keys)) {
    5204                 PyErr_Clear();
    5205                 return;
    5206         }
    5207 
    5208         /* Since _Py_ReleaseInternedStrings() is intended to help a leak
    5209            detector, interned strings are not forcibly deallocated; rather, we
    5210            give them their stolen references back, and then clear and DECREF
    5211            the interned dict. */
    5212 
    5213         n = PyList_GET_SIZE(keys);
    5214         fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
    5215                 n);
    5216         for (i = 0; i < n; i++) {
    5217                 s = (PyStringObject *) PyList_GET_ITEM(keys, i);
    5218                 switch (s->ob_sstate) {
    5219                 case SSTATE_NOT_INTERNED:
    5220                         /* XXX Shouldn't happen */
    5221                         break;
    5222                 case SSTATE_INTERNED_IMMORTAL:
    5223                         Py_REFCNT(s) += 1;
    5224                         immortal_size += Py_SIZE(s);
    5225                         break;
    5226                 case SSTATE_INTERNED_MORTAL:
    5227                         Py_REFCNT(s) += 2;
    5228                         mortal_size += Py_SIZE(s);
    5229                         break;
    5230                 default:
    5231                         Py_FatalError("Inconsistent interned string state.");
    5232                 }
    5233                 s->ob_sstate = SSTATE_NOT_INTERNED;
    5234         }
    5235         fprintf(stderr, "total size of all interned strings: "
    5236                         "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
    5237                         "mortal/immortal\n", mortal_size, immortal_size);
    5238         Py_DECREF(keys);
    5239         PyDict_Clear(interned);
    5240         Py_DECREF(interned);
    5241         interned = NULL;
    5242 }
     4798    PyObject *keys;
     4799    PyStringObject *s;
     4800    Py_ssize_t i, n;
     4801    Py_ssize_t immortal_size = 0, mortal_size = 0;
     4802
     4803    if (interned == NULL || !PyDict_Check(interned))
     4804        return;
     4805    keys = PyDict_Keys(interned);
     4806    if (keys == NULL || !PyList_Check(keys)) {
     4807        PyErr_Clear();
     4808        return;
     4809    }
     4810
     4811    /* Since _Py_ReleaseInternedStrings() is intended to help a leak
     4812       detector, interned strings are not forcibly deallocated; rather, we
     4813       give them their stolen references back, and then clear and DECREF
     4814       the interned dict. */
     4815
     4816    n = PyList_GET_SIZE(keys);
     4817    fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
     4818        n);
     4819    for (i = 0; i < n; i++) {
     4820        s = (PyStringObject *) PyList_GET_ITEM(keys, i);
     4821        switch (s->ob_sstate) {
     4822        case SSTATE_NOT_INTERNED:
     4823            /* XXX Shouldn't happen */
     4824            break;
     4825        case SSTATE_INTERNED_IMMORTAL:
     4826            Py_REFCNT(s) += 1;
     4827            immortal_size += Py_SIZE(s);
     4828            break;
     4829        case SSTATE_INTERNED_MORTAL:
     4830            Py_REFCNT(s) += 2;
     4831            mortal_size += Py_SIZE(s);
     4832            break;
     4833        default:
     4834            Py_FatalError("Inconsistent interned string state.");
     4835        }
     4836        s->ob_sstate = SSTATE_NOT_INTERNED;
     4837    }
     4838    fprintf(stderr, "total size of all interned strings: "
     4839                    "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
     4840                    "mortal/immortal\n", mortal_size, immortal_size);
     4841    Py_DECREF(keys);
     4842    PyDict_Clear(interned);
     4843    Py_CLEAR(interned);
     4844}
Note: See TracChangeset for help on using the changeset viewer.