blob: 536caeff972fa64cd0e6e7102eea053f3a32ef45 [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* String object implementation */
2
Martin v. Löwis5cb69362006-04-14 09:08:42 +00003#define PY_SSIZE_T_CLEAN
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004#include "Python.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00005
Guido van Rossum013142a1994-08-30 08:19:36 +00006#include <ctype.h>
7
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +00008#ifdef COUNT_ALLOCS
9int null_strings, one_strings;
10#endif
11
Guido van Rossumc0b618a1997-05-02 03:12:38 +000012static PyStringObject *characters[UCHAR_MAX + 1];
Guido van Rossumc0b618a1997-05-02 03:12:38 +000013static PyStringObject *nullstring;
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +000014
Guido van Rossum45ec02a2002-08-19 21:43:18 +000015/* This dictionary holds all interned strings. Note that references to
16 strings in this dictionary are *not* counted in the string's ob_refcnt.
17 When the interned string reaches a refcnt of 0 the string deallocation
18 function will delete the reference from this dictionary.
19
Tim Petersae1d0c92006-03-17 03:29:34 +000020 Another way to look at this is that to say that the actual reference
Guido van Rossum45ec02a2002-08-19 21:43:18 +000021 count of a string is: s->ob_refcnt + (s->ob_sstate?2:0)
22*/
23static PyObject *interned;
24
25
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +000026/*
Guido van Rossum3aa3fc42002-04-15 13:48:52 +000027 For both PyString_FromString() and PyString_FromStringAndSize(), the
28 parameter `size' denotes number of characters to allocate, not counting any
Martin v. Löwis1f803f72002-01-16 10:53:24 +000029 null terminating character.
Martin v. Löwisd1327502001-12-02 18:09:41 +000030
Guido van Rossum3aa3fc42002-04-15 13:48:52 +000031 For PyString_FromString(), the parameter `str' points to a null-terminated
Martin v. Löwis1f803f72002-01-16 10:53:24 +000032 string containing exactly `size' bytes.
Martin v. Löwisd1327502001-12-02 18:09:41 +000033
Guido van Rossum3aa3fc42002-04-15 13:48:52 +000034 For PyString_FromStringAndSize(), the parameter the parameter `str' is
35 either NULL or else points to a string containing at least `size' bytes.
36 For PyString_FromStringAndSize(), the string in the `str' parameter does
37 not have to be null-terminated. (Therefore it is safe to construct a
38 substring by calling `PyString_FromStringAndSize(origstring, substrlen)'.)
39 If `str' is NULL then PyString_FromStringAndSize() will allocate `size+1'
40 bytes (setting the last byte to the null terminating character) and you can
41 fill in the data yourself. If `str' is non-NULL then the resulting
42 PyString object must be treated as immutable and you must not fill in nor
43 alter the data yourself, since the strings may be shared.
Martin v. Löwis8f1ea712001-12-03 08:24:52 +000044
Guido van Rossum3aa3fc42002-04-15 13:48:52 +000045 The PyObject member `op->ob_size', which denotes the number of "extra
46 items" in a variable-size object, will contain the number of bytes
47 allocated for string data, not counting the null terminating character. It
48 is therefore equal to the equal to the `size' parameter (for
49 PyString_FromStringAndSize()) or the length of the string in the `str'
50 parameter (for PyString_FromString()).
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +000051*/
Guido van Rossumc0b618a1997-05-02 03:12:38 +000052PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +000053PyString_FromStringAndSize(const char *str, Py_ssize_t size)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000054{
Tim Peters9e897f42001-05-09 07:37:07 +000055 register PyStringObject *op;
Michael W. Hudsonfaa76482005-01-31 17:09:25 +000056 assert(size >= 0);
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +000057 if (size == 0 && (op = nullstring) != NULL) {
58#ifdef COUNT_ALLOCS
59 null_strings++;
60#endif
Guido van Rossumc0b618a1997-05-02 03:12:38 +000061 Py_INCREF(op);
62 return (PyObject *)op;
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +000063 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +000064 if (size == 1 && str != NULL &&
65 (op = characters[*str & UCHAR_MAX]) != NULL)
66 {
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +000067#ifdef COUNT_ALLOCS
68 one_strings++;
69#endif
Guido van Rossumc0b618a1997-05-02 03:12:38 +000070 Py_INCREF(op);
71 return (PyObject *)op;
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +000072 }
Guido van Rossumb18618d2000-05-03 23:44:39 +000073
Guido van Rossume3a8e7e2002-08-19 19:26:42 +000074 /* Inline PyObject_NewVar */
Tim Peterse7c05322004-06-27 17:24:49 +000075 op = (PyStringObject *)PyObject_MALLOC(sizeof(PyStringObject) + size);
Guido van Rossum2a9096b1990-10-21 22:15:08 +000076 if (op == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +000077 return PyErr_NoMemory();
Guido van Rossumb18618d2000-05-03 23:44:39 +000078 PyObject_INIT_VAR(op, &PyString_Type, size);
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +000079 op->ob_shash = -1;
Guido van Rossum45ec02a2002-08-19 21:43:18 +000080 op->ob_sstate = SSTATE_NOT_INTERNED;
Guido van Rossum2a9096b1990-10-21 22:15:08 +000081 if (str != NULL)
82 memcpy(op->ob_sval, str, size);
83 op->ob_sval[size] = '\0';
Tim Peters8deda702002-03-30 10:06:07 +000084 /* share short strings */
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +000085 if (size == 0) {
Tim Peters9e897f42001-05-09 07:37:07 +000086 PyObject *t = (PyObject *)op;
87 PyString_InternInPlace(&t);
Tim Peters4862ab72001-05-09 08:43:21 +000088 op = (PyStringObject *)t;
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +000089 nullstring = op;
Guido van Rossumc0b618a1997-05-02 03:12:38 +000090 Py_INCREF(op);
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +000091 } else if (size == 1 && str != NULL) {
Tim Peters9e897f42001-05-09 07:37:07 +000092 PyObject *t = (PyObject *)op;
93 PyString_InternInPlace(&t);
Tim Peters4862ab72001-05-09 08:43:21 +000094 op = (PyStringObject *)t;
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +000095 characters[*str & UCHAR_MAX] = op;
Guido van Rossumc0b618a1997-05-02 03:12:38 +000096 Py_INCREF(op);
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +000097 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +000098 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000099}
100
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000101PyObject *
Fred Drakeba096332000-07-09 07:04:36 +0000102PyString_FromString(const char *str)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000103{
Tim Peters62de65b2001-12-06 20:29:32 +0000104 register size_t size;
Tim Peters9e897f42001-05-09 07:37:07 +0000105 register PyStringObject *op;
Tim Peters62de65b2001-12-06 20:29:32 +0000106
107 assert(str != NULL);
108 size = strlen(str);
Martin v. Löwis8ce358f2006-04-13 07:22:51 +0000109 if (size > PY_SSIZE_T_MAX) {
Marc-André Lemburgf28dd832000-06-30 10:29:57 +0000110 PyErr_SetString(PyExc_OverflowError,
111 "string is too long for a Python string");
112 return NULL;
113 }
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +0000114 if (size == 0 && (op = nullstring) != NULL) {
115#ifdef COUNT_ALLOCS
116 null_strings++;
117#endif
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000118 Py_INCREF(op);
119 return (PyObject *)op;
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +0000120 }
121 if (size == 1 && (op = characters[*str & UCHAR_MAX]) != NULL) {
122#ifdef COUNT_ALLOCS
123 one_strings++;
124#endif
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000125 Py_INCREF(op);
126 return (PyObject *)op;
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +0000127 }
Guido van Rossumb18618d2000-05-03 23:44:39 +0000128
Guido van Rossume3a8e7e2002-08-19 19:26:42 +0000129 /* Inline PyObject_NewVar */
Tim Peterse7c05322004-06-27 17:24:49 +0000130 op = (PyStringObject *)PyObject_MALLOC(sizeof(PyStringObject) + size);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000131 if (op == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000132 return PyErr_NoMemory();
Guido van Rossumb18618d2000-05-03 23:44:39 +0000133 PyObject_INIT_VAR(op, &PyString_Type, size);
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +0000134 op->ob_shash = -1;
Guido van Rossum45ec02a2002-08-19 21:43:18 +0000135 op->ob_sstate = SSTATE_NOT_INTERNED;
Guido van Rossum169192e2001-12-10 15:45:54 +0000136 memcpy(op->ob_sval, str, size+1);
Tim Peters8deda702002-03-30 10:06:07 +0000137 /* share short strings */
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +0000138 if (size == 0) {
Tim Peters9e897f42001-05-09 07:37:07 +0000139 PyObject *t = (PyObject *)op;
140 PyString_InternInPlace(&t);
Tim Peters4862ab72001-05-09 08:43:21 +0000141 op = (PyStringObject *)t;
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +0000142 nullstring = op;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000143 Py_INCREF(op);
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +0000144 } else if (size == 1) {
Tim Peters9e897f42001-05-09 07:37:07 +0000145 PyObject *t = (PyObject *)op;
146 PyString_InternInPlace(&t);
Tim Peters4862ab72001-05-09 08:43:21 +0000147 op = (PyStringObject *)t;
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +0000148 characters[*str & UCHAR_MAX] = op;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000149 Py_INCREF(op);
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +0000150 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000151 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000152}
153
Barry Warsawdadace02001-08-24 18:32:06 +0000154PyObject *
155PyString_FromFormatV(const char *format, va_list vargs)
156{
Tim Petersc15c4f12001-10-02 21:32:07 +0000157 va_list count;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000158 Py_ssize_t n = 0;
Barry Warsawdadace02001-08-24 18:32:06 +0000159 const char* f;
160 char *s;
161 PyObject* string;
162
Tim Petersc15c4f12001-10-02 21:32:07 +0000163#ifdef VA_LIST_IS_ARRAY
164 memcpy(count, vargs, sizeof(va_list));
165#else
Martin v. Löwis75d2d942002-07-28 10:23:27 +0000166#ifdef __va_copy
167 __va_copy(count, vargs);
168#else
Tim Petersc15c4f12001-10-02 21:32:07 +0000169 count = vargs;
170#endif
Martin v. Löwis75d2d942002-07-28 10:23:27 +0000171#endif
Barry Warsawdadace02001-08-24 18:32:06 +0000172 /* step 1: figure out how large a buffer we need */
173 for (f = format; *f; f++) {
174 if (*f == '%') {
175 const char* p = f;
176 while (*++f && *f != '%' && !isalpha(Py_CHARMASK(*f)))
177 ;
178
Tim Peters8931ff12006-05-13 23:28:20 +0000179 /* skip the 'l' or 'z' in {%ld, %zd, %lu, %zu} since
180 * they don't affect the amount of space we reserve.
181 */
182 if ((*f == 'l' || *f == 'z') &&
183 (f[1] == 'd' || f[1] == 'u'))
Tim Petersae1d0c92006-03-17 03:29:34 +0000184 ++f;
Guido van Rossum3aa3fc42002-04-15 13:48:52 +0000185
Barry Warsawdadace02001-08-24 18:32:06 +0000186 switch (*f) {
187 case 'c':
188 (void)va_arg(count, int);
189 /* fall through... */
190 case '%':
191 n++;
192 break;
Tim Peters8931ff12006-05-13 23:28:20 +0000193 case 'd': case 'u': case 'i': case 'x':
Barry Warsawdadace02001-08-24 18:32:06 +0000194 (void) va_arg(count, int);
Tim Peters9161c8b2001-12-03 01:55:38 +0000195 /* 20 bytes is enough to hold a 64-bit
196 integer. Decimal takes the most space.
197 This isn't enough for octal. */
Barry Warsawdadace02001-08-24 18:32:06 +0000198 n += 20;
199 break;
200 case 's':
201 s = va_arg(count, char*);
202 n += strlen(s);
203 break;
204 case 'p':
205 (void) va_arg(count, int);
206 /* maximum 64-bit pointer representation:
207 * 0xffffffffffffffff
208 * so 19 characters is enough.
Tim Peters9161c8b2001-12-03 01:55:38 +0000209 * XXX I count 18 -- what's the extra for?
Barry Warsawdadace02001-08-24 18:32:06 +0000210 */
211 n += 19;
212 break;
213 default:
214 /* if we stumble upon an unknown
215 formatting code, copy the rest of
216 the format string to the output
217 string. (we cannot just skip the
218 code, since there's no way to know
Guido van Rossum3aa3fc42002-04-15 13:48:52 +0000219 what's in the argument list) */
Barry Warsawdadace02001-08-24 18:32:06 +0000220 n += strlen(p);
221 goto expand;
222 }
223 } else
224 n++;
225 }
226 expand:
227 /* step 2: fill the buffer */
Tim Peters9161c8b2001-12-03 01:55:38 +0000228 /* Since we've analyzed how much space we need for the worst case,
229 use sprintf directly instead of the slower PyOS_snprintf. */
Barry Warsawdadace02001-08-24 18:32:06 +0000230 string = PyString_FromStringAndSize(NULL, n);
231 if (!string)
232 return NULL;
Guido van Rossum3aa3fc42002-04-15 13:48:52 +0000233
Barry Warsawdadace02001-08-24 18:32:06 +0000234 s = PyString_AsString(string);
235
236 for (f = format; *f; f++) {
237 if (*f == '%') {
238 const char* p = f++;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000239 Py_ssize_t i;
240 int longflag = 0;
Martin v. Löwis2c95cc62006-02-16 06:54:25 +0000241 int size_tflag = 0;
Barry Warsawdadace02001-08-24 18:32:06 +0000242 /* parse the width.precision part (we're only
243 interested in the precision value, if any) */
244 n = 0;
245 while (isdigit(Py_CHARMASK(*f)))
246 n = (n*10) + *f++ - '0';
247 if (*f == '.') {
248 f++;
249 n = 0;
250 while (isdigit(Py_CHARMASK(*f)))
251 n = (n*10) + *f++ - '0';
252 }
253 while (*f && *f != '%' && !isalpha(Py_CHARMASK(*f)))
254 f++;
Tim Peters8931ff12006-05-13 23:28:20 +0000255 /* handle the long flag, but only for %ld and %lu.
256 others can be added when necessary. */
257 if (*f == 'l' && (f[1] == 'd' || f[1] == 'u')) {
Barry Warsawdadace02001-08-24 18:32:06 +0000258 longflag = 1;
259 ++f;
260 }
Martin v. Löwis2c95cc62006-02-16 06:54:25 +0000261 /* handle the size_t flag. */
Tim Peters8931ff12006-05-13 23:28:20 +0000262 if (*f == 'z' && (f[1] == 'd' || f[1] == 'u')) {
Martin v. Löwis2c95cc62006-02-16 06:54:25 +0000263 size_tflag = 1;
264 ++f;
265 }
Guido van Rossum3aa3fc42002-04-15 13:48:52 +0000266
Barry Warsawdadace02001-08-24 18:32:06 +0000267 switch (*f) {
268 case 'c':
269 *s++ = va_arg(vargs, int);
270 break;
271 case 'd':
272 if (longflag)
273 sprintf(s, "%ld", va_arg(vargs, long));
Tim Petersae1d0c92006-03-17 03:29:34 +0000274 else if (size_tflag)
Martin v. Löwis822f34a2006-05-13 13:34:04 +0000275 sprintf(s, "%" PY_FORMAT_SIZE_T "d",
276 va_arg(vargs, Py_ssize_t));
Barry Warsawdadace02001-08-24 18:32:06 +0000277 else
278 sprintf(s, "%d", va_arg(vargs, int));
279 s += strlen(s);
280 break;
Tim Peters8931ff12006-05-13 23:28:20 +0000281 case 'u':
282 if (longflag)
283 sprintf(s, "%lu",
284 va_arg(vargs, unsigned long));
285 else if (size_tflag)
286 sprintf(s, "%" PY_FORMAT_SIZE_T "u",
287 va_arg(vargs, size_t));
288 else
289 sprintf(s, "%u",
290 va_arg(vargs, unsigned int));
291 s += strlen(s);
292 break;
Barry Warsawdadace02001-08-24 18:32:06 +0000293 case 'i':
294 sprintf(s, "%i", va_arg(vargs, int));
295 s += strlen(s);
296 break;
297 case 'x':
298 sprintf(s, "%x", va_arg(vargs, int));
299 s += strlen(s);
300 break;
301 case 's':
302 p = va_arg(vargs, char*);
303 i = strlen(p);
304 if (n > 0 && i > n)
305 i = n;
306 memcpy(s, p, i);
307 s += i;
308 break;
309 case 'p':
310 sprintf(s, "%p", va_arg(vargs, void*));
Tim Peters6af5bbb2001-08-25 03:02:28 +0000311 /* %p is ill-defined: ensure leading 0x. */
312 if (s[1] == 'X')
313 s[1] = 'x';
314 else if (s[1] != 'x') {
315 memmove(s+2, s, strlen(s)+1);
316 s[0] = '0';
317 s[1] = 'x';
318 }
Barry Warsawdadace02001-08-24 18:32:06 +0000319 s += strlen(s);
320 break;
321 case '%':
322 *s++ = '%';
323 break;
324 default:
325 strcpy(s, p);
326 s += strlen(s);
327 goto end;
328 }
329 } else
330 *s++ = *f;
331 }
Guido van Rossum3aa3fc42002-04-15 13:48:52 +0000332
Barry Warsawdadace02001-08-24 18:32:06 +0000333 end:
Barry Warsaw7c47beb2001-08-27 03:11:09 +0000334 _PyString_Resize(&string, s - PyString_AS_STRING(string));
Barry Warsawdadace02001-08-24 18:32:06 +0000335 return string;
336}
Guido van Rossum3aa3fc42002-04-15 13:48:52 +0000337
Barry Warsawdadace02001-08-24 18:32:06 +0000338PyObject *
Guido van Rossum3aa3fc42002-04-15 13:48:52 +0000339PyString_FromFormat(const char *format, ...)
Barry Warsawdadace02001-08-24 18:32:06 +0000340{
Barry Warsaw7c47beb2001-08-27 03:11:09 +0000341 PyObject* ret;
Barry Warsawdadace02001-08-24 18:32:06 +0000342 va_list vargs;
343
344#ifdef HAVE_STDARG_PROTOTYPES
345 va_start(vargs, format);
346#else
347 va_start(vargs);
348#endif
Barry Warsaw7c47beb2001-08-27 03:11:09 +0000349 ret = PyString_FromFormatV(format, vargs);
350 va_end(vargs);
351 return ret;
Barry Warsawdadace02001-08-24 18:32:06 +0000352}
353
354
Marc-André Lemburg63f3d172000-07-06 11:29:01 +0000355PyObject *PyString_Decode(const char *s,
Martin v. Löwis18e16552006-02-15 17:27:45 +0000356 Py_ssize_t size,
Marc-André Lemburg63f3d172000-07-06 11:29:01 +0000357 const char *encoding,
358 const char *errors)
359{
Marc-André Lemburg2d920412001-05-15 12:00:02 +0000360 PyObject *v, *str;
361
362 str = PyString_FromStringAndSize(s, size);
363 if (str == NULL)
364 return NULL;
365 v = PyString_AsDecodedString(str, encoding, errors);
366 Py_DECREF(str);
367 return v;
368}
369
370PyObject *PyString_AsDecodedObject(PyObject *str,
371 const char *encoding,
372 const char *errors)
373{
374 PyObject *v;
375
376 if (!PyString_Check(str)) {
377 PyErr_BadArgument();
378 goto onError;
379 }
Tim Petersb3d8d1f2001-04-28 05:38:26 +0000380
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000381 if (encoding == NULL) {
382#ifdef Py_USING_UNICODE
Marc-André Lemburg63f3d172000-07-06 11:29:01 +0000383 encoding = PyUnicode_GetDefaultEncoding();
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000384#else
385 PyErr_SetString(PyExc_ValueError, "no encoding specified");
386 goto onError;
387#endif
388 }
Marc-André Lemburg63f3d172000-07-06 11:29:01 +0000389
390 /* Decode via the codec registry */
Marc-André Lemburg2d920412001-05-15 12:00:02 +0000391 v = PyCodec_Decode(str, encoding, errors);
392 if (v == NULL)
Marc-André Lemburg63f3d172000-07-06 11:29:01 +0000393 goto onError;
Marc-André Lemburg2d920412001-05-15 12:00:02 +0000394
395 return v;
Tim Petersb3d8d1f2001-04-28 05:38:26 +0000396
Marc-André Lemburg63f3d172000-07-06 11:29:01 +0000397 onError:
Marc-André Lemburg2d920412001-05-15 12:00:02 +0000398 return NULL;
399}
400
401PyObject *PyString_AsDecodedString(PyObject *str,
402 const char *encoding,
403 const char *errors)
404{
405 PyObject *v;
406
407 v = PyString_AsDecodedObject(str, encoding, errors);
408 if (v == NULL)
409 goto onError;
410
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000411#ifdef Py_USING_UNICODE
Marc-André Lemburg2d920412001-05-15 12:00:02 +0000412 /* Convert Unicode to a string using the default encoding */
413 if (PyUnicode_Check(v)) {
414 PyObject *temp = v;
415 v = PyUnicode_AsEncodedString(v, NULL, NULL);
416 Py_DECREF(temp);
417 if (v == NULL)
418 goto onError;
419 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000420#endif
Marc-André Lemburg2d920412001-05-15 12:00:02 +0000421 if (!PyString_Check(v)) {
422 PyErr_Format(PyExc_TypeError,
423 "decoder did not return a string object (type=%.400s)",
424 v->ob_type->tp_name);
425 Py_DECREF(v);
426 goto onError;
427 }
428
429 return v;
430
431 onError:
Marc-André Lemburg63f3d172000-07-06 11:29:01 +0000432 return NULL;
433}
434
435PyObject *PyString_Encode(const char *s,
Martin v. Löwis18e16552006-02-15 17:27:45 +0000436 Py_ssize_t size,
Marc-André Lemburg63f3d172000-07-06 11:29:01 +0000437 const char *encoding,
438 const char *errors)
439{
440 PyObject *v, *str;
Tim Petersb3d8d1f2001-04-28 05:38:26 +0000441
Marc-André Lemburg63f3d172000-07-06 11:29:01 +0000442 str = PyString_FromStringAndSize(s, size);
443 if (str == NULL)
444 return NULL;
445 v = PyString_AsEncodedString(str, encoding, errors);
446 Py_DECREF(str);
447 return v;
448}
449
Marc-André Lemburg2d920412001-05-15 12:00:02 +0000450PyObject *PyString_AsEncodedObject(PyObject *str,
Marc-André Lemburg63f3d172000-07-06 11:29:01 +0000451 const char *encoding,
452 const char *errors)
453{
454 PyObject *v;
Tim Petersb3d8d1f2001-04-28 05:38:26 +0000455
Marc-André Lemburg63f3d172000-07-06 11:29:01 +0000456 if (!PyString_Check(str)) {
457 PyErr_BadArgument();
458 goto onError;
459 }
460
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000461 if (encoding == NULL) {
462#ifdef Py_USING_UNICODE
Marc-André Lemburg63f3d172000-07-06 11:29:01 +0000463 encoding = PyUnicode_GetDefaultEncoding();
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000464#else
465 PyErr_SetString(PyExc_ValueError, "no encoding specified");
466 goto onError;
467#endif
468 }
Marc-André Lemburg63f3d172000-07-06 11:29:01 +0000469
470 /* Encode via the codec registry */
471 v = PyCodec_Encode(str, encoding, errors);
472 if (v == NULL)
473 goto onError;
Marc-André Lemburg2d920412001-05-15 12:00:02 +0000474
475 return v;
476
477 onError:
478 return NULL;
479}
480
481PyObject *PyString_AsEncodedString(PyObject *str,
482 const char *encoding,
483 const char *errors)
484{
485 PyObject *v;
486
Marc-André Lemburg8c2133d2001-06-12 13:14:10 +0000487 v = PyString_AsEncodedObject(str, encoding, errors);
Marc-André Lemburg2d920412001-05-15 12:00:02 +0000488 if (v == NULL)
489 goto onError;
490
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000491#ifdef Py_USING_UNICODE
Marc-André Lemburg63f3d172000-07-06 11:29:01 +0000492 /* Convert Unicode to a string using the default encoding */
493 if (PyUnicode_Check(v)) {
494 PyObject *temp = v;
495 v = PyUnicode_AsEncodedString(v, NULL, NULL);
496 Py_DECREF(temp);
497 if (v == NULL)
498 goto onError;
499 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000500#endif
Marc-André Lemburg63f3d172000-07-06 11:29:01 +0000501 if (!PyString_Check(v)) {
502 PyErr_Format(PyExc_TypeError,
503 "encoder did not return a string object (type=%.400s)",
504 v->ob_type->tp_name);
505 Py_DECREF(v);
506 goto onError;
507 }
Marc-André Lemburg2d920412001-05-15 12:00:02 +0000508
Marc-André Lemburg63f3d172000-07-06 11:29:01 +0000509 return v;
Tim Petersb3d8d1f2001-04-28 05:38:26 +0000510
Marc-André Lemburg63f3d172000-07-06 11:29:01 +0000511 onError:
512 return NULL;
513}
514
Guido van Rossum234f9421993-06-17 12:35:49 +0000515static void
Fred Drakeba096332000-07-09 07:04:36 +0000516string_dealloc(PyObject *op)
Guido van Rossum719f5fa1992-03-27 17:31:02 +0000517{
Guido van Rossum45ec02a2002-08-19 21:43:18 +0000518 switch (PyString_CHECK_INTERNED(op)) {
519 case SSTATE_NOT_INTERNED:
520 break;
521
522 case SSTATE_INTERNED_MORTAL:
523 /* revive dead object temporarily for DelItem */
524 op->ob_refcnt = 3;
525 if (PyDict_DelItem(interned, op) != 0)
526 Py_FatalError(
527 "deletion of interned string failed");
528 break;
529
530 case SSTATE_INTERNED_IMMORTAL:
531 Py_FatalError("Immortal interned string died.");
532
533 default:
534 Py_FatalError("Inconsistent interned string state.");
535 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000536 op->ob_type->tp_free(op);
Guido van Rossum719f5fa1992-03-27 17:31:02 +0000537}
538
Martin v. Löwis8a8da792002-08-14 07:46:28 +0000539/* Unescape a backslash-escaped string. If unicode is non-zero,
540 the string is a u-literal. If recode_encoding is non-zero,
541 the string is UTF-8 encoded and should be re-encoded in the
542 specified encoding. */
543
544PyObject *PyString_DecodeEscape(const char *s,
Martin v. Löwis18e16552006-02-15 17:27:45 +0000545 Py_ssize_t len,
Martin v. Löwis8a8da792002-08-14 07:46:28 +0000546 const char *errors,
Martin v. Löwis18e16552006-02-15 17:27:45 +0000547 Py_ssize_t unicode,
Martin v. Löwis8a8da792002-08-14 07:46:28 +0000548 const char *recode_encoding)
549{
550 int c;
551 char *p, *buf;
552 const char *end;
553 PyObject *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000554 Py_ssize_t newlen = recode_encoding ? 4*len:len;
Walter Dörwald8709a422002-09-03 13:53:40 +0000555 v = PyString_FromStringAndSize((char *)NULL, newlen);
Martin v. Löwis8a8da792002-08-14 07:46:28 +0000556 if (v == NULL)
557 return NULL;
558 p = buf = PyString_AsString(v);
559 end = s + len;
560 while (s < end) {
561 if (*s != '\\') {
Martin v. Löwis24128532002-09-09 06:17:05 +0000562 non_esc:
Martin v. Löwis8a8da792002-08-14 07:46:28 +0000563#ifdef Py_USING_UNICODE
564 if (recode_encoding && (*s & 0x80)) {
565 PyObject *u, *w;
566 char *r;
567 const char* t;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000568 Py_ssize_t rn;
Martin v. Löwis8a8da792002-08-14 07:46:28 +0000569 t = s;
570 /* Decode non-ASCII bytes as UTF-8. */
571 while (t < end && (*t & 0x80)) t++;
572 u = PyUnicode_DecodeUTF8(s, t - s, errors);
573 if(!u) goto failed;
574
575 /* Recode them in target encoding. */
576 w = PyUnicode_AsEncodedString(
577 u, recode_encoding, errors);
578 Py_DECREF(u);
579 if (!w) goto failed;
580
581 /* Append bytes to output buffer. */
Neal Norwitz2aa9a5d2006-03-20 01:53:23 +0000582 assert(PyString_Check(w));
583 r = PyString_AS_STRING(w);
584 rn = PyString_GET_SIZE(w);
Martin v. Löwis8a8da792002-08-14 07:46:28 +0000585 memcpy(p, r, rn);
586 p += rn;
587 Py_DECREF(w);
588 s = t;
589 } else {
590 *p++ = *s++;
591 }
592#else
593 *p++ = *s++;
594#endif
595 continue;
596 }
597 s++;
Martin v. Löwiseb3f00a2002-08-14 08:22:50 +0000598 if (s==end) {
599 PyErr_SetString(PyExc_ValueError,
600 "Trailing \\ in string");
601 goto failed;
602 }
Martin v. Löwis8a8da792002-08-14 07:46:28 +0000603 switch (*s++) {
604 /* XXX This assumes ASCII! */
605 case '\n': break;
606 case '\\': *p++ = '\\'; break;
607 case '\'': *p++ = '\''; break;
608 case '\"': *p++ = '\"'; break;
609 case 'b': *p++ = '\b'; break;
610 case 'f': *p++ = '\014'; break; /* FF */
611 case 't': *p++ = '\t'; break;
612 case 'n': *p++ = '\n'; break;
613 case 'r': *p++ = '\r'; break;
614 case 'v': *p++ = '\013'; break; /* VT */
615 case 'a': *p++ = '\007'; break; /* BEL, not classic C */
616 case '0': case '1': case '2': case '3':
617 case '4': case '5': case '6': case '7':
618 c = s[-1] - '0';
619 if ('0' <= *s && *s <= '7') {
620 c = (c<<3) + *s++ - '0';
621 if ('0' <= *s && *s <= '7')
622 c = (c<<3) + *s++ - '0';
623 }
624 *p++ = c;
625 break;
626 case 'x':
Tim Petersae1d0c92006-03-17 03:29:34 +0000627 if (isxdigit(Py_CHARMASK(s[0]))
Martin v. Löwis8a8da792002-08-14 07:46:28 +0000628 && isxdigit(Py_CHARMASK(s[1]))) {
629 unsigned int x = 0;
630 c = Py_CHARMASK(*s);
631 s++;
632 if (isdigit(c))
633 x = c - '0';
634 else if (islower(c))
635 x = 10 + c - 'a';
636 else
637 x = 10 + c - 'A';
638 x = x << 4;
639 c = Py_CHARMASK(*s);
640 s++;
641 if (isdigit(c))
642 x += c - '0';
643 else if (islower(c))
644 x += 10 + c - 'a';
645 else
646 x += 10 + c - 'A';
647 *p++ = x;
648 break;
649 }
650 if (!errors || strcmp(errors, "strict") == 0) {
Tim Petersae1d0c92006-03-17 03:29:34 +0000651 PyErr_SetString(PyExc_ValueError,
Martin v. Löwis8a8da792002-08-14 07:46:28 +0000652 "invalid \\x escape");
Martin v. Löwiseb3f00a2002-08-14 08:22:50 +0000653 goto failed;
Martin v. Löwis8a8da792002-08-14 07:46:28 +0000654 }
655 if (strcmp(errors, "replace") == 0) {
656 *p++ = '?';
657 } else if (strcmp(errors, "ignore") == 0)
658 /* do nothing */;
659 else {
660 PyErr_Format(PyExc_ValueError,
661 "decoding error; "
662 "unknown error handling code: %.400s",
663 errors);
Martin v. Löwiseb3f00a2002-08-14 08:22:50 +0000664 goto failed;
Martin v. Löwis8a8da792002-08-14 07:46:28 +0000665 }
666#ifndef Py_USING_UNICODE
667 case 'u':
668 case 'U':
669 case 'N':
670 if (unicode) {
Neal Norwitzb898d9f2002-08-16 23:20:39 +0000671 PyErr_SetString(PyExc_ValueError,
Martin v. Löwis8a8da792002-08-14 07:46:28 +0000672 "Unicode escapes not legal "
673 "when Unicode disabled");
Martin v. Löwiseb3f00a2002-08-14 08:22:50 +0000674 goto failed;
Martin v. Löwis8a8da792002-08-14 07:46:28 +0000675 }
676#endif
677 default:
678 *p++ = '\\';
Martin v. Löwis24128532002-09-09 06:17:05 +0000679 s--;
680 goto non_esc; /* an arbitry number of unescaped
681 UTF-8 bytes may follow. */
Martin v. Löwis8a8da792002-08-14 07:46:28 +0000682 }
683 }
Walter Dörwald8709a422002-09-03 13:53:40 +0000684 if (p-buf < newlen)
Martin v. Löwis18e16552006-02-15 17:27:45 +0000685 _PyString_Resize(&v, p - buf);
Martin v. Löwis8a8da792002-08-14 07:46:28 +0000686 return v;
687 failed:
688 Py_DECREF(v);
689 return NULL;
690}
691
Martin v. Löwis18e16552006-02-15 17:27:45 +0000692static Py_ssize_t
Marc-André Lemburgd1ba4432000-09-19 21:04:18 +0000693string_getsize(register PyObject *op)
694{
695 char *s;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000696 Py_ssize_t len;
Marc-André Lemburgd1ba4432000-09-19 21:04:18 +0000697 if (PyString_AsStringAndSize(op, &s, &len))
698 return -1;
699 return len;
700}
701
702static /*const*/ char *
703string_getbuffer(register PyObject *op)
704{
705 char *s;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000706 Py_ssize_t len;
Marc-André Lemburgd1ba4432000-09-19 21:04:18 +0000707 if (PyString_AsStringAndSize(op, &s, &len))
708 return NULL;
709 return s;
710}
711
Martin v. Löwis18e16552006-02-15 17:27:45 +0000712Py_ssize_t
Fred Drakeba096332000-07-09 07:04:36 +0000713PyString_Size(register PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000714{
Marc-André Lemburgd1ba4432000-09-19 21:04:18 +0000715 if (!PyString_Check(op))
716 return string_getsize(op);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000717 return ((PyStringObject *)op) -> ob_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000718}
719
720/*const*/ char *
Fred Drakeba096332000-07-09 07:04:36 +0000721PyString_AsString(register PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000722{
Marc-André Lemburgd1ba4432000-09-19 21:04:18 +0000723 if (!PyString_Check(op))
724 return string_getbuffer(op);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000725 return ((PyStringObject *)op) -> ob_sval;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000726}
727
Marc-André Lemburgd1ba4432000-09-19 21:04:18 +0000728int
729PyString_AsStringAndSize(register PyObject *obj,
730 register char **s,
Martin v. Löwis18e16552006-02-15 17:27:45 +0000731 register Py_ssize_t *len)
Marc-André Lemburgd1ba4432000-09-19 21:04:18 +0000732{
733 if (s == NULL) {
734 PyErr_BadInternalCall();
735 return -1;
736 }
737
738 if (!PyString_Check(obj)) {
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000739#ifdef Py_USING_UNICODE
Marc-André Lemburgd1ba4432000-09-19 21:04:18 +0000740 if (PyUnicode_Check(obj)) {
741 obj = _PyUnicode_AsDefaultEncodedString(obj, NULL);
742 if (obj == NULL)
743 return -1;
744 }
Guido van Rossum3aa3fc42002-04-15 13:48:52 +0000745 else
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000746#endif
747 {
Marc-André Lemburgd1ba4432000-09-19 21:04:18 +0000748 PyErr_Format(PyExc_TypeError,
749 "expected string or Unicode object, "
750 "%.200s found", obj->ob_type->tp_name);
751 return -1;
752 }
753 }
754
755 *s = PyString_AS_STRING(obj);
756 if (len != NULL)
757 *len = PyString_GET_SIZE(obj);
Skip Montanaro429433b2006-04-18 00:35:43 +0000758 else if (strlen(*s) != (size_t)PyString_GET_SIZE(obj)) {
Marc-André Lemburgd1ba4432000-09-19 21:04:18 +0000759 PyErr_SetString(PyExc_TypeError,
760 "expected string without null bytes");
761 return -1;
762 }
763 return 0;
764}
765
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000766/* Methods */
767
Guido van Rossumbcaa31c1991-06-07 22:58:57 +0000768static int
Fred Drakeba096332000-07-09 07:04:36 +0000769string_print(PyStringObject *op, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000770{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000771 Py_ssize_t i;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000772 char c;
Guido van Rossum444fc7c1993-10-26 15:25:16 +0000773 int quote;
Tim Petersc9933152001-10-16 20:18:24 +0000774
Guido van Rossumbcaa31c1991-06-07 22:58:57 +0000775 /* XXX Ought to check for interrupts when writing long strings */
Tim Petersc9933152001-10-16 20:18:24 +0000776 if (! PyString_CheckExact(op)) {
777 int ret;
778 /* A str subclass may have its own __str__ method. */
779 op = (PyStringObject *) PyObject_Str((PyObject *)op);
780 if (op == NULL)
781 return -1;
782 ret = string_print(op, fp, flags);
783 Py_DECREF(op);
784 return ret;
785 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000786 if (flags & Py_PRINT_RAW) {
Martin v. Löwis79acb9e2002-12-06 12:48:53 +0000787#ifdef __VMS
788 if (op->ob_size) fwrite(op->ob_sval, (int) op->ob_size, 1, fp);
789#else
790 fwrite(op->ob_sval, 1, (int) op->ob_size, fp);
791#endif
Guido van Rossumbcaa31c1991-06-07 22:58:57 +0000792 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000793 }
Guido van Rossum444fc7c1993-10-26 15:25:16 +0000794
Thomas Wouters7e474022000-07-16 12:04:32 +0000795 /* figure out which quote to use; single is preferred */
Guido van Rossum444fc7c1993-10-26 15:25:16 +0000796 quote = '\'';
Guido van Rossum3aa3fc42002-04-15 13:48:52 +0000797 if (memchr(op->ob_sval, '\'', op->ob_size) &&
798 !memchr(op->ob_sval, '"', op->ob_size))
Guido van Rossum444fc7c1993-10-26 15:25:16 +0000799 quote = '"';
800
801 fputc(quote, fp);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000802 for (i = 0; i < op->ob_size; i++) {
803 c = op->ob_sval[i];
Guido van Rossum444fc7c1993-10-26 15:25:16 +0000804 if (c == quote || c == '\\')
Martin v. Löwisa5f09072002-10-11 05:37:59 +0000805 fprintf(fp, "\\%c", c);
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +0000806 else if (c == '\t')
Martin v. Löwisa5f09072002-10-11 05:37:59 +0000807 fprintf(fp, "\\t");
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +0000808 else if (c == '\n')
Martin v. Löwisa5f09072002-10-11 05:37:59 +0000809 fprintf(fp, "\\n");
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +0000810 else if (c == '\r')
Martin v. Löwisa5f09072002-10-11 05:37:59 +0000811 fprintf(fp, "\\r");
812 else if (c < ' ' || c >= 0x7f)
813 fprintf(fp, "\\x%02x", c & 0xff);
Martin v. Löwisfed24052002-10-07 13:55:50 +0000814 else
Martin v. Löwisa5f09072002-10-11 05:37:59 +0000815 fputc(c, fp);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000816 }
Guido van Rossum444fc7c1993-10-26 15:25:16 +0000817 fputc(quote, fp);
Guido van Rossumbcaa31c1991-06-07 22:58:57 +0000818 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000819}
820
Martin v. Löwis8a8da792002-08-14 07:46:28 +0000821PyObject *
822PyString_Repr(PyObject *obj, int smartquotes)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000823{
Martin v. Löwis8a8da792002-08-14 07:46:28 +0000824 register PyStringObject* op = (PyStringObject*) obj;
Tim Peterse7c05322004-06-27 17:24:49 +0000825 size_t newsize = 2 + 4 * op->ob_size;
Marc-André Lemburgf28dd832000-06-30 10:29:57 +0000826 PyObject *v;
Martin v. Löwis8ce358f2006-04-13 07:22:51 +0000827 if (newsize > PY_SSIZE_T_MAX) {
Marc-André Lemburgf28dd832000-06-30 10:29:57 +0000828 PyErr_SetString(PyExc_OverflowError,
829 "string is too large to make repr");
830 }
831 v = PyString_FromStringAndSize((char *)NULL, newsize);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000832 if (v == NULL) {
Guido van Rossumbcaa31c1991-06-07 22:58:57 +0000833 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000834 }
835 else {
Martin v. Löwis18e16552006-02-15 17:27:45 +0000836 register Py_ssize_t i;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000837 register char c;
838 register char *p;
Guido van Rossum444fc7c1993-10-26 15:25:16 +0000839 int quote;
840
Thomas Wouters7e474022000-07-16 12:04:32 +0000841 /* figure out which quote to use; single is preferred */
Guido van Rossum444fc7c1993-10-26 15:25:16 +0000842 quote = '\'';
Tim Petersae1d0c92006-03-17 03:29:34 +0000843 if (smartquotes &&
Martin v. Löwis8a8da792002-08-14 07:46:28 +0000844 memchr(op->ob_sval, '\'', op->ob_size) &&
Guido van Rossum3aa3fc42002-04-15 13:48:52 +0000845 !memchr(op->ob_sval, '"', op->ob_size))
Guido van Rossum444fc7c1993-10-26 15:25:16 +0000846 quote = '"';
847
Tim Peters9161c8b2001-12-03 01:55:38 +0000848 p = PyString_AS_STRING(v);
Guido van Rossum444fc7c1993-10-26 15:25:16 +0000849 *p++ = quote;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000850 for (i = 0; i < op->ob_size; i++) {
Tim Peters9161c8b2001-12-03 01:55:38 +0000851 /* There's at least enough room for a hex escape
852 and a closing quote. */
853 assert(newsize - (p - PyString_AS_STRING(v)) >= 5);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000854 c = op->ob_sval[i];
Guido van Rossum444fc7c1993-10-26 15:25:16 +0000855 if (c == quote || c == '\\')
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000856 *p++ = '\\', *p++ = c;
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +0000857 else if (c == '\t')
858 *p++ = '\\', *p++ = 't';
859 else if (c == '\n')
860 *p++ = '\\', *p++ = 'n';
861 else if (c == '\r')
862 *p++ = '\\', *p++ = 'r';
Martin v. Löwisa5f09072002-10-11 05:37:59 +0000863 else if (c < ' ' || c >= 0x7f) {
864 /* For performance, we don't want to call
865 PyOS_snprintf here (extra layers of
866 function call). */
867 sprintf(p, "\\x%02x", c & 0xff);
868 p += 4;
Martin v. Löwisfed24052002-10-07 13:55:50 +0000869 }
Martin v. Löwisa5f09072002-10-11 05:37:59 +0000870 else
871 *p++ = c;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000872 }
Tim Peters9161c8b2001-12-03 01:55:38 +0000873 assert(newsize - (p - PyString_AS_STRING(v)) >= 1);
Guido van Rossum444fc7c1993-10-26 15:25:16 +0000874 *p++ = quote;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000875 *p = '\0';
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000876 _PyString_Resize(
Thomas Wouters568f1d02006-04-21 13:54:43 +0000877 &v, (p - PyString_AS_STRING(v)));
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000878 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000879 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000880}
881
Guido van Rossum189f1df2001-05-01 16:51:53 +0000882static PyObject *
Martin v. Löwis8a8da792002-08-14 07:46:28 +0000883string_repr(PyObject *op)
884{
885 return PyString_Repr(op, 1);
886}
887
888static PyObject *
Guido van Rossum189f1df2001-05-01 16:51:53 +0000889string_str(PyObject *s)
890{
Tim Petersc9933152001-10-16 20:18:24 +0000891 assert(PyString_Check(s));
892 if (PyString_CheckExact(s)) {
893 Py_INCREF(s);
894 return s;
895 }
896 else {
897 /* Subtype -- return genuine string with the same value. */
898 PyStringObject *t = (PyStringObject *) s;
899 return PyString_FromStringAndSize(t->ob_sval, t->ob_size);
900 }
Guido van Rossum189f1df2001-05-01 16:51:53 +0000901}
902
Martin v. Löwis18e16552006-02-15 17:27:45 +0000903static Py_ssize_t
Fred Drakeba096332000-07-09 07:04:36 +0000904string_length(PyStringObject *a)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000905{
906 return a->ob_size;
907}
908
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000909static PyObject *
Fred Drakeba096332000-07-09 07:04:36 +0000910string_concat(register PyStringObject *a, register PyObject *bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000911{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000912 register size_t size;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000913 register PyStringObject *op;
914 if (!PyString_Check(bb)) {
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000915#ifdef Py_USING_UNICODE
Guido van Rossum4c08d552000-03-10 22:55:18 +0000916 if (PyUnicode_Check(bb))
917 return PyUnicode_Concat((PyObject *)a, bb);
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000918#endif
Tim Petersb3d8d1f2001-04-28 05:38:26 +0000919 PyErr_Format(PyExc_TypeError,
Guido van Rossum5c66a262001-10-22 04:12:44 +0000920 "cannot concatenate 'str' and '%.200s' objects",
Fred Drakeb6a9ada2000-06-01 03:12:13 +0000921 bb->ob_type->tp_name);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000922 return NULL;
923 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000924#define b ((PyStringObject *)bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000925 /* Optimize cases with empty left or right operand */
Tim Peters8fa5dd02001-09-12 02:18:30 +0000926 if ((a->ob_size == 0 || b->ob_size == 0) &&
927 PyString_CheckExact(a) && PyString_CheckExact(b)) {
928 if (a->ob_size == 0) {
929 Py_INCREF(bb);
930 return bb;
931 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000932 Py_INCREF(a);
933 return (PyObject *)a;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000934 }
935 size = a->ob_size + b->ob_size;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000936 /* XXX check overflow */
Guido van Rossume3a8e7e2002-08-19 19:26:42 +0000937 /* Inline PyObject_NewVar */
Tim Peterse7c05322004-06-27 17:24:49 +0000938 op = (PyStringObject *)PyObject_MALLOC(sizeof(PyStringObject) + size);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000939 if (op == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000940 return PyErr_NoMemory();
Guido van Rossumb18618d2000-05-03 23:44:39 +0000941 PyObject_INIT_VAR(op, &PyString_Type, size);
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +0000942 op->ob_shash = -1;
Guido van Rossum45ec02a2002-08-19 21:43:18 +0000943 op->ob_sstate = SSTATE_NOT_INTERNED;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000944 memcpy(op->ob_sval, a->ob_sval, a->ob_size);
945 memcpy(op->ob_sval + a->ob_size, b->ob_sval, b->ob_size);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000946 op->ob_sval[size] = '\0';
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000947 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000948#undef b
949}
950
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000951static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000952string_repeat(register PyStringObject *a, register Py_ssize_t n)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000953{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000954 register Py_ssize_t i;
955 register Py_ssize_t j;
956 register Py_ssize_t size;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000957 register PyStringObject *op;
Tim Peters8f422462000-09-09 06:13:41 +0000958 size_t nbytes;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000959 if (n < 0)
960 n = 0;
Tim Peters8f422462000-09-09 06:13:41 +0000961 /* watch out for overflows: the size can overflow int,
962 * and the # of bytes needed can overflow size_t
963 */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000964 size = a->ob_size * n;
Tim Peters8f422462000-09-09 06:13:41 +0000965 if (n && size / n != a->ob_size) {
966 PyErr_SetString(PyExc_OverflowError,
967 "repeated string is too long");
968 return NULL;
969 }
Tim Peters8fa5dd02001-09-12 02:18:30 +0000970 if (size == a->ob_size && PyString_CheckExact(a)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000971 Py_INCREF(a);
972 return (PyObject *)a;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000973 }
Tim Peterse7c05322004-06-27 17:24:49 +0000974 nbytes = (size_t)size;
975 if (nbytes + sizeof(PyStringObject) <= nbytes) {
Tim Peters8f422462000-09-09 06:13:41 +0000976 PyErr_SetString(PyExc_OverflowError,
977 "repeated string is too long");
978 return NULL;
979 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000980 op = (PyStringObject *)
Neil Schemenauer510492e2002-04-12 03:05:19 +0000981 PyObject_MALLOC(sizeof(PyStringObject) + nbytes);
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000982 if (op == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000983 return PyErr_NoMemory();
Guido van Rossumb18618d2000-05-03 23:44:39 +0000984 PyObject_INIT_VAR(op, &PyString_Type, size);
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +0000985 op->ob_shash = -1;
Guido van Rossum45ec02a2002-08-19 21:43:18 +0000986 op->ob_sstate = SSTATE_NOT_INTERNED;
Raymond Hettinger0a2f8492003-01-06 22:42:41 +0000987 op->ob_sval[size] = '\0';
988 if (a->ob_size == 1 && n > 0) {
989 memset(op->ob_sval, a->ob_sval[0] , n);
990 return (PyObject *) op;
991 }
Raymond Hettinger698258a2003-01-06 10:33:56 +0000992 i = 0;
993 if (i < size) {
Martin v. Löwis18e16552006-02-15 17:27:45 +0000994 memcpy(op->ob_sval, a->ob_sval, a->ob_size);
995 i = a->ob_size;
Raymond Hettinger698258a2003-01-06 10:33:56 +0000996 }
997 while (i < size) {
998 j = (i <= size-i) ? i : size-i;
999 memcpy(op->ob_sval+i, op->ob_sval, j);
1000 i += j;
1001 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001002 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001003}
1004
1005/* String slice a[i:j] consists of characters a[i] ... a[j-1] */
1006
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001007static PyObject *
Tim Petersae1d0c92006-03-17 03:29:34 +00001008string_slice(register PyStringObject *a, register Py_ssize_t i,
Martin v. Löwis18e16552006-02-15 17:27:45 +00001009 register Py_ssize_t j)
Fred Drakeba096332000-07-09 07:04:36 +00001010 /* j -- may be negative! */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001011{
1012 if (i < 0)
1013 i = 0;
1014 if (j < 0)
1015 j = 0; /* Avoid signed/unsigned bug in next line */
1016 if (j > a->ob_size)
1017 j = a->ob_size;
Tim Peters8fa5dd02001-09-12 02:18:30 +00001018 if (i == 0 && j == a->ob_size && PyString_CheckExact(a)) {
1019 /* It's the same as a */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001020 Py_INCREF(a);
1021 return (PyObject *)a;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001022 }
1023 if (j < i)
1024 j = i;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001025 return PyString_FromStringAndSize(a->ob_sval + i, j-i);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001026}
1027
Guido van Rossum9284a572000-03-07 15:53:43 +00001028static int
Fred Drakeba096332000-07-09 07:04:36 +00001029string_contains(PyObject *a, PyObject *el)
Guido van Rossum9284a572000-03-07 15:53:43 +00001030{
Raymond Hettinger7cbf1bc2005-02-20 04:07:08 +00001031 char *s = PyString_AS_STRING(a);
1032 const char *sub = PyString_AS_STRING(el);
1033 char *last;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001034 Py_ssize_t len_sub = PyString_GET_SIZE(el);
Martin v. Löwiseb079f12006-02-16 14:32:27 +00001035 Py_ssize_t shortsub;
Raymond Hettinger7cbf1bc2005-02-20 04:07:08 +00001036 char firstchar, lastchar;
Guido van Rossumbf935fd2002-08-24 06:57:49 +00001037
1038 if (!PyString_CheckExact(el)) {
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001039#ifdef Py_USING_UNICODE
Guido van Rossumbf935fd2002-08-24 06:57:49 +00001040 if (PyUnicode_Check(el))
1041 return PyUnicode_Contains(a, el);
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001042#endif
Guido van Rossumbf935fd2002-08-24 06:57:49 +00001043 if (!PyString_Check(el)) {
1044 PyErr_SetString(PyExc_TypeError,
1045 "'in <string>' requires string as left operand");
1046 return -1;
1047 }
Guido van Rossum9284a572000-03-07 15:53:43 +00001048 }
Barry Warsaw817918c2002-08-06 16:58:21 +00001049
Raymond Hettinger7cbf1bc2005-02-20 04:07:08 +00001050 if (len_sub == 0)
1051 return 1;
Tim Petersae1d0c92006-03-17 03:29:34 +00001052 /* last points to one char beyond the start of the rightmost
Raymond Hettinger7cbf1bc2005-02-20 04:07:08 +00001053 substring. When s<last, there is still room for a possible match
1054 and s[0] through s[len_sub-1] will be in bounds.
1055 shortsub is len_sub minus the last character which is checked
1056 separately just before the memcmp(). That check helps prevent
1057 false starts and saves the setup time for memcmp().
1058 */
1059 firstchar = sub[0];
1060 shortsub = len_sub - 1;
1061 lastchar = sub[shortsub];
1062 last = s + PyString_GET_SIZE(a) - len_sub + 1;
1063 while (s < last) {
Anthony Baxtera6286212006-04-11 07:42:36 +00001064 s = (char *)memchr(s, firstchar, last-s);
Raymond Hettinger7cbf1bc2005-02-20 04:07:08 +00001065 if (s == NULL)
1066 return 0;
1067 assert(s < last);
1068 if (s[shortsub] == lastchar && memcmp(s, sub, shortsub) == 0)
Guido van Rossum9284a572000-03-07 15:53:43 +00001069 return 1;
Raymond Hettinger7cbf1bc2005-02-20 04:07:08 +00001070 s++;
Guido van Rossum9284a572000-03-07 15:53:43 +00001071 }
1072 return 0;
1073}
1074
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001075static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001076string_item(PyStringObject *a, register Py_ssize_t i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001077{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001078 PyObject *v;
Tim Peters5b4d4772001-05-08 22:33:50 +00001079 char *pchar;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001080 if (i < 0 || i >= a->ob_size) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001081 PyErr_SetString(PyExc_IndexError, "string index out of range");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001082 return NULL;
1083 }
Tim Peters5b4d4772001-05-08 22:33:50 +00001084 pchar = a->ob_sval + i;
Tim Peterscf5ad5d2001-05-09 00:24:55 +00001085 v = (PyObject *)characters[*pchar & UCHAR_MAX];
Tim Peters5b4d4772001-05-08 22:33:50 +00001086 if (v == NULL)
1087 v = PyString_FromStringAndSize(pchar, 1);
Tim Petersb4bbcd72001-05-09 00:31:40 +00001088 else {
1089#ifdef COUNT_ALLOCS
1090 one_strings++;
1091#endif
Tim Peterscf5ad5d2001-05-09 00:24:55 +00001092 Py_INCREF(v);
Tim Petersb4bbcd72001-05-09 00:31:40 +00001093 }
Guido van Rossumdaa8bb31991-04-04 10:48:33 +00001094 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001095}
1096
Martin v. Löwiscd353062001-05-24 16:56:35 +00001097static PyObject*
1098string_richcompare(PyStringObject *a, PyStringObject *b, int op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001099{
Martin v. Löwiscd353062001-05-24 16:56:35 +00001100 int c;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001101 Py_ssize_t len_a, len_b;
1102 Py_ssize_t min_len;
Martin v. Löwiscd353062001-05-24 16:56:35 +00001103 PyObject *result;
1104
Guido van Rossum2ed6bf82001-09-27 20:30:07 +00001105 /* Make sure both arguments are strings. */
1106 if (!(PyString_Check(a) && PyString_Check(b))) {
Martin v. Löwiscd353062001-05-24 16:56:35 +00001107 result = Py_NotImplemented;
1108 goto out;
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +00001109 }
Martin v. Löwiscd353062001-05-24 16:56:35 +00001110 if (a == b) {
1111 switch (op) {
1112 case Py_EQ:case Py_LE:case Py_GE:
1113 result = Py_True;
1114 goto out;
1115 case Py_NE:case Py_LT:case Py_GT:
1116 result = Py_False;
1117 goto out;
1118 }
1119 }
1120 if (op == Py_EQ) {
1121 /* Supporting Py_NE here as well does not save
1122 much time, since Py_NE is rarely used. */
1123 if (a->ob_size == b->ob_size
1124 && (a->ob_sval[0] == b->ob_sval[0]
Guido van Rossum3aa3fc42002-04-15 13:48:52 +00001125 && memcmp(a->ob_sval, b->ob_sval,
Martin v. Löwiscd353062001-05-24 16:56:35 +00001126 a->ob_size) == 0)) {
1127 result = Py_True;
1128 } else {
1129 result = Py_False;
1130 }
1131 goto out;
1132 }
1133 len_a = a->ob_size; len_b = b->ob_size;
1134 min_len = (len_a < len_b) ? len_a : len_b;
1135 if (min_len > 0) {
1136 c = Py_CHARMASK(*a->ob_sval) - Py_CHARMASK(*b->ob_sval);
1137 if (c==0)
1138 c = memcmp(a->ob_sval, b->ob_sval, min_len);
1139 }else
1140 c = 0;
1141 if (c == 0)
1142 c = (len_a < len_b) ? -1 : (len_a > len_b) ? 1 : 0;
1143 switch (op) {
1144 case Py_LT: c = c < 0; break;
1145 case Py_LE: c = c <= 0; break;
1146 case Py_EQ: assert(0); break; /* unreachable */
1147 case Py_NE: c = c != 0; break;
1148 case Py_GT: c = c > 0; break;
1149 case Py_GE: c = c >= 0; break;
1150 default:
1151 result = Py_NotImplemented;
1152 goto out;
1153 }
1154 result = c ? Py_True : Py_False;
1155 out:
1156 Py_INCREF(result);
1157 return result;
1158}
1159
1160int
1161_PyString_Eq(PyObject *o1, PyObject *o2)
1162{
1163 PyStringObject *a, *b;
1164 a = (PyStringObject*)o1;
1165 b = (PyStringObject*)o2;
1166 return a->ob_size == b->ob_size
1167 && *a->ob_sval == *b->ob_sval
1168 && memcmp(a->ob_sval, b->ob_sval, a->ob_size) == 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001169}
1170
Guido van Rossum9bfef441993-03-29 10:43:31 +00001171static long
Fred Drakeba096332000-07-09 07:04:36 +00001172string_hash(PyStringObject *a)
Guido van Rossum9bfef441993-03-29 10:43:31 +00001173{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001174 register Py_ssize_t len;
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +00001175 register unsigned char *p;
1176 register long x;
1177
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +00001178 if (a->ob_shash != -1)
1179 return a->ob_shash;
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +00001180 len = a->ob_size;
1181 p = (unsigned char *) a->ob_sval;
1182 x = *p << 7;
Guido van Rossum9bfef441993-03-29 10:43:31 +00001183 while (--len >= 0)
Guido van Rossumeddcb3b1996-09-11 20:22:48 +00001184 x = (1000003*x) ^ *p++;
Guido van Rossum9bfef441993-03-29 10:43:31 +00001185 x ^= a->ob_size;
1186 if (x == -1)
1187 x = -2;
Sjoerd Mullender3bb8a051993-10-22 12:04:32 +00001188 a->ob_shash = x;
Guido van Rossum9bfef441993-03-29 10:43:31 +00001189 return x;
1190}
1191
Guido van Rossum38fff8c2006-03-07 18:50:55 +00001192#define HASINDEX(o) PyType_HasFeature((o)->ob_type, Py_TPFLAGS_HAVE_INDEX)
1193
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00001194static PyObject*
1195string_subscript(PyStringObject* self, PyObject* item)
1196{
Guido van Rossum38fff8c2006-03-07 18:50:55 +00001197 PyNumberMethods *nb = item->ob_type->tp_as_number;
1198 if (nb != NULL && HASINDEX(item) && nb->nb_index != NULL) {
1199 Py_ssize_t i = nb->nb_index(item);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00001200 if (i == -1 && PyErr_Occurred())
1201 return NULL;
1202 if (i < 0)
1203 i += PyString_GET_SIZE(self);
Guido van Rossum38fff8c2006-03-07 18:50:55 +00001204 return string_item(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00001205 }
1206 else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001207 Py_ssize_t start, stop, step, slicelength, cur, i;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00001208 char* source_buf;
1209 char* result_buf;
1210 PyObject* result;
1211
Tim Petersae1d0c92006-03-17 03:29:34 +00001212 if (PySlice_GetIndicesEx((PySliceObject*)item,
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00001213 PyString_GET_SIZE(self),
1214 &start, &stop, &step, &slicelength) < 0) {
1215 return NULL;
1216 }
1217
1218 if (slicelength <= 0) {
1219 return PyString_FromStringAndSize("", 0);
1220 }
1221 else {
1222 source_buf = PyString_AsString((PyObject*)self);
Anthony Baxtera6286212006-04-11 07:42:36 +00001223 result_buf = (char *)PyMem_Malloc(slicelength);
Neal Norwitz95c1e502005-10-20 04:15:52 +00001224 if (result_buf == NULL)
1225 return PyErr_NoMemory();
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00001226
Tim Petersae1d0c92006-03-17 03:29:34 +00001227 for (cur = start, i = 0; i < slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00001228 cur += step, i++) {
1229 result_buf[i] = source_buf[cur];
1230 }
Tim Petersae1d0c92006-03-17 03:29:34 +00001231
1232 result = PyString_FromStringAndSize(result_buf,
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00001233 slicelength);
1234 PyMem_Free(result_buf);
1235 return result;
1236 }
Tim Petersae1d0c92006-03-17 03:29:34 +00001237 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00001238 else {
Tim Petersae1d0c92006-03-17 03:29:34 +00001239 PyErr_SetString(PyExc_TypeError,
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00001240 "string indices must be integers");
1241 return NULL;
1242 }
1243}
1244
Martin v. Löwis18e16552006-02-15 17:27:45 +00001245static Py_ssize_t
1246string_buffer_getreadbuf(PyStringObject *self, Py_ssize_t index, const void **ptr)
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001247{
1248 if ( index != 0 ) {
Guido van Rossum045e6881997-09-08 18:30:11 +00001249 PyErr_SetString(PyExc_SystemError,
Guido van Rossum1db70701998-10-08 02:18:52 +00001250 "accessing non-existent string segment");
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001251 return -1;
1252 }
1253 *ptr = (void *)self->ob_sval;
1254 return self->ob_size;
1255}
1256
Martin v. Löwis18e16552006-02-15 17:27:45 +00001257static Py_ssize_t
1258string_buffer_getwritebuf(PyStringObject *self, Py_ssize_t index, const void **ptr)
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001259{
Guido van Rossum045e6881997-09-08 18:30:11 +00001260 PyErr_SetString(PyExc_TypeError,
Guido van Rossum07d78001998-10-01 15:59:48 +00001261 "Cannot use string as modifiable buffer");
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001262 return -1;
1263}
1264
Martin v. Löwis18e16552006-02-15 17:27:45 +00001265static Py_ssize_t
1266string_buffer_getsegcount(PyStringObject *self, Py_ssize_t *lenp)
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001267{
1268 if ( lenp )
1269 *lenp = self->ob_size;
1270 return 1;
1271}
1272
Martin v. Löwis18e16552006-02-15 17:27:45 +00001273static Py_ssize_t
1274string_buffer_getcharbuf(PyStringObject *self, Py_ssize_t index, const char **ptr)
Guido van Rossum1db70701998-10-08 02:18:52 +00001275{
1276 if ( index != 0 ) {
1277 PyErr_SetString(PyExc_SystemError,
1278 "accessing non-existent string segment");
1279 return -1;
1280 }
1281 *ptr = self->ob_sval;
1282 return self->ob_size;
1283}
1284
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001285static PySequenceMethods string_as_sequence = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001286 (lenfunc)string_length, /*sq_length*/
Guido van Rossum013142a1994-08-30 08:19:36 +00001287 (binaryfunc)string_concat, /*sq_concat*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001288 (ssizeargfunc)string_repeat, /*sq_repeat*/
1289 (ssizeargfunc)string_item, /*sq_item*/
1290 (ssizessizeargfunc)string_slice, /*sq_slice*/
Guido van Rossumf380e661991-06-04 19:36:32 +00001291 0, /*sq_ass_item*/
1292 0, /*sq_ass_slice*/
Guido van Rossum9284a572000-03-07 15:53:43 +00001293 (objobjproc)string_contains /*sq_contains*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001294};
1295
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00001296static PyMappingMethods string_as_mapping = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001297 (lenfunc)string_length,
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00001298 (binaryfunc)string_subscript,
1299 0,
1300};
1301
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001302static PyBufferProcs string_as_buffer = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001303 (readbufferproc)string_buffer_getreadbuf,
1304 (writebufferproc)string_buffer_getwritebuf,
1305 (segcountproc)string_buffer_getsegcount,
1306 (charbufferproc)string_buffer_getcharbuf,
Guido van Rossumfdf95dd1997-05-05 22:15:02 +00001307};
1308
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001309
1310
1311#define LEFTSTRIP 0
1312#define RIGHTSTRIP 1
1313#define BOTHSTRIP 2
1314
Guido van Rossum018b0eb2002-04-13 00:56:08 +00001315/* Arrays indexed by above */
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00001316static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
1317
1318#define STRIPNAME(i) (stripformat[i]+3)
Guido van Rossum018b0eb2002-04-13 00:56:08 +00001319
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +00001320#define SPLIT_APPEND(data, left, right) \
1321 str = PyString_FromStringAndSize((data) + (left), \
1322 (right) - (left)); \
1323 if (str == NULL) \
1324 goto onError; \
1325 if (PyList_Append(list, str)) { \
1326 Py_DECREF(str); \
1327 goto onError; \
1328 } \
1329 else \
1330 Py_DECREF(str);
1331
1332#define SPLIT_INSERT(data, left, right) \
1333 str = PyString_FromStringAndSize((data) + (left), \
1334 (right) - (left)); \
1335 if (str == NULL) \
1336 goto onError; \
1337 if (PyList_Insert(list, 0, str)) { \
1338 Py_DECREF(str); \
1339 goto onError; \
1340 } \
1341 else \
1342 Py_DECREF(str);
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001343
1344static PyObject *
Martin v. Löwis83687c92006-04-13 08:52:56 +00001345split_whitespace(const char *s, Py_ssize_t len, Py_ssize_t maxsplit)
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001346{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001347 Py_ssize_t i, j;
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +00001348 PyObject *str;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001349 PyObject *list = PyList_New(0);
1350
1351 if (list == NULL)
1352 return NULL;
1353
Guido van Rossum4c08d552000-03-10 22:55:18 +00001354 for (i = j = 0; i < len; ) {
1355 while (i < len && isspace(Py_CHARMASK(s[i])))
1356 i++;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001357 j = i;
Guido van Rossum4c08d552000-03-10 22:55:18 +00001358 while (i < len && !isspace(Py_CHARMASK(s[i])))
1359 i++;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001360 if (j < i) {
Guido van Rossum4c08d552000-03-10 22:55:18 +00001361 if (maxsplit-- <= 0)
1362 break;
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +00001363 SPLIT_APPEND(s, j, i);
Guido van Rossum4c08d552000-03-10 22:55:18 +00001364 while (i < len && isspace(Py_CHARMASK(s[i])))
1365 i++;
1366 j = i;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001367 }
1368 }
Guido van Rossum4c08d552000-03-10 22:55:18 +00001369 if (j < len) {
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +00001370 SPLIT_APPEND(s, j, len);
Guido van Rossum4c08d552000-03-10 22:55:18 +00001371 }
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001372 return list;
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +00001373 onError:
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001374 Py_DECREF(list);
1375 return NULL;
1376}
1377
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +00001378static PyObject *
Martin v. Löwis83687c92006-04-13 08:52:56 +00001379split_char(const char *s, Py_ssize_t len, char ch, Py_ssize_t maxcount)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +00001380{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001381 register Py_ssize_t i, j;
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +00001382 PyObject *str;
1383 PyObject *list = PyList_New(0);
1384
1385 if (list == NULL)
1386 return NULL;
1387
1388 for (i = j = 0; i < len; ) {
1389 if (s[i] == ch) {
1390 if (maxcount-- <= 0)
1391 break;
1392 SPLIT_APPEND(s, j, i);
1393 i = j = i + 1;
1394 } else
1395 i++;
1396 }
1397 if (j <= len) {
1398 SPLIT_APPEND(s, j, len);
1399 }
1400 return list;
1401
1402 onError:
1403 Py_DECREF(list);
1404 return NULL;
1405}
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001406
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001407PyDoc_STRVAR(split__doc__,
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001408"S.split([sep [,maxsplit]]) -> list of strings\n\
1409\n\
1410Return a list of the words in the string S, using sep as the\n\
Guido van Rossum4c08d552000-03-10 22:55:18 +00001411delimiter string. If maxsplit is given, at most maxsplit\n\
Raymond Hettingerbc552ce2002-08-05 06:28:21 +00001412splits are done. If sep is not specified or is None, any\n\
1413whitespace string is a separator.");
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001414
1415static PyObject *
Fred Drakeba096332000-07-09 07:04:36 +00001416string_split(PyStringObject *self, PyObject *args)
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001417{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001418 Py_ssize_t len = PyString_GET_SIZE(self), n, i, j;
1419 int err;
Martin v. Löwis9c830762006-04-13 08:37:17 +00001420 Py_ssize_t maxsplit = -1;
Guido van Rossum4c08d552000-03-10 22:55:18 +00001421 const char *s = PyString_AS_STRING(self), *sub;
1422 PyObject *list, *item, *subobj = Py_None;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001423
Martin v. Löwis9c830762006-04-13 08:37:17 +00001424 if (!PyArg_ParseTuple(args, "|On:split", &subobj, &maxsplit))
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001425 return NULL;
Guido van Rossum4c08d552000-03-10 22:55:18 +00001426 if (maxsplit < 0)
Martin v. Löwis8ce358f2006-04-13 07:22:51 +00001427 maxsplit = PY_SSIZE_T_MAX;
Guido van Rossum4c08d552000-03-10 22:55:18 +00001428 if (subobj == Py_None)
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001429 return split_whitespace(s, len, maxsplit);
Guido van Rossum4c08d552000-03-10 22:55:18 +00001430 if (PyString_Check(subobj)) {
1431 sub = PyString_AS_STRING(subobj);
1432 n = PyString_GET_SIZE(subobj);
1433 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001434#ifdef Py_USING_UNICODE
Guido van Rossum4c08d552000-03-10 22:55:18 +00001435 else if (PyUnicode_Check(subobj))
1436 return PyUnicode_Split((PyObject *)self, subobj, maxsplit);
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001437#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +00001438 else if (PyObject_AsCharBuffer(subobj, &sub, &n))
1439 return NULL;
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +00001440
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001441 if (n == 0) {
1442 PyErr_SetString(PyExc_ValueError, "empty separator");
1443 return NULL;
1444 }
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +00001445 else if (n == 1)
1446 return split_char(s, len, sub[0], maxsplit);
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001447
1448 list = PyList_New(0);
1449 if (list == NULL)
1450 return NULL;
1451
1452 i = j = 0;
1453 while (i+n <= len) {
Fred Drake396f6e02000-06-20 15:47:54 +00001454 if (s[i] == sub[0] && memcmp(s+i, sub, n) == 0) {
Guido van Rossum4c08d552000-03-10 22:55:18 +00001455 if (maxsplit-- <= 0)
1456 break;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001457 item = PyString_FromStringAndSize(s+j, i-j);
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001458 if (item == NULL)
1459 goto fail;
1460 err = PyList_Append(list, item);
1461 Py_DECREF(item);
1462 if (err < 0)
1463 goto fail;
1464 i = j = i + n;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001465 }
1466 else
1467 i++;
1468 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00001469 item = PyString_FromStringAndSize(s+j, len-j);
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001470 if (item == NULL)
1471 goto fail;
1472 err = PyList_Append(list, item);
1473 Py_DECREF(item);
1474 if (err < 0)
1475 goto fail;
1476
1477 return list;
1478
1479 fail:
1480 Py_DECREF(list);
1481 return NULL;
1482}
1483
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00001484static PyObject *
Martin v. Löwis83687c92006-04-13 08:52:56 +00001485rsplit_whitespace(const char *s, Py_ssize_t len, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00001486{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001487 Py_ssize_t i, j;
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +00001488 PyObject *str;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00001489 PyObject *list = PyList_New(0);
1490
1491 if (list == NULL)
1492 return NULL;
1493
1494 for (i = j = len - 1; i >= 0; ) {
1495 while (i >= 0 && isspace(Py_CHARMASK(s[i])))
1496 i--;
1497 j = i;
1498 while (i >= 0 && !isspace(Py_CHARMASK(s[i])))
1499 i--;
1500 if (j > i) {
1501 if (maxsplit-- <= 0)
1502 break;
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +00001503 SPLIT_INSERT(s, i + 1, j + 1);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00001504 while (i >= 0 && isspace(Py_CHARMASK(s[i])))
1505 i--;
1506 j = i;
1507 }
1508 }
1509 if (j >= 0) {
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +00001510 SPLIT_INSERT(s, 0, j + 1);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00001511 }
1512 return list;
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +00001513 onError:
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00001514 Py_DECREF(list);
1515 return NULL;
1516}
1517
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +00001518static PyObject *
Martin v. Löwis83687c92006-04-13 08:52:56 +00001519rsplit_char(const char *s, Py_ssize_t len, char ch, Py_ssize_t maxcount)
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +00001520{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001521 register Py_ssize_t i, j;
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +00001522 PyObject *str;
1523 PyObject *list = PyList_New(0);
1524
1525 if (list == NULL)
1526 return NULL;
1527
1528 for (i = j = len - 1; i >= 0; ) {
1529 if (s[i] == ch) {
1530 if (maxcount-- <= 0)
1531 break;
1532 SPLIT_INSERT(s, i + 1, j + 1);
1533 j = i = i - 1;
1534 } else
1535 i--;
1536 }
1537 if (j >= -1) {
1538 SPLIT_INSERT(s, 0, j + 1);
1539 }
1540 return list;
1541
1542 onError:
1543 Py_DECREF(list);
1544 return NULL;
1545}
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00001546
1547PyDoc_STRVAR(rsplit__doc__,
1548"S.rsplit([sep [,maxsplit]]) -> list of strings\n\
1549\n\
1550Return a list of the words in the string S, using sep as the\n\
1551delimiter string, starting at the end of the string and working\n\
1552to the front. If maxsplit is given, at most maxsplit splits are\n\
1553done. If sep is not specified or is None, any whitespace string\n\
1554is a separator.");
1555
1556static PyObject *
1557string_rsplit(PyStringObject *self, PyObject *args)
1558{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001559 Py_ssize_t len = PyString_GET_SIZE(self), n, i, j;
1560 int err;
Martin v. Löwis9c830762006-04-13 08:37:17 +00001561 Py_ssize_t maxsplit = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00001562 const char *s = PyString_AS_STRING(self), *sub;
1563 PyObject *list, *item, *subobj = Py_None;
1564
Martin v. Löwis9c830762006-04-13 08:37:17 +00001565 if (!PyArg_ParseTuple(args, "|On:rsplit", &subobj, &maxsplit))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00001566 return NULL;
1567 if (maxsplit < 0)
Martin v. Löwis8ce358f2006-04-13 07:22:51 +00001568 maxsplit = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00001569 if (subobj == Py_None)
1570 return rsplit_whitespace(s, len, maxsplit);
1571 if (PyString_Check(subobj)) {
1572 sub = PyString_AS_STRING(subobj);
1573 n = PyString_GET_SIZE(subobj);
1574 }
1575#ifdef Py_USING_UNICODE
1576 else if (PyUnicode_Check(subobj))
1577 return PyUnicode_RSplit((PyObject *)self, subobj, maxsplit);
1578#endif
1579 else if (PyObject_AsCharBuffer(subobj, &sub, &n))
1580 return NULL;
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +00001581
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00001582 if (n == 0) {
1583 PyErr_SetString(PyExc_ValueError, "empty separator");
1584 return NULL;
1585 }
Hye-Shik Chang75c00ef2004-01-05 00:29:51 +00001586 else if (n == 1)
1587 return rsplit_char(s, len, sub[0], maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00001588
1589 list = PyList_New(0);
1590 if (list == NULL)
1591 return NULL;
1592
1593 j = len;
1594 i = j - n;
1595 while (i >= 0) {
1596 if (s[i] == sub[0] && memcmp(s+i, sub, n) == 0) {
1597 if (maxsplit-- <= 0)
1598 break;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001599 item = PyString_FromStringAndSize(s+i+n, j-i-n);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00001600 if (item == NULL)
1601 goto fail;
1602 err = PyList_Insert(list, 0, item);
1603 Py_DECREF(item);
1604 if (err < 0)
1605 goto fail;
1606 j = i;
1607 i -= n;
1608 }
1609 else
1610 i--;
1611 }
1612 item = PyString_FromStringAndSize(s, j);
1613 if (item == NULL)
1614 goto fail;
1615 err = PyList_Insert(list, 0, item);
1616 Py_DECREF(item);
1617 if (err < 0)
1618 goto fail;
1619
1620 return list;
1621
1622 fail:
1623 Py_DECREF(list);
1624 return NULL;
1625}
1626
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001627
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001628PyDoc_STRVAR(join__doc__,
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001629"S.join(sequence) -> string\n\
1630\n\
Guido van Rossum4c08d552000-03-10 22:55:18 +00001631Return a string which is the concatenation of the strings in the\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001632sequence. The separator between elements is S.");
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001633
1634static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001635string_join(PyStringObject *self, PyObject *orig)
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001636{
1637 char *sep = PyString_AS_STRING(self);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001638 const Py_ssize_t seplen = PyString_GET_SIZE(self);
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001639 PyObject *res = NULL;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001640 char *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001641 Py_ssize_t seqlen = 0;
Tim Peters19fe14e2001-01-19 03:03:47 +00001642 size_t sz = 0;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001643 Py_ssize_t i;
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001644 PyObject *seq, *item;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001645
Tim Peters19fe14e2001-01-19 03:03:47 +00001646 seq = PySequence_Fast(orig, "");
1647 if (seq == NULL) {
Jeremy Hylton194e43e2000-07-10 21:30:28 +00001648 return NULL;
1649 }
Tim Peters19fe14e2001-01-19 03:03:47 +00001650
Jeremy Hylton03657cf2000-07-12 13:05:33 +00001651 seqlen = PySequence_Size(seq);
Tim Peters19fe14e2001-01-19 03:03:47 +00001652 if (seqlen == 0) {
1653 Py_DECREF(seq);
1654 return PyString_FromString("");
1655 }
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001656 if (seqlen == 1) {
Jeremy Hylton194e43e2000-07-10 21:30:28 +00001657 item = PySequence_Fast_GET_ITEM(seq, 0);
Raymond Hettinger674f2412004-08-23 23:23:54 +00001658 if (PyString_CheckExact(item) || PyUnicode_CheckExact(item)) {
1659 Py_INCREF(item);
Tim Peters19fe14e2001-01-19 03:03:47 +00001660 Py_DECREF(seq);
Raymond Hettinger674f2412004-08-23 23:23:54 +00001661 return item;
Tim Peters19fe14e2001-01-19 03:03:47 +00001662 }
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001663 }
Jeremy Hylton194e43e2000-07-10 21:30:28 +00001664
Raymond Hettinger674f2412004-08-23 23:23:54 +00001665 /* There are at least two things to join, or else we have a subclass
Tim Petersae1d0c92006-03-17 03:29:34 +00001666 * of the builtin types in the sequence.
Raymond Hettinger674f2412004-08-23 23:23:54 +00001667 * Do a pre-pass to figure out the total amount of space we'll
1668 * need (sz), see whether any argument is absurd, and defer to
1669 * the Unicode join if appropriate.
Tim Peters19fe14e2001-01-19 03:03:47 +00001670 */
Jeremy Hylton194e43e2000-07-10 21:30:28 +00001671 for (i = 0; i < seqlen; i++) {
Tim Peters19fe14e2001-01-19 03:03:47 +00001672 const size_t old_sz = sz;
Jeremy Hylton194e43e2000-07-10 21:30:28 +00001673 item = PySequence_Fast_GET_ITEM(seq, i);
1674 if (!PyString_Check(item)){
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001675#ifdef Py_USING_UNICODE
Jeremy Hylton194e43e2000-07-10 21:30:28 +00001676 if (PyUnicode_Check(item)) {
Tim Peters2cfe3682001-05-05 05:36:48 +00001677 /* Defer to Unicode join.
1678 * CAUTION: There's no gurantee that the
1679 * original sequence can be iterated over
1680 * again, so we must pass seq here.
1681 */
1682 PyObject *result;
1683 result = PyUnicode_Join((PyObject *)self, seq);
Barry Warsaw771d0672000-07-11 04:58:12 +00001684 Py_DECREF(seq);
Tim Peters2cfe3682001-05-05 05:36:48 +00001685 return result;
Jeremy Hylton194e43e2000-07-10 21:30:28 +00001686 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001687#endif
Jeremy Hylton194e43e2000-07-10 21:30:28 +00001688 PyErr_Format(PyExc_TypeError,
Neal Norwitz0e2cbab2006-04-17 05:56:32 +00001689 "sequence item %zd: expected string,"
Jeremy Hylton88887aa2000-07-11 20:55:38 +00001690 " %.80s found",
Neal Norwitz0e2cbab2006-04-17 05:56:32 +00001691 i, item->ob_type->tp_name);
Tim Peters19fe14e2001-01-19 03:03:47 +00001692 Py_DECREF(seq);
1693 return NULL;
Jeremy Hylton194e43e2000-07-10 21:30:28 +00001694 }
Tim Peters19fe14e2001-01-19 03:03:47 +00001695 sz += PyString_GET_SIZE(item);
1696 if (i != 0)
1697 sz += seplen;
Martin v. Löwis8ce358f2006-04-13 07:22:51 +00001698 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
Tim Peters19fe14e2001-01-19 03:03:47 +00001699 PyErr_SetString(PyExc_OverflowError,
1700 "join() is too long for a Python string");
1701 Py_DECREF(seq);
1702 return NULL;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001703 }
Tim Peters19fe14e2001-01-19 03:03:47 +00001704 }
1705
1706 /* Allocate result space. */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001707 res = PyString_FromStringAndSize((char*)NULL, sz);
Tim Peters19fe14e2001-01-19 03:03:47 +00001708 if (res == NULL) {
1709 Py_DECREF(seq);
1710 return NULL;
1711 }
1712
1713 /* Catenate everything. */
1714 p = PyString_AS_STRING(res);
1715 for (i = 0; i < seqlen; ++i) {
1716 size_t n;
1717 item = PySequence_Fast_GET_ITEM(seq, i);
1718 n = PyString_GET_SIZE(item);
1719 memcpy(p, PyString_AS_STRING(item), n);
1720 p += n;
1721 if (i < seqlen - 1) {
Jeremy Hylton194e43e2000-07-10 21:30:28 +00001722 memcpy(p, sep, seplen);
1723 p += seplen;
Jeremy Hylton194e43e2000-07-10 21:30:28 +00001724 }
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001725 }
Tim Peters19fe14e2001-01-19 03:03:47 +00001726
Jeremy Hylton49048292000-07-11 03:28:17 +00001727 Py_DECREF(seq);
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001728 return res;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001729}
1730
Tim Peters52e155e2001-06-16 05:42:57 +00001731PyObject *
1732_PyString_Join(PyObject *sep, PyObject *x)
Tim Petersa7259592001-06-16 05:11:17 +00001733{
Tim Petersa7259592001-06-16 05:11:17 +00001734 assert(sep != NULL && PyString_Check(sep));
1735 assert(x != NULL);
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001736 return string_join((PyStringObject *)sep, x);
Tim Petersa7259592001-06-16 05:11:17 +00001737}
1738
Neal Norwitz1f68fc72002-06-14 00:50:42 +00001739static void
Martin v. Löwis18e16552006-02-15 17:27:45 +00001740string_adjust_indices(Py_ssize_t *start, Py_ssize_t *end, Py_ssize_t len)
Neal Norwitz1f68fc72002-06-14 00:50:42 +00001741{
1742 if (*end > len)
1743 *end = len;
1744 else if (*end < 0)
1745 *end += len;
1746 if (*end < 0)
1747 *end = 0;
1748 if (*start < 0)
1749 *start += len;
1750 if (*start < 0)
1751 *start = 0;
1752}
1753
Martin v. Löwis18e16552006-02-15 17:27:45 +00001754static Py_ssize_t
Fred Drakeba096332000-07-09 07:04:36 +00001755string_find_internal(PyStringObject *self, PyObject *args, int dir)
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001756{
Guido van Rossum4c08d552000-03-10 22:55:18 +00001757 const char *s = PyString_AS_STRING(self), *sub;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001758 Py_ssize_t len = PyString_GET_SIZE(self);
Martin v. Löwis8ce358f2006-04-13 07:22:51 +00001759 Py_ssize_t n, i = 0, last = PY_SSIZE_T_MAX;
Guido van Rossum4c08d552000-03-10 22:55:18 +00001760 PyObject *subobj;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001761
Martin v. Löwis18e16552006-02-15 17:27:45 +00001762 /* XXX ssize_t i */
Tim Petersb3d8d1f2001-04-28 05:38:26 +00001763 if (!PyArg_ParseTuple(args, "O|O&O&:find/rfind/index/rindex",
Guido van Rossumc6821402000-05-08 14:08:05 +00001764 &subobj, _PyEval_SliceIndex, &i, _PyEval_SliceIndex, &last))
Guido van Rossum4c08d552000-03-10 22:55:18 +00001765 return -2;
1766 if (PyString_Check(subobj)) {
1767 sub = PyString_AS_STRING(subobj);
1768 n = PyString_GET_SIZE(subobj);
1769 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001770#ifdef Py_USING_UNICODE
Guido van Rossum4c08d552000-03-10 22:55:18 +00001771 else if (PyUnicode_Check(subobj))
Guido van Rossum76afbd92002-08-20 17:29:29 +00001772 return PyUnicode_Find((PyObject *)self, subobj, i, last, dir);
Martin v. Löwis339d0f72001-08-17 18:39:25 +00001773#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +00001774 else if (PyObject_AsCharBuffer(subobj, &sub, &n))
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001775 return -2;
1776
Neal Norwitz1f68fc72002-06-14 00:50:42 +00001777 string_adjust_indices(&i, &last, len);
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001778
Guido van Rossum4c08d552000-03-10 22:55:18 +00001779 if (dir > 0) {
1780 if (n == 0 && i <= last)
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001781 return (long)i;
Guido van Rossum4c08d552000-03-10 22:55:18 +00001782 last -= n;
1783 for (; i <= last; ++i)
Fred Drake396f6e02000-06-20 15:47:54 +00001784 if (s[i] == sub[0] && memcmp(&s[i], sub, n) == 0)
Guido van Rossum4c08d552000-03-10 22:55:18 +00001785 return (long)i;
1786 }
1787 else {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001788 Py_ssize_t j;
Tim Petersb3d8d1f2001-04-28 05:38:26 +00001789
Guido van Rossum4c08d552000-03-10 22:55:18 +00001790 if (n == 0 && i <= last)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001791 return last;
Guido van Rossum4c08d552000-03-10 22:55:18 +00001792 for (j = last-n; j >= i; --j)
Fred Drake396f6e02000-06-20 15:47:54 +00001793 if (s[j] == sub[0] && memcmp(&s[j], sub, n) == 0)
Martin v. Löwis18e16552006-02-15 17:27:45 +00001794 return j;
Guido van Rossum4c08d552000-03-10 22:55:18 +00001795 }
Tim Petersb3d8d1f2001-04-28 05:38:26 +00001796
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001797 return -1;
1798}
1799
1800
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001801PyDoc_STRVAR(find__doc__,
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001802"S.find(sub [,start [,end]]) -> int\n\
1803\n\
1804Return the lowest index in S where substring sub is found,\n\
1805such that sub is contained within s[start,end]. Optional\n\
1806arguments start and end are interpreted as in slice notation.\n\
1807\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001808Return -1 on failure.");
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001809
1810static PyObject *
Fred Drakeba096332000-07-09 07:04:36 +00001811string_find(PyStringObject *self, PyObject *args)
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001812{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001813 Py_ssize_t result = string_find_internal(self, args, +1);
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001814 if (result == -2)
1815 return NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001816 return PyInt_FromSsize_t(result);
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001817}
1818
1819
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001820PyDoc_STRVAR(index__doc__,
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001821"S.index(sub [,start [,end]]) -> int\n\
1822\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001823Like S.find() but raise ValueError when the substring is not found.");
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001824
1825static PyObject *
Fred Drakeba096332000-07-09 07:04:36 +00001826string_index(PyStringObject *self, PyObject *args)
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001827{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001828 Py_ssize_t result = string_find_internal(self, args, +1);
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001829 if (result == -2)
1830 return NULL;
1831 if (result == -1) {
1832 PyErr_SetString(PyExc_ValueError,
Raymond Hettinger5d5e7c02003-01-15 05:32:57 +00001833 "substring not found");
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001834 return NULL;
1835 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00001836 return PyInt_FromSsize_t(result);
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001837}
1838
1839
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001840PyDoc_STRVAR(rfind__doc__,
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001841"S.rfind(sub [,start [,end]]) -> int\n\
1842\n\
1843Return the highest index in S where substring sub is found,\n\
1844such that sub is contained within s[start,end]. Optional\n\
1845arguments start and end are interpreted as in slice notation.\n\
1846\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001847Return -1 on failure.");
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001848
1849static PyObject *
Fred Drakeba096332000-07-09 07:04:36 +00001850string_rfind(PyStringObject *self, PyObject *args)
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001851{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001852 Py_ssize_t result = string_find_internal(self, args, -1);
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001853 if (result == -2)
1854 return NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001855 return PyInt_FromSsize_t(result);
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001856}
1857
1858
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001859PyDoc_STRVAR(rindex__doc__,
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001860"S.rindex(sub [,start [,end]]) -> int\n\
1861\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001862Like S.rfind() but raise ValueError when the substring is not found.");
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001863
1864static PyObject *
Fred Drakeba096332000-07-09 07:04:36 +00001865string_rindex(PyStringObject *self, PyObject *args)
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001866{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001867 Py_ssize_t result = string_find_internal(self, args, -1);
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001868 if (result == -2)
1869 return NULL;
1870 if (result == -1) {
1871 PyErr_SetString(PyExc_ValueError,
Raymond Hettinger5d5e7c02003-01-15 05:32:57 +00001872 "substring not found");
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001873 return NULL;
1874 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00001875 return PyInt_FromSsize_t(result);
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001876}
1877
1878
1879static PyObject *
Guido van Rossum018b0eb2002-04-13 00:56:08 +00001880do_xstrip(PyStringObject *self, int striptype, PyObject *sepobj)
1881{
1882 char *s = PyString_AS_STRING(self);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001883 Py_ssize_t len = PyString_GET_SIZE(self);
Guido van Rossum018b0eb2002-04-13 00:56:08 +00001884 char *sep = PyString_AS_STRING(sepobj);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001885 Py_ssize_t seplen = PyString_GET_SIZE(sepobj);
1886 Py_ssize_t i, j;
Guido van Rossum018b0eb2002-04-13 00:56:08 +00001887
1888 i = 0;
1889 if (striptype != RIGHTSTRIP) {
1890 while (i < len && memchr(sep, Py_CHARMASK(s[i]), seplen)) {
1891 i++;
1892 }
1893 }
1894
1895 j = len;
1896 if (striptype != LEFTSTRIP) {
1897 do {
1898 j--;
1899 } while (j >= i && memchr(sep, Py_CHARMASK(s[j]), seplen));
1900 j++;
1901 }
1902
1903 if (i == 0 && j == len && PyString_CheckExact(self)) {
1904 Py_INCREF(self);
1905 return (PyObject*)self;
1906 }
1907 else
1908 return PyString_FromStringAndSize(s+i, j-i);
1909}
1910
1911
1912static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001913do_strip(PyStringObject *self, int striptype)
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001914{
1915 char *s = PyString_AS_STRING(self);
Martin v. Löwis18e16552006-02-15 17:27:45 +00001916 Py_ssize_t len = PyString_GET_SIZE(self), i, j;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001917
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001918 i = 0;
1919 if (striptype != RIGHTSTRIP) {
1920 while (i < len && isspace(Py_CHARMASK(s[i]))) {
1921 i++;
1922 }
1923 }
1924
1925 j = len;
1926 if (striptype != LEFTSTRIP) {
1927 do {
1928 j--;
1929 } while (j >= i && isspace(Py_CHARMASK(s[j])));
1930 j++;
1931 }
1932
Tim Peters8fa5dd02001-09-12 02:18:30 +00001933 if (i == 0 && j == len && PyString_CheckExact(self)) {
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001934 Py_INCREF(self);
1935 return (PyObject*)self;
1936 }
1937 else
1938 return PyString_FromStringAndSize(s+i, j-i);
1939}
1940
1941
Guido van Rossum018b0eb2002-04-13 00:56:08 +00001942static PyObject *
1943do_argstrip(PyStringObject *self, int striptype, PyObject *args)
1944{
1945 PyObject *sep = NULL;
1946
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00001947 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
Guido van Rossum018b0eb2002-04-13 00:56:08 +00001948 return NULL;
1949
1950 if (sep != NULL && sep != Py_None) {
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00001951 if (PyString_Check(sep))
1952 return do_xstrip(self, striptype, sep);
Walter Dörwald775c11f2002-05-13 09:00:41 +00001953#ifdef Py_USING_UNICODE
Walter Dörwaldde02bcb2002-04-22 17:42:37 +00001954 else if (PyUnicode_Check(sep)) {
1955 PyObject *uniself = PyUnicode_FromObject((PyObject *)self);
1956 PyObject *res;
1957 if (uniself==NULL)
1958 return NULL;
1959 res = _PyUnicode_XStrip((PyUnicodeObject *)uniself,
1960 striptype, sep);
1961 Py_DECREF(uniself);
1962 return res;
1963 }
Walter Dörwald775c11f2002-05-13 09:00:41 +00001964#endif
Neal Norwitz7e957d32006-04-06 08:17:41 +00001965 PyErr_Format(PyExc_TypeError,
Walter Dörwald775c11f2002-05-13 09:00:41 +00001966#ifdef Py_USING_UNICODE
Neal Norwitz7e957d32006-04-06 08:17:41 +00001967 "%s arg must be None, str or unicode",
Walter Dörwald775c11f2002-05-13 09:00:41 +00001968#else
Neal Norwitz7e957d32006-04-06 08:17:41 +00001969 "%s arg must be None or str",
Walter Dörwald775c11f2002-05-13 09:00:41 +00001970#endif
Neal Norwitz7e957d32006-04-06 08:17:41 +00001971 STRIPNAME(striptype));
1972 return NULL;
Guido van Rossum018b0eb2002-04-13 00:56:08 +00001973 }
1974
1975 return do_strip(self, striptype);
1976}
1977
1978
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001979PyDoc_STRVAR(strip__doc__,
Neal Norwitzffe33b72003-04-10 22:35:32 +00001980"S.strip([chars]) -> string or unicode\n\
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001981\n\
1982Return a copy of the string S with leading and trailing\n\
Guido van Rossum018b0eb2002-04-13 00:56:08 +00001983whitespace removed.\n\
Neal Norwitzffe33b72003-04-10 22:35:32 +00001984If chars is given and not None, remove characters in chars instead.\n\
1985If chars is unicode, S will be converted to unicode before stripping");
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001986
1987static PyObject *
Guido van Rossum018b0eb2002-04-13 00:56:08 +00001988string_strip(PyStringObject *self, PyObject *args)
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001989{
Guido van Rossum018b0eb2002-04-13 00:56:08 +00001990 if (PyTuple_GET_SIZE(args) == 0)
1991 return do_strip(self, BOTHSTRIP); /* Common case */
1992 else
1993 return do_argstrip(self, BOTHSTRIP, args);
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001994}
1995
1996
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001997PyDoc_STRVAR(lstrip__doc__,
Neal Norwitzffe33b72003-04-10 22:35:32 +00001998"S.lstrip([chars]) -> string or unicode\n\
Barry Warsaw226ae6c1999-10-12 19:54:53 +00001999\n\
Guido van Rossum018b0eb2002-04-13 00:56:08 +00002000Return a copy of the string S with leading whitespace removed.\n\
Neal Norwitzffe33b72003-04-10 22:35:32 +00002001If chars is given and not None, remove characters in chars instead.\n\
2002If chars is unicode, S will be converted to unicode before stripping");
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002003
2004static PyObject *
Guido van Rossum018b0eb2002-04-13 00:56:08 +00002005string_lstrip(PyStringObject *self, PyObject *args)
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002006{
Guido van Rossum018b0eb2002-04-13 00:56:08 +00002007 if (PyTuple_GET_SIZE(args) == 0)
2008 return do_strip(self, LEFTSTRIP); /* Common case */
2009 else
2010 return do_argstrip(self, LEFTSTRIP, args);
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002011}
2012
2013
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002014PyDoc_STRVAR(rstrip__doc__,
Neal Norwitzffe33b72003-04-10 22:35:32 +00002015"S.rstrip([chars]) -> string or unicode\n\
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002016\n\
Guido van Rossum018b0eb2002-04-13 00:56:08 +00002017Return a copy of the string S with trailing whitespace removed.\n\
Neal Norwitzffe33b72003-04-10 22:35:32 +00002018If chars is given and not None, remove characters in chars instead.\n\
2019If chars is unicode, S will be converted to unicode before stripping");
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002020
2021static PyObject *
Guido van Rossum018b0eb2002-04-13 00:56:08 +00002022string_rstrip(PyStringObject *self, PyObject *args)
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002023{
Guido van Rossum018b0eb2002-04-13 00:56:08 +00002024 if (PyTuple_GET_SIZE(args) == 0)
2025 return do_strip(self, RIGHTSTRIP); /* Common case */
2026 else
2027 return do_argstrip(self, RIGHTSTRIP, args);
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002028}
2029
2030
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002031PyDoc_STRVAR(lower__doc__,
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002032"S.lower() -> string\n\
2033\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002034Return a copy of the string S converted to lowercase.");
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002035
2036static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002037string_lower(PyStringObject *self)
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002038{
2039 char *s = PyString_AS_STRING(self), *s_new;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002040 Py_ssize_t i, n = PyString_GET_SIZE(self);
Anthony Baxtera6286212006-04-11 07:42:36 +00002041 PyObject *newobj;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002042
Anthony Baxtera6286212006-04-11 07:42:36 +00002043 newobj = PyString_FromStringAndSize(NULL, n);
2044 if (newobj == NULL)
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002045 return NULL;
Anthony Baxtera6286212006-04-11 07:42:36 +00002046 s_new = PyString_AsString(newobj);
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002047 for (i = 0; i < n; i++) {
2048 int c = Py_CHARMASK(*s++);
2049 if (isupper(c)) {
2050 *s_new = tolower(c);
2051 } else
2052 *s_new = c;
2053 s_new++;
2054 }
Anthony Baxtera6286212006-04-11 07:42:36 +00002055 return newobj;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002056}
2057
2058
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002059PyDoc_STRVAR(upper__doc__,
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002060"S.upper() -> string\n\
2061\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002062Return a copy of the string S converted to uppercase.");
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002063
2064static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002065string_upper(PyStringObject *self)
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002066{
2067 char *s = PyString_AS_STRING(self), *s_new;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002068 Py_ssize_t i, n = PyString_GET_SIZE(self);
Anthony Baxtera6286212006-04-11 07:42:36 +00002069 PyObject *newobj;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002070
Anthony Baxtera6286212006-04-11 07:42:36 +00002071 newobj = PyString_FromStringAndSize(NULL, n);
2072 if (newobj == NULL)
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002073 return NULL;
Anthony Baxtera6286212006-04-11 07:42:36 +00002074 s_new = PyString_AsString(newobj);
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002075 for (i = 0; i < n; i++) {
2076 int c = Py_CHARMASK(*s++);
2077 if (islower(c)) {
2078 *s_new = toupper(c);
2079 } else
2080 *s_new = c;
2081 s_new++;
2082 }
Anthony Baxtera6286212006-04-11 07:42:36 +00002083 return newobj;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002084}
2085
2086
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002087PyDoc_STRVAR(title__doc__,
Guido van Rossum4c08d552000-03-10 22:55:18 +00002088"S.title() -> string\n\
2089\n\
2090Return a titlecased version of S, i.e. words start with uppercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002091characters, all remaining cased characters have lowercase.");
Guido van Rossum4c08d552000-03-10 22:55:18 +00002092
2093static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002094string_title(PyStringObject *self)
Guido van Rossum4c08d552000-03-10 22:55:18 +00002095{
2096 char *s = PyString_AS_STRING(self), *s_new;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002097 Py_ssize_t i, n = PyString_GET_SIZE(self);
Guido van Rossum4c08d552000-03-10 22:55:18 +00002098 int previous_is_cased = 0;
Anthony Baxtera6286212006-04-11 07:42:36 +00002099 PyObject *newobj;
Guido van Rossum4c08d552000-03-10 22:55:18 +00002100
Anthony Baxtera6286212006-04-11 07:42:36 +00002101 newobj = PyString_FromStringAndSize(NULL, n);
2102 if (newobj == NULL)
Guido van Rossum4c08d552000-03-10 22:55:18 +00002103 return NULL;
Anthony Baxtera6286212006-04-11 07:42:36 +00002104 s_new = PyString_AsString(newobj);
Guido van Rossum4c08d552000-03-10 22:55:18 +00002105 for (i = 0; i < n; i++) {
2106 int c = Py_CHARMASK(*s++);
2107 if (islower(c)) {
2108 if (!previous_is_cased)
2109 c = toupper(c);
2110 previous_is_cased = 1;
2111 } else if (isupper(c)) {
2112 if (previous_is_cased)
2113 c = tolower(c);
2114 previous_is_cased = 1;
2115 } else
2116 previous_is_cased = 0;
2117 *s_new++ = c;
2118 }
Anthony Baxtera6286212006-04-11 07:42:36 +00002119 return newobj;
Guido van Rossum4c08d552000-03-10 22:55:18 +00002120}
2121
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002122PyDoc_STRVAR(capitalize__doc__,
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002123"S.capitalize() -> string\n\
2124\n\
2125Return a copy of the string S with only its first character\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002126capitalized.");
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002127
2128static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002129string_capitalize(PyStringObject *self)
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002130{
2131 char *s = PyString_AS_STRING(self), *s_new;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002132 Py_ssize_t i, n = PyString_GET_SIZE(self);
Anthony Baxtera6286212006-04-11 07:42:36 +00002133 PyObject *newobj;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002134
Anthony Baxtera6286212006-04-11 07:42:36 +00002135 newobj = PyString_FromStringAndSize(NULL, n);
2136 if (newobj == NULL)
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002137 return NULL;
Anthony Baxtera6286212006-04-11 07:42:36 +00002138 s_new = PyString_AsString(newobj);
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002139 if (0 < n) {
2140 int c = Py_CHARMASK(*s++);
2141 if (islower(c))
2142 *s_new = toupper(c);
2143 else
2144 *s_new = c;
2145 s_new++;
2146 }
2147 for (i = 1; i < n; i++) {
2148 int c = Py_CHARMASK(*s++);
2149 if (isupper(c))
2150 *s_new = tolower(c);
2151 else
2152 *s_new = c;
2153 s_new++;
2154 }
Anthony Baxtera6286212006-04-11 07:42:36 +00002155 return newobj;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002156}
2157
2158
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002159PyDoc_STRVAR(count__doc__,
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002160"S.count(sub[, start[, end]]) -> int\n\
2161\n\
2162Return the number of occurrences of substring sub in string\n\
2163S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002164interpreted as in slice notation.");
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002165
2166static PyObject *
Fred Drakeba096332000-07-09 07:04:36 +00002167string_count(PyStringObject *self, PyObject *args)
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002168{
Raymond Hettinger57e74472005-02-20 09:54:53 +00002169 const char *s = PyString_AS_STRING(self), *sub, *t;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002170 Py_ssize_t len = PyString_GET_SIZE(self), n;
Martin v. Löwis8ce358f2006-04-13 07:22:51 +00002171 Py_ssize_t i = 0, last = PY_SSIZE_T_MAX;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002172 Py_ssize_t m, r;
Guido van Rossum4c08d552000-03-10 22:55:18 +00002173 PyObject *subobj;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002174
Guido van Rossumc6821402000-05-08 14:08:05 +00002175 if (!PyArg_ParseTuple(args, "O|O&O&:count", &subobj,
2176 _PyEval_SliceIndex, &i, _PyEval_SliceIndex, &last))
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002177 return NULL;
Guido van Rossumc6821402000-05-08 14:08:05 +00002178
Guido van Rossum4c08d552000-03-10 22:55:18 +00002179 if (PyString_Check(subobj)) {
2180 sub = PyString_AS_STRING(subobj);
2181 n = PyString_GET_SIZE(subobj);
2182 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002183#ifdef Py_USING_UNICODE
Marc-André Lemburg3a645e42001-01-16 11:54:12 +00002184 else if (PyUnicode_Check(subobj)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002185 Py_ssize_t count;
Marc-André Lemburg3a645e42001-01-16 11:54:12 +00002186 count = PyUnicode_Count((PyObject *)self, subobj, i, last);
2187 if (count == -1)
2188 return NULL;
2189 else
2190 return PyInt_FromLong((long) count);
2191 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002192#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +00002193 else if (PyObject_AsCharBuffer(subobj, &sub, &n))
2194 return NULL;
2195
Neal Norwitz1f68fc72002-06-14 00:50:42 +00002196 string_adjust_indices(&i, &last, len);
2197
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002198 m = last + 1 - n;
2199 if (n == 0)
Martin v. Löwis18e16552006-02-15 17:27:45 +00002200 return PyInt_FromSsize_t(m-i);
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002201
2202 r = 0;
2203 while (i < m) {
2204 if (!memcmp(s+i, sub, n)) {
2205 r++;
2206 i += n;
2207 } else {
2208 i++;
2209 }
Raymond Hettinger57e74472005-02-20 09:54:53 +00002210 if (i >= m)
2211 break;
Anthony Baxtera6286212006-04-11 07:42:36 +00002212 t = (const char *)memchr(s+i, sub[0], m-i);
Raymond Hettinger57e74472005-02-20 09:54:53 +00002213 if (t == NULL)
2214 break;
2215 i = t - s;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002216 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002217 return PyInt_FromSsize_t(r);
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002218}
2219
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002220PyDoc_STRVAR(swapcase__doc__,
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002221"S.swapcase() -> string\n\
2222\n\
Guido van Rossum4c08d552000-03-10 22:55:18 +00002223Return a copy of the string S with uppercase characters\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002224converted to lowercase and vice versa.");
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002225
2226static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002227string_swapcase(PyStringObject *self)
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002228{
2229 char *s = PyString_AS_STRING(self), *s_new;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002230 Py_ssize_t i, n = PyString_GET_SIZE(self);
Anthony Baxtera6286212006-04-11 07:42:36 +00002231 PyObject *newobj;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002232
Anthony Baxtera6286212006-04-11 07:42:36 +00002233 newobj = PyString_FromStringAndSize(NULL, n);
2234 if (newobj == NULL)
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002235 return NULL;
Anthony Baxtera6286212006-04-11 07:42:36 +00002236 s_new = PyString_AsString(newobj);
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002237 for (i = 0; i < n; i++) {
2238 int c = Py_CHARMASK(*s++);
2239 if (islower(c)) {
2240 *s_new = toupper(c);
2241 }
2242 else if (isupper(c)) {
2243 *s_new = tolower(c);
2244 }
2245 else
2246 *s_new = c;
2247 s_new++;
2248 }
Anthony Baxtera6286212006-04-11 07:42:36 +00002249 return newobj;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002250}
2251
2252
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002253PyDoc_STRVAR(translate__doc__,
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002254"S.translate(table [,deletechars]) -> string\n\
2255\n\
2256Return a copy of the string S, where all characters occurring\n\
2257in the optional argument deletechars are removed, and the\n\
2258remaining characters have been mapped through the given\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002259translation table, which must be a string of length 256.");
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002260
2261static PyObject *
Fred Drakeba096332000-07-09 07:04:36 +00002262string_translate(PyStringObject *self, PyObject *args)
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002263{
Guido van Rossum4c08d552000-03-10 22:55:18 +00002264 register char *input, *output;
2265 register const char *table;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002266 register Py_ssize_t i, c, changed = 0;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002267 PyObject *input_obj = (PyObject*)self;
Guido van Rossum4c08d552000-03-10 22:55:18 +00002268 const char *table1, *output_start, *del_table=NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002269 Py_ssize_t inlen, tablen, dellen = 0;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002270 PyObject *result;
2271 int trans_table[256];
Guido van Rossum4c08d552000-03-10 22:55:18 +00002272 PyObject *tableobj, *delobj = NULL;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002273
Raymond Hettingerea3fdf42002-12-29 16:33:45 +00002274 if (!PyArg_UnpackTuple(args, "translate", 1, 2,
Guido van Rossum4c08d552000-03-10 22:55:18 +00002275 &tableobj, &delobj))
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002276 return NULL;
Guido van Rossum4c08d552000-03-10 22:55:18 +00002277
2278 if (PyString_Check(tableobj)) {
2279 table1 = PyString_AS_STRING(tableobj);
2280 tablen = PyString_GET_SIZE(tableobj);
2281 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002282#ifdef Py_USING_UNICODE
Guido van Rossum4c08d552000-03-10 22:55:18 +00002283 else if (PyUnicode_Check(tableobj)) {
Tim Petersb3d8d1f2001-04-28 05:38:26 +00002284 /* Unicode .translate() does not support the deletechars
Guido van Rossum4c08d552000-03-10 22:55:18 +00002285 parameter; instead a mapping to None will cause characters
2286 to be deleted. */
2287 if (delobj != NULL) {
2288 PyErr_SetString(PyExc_TypeError,
2289 "deletions are implemented differently for unicode");
2290 return NULL;
2291 }
2292 return PyUnicode_Translate((PyObject *)self, tableobj, NULL);
2293 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002294#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +00002295 else if (PyObject_AsCharBuffer(tableobj, &table1, &tablen))
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002296 return NULL;
Guido van Rossum4c08d552000-03-10 22:55:18 +00002297
Martin v. Löwis00b61272002-12-12 20:03:19 +00002298 if (tablen != 256) {
2299 PyErr_SetString(PyExc_ValueError,
2300 "translation table must be 256 characters long");
2301 return NULL;
2302 }
2303
Guido van Rossum4c08d552000-03-10 22:55:18 +00002304 if (delobj != NULL) {
2305 if (PyString_Check(delobj)) {
2306 del_table = PyString_AS_STRING(delobj);
2307 dellen = PyString_GET_SIZE(delobj);
2308 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002309#ifdef Py_USING_UNICODE
Guido van Rossum4c08d552000-03-10 22:55:18 +00002310 else if (PyUnicode_Check(delobj)) {
2311 PyErr_SetString(PyExc_TypeError,
2312 "deletions are implemented differently for unicode");
2313 return NULL;
2314 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002315#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +00002316 else if (PyObject_AsCharBuffer(delobj, &del_table, &dellen))
2317 return NULL;
Guido van Rossum4c08d552000-03-10 22:55:18 +00002318 }
2319 else {
2320 del_table = NULL;
2321 dellen = 0;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002322 }
2323
2324 table = table1;
Neal Norwitz2aa9a5d2006-03-20 01:53:23 +00002325 inlen = PyString_GET_SIZE(input_obj);
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002326 result = PyString_FromStringAndSize((char *)NULL, inlen);
2327 if (result == NULL)
2328 return NULL;
2329 output_start = output = PyString_AsString(result);
Neal Norwitz2aa9a5d2006-03-20 01:53:23 +00002330 input = PyString_AS_STRING(input_obj);
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002331
2332 if (dellen == 0) {
2333 /* If no deletions are required, use faster code */
2334 for (i = inlen; --i >= 0; ) {
2335 c = Py_CHARMASK(*input++);
2336 if (Py_CHARMASK((*output++ = table[c])) != c)
2337 changed = 1;
2338 }
Tim Peters8fa5dd02001-09-12 02:18:30 +00002339 if (changed || !PyString_CheckExact(input_obj))
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002340 return result;
2341 Py_DECREF(result);
2342 Py_INCREF(input_obj);
2343 return input_obj;
2344 }
2345
2346 for (i = 0; i < 256; i++)
2347 trans_table[i] = Py_CHARMASK(table[i]);
2348
2349 for (i = 0; i < dellen; i++)
2350 trans_table[(int) Py_CHARMASK(del_table[i])] = -1;
2351
2352 for (i = inlen; --i >= 0; ) {
2353 c = Py_CHARMASK(*input++);
2354 if (trans_table[c] != -1)
2355 if (Py_CHARMASK(*output++ = (char)trans_table[c]) == c)
2356 continue;
2357 changed = 1;
2358 }
Tim Peters8fa5dd02001-09-12 02:18:30 +00002359 if (!changed && PyString_CheckExact(input_obj)) {
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002360 Py_DECREF(result);
2361 Py_INCREF(input_obj);
2362 return input_obj;
2363 }
2364 /* Fix the size of the resulting string */
Tim Peters5de98422002-04-27 18:44:32 +00002365 if (inlen > 0)
2366 _PyString_Resize(&result, output - output_start);
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002367 return result;
2368}
2369
2370
2371/* What follows is used for implementing replace(). Perry Stoll. */
2372
2373/*
2374 mymemfind
2375
2376 strstr replacement for arbitrary blocks of memory.
2377
Barry Warsaw51ac5802000-03-20 16:36:48 +00002378 Locates the first occurrence in the memory pointed to by MEM of the
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002379 contents of memory pointed to by PAT. Returns the index into MEM if
2380 found, or -1 if not found. If len of PAT is greater than length of
2381 MEM, the function returns -1.
2382*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00002383static Py_ssize_t
2384mymemfind(const char *mem, Py_ssize_t len, const char *pat, Py_ssize_t pat_len)
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002385{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002386 register Py_ssize_t ii;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002387
2388 /* pattern can not occur in the last pat_len-1 chars */
2389 len -= pat_len;
2390
2391 for (ii = 0; ii <= len; ii++) {
Fred Drake396f6e02000-06-20 15:47:54 +00002392 if (mem[ii] == pat[0] && memcmp(&mem[ii], pat, pat_len) == 0) {
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002393 return ii;
2394 }
2395 }
2396 return -1;
2397}
2398
2399/*
2400 mymemcnt
2401
2402 Return the number of distinct times PAT is found in MEM.
2403 meaning mem=1111 and pat==11 returns 2.
2404 mem=11111 and pat==11 also return 2.
2405 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002406static Py_ssize_t
2407mymemcnt(const char *mem, Py_ssize_t len, const char *pat, Py_ssize_t pat_len)
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002408{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002409 register Py_ssize_t offset = 0;
2410 Py_ssize_t nfound = 0;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002411
2412 while (len >= 0) {
2413 offset = mymemfind(mem, len, pat, pat_len);
2414 if (offset == -1)
2415 break;
2416 mem += offset + pat_len;
2417 len -= offset + pat_len;
2418 nfound++;
2419 }
2420 return nfound;
2421}
2422
2423/*
2424 mymemreplace
2425
Thomas Wouters7e474022000-07-16 12:04:32 +00002426 Return a string in which all occurrences of PAT in memory STR are
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002427 replaced with SUB.
2428
Thomas Wouters7e474022000-07-16 12:04:32 +00002429 If length of PAT is less than length of STR or there are no occurrences
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002430 of PAT in STR, then the original string is returned. Otherwise, a new
2431 string is allocated here and returned.
2432
2433 on return, out_len is:
2434 the length of output string, or
2435 -1 if the input string is returned, or
2436 unchanged if an error occurs (no memory).
2437
2438 return value is:
2439 the new string allocated locally, or
2440 NULL if an error occurred.
2441*/
2442static char *
Martin v. Löwis18e16552006-02-15 17:27:45 +00002443mymemreplace(const char *str, Py_ssize_t len, /* input string */
2444 const char *pat, Py_ssize_t pat_len, /* pattern string to find */
2445 const char *sub, Py_ssize_t sub_len, /* substitution string */
2446 Py_ssize_t count, /* number of replacements */
2447 Py_ssize_t *out_len)
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002448{
2449 char *out_s;
2450 char *new_s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002451 Py_ssize_t nfound, offset, new_len;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002452
Guido van Rossum8b1a6d62002-08-23 18:21:28 +00002453 if (len == 0 || (pat_len == 0 && sub_len == 0) || pat_len > len)
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002454 goto return_same;
2455
2456 /* find length of output string */
Guido van Rossum8b1a6d62002-08-23 18:21:28 +00002457 nfound = (pat_len > 0) ? mymemcnt(str, len, pat, pat_len) : len + 1;
Tim Peters9c012af2001-05-10 00:32:57 +00002458 if (count < 0)
Martin v. Löwis8ce358f2006-04-13 07:22:51 +00002459 count = PY_SSIZE_T_MAX;
Tim Peters9c012af2001-05-10 00:32:57 +00002460 else if (nfound > count)
2461 nfound = count;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002462 if (nfound == 0)
2463 goto return_same;
Tim Peters4cd44ef2001-05-10 00:05:33 +00002464
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002465 new_len = len + nfound*(sub_len - pat_len);
Tim Peters4cd44ef2001-05-10 00:05:33 +00002466 if (new_len == 0) {
2467 /* Have to allocate something for the caller to free(). */
2468 out_s = (char *)PyMem_MALLOC(1);
Tim Peters9c012af2001-05-10 00:32:57 +00002469 if (out_s == NULL)
Tim Peters4cd44ef2001-05-10 00:05:33 +00002470 return NULL;
2471 out_s[0] = '\0';
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002472 }
Tim Peters4cd44ef2001-05-10 00:05:33 +00002473 else {
2474 assert(new_len > 0);
2475 new_s = (char *)PyMem_MALLOC(new_len);
2476 if (new_s == NULL)
2477 return NULL;
2478 out_s = new_s;
2479
Guido van Rossum8b1a6d62002-08-23 18:21:28 +00002480 if (pat_len > 0) {
2481 for (; nfound > 0; --nfound) {
2482 /* find index of next instance of pattern */
2483 offset = mymemfind(str, len, pat, pat_len);
2484 if (offset == -1)
2485 break;
Tim Peters4cd44ef2001-05-10 00:05:33 +00002486
Guido van Rossum8b1a6d62002-08-23 18:21:28 +00002487 /* copy non matching part of input string */
2488 memcpy(new_s, str, offset);
2489 str += offset + pat_len;
2490 len -= offset + pat_len;
Tim Peters4cd44ef2001-05-10 00:05:33 +00002491
Guido van Rossum8b1a6d62002-08-23 18:21:28 +00002492 /* copy substitute into the output string */
2493 new_s += offset;
2494 memcpy(new_s, sub, sub_len);
2495 new_s += sub_len;
2496 }
2497 /* copy any remaining values into output string */
2498 if (len > 0)
2499 memcpy(new_s, str, len);
Tim Peters4cd44ef2001-05-10 00:05:33 +00002500 }
Guido van Rossum8b1a6d62002-08-23 18:21:28 +00002501 else {
2502 for (;;++str, --len) {
2503 memcpy(new_s, sub, sub_len);
2504 new_s += sub_len;
2505 if (--nfound <= 0) {
2506 memcpy(new_s, str, len);
2507 break;
2508 }
2509 *new_s++ = *str;
2510 }
2511 }
Tim Peters4cd44ef2001-05-10 00:05:33 +00002512 }
2513 *out_len = new_len;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002514 return out_s;
2515
2516 return_same:
2517 *out_len = -1;
Tim Peters4cd44ef2001-05-10 00:05:33 +00002518 return (char *)str; /* cast away const */
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002519}
2520
2521
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002522PyDoc_STRVAR(replace__doc__,
Fred Draked22bb652003-10-22 02:56:40 +00002523"S.replace (old, new[, count]) -> string\n\
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002524\n\
2525Return a copy of string S with all occurrences of substring\n\
Fred Draked22bb652003-10-22 02:56:40 +00002526old replaced by new. If the optional argument count is\n\
2527given, only the first count occurrences are replaced.");
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002528
2529static PyObject *
Fred Drakeba096332000-07-09 07:04:36 +00002530string_replace(PyStringObject *self, PyObject *args)
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002531{
Guido van Rossum4c08d552000-03-10 22:55:18 +00002532 const char *str = PyString_AS_STRING(self), *sub, *repl;
2533 char *new_s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002534 const Py_ssize_t len = PyString_GET_SIZE(self);
2535 Py_ssize_t sub_len, repl_len, out_len;
Thomas Woutersdc5f8082006-04-19 15:38:01 +00002536 Py_ssize_t count = -1;
Anthony Baxtera6286212006-04-11 07:42:36 +00002537 PyObject *newobj;
Guido van Rossum4c08d552000-03-10 22:55:18 +00002538 PyObject *subobj, *replobj;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002539
Thomas Woutersdc5f8082006-04-19 15:38:01 +00002540 if (!PyArg_ParseTuple(args, "OO|n:replace",
Guido van Rossum4c08d552000-03-10 22:55:18 +00002541 &subobj, &replobj, &count))
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002542 return NULL;
Guido van Rossum4c08d552000-03-10 22:55:18 +00002543
2544 if (PyString_Check(subobj)) {
2545 sub = PyString_AS_STRING(subobj);
2546 sub_len = PyString_GET_SIZE(subobj);
2547 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002548#ifdef Py_USING_UNICODE
Guido van Rossum4c08d552000-03-10 22:55:18 +00002549 else if (PyUnicode_Check(subobj))
Tim Petersb3d8d1f2001-04-28 05:38:26 +00002550 return PyUnicode_Replace((PyObject *)self,
Guido van Rossum4c08d552000-03-10 22:55:18 +00002551 subobj, replobj, count);
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002552#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +00002553 else if (PyObject_AsCharBuffer(subobj, &sub, &sub_len))
2554 return NULL;
2555
2556 if (PyString_Check(replobj)) {
2557 repl = PyString_AS_STRING(replobj);
2558 repl_len = PyString_GET_SIZE(replobj);
2559 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002560#ifdef Py_USING_UNICODE
Guido van Rossum4c08d552000-03-10 22:55:18 +00002561 else if (PyUnicode_Check(replobj))
Tim Petersb3d8d1f2001-04-28 05:38:26 +00002562 return PyUnicode_Replace((PyObject *)self,
Guido van Rossum4c08d552000-03-10 22:55:18 +00002563 subobj, replobj, count);
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002564#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +00002565 else if (PyObject_AsCharBuffer(replobj, &repl, &repl_len))
2566 return NULL;
2567
Guido van Rossum4c08d552000-03-10 22:55:18 +00002568 new_s = mymemreplace(str,len,sub,sub_len,repl,repl_len,count,&out_len);
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002569 if (new_s == NULL) {
2570 PyErr_NoMemory();
2571 return NULL;
2572 }
2573 if (out_len == -1) {
Tim Peters8fa5dd02001-09-12 02:18:30 +00002574 if (PyString_CheckExact(self)) {
2575 /* we're returning another reference to self */
Anthony Baxtera6286212006-04-11 07:42:36 +00002576 newobj = (PyObject*)self;
2577 Py_INCREF(newobj);
Tim Peters8fa5dd02001-09-12 02:18:30 +00002578 }
2579 else {
Anthony Baxtera6286212006-04-11 07:42:36 +00002580 newobj = PyString_FromStringAndSize(str, len);
2581 if (newobj == NULL)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002582 return NULL;
2583 }
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002584 }
2585 else {
Anthony Baxtera6286212006-04-11 07:42:36 +00002586 newobj = PyString_FromStringAndSize(new_s, out_len);
Guido van Rossumb18618d2000-05-03 23:44:39 +00002587 PyMem_FREE(new_s);
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002588 }
Anthony Baxtera6286212006-04-11 07:42:36 +00002589 return newobj;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002590}
2591
2592
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002593PyDoc_STRVAR(startswith__doc__,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002594"S.startswith(prefix[, start[, end]]) -> bool\n\
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002595\n\
Guido van Rossuma7132182003-04-09 19:32:45 +00002596Return True if S starts with the specified prefix, False otherwise.\n\
2597With optional start, test S beginning at that position.\n\
2598With optional end, stop comparing S at that position.");
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002599
2600static PyObject *
Fred Drakeba096332000-07-09 07:04:36 +00002601string_startswith(PyStringObject *self, PyObject *args)
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002602{
Guido van Rossum4c08d552000-03-10 22:55:18 +00002603 const char* str = PyString_AS_STRING(self);
Martin v. Löwis18e16552006-02-15 17:27:45 +00002604 Py_ssize_t len = PyString_GET_SIZE(self);
Guido van Rossum4c08d552000-03-10 22:55:18 +00002605 const char* prefix;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002606 Py_ssize_t plen;
2607 Py_ssize_t start = 0;
Martin v. Löwis8ce358f2006-04-13 07:22:51 +00002608 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossum4c08d552000-03-10 22:55:18 +00002609 PyObject *subobj;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002610
Guido van Rossumc6821402000-05-08 14:08:05 +00002611 if (!PyArg_ParseTuple(args, "O|O&O&:startswith", &subobj,
2612 _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
Guido van Rossum4c08d552000-03-10 22:55:18 +00002613 return NULL;
2614 if (PyString_Check(subobj)) {
2615 prefix = PyString_AS_STRING(subobj);
2616 plen = PyString_GET_SIZE(subobj);
2617 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002618#ifdef Py_USING_UNICODE
Marc-André Lemburg3a645e42001-01-16 11:54:12 +00002619 else if (PyUnicode_Check(subobj)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002620 Py_ssize_t rc;
Tim Petersb3d8d1f2001-04-28 05:38:26 +00002621 rc = PyUnicode_Tailmatch((PyObject *)self,
Marc-André Lemburg3a645e42001-01-16 11:54:12 +00002622 subobj, start, end, -1);
2623 if (rc == -1)
2624 return NULL;
2625 else
Guido van Rossum77f6a652002-04-03 22:41:51 +00002626 return PyBool_FromLong((long) rc);
Marc-André Lemburg3a645e42001-01-16 11:54:12 +00002627 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002628#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +00002629 else if (PyObject_AsCharBuffer(subobj, &prefix, &plen))
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002630 return NULL;
2631
Neal Norwitz1f68fc72002-06-14 00:50:42 +00002632 string_adjust_indices(&start, &end, len);
2633
2634 if (start+plen > len)
Guido van Rossum77f6a652002-04-03 22:41:51 +00002635 return PyBool_FromLong(0);
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002636
Neal Norwitz1f68fc72002-06-14 00:50:42 +00002637 if (end-start >= plen)
2638 return PyBool_FromLong(!memcmp(str+start, prefix, plen));
2639 else
2640 return PyBool_FromLong(0);
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002641}
2642
2643
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002644PyDoc_STRVAR(endswith__doc__,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002645"S.endswith(suffix[, start[, end]]) -> bool\n\
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002646\n\
Guido van Rossuma7132182003-04-09 19:32:45 +00002647Return True if S ends with the specified suffix, False otherwise.\n\
2648With optional start, test S beginning at that position.\n\
2649With optional end, stop comparing S at that position.");
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002650
2651static PyObject *
Fred Drakeba096332000-07-09 07:04:36 +00002652string_endswith(PyStringObject *self, PyObject *args)
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002653{
Guido van Rossum4c08d552000-03-10 22:55:18 +00002654 const char* str = PyString_AS_STRING(self);
Martin v. Löwis18e16552006-02-15 17:27:45 +00002655 Py_ssize_t len = PyString_GET_SIZE(self);
Guido van Rossum4c08d552000-03-10 22:55:18 +00002656 const char* suffix;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002657 Py_ssize_t slen;
2658 Py_ssize_t start = 0;
Martin v. Löwis8ce358f2006-04-13 07:22:51 +00002659 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossum4c08d552000-03-10 22:55:18 +00002660 PyObject *subobj;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002661
Guido van Rossumc6821402000-05-08 14:08:05 +00002662 if (!PyArg_ParseTuple(args, "O|O&O&:endswith", &subobj,
2663 _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
Guido van Rossum4c08d552000-03-10 22:55:18 +00002664 return NULL;
2665 if (PyString_Check(subobj)) {
2666 suffix = PyString_AS_STRING(subobj);
2667 slen = PyString_GET_SIZE(subobj);
2668 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002669#ifdef Py_USING_UNICODE
Marc-André Lemburg3a645e42001-01-16 11:54:12 +00002670 else if (PyUnicode_Check(subobj)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002671 Py_ssize_t rc;
Tim Petersb3d8d1f2001-04-28 05:38:26 +00002672 rc = PyUnicode_Tailmatch((PyObject *)self,
Marc-André Lemburg3a645e42001-01-16 11:54:12 +00002673 subobj, start, end, +1);
2674 if (rc == -1)
2675 return NULL;
2676 else
Guido van Rossum77f6a652002-04-03 22:41:51 +00002677 return PyBool_FromLong((long) rc);
Marc-André Lemburg3a645e42001-01-16 11:54:12 +00002678 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002679#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +00002680 else if (PyObject_AsCharBuffer(subobj, &suffix, &slen))
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002681 return NULL;
2682
Neal Norwitz1f68fc72002-06-14 00:50:42 +00002683 string_adjust_indices(&start, &end, len);
2684
2685 if (end-start < slen || start > len)
Guido van Rossum77f6a652002-04-03 22:41:51 +00002686 return PyBool_FromLong(0);
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002687
Neal Norwitz1f68fc72002-06-14 00:50:42 +00002688 if (end-slen > start)
2689 start = end - slen;
2690 if (end-start >= slen)
2691 return PyBool_FromLong(!memcmp(str+start, suffix, slen));
2692 else
2693 return PyBool_FromLong(0);
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002694}
2695
2696
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002697PyDoc_STRVAR(encode__doc__,
Marc-André Lemburg2d920412001-05-15 12:00:02 +00002698"S.encode([encoding[,errors]]) -> object\n\
Marc-André Lemburg63f3d172000-07-06 11:29:01 +00002699\n\
Marc-André Lemburg2d920412001-05-15 12:00:02 +00002700Encodes S using the codec registered for encoding. encoding defaults\n\
2701to the default encoding. errors may be given to set a different error\n\
Marc-André Lemburg63f3d172000-07-06 11:29:01 +00002702handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002703a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
2704'xmlcharrefreplace' as well as any other name registered with\n\
2705codecs.register_error that is able to handle UnicodeEncodeErrors.");
Marc-André Lemburg63f3d172000-07-06 11:29:01 +00002706
2707static PyObject *
2708string_encode(PyStringObject *self, PyObject *args)
2709{
2710 char *encoding = NULL;
2711 char *errors = NULL;
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002712 PyObject *v;
Tim Petersae1d0c92006-03-17 03:29:34 +00002713
Marc-André Lemburg63f3d172000-07-06 11:29:01 +00002714 if (!PyArg_ParseTuple(args, "|ss:encode", &encoding, &errors))
2715 return NULL;
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002716 v = PyString_AsEncodedObject((PyObject *)self, encoding, errors);
Marc-André Lemburg1dffb122004-07-08 19:13:55 +00002717 if (v == NULL)
2718 goto onError;
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002719 if (!PyString_Check(v) && !PyUnicode_Check(v)) {
2720 PyErr_Format(PyExc_TypeError,
2721 "encoder did not return a string/unicode object "
2722 "(type=%.400s)",
2723 v->ob_type->tp_name);
2724 Py_DECREF(v);
2725 return NULL;
2726 }
2727 return v;
Marc-André Lemburg1dffb122004-07-08 19:13:55 +00002728
2729 onError:
2730 return NULL;
Marc-André Lemburg2d920412001-05-15 12:00:02 +00002731}
2732
2733
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002734PyDoc_STRVAR(decode__doc__,
Marc-André Lemburg2d920412001-05-15 12:00:02 +00002735"S.decode([encoding[,errors]]) -> object\n\
2736\n\
2737Decodes S using the codec registered for encoding. encoding defaults\n\
2738to the default encoding. errors may be given to set a different error\n\
2739handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002740a UnicodeDecodeError. Other possible values are 'ignore' and 'replace'\n\
2741as well as any other name registerd with codecs.register_error that is\n\
2742able to handle UnicodeDecodeErrors.");
Marc-André Lemburg2d920412001-05-15 12:00:02 +00002743
2744static PyObject *
2745string_decode(PyStringObject *self, PyObject *args)
2746{
2747 char *encoding = NULL;
2748 char *errors = NULL;
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002749 PyObject *v;
Tim Petersae1d0c92006-03-17 03:29:34 +00002750
Marc-André Lemburg2d920412001-05-15 12:00:02 +00002751 if (!PyArg_ParseTuple(args, "|ss:decode", &encoding, &errors))
2752 return NULL;
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002753 v = PyString_AsDecodedObject((PyObject *)self, encoding, errors);
Marc-André Lemburg1dffb122004-07-08 19:13:55 +00002754 if (v == NULL)
2755 goto onError;
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002756 if (!PyString_Check(v) && !PyUnicode_Check(v)) {
2757 PyErr_Format(PyExc_TypeError,
2758 "decoder did not return a string/unicode object "
2759 "(type=%.400s)",
2760 v->ob_type->tp_name);
2761 Py_DECREF(v);
2762 return NULL;
2763 }
2764 return v;
Marc-André Lemburg1dffb122004-07-08 19:13:55 +00002765
2766 onError:
2767 return NULL;
Marc-André Lemburg63f3d172000-07-06 11:29:01 +00002768}
2769
2770
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002771PyDoc_STRVAR(expandtabs__doc__,
Guido van Rossum4c08d552000-03-10 22:55:18 +00002772"S.expandtabs([tabsize]) -> string\n\
2773\n\
2774Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002775If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossum4c08d552000-03-10 22:55:18 +00002776
2777static PyObject*
2778string_expandtabs(PyStringObject *self, PyObject *args)
2779{
2780 const char *e, *p;
2781 char *q;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002782 Py_ssize_t i, j;
Guido van Rossum4c08d552000-03-10 22:55:18 +00002783 PyObject *u;
2784 int tabsize = 8;
2785
2786 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
2787 return NULL;
2788
Thomas Wouters7e474022000-07-16 12:04:32 +00002789 /* First pass: determine size of output string */
Guido van Rossum4c08d552000-03-10 22:55:18 +00002790 i = j = 0;
2791 e = PyString_AS_STRING(self) + PyString_GET_SIZE(self);
2792 for (p = PyString_AS_STRING(self); p < e; p++)
2793 if (*p == '\t') {
2794 if (tabsize > 0)
2795 j += tabsize - (j % tabsize);
2796 }
2797 else {
2798 j++;
2799 if (*p == '\n' || *p == '\r') {
2800 i += j;
2801 j = 0;
2802 }
2803 }
2804
2805 /* Second pass: create output string and fill it */
2806 u = PyString_FromStringAndSize(NULL, i + j);
2807 if (!u)
2808 return NULL;
2809
2810 j = 0;
2811 q = PyString_AS_STRING(u);
2812
2813 for (p = PyString_AS_STRING(self); p < e; p++)
2814 if (*p == '\t') {
2815 if (tabsize > 0) {
2816 i = tabsize - (j % tabsize);
2817 j += i;
2818 while (i--)
2819 *q++ = ' ';
2820 }
2821 }
2822 else {
2823 j++;
2824 *q++ = *p;
2825 if (*p == '\n' || *p == '\r')
2826 j = 0;
2827 }
2828
2829 return u;
2830}
2831
Tim Peters8fa5dd02001-09-12 02:18:30 +00002832static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00002833pad(PyStringObject *self, Py_ssize_t left, Py_ssize_t right, char fill)
Guido van Rossum4c08d552000-03-10 22:55:18 +00002834{
2835 PyObject *u;
2836
2837 if (left < 0)
2838 left = 0;
2839 if (right < 0)
2840 right = 0;
2841
Tim Peters8fa5dd02001-09-12 02:18:30 +00002842 if (left == 0 && right == 0 && PyString_CheckExact(self)) {
Guido van Rossum4c08d552000-03-10 22:55:18 +00002843 Py_INCREF(self);
2844 return (PyObject *)self;
2845 }
2846
Tim Petersb3d8d1f2001-04-28 05:38:26 +00002847 u = PyString_FromStringAndSize(NULL,
Guido van Rossum4c08d552000-03-10 22:55:18 +00002848 left + PyString_GET_SIZE(self) + right);
2849 if (u) {
2850 if (left)
2851 memset(PyString_AS_STRING(u), fill, left);
Tim Petersb3d8d1f2001-04-28 05:38:26 +00002852 memcpy(PyString_AS_STRING(u) + left,
2853 PyString_AS_STRING(self),
Guido van Rossum4c08d552000-03-10 22:55:18 +00002854 PyString_GET_SIZE(self));
2855 if (right)
2856 memset(PyString_AS_STRING(u) + left + PyString_GET_SIZE(self),
2857 fill, right);
2858 }
2859
2860 return u;
2861}
2862
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002863PyDoc_STRVAR(ljust__doc__,
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00002864"S.ljust(width[, fillchar]) -> string\n"
Tim Peters8fa5dd02001-09-12 02:18:30 +00002865"\n"
2866"Return S left justified in a string of length width. Padding is\n"
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00002867"done using the specified fill character (default is a space).");
Guido van Rossum4c08d552000-03-10 22:55:18 +00002868
2869static PyObject *
2870string_ljust(PyStringObject *self, PyObject *args)
2871{
Thomas Wouters4abb3662006-04-19 14:50:15 +00002872 Py_ssize_t width;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00002873 char fillchar = ' ';
2874
Thomas Wouters4abb3662006-04-19 14:50:15 +00002875 if (!PyArg_ParseTuple(args, "n|c:ljust", &width, &fillchar))
Guido van Rossum4c08d552000-03-10 22:55:18 +00002876 return NULL;
2877
Tim Peters8fa5dd02001-09-12 02:18:30 +00002878 if (PyString_GET_SIZE(self) >= width && PyString_CheckExact(self)) {
Guido van Rossum4c08d552000-03-10 22:55:18 +00002879 Py_INCREF(self);
2880 return (PyObject*) self;
2881 }
2882
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00002883 return pad(self, 0, width - PyString_GET_SIZE(self), fillchar);
Guido van Rossum4c08d552000-03-10 22:55:18 +00002884}
2885
2886
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002887PyDoc_STRVAR(rjust__doc__,
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00002888"S.rjust(width[, fillchar]) -> string\n"
Tim Peters8fa5dd02001-09-12 02:18:30 +00002889"\n"
2890"Return S right justified in a string of length width. Padding is\n"
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00002891"done using the specified fill character (default is a space)");
Guido van Rossum4c08d552000-03-10 22:55:18 +00002892
2893static PyObject *
2894string_rjust(PyStringObject *self, PyObject *args)
2895{
Thomas Wouters4abb3662006-04-19 14:50:15 +00002896 Py_ssize_t width;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00002897 char fillchar = ' ';
2898
Thomas Wouters4abb3662006-04-19 14:50:15 +00002899 if (!PyArg_ParseTuple(args, "n|c:rjust", &width, &fillchar))
Guido van Rossum4c08d552000-03-10 22:55:18 +00002900 return NULL;
2901
Tim Peters8fa5dd02001-09-12 02:18:30 +00002902 if (PyString_GET_SIZE(self) >= width && PyString_CheckExact(self)) {
Guido van Rossum4c08d552000-03-10 22:55:18 +00002903 Py_INCREF(self);
2904 return (PyObject*) self;
2905 }
2906
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00002907 return pad(self, width - PyString_GET_SIZE(self), 0, fillchar);
Guido van Rossum4c08d552000-03-10 22:55:18 +00002908}
2909
2910
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002911PyDoc_STRVAR(center__doc__,
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00002912"S.center(width[, fillchar]) -> string\n"
Tim Peters8fa5dd02001-09-12 02:18:30 +00002913"\n"
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00002914"Return S centered in a string of length width. Padding is\n"
2915"done using the specified fill character (default is a space)");
Guido van Rossum4c08d552000-03-10 22:55:18 +00002916
2917static PyObject *
2918string_center(PyStringObject *self, PyObject *args)
2919{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002920 Py_ssize_t marg, left;
Thomas Wouters4abb3662006-04-19 14:50:15 +00002921 Py_ssize_t width;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00002922 char fillchar = ' ';
Guido van Rossum4c08d552000-03-10 22:55:18 +00002923
Thomas Wouters4abb3662006-04-19 14:50:15 +00002924 if (!PyArg_ParseTuple(args, "n|c:center", &width, &fillchar))
Guido van Rossum4c08d552000-03-10 22:55:18 +00002925 return NULL;
2926
Tim Peters8fa5dd02001-09-12 02:18:30 +00002927 if (PyString_GET_SIZE(self) >= width && PyString_CheckExact(self)) {
Guido van Rossum4c08d552000-03-10 22:55:18 +00002928 Py_INCREF(self);
2929 return (PyObject*) self;
2930 }
2931
2932 marg = width - PyString_GET_SIZE(self);
2933 left = marg / 2 + (marg & width & 1);
2934
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00002935 return pad(self, left, marg - left, fillchar);
Guido van Rossum4c08d552000-03-10 22:55:18 +00002936}
2937
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002938PyDoc_STRVAR(zfill__doc__,
Walter Dörwald068325e2002-04-15 13:36:47 +00002939"S.zfill(width) -> string\n"
2940"\n"
2941"Pad a numeric string S with zeros on the left, to fill a field\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002942"of the specified width. The string S is never truncated.");
Walter Dörwald068325e2002-04-15 13:36:47 +00002943
2944static PyObject *
2945string_zfill(PyStringObject *self, PyObject *args)
2946{
Martin v. Löwiseb079f12006-02-16 14:32:27 +00002947 Py_ssize_t fill;
Walter Dörwald068325e2002-04-15 13:36:47 +00002948 PyObject *s;
Guido van Rossum3aa3fc42002-04-15 13:48:52 +00002949 char *p;
Thomas Wouters4abb3662006-04-19 14:50:15 +00002950 Py_ssize_t width;
Walter Dörwald068325e2002-04-15 13:36:47 +00002951
Thomas Wouters4abb3662006-04-19 14:50:15 +00002952 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Walter Dörwald068325e2002-04-15 13:36:47 +00002953 return NULL;
2954
2955 if (PyString_GET_SIZE(self) >= width) {
Walter Dörwald0fe940c2002-04-15 18:42:15 +00002956 if (PyString_CheckExact(self)) {
2957 Py_INCREF(self);
2958 return (PyObject*) self;
2959 }
2960 else
2961 return PyString_FromStringAndSize(
2962 PyString_AS_STRING(self),
2963 PyString_GET_SIZE(self)
2964 );
Walter Dörwald068325e2002-04-15 13:36:47 +00002965 }
2966
2967 fill = width - PyString_GET_SIZE(self);
2968
2969 s = pad(self, fill, 0, '0');
2970
2971 if (s == NULL)
2972 return NULL;
2973
2974 p = PyString_AS_STRING(s);
2975 if (p[fill] == '+' || p[fill] == '-') {
2976 /* move sign to beginning of string */
2977 p[0] = p[fill];
2978 p[fill] = '0';
2979 }
2980
2981 return (PyObject*) s;
2982}
2983
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002984PyDoc_STRVAR(isspace__doc__,
Martin v. Löwis6828e182003-10-18 09:55:08 +00002985"S.isspace() -> bool\n\
2986\n\
2987Return True if all characters in S are whitespace\n\
2988and there is at least one character in S, False otherwise.");
Guido van Rossum4c08d552000-03-10 22:55:18 +00002989
2990static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002991string_isspace(PyStringObject *self)
Guido van Rossum4c08d552000-03-10 22:55:18 +00002992{
Fred Drakeba096332000-07-09 07:04:36 +00002993 register const unsigned char *p
2994 = (unsigned char *) PyString_AS_STRING(self);
Guido van Rossumb8f820c2000-05-05 20:44:24 +00002995 register const unsigned char *e;
Guido van Rossum4c08d552000-03-10 22:55:18 +00002996
Guido van Rossum4c08d552000-03-10 22:55:18 +00002997 /* Shortcut for single character strings */
2998 if (PyString_GET_SIZE(self) == 1 &&
2999 isspace(*p))
Guido van Rossum77f6a652002-04-03 22:41:51 +00003000 return PyBool_FromLong(1);
Guido van Rossum4c08d552000-03-10 22:55:18 +00003001
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00003002 /* Special case for empty strings */
3003 if (PyString_GET_SIZE(self) == 0)
Guido van Rossum77f6a652002-04-03 22:41:51 +00003004 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00003005
Guido van Rossum4c08d552000-03-10 22:55:18 +00003006 e = p + PyString_GET_SIZE(self);
3007 for (; p < e; p++) {
3008 if (!isspace(*p))
Guido van Rossum77f6a652002-04-03 22:41:51 +00003009 return PyBool_FromLong(0);
Guido van Rossum4c08d552000-03-10 22:55:18 +00003010 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00003011 return PyBool_FromLong(1);
Guido van Rossum4c08d552000-03-10 22:55:18 +00003012}
3013
3014
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003015PyDoc_STRVAR(isalpha__doc__,
Guido van Rossum77f6a652002-04-03 22:41:51 +00003016"S.isalpha() -> bool\n\
Marc-André Lemburg4027f8f2000-07-05 09:47:46 +00003017\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00003018Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003019and there is at least one character in S, False otherwise.");
Marc-André Lemburg4027f8f2000-07-05 09:47:46 +00003020
3021static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00003022string_isalpha(PyStringObject *self)
Marc-André Lemburg4027f8f2000-07-05 09:47:46 +00003023{
Fred Drakeba096332000-07-09 07:04:36 +00003024 register const unsigned char *p
3025 = (unsigned char *) PyString_AS_STRING(self);
Marc-André Lemburg4027f8f2000-07-05 09:47:46 +00003026 register const unsigned char *e;
3027
Marc-André Lemburg4027f8f2000-07-05 09:47:46 +00003028 /* Shortcut for single character strings */
3029 if (PyString_GET_SIZE(self) == 1 &&
3030 isalpha(*p))
Guido van Rossum77f6a652002-04-03 22:41:51 +00003031 return PyBool_FromLong(1);
Marc-André Lemburg4027f8f2000-07-05 09:47:46 +00003032
3033 /* Special case for empty strings */
3034 if (PyString_GET_SIZE(self) == 0)
Guido van Rossum77f6a652002-04-03 22:41:51 +00003035 return PyBool_FromLong(0);
Marc-André Lemburg4027f8f2000-07-05 09:47:46 +00003036
3037 e = p + PyString_GET_SIZE(self);
3038 for (; p < e; p++) {
3039 if (!isalpha(*p))
Guido van Rossum77f6a652002-04-03 22:41:51 +00003040 return PyBool_FromLong(0);
Marc-André Lemburg4027f8f2000-07-05 09:47:46 +00003041 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00003042 return PyBool_FromLong(1);
Marc-André Lemburg4027f8f2000-07-05 09:47:46 +00003043}
3044
3045
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003046PyDoc_STRVAR(isalnum__doc__,
Guido van Rossum77f6a652002-04-03 22:41:51 +00003047"S.isalnum() -> bool\n\
Marc-André Lemburg4027f8f2000-07-05 09:47:46 +00003048\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00003049Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003050and there is at least one character in S, False otherwise.");
Marc-André Lemburg4027f8f2000-07-05 09:47:46 +00003051
3052static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00003053string_isalnum(PyStringObject *self)
Marc-André Lemburg4027f8f2000-07-05 09:47:46 +00003054{
Fred Drakeba096332000-07-09 07:04:36 +00003055 register const unsigned char *p
3056 = (unsigned char *) PyString_AS_STRING(self);
Marc-André Lemburg4027f8f2000-07-05 09:47:46 +00003057 register const unsigned char *e;
3058
Marc-André Lemburg4027f8f2000-07-05 09:47:46 +00003059 /* Shortcut for single character strings */
3060 if (PyString_GET_SIZE(self) == 1 &&
3061 isalnum(*p))
Guido van Rossum77f6a652002-04-03 22:41:51 +00003062 return PyBool_FromLong(1);
Marc-André Lemburg4027f8f2000-07-05 09:47:46 +00003063
3064 /* Special case for empty strings */
3065 if (PyString_GET_SIZE(self) == 0)
Guido van Rossum77f6a652002-04-03 22:41:51 +00003066 return PyBool_FromLong(0);
Marc-André Lemburg4027f8f2000-07-05 09:47:46 +00003067
3068 e = p + PyString_GET_SIZE(self);
3069 for (; p < e; p++) {
3070 if (!isalnum(*p))
Guido van Rossum77f6a652002-04-03 22:41:51 +00003071 return PyBool_FromLong(0);
Marc-André Lemburg4027f8f2000-07-05 09:47:46 +00003072 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00003073 return PyBool_FromLong(1);
Marc-André Lemburg4027f8f2000-07-05 09:47:46 +00003074}
3075
3076
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003077PyDoc_STRVAR(isdigit__doc__,
Guido van Rossum77f6a652002-04-03 22:41:51 +00003078"S.isdigit() -> bool\n\
Guido van Rossum4c08d552000-03-10 22:55:18 +00003079\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00003080Return True if all characters in S are digits\n\
3081and there is at least one character in S, False otherwise.");
Guido van Rossum4c08d552000-03-10 22:55:18 +00003082
3083static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00003084string_isdigit(PyStringObject *self)
Guido van Rossum4c08d552000-03-10 22:55:18 +00003085{
Fred Drakeba096332000-07-09 07:04:36 +00003086 register const unsigned char *p
3087 = (unsigned char *) PyString_AS_STRING(self);
Guido van Rossumb8f820c2000-05-05 20:44:24 +00003088 register const unsigned char *e;
Guido van Rossum4c08d552000-03-10 22:55:18 +00003089
Guido van Rossum4c08d552000-03-10 22:55:18 +00003090 /* Shortcut for single character strings */
3091 if (PyString_GET_SIZE(self) == 1 &&
3092 isdigit(*p))
Guido van Rossum77f6a652002-04-03 22:41:51 +00003093 return PyBool_FromLong(1);
Guido van Rossum4c08d552000-03-10 22:55:18 +00003094
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00003095 /* Special case for empty strings */
3096 if (PyString_GET_SIZE(self) == 0)
Guido van Rossum77f6a652002-04-03 22:41:51 +00003097 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00003098
Guido van Rossum4c08d552000-03-10 22:55:18 +00003099 e = p + PyString_GET_SIZE(self);
3100 for (; p < e; p++) {
3101 if (!isdigit(*p))
Guido van Rossum77f6a652002-04-03 22:41:51 +00003102 return PyBool_FromLong(0);
Guido van Rossum4c08d552000-03-10 22:55:18 +00003103 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00003104 return PyBool_FromLong(1);
Guido van Rossum4c08d552000-03-10 22:55:18 +00003105}
3106
3107
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003108PyDoc_STRVAR(islower__doc__,
Guido van Rossum77f6a652002-04-03 22:41:51 +00003109"S.islower() -> bool\n\
Guido van Rossum4c08d552000-03-10 22:55:18 +00003110\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +00003111Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003112at least one cased character in S, False otherwise.");
Guido van Rossum4c08d552000-03-10 22:55:18 +00003113
3114static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00003115string_islower(PyStringObject *self)
Guido van Rossum4c08d552000-03-10 22:55:18 +00003116{
Fred Drakeba096332000-07-09 07:04:36 +00003117 register const unsigned char *p
3118 = (unsigned char *) PyString_AS_STRING(self);
Guido van Rossumb8f820c2000-05-05 20:44:24 +00003119 register const unsigned char *e;
Guido van Rossum4c08d552000-03-10 22:55:18 +00003120 int cased;
3121
Guido van Rossum4c08d552000-03-10 22:55:18 +00003122 /* Shortcut for single character strings */
3123 if (PyString_GET_SIZE(self) == 1)
Guido van Rossum77f6a652002-04-03 22:41:51 +00003124 return PyBool_FromLong(islower(*p) != 0);
Guido van Rossum4c08d552000-03-10 22:55:18 +00003125
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00003126 /* Special case for empty strings */
3127 if (PyString_GET_SIZE(self) == 0)
Guido van Rossum77f6a652002-04-03 22:41:51 +00003128 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00003129
Guido van Rossum4c08d552000-03-10 22:55:18 +00003130 e = p + PyString_GET_SIZE(self);
3131 cased = 0;
3132 for (; p < e; p++) {
3133 if (isupper(*p))
Guido van Rossum77f6a652002-04-03 22:41:51 +00003134 return PyBool_FromLong(0);
Guido van Rossum4c08d552000-03-10 22:55:18 +00003135 else if (!cased && islower(*p))
3136 cased = 1;
3137 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00003138 return PyBool_FromLong(cased);
Guido van Rossum4c08d552000-03-10 22:55:18 +00003139}
3140
3141
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003142PyDoc_STRVAR(isupper__doc__,
Guido van Rossum77f6a652002-04-03 22:41:51 +00003143"S.isupper() -> bool\n\
Guido van Rossum4c08d552000-03-10 22:55:18 +00003144\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00003145Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003146at least one cased character in S, False otherwise.");
Guido van Rossum4c08d552000-03-10 22:55:18 +00003147
3148static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00003149string_isupper(PyStringObject *self)
Guido van Rossum4c08d552000-03-10 22:55:18 +00003150{
Fred Drakeba096332000-07-09 07:04:36 +00003151 register const unsigned char *p
3152 = (unsigned char *) PyString_AS_STRING(self);
Guido van Rossumb8f820c2000-05-05 20:44:24 +00003153 register const unsigned char *e;
Guido van Rossum4c08d552000-03-10 22:55:18 +00003154 int cased;
3155
Guido van Rossum4c08d552000-03-10 22:55:18 +00003156 /* Shortcut for single character strings */
3157 if (PyString_GET_SIZE(self) == 1)
Guido van Rossum77f6a652002-04-03 22:41:51 +00003158 return PyBool_FromLong(isupper(*p) != 0);
Guido van Rossum4c08d552000-03-10 22:55:18 +00003159
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00003160 /* Special case for empty strings */
3161 if (PyString_GET_SIZE(self) == 0)
Guido van Rossum77f6a652002-04-03 22:41:51 +00003162 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00003163
Guido van Rossum4c08d552000-03-10 22:55:18 +00003164 e = p + PyString_GET_SIZE(self);
3165 cased = 0;
3166 for (; p < e; p++) {
3167 if (islower(*p))
Guido van Rossum77f6a652002-04-03 22:41:51 +00003168 return PyBool_FromLong(0);
Guido van Rossum4c08d552000-03-10 22:55:18 +00003169 else if (!cased && isupper(*p))
3170 cased = 1;
3171 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00003172 return PyBool_FromLong(cased);
Guido van Rossum4c08d552000-03-10 22:55:18 +00003173}
3174
3175
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003176PyDoc_STRVAR(istitle__doc__,
Guido van Rossum77f6a652002-04-03 22:41:51 +00003177"S.istitle() -> bool\n\
Guido van Rossum4c08d552000-03-10 22:55:18 +00003178\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00003179Return True if S is a titlecased string and there is at least one\n\
3180character in S, i.e. uppercase characters may only follow uncased\n\
3181characters and lowercase characters only cased ones. Return False\n\
3182otherwise.");
Guido van Rossum4c08d552000-03-10 22:55:18 +00003183
3184static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00003185string_istitle(PyStringObject *self, PyObject *uncased)
Guido van Rossum4c08d552000-03-10 22:55:18 +00003186{
Fred Drakeba096332000-07-09 07:04:36 +00003187 register const unsigned char *p
3188 = (unsigned char *) PyString_AS_STRING(self);
Guido van Rossumb8f820c2000-05-05 20:44:24 +00003189 register const unsigned char *e;
Guido van Rossum4c08d552000-03-10 22:55:18 +00003190 int cased, previous_is_cased;
3191
Guido van Rossum4c08d552000-03-10 22:55:18 +00003192 /* Shortcut for single character strings */
3193 if (PyString_GET_SIZE(self) == 1)
Guido van Rossum77f6a652002-04-03 22:41:51 +00003194 return PyBool_FromLong(isupper(*p) != 0);
Guido van Rossum4c08d552000-03-10 22:55:18 +00003195
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00003196 /* Special case for empty strings */
3197 if (PyString_GET_SIZE(self) == 0)
Guido van Rossum77f6a652002-04-03 22:41:51 +00003198 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00003199
Guido van Rossum4c08d552000-03-10 22:55:18 +00003200 e = p + PyString_GET_SIZE(self);
3201 cased = 0;
3202 previous_is_cased = 0;
3203 for (; p < e; p++) {
Guido van Rossumb8f820c2000-05-05 20:44:24 +00003204 register const unsigned char ch = *p;
Guido van Rossum4c08d552000-03-10 22:55:18 +00003205
3206 if (isupper(ch)) {
3207 if (previous_is_cased)
Guido van Rossum77f6a652002-04-03 22:41:51 +00003208 return PyBool_FromLong(0);
Guido van Rossum4c08d552000-03-10 22:55:18 +00003209 previous_is_cased = 1;
3210 cased = 1;
3211 }
3212 else if (islower(ch)) {
3213 if (!previous_is_cased)
Guido van Rossum77f6a652002-04-03 22:41:51 +00003214 return PyBool_FromLong(0);
Guido van Rossum4c08d552000-03-10 22:55:18 +00003215 previous_is_cased = 1;
3216 cased = 1;
3217 }
3218 else
3219 previous_is_cased = 0;
3220 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00003221 return PyBool_FromLong(cased);
Guido van Rossum4c08d552000-03-10 22:55:18 +00003222}
3223
3224
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003225PyDoc_STRVAR(splitlines__doc__,
Fred Drake2bae4fa2001-10-13 15:57:55 +00003226"S.splitlines([keepends]) -> list of strings\n\
Guido van Rossum4c08d552000-03-10 22:55:18 +00003227\n\
3228Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossumf0b7b042000-04-11 15:39:26 +00003229Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003230is given and true.");
Guido van Rossum4c08d552000-03-10 22:55:18 +00003231
Guido van Rossum4c08d552000-03-10 22:55:18 +00003232static PyObject*
3233string_splitlines(PyStringObject *self, PyObject *args)
3234{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003235 register Py_ssize_t i;
3236 register Py_ssize_t j;
3237 Py_ssize_t len;
Guido van Rossumf0b7b042000-04-11 15:39:26 +00003238 int keepends = 0;
Guido van Rossum4c08d552000-03-10 22:55:18 +00003239 PyObject *list;
3240 PyObject *str;
3241 char *data;
3242
Guido van Rossumf0b7b042000-04-11 15:39:26 +00003243 if (!PyArg_ParseTuple(args, "|i:splitlines", &keepends))
Guido van Rossum4c08d552000-03-10 22:55:18 +00003244 return NULL;
3245
3246 data = PyString_AS_STRING(self);
3247 len = PyString_GET_SIZE(self);
3248
Guido van Rossum4c08d552000-03-10 22:55:18 +00003249 list = PyList_New(0);
3250 if (!list)
3251 goto onError;
3252
3253 for (i = j = 0; i < len; ) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00003254 Py_ssize_t eol;
Guido van Rossumf0b7b042000-04-11 15:39:26 +00003255
Guido van Rossum4c08d552000-03-10 22:55:18 +00003256 /* Find a line and append it */
3257 while (i < len && data[i] != '\n' && data[i] != '\r')
3258 i++;
Guido van Rossum4c08d552000-03-10 22:55:18 +00003259
3260 /* Skip the line break reading CRLF as one line break */
Guido van Rossumf0b7b042000-04-11 15:39:26 +00003261 eol = i;
Guido van Rossum4c08d552000-03-10 22:55:18 +00003262 if (i < len) {
3263 if (data[i] == '\r' && i + 1 < len &&
3264 data[i+1] == '\n')
3265 i += 2;
3266 else
3267 i++;
Guido van Rossumf0b7b042000-04-11 15:39:26 +00003268 if (keepends)
3269 eol = i;
Guido van Rossum4c08d552000-03-10 22:55:18 +00003270 }
Guido van Rossumf0b7b042000-04-11 15:39:26 +00003271 SPLIT_APPEND(data, j, eol);
Guido van Rossum4c08d552000-03-10 22:55:18 +00003272 j = i;
3273 }
3274 if (j < len) {
3275 SPLIT_APPEND(data, j, len);
3276 }
3277
3278 return list;
3279
3280 onError:
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003281 Py_XDECREF(list);
Guido van Rossum4c08d552000-03-10 22:55:18 +00003282 return NULL;
3283}
3284
3285#undef SPLIT_APPEND
3286
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003287static PyObject *
3288string_getnewargs(PyStringObject *v)
3289{
3290 return Py_BuildValue("(s#)", v->ob_sval, v->ob_size);
3291}
3292
Barry Warsaw226ae6c1999-10-12 19:54:53 +00003293
Tim Petersb3d8d1f2001-04-28 05:38:26 +00003294static PyMethodDef
Barry Warsaw226ae6c1999-10-12 19:54:53 +00003295string_methods[] = {
Guido van Rossum4c08d552000-03-10 22:55:18 +00003296 /* Counterparts of the obsolete stropmodule functions; except
3297 string.maketrans(). */
Guido van Rossum3aa3fc42002-04-15 13:48:52 +00003298 {"join", (PyCFunction)string_join, METH_O, join__doc__},
3299 {"split", (PyCFunction)string_split, METH_VARARGS, split__doc__},
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00003300 {"rsplit", (PyCFunction)string_rsplit, METH_VARARGS, rsplit__doc__},
Guido van Rossum3aa3fc42002-04-15 13:48:52 +00003301 {"lower", (PyCFunction)string_lower, METH_NOARGS, lower__doc__},
3302 {"upper", (PyCFunction)string_upper, METH_NOARGS, upper__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00003303 {"islower", (PyCFunction)string_islower, METH_NOARGS, islower__doc__},
3304 {"isupper", (PyCFunction)string_isupper, METH_NOARGS, isupper__doc__},
3305 {"isspace", (PyCFunction)string_isspace, METH_NOARGS, isspace__doc__},
3306 {"isdigit", (PyCFunction)string_isdigit, METH_NOARGS, isdigit__doc__},
3307 {"istitle", (PyCFunction)string_istitle, METH_NOARGS, istitle__doc__},
3308 {"isalpha", (PyCFunction)string_isalpha, METH_NOARGS, isalpha__doc__},
3309 {"isalnum", (PyCFunction)string_isalnum, METH_NOARGS, isalnum__doc__},
Guido van Rossum3aa3fc42002-04-15 13:48:52 +00003310 {"capitalize", (PyCFunction)string_capitalize, METH_NOARGS,
3311 capitalize__doc__},
3312 {"count", (PyCFunction)string_count, METH_VARARGS, count__doc__},
3313 {"endswith", (PyCFunction)string_endswith, METH_VARARGS,
3314 endswith__doc__},
3315 {"find", (PyCFunction)string_find, METH_VARARGS, find__doc__},
3316 {"index", (PyCFunction)string_index, METH_VARARGS, index__doc__},
3317 {"lstrip", (PyCFunction)string_lstrip, METH_VARARGS, lstrip__doc__},
3318 {"replace", (PyCFunction)string_replace, METH_VARARGS, replace__doc__},
3319 {"rfind", (PyCFunction)string_rfind, METH_VARARGS, rfind__doc__},
3320 {"rindex", (PyCFunction)string_rindex, METH_VARARGS, rindex__doc__},
3321 {"rstrip", (PyCFunction)string_rstrip, METH_VARARGS, rstrip__doc__},
3322 {"startswith", (PyCFunction)string_startswith, METH_VARARGS,
3323 startswith__doc__},
3324 {"strip", (PyCFunction)string_strip, METH_VARARGS, strip__doc__},
3325 {"swapcase", (PyCFunction)string_swapcase, METH_NOARGS,
3326 swapcase__doc__},
3327 {"translate", (PyCFunction)string_translate, METH_VARARGS,
3328 translate__doc__},
3329 {"title", (PyCFunction)string_title, METH_NOARGS, title__doc__},
3330 {"ljust", (PyCFunction)string_ljust, METH_VARARGS, ljust__doc__},
3331 {"rjust", (PyCFunction)string_rjust, METH_VARARGS, rjust__doc__},
3332 {"center", (PyCFunction)string_center, METH_VARARGS, center__doc__},
3333 {"zfill", (PyCFunction)string_zfill, METH_VARARGS, zfill__doc__},
3334 {"encode", (PyCFunction)string_encode, METH_VARARGS, encode__doc__},
3335 {"decode", (PyCFunction)string_decode, METH_VARARGS, decode__doc__},
3336 {"expandtabs", (PyCFunction)string_expandtabs, METH_VARARGS,
3337 expandtabs__doc__},
3338 {"splitlines", (PyCFunction)string_splitlines, METH_VARARGS,
3339 splitlines__doc__},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003340 {"__getnewargs__", (PyCFunction)string_getnewargs, METH_NOARGS},
Barry Warsaw226ae6c1999-10-12 19:54:53 +00003341 {NULL, NULL} /* sentinel */
3342};
3343
Jeremy Hylton938ace62002-07-17 16:30:39 +00003344static PyObject *
Guido van Rossumae960af2001-08-30 03:11:59 +00003345str_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
3346
Barry Warsaw226ae6c1999-10-12 19:54:53 +00003347static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003348string_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Barry Warsaw226ae6c1999-10-12 19:54:53 +00003349{
Tim Peters6d6c1a32001-08-02 04:15:00 +00003350 PyObject *x = NULL;
Martin v. Löwis15e62742006-02-27 16:46:16 +00003351 static char *kwlist[] = {"object", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00003352
Guido van Rossumae960af2001-08-30 03:11:59 +00003353 if (type != &PyString_Type)
3354 return str_subtype_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003355 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:str", kwlist, &x))
3356 return NULL;
3357 if (x == NULL)
3358 return PyString_FromString("");
3359 return PyObject_Str(x);
Barry Warsaw226ae6c1999-10-12 19:54:53 +00003360}
3361
Guido van Rossumae960af2001-08-30 03:11:59 +00003362static PyObject *
3363str_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3364{
Tim Petersaf90b3e2001-09-12 05:18:58 +00003365 PyObject *tmp, *pnew;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003366 Py_ssize_t n;
Guido van Rossumae960af2001-08-30 03:11:59 +00003367
3368 assert(PyType_IsSubtype(type, &PyString_Type));
3369 tmp = string_new(&PyString_Type, args, kwds);
3370 if (tmp == NULL)
3371 return NULL;
Tim Peters5a49ade2001-09-11 01:41:59 +00003372 assert(PyString_CheckExact(tmp));
Tim Petersaf90b3e2001-09-12 05:18:58 +00003373 n = PyString_GET_SIZE(tmp);
3374 pnew = type->tp_alloc(type, n);
3375 if (pnew != NULL) {
3376 memcpy(PyString_AS_STRING(pnew), PyString_AS_STRING(tmp), n+1);
Tim Petersaf90b3e2001-09-12 05:18:58 +00003377 ((PyStringObject *)pnew)->ob_shash =
3378 ((PyStringObject *)tmp)->ob_shash;
Guido van Rossum45ec02a2002-08-19 21:43:18 +00003379 ((PyStringObject *)pnew)->ob_sstate = SSTATE_NOT_INTERNED;
Tim Petersaf90b3e2001-09-12 05:18:58 +00003380 }
Guido van Rossum29d55a32001-08-31 16:11:15 +00003381 Py_DECREF(tmp);
Tim Petersaf90b3e2001-09-12 05:18:58 +00003382 return pnew;
Guido van Rossumae960af2001-08-30 03:11:59 +00003383}
3384
Guido van Rossumcacfc072002-05-24 19:01:59 +00003385static PyObject *
3386basestring_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3387{
3388 PyErr_SetString(PyExc_TypeError,
Neal Norwitz32a7e7f2002-05-31 19:58:02 +00003389 "The basestring type cannot be instantiated");
Guido van Rossumcacfc072002-05-24 19:01:59 +00003390 return NULL;
3391}
3392
Neil Schemenauera6cd4e62002-11-18 16:09:38 +00003393static PyObject *
3394string_mod(PyObject *v, PyObject *w)
3395{
3396 if (!PyString_Check(v)) {
3397 Py_INCREF(Py_NotImplemented);
3398 return Py_NotImplemented;
3399 }
3400 return PyString_Format(v, w);
3401}
3402
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003403PyDoc_STRVAR(basestring_doc,
3404"Type basestring cannot be instantiated; it is the base for str and unicode.");
Guido van Rossumcacfc072002-05-24 19:01:59 +00003405
Neil Schemenauera6cd4e62002-11-18 16:09:38 +00003406static PyNumberMethods string_as_number = {
3407 0, /*nb_add*/
3408 0, /*nb_subtract*/
3409 0, /*nb_multiply*/
3410 0, /*nb_divide*/
3411 string_mod, /*nb_remainder*/
3412};
3413
3414
Guido van Rossumcacfc072002-05-24 19:01:59 +00003415PyTypeObject PyBaseString_Type = {
3416 PyObject_HEAD_INIT(&PyType_Type)
3417 0,
Neal Norwitz32a7e7f2002-05-31 19:58:02 +00003418 "basestring",
Guido van Rossumcacfc072002-05-24 19:01:59 +00003419 0,
3420 0,
3421 0, /* tp_dealloc */
3422 0, /* tp_print */
3423 0, /* tp_getattr */
3424 0, /* tp_setattr */
3425 0, /* tp_compare */
3426 0, /* tp_repr */
3427 0, /* tp_as_number */
3428 0, /* tp_as_sequence */
3429 0, /* tp_as_mapping */
3430 0, /* tp_hash */
3431 0, /* tp_call */
3432 0, /* tp_str */
3433 0, /* tp_getattro */
3434 0, /* tp_setattro */
3435 0, /* tp_as_buffer */
3436 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
3437 basestring_doc, /* tp_doc */
3438 0, /* tp_traverse */
3439 0, /* tp_clear */
3440 0, /* tp_richcompare */
3441 0, /* tp_weaklistoffset */
3442 0, /* tp_iter */
3443 0, /* tp_iternext */
3444 0, /* tp_methods */
3445 0, /* tp_members */
3446 0, /* tp_getset */
3447 &PyBaseObject_Type, /* tp_base */
3448 0, /* tp_dict */
3449 0, /* tp_descr_get */
3450 0, /* tp_descr_set */
3451 0, /* tp_dictoffset */
3452 0, /* tp_init */
3453 0, /* tp_alloc */
3454 basestring_new, /* tp_new */
3455 0, /* tp_free */
3456};
3457
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003458PyDoc_STRVAR(string_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00003459"str(object) -> string\n\
3460\n\
3461Return a nice string representation of the object.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003462If the argument is a string, the return value is the same object.");
Barry Warsaw226ae6c1999-10-12 19:54:53 +00003463
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003464PyTypeObject PyString_Type = {
3465 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003466 0,
Tim Peters6d6c1a32001-08-02 04:15:00 +00003467 "str",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003468 sizeof(PyStringObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003469 sizeof(char),
Georg Brandl347b3002006-03-30 11:57:00 +00003470 string_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003471 (printfunc)string_print, /* tp_print */
3472 0, /* tp_getattr */
3473 0, /* tp_setattr */
3474 0, /* tp_compare */
Georg Brandl347b3002006-03-30 11:57:00 +00003475 string_repr, /* tp_repr */
Neil Schemenauera6cd4e62002-11-18 16:09:38 +00003476 &string_as_number, /* tp_as_number */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003477 &string_as_sequence, /* tp_as_sequence */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00003478 &string_as_mapping, /* tp_as_mapping */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003479 (hashfunc)string_hash, /* tp_hash */
3480 0, /* tp_call */
Georg Brandl347b3002006-03-30 11:57:00 +00003481 string_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003482 PyObject_GenericGetAttr, /* tp_getattro */
3483 0, /* tp_setattro */
3484 &string_as_buffer, /* tp_as_buffer */
Tim Petersae1d0c92006-03-17 03:29:34 +00003485 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
Neil Schemenauera6cd4e62002-11-18 16:09:38 +00003486 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003487 string_doc, /* tp_doc */
3488 0, /* tp_traverse */
3489 0, /* tp_clear */
3490 (richcmpfunc)string_richcompare, /* tp_richcompare */
3491 0, /* tp_weaklistoffset */
3492 0, /* tp_iter */
3493 0, /* tp_iternext */
3494 string_methods, /* tp_methods */
3495 0, /* tp_members */
3496 0, /* tp_getset */
Guido van Rossumcacfc072002-05-24 19:01:59 +00003497 &PyBaseString_Type, /* tp_base */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003498 0, /* tp_dict */
3499 0, /* tp_descr_get */
3500 0, /* tp_descr_set */
3501 0, /* tp_dictoffset */
3502 0, /* tp_init */
3503 0, /* tp_alloc */
3504 string_new, /* tp_new */
Neil Schemenauer510492e2002-04-12 03:05:19 +00003505 PyObject_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003506};
3507
3508void
Fred Drakeba096332000-07-09 07:04:36 +00003509PyString_Concat(register PyObject **pv, register PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003510{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003511 register PyObject *v;
Guido van Rossum013142a1994-08-30 08:19:36 +00003512 if (*pv == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003513 return;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003514 if (w == NULL || !PyString_Check(*pv)) {
3515 Py_DECREF(*pv);
Guido van Rossum013142a1994-08-30 08:19:36 +00003516 *pv = NULL;
3517 return;
3518 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003519 v = string_concat((PyStringObject *) *pv, w);
3520 Py_DECREF(*pv);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003521 *pv = v;
3522}
3523
Guido van Rossum013142a1994-08-30 08:19:36 +00003524void
Fred Drakeba096332000-07-09 07:04:36 +00003525PyString_ConcatAndDel(register PyObject **pv, register PyObject *w)
Guido van Rossum013142a1994-08-30 08:19:36 +00003526{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003527 PyString_Concat(pv, w);
3528 Py_XDECREF(w);
Guido van Rossum013142a1994-08-30 08:19:36 +00003529}
3530
3531
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003532/* The following function breaks the notion that strings are immutable:
3533 it changes the size of a string. We get away with this only if there
3534 is only one module referencing the object. You can also think of it
3535 as creating a new string object and destroying the old one, only
3536 more efficiently. In any case, don't use this if the string may
Tim Peters5de98422002-04-27 18:44:32 +00003537 already be known to some other part of the code...
3538 Note that if there's not enough memory to resize the string, the original
3539 string object at *pv is deallocated, *pv is set to NULL, an "out of
3540 memory" exception is set, and -1 is returned. Else (on success) 0 is
3541 returned, and the value in *pv may or may not be the same as on input.
3542 As always, an extra byte is allocated for a trailing \0 byte (newsize
3543 does *not* include that), and a trailing \0 byte is stored.
3544*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003545
3546int
Martin v. Löwis18e16552006-02-15 17:27:45 +00003547_PyString_Resize(PyObject **pv, Py_ssize_t newsize)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003548{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003549 register PyObject *v;
3550 register PyStringObject *sv;
Guido van Rossum921842f1990-11-18 17:30:23 +00003551 v = *pv;
Armin Rigo618fbf52004-08-07 20:58:32 +00003552 if (!PyString_Check(v) || v->ob_refcnt != 1 || newsize < 0 ||
3553 PyString_CHECK_INTERNED(v)) {
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003554 *pv = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003555 Py_DECREF(v);
3556 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +00003557 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003558 }
Guido van Rossum921842f1990-11-18 17:30:23 +00003559 /* XXX UNREF/NEWREF interface should be more symmetrical */
Tim Peters34592512002-07-11 06:23:50 +00003560 _Py_DEC_REFTOTAL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003561 _Py_ForgetReference(v);
3562 *pv = (PyObject *)
Tim Peterse7c05322004-06-27 17:24:49 +00003563 PyObject_REALLOC((char *)v, sizeof(PyStringObject) + newsize);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003564 if (*pv == NULL) {
Neil Schemenauer510492e2002-04-12 03:05:19 +00003565 PyObject_Del(v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003566 PyErr_NoMemory();
Guido van Rossum2a9096b1990-10-21 22:15:08 +00003567 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003568 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003569 _Py_NewReference(*pv);
3570 sv = (PyStringObject *) *pv;
Guido van Rossum921842f1990-11-18 17:30:23 +00003571 sv->ob_size = newsize;
3572 sv->ob_sval[newsize] = '\0';
Raymond Hettinger561fbf12004-10-26 01:52:37 +00003573 sv->ob_shash = -1; /* invalidate cached hash value */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003574 return 0;
3575}
Guido van Rossume5372401993-03-16 12:15:04 +00003576
3577/* Helpers for formatstring */
3578
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003579static PyObject *
Thomas Wouters977485d2006-02-16 15:59:12 +00003580getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
Guido van Rossume5372401993-03-16 12:15:04 +00003581{
Thomas Wouters977485d2006-02-16 15:59:12 +00003582 Py_ssize_t argidx = *p_argidx;
Guido van Rossume5372401993-03-16 12:15:04 +00003583 if (argidx < arglen) {
3584 (*p_argidx)++;
3585 if (arglen < 0)
3586 return args;
3587 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003588 return PyTuple_GetItem(args, argidx);
Guido van Rossume5372401993-03-16 12:15:04 +00003589 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003590 PyErr_SetString(PyExc_TypeError,
3591 "not enough arguments for format string");
Guido van Rossume5372401993-03-16 12:15:04 +00003592 return NULL;
3593}
3594
Tim Peters38fd5b62000-09-21 05:43:11 +00003595/* Format codes
3596 * F_LJUST '-'
3597 * F_SIGN '+'
3598 * F_BLANK ' '
3599 * F_ALT '#'
3600 * F_ZERO '0'
3601 */
Guido van Rossume5372401993-03-16 12:15:04 +00003602#define F_LJUST (1<<0)
3603#define F_SIGN (1<<1)
3604#define F_BLANK (1<<2)
3605#define F_ALT (1<<3)
3606#define F_ZERO (1<<4)
3607
Guido van Rossuma04d47b1997-01-21 16:12:09 +00003608static int
Fred Drakeba096332000-07-09 07:04:36 +00003609formatfloat(char *buf, size_t buflen, int flags,
3610 int prec, int type, PyObject *v)
Guido van Rossume5372401993-03-16 12:15:04 +00003611{
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00003612 /* fmt = '%#.' + `prec` + `type`
3613 worst case length = 3 + 10 (len of INT_MAX) + 1 = 14 (use 20)*/
Guido van Rossume5372401993-03-16 12:15:04 +00003614 char fmt[20];
Guido van Rossume5372401993-03-16 12:15:04 +00003615 double x;
Neal Norwitz88fe4ff2002-07-28 16:44:23 +00003616 x = PyFloat_AsDouble(v);
3617 if (x == -1.0 && PyErr_Occurred()) {
3618 PyErr_SetString(PyExc_TypeError, "float argument required");
Guido van Rossuma04d47b1997-01-21 16:12:09 +00003619 return -1;
Neal Norwitz88fe4ff2002-07-28 16:44:23 +00003620 }
Guido van Rossume5372401993-03-16 12:15:04 +00003621 if (prec < 0)
3622 prec = 6;
Guido van Rossume5372401993-03-16 12:15:04 +00003623 if (type == 'f' && fabs(x)/1e25 >= 1e25)
3624 type = 'g';
Marc-André Lemburg79f57832002-12-29 19:44:06 +00003625 /* Worst case length calc to ensure no buffer overrun:
3626
3627 'g' formats:
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00003628 fmt = %#.<prec>g
3629 buf = '-' + [0-9]*prec + '.' + 'e+' + (longest exp
Tim Petersb3d8d1f2001-04-28 05:38:26 +00003630 for any double rep.)
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00003631 len = 1 + prec + 1 + 2 + 5 = 9 + prec
Marc-André Lemburg79f57832002-12-29 19:44:06 +00003632
3633 'f' formats:
3634 buf = '-' + [0-9]*x + '.' + [0-9]*prec (with x < 50)
3635 len = 1 + 50 + 1 + prec = 52 + prec
3636
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00003637 If prec=0 the effective precision is 1 (the leading digit is
Tim Petersae1d0c92006-03-17 03:29:34 +00003638 always given), therefore increase the length by one.
Marc-André Lemburg79f57832002-12-29 19:44:06 +00003639
3640 */
3641 if ((type == 'g' && buflen <= (size_t)10 + (size_t)prec) ||
3642 (type == 'f' && buflen <= (size_t)53 + (size_t)prec)) {
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00003643 PyErr_SetString(PyExc_OverflowError,
Fred Drake661ea262000-10-24 19:57:45 +00003644 "formatted float is too long (precision too large?)");
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00003645 return -1;
3646 }
Marc-André Lemburg79f57832002-12-29 19:44:06 +00003647 PyOS_snprintf(fmt, sizeof(fmt), "%%%s.%d%c",
3648 (flags&F_ALT) ? "#" : "",
3649 prec, type);
Martin v. Löwis737ea822004-06-08 18:52:54 +00003650 PyOS_ascii_formatd(buf, buflen, fmt, x);
Martin v. Löwis18e16552006-02-15 17:27:45 +00003651 return (int)strlen(buf);
Guido van Rossume5372401993-03-16 12:15:04 +00003652}
3653
Tim Peters38fd5b62000-09-21 05:43:11 +00003654/* _PyString_FormatLong emulates the format codes d, u, o, x and X, and
3655 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
3656 * Python's regular ints.
3657 * Return value: a new PyString*, or NULL if error.
3658 * . *pbuf is set to point into it,
3659 * *plen set to the # of chars following that.
3660 * Caller must decref it when done using pbuf.
3661 * The string starting at *pbuf is of the form
3662 * "-"? ("0x" | "0X")? digit+
3663 * "0x"/"0X" are present only for x and X conversions, with F_ALT
Tim Petersb3d8d1f2001-04-28 05:38:26 +00003664 * set in flags. The case of hex digits will be correct,
Tim Peters38fd5b62000-09-21 05:43:11 +00003665 * There will be at least prec digits, zero-filled on the left if
3666 * necessary to get that many.
3667 * val object to be converted
3668 * flags bitmask of format flags; only F_ALT is looked at
3669 * prec minimum number of digits; 0-fill on left if needed
3670 * type a character in [duoxX]; u acts the same as d
3671 *
3672 * CAUTION: o, x and X conversions on regular ints can never
3673 * produce a '-' sign, but can for Python's unbounded ints.
3674 */
3675PyObject*
3676_PyString_FormatLong(PyObject *val, int flags, int prec, int type,
3677 char **pbuf, int *plen)
3678{
3679 PyObject *result = NULL;
3680 char *buf;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003681 Py_ssize_t i;
Tim Peters38fd5b62000-09-21 05:43:11 +00003682 int sign; /* 1 if '-', else 0 */
3683 int len; /* number of characters */
Martin v. Löwis725507b2006-03-07 12:08:51 +00003684 Py_ssize_t llen;
Tim Peters38fd5b62000-09-21 05:43:11 +00003685 int numdigits; /* len == numnondigits + numdigits */
3686 int numnondigits = 0;
3687
3688 switch (type) {
3689 case 'd':
3690 case 'u':
3691 result = val->ob_type->tp_str(val);
3692 break;
3693 case 'o':
3694 result = val->ob_type->tp_as_number->nb_oct(val);
3695 break;
3696 case 'x':
3697 case 'X':
3698 numnondigits = 2;
3699 result = val->ob_type->tp_as_number->nb_hex(val);
3700 break;
3701 default:
3702 assert(!"'type' not in [duoxX]");
3703 }
3704 if (!result)
3705 return NULL;
3706
3707 /* To modify the string in-place, there can only be one reference. */
3708 if (result->ob_refcnt != 1) {
3709 PyErr_BadInternalCall();
3710 return NULL;
3711 }
3712 buf = PyString_AsString(result);
Martin v. Löwis725507b2006-03-07 12:08:51 +00003713 llen = PyString_Size(result);
Martin v. Löwis8ce358f2006-04-13 07:22:51 +00003714 if (llen > PY_SSIZE_T_MAX) {
Martin v. Löwis725507b2006-03-07 12:08:51 +00003715 PyErr_SetString(PyExc_ValueError, "string too large in _PyString_FormatLong");
3716 return NULL;
3717 }
3718 len = (int)llen;
Tim Peters38fd5b62000-09-21 05:43:11 +00003719 if (buf[len-1] == 'L') {
3720 --len;
3721 buf[len] = '\0';
3722 }
3723 sign = buf[0] == '-';
3724 numnondigits += sign;
3725 numdigits = len - numnondigits;
3726 assert(numdigits > 0);
3727
Tim Petersfff53252001-04-12 18:38:48 +00003728 /* Get rid of base marker unless F_ALT */
3729 if ((flags & F_ALT) == 0) {
Tim Peters38fd5b62000-09-21 05:43:11 +00003730 /* Need to skip 0x, 0X or 0. */
3731 int skipped = 0;
3732 switch (type) {
3733 case 'o':
3734 assert(buf[sign] == '0');
3735 /* If 0 is only digit, leave it alone. */
3736 if (numdigits > 1) {
3737 skipped = 1;
3738 --numdigits;
3739 }
3740 break;
3741 case 'x':
3742 case 'X':
3743 assert(buf[sign] == '0');
3744 assert(buf[sign + 1] == 'x');
3745 skipped = 2;
3746 numnondigits -= 2;
3747 break;
3748 }
3749 if (skipped) {
3750 buf += skipped;
3751 len -= skipped;
3752 if (sign)
3753 buf[0] = '-';
3754 }
3755 assert(len == numnondigits + numdigits);
3756 assert(numdigits > 0);
3757 }
3758
3759 /* Fill with leading zeroes to meet minimum width. */
3760 if (prec > numdigits) {
3761 PyObject *r1 = PyString_FromStringAndSize(NULL,
3762 numnondigits + prec);
3763 char *b1;
3764 if (!r1) {
3765 Py_DECREF(result);
3766 return NULL;
3767 }
3768 b1 = PyString_AS_STRING(r1);
3769 for (i = 0; i < numnondigits; ++i)
3770 *b1++ = *buf++;
3771 for (i = 0; i < prec - numdigits; i++)
3772 *b1++ = '0';
3773 for (i = 0; i < numdigits; i++)
3774 *b1++ = *buf++;
3775 *b1 = '\0';
3776 Py_DECREF(result);
3777 result = r1;
3778 buf = PyString_AS_STRING(result);
3779 len = numnondigits + prec;
3780 }
3781
3782 /* Fix up case for hex conversions. */
Raymond Hettinger3296e692005-06-29 23:29:56 +00003783 if (type == 'X') {
3784 /* Need to convert all lower case letters to upper case.
3785 and need to convert 0x to 0X (and -0x to -0X). */
Tim Peters38fd5b62000-09-21 05:43:11 +00003786 for (i = 0; i < len; i++)
Raymond Hettinger3296e692005-06-29 23:29:56 +00003787 if (buf[i] >= 'a' && buf[i] <= 'x')
3788 buf[i] -= 'a'-'A';
Tim Peters38fd5b62000-09-21 05:43:11 +00003789 }
3790 *pbuf = buf;
3791 *plen = len;
3792 return result;
3793}
3794
Guido van Rossuma04d47b1997-01-21 16:12:09 +00003795static int
Fred Drakeba096332000-07-09 07:04:36 +00003796formatint(char *buf, size_t buflen, int flags,
3797 int prec, int type, PyObject *v)
Guido van Rossume5372401993-03-16 12:15:04 +00003798{
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00003799 /* fmt = '%#.' + `prec` + 'l' + `type`
Tim Peters38fd5b62000-09-21 05:43:11 +00003800 worst case length = 3 + 19 (worst len of INT_MAX on 64-bit machine)
3801 + 1 + 1 = 24 */
3802 char fmt[64]; /* plenty big enough! */
Guido van Rossum6c9e1302003-11-29 23:52:13 +00003803 char *sign;
Guido van Rossume5372401993-03-16 12:15:04 +00003804 long x;
Andrew MacIntyre5e9c80d2002-02-28 11:38:24 +00003805
Neal Norwitz88fe4ff2002-07-28 16:44:23 +00003806 x = PyInt_AsLong(v);
3807 if (x == -1 && PyErr_Occurred()) {
3808 PyErr_SetString(PyExc_TypeError, "int argument required");
Guido van Rossuma04d47b1997-01-21 16:12:09 +00003809 return -1;
Neal Norwitz88fe4ff2002-07-28 16:44:23 +00003810 }
Guido van Rossum6c9e1302003-11-29 23:52:13 +00003811 if (x < 0 && type == 'u') {
3812 type = 'd';
Guido van Rossum078151d2002-08-11 04:24:12 +00003813 }
Guido van Rossum6c9e1302003-11-29 23:52:13 +00003814 if (x < 0 && (type == 'x' || type == 'X' || type == 'o'))
3815 sign = "-";
3816 else
3817 sign = "";
Guido van Rossume5372401993-03-16 12:15:04 +00003818 if (prec < 0)
3819 prec = 1;
Andrew MacIntyre5e9c80d2002-02-28 11:38:24 +00003820
3821 if ((flags & F_ALT) &&
3822 (type == 'x' || type == 'X')) {
Guido van Rossum3aa3fc42002-04-15 13:48:52 +00003823 /* When converting under %#x or %#X, there are a number
Andrew MacIntyre5e9c80d2002-02-28 11:38:24 +00003824 * of issues that cause pain:
3825 * - when 0 is being converted, the C standard leaves off
3826 * the '0x' or '0X', which is inconsistent with other
3827 * %#x/%#X conversions and inconsistent with Python's
3828 * hex() function
3829 * - there are platforms that violate the standard and
3830 * convert 0 with the '0x' or '0X'
3831 * (Metrowerks, Compaq Tru64)
3832 * - there are platforms that give '0x' when converting
Guido van Rossum3aa3fc42002-04-15 13:48:52 +00003833 * under %#X, but convert 0 in accordance with the
Andrew MacIntyre5e9c80d2002-02-28 11:38:24 +00003834 * standard (OS/2 EMX)
Guido van Rossum3aa3fc42002-04-15 13:48:52 +00003835 *
Andrew MacIntyre5e9c80d2002-02-28 11:38:24 +00003836 * We can achieve the desired consistency by inserting our
3837 * own '0x' or '0X' prefix, and substituting %x/%X in place
3838 * of %#x/%#X.
3839 *
3840 * Note that this is the same approach as used in
3841 * formatint() in unicodeobject.c
3842 */
Guido van Rossum6c9e1302003-11-29 23:52:13 +00003843 PyOS_snprintf(fmt, sizeof(fmt), "%s0%c%%.%dl%c",
3844 sign, type, prec, type);
Andrew MacIntyre5e9c80d2002-02-28 11:38:24 +00003845 }
3846 else {
Guido van Rossum6c9e1302003-11-29 23:52:13 +00003847 PyOS_snprintf(fmt, sizeof(fmt), "%s%%%s.%dl%c",
3848 sign, (flags&F_ALT) ? "#" : "",
Andrew MacIntyre5e9c80d2002-02-28 11:38:24 +00003849 prec, type);
3850 }
3851
Guido van Rossum6c9e1302003-11-29 23:52:13 +00003852 /* buf = '+'/'-'/'' + '0'/'0x'/'' + '[0-9]'*max(prec, len(x in octal))
3853 * worst case buf = '-0x' + [0-9]*prec, where prec >= 11
Andrew MacIntyre5e9c80d2002-02-28 11:38:24 +00003854 */
Guido van Rossum6c9e1302003-11-29 23:52:13 +00003855 if (buflen <= 14 || buflen <= (size_t)3 + (size_t)prec) {
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00003856 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum3aa3fc42002-04-15 13:48:52 +00003857 "formatted integer is too long (precision too large?)");
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00003858 return -1;
3859 }
Guido van Rossum6c9e1302003-11-29 23:52:13 +00003860 if (sign[0])
3861 PyOS_snprintf(buf, buflen, fmt, -x);
3862 else
3863 PyOS_snprintf(buf, buflen, fmt, x);
Martin v. Löwis18e16552006-02-15 17:27:45 +00003864 return (int)strlen(buf);
Guido van Rossume5372401993-03-16 12:15:04 +00003865}
3866
Guido van Rossuma04d47b1997-01-21 16:12:09 +00003867static int
Fred Drakeba096332000-07-09 07:04:36 +00003868formatchar(char *buf, size_t buflen, PyObject *v)
Guido van Rossume5372401993-03-16 12:15:04 +00003869{
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00003870 /* presume that the buffer is at least 2 characters long */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003871 if (PyString_Check(v)) {
3872 if (!PyArg_Parse(v, "c;%c requires int or char", &buf[0]))
Guido van Rossuma04d47b1997-01-21 16:12:09 +00003873 return -1;
Guido van Rossume5372401993-03-16 12:15:04 +00003874 }
3875 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003876 if (!PyArg_Parse(v, "b;%c requires int or char", &buf[0]))
Guido van Rossuma04d47b1997-01-21 16:12:09 +00003877 return -1;
Guido van Rossume5372401993-03-16 12:15:04 +00003878 }
3879 buf[1] = '\0';
Guido van Rossuma04d47b1997-01-21 16:12:09 +00003880 return 1;
Guido van Rossume5372401993-03-16 12:15:04 +00003881}
3882
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00003883/* fmt%(v1,v2,...) is roughly equivalent to sprintf(fmt, v1, v2, ...)
3884
3885 FORMATBUFLEN is the length of the buffer in which the floats, ints, &
3886 chars are formatted. XXX This is a magic number. Each formatting
3887 routine does bounds checking to ensure no overflow, but a better
3888 solution may be to malloc a buffer of appropriate size for each
3889 format. For now, the current solution is sufficient.
3890*/
3891#define FORMATBUFLEN (size_t)120
Guido van Rossume5372401993-03-16 12:15:04 +00003892
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003893PyObject *
Fred Drakeba096332000-07-09 07:04:36 +00003894PyString_Format(PyObject *format, PyObject *args)
Guido van Rossume5372401993-03-16 12:15:04 +00003895{
3896 char *fmt, *res;
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003897 Py_ssize_t arglen, argidx;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003898 Py_ssize_t reslen, rescnt, fmtcnt;
Guido van Rossum993952b1996-05-21 22:44:20 +00003899 int args_owned = 0;
Martin v. Löwis339d0f72001-08-17 18:39:25 +00003900 PyObject *result, *orig_args;
3901#ifdef Py_USING_UNICODE
3902 PyObject *v, *w;
3903#endif
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003904 PyObject *dict = NULL;
3905 if (format == NULL || !PyString_Check(format) || args == NULL) {
3906 PyErr_BadInternalCall();
Guido van Rossume5372401993-03-16 12:15:04 +00003907 return NULL;
3908 }
Guido van Rossum90daa872000-04-10 13:47:21 +00003909 orig_args = args;
Jeremy Hylton7802a532001-12-06 15:18:48 +00003910 fmt = PyString_AS_STRING(format);
3911 fmtcnt = PyString_GET_SIZE(format);
Guido van Rossum6ac258d1993-05-12 08:24:20 +00003912 reslen = rescnt = fmtcnt + 100;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003913 result = PyString_FromStringAndSize((char *)NULL, reslen);
Guido van Rossume5372401993-03-16 12:15:04 +00003914 if (result == NULL)
3915 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003916 res = PyString_AsString(result);
3917 if (PyTuple_Check(args)) {
Jeremy Hylton7802a532001-12-06 15:18:48 +00003918 arglen = PyTuple_GET_SIZE(args);
Guido van Rossume5372401993-03-16 12:15:04 +00003919 argidx = 0;
3920 }
3921 else {
3922 arglen = -1;
3923 argidx = -2;
3924 }
Neal Norwitz80a1bf42002-11-12 23:01:12 +00003925 if (args->ob_type->tp_as_mapping && !PyTuple_Check(args) &&
3926 !PyObject_TypeCheck(args, &PyBaseString_Type))
Guido van Rossum013142a1994-08-30 08:19:36 +00003927 dict = args;
Guido van Rossume5372401993-03-16 12:15:04 +00003928 while (--fmtcnt >= 0) {
3929 if (*fmt != '%') {
3930 if (--rescnt < 0) {
Guido van Rossum6ac258d1993-05-12 08:24:20 +00003931 rescnt = fmtcnt + 100;
3932 reslen += rescnt;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003933 if (_PyString_Resize(&result, reslen) < 0)
Guido van Rossume5372401993-03-16 12:15:04 +00003934 return NULL;
Jeremy Hylton7802a532001-12-06 15:18:48 +00003935 res = PyString_AS_STRING(result)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003936 + reslen - rescnt;
Guido van Rossum013142a1994-08-30 08:19:36 +00003937 --rescnt;
Guido van Rossume5372401993-03-16 12:15:04 +00003938 }
3939 *res++ = *fmt++;
3940 }
3941 else {
3942 /* Got a format specifier */
3943 int flags = 0;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003944 Py_ssize_t width = -1;
Guido van Rossume5372401993-03-16 12:15:04 +00003945 int prec = -1;
Guido van Rossum6938a291993-11-11 14:51:57 +00003946 int c = '\0';
Guido van Rossume5372401993-03-16 12:15:04 +00003947 int fill;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003948 PyObject *v = NULL;
3949 PyObject *temp = NULL;
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00003950 char *pbuf;
Guido van Rossume5372401993-03-16 12:15:04 +00003951 int sign;
Martin v. Löwis725507b2006-03-07 12:08:51 +00003952 Py_ssize_t len;
Guido van Rossum3aa3fc42002-04-15 13:48:52 +00003953 char formatbuf[FORMATBUFLEN];
3954 /* For format{float,int,char}() */
Martin v. Löwis339d0f72001-08-17 18:39:25 +00003955#ifdef Py_USING_UNICODE
Guido van Rossum90daa872000-04-10 13:47:21 +00003956 char *fmt_start = fmt;
Martin v. Löwis725507b2006-03-07 12:08:51 +00003957 Py_ssize_t argidx_start = argidx;
Martin v. Löwis339d0f72001-08-17 18:39:25 +00003958#endif
Tim Petersb3d8d1f2001-04-28 05:38:26 +00003959
Guido van Rossumda9c2711996-12-05 21:58:58 +00003960 fmt++;
Guido van Rossum013142a1994-08-30 08:19:36 +00003961 if (*fmt == '(') {
3962 char *keystart;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003963 Py_ssize_t keylen;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003964 PyObject *key;
Guido van Rossum045e6881997-09-08 18:30:11 +00003965 int pcount = 1;
Guido van Rossum013142a1994-08-30 08:19:36 +00003966
3967 if (dict == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003968 PyErr_SetString(PyExc_TypeError,
Tim Petersb3d8d1f2001-04-28 05:38:26 +00003969 "format requires a mapping");
Guido van Rossum013142a1994-08-30 08:19:36 +00003970 goto error;
3971 }
3972 ++fmt;
3973 --fmtcnt;
3974 keystart = fmt;
Guido van Rossum045e6881997-09-08 18:30:11 +00003975 /* Skip over balanced parentheses */
3976 while (pcount > 0 && --fmtcnt >= 0) {
3977 if (*fmt == ')')
3978 --pcount;
3979 else if (*fmt == '(')
3980 ++pcount;
Guido van Rossum013142a1994-08-30 08:19:36 +00003981 fmt++;
Guido van Rossum045e6881997-09-08 18:30:11 +00003982 }
3983 keylen = fmt - keystart - 1;
3984 if (fmtcnt < 0 || pcount > 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003985 PyErr_SetString(PyExc_ValueError,
Guido van Rossum013142a1994-08-30 08:19:36 +00003986 "incomplete format key");
3987 goto error;
3988 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003989 key = PyString_FromStringAndSize(keystart,
3990 keylen);
Guido van Rossum013142a1994-08-30 08:19:36 +00003991 if (key == NULL)
3992 goto error;
Guido van Rossum993952b1996-05-21 22:44:20 +00003993 if (args_owned) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003994 Py_DECREF(args);
Guido van Rossum993952b1996-05-21 22:44:20 +00003995 args_owned = 0;
3996 }
3997 args = PyObject_GetItem(dict, key);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003998 Py_DECREF(key);
Guido van Rossum013142a1994-08-30 08:19:36 +00003999 if (args == NULL) {
4000 goto error;
4001 }
Guido van Rossum993952b1996-05-21 22:44:20 +00004002 args_owned = 1;
Guido van Rossum013142a1994-08-30 08:19:36 +00004003 arglen = -1;
4004 argidx = -2;
4005 }
Guido van Rossume5372401993-03-16 12:15:04 +00004006 while (--fmtcnt >= 0) {
4007 switch (c = *fmt++) {
4008 case '-': flags |= F_LJUST; continue;
4009 case '+': flags |= F_SIGN; continue;
4010 case ' ': flags |= F_BLANK; continue;
4011 case '#': flags |= F_ALT; continue;
4012 case '0': flags |= F_ZERO; continue;
4013 }
4014 break;
4015 }
4016 if (c == '*') {
4017 v = getnextarg(args, arglen, &argidx);
4018 if (v == NULL)
4019 goto error;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004020 if (!PyInt_Check(v)) {
4021 PyErr_SetString(PyExc_TypeError,
4022 "* wants int");
Guido van Rossume5372401993-03-16 12:15:04 +00004023 goto error;
4024 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004025 width = PyInt_AsLong(v);
Guido van Rossum98c9eba1999-06-07 15:12:32 +00004026 if (width < 0) {
4027 flags |= F_LJUST;
4028 width = -width;
4029 }
Guido van Rossume5372401993-03-16 12:15:04 +00004030 if (--fmtcnt >= 0)
4031 c = *fmt++;
4032 }
Guido van Rossum9fa2c111995-02-10 17:00:37 +00004033 else if (c >= 0 && isdigit(c)) {
Guido van Rossume5372401993-03-16 12:15:04 +00004034 width = c - '0';
4035 while (--fmtcnt >= 0) {
Guido van Rossum9fa2c111995-02-10 17:00:37 +00004036 c = Py_CHARMASK(*fmt++);
Guido van Rossume5372401993-03-16 12:15:04 +00004037 if (!isdigit(c))
4038 break;
4039 if ((width*10) / 10 != width) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004040 PyErr_SetString(
4041 PyExc_ValueError,
4042 "width too big");
Guido van Rossume5372401993-03-16 12:15:04 +00004043 goto error;
4044 }
4045 width = width*10 + (c - '0');
4046 }
4047 }
4048 if (c == '.') {
4049 prec = 0;
4050 if (--fmtcnt >= 0)
4051 c = *fmt++;
4052 if (c == '*') {
4053 v = getnextarg(args, arglen, &argidx);
4054 if (v == NULL)
4055 goto error;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004056 if (!PyInt_Check(v)) {
4057 PyErr_SetString(
4058 PyExc_TypeError,
4059 "* wants int");
Guido van Rossume5372401993-03-16 12:15:04 +00004060 goto error;
4061 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004062 prec = PyInt_AsLong(v);
Guido van Rossume5372401993-03-16 12:15:04 +00004063 if (prec < 0)
4064 prec = 0;
4065 if (--fmtcnt >= 0)
4066 c = *fmt++;
4067 }
Guido van Rossum9fa2c111995-02-10 17:00:37 +00004068 else if (c >= 0 && isdigit(c)) {
Guido van Rossume5372401993-03-16 12:15:04 +00004069 prec = c - '0';
4070 while (--fmtcnt >= 0) {
Guido van Rossum9fa2c111995-02-10 17:00:37 +00004071 c = Py_CHARMASK(*fmt++);
Guido van Rossume5372401993-03-16 12:15:04 +00004072 if (!isdigit(c))
4073 break;
4074 if ((prec*10) / 10 != prec) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004075 PyErr_SetString(
4076 PyExc_ValueError,
Guido van Rossume5372401993-03-16 12:15:04 +00004077 "prec too big");
4078 goto error;
4079 }
4080 prec = prec*10 + (c - '0');
4081 }
4082 }
4083 } /* prec */
4084 if (fmtcnt >= 0) {
4085 if (c == 'h' || c == 'l' || c == 'L') {
Guido van Rossume5372401993-03-16 12:15:04 +00004086 if (--fmtcnt >= 0)
4087 c = *fmt++;
4088 }
4089 }
4090 if (fmtcnt < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004091 PyErr_SetString(PyExc_ValueError,
4092 "incomplete format");
Guido van Rossume5372401993-03-16 12:15:04 +00004093 goto error;
4094 }
4095 if (c != '%') {
4096 v = getnextarg(args, arglen, &argidx);
4097 if (v == NULL)
4098 goto error;
4099 }
4100 sign = 0;
4101 fill = ' ';
4102 switch (c) {
4103 case '%':
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00004104 pbuf = "%";
Guido van Rossume5372401993-03-16 12:15:04 +00004105 len = 1;
4106 break;
4107 case 's':
Martin v. Löwis339d0f72001-08-17 18:39:25 +00004108#ifdef Py_USING_UNICODE
Neil Schemenauerab619232005-08-31 23:02:05 +00004109 if (PyUnicode_Check(v)) {
4110 fmt = fmt_start;
4111 argidx = argidx_start;
4112 goto unicode;
4113 }
Georg Brandld45014b2005-10-01 17:06:00 +00004114#endif
Neil Schemenauercf52c072005-08-12 17:34:58 +00004115 temp = _PyObject_Str(v);
Georg Brandld45014b2005-10-01 17:06:00 +00004116#ifdef Py_USING_UNICODE
Neil Schemenauercf52c072005-08-12 17:34:58 +00004117 if (temp != NULL && PyUnicode_Check(temp)) {
4118 Py_DECREF(temp);
Guido van Rossum90daa872000-04-10 13:47:21 +00004119 fmt = fmt_start;
Marc-André Lemburg542fe562001-05-02 14:21:53 +00004120 argidx = argidx_start;
Guido van Rossum90daa872000-04-10 13:47:21 +00004121 goto unicode;
4122 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00004123#endif
Guido van Rossumb00c07f2002-10-09 19:07:53 +00004124 /* Fall through */
Walter Dörwald9ff3f032003-06-18 14:17:01 +00004125 case 'r':
Neil Schemenauercf52c072005-08-12 17:34:58 +00004126 if (c == 'r')
Guido van Rossumf0b7b042000-04-11 15:39:26 +00004127 temp = PyObject_Repr(v);
Guido van Rossum013142a1994-08-30 08:19:36 +00004128 if (temp == NULL)
Guido van Rossume5372401993-03-16 12:15:04 +00004129 goto error;
Guido van Rossum4a0144c1998-06-09 15:08:41 +00004130 if (!PyString_Check(temp)) {
4131 PyErr_SetString(PyExc_TypeError,
Guido van Rossum8052f892002-10-09 19:14:30 +00004132 "%s argument has non-string str()");
Jeremy Hylton7802a532001-12-06 15:18:48 +00004133 Py_DECREF(temp);
Guido van Rossum4a0144c1998-06-09 15:08:41 +00004134 goto error;
4135 }
Jeremy Hylton7802a532001-12-06 15:18:48 +00004136 pbuf = PyString_AS_STRING(temp);
4137 len = PyString_GET_SIZE(temp);
Guido van Rossume5372401993-03-16 12:15:04 +00004138 if (prec >= 0 && len > prec)
4139 len = prec;
4140 break;
4141 case 'i':
4142 case 'd':
4143 case 'u':
4144 case 'o':
4145 case 'x':
4146 case 'X':
4147 if (c == 'i')
4148 c = 'd';
Tim Petersa3a3a032000-11-30 05:22:44 +00004149 if (PyLong_Check(v)) {
Martin v. Löwis725507b2006-03-07 12:08:51 +00004150 int ilen;
Tim Peters38fd5b62000-09-21 05:43:11 +00004151 temp = _PyString_FormatLong(v, flags,
Martin v. Löwis725507b2006-03-07 12:08:51 +00004152 prec, c, &pbuf, &ilen);
4153 len = ilen;
Tim Peters38fd5b62000-09-21 05:43:11 +00004154 if (!temp)
4155 goto error;
Tim Peters38fd5b62000-09-21 05:43:11 +00004156 sign = 1;
Guido van Rossum4acdc231997-01-29 06:00:24 +00004157 }
Tim Peters38fd5b62000-09-21 05:43:11 +00004158 else {
4159 pbuf = formatbuf;
Guido van Rossum3aa3fc42002-04-15 13:48:52 +00004160 len = formatint(pbuf,
4161 sizeof(formatbuf),
Tim Peters38fd5b62000-09-21 05:43:11 +00004162 flags, prec, c, v);
4163 if (len < 0)
4164 goto error;
Guido van Rossum6c9e1302003-11-29 23:52:13 +00004165 sign = 1;
Tim Peters38fd5b62000-09-21 05:43:11 +00004166 }
4167 if (flags & F_ZERO)
4168 fill = '0';
Guido van Rossume5372401993-03-16 12:15:04 +00004169 break;
4170 case 'e':
4171 case 'E':
4172 case 'f':
Raymond Hettinger9bfe5332003-08-27 04:55:52 +00004173 case 'F':
Guido van Rossume5372401993-03-16 12:15:04 +00004174 case 'g':
4175 case 'G':
Raymond Hettinger9bfe5332003-08-27 04:55:52 +00004176 if (c == 'F')
4177 c = 'f';
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00004178 pbuf = formatbuf;
Guido van Rossum3aa3fc42002-04-15 13:48:52 +00004179 len = formatfloat(pbuf, sizeof(formatbuf),
4180 flags, prec, c, v);
Guido van Rossuma04d47b1997-01-21 16:12:09 +00004181 if (len < 0)
Guido van Rossume5372401993-03-16 12:15:04 +00004182 goto error;
Guido van Rossume5372401993-03-16 12:15:04 +00004183 sign = 1;
Tim Peters38fd5b62000-09-21 05:43:11 +00004184 if (flags & F_ZERO)
Guido van Rossume5372401993-03-16 12:15:04 +00004185 fill = '0';
4186 break;
4187 case 'c':
Walter Dörwald43440a62003-03-31 18:07:50 +00004188#ifdef Py_USING_UNICODE
4189 if (PyUnicode_Check(v)) {
4190 fmt = fmt_start;
4191 argidx = argidx_start;
4192 goto unicode;
4193 }
4194#endif
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00004195 pbuf = formatbuf;
4196 len = formatchar(pbuf, sizeof(formatbuf), v);
Guido van Rossuma04d47b1997-01-21 16:12:09 +00004197 if (len < 0)
Guido van Rossume5372401993-03-16 12:15:04 +00004198 goto error;
Guido van Rossume5372401993-03-16 12:15:04 +00004199 break;
4200 default:
Guido van Rossum045e6881997-09-08 18:30:11 +00004201 PyErr_Format(PyExc_ValueError,
Andrew M. Kuchling6ca89172000-12-15 13:07:46 +00004202 "unsupported format character '%c' (0x%x) "
4203 "at index %i",
Guido van Rossumefc11882002-09-12 14:43:41 +00004204 c, c,
4205 (int)(fmt - 1 - PyString_AsString(format)));
Guido van Rossume5372401993-03-16 12:15:04 +00004206 goto error;
4207 }
4208 if (sign) {
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00004209 if (*pbuf == '-' || *pbuf == '+') {
4210 sign = *pbuf++;
Guido van Rossume5372401993-03-16 12:15:04 +00004211 len--;
4212 }
4213 else if (flags & F_SIGN)
4214 sign = '+';
4215 else if (flags & F_BLANK)
4216 sign = ' ';
4217 else
Tim Peters38fd5b62000-09-21 05:43:11 +00004218 sign = 0;
Guido van Rossume5372401993-03-16 12:15:04 +00004219 }
4220 if (width < len)
4221 width = len;
Guido van Rossum049cd6b2002-10-11 00:43:48 +00004222 if (rescnt - (sign != 0) < width) {
Guido van Rossum6ac258d1993-05-12 08:24:20 +00004223 reslen -= rescnt;
4224 rescnt = width + fmtcnt + 100;
4225 reslen += rescnt;
Guido van Rossum049cd6b2002-10-11 00:43:48 +00004226 if (reslen < 0) {
4227 Py_DECREF(result);
4228 return PyErr_NoMemory();
4229 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004230 if (_PyString_Resize(&result, reslen) < 0)
Guido van Rossume5372401993-03-16 12:15:04 +00004231 return NULL;
Jeremy Hylton7802a532001-12-06 15:18:48 +00004232 res = PyString_AS_STRING(result)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004233 + reslen - rescnt;
Guido van Rossume5372401993-03-16 12:15:04 +00004234 }
4235 if (sign) {
Guido van Rossum71e57d01993-11-11 15:03:51 +00004236 if (fill != ' ')
4237 *res++ = sign;
Guido van Rossume5372401993-03-16 12:15:04 +00004238 rescnt--;
4239 if (width > len)
4240 width--;
4241 }
Tim Peters38fd5b62000-09-21 05:43:11 +00004242 if ((flags & F_ALT) && (c == 'x' || c == 'X')) {
4243 assert(pbuf[0] == '0');
Tim Petersfff53252001-04-12 18:38:48 +00004244 assert(pbuf[1] == c);
4245 if (fill != ' ') {
4246 *res++ = *pbuf++;
4247 *res++ = *pbuf++;
Tim Peters38fd5b62000-09-21 05:43:11 +00004248 }
Tim Petersfff53252001-04-12 18:38:48 +00004249 rescnt -= 2;
4250 width -= 2;
4251 if (width < 0)
4252 width = 0;
4253 len -= 2;
Tim Peters38fd5b62000-09-21 05:43:11 +00004254 }
4255 if (width > len && !(flags & F_LJUST)) {
Guido van Rossume5372401993-03-16 12:15:04 +00004256 do {
4257 --rescnt;
4258 *res++ = fill;
4259 } while (--width > len);
4260 }
Tim Peters38fd5b62000-09-21 05:43:11 +00004261 if (fill == ' ') {
4262 if (sign)
4263 *res++ = sign;
4264 if ((flags & F_ALT) &&
Tim Petersfff53252001-04-12 18:38:48 +00004265 (c == 'x' || c == 'X')) {
4266 assert(pbuf[0] == '0');
4267 assert(pbuf[1] == c);
Tim Peters38fd5b62000-09-21 05:43:11 +00004268 *res++ = *pbuf++;
4269 *res++ = *pbuf++;
4270 }
4271 }
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00004272 memcpy(res, pbuf, len);
Guido van Rossume5372401993-03-16 12:15:04 +00004273 res += len;
4274 rescnt -= len;
4275 while (--width >= len) {
4276 --rescnt;
4277 *res++ = ' ';
4278 }
Guido van Rossum9fa2c111995-02-10 17:00:37 +00004279 if (dict && (argidx < arglen) && c != '%') {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004280 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger0ebac972002-05-21 15:14:57 +00004281 "not all arguments converted during string formatting");
Guido van Rossum013142a1994-08-30 08:19:36 +00004282 goto error;
4283 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004284 Py_XDECREF(temp);
Guido van Rossume5372401993-03-16 12:15:04 +00004285 } /* '%' */
4286 } /* until end */
Guido van Rossumcaeaafc1995-02-27 10:13:23 +00004287 if (argidx < arglen && !dict) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004288 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger0ebac972002-05-21 15:14:57 +00004289 "not all arguments converted during string formatting");
Guido van Rossume5372401993-03-16 12:15:04 +00004290 goto error;
4291 }
Guido van Rossum1109fbc1998-04-10 22:16:39 +00004292 if (args_owned) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004293 Py_DECREF(args);
Guido van Rossum1109fbc1998-04-10 22:16:39 +00004294 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004295 _PyString_Resize(&result, reslen - rescnt);
Guido van Rossume5372401993-03-16 12:15:04 +00004296 return result;
Guido van Rossum90daa872000-04-10 13:47:21 +00004297
Martin v. Löwis339d0f72001-08-17 18:39:25 +00004298#ifdef Py_USING_UNICODE
Guido van Rossum90daa872000-04-10 13:47:21 +00004299 unicode:
4300 if (args_owned) {
4301 Py_DECREF(args);
4302 args_owned = 0;
4303 }
Marc-André Lemburg542fe562001-05-02 14:21:53 +00004304 /* Fiddle args right (remove the first argidx arguments) */
Guido van Rossum90daa872000-04-10 13:47:21 +00004305 if (PyTuple_Check(orig_args) && argidx > 0) {
4306 PyObject *v;
Martin v. Löwiseb079f12006-02-16 14:32:27 +00004307 Py_ssize_t n = PyTuple_GET_SIZE(orig_args) - argidx;
Guido van Rossum90daa872000-04-10 13:47:21 +00004308 v = PyTuple_New(n);
4309 if (v == NULL)
4310 goto error;
4311 while (--n >= 0) {
4312 PyObject *w = PyTuple_GET_ITEM(orig_args, n + argidx);
4313 Py_INCREF(w);
4314 PyTuple_SET_ITEM(v, n, w);
4315 }
4316 args = v;
4317 } else {
4318 Py_INCREF(orig_args);
4319 args = orig_args;
4320 }
Marc-André Lemburg53f3d4a2000-10-07 08:54:09 +00004321 args_owned = 1;
4322 /* Take what we have of the result and let the Unicode formatting
4323 function format the rest of the input. */
Guido van Rossum90daa872000-04-10 13:47:21 +00004324 rescnt = res - PyString_AS_STRING(result);
Marc-André Lemburg53f3d4a2000-10-07 08:54:09 +00004325 if (_PyString_Resize(&result, rescnt))
4326 goto error;
Guido van Rossum90daa872000-04-10 13:47:21 +00004327 fmtcnt = PyString_GET_SIZE(format) - \
4328 (fmt - PyString_AS_STRING(format));
Marc-André Lemburg53f3d4a2000-10-07 08:54:09 +00004329 format = PyUnicode_Decode(fmt, fmtcnt, NULL, NULL);
4330 if (format == NULL)
Guido van Rossum90daa872000-04-10 13:47:21 +00004331 goto error;
Marc-André Lemburg53f3d4a2000-10-07 08:54:09 +00004332 v = PyUnicode_Format(format, args);
Guido van Rossum90daa872000-04-10 13:47:21 +00004333 Py_DECREF(format);
Marc-André Lemburg53f3d4a2000-10-07 08:54:09 +00004334 if (v == NULL)
4335 goto error;
4336 /* Paste what we have (result) to what the Unicode formatting
4337 function returned (v) and return the result (or error) */
4338 w = PyUnicode_Concat(result, v);
4339 Py_DECREF(result);
4340 Py_DECREF(v);
Guido van Rossum90daa872000-04-10 13:47:21 +00004341 Py_DECREF(args);
Marc-André Lemburg53f3d4a2000-10-07 08:54:09 +00004342 return w;
Martin v. Löwis339d0f72001-08-17 18:39:25 +00004343#endif /* Py_USING_UNICODE */
Tim Petersb3d8d1f2001-04-28 05:38:26 +00004344
Guido van Rossume5372401993-03-16 12:15:04 +00004345 error:
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004346 Py_DECREF(result);
Guido van Rossum1109fbc1998-04-10 22:16:39 +00004347 if (args_owned) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004348 Py_DECREF(args);
Guido van Rossum1109fbc1998-04-10 22:16:39 +00004349 }
Guido van Rossume5372401993-03-16 12:15:04 +00004350 return NULL;
4351}
Guido van Rossum2a61e741997-01-18 07:55:05 +00004352
Guido van Rossum2a61e741997-01-18 07:55:05 +00004353void
Fred Drakeba096332000-07-09 07:04:36 +00004354PyString_InternInPlace(PyObject **p)
Guido van Rossum2a61e741997-01-18 07:55:05 +00004355{
4356 register PyStringObject *s = (PyStringObject *)(*p);
4357 PyObject *t;
4358 if (s == NULL || !PyString_Check(s))
4359 Py_FatalError("PyString_InternInPlace: strings only please!");
Jeremy Hylton4c989dd2004-08-07 19:20:05 +00004360 /* If it's a string subclass, we don't really know what putting
4361 it in the interned dict might do. */
4362 if (!PyString_CheckExact(s))
4363 return;
Guido van Rossum45ec02a2002-08-19 21:43:18 +00004364 if (PyString_CHECK_INTERNED(s))
Guido van Rossum2a61e741997-01-18 07:55:05 +00004365 return;
Guido van Rossum2a61e741997-01-18 07:55:05 +00004366 if (interned == NULL) {
4367 interned = PyDict_New();
Guido van Rossum45ec02a2002-08-19 21:43:18 +00004368 if (interned == NULL) {
4369 PyErr_Clear(); /* Don't leave an exception */
Guido van Rossum2a61e741997-01-18 07:55:05 +00004370 return;
Guido van Rossum45ec02a2002-08-19 21:43:18 +00004371 }
Guido van Rossum2a61e741997-01-18 07:55:05 +00004372 }
Jeremy Hylton4c989dd2004-08-07 19:20:05 +00004373 t = PyDict_GetItem(interned, (PyObject *)s);
4374 if (t) {
Guido van Rossum2a61e741997-01-18 07:55:05 +00004375 Py_INCREF(t);
Guido van Rossum45ec02a2002-08-19 21:43:18 +00004376 Py_DECREF(*p);
4377 *p = t;
Guido van Rossum2a61e741997-01-18 07:55:05 +00004378 return;
4379 }
Guido van Rossum45ec02a2002-08-19 21:43:18 +00004380
Armin Rigo79f7ad22004-08-07 19:27:39 +00004381 if (PyDict_SetItem(interned, (PyObject *)s, (PyObject *)s) < 0) {
Jeremy Hylton4c989dd2004-08-07 19:20:05 +00004382 PyErr_Clear();
Guido van Rossum45ec02a2002-08-19 21:43:18 +00004383 return;
4384 }
Jeremy Hylton4c989dd2004-08-07 19:20:05 +00004385 /* The two references in interned are not counted by refcnt.
4386 The string deallocator will take care of this */
Armin Rigo79f7ad22004-08-07 19:27:39 +00004387 s->ob_refcnt -= 2;
Jeremy Hylton4c989dd2004-08-07 19:20:05 +00004388 PyString_CHECK_INTERNED(s) = SSTATE_INTERNED_MORTAL;
Guido van Rossum2a61e741997-01-18 07:55:05 +00004389}
4390
Guido van Rossum45ec02a2002-08-19 21:43:18 +00004391void
4392PyString_InternImmortal(PyObject **p)
4393{
4394 PyString_InternInPlace(p);
4395 if (PyString_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
4396 PyString_CHECK_INTERNED(*p) = SSTATE_INTERNED_IMMORTAL;
4397 Py_INCREF(*p);
4398 }
4399}
4400
Guido van Rossum2a61e741997-01-18 07:55:05 +00004401
4402PyObject *
Fred Drakeba096332000-07-09 07:04:36 +00004403PyString_InternFromString(const char *cp)
Guido van Rossum2a61e741997-01-18 07:55:05 +00004404{
4405 PyObject *s = PyString_FromString(cp);
4406 if (s == NULL)
4407 return NULL;
4408 PyString_InternInPlace(&s);
4409 return s;
4410}
4411
Guido van Rossum8cf04761997-08-02 02:57:45 +00004412void
Fred Drakeba096332000-07-09 07:04:36 +00004413PyString_Fini(void)
Guido van Rossum8cf04761997-08-02 02:57:45 +00004414{
4415 int i;
Guido van Rossum8cf04761997-08-02 02:57:45 +00004416 for (i = 0; i < UCHAR_MAX + 1; i++) {
4417 Py_XDECREF(characters[i]);
4418 characters[i] = NULL;
4419 }
Guido van Rossum8cf04761997-08-02 02:57:45 +00004420 Py_XDECREF(nullstring);
4421 nullstring = NULL;
Guido van Rossum8cf04761997-08-02 02:57:45 +00004422}
Barry Warsawa903ad982001-02-23 16:40:48 +00004423
Barry Warsawa903ad982001-02-23 16:40:48 +00004424void _Py_ReleaseInternedStrings(void)
4425{
Guido van Rossum45ec02a2002-08-19 21:43:18 +00004426 PyObject *keys;
4427 PyStringObject *s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004428 Py_ssize_t i, n;
Guido van Rossum45ec02a2002-08-19 21:43:18 +00004429
4430 if (interned == NULL || !PyDict_Check(interned))
4431 return;
4432 keys = PyDict_Keys(interned);
4433 if (keys == NULL || !PyList_Check(keys)) {
4434 PyErr_Clear();
4435 return;
Barry Warsawa903ad982001-02-23 16:40:48 +00004436 }
Guido van Rossum45ec02a2002-08-19 21:43:18 +00004437
4438 /* Since _Py_ReleaseInternedStrings() is intended to help a leak
4439 detector, interned strings are not forcibly deallocated; rather, we
4440 give them their stolen references back, and then clear and DECREF
4441 the interned dict. */
Tim Petersae1d0c92006-03-17 03:29:34 +00004442
Guido van Rossum45ec02a2002-08-19 21:43:18 +00004443 fprintf(stderr, "releasing interned strings\n");
4444 n = PyList_GET_SIZE(keys);
4445 for (i = 0; i < n; i++) {
4446 s = (PyStringObject *) PyList_GET_ITEM(keys, i);
4447 switch (s->ob_sstate) {
4448 case SSTATE_NOT_INTERNED:
4449 /* XXX Shouldn't happen */
4450 break;
4451 case SSTATE_INTERNED_IMMORTAL:
4452 s->ob_refcnt += 1;
4453 break;
4454 case SSTATE_INTERNED_MORTAL:
4455 s->ob_refcnt += 2;
4456 break;
4457 default:
4458 Py_FatalError("Inconsistent interned string state.");
4459 }
4460 s->ob_sstate = SSTATE_NOT_INTERNED;
4461 }
4462 Py_DECREF(keys);
4463 PyDict_Clear(interned);
4464 Py_DECREF(interned);
4465 interned = NULL;
Barry Warsawa903ad982001-02-23 16:40:48 +00004466}