blob: 3ec45243d23c8019b18f7112536a5a02bf7550f2 [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{
Fredrik Lundh39ccef62006-05-25 15:22:03 +00002039 char *s;
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
Fredrik Lundh4b4e33e2006-05-25 15:49:45 +00002043 newobj = PyString_FromStringAndSize(NULL, n);
Fredrik Lundh39ccef62006-05-25 15:22:03 +00002044 if (!newobj)
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002045 return NULL;
Fredrik Lundh39ccef62006-05-25 15:22:03 +00002046
2047 s = PyString_AS_STRING(newobj);
2048
Fredrik Lundh4b4e33e2006-05-25 15:49:45 +00002049 memcpy(s, PyString_AS_STRING(self), n);
2050
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002051 for (i = 0; i < n; i++) {
Fredrik Lundh4b4e33e2006-05-25 15:49:45 +00002052 int c = Py_CHARMASK(s[i]);
Fredrik Lundh39ccef62006-05-25 15:22:03 +00002053 if (isupper(c))
2054 s[i] = _tolower(c);
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002055 }
Fredrik Lundh39ccef62006-05-25 15:22:03 +00002056
Anthony Baxtera6286212006-04-11 07:42:36 +00002057 return newobj;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002058}
2059
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002060PyDoc_STRVAR(upper__doc__,
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002061"S.upper() -> string\n\
2062\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002063Return a copy of the string S converted to uppercase.");
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002064
2065static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002066string_upper(PyStringObject *self)
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002067{
Fredrik Lundh39ccef62006-05-25 15:22:03 +00002068 char *s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002069 Py_ssize_t i, n = PyString_GET_SIZE(self);
Anthony Baxtera6286212006-04-11 07:42:36 +00002070 PyObject *newobj;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002071
Fredrik Lundh4b4e33e2006-05-25 15:49:45 +00002072 newobj = PyString_FromStringAndSize(NULL, n);
Fredrik Lundh39ccef62006-05-25 15:22:03 +00002073 if (!newobj)
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002074 return NULL;
Fredrik Lundh39ccef62006-05-25 15:22:03 +00002075
2076 s = PyString_AS_STRING(newobj);
2077
Fredrik Lundh4b4e33e2006-05-25 15:49:45 +00002078 memcpy(s, PyString_AS_STRING(self), n);
2079
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002080 for (i = 0; i < n; i++) {
Fredrik Lundh4b4e33e2006-05-25 15:49:45 +00002081 int c = Py_CHARMASK(s[i]);
Fredrik Lundh39ccef62006-05-25 15:22:03 +00002082 if (islower(c))
2083 s[i] = _toupper(c);
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002084 }
Fredrik Lundh39ccef62006-05-25 15:22:03 +00002085
Anthony Baxtera6286212006-04-11 07:42:36 +00002086 return newobj;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002087}
2088
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002089PyDoc_STRVAR(title__doc__,
Guido van Rossum4c08d552000-03-10 22:55:18 +00002090"S.title() -> string\n\
2091\n\
2092Return a titlecased version of S, i.e. words start with uppercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002093characters, all remaining cased characters have lowercase.");
Guido van Rossum4c08d552000-03-10 22:55:18 +00002094
2095static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002096string_title(PyStringObject *self)
Guido van Rossum4c08d552000-03-10 22:55:18 +00002097{
2098 char *s = PyString_AS_STRING(self), *s_new;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002099 Py_ssize_t i, n = PyString_GET_SIZE(self);
Guido van Rossum4c08d552000-03-10 22:55:18 +00002100 int previous_is_cased = 0;
Anthony Baxtera6286212006-04-11 07:42:36 +00002101 PyObject *newobj;
Guido van Rossum4c08d552000-03-10 22:55:18 +00002102
Anthony Baxtera6286212006-04-11 07:42:36 +00002103 newobj = PyString_FromStringAndSize(NULL, n);
2104 if (newobj == NULL)
Guido van Rossum4c08d552000-03-10 22:55:18 +00002105 return NULL;
Anthony Baxtera6286212006-04-11 07:42:36 +00002106 s_new = PyString_AsString(newobj);
Guido van Rossum4c08d552000-03-10 22:55:18 +00002107 for (i = 0; i < n; i++) {
2108 int c = Py_CHARMASK(*s++);
2109 if (islower(c)) {
2110 if (!previous_is_cased)
2111 c = toupper(c);
2112 previous_is_cased = 1;
2113 } else if (isupper(c)) {
2114 if (previous_is_cased)
2115 c = tolower(c);
2116 previous_is_cased = 1;
2117 } else
2118 previous_is_cased = 0;
2119 *s_new++ = c;
2120 }
Anthony Baxtera6286212006-04-11 07:42:36 +00002121 return newobj;
Guido van Rossum4c08d552000-03-10 22:55:18 +00002122}
2123
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002124PyDoc_STRVAR(capitalize__doc__,
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002125"S.capitalize() -> string\n\
2126\n\
2127Return a copy of the string S with only its first character\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002128capitalized.");
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002129
2130static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002131string_capitalize(PyStringObject *self)
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002132{
2133 char *s = PyString_AS_STRING(self), *s_new;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002134 Py_ssize_t i, n = PyString_GET_SIZE(self);
Anthony Baxtera6286212006-04-11 07:42:36 +00002135 PyObject *newobj;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002136
Anthony Baxtera6286212006-04-11 07:42:36 +00002137 newobj = PyString_FromStringAndSize(NULL, n);
2138 if (newobj == NULL)
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002139 return NULL;
Anthony Baxtera6286212006-04-11 07:42:36 +00002140 s_new = PyString_AsString(newobj);
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002141 if (0 < n) {
2142 int c = Py_CHARMASK(*s++);
2143 if (islower(c))
2144 *s_new = toupper(c);
2145 else
2146 *s_new = c;
2147 s_new++;
2148 }
2149 for (i = 1; i < n; i++) {
2150 int c = Py_CHARMASK(*s++);
2151 if (isupper(c))
2152 *s_new = tolower(c);
2153 else
2154 *s_new = c;
2155 s_new++;
2156 }
Anthony Baxtera6286212006-04-11 07:42:36 +00002157 return newobj;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002158}
2159
2160
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002161PyDoc_STRVAR(count__doc__,
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002162"S.count(sub[, start[, end]]) -> int\n\
2163\n\
Fredrik Lundh763b50f2006-05-22 15:35:12 +00002164Return the number of non-overlapping occurrences of substring sub in\n\
2165string S[start:end]. Optional arguments start and end are interpreted\n\
2166as in slice notation.");
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002167
2168static PyObject *
Fred Drakeba096332000-07-09 07:04:36 +00002169string_count(PyStringObject *self, PyObject *args)
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002170{
Raymond Hettinger57e74472005-02-20 09:54:53 +00002171 const char *s = PyString_AS_STRING(self), *sub, *t;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002172 Py_ssize_t len = PyString_GET_SIZE(self), n;
Martin v. Löwis8ce358f2006-04-13 07:22:51 +00002173 Py_ssize_t i = 0, last = PY_SSIZE_T_MAX;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002174 Py_ssize_t m, r;
Guido van Rossum4c08d552000-03-10 22:55:18 +00002175 PyObject *subobj;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002176
Guido van Rossumc6821402000-05-08 14:08:05 +00002177 if (!PyArg_ParseTuple(args, "O|O&O&:count", &subobj,
2178 _PyEval_SliceIndex, &i, _PyEval_SliceIndex, &last))
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002179 return NULL;
Guido van Rossumc6821402000-05-08 14:08:05 +00002180
Guido van Rossum4c08d552000-03-10 22:55:18 +00002181 if (PyString_Check(subobj)) {
2182 sub = PyString_AS_STRING(subobj);
2183 n = PyString_GET_SIZE(subobj);
2184 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002185#ifdef Py_USING_UNICODE
Marc-André Lemburg3a645e42001-01-16 11:54:12 +00002186 else if (PyUnicode_Check(subobj)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002187 Py_ssize_t count;
Marc-André Lemburg3a645e42001-01-16 11:54:12 +00002188 count = PyUnicode_Count((PyObject *)self, subobj, i, last);
2189 if (count == -1)
2190 return NULL;
2191 else
2192 return PyInt_FromLong((long) count);
2193 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002194#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +00002195 else if (PyObject_AsCharBuffer(subobj, &sub, &n))
2196 return NULL;
2197
Neal Norwitz1f68fc72002-06-14 00:50:42 +00002198 string_adjust_indices(&i, &last, len);
2199
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002200 m = last + 1 - n;
2201 if (n == 0)
Martin v. Löwis18e16552006-02-15 17:27:45 +00002202 return PyInt_FromSsize_t(m-i);
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002203
2204 r = 0;
2205 while (i < m) {
2206 if (!memcmp(s+i, sub, n)) {
2207 r++;
2208 i += n;
2209 } else {
2210 i++;
2211 }
Raymond Hettinger57e74472005-02-20 09:54:53 +00002212 if (i >= m)
2213 break;
Anthony Baxtera6286212006-04-11 07:42:36 +00002214 t = (const char *)memchr(s+i, sub[0], m-i);
Raymond Hettinger57e74472005-02-20 09:54:53 +00002215 if (t == NULL)
2216 break;
2217 i = t - s;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002218 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002219 return PyInt_FromSsize_t(r);
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002220}
2221
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002222PyDoc_STRVAR(swapcase__doc__,
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002223"S.swapcase() -> string\n\
2224\n\
Guido van Rossum4c08d552000-03-10 22:55:18 +00002225Return a copy of the string S with uppercase characters\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002226converted to lowercase and vice versa.");
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002227
2228static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002229string_swapcase(PyStringObject *self)
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002230{
2231 char *s = PyString_AS_STRING(self), *s_new;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002232 Py_ssize_t i, n = PyString_GET_SIZE(self);
Anthony Baxtera6286212006-04-11 07:42:36 +00002233 PyObject *newobj;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002234
Anthony Baxtera6286212006-04-11 07:42:36 +00002235 newobj = PyString_FromStringAndSize(NULL, n);
2236 if (newobj == NULL)
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002237 return NULL;
Anthony Baxtera6286212006-04-11 07:42:36 +00002238 s_new = PyString_AsString(newobj);
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002239 for (i = 0; i < n; i++) {
2240 int c = Py_CHARMASK(*s++);
2241 if (islower(c)) {
2242 *s_new = toupper(c);
2243 }
2244 else if (isupper(c)) {
2245 *s_new = tolower(c);
2246 }
2247 else
2248 *s_new = c;
2249 s_new++;
2250 }
Anthony Baxtera6286212006-04-11 07:42:36 +00002251 return newobj;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002252}
2253
2254
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002255PyDoc_STRVAR(translate__doc__,
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002256"S.translate(table [,deletechars]) -> string\n\
2257\n\
2258Return a copy of the string S, where all characters occurring\n\
2259in the optional argument deletechars are removed, and the\n\
2260remaining characters have been mapped through the given\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002261translation table, which must be a string of length 256.");
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002262
2263static PyObject *
Fred Drakeba096332000-07-09 07:04:36 +00002264string_translate(PyStringObject *self, PyObject *args)
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002265{
Guido van Rossum4c08d552000-03-10 22:55:18 +00002266 register char *input, *output;
2267 register const char *table;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002268 register Py_ssize_t i, c, changed = 0;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002269 PyObject *input_obj = (PyObject*)self;
Guido van Rossum4c08d552000-03-10 22:55:18 +00002270 const char *table1, *output_start, *del_table=NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002271 Py_ssize_t inlen, tablen, dellen = 0;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002272 PyObject *result;
2273 int trans_table[256];
Guido van Rossum4c08d552000-03-10 22:55:18 +00002274 PyObject *tableobj, *delobj = NULL;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002275
Raymond Hettingerea3fdf42002-12-29 16:33:45 +00002276 if (!PyArg_UnpackTuple(args, "translate", 1, 2,
Guido van Rossum4c08d552000-03-10 22:55:18 +00002277 &tableobj, &delobj))
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002278 return NULL;
Guido van Rossum4c08d552000-03-10 22:55:18 +00002279
2280 if (PyString_Check(tableobj)) {
2281 table1 = PyString_AS_STRING(tableobj);
2282 tablen = PyString_GET_SIZE(tableobj);
2283 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002284#ifdef Py_USING_UNICODE
Guido van Rossum4c08d552000-03-10 22:55:18 +00002285 else if (PyUnicode_Check(tableobj)) {
Tim Petersb3d8d1f2001-04-28 05:38:26 +00002286 /* Unicode .translate() does not support the deletechars
Guido van Rossum4c08d552000-03-10 22:55:18 +00002287 parameter; instead a mapping to None will cause characters
2288 to be deleted. */
2289 if (delobj != NULL) {
2290 PyErr_SetString(PyExc_TypeError,
2291 "deletions are implemented differently for unicode");
2292 return NULL;
2293 }
2294 return PyUnicode_Translate((PyObject *)self, tableobj, NULL);
2295 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002296#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +00002297 else if (PyObject_AsCharBuffer(tableobj, &table1, &tablen))
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002298 return NULL;
Guido van Rossum4c08d552000-03-10 22:55:18 +00002299
Martin v. Löwis00b61272002-12-12 20:03:19 +00002300 if (tablen != 256) {
2301 PyErr_SetString(PyExc_ValueError,
2302 "translation table must be 256 characters long");
2303 return NULL;
2304 }
2305
Guido van Rossum4c08d552000-03-10 22:55:18 +00002306 if (delobj != NULL) {
2307 if (PyString_Check(delobj)) {
2308 del_table = PyString_AS_STRING(delobj);
2309 dellen = PyString_GET_SIZE(delobj);
2310 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002311#ifdef Py_USING_UNICODE
Guido van Rossum4c08d552000-03-10 22:55:18 +00002312 else if (PyUnicode_Check(delobj)) {
2313 PyErr_SetString(PyExc_TypeError,
2314 "deletions are implemented differently for unicode");
2315 return NULL;
2316 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002317#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +00002318 else if (PyObject_AsCharBuffer(delobj, &del_table, &dellen))
2319 return NULL;
Guido van Rossum4c08d552000-03-10 22:55:18 +00002320 }
2321 else {
2322 del_table = NULL;
2323 dellen = 0;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002324 }
2325
2326 table = table1;
Neal Norwitz2aa9a5d2006-03-20 01:53:23 +00002327 inlen = PyString_GET_SIZE(input_obj);
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002328 result = PyString_FromStringAndSize((char *)NULL, inlen);
2329 if (result == NULL)
2330 return NULL;
2331 output_start = output = PyString_AsString(result);
Neal Norwitz2aa9a5d2006-03-20 01:53:23 +00002332 input = PyString_AS_STRING(input_obj);
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002333
2334 if (dellen == 0) {
2335 /* If no deletions are required, use faster code */
2336 for (i = inlen; --i >= 0; ) {
2337 c = Py_CHARMASK(*input++);
2338 if (Py_CHARMASK((*output++ = table[c])) != c)
2339 changed = 1;
2340 }
Tim Peters8fa5dd02001-09-12 02:18:30 +00002341 if (changed || !PyString_CheckExact(input_obj))
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002342 return result;
2343 Py_DECREF(result);
2344 Py_INCREF(input_obj);
2345 return input_obj;
2346 }
2347
2348 for (i = 0; i < 256; i++)
2349 trans_table[i] = Py_CHARMASK(table[i]);
2350
2351 for (i = 0; i < dellen; i++)
2352 trans_table[(int) Py_CHARMASK(del_table[i])] = -1;
2353
2354 for (i = inlen; --i >= 0; ) {
2355 c = Py_CHARMASK(*input++);
2356 if (trans_table[c] != -1)
2357 if (Py_CHARMASK(*output++ = (char)trans_table[c]) == c)
2358 continue;
2359 changed = 1;
2360 }
Tim Peters8fa5dd02001-09-12 02:18:30 +00002361 if (!changed && PyString_CheckExact(input_obj)) {
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002362 Py_DECREF(result);
2363 Py_INCREF(input_obj);
2364 return input_obj;
2365 }
2366 /* Fix the size of the resulting string */
Tim Peters5de98422002-04-27 18:44:32 +00002367 if (inlen > 0)
2368 _PyString_Resize(&result, output - output_start);
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002369 return result;
2370}
2371
2372
2373/* What follows is used for implementing replace(). Perry Stoll. */
2374
2375/*
2376 mymemfind
2377
2378 strstr replacement for arbitrary blocks of memory.
2379
Barry Warsaw51ac5802000-03-20 16:36:48 +00002380 Locates the first occurrence in the memory pointed to by MEM of the
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002381 contents of memory pointed to by PAT. Returns the index into MEM if
2382 found, or -1 if not found. If len of PAT is greater than length of
2383 MEM, the function returns -1.
2384*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00002385static Py_ssize_t
2386mymemfind(const char *mem, Py_ssize_t len, const char *pat, Py_ssize_t pat_len)
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002387{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002388 register Py_ssize_t ii;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002389
2390 /* pattern can not occur in the last pat_len-1 chars */
2391 len -= pat_len;
2392
2393 for (ii = 0; ii <= len; ii++) {
Fred Drake396f6e02000-06-20 15:47:54 +00002394 if (mem[ii] == pat[0] && memcmp(&mem[ii], pat, pat_len) == 0) {
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002395 return ii;
2396 }
2397 }
2398 return -1;
2399}
2400
2401/*
2402 mymemcnt
2403
2404 Return the number of distinct times PAT is found in MEM.
2405 meaning mem=1111 and pat==11 returns 2.
2406 mem=11111 and pat==11 also return 2.
2407 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002408static Py_ssize_t
2409mymemcnt(const char *mem, Py_ssize_t len, const char *pat, Py_ssize_t pat_len)
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002410{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002411 register Py_ssize_t offset = 0;
2412 Py_ssize_t nfound = 0;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002413
2414 while (len >= 0) {
2415 offset = mymemfind(mem, len, pat, pat_len);
2416 if (offset == -1)
2417 break;
2418 mem += offset + pat_len;
2419 len -= offset + pat_len;
2420 nfound++;
2421 }
2422 return nfound;
2423}
2424
2425/*
2426 mymemreplace
2427
Thomas Wouters7e474022000-07-16 12:04:32 +00002428 Return a string in which all occurrences of PAT in memory STR are
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002429 replaced with SUB.
2430
Thomas Wouters7e474022000-07-16 12:04:32 +00002431 If length of PAT is less than length of STR or there are no occurrences
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002432 of PAT in STR, then the original string is returned. Otherwise, a new
2433 string is allocated here and returned.
2434
2435 on return, out_len is:
2436 the length of output string, or
2437 -1 if the input string is returned, or
2438 unchanged if an error occurs (no memory).
2439
2440 return value is:
2441 the new string allocated locally, or
2442 NULL if an error occurred.
2443*/
2444static char *
Martin v. Löwis18e16552006-02-15 17:27:45 +00002445mymemreplace(const char *str, Py_ssize_t len, /* input string */
2446 const char *pat, Py_ssize_t pat_len, /* pattern string to find */
2447 const char *sub, Py_ssize_t sub_len, /* substitution string */
2448 Py_ssize_t count, /* number of replacements */
2449 Py_ssize_t *out_len)
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002450{
2451 char *out_s;
2452 char *new_s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002453 Py_ssize_t nfound, offset, new_len;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002454
Guido van Rossum8b1a6d62002-08-23 18:21:28 +00002455 if (len == 0 || (pat_len == 0 && sub_len == 0) || pat_len > len)
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002456 goto return_same;
2457
2458 /* find length of output string */
Guido van Rossum8b1a6d62002-08-23 18:21:28 +00002459 nfound = (pat_len > 0) ? mymemcnt(str, len, pat, pat_len) : len + 1;
Tim Peters9c012af2001-05-10 00:32:57 +00002460 if (count < 0)
Martin v. Löwis8ce358f2006-04-13 07:22:51 +00002461 count = PY_SSIZE_T_MAX;
Tim Peters9c012af2001-05-10 00:32:57 +00002462 else if (nfound > count)
2463 nfound = count;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002464 if (nfound == 0)
2465 goto return_same;
Tim Peters4cd44ef2001-05-10 00:05:33 +00002466
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002467 new_len = len + nfound*(sub_len - pat_len);
Tim Peters4cd44ef2001-05-10 00:05:33 +00002468 if (new_len == 0) {
2469 /* Have to allocate something for the caller to free(). */
2470 out_s = (char *)PyMem_MALLOC(1);
Tim Peters9c012af2001-05-10 00:32:57 +00002471 if (out_s == NULL)
Tim Peters4cd44ef2001-05-10 00:05:33 +00002472 return NULL;
2473 out_s[0] = '\0';
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002474 }
Tim Peters4cd44ef2001-05-10 00:05:33 +00002475 else {
2476 assert(new_len > 0);
2477 new_s = (char *)PyMem_MALLOC(new_len);
2478 if (new_s == NULL)
2479 return NULL;
2480 out_s = new_s;
2481
Guido van Rossum8b1a6d62002-08-23 18:21:28 +00002482 if (pat_len > 0) {
2483 for (; nfound > 0; --nfound) {
2484 /* find index of next instance of pattern */
2485 offset = mymemfind(str, len, pat, pat_len);
2486 if (offset == -1)
2487 break;
Tim Peters4cd44ef2001-05-10 00:05:33 +00002488
Guido van Rossum8b1a6d62002-08-23 18:21:28 +00002489 /* copy non matching part of input string */
2490 memcpy(new_s, str, offset);
2491 str += offset + pat_len;
2492 len -= offset + pat_len;
Tim Peters4cd44ef2001-05-10 00:05:33 +00002493
Guido van Rossum8b1a6d62002-08-23 18:21:28 +00002494 /* copy substitute into the output string */
2495 new_s += offset;
2496 memcpy(new_s, sub, sub_len);
2497 new_s += sub_len;
2498 }
2499 /* copy any remaining values into output string */
2500 if (len > 0)
2501 memcpy(new_s, str, len);
Tim Peters4cd44ef2001-05-10 00:05:33 +00002502 }
Guido van Rossum8b1a6d62002-08-23 18:21:28 +00002503 else {
2504 for (;;++str, --len) {
2505 memcpy(new_s, sub, sub_len);
2506 new_s += sub_len;
2507 if (--nfound <= 0) {
2508 memcpy(new_s, str, len);
2509 break;
2510 }
2511 *new_s++ = *str;
2512 }
2513 }
Tim Peters4cd44ef2001-05-10 00:05:33 +00002514 }
2515 *out_len = new_len;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002516 return out_s;
2517
2518 return_same:
2519 *out_len = -1;
Tim Peters4cd44ef2001-05-10 00:05:33 +00002520 return (char *)str; /* cast away const */
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002521}
2522
2523
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002524PyDoc_STRVAR(replace__doc__,
Fred Draked22bb652003-10-22 02:56:40 +00002525"S.replace (old, new[, count]) -> string\n\
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002526\n\
2527Return a copy of string S with all occurrences of substring\n\
Fred Draked22bb652003-10-22 02:56:40 +00002528old replaced by new. If the optional argument count is\n\
2529given, only the first count occurrences are replaced.");
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002530
2531static PyObject *
Fred Drakeba096332000-07-09 07:04:36 +00002532string_replace(PyStringObject *self, PyObject *args)
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002533{
Guido van Rossum4c08d552000-03-10 22:55:18 +00002534 const char *str = PyString_AS_STRING(self), *sub, *repl;
2535 char *new_s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002536 const Py_ssize_t len = PyString_GET_SIZE(self);
2537 Py_ssize_t sub_len, repl_len, out_len;
Thomas Woutersdc5f8082006-04-19 15:38:01 +00002538 Py_ssize_t count = -1;
Anthony Baxtera6286212006-04-11 07:42:36 +00002539 PyObject *newobj;
Guido van Rossum4c08d552000-03-10 22:55:18 +00002540 PyObject *subobj, *replobj;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002541
Thomas Woutersdc5f8082006-04-19 15:38:01 +00002542 if (!PyArg_ParseTuple(args, "OO|n:replace",
Guido van Rossum4c08d552000-03-10 22:55:18 +00002543 &subobj, &replobj, &count))
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002544 return NULL;
Guido van Rossum4c08d552000-03-10 22:55:18 +00002545
2546 if (PyString_Check(subobj)) {
2547 sub = PyString_AS_STRING(subobj);
2548 sub_len = PyString_GET_SIZE(subobj);
2549 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002550#ifdef Py_USING_UNICODE
Guido van Rossum4c08d552000-03-10 22:55:18 +00002551 else if (PyUnicode_Check(subobj))
Tim Petersb3d8d1f2001-04-28 05:38:26 +00002552 return PyUnicode_Replace((PyObject *)self,
Guido van Rossum4c08d552000-03-10 22:55:18 +00002553 subobj, replobj, count);
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002554#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +00002555 else if (PyObject_AsCharBuffer(subobj, &sub, &sub_len))
2556 return NULL;
2557
2558 if (PyString_Check(replobj)) {
2559 repl = PyString_AS_STRING(replobj);
2560 repl_len = PyString_GET_SIZE(replobj);
2561 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002562#ifdef Py_USING_UNICODE
Guido van Rossum4c08d552000-03-10 22:55:18 +00002563 else if (PyUnicode_Check(replobj))
Tim Petersb3d8d1f2001-04-28 05:38:26 +00002564 return PyUnicode_Replace((PyObject *)self,
Guido van Rossum4c08d552000-03-10 22:55:18 +00002565 subobj, replobj, count);
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002566#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +00002567 else if (PyObject_AsCharBuffer(replobj, &repl, &repl_len))
2568 return NULL;
2569
Guido van Rossum4c08d552000-03-10 22:55:18 +00002570 new_s = mymemreplace(str,len,sub,sub_len,repl,repl_len,count,&out_len);
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002571 if (new_s == NULL) {
2572 PyErr_NoMemory();
2573 return NULL;
2574 }
2575 if (out_len == -1) {
Tim Peters8fa5dd02001-09-12 02:18:30 +00002576 if (PyString_CheckExact(self)) {
2577 /* we're returning another reference to self */
Anthony Baxtera6286212006-04-11 07:42:36 +00002578 newobj = (PyObject*)self;
2579 Py_INCREF(newobj);
Tim Peters8fa5dd02001-09-12 02:18:30 +00002580 }
2581 else {
Anthony Baxtera6286212006-04-11 07:42:36 +00002582 newobj = PyString_FromStringAndSize(str, len);
2583 if (newobj == NULL)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002584 return NULL;
2585 }
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002586 }
2587 else {
Anthony Baxtera6286212006-04-11 07:42:36 +00002588 newobj = PyString_FromStringAndSize(new_s, out_len);
Guido van Rossumb18618d2000-05-03 23:44:39 +00002589 PyMem_FREE(new_s);
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002590 }
Anthony Baxtera6286212006-04-11 07:42:36 +00002591 return newobj;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002592}
2593
2594
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002595PyDoc_STRVAR(startswith__doc__,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002596"S.startswith(prefix[, start[, end]]) -> bool\n\
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002597\n\
Guido van Rossuma7132182003-04-09 19:32:45 +00002598Return True if S starts with the specified prefix, False otherwise.\n\
2599With optional start, test S beginning at that position.\n\
2600With optional end, stop comparing S at that position.");
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002601
2602static PyObject *
Fred Drakeba096332000-07-09 07:04:36 +00002603string_startswith(PyStringObject *self, PyObject *args)
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002604{
Guido van Rossum4c08d552000-03-10 22:55:18 +00002605 const char* str = PyString_AS_STRING(self);
Martin v. Löwis18e16552006-02-15 17:27:45 +00002606 Py_ssize_t len = PyString_GET_SIZE(self);
Guido van Rossum4c08d552000-03-10 22:55:18 +00002607 const char* prefix;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002608 Py_ssize_t plen;
2609 Py_ssize_t start = 0;
Martin v. Löwis8ce358f2006-04-13 07:22:51 +00002610 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossum4c08d552000-03-10 22:55:18 +00002611 PyObject *subobj;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002612
Guido van Rossumc6821402000-05-08 14:08:05 +00002613 if (!PyArg_ParseTuple(args, "O|O&O&:startswith", &subobj,
2614 _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
Guido van Rossum4c08d552000-03-10 22:55:18 +00002615 return NULL;
2616 if (PyString_Check(subobj)) {
2617 prefix = PyString_AS_STRING(subobj);
2618 plen = PyString_GET_SIZE(subobj);
2619 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002620#ifdef Py_USING_UNICODE
Marc-André Lemburg3a645e42001-01-16 11:54:12 +00002621 else if (PyUnicode_Check(subobj)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002622 Py_ssize_t rc;
Tim Petersb3d8d1f2001-04-28 05:38:26 +00002623 rc = PyUnicode_Tailmatch((PyObject *)self,
Marc-André Lemburg3a645e42001-01-16 11:54:12 +00002624 subobj, start, end, -1);
2625 if (rc == -1)
2626 return NULL;
2627 else
Guido van Rossum77f6a652002-04-03 22:41:51 +00002628 return PyBool_FromLong((long) rc);
Marc-André Lemburg3a645e42001-01-16 11:54:12 +00002629 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002630#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +00002631 else if (PyObject_AsCharBuffer(subobj, &prefix, &plen))
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002632 return NULL;
2633
Neal Norwitz1f68fc72002-06-14 00:50:42 +00002634 string_adjust_indices(&start, &end, len);
2635
2636 if (start+plen > len)
Guido van Rossum77f6a652002-04-03 22:41:51 +00002637 return PyBool_FromLong(0);
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002638
Neal Norwitz1f68fc72002-06-14 00:50:42 +00002639 if (end-start >= plen)
2640 return PyBool_FromLong(!memcmp(str+start, prefix, plen));
2641 else
2642 return PyBool_FromLong(0);
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002643}
2644
2645
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002646PyDoc_STRVAR(endswith__doc__,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002647"S.endswith(suffix[, start[, end]]) -> bool\n\
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002648\n\
Guido van Rossuma7132182003-04-09 19:32:45 +00002649Return True if S ends with the specified suffix, False otherwise.\n\
2650With optional start, test S beginning at that position.\n\
2651With optional end, stop comparing S at that position.");
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002652
2653static PyObject *
Fred Drakeba096332000-07-09 07:04:36 +00002654string_endswith(PyStringObject *self, PyObject *args)
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002655{
Guido van Rossum4c08d552000-03-10 22:55:18 +00002656 const char* str = PyString_AS_STRING(self);
Martin v. Löwis18e16552006-02-15 17:27:45 +00002657 Py_ssize_t len = PyString_GET_SIZE(self);
Guido van Rossum4c08d552000-03-10 22:55:18 +00002658 const char* suffix;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002659 Py_ssize_t slen;
2660 Py_ssize_t start = 0;
Martin v. Löwis8ce358f2006-04-13 07:22:51 +00002661 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossum4c08d552000-03-10 22:55:18 +00002662 PyObject *subobj;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002663
Guido van Rossumc6821402000-05-08 14:08:05 +00002664 if (!PyArg_ParseTuple(args, "O|O&O&:endswith", &subobj,
2665 _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
Guido van Rossum4c08d552000-03-10 22:55:18 +00002666 return NULL;
2667 if (PyString_Check(subobj)) {
2668 suffix = PyString_AS_STRING(subobj);
2669 slen = PyString_GET_SIZE(subobj);
2670 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002671#ifdef Py_USING_UNICODE
Marc-André Lemburg3a645e42001-01-16 11:54:12 +00002672 else if (PyUnicode_Check(subobj)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002673 Py_ssize_t rc;
Tim Petersb3d8d1f2001-04-28 05:38:26 +00002674 rc = PyUnicode_Tailmatch((PyObject *)self,
Marc-André Lemburg3a645e42001-01-16 11:54:12 +00002675 subobj, start, end, +1);
2676 if (rc == -1)
2677 return NULL;
2678 else
Guido van Rossum77f6a652002-04-03 22:41:51 +00002679 return PyBool_FromLong((long) rc);
Marc-André Lemburg3a645e42001-01-16 11:54:12 +00002680 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002681#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +00002682 else if (PyObject_AsCharBuffer(subobj, &suffix, &slen))
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002683 return NULL;
2684
Neal Norwitz1f68fc72002-06-14 00:50:42 +00002685 string_adjust_indices(&start, &end, len);
2686
2687 if (end-start < slen || start > len)
Guido van Rossum77f6a652002-04-03 22:41:51 +00002688 return PyBool_FromLong(0);
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002689
Neal Norwitz1f68fc72002-06-14 00:50:42 +00002690 if (end-slen > start)
2691 start = end - slen;
2692 if (end-start >= slen)
2693 return PyBool_FromLong(!memcmp(str+start, suffix, slen));
2694 else
2695 return PyBool_FromLong(0);
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002696}
2697
2698
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002699PyDoc_STRVAR(encode__doc__,
Marc-André Lemburg2d920412001-05-15 12:00:02 +00002700"S.encode([encoding[,errors]]) -> object\n\
Marc-André Lemburg63f3d172000-07-06 11:29:01 +00002701\n\
Marc-André Lemburg2d920412001-05-15 12:00:02 +00002702Encodes S using the codec registered for encoding. encoding defaults\n\
2703to the default encoding. errors may be given to set a different error\n\
Marc-André Lemburg63f3d172000-07-06 11:29:01 +00002704handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002705a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
2706'xmlcharrefreplace' as well as any other name registered with\n\
2707codecs.register_error that is able to handle UnicodeEncodeErrors.");
Marc-André Lemburg63f3d172000-07-06 11:29:01 +00002708
2709static PyObject *
2710string_encode(PyStringObject *self, PyObject *args)
2711{
2712 char *encoding = NULL;
2713 char *errors = NULL;
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002714 PyObject *v;
Tim Petersae1d0c92006-03-17 03:29:34 +00002715
Marc-André Lemburg63f3d172000-07-06 11:29:01 +00002716 if (!PyArg_ParseTuple(args, "|ss:encode", &encoding, &errors))
2717 return NULL;
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002718 v = PyString_AsEncodedObject((PyObject *)self, encoding, errors);
Marc-André Lemburg1dffb122004-07-08 19:13:55 +00002719 if (v == NULL)
2720 goto onError;
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002721 if (!PyString_Check(v) && !PyUnicode_Check(v)) {
2722 PyErr_Format(PyExc_TypeError,
2723 "encoder did not return a string/unicode object "
2724 "(type=%.400s)",
2725 v->ob_type->tp_name);
2726 Py_DECREF(v);
2727 return NULL;
2728 }
2729 return v;
Marc-André Lemburg1dffb122004-07-08 19:13:55 +00002730
2731 onError:
2732 return NULL;
Marc-André Lemburg2d920412001-05-15 12:00:02 +00002733}
2734
2735
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002736PyDoc_STRVAR(decode__doc__,
Marc-André Lemburg2d920412001-05-15 12:00:02 +00002737"S.decode([encoding[,errors]]) -> object\n\
2738\n\
2739Decodes S using the codec registered for encoding. encoding defaults\n\
2740to the default encoding. errors may be given to set a different error\n\
2741handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002742a UnicodeDecodeError. Other possible values are 'ignore' and 'replace'\n\
2743as well as any other name registerd with codecs.register_error that is\n\
2744able to handle UnicodeDecodeErrors.");
Marc-André Lemburg2d920412001-05-15 12:00:02 +00002745
2746static PyObject *
2747string_decode(PyStringObject *self, PyObject *args)
2748{
2749 char *encoding = NULL;
2750 char *errors = NULL;
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002751 PyObject *v;
Tim Petersae1d0c92006-03-17 03:29:34 +00002752
Marc-André Lemburg2d920412001-05-15 12:00:02 +00002753 if (!PyArg_ParseTuple(args, "|ss:decode", &encoding, &errors))
2754 return NULL;
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002755 v = PyString_AsDecodedObject((PyObject *)self, encoding, errors);
Marc-André Lemburg1dffb122004-07-08 19:13:55 +00002756 if (v == NULL)
2757 goto onError;
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002758 if (!PyString_Check(v) && !PyUnicode_Check(v)) {
2759 PyErr_Format(PyExc_TypeError,
2760 "decoder did not return a string/unicode object "
2761 "(type=%.400s)",
2762 v->ob_type->tp_name);
2763 Py_DECREF(v);
2764 return NULL;
2765 }
2766 return v;
Marc-André Lemburg1dffb122004-07-08 19:13:55 +00002767
2768 onError:
2769 return NULL;
Marc-André Lemburg63f3d172000-07-06 11:29:01 +00002770}
2771
2772
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002773PyDoc_STRVAR(expandtabs__doc__,
Guido van Rossum4c08d552000-03-10 22:55:18 +00002774"S.expandtabs([tabsize]) -> string\n\
2775\n\
2776Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002777If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossum4c08d552000-03-10 22:55:18 +00002778
2779static PyObject*
2780string_expandtabs(PyStringObject *self, PyObject *args)
2781{
2782 const char *e, *p;
2783 char *q;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002784 Py_ssize_t i, j;
Guido van Rossum4c08d552000-03-10 22:55:18 +00002785 PyObject *u;
2786 int tabsize = 8;
2787
2788 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
2789 return NULL;
2790
Thomas Wouters7e474022000-07-16 12:04:32 +00002791 /* First pass: determine size of output string */
Guido van Rossum4c08d552000-03-10 22:55:18 +00002792 i = j = 0;
2793 e = PyString_AS_STRING(self) + PyString_GET_SIZE(self);
2794 for (p = PyString_AS_STRING(self); p < e; p++)
2795 if (*p == '\t') {
2796 if (tabsize > 0)
2797 j += tabsize - (j % tabsize);
2798 }
2799 else {
2800 j++;
2801 if (*p == '\n' || *p == '\r') {
2802 i += j;
2803 j = 0;
2804 }
2805 }
2806
2807 /* Second pass: create output string and fill it */
2808 u = PyString_FromStringAndSize(NULL, i + j);
2809 if (!u)
2810 return NULL;
2811
2812 j = 0;
2813 q = PyString_AS_STRING(u);
2814
2815 for (p = PyString_AS_STRING(self); p < e; p++)
2816 if (*p == '\t') {
2817 if (tabsize > 0) {
2818 i = tabsize - (j % tabsize);
2819 j += i;
2820 while (i--)
2821 *q++ = ' ';
2822 }
2823 }
2824 else {
2825 j++;
2826 *q++ = *p;
2827 if (*p == '\n' || *p == '\r')
2828 j = 0;
2829 }
2830
2831 return u;
2832}
2833
Tim Peters8fa5dd02001-09-12 02:18:30 +00002834static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00002835pad(PyStringObject *self, Py_ssize_t left, Py_ssize_t right, char fill)
Guido van Rossum4c08d552000-03-10 22:55:18 +00002836{
2837 PyObject *u;
2838
2839 if (left < 0)
2840 left = 0;
2841 if (right < 0)
2842 right = 0;
2843
Tim Peters8fa5dd02001-09-12 02:18:30 +00002844 if (left == 0 && right == 0 && PyString_CheckExact(self)) {
Guido van Rossum4c08d552000-03-10 22:55:18 +00002845 Py_INCREF(self);
2846 return (PyObject *)self;
2847 }
2848
Tim Petersb3d8d1f2001-04-28 05:38:26 +00002849 u = PyString_FromStringAndSize(NULL,
Guido van Rossum4c08d552000-03-10 22:55:18 +00002850 left + PyString_GET_SIZE(self) + right);
2851 if (u) {
2852 if (left)
2853 memset(PyString_AS_STRING(u), fill, left);
Tim Petersb3d8d1f2001-04-28 05:38:26 +00002854 memcpy(PyString_AS_STRING(u) + left,
2855 PyString_AS_STRING(self),
Guido van Rossum4c08d552000-03-10 22:55:18 +00002856 PyString_GET_SIZE(self));
2857 if (right)
2858 memset(PyString_AS_STRING(u) + left + PyString_GET_SIZE(self),
2859 fill, right);
2860 }
2861
2862 return u;
2863}
2864
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002865PyDoc_STRVAR(ljust__doc__,
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00002866"S.ljust(width[, fillchar]) -> string\n"
Tim Peters8fa5dd02001-09-12 02:18:30 +00002867"\n"
2868"Return S left justified in a string of length width. Padding is\n"
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00002869"done using the specified fill character (default is a space).");
Guido van Rossum4c08d552000-03-10 22:55:18 +00002870
2871static PyObject *
2872string_ljust(PyStringObject *self, PyObject *args)
2873{
Thomas Wouters4abb3662006-04-19 14:50:15 +00002874 Py_ssize_t width;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00002875 char fillchar = ' ';
2876
Thomas Wouters4abb3662006-04-19 14:50:15 +00002877 if (!PyArg_ParseTuple(args, "n|c:ljust", &width, &fillchar))
Guido van Rossum4c08d552000-03-10 22:55:18 +00002878 return NULL;
2879
Tim Peters8fa5dd02001-09-12 02:18:30 +00002880 if (PyString_GET_SIZE(self) >= width && PyString_CheckExact(self)) {
Guido van Rossum4c08d552000-03-10 22:55:18 +00002881 Py_INCREF(self);
2882 return (PyObject*) self;
2883 }
2884
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00002885 return pad(self, 0, width - PyString_GET_SIZE(self), fillchar);
Guido van Rossum4c08d552000-03-10 22:55:18 +00002886}
2887
2888
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002889PyDoc_STRVAR(rjust__doc__,
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00002890"S.rjust(width[, fillchar]) -> string\n"
Tim Peters8fa5dd02001-09-12 02:18:30 +00002891"\n"
2892"Return S right justified in a string of length width. Padding is\n"
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00002893"done using the specified fill character (default is a space)");
Guido van Rossum4c08d552000-03-10 22:55:18 +00002894
2895static PyObject *
2896string_rjust(PyStringObject *self, PyObject *args)
2897{
Thomas Wouters4abb3662006-04-19 14:50:15 +00002898 Py_ssize_t width;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00002899 char fillchar = ' ';
2900
Thomas Wouters4abb3662006-04-19 14:50:15 +00002901 if (!PyArg_ParseTuple(args, "n|c:rjust", &width, &fillchar))
Guido van Rossum4c08d552000-03-10 22:55:18 +00002902 return NULL;
2903
Tim Peters8fa5dd02001-09-12 02:18:30 +00002904 if (PyString_GET_SIZE(self) >= width && PyString_CheckExact(self)) {
Guido van Rossum4c08d552000-03-10 22:55:18 +00002905 Py_INCREF(self);
2906 return (PyObject*) self;
2907 }
2908
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00002909 return pad(self, width - PyString_GET_SIZE(self), 0, fillchar);
Guido van Rossum4c08d552000-03-10 22:55:18 +00002910}
2911
2912
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002913PyDoc_STRVAR(center__doc__,
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00002914"S.center(width[, fillchar]) -> string\n"
Tim Peters8fa5dd02001-09-12 02:18:30 +00002915"\n"
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00002916"Return S centered in a string of length width. Padding is\n"
2917"done using the specified fill character (default is a space)");
Guido van Rossum4c08d552000-03-10 22:55:18 +00002918
2919static PyObject *
2920string_center(PyStringObject *self, PyObject *args)
2921{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002922 Py_ssize_t marg, left;
Thomas Wouters4abb3662006-04-19 14:50:15 +00002923 Py_ssize_t width;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00002924 char fillchar = ' ';
Guido van Rossum4c08d552000-03-10 22:55:18 +00002925
Thomas Wouters4abb3662006-04-19 14:50:15 +00002926 if (!PyArg_ParseTuple(args, "n|c:center", &width, &fillchar))
Guido van Rossum4c08d552000-03-10 22:55:18 +00002927 return NULL;
2928
Tim Peters8fa5dd02001-09-12 02:18:30 +00002929 if (PyString_GET_SIZE(self) >= width && PyString_CheckExact(self)) {
Guido van Rossum4c08d552000-03-10 22:55:18 +00002930 Py_INCREF(self);
2931 return (PyObject*) self;
2932 }
2933
2934 marg = width - PyString_GET_SIZE(self);
2935 left = marg / 2 + (marg & width & 1);
2936
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00002937 return pad(self, left, marg - left, fillchar);
Guido van Rossum4c08d552000-03-10 22:55:18 +00002938}
2939
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002940PyDoc_STRVAR(zfill__doc__,
Walter Dörwald068325e2002-04-15 13:36:47 +00002941"S.zfill(width) -> string\n"
2942"\n"
2943"Pad a numeric string S with zeros on the left, to fill a field\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002944"of the specified width. The string S is never truncated.");
Walter Dörwald068325e2002-04-15 13:36:47 +00002945
2946static PyObject *
2947string_zfill(PyStringObject *self, PyObject *args)
2948{
Martin v. Löwiseb079f12006-02-16 14:32:27 +00002949 Py_ssize_t fill;
Walter Dörwald068325e2002-04-15 13:36:47 +00002950 PyObject *s;
Guido van Rossum3aa3fc42002-04-15 13:48:52 +00002951 char *p;
Thomas Wouters4abb3662006-04-19 14:50:15 +00002952 Py_ssize_t width;
Walter Dörwald068325e2002-04-15 13:36:47 +00002953
Thomas Wouters4abb3662006-04-19 14:50:15 +00002954 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Walter Dörwald068325e2002-04-15 13:36:47 +00002955 return NULL;
2956
2957 if (PyString_GET_SIZE(self) >= width) {
Walter Dörwald0fe940c2002-04-15 18:42:15 +00002958 if (PyString_CheckExact(self)) {
2959 Py_INCREF(self);
2960 return (PyObject*) self;
2961 }
2962 else
2963 return PyString_FromStringAndSize(
2964 PyString_AS_STRING(self),
2965 PyString_GET_SIZE(self)
2966 );
Walter Dörwald068325e2002-04-15 13:36:47 +00002967 }
2968
2969 fill = width - PyString_GET_SIZE(self);
2970
2971 s = pad(self, fill, 0, '0');
2972
2973 if (s == NULL)
2974 return NULL;
2975
2976 p = PyString_AS_STRING(s);
2977 if (p[fill] == '+' || p[fill] == '-') {
2978 /* move sign to beginning of string */
2979 p[0] = p[fill];
2980 p[fill] = '0';
2981 }
2982
2983 return (PyObject*) s;
2984}
2985
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002986PyDoc_STRVAR(isspace__doc__,
Martin v. Löwis6828e182003-10-18 09:55:08 +00002987"S.isspace() -> bool\n\
2988\n\
2989Return True if all characters in S are whitespace\n\
2990and there is at least one character in S, False otherwise.");
Guido van Rossum4c08d552000-03-10 22:55:18 +00002991
2992static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002993string_isspace(PyStringObject *self)
Guido van Rossum4c08d552000-03-10 22:55:18 +00002994{
Fred Drakeba096332000-07-09 07:04:36 +00002995 register const unsigned char *p
2996 = (unsigned char *) PyString_AS_STRING(self);
Guido van Rossumb8f820c2000-05-05 20:44:24 +00002997 register const unsigned char *e;
Guido van Rossum4c08d552000-03-10 22:55:18 +00002998
Guido van Rossum4c08d552000-03-10 22:55:18 +00002999 /* Shortcut for single character strings */
3000 if (PyString_GET_SIZE(self) == 1 &&
3001 isspace(*p))
Guido van Rossum77f6a652002-04-03 22:41:51 +00003002 return PyBool_FromLong(1);
Guido van Rossum4c08d552000-03-10 22:55:18 +00003003
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00003004 /* Special case for empty strings */
3005 if (PyString_GET_SIZE(self) == 0)
Guido van Rossum77f6a652002-04-03 22:41:51 +00003006 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00003007
Guido van Rossum4c08d552000-03-10 22:55:18 +00003008 e = p + PyString_GET_SIZE(self);
3009 for (; p < e; p++) {
3010 if (!isspace(*p))
Guido van Rossum77f6a652002-04-03 22:41:51 +00003011 return PyBool_FromLong(0);
Guido van Rossum4c08d552000-03-10 22:55:18 +00003012 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00003013 return PyBool_FromLong(1);
Guido van Rossum4c08d552000-03-10 22:55:18 +00003014}
3015
3016
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003017PyDoc_STRVAR(isalpha__doc__,
Guido van Rossum77f6a652002-04-03 22:41:51 +00003018"S.isalpha() -> bool\n\
Marc-André Lemburg4027f8f2000-07-05 09:47:46 +00003019\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00003020Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003021and there is at least one character in S, False otherwise.");
Marc-André Lemburg4027f8f2000-07-05 09:47:46 +00003022
3023static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00003024string_isalpha(PyStringObject *self)
Marc-André Lemburg4027f8f2000-07-05 09:47:46 +00003025{
Fred Drakeba096332000-07-09 07:04:36 +00003026 register const unsigned char *p
3027 = (unsigned char *) PyString_AS_STRING(self);
Marc-André Lemburg4027f8f2000-07-05 09:47:46 +00003028 register const unsigned char *e;
3029
Marc-André Lemburg4027f8f2000-07-05 09:47:46 +00003030 /* Shortcut for single character strings */
3031 if (PyString_GET_SIZE(self) == 1 &&
3032 isalpha(*p))
Guido van Rossum77f6a652002-04-03 22:41:51 +00003033 return PyBool_FromLong(1);
Marc-André Lemburg4027f8f2000-07-05 09:47:46 +00003034
3035 /* Special case for empty strings */
3036 if (PyString_GET_SIZE(self) == 0)
Guido van Rossum77f6a652002-04-03 22:41:51 +00003037 return PyBool_FromLong(0);
Marc-André Lemburg4027f8f2000-07-05 09:47:46 +00003038
3039 e = p + PyString_GET_SIZE(self);
3040 for (; p < e; p++) {
3041 if (!isalpha(*p))
Guido van Rossum77f6a652002-04-03 22:41:51 +00003042 return PyBool_FromLong(0);
Marc-André Lemburg4027f8f2000-07-05 09:47:46 +00003043 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00003044 return PyBool_FromLong(1);
Marc-André Lemburg4027f8f2000-07-05 09:47:46 +00003045}
3046
3047
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003048PyDoc_STRVAR(isalnum__doc__,
Guido van Rossum77f6a652002-04-03 22:41:51 +00003049"S.isalnum() -> bool\n\
Marc-André Lemburg4027f8f2000-07-05 09:47:46 +00003050\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00003051Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003052and there is at least one character in S, False otherwise.");
Marc-André Lemburg4027f8f2000-07-05 09:47:46 +00003053
3054static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00003055string_isalnum(PyStringObject *self)
Marc-André Lemburg4027f8f2000-07-05 09:47:46 +00003056{
Fred Drakeba096332000-07-09 07:04:36 +00003057 register const unsigned char *p
3058 = (unsigned char *) PyString_AS_STRING(self);
Marc-André Lemburg4027f8f2000-07-05 09:47:46 +00003059 register const unsigned char *e;
3060
Marc-André Lemburg4027f8f2000-07-05 09:47:46 +00003061 /* Shortcut for single character strings */
3062 if (PyString_GET_SIZE(self) == 1 &&
3063 isalnum(*p))
Guido van Rossum77f6a652002-04-03 22:41:51 +00003064 return PyBool_FromLong(1);
Marc-André Lemburg4027f8f2000-07-05 09:47:46 +00003065
3066 /* Special case for empty strings */
3067 if (PyString_GET_SIZE(self) == 0)
Guido van Rossum77f6a652002-04-03 22:41:51 +00003068 return PyBool_FromLong(0);
Marc-André Lemburg4027f8f2000-07-05 09:47:46 +00003069
3070 e = p + PyString_GET_SIZE(self);
3071 for (; p < e; p++) {
3072 if (!isalnum(*p))
Guido van Rossum77f6a652002-04-03 22:41:51 +00003073 return PyBool_FromLong(0);
Marc-André Lemburg4027f8f2000-07-05 09:47:46 +00003074 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00003075 return PyBool_FromLong(1);
Marc-André Lemburg4027f8f2000-07-05 09:47:46 +00003076}
3077
3078
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003079PyDoc_STRVAR(isdigit__doc__,
Guido van Rossum77f6a652002-04-03 22:41:51 +00003080"S.isdigit() -> bool\n\
Guido van Rossum4c08d552000-03-10 22:55:18 +00003081\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00003082Return True if all characters in S are digits\n\
3083and there is at least one character in S, False otherwise.");
Guido van Rossum4c08d552000-03-10 22:55:18 +00003084
3085static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00003086string_isdigit(PyStringObject *self)
Guido van Rossum4c08d552000-03-10 22:55:18 +00003087{
Fred Drakeba096332000-07-09 07:04:36 +00003088 register const unsigned char *p
3089 = (unsigned char *) PyString_AS_STRING(self);
Guido van Rossumb8f820c2000-05-05 20:44:24 +00003090 register const unsigned char *e;
Guido van Rossum4c08d552000-03-10 22:55:18 +00003091
Guido van Rossum4c08d552000-03-10 22:55:18 +00003092 /* Shortcut for single character strings */
3093 if (PyString_GET_SIZE(self) == 1 &&
3094 isdigit(*p))
Guido van Rossum77f6a652002-04-03 22:41:51 +00003095 return PyBool_FromLong(1);
Guido van Rossum4c08d552000-03-10 22:55:18 +00003096
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00003097 /* Special case for empty strings */
3098 if (PyString_GET_SIZE(self) == 0)
Guido van Rossum77f6a652002-04-03 22:41:51 +00003099 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00003100
Guido van Rossum4c08d552000-03-10 22:55:18 +00003101 e = p + PyString_GET_SIZE(self);
3102 for (; p < e; p++) {
3103 if (!isdigit(*p))
Guido van Rossum77f6a652002-04-03 22:41:51 +00003104 return PyBool_FromLong(0);
Guido van Rossum4c08d552000-03-10 22:55:18 +00003105 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00003106 return PyBool_FromLong(1);
Guido van Rossum4c08d552000-03-10 22:55:18 +00003107}
3108
3109
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003110PyDoc_STRVAR(islower__doc__,
Guido van Rossum77f6a652002-04-03 22:41:51 +00003111"S.islower() -> bool\n\
Guido van Rossum4c08d552000-03-10 22:55:18 +00003112\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +00003113Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003114at least one cased character in S, False otherwise.");
Guido van Rossum4c08d552000-03-10 22:55:18 +00003115
3116static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00003117string_islower(PyStringObject *self)
Guido van Rossum4c08d552000-03-10 22:55:18 +00003118{
Fred Drakeba096332000-07-09 07:04:36 +00003119 register const unsigned char *p
3120 = (unsigned char *) PyString_AS_STRING(self);
Guido van Rossumb8f820c2000-05-05 20:44:24 +00003121 register const unsigned char *e;
Guido van Rossum4c08d552000-03-10 22:55:18 +00003122 int cased;
3123
Guido van Rossum4c08d552000-03-10 22:55:18 +00003124 /* Shortcut for single character strings */
3125 if (PyString_GET_SIZE(self) == 1)
Guido van Rossum77f6a652002-04-03 22:41:51 +00003126 return PyBool_FromLong(islower(*p) != 0);
Guido van Rossum4c08d552000-03-10 22:55:18 +00003127
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00003128 /* Special case for empty strings */
3129 if (PyString_GET_SIZE(self) == 0)
Guido van Rossum77f6a652002-04-03 22:41:51 +00003130 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00003131
Guido van Rossum4c08d552000-03-10 22:55:18 +00003132 e = p + PyString_GET_SIZE(self);
3133 cased = 0;
3134 for (; p < e; p++) {
3135 if (isupper(*p))
Guido van Rossum77f6a652002-04-03 22:41:51 +00003136 return PyBool_FromLong(0);
Guido van Rossum4c08d552000-03-10 22:55:18 +00003137 else if (!cased && islower(*p))
3138 cased = 1;
3139 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00003140 return PyBool_FromLong(cased);
Guido van Rossum4c08d552000-03-10 22:55:18 +00003141}
3142
3143
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003144PyDoc_STRVAR(isupper__doc__,
Guido van Rossum77f6a652002-04-03 22:41:51 +00003145"S.isupper() -> bool\n\
Guido van Rossum4c08d552000-03-10 22:55:18 +00003146\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00003147Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003148at least one cased character in S, False otherwise.");
Guido van Rossum4c08d552000-03-10 22:55:18 +00003149
3150static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00003151string_isupper(PyStringObject *self)
Guido van Rossum4c08d552000-03-10 22:55:18 +00003152{
Fred Drakeba096332000-07-09 07:04:36 +00003153 register const unsigned char *p
3154 = (unsigned char *) PyString_AS_STRING(self);
Guido van Rossumb8f820c2000-05-05 20:44:24 +00003155 register const unsigned char *e;
Guido van Rossum4c08d552000-03-10 22:55:18 +00003156 int cased;
3157
Guido van Rossum4c08d552000-03-10 22:55:18 +00003158 /* Shortcut for single character strings */
3159 if (PyString_GET_SIZE(self) == 1)
Guido van Rossum77f6a652002-04-03 22:41:51 +00003160 return PyBool_FromLong(isupper(*p) != 0);
Guido van Rossum4c08d552000-03-10 22:55:18 +00003161
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00003162 /* Special case for empty strings */
3163 if (PyString_GET_SIZE(self) == 0)
Guido van Rossum77f6a652002-04-03 22:41:51 +00003164 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00003165
Guido van Rossum4c08d552000-03-10 22:55:18 +00003166 e = p + PyString_GET_SIZE(self);
3167 cased = 0;
3168 for (; p < e; p++) {
3169 if (islower(*p))
Guido van Rossum77f6a652002-04-03 22:41:51 +00003170 return PyBool_FromLong(0);
Guido van Rossum4c08d552000-03-10 22:55:18 +00003171 else if (!cased && isupper(*p))
3172 cased = 1;
3173 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00003174 return PyBool_FromLong(cased);
Guido van Rossum4c08d552000-03-10 22:55:18 +00003175}
3176
3177
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003178PyDoc_STRVAR(istitle__doc__,
Guido van Rossum77f6a652002-04-03 22:41:51 +00003179"S.istitle() -> bool\n\
Guido van Rossum4c08d552000-03-10 22:55:18 +00003180\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00003181Return True if S is a titlecased string and there is at least one\n\
3182character in S, i.e. uppercase characters may only follow uncased\n\
3183characters and lowercase characters only cased ones. Return False\n\
3184otherwise.");
Guido van Rossum4c08d552000-03-10 22:55:18 +00003185
3186static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00003187string_istitle(PyStringObject *self, PyObject *uncased)
Guido van Rossum4c08d552000-03-10 22:55:18 +00003188{
Fred Drakeba096332000-07-09 07:04:36 +00003189 register const unsigned char *p
3190 = (unsigned char *) PyString_AS_STRING(self);
Guido van Rossumb8f820c2000-05-05 20:44:24 +00003191 register const unsigned char *e;
Guido van Rossum4c08d552000-03-10 22:55:18 +00003192 int cased, previous_is_cased;
3193
Guido van Rossum4c08d552000-03-10 22:55:18 +00003194 /* Shortcut for single character strings */
3195 if (PyString_GET_SIZE(self) == 1)
Guido van Rossum77f6a652002-04-03 22:41:51 +00003196 return PyBool_FromLong(isupper(*p) != 0);
Guido van Rossum4c08d552000-03-10 22:55:18 +00003197
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00003198 /* Special case for empty strings */
3199 if (PyString_GET_SIZE(self) == 0)
Guido van Rossum77f6a652002-04-03 22:41:51 +00003200 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00003201
Guido van Rossum4c08d552000-03-10 22:55:18 +00003202 e = p + PyString_GET_SIZE(self);
3203 cased = 0;
3204 previous_is_cased = 0;
3205 for (; p < e; p++) {
Guido van Rossumb8f820c2000-05-05 20:44:24 +00003206 register const unsigned char ch = *p;
Guido van Rossum4c08d552000-03-10 22:55:18 +00003207
3208 if (isupper(ch)) {
3209 if (previous_is_cased)
Guido van Rossum77f6a652002-04-03 22:41:51 +00003210 return PyBool_FromLong(0);
Guido van Rossum4c08d552000-03-10 22:55:18 +00003211 previous_is_cased = 1;
3212 cased = 1;
3213 }
3214 else if (islower(ch)) {
3215 if (!previous_is_cased)
Guido van Rossum77f6a652002-04-03 22:41:51 +00003216 return PyBool_FromLong(0);
Guido van Rossum4c08d552000-03-10 22:55:18 +00003217 previous_is_cased = 1;
3218 cased = 1;
3219 }
3220 else
3221 previous_is_cased = 0;
3222 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00003223 return PyBool_FromLong(cased);
Guido van Rossum4c08d552000-03-10 22:55:18 +00003224}
3225
3226
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003227PyDoc_STRVAR(splitlines__doc__,
Fred Drake2bae4fa2001-10-13 15:57:55 +00003228"S.splitlines([keepends]) -> list of strings\n\
Guido van Rossum4c08d552000-03-10 22:55:18 +00003229\n\
3230Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossumf0b7b042000-04-11 15:39:26 +00003231Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003232is given and true.");
Guido van Rossum4c08d552000-03-10 22:55:18 +00003233
Guido van Rossum4c08d552000-03-10 22:55:18 +00003234static PyObject*
3235string_splitlines(PyStringObject *self, PyObject *args)
3236{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003237 register Py_ssize_t i;
3238 register Py_ssize_t j;
3239 Py_ssize_t len;
Guido van Rossumf0b7b042000-04-11 15:39:26 +00003240 int keepends = 0;
Guido van Rossum4c08d552000-03-10 22:55:18 +00003241 PyObject *list;
3242 PyObject *str;
3243 char *data;
3244
Guido van Rossumf0b7b042000-04-11 15:39:26 +00003245 if (!PyArg_ParseTuple(args, "|i:splitlines", &keepends))
Guido van Rossum4c08d552000-03-10 22:55:18 +00003246 return NULL;
3247
3248 data = PyString_AS_STRING(self);
3249 len = PyString_GET_SIZE(self);
3250
Guido van Rossum4c08d552000-03-10 22:55:18 +00003251 list = PyList_New(0);
3252 if (!list)
3253 goto onError;
3254
3255 for (i = j = 0; i < len; ) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00003256 Py_ssize_t eol;
Guido van Rossumf0b7b042000-04-11 15:39:26 +00003257
Guido van Rossum4c08d552000-03-10 22:55:18 +00003258 /* Find a line and append it */
3259 while (i < len && data[i] != '\n' && data[i] != '\r')
3260 i++;
Guido van Rossum4c08d552000-03-10 22:55:18 +00003261
3262 /* Skip the line break reading CRLF as one line break */
Guido van Rossumf0b7b042000-04-11 15:39:26 +00003263 eol = i;
Guido van Rossum4c08d552000-03-10 22:55:18 +00003264 if (i < len) {
3265 if (data[i] == '\r' && i + 1 < len &&
3266 data[i+1] == '\n')
3267 i += 2;
3268 else
3269 i++;
Guido van Rossumf0b7b042000-04-11 15:39:26 +00003270 if (keepends)
3271 eol = i;
Guido van Rossum4c08d552000-03-10 22:55:18 +00003272 }
Guido van Rossumf0b7b042000-04-11 15:39:26 +00003273 SPLIT_APPEND(data, j, eol);
Guido van Rossum4c08d552000-03-10 22:55:18 +00003274 j = i;
3275 }
3276 if (j < len) {
3277 SPLIT_APPEND(data, j, len);
3278 }
3279
3280 return list;
3281
3282 onError:
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003283 Py_XDECREF(list);
Guido van Rossum4c08d552000-03-10 22:55:18 +00003284 return NULL;
3285}
3286
3287#undef SPLIT_APPEND
3288
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003289static PyObject *
3290string_getnewargs(PyStringObject *v)
3291{
3292 return Py_BuildValue("(s#)", v->ob_sval, v->ob_size);
3293}
3294
Barry Warsaw226ae6c1999-10-12 19:54:53 +00003295
Tim Petersb3d8d1f2001-04-28 05:38:26 +00003296static PyMethodDef
Barry Warsaw226ae6c1999-10-12 19:54:53 +00003297string_methods[] = {
Guido van Rossum4c08d552000-03-10 22:55:18 +00003298 /* Counterparts of the obsolete stropmodule functions; except
3299 string.maketrans(). */
Guido van Rossum3aa3fc42002-04-15 13:48:52 +00003300 {"join", (PyCFunction)string_join, METH_O, join__doc__},
3301 {"split", (PyCFunction)string_split, METH_VARARGS, split__doc__},
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00003302 {"rsplit", (PyCFunction)string_rsplit, METH_VARARGS, rsplit__doc__},
Guido van Rossum3aa3fc42002-04-15 13:48:52 +00003303 {"lower", (PyCFunction)string_lower, METH_NOARGS, lower__doc__},
3304 {"upper", (PyCFunction)string_upper, METH_NOARGS, upper__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00003305 {"islower", (PyCFunction)string_islower, METH_NOARGS, islower__doc__},
3306 {"isupper", (PyCFunction)string_isupper, METH_NOARGS, isupper__doc__},
3307 {"isspace", (PyCFunction)string_isspace, METH_NOARGS, isspace__doc__},
3308 {"isdigit", (PyCFunction)string_isdigit, METH_NOARGS, isdigit__doc__},
3309 {"istitle", (PyCFunction)string_istitle, METH_NOARGS, istitle__doc__},
3310 {"isalpha", (PyCFunction)string_isalpha, METH_NOARGS, isalpha__doc__},
3311 {"isalnum", (PyCFunction)string_isalnum, METH_NOARGS, isalnum__doc__},
Guido van Rossum3aa3fc42002-04-15 13:48:52 +00003312 {"capitalize", (PyCFunction)string_capitalize, METH_NOARGS,
3313 capitalize__doc__},
3314 {"count", (PyCFunction)string_count, METH_VARARGS, count__doc__},
3315 {"endswith", (PyCFunction)string_endswith, METH_VARARGS,
3316 endswith__doc__},
3317 {"find", (PyCFunction)string_find, METH_VARARGS, find__doc__},
3318 {"index", (PyCFunction)string_index, METH_VARARGS, index__doc__},
3319 {"lstrip", (PyCFunction)string_lstrip, METH_VARARGS, lstrip__doc__},
3320 {"replace", (PyCFunction)string_replace, METH_VARARGS, replace__doc__},
3321 {"rfind", (PyCFunction)string_rfind, METH_VARARGS, rfind__doc__},
3322 {"rindex", (PyCFunction)string_rindex, METH_VARARGS, rindex__doc__},
3323 {"rstrip", (PyCFunction)string_rstrip, METH_VARARGS, rstrip__doc__},
3324 {"startswith", (PyCFunction)string_startswith, METH_VARARGS,
3325 startswith__doc__},
3326 {"strip", (PyCFunction)string_strip, METH_VARARGS, strip__doc__},
3327 {"swapcase", (PyCFunction)string_swapcase, METH_NOARGS,
3328 swapcase__doc__},
3329 {"translate", (PyCFunction)string_translate, METH_VARARGS,
3330 translate__doc__},
3331 {"title", (PyCFunction)string_title, METH_NOARGS, title__doc__},
3332 {"ljust", (PyCFunction)string_ljust, METH_VARARGS, ljust__doc__},
3333 {"rjust", (PyCFunction)string_rjust, METH_VARARGS, rjust__doc__},
3334 {"center", (PyCFunction)string_center, METH_VARARGS, center__doc__},
3335 {"zfill", (PyCFunction)string_zfill, METH_VARARGS, zfill__doc__},
3336 {"encode", (PyCFunction)string_encode, METH_VARARGS, encode__doc__},
3337 {"decode", (PyCFunction)string_decode, METH_VARARGS, decode__doc__},
3338 {"expandtabs", (PyCFunction)string_expandtabs, METH_VARARGS,
3339 expandtabs__doc__},
3340 {"splitlines", (PyCFunction)string_splitlines, METH_VARARGS,
3341 splitlines__doc__},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003342 {"__getnewargs__", (PyCFunction)string_getnewargs, METH_NOARGS},
Barry Warsaw226ae6c1999-10-12 19:54:53 +00003343 {NULL, NULL} /* sentinel */
3344};
3345
Jeremy Hylton938ace62002-07-17 16:30:39 +00003346static PyObject *
Guido van Rossumae960af2001-08-30 03:11:59 +00003347str_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
3348
Barry Warsaw226ae6c1999-10-12 19:54:53 +00003349static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003350string_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Barry Warsaw226ae6c1999-10-12 19:54:53 +00003351{
Tim Peters6d6c1a32001-08-02 04:15:00 +00003352 PyObject *x = NULL;
Martin v. Löwis15e62742006-02-27 16:46:16 +00003353 static char *kwlist[] = {"object", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00003354
Guido van Rossumae960af2001-08-30 03:11:59 +00003355 if (type != &PyString_Type)
3356 return str_subtype_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003357 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:str", kwlist, &x))
3358 return NULL;
3359 if (x == NULL)
3360 return PyString_FromString("");
3361 return PyObject_Str(x);
Barry Warsaw226ae6c1999-10-12 19:54:53 +00003362}
3363
Guido van Rossumae960af2001-08-30 03:11:59 +00003364static PyObject *
3365str_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3366{
Tim Petersaf90b3e2001-09-12 05:18:58 +00003367 PyObject *tmp, *pnew;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003368 Py_ssize_t n;
Guido van Rossumae960af2001-08-30 03:11:59 +00003369
3370 assert(PyType_IsSubtype(type, &PyString_Type));
3371 tmp = string_new(&PyString_Type, args, kwds);
3372 if (tmp == NULL)
3373 return NULL;
Tim Peters5a49ade2001-09-11 01:41:59 +00003374 assert(PyString_CheckExact(tmp));
Tim Petersaf90b3e2001-09-12 05:18:58 +00003375 n = PyString_GET_SIZE(tmp);
3376 pnew = type->tp_alloc(type, n);
3377 if (pnew != NULL) {
3378 memcpy(PyString_AS_STRING(pnew), PyString_AS_STRING(tmp), n+1);
Tim Petersaf90b3e2001-09-12 05:18:58 +00003379 ((PyStringObject *)pnew)->ob_shash =
3380 ((PyStringObject *)tmp)->ob_shash;
Guido van Rossum45ec02a2002-08-19 21:43:18 +00003381 ((PyStringObject *)pnew)->ob_sstate = SSTATE_NOT_INTERNED;
Tim Petersaf90b3e2001-09-12 05:18:58 +00003382 }
Guido van Rossum29d55a32001-08-31 16:11:15 +00003383 Py_DECREF(tmp);
Tim Petersaf90b3e2001-09-12 05:18:58 +00003384 return pnew;
Guido van Rossumae960af2001-08-30 03:11:59 +00003385}
3386
Guido van Rossumcacfc072002-05-24 19:01:59 +00003387static PyObject *
3388basestring_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3389{
3390 PyErr_SetString(PyExc_TypeError,
Neal Norwitz32a7e7f2002-05-31 19:58:02 +00003391 "The basestring type cannot be instantiated");
Guido van Rossumcacfc072002-05-24 19:01:59 +00003392 return NULL;
3393}
3394
Neil Schemenauera6cd4e62002-11-18 16:09:38 +00003395static PyObject *
3396string_mod(PyObject *v, PyObject *w)
3397{
3398 if (!PyString_Check(v)) {
3399 Py_INCREF(Py_NotImplemented);
3400 return Py_NotImplemented;
3401 }
3402 return PyString_Format(v, w);
3403}
3404
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003405PyDoc_STRVAR(basestring_doc,
3406"Type basestring cannot be instantiated; it is the base for str and unicode.");
Guido van Rossumcacfc072002-05-24 19:01:59 +00003407
Neil Schemenauera6cd4e62002-11-18 16:09:38 +00003408static PyNumberMethods string_as_number = {
3409 0, /*nb_add*/
3410 0, /*nb_subtract*/
3411 0, /*nb_multiply*/
3412 0, /*nb_divide*/
3413 string_mod, /*nb_remainder*/
3414};
3415
3416
Guido van Rossumcacfc072002-05-24 19:01:59 +00003417PyTypeObject PyBaseString_Type = {
3418 PyObject_HEAD_INIT(&PyType_Type)
3419 0,
Neal Norwitz32a7e7f2002-05-31 19:58:02 +00003420 "basestring",
Guido van Rossumcacfc072002-05-24 19:01:59 +00003421 0,
3422 0,
3423 0, /* tp_dealloc */
3424 0, /* tp_print */
3425 0, /* tp_getattr */
3426 0, /* tp_setattr */
3427 0, /* tp_compare */
3428 0, /* tp_repr */
3429 0, /* tp_as_number */
3430 0, /* tp_as_sequence */
3431 0, /* tp_as_mapping */
3432 0, /* tp_hash */
3433 0, /* tp_call */
3434 0, /* tp_str */
3435 0, /* tp_getattro */
3436 0, /* tp_setattro */
3437 0, /* tp_as_buffer */
3438 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
3439 basestring_doc, /* tp_doc */
3440 0, /* tp_traverse */
3441 0, /* tp_clear */
3442 0, /* tp_richcompare */
3443 0, /* tp_weaklistoffset */
3444 0, /* tp_iter */
3445 0, /* tp_iternext */
3446 0, /* tp_methods */
3447 0, /* tp_members */
3448 0, /* tp_getset */
3449 &PyBaseObject_Type, /* tp_base */
3450 0, /* tp_dict */
3451 0, /* tp_descr_get */
3452 0, /* tp_descr_set */
3453 0, /* tp_dictoffset */
3454 0, /* tp_init */
3455 0, /* tp_alloc */
3456 basestring_new, /* tp_new */
3457 0, /* tp_free */
3458};
3459
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003460PyDoc_STRVAR(string_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00003461"str(object) -> string\n\
3462\n\
3463Return a nice string representation of the object.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003464If the argument is a string, the return value is the same object.");
Barry Warsaw226ae6c1999-10-12 19:54:53 +00003465
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003466PyTypeObject PyString_Type = {
3467 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003468 0,
Tim Peters6d6c1a32001-08-02 04:15:00 +00003469 "str",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003470 sizeof(PyStringObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003471 sizeof(char),
Georg Brandl347b3002006-03-30 11:57:00 +00003472 string_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003473 (printfunc)string_print, /* tp_print */
3474 0, /* tp_getattr */
3475 0, /* tp_setattr */
3476 0, /* tp_compare */
Georg Brandl347b3002006-03-30 11:57:00 +00003477 string_repr, /* tp_repr */
Neil Schemenauera6cd4e62002-11-18 16:09:38 +00003478 &string_as_number, /* tp_as_number */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003479 &string_as_sequence, /* tp_as_sequence */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00003480 &string_as_mapping, /* tp_as_mapping */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003481 (hashfunc)string_hash, /* tp_hash */
3482 0, /* tp_call */
Georg Brandl347b3002006-03-30 11:57:00 +00003483 string_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003484 PyObject_GenericGetAttr, /* tp_getattro */
3485 0, /* tp_setattro */
3486 &string_as_buffer, /* tp_as_buffer */
Tim Petersae1d0c92006-03-17 03:29:34 +00003487 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
Neil Schemenauera6cd4e62002-11-18 16:09:38 +00003488 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003489 string_doc, /* tp_doc */
3490 0, /* tp_traverse */
3491 0, /* tp_clear */
3492 (richcmpfunc)string_richcompare, /* tp_richcompare */
3493 0, /* tp_weaklistoffset */
3494 0, /* tp_iter */
3495 0, /* tp_iternext */
3496 string_methods, /* tp_methods */
3497 0, /* tp_members */
3498 0, /* tp_getset */
Guido van Rossumcacfc072002-05-24 19:01:59 +00003499 &PyBaseString_Type, /* tp_base */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003500 0, /* tp_dict */
3501 0, /* tp_descr_get */
3502 0, /* tp_descr_set */
3503 0, /* tp_dictoffset */
3504 0, /* tp_init */
3505 0, /* tp_alloc */
3506 string_new, /* tp_new */
Neil Schemenauer510492e2002-04-12 03:05:19 +00003507 PyObject_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003508};
3509
3510void
Fred Drakeba096332000-07-09 07:04:36 +00003511PyString_Concat(register PyObject **pv, register PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003512{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003513 register PyObject *v;
Guido van Rossum013142a1994-08-30 08:19:36 +00003514 if (*pv == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003515 return;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003516 if (w == NULL || !PyString_Check(*pv)) {
3517 Py_DECREF(*pv);
Guido van Rossum013142a1994-08-30 08:19:36 +00003518 *pv = NULL;
3519 return;
3520 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003521 v = string_concat((PyStringObject *) *pv, w);
3522 Py_DECREF(*pv);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003523 *pv = v;
3524}
3525
Guido van Rossum013142a1994-08-30 08:19:36 +00003526void
Fred Drakeba096332000-07-09 07:04:36 +00003527PyString_ConcatAndDel(register PyObject **pv, register PyObject *w)
Guido van Rossum013142a1994-08-30 08:19:36 +00003528{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003529 PyString_Concat(pv, w);
3530 Py_XDECREF(w);
Guido van Rossum013142a1994-08-30 08:19:36 +00003531}
3532
3533
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003534/* The following function breaks the notion that strings are immutable:
3535 it changes the size of a string. We get away with this only if there
3536 is only one module referencing the object. You can also think of it
3537 as creating a new string object and destroying the old one, only
3538 more efficiently. In any case, don't use this if the string may
Tim Peters5de98422002-04-27 18:44:32 +00003539 already be known to some other part of the code...
3540 Note that if there's not enough memory to resize the string, the original
3541 string object at *pv is deallocated, *pv is set to NULL, an "out of
3542 memory" exception is set, and -1 is returned. Else (on success) 0 is
3543 returned, and the value in *pv may or may not be the same as on input.
3544 As always, an extra byte is allocated for a trailing \0 byte (newsize
3545 does *not* include that), and a trailing \0 byte is stored.
3546*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003547
3548int
Martin v. Löwis18e16552006-02-15 17:27:45 +00003549_PyString_Resize(PyObject **pv, Py_ssize_t newsize)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003550{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003551 register PyObject *v;
3552 register PyStringObject *sv;
Guido van Rossum921842f1990-11-18 17:30:23 +00003553 v = *pv;
Armin Rigo618fbf52004-08-07 20:58:32 +00003554 if (!PyString_Check(v) || v->ob_refcnt != 1 || newsize < 0 ||
3555 PyString_CHECK_INTERNED(v)) {
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003556 *pv = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003557 Py_DECREF(v);
3558 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +00003559 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003560 }
Guido van Rossum921842f1990-11-18 17:30:23 +00003561 /* XXX UNREF/NEWREF interface should be more symmetrical */
Tim Peters34592512002-07-11 06:23:50 +00003562 _Py_DEC_REFTOTAL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003563 _Py_ForgetReference(v);
3564 *pv = (PyObject *)
Tim Peterse7c05322004-06-27 17:24:49 +00003565 PyObject_REALLOC((char *)v, sizeof(PyStringObject) + newsize);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003566 if (*pv == NULL) {
Neil Schemenauer510492e2002-04-12 03:05:19 +00003567 PyObject_Del(v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003568 PyErr_NoMemory();
Guido van Rossum2a9096b1990-10-21 22:15:08 +00003569 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003570 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003571 _Py_NewReference(*pv);
3572 sv = (PyStringObject *) *pv;
Guido van Rossum921842f1990-11-18 17:30:23 +00003573 sv->ob_size = newsize;
3574 sv->ob_sval[newsize] = '\0';
Raymond Hettinger561fbf12004-10-26 01:52:37 +00003575 sv->ob_shash = -1; /* invalidate cached hash value */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003576 return 0;
3577}
Guido van Rossume5372401993-03-16 12:15:04 +00003578
3579/* Helpers for formatstring */
3580
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003581static PyObject *
Thomas Wouters977485d2006-02-16 15:59:12 +00003582getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
Guido van Rossume5372401993-03-16 12:15:04 +00003583{
Thomas Wouters977485d2006-02-16 15:59:12 +00003584 Py_ssize_t argidx = *p_argidx;
Guido van Rossume5372401993-03-16 12:15:04 +00003585 if (argidx < arglen) {
3586 (*p_argidx)++;
3587 if (arglen < 0)
3588 return args;
3589 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003590 return PyTuple_GetItem(args, argidx);
Guido van Rossume5372401993-03-16 12:15:04 +00003591 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003592 PyErr_SetString(PyExc_TypeError,
3593 "not enough arguments for format string");
Guido van Rossume5372401993-03-16 12:15:04 +00003594 return NULL;
3595}
3596
Tim Peters38fd5b62000-09-21 05:43:11 +00003597/* Format codes
3598 * F_LJUST '-'
3599 * F_SIGN '+'
3600 * F_BLANK ' '
3601 * F_ALT '#'
3602 * F_ZERO '0'
3603 */
Guido van Rossume5372401993-03-16 12:15:04 +00003604#define F_LJUST (1<<0)
3605#define F_SIGN (1<<1)
3606#define F_BLANK (1<<2)
3607#define F_ALT (1<<3)
3608#define F_ZERO (1<<4)
3609
Guido van Rossuma04d47b1997-01-21 16:12:09 +00003610static int
Fred Drakeba096332000-07-09 07:04:36 +00003611formatfloat(char *buf, size_t buflen, int flags,
3612 int prec, int type, PyObject *v)
Guido van Rossume5372401993-03-16 12:15:04 +00003613{
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00003614 /* fmt = '%#.' + `prec` + `type`
3615 worst case length = 3 + 10 (len of INT_MAX) + 1 = 14 (use 20)*/
Guido van Rossume5372401993-03-16 12:15:04 +00003616 char fmt[20];
Guido van Rossume5372401993-03-16 12:15:04 +00003617 double x;
Neal Norwitz88fe4ff2002-07-28 16:44:23 +00003618 x = PyFloat_AsDouble(v);
3619 if (x == -1.0 && PyErr_Occurred()) {
3620 PyErr_SetString(PyExc_TypeError, "float argument required");
Guido van Rossuma04d47b1997-01-21 16:12:09 +00003621 return -1;
Neal Norwitz88fe4ff2002-07-28 16:44:23 +00003622 }
Guido van Rossume5372401993-03-16 12:15:04 +00003623 if (prec < 0)
3624 prec = 6;
Guido van Rossume5372401993-03-16 12:15:04 +00003625 if (type == 'f' && fabs(x)/1e25 >= 1e25)
3626 type = 'g';
Marc-André Lemburg79f57832002-12-29 19:44:06 +00003627 /* Worst case length calc to ensure no buffer overrun:
3628
3629 'g' formats:
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00003630 fmt = %#.<prec>g
3631 buf = '-' + [0-9]*prec + '.' + 'e+' + (longest exp
Tim Petersb3d8d1f2001-04-28 05:38:26 +00003632 for any double rep.)
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00003633 len = 1 + prec + 1 + 2 + 5 = 9 + prec
Marc-André Lemburg79f57832002-12-29 19:44:06 +00003634
3635 'f' formats:
3636 buf = '-' + [0-9]*x + '.' + [0-9]*prec (with x < 50)
3637 len = 1 + 50 + 1 + prec = 52 + prec
3638
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00003639 If prec=0 the effective precision is 1 (the leading digit is
Tim Petersae1d0c92006-03-17 03:29:34 +00003640 always given), therefore increase the length by one.
Marc-André Lemburg79f57832002-12-29 19:44:06 +00003641
3642 */
3643 if ((type == 'g' && buflen <= (size_t)10 + (size_t)prec) ||
3644 (type == 'f' && buflen <= (size_t)53 + (size_t)prec)) {
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00003645 PyErr_SetString(PyExc_OverflowError,
Fred Drake661ea262000-10-24 19:57:45 +00003646 "formatted float is too long (precision too large?)");
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00003647 return -1;
3648 }
Marc-André Lemburg79f57832002-12-29 19:44:06 +00003649 PyOS_snprintf(fmt, sizeof(fmt), "%%%s.%d%c",
3650 (flags&F_ALT) ? "#" : "",
3651 prec, type);
Martin v. Löwis737ea822004-06-08 18:52:54 +00003652 PyOS_ascii_formatd(buf, buflen, fmt, x);
Martin v. Löwis18e16552006-02-15 17:27:45 +00003653 return (int)strlen(buf);
Guido van Rossume5372401993-03-16 12:15:04 +00003654}
3655
Tim Peters38fd5b62000-09-21 05:43:11 +00003656/* _PyString_FormatLong emulates the format codes d, u, o, x and X, and
3657 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
3658 * Python's regular ints.
3659 * Return value: a new PyString*, or NULL if error.
3660 * . *pbuf is set to point into it,
3661 * *plen set to the # of chars following that.
3662 * Caller must decref it when done using pbuf.
3663 * The string starting at *pbuf is of the form
3664 * "-"? ("0x" | "0X")? digit+
3665 * "0x"/"0X" are present only for x and X conversions, with F_ALT
Tim Petersb3d8d1f2001-04-28 05:38:26 +00003666 * set in flags. The case of hex digits will be correct,
Tim Peters38fd5b62000-09-21 05:43:11 +00003667 * There will be at least prec digits, zero-filled on the left if
3668 * necessary to get that many.
3669 * val object to be converted
3670 * flags bitmask of format flags; only F_ALT is looked at
3671 * prec minimum number of digits; 0-fill on left if needed
3672 * type a character in [duoxX]; u acts the same as d
3673 *
3674 * CAUTION: o, x and X conversions on regular ints can never
3675 * produce a '-' sign, but can for Python's unbounded ints.
3676 */
3677PyObject*
3678_PyString_FormatLong(PyObject *val, int flags, int prec, int type,
3679 char **pbuf, int *plen)
3680{
3681 PyObject *result = NULL;
3682 char *buf;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003683 Py_ssize_t i;
Tim Peters38fd5b62000-09-21 05:43:11 +00003684 int sign; /* 1 if '-', else 0 */
3685 int len; /* number of characters */
Martin v. Löwis725507b2006-03-07 12:08:51 +00003686 Py_ssize_t llen;
Tim Peters38fd5b62000-09-21 05:43:11 +00003687 int numdigits; /* len == numnondigits + numdigits */
3688 int numnondigits = 0;
3689
3690 switch (type) {
3691 case 'd':
3692 case 'u':
3693 result = val->ob_type->tp_str(val);
3694 break;
3695 case 'o':
3696 result = val->ob_type->tp_as_number->nb_oct(val);
3697 break;
3698 case 'x':
3699 case 'X':
3700 numnondigits = 2;
3701 result = val->ob_type->tp_as_number->nb_hex(val);
3702 break;
3703 default:
3704 assert(!"'type' not in [duoxX]");
3705 }
3706 if (!result)
3707 return NULL;
3708
3709 /* To modify the string in-place, there can only be one reference. */
3710 if (result->ob_refcnt != 1) {
3711 PyErr_BadInternalCall();
3712 return NULL;
3713 }
3714 buf = PyString_AsString(result);
Martin v. Löwis725507b2006-03-07 12:08:51 +00003715 llen = PyString_Size(result);
Martin v. Löwis8ce358f2006-04-13 07:22:51 +00003716 if (llen > PY_SSIZE_T_MAX) {
Martin v. Löwis725507b2006-03-07 12:08:51 +00003717 PyErr_SetString(PyExc_ValueError, "string too large in _PyString_FormatLong");
3718 return NULL;
3719 }
3720 len = (int)llen;
Tim Peters38fd5b62000-09-21 05:43:11 +00003721 if (buf[len-1] == 'L') {
3722 --len;
3723 buf[len] = '\0';
3724 }
3725 sign = buf[0] == '-';
3726 numnondigits += sign;
3727 numdigits = len - numnondigits;
3728 assert(numdigits > 0);
3729
Tim Petersfff53252001-04-12 18:38:48 +00003730 /* Get rid of base marker unless F_ALT */
3731 if ((flags & F_ALT) == 0) {
Tim Peters38fd5b62000-09-21 05:43:11 +00003732 /* Need to skip 0x, 0X or 0. */
3733 int skipped = 0;
3734 switch (type) {
3735 case 'o':
3736 assert(buf[sign] == '0');
3737 /* If 0 is only digit, leave it alone. */
3738 if (numdigits > 1) {
3739 skipped = 1;
3740 --numdigits;
3741 }
3742 break;
3743 case 'x':
3744 case 'X':
3745 assert(buf[sign] == '0');
3746 assert(buf[sign + 1] == 'x');
3747 skipped = 2;
3748 numnondigits -= 2;
3749 break;
3750 }
3751 if (skipped) {
3752 buf += skipped;
3753 len -= skipped;
3754 if (sign)
3755 buf[0] = '-';
3756 }
3757 assert(len == numnondigits + numdigits);
3758 assert(numdigits > 0);
3759 }
3760
3761 /* Fill with leading zeroes to meet minimum width. */
3762 if (prec > numdigits) {
3763 PyObject *r1 = PyString_FromStringAndSize(NULL,
3764 numnondigits + prec);
3765 char *b1;
3766 if (!r1) {
3767 Py_DECREF(result);
3768 return NULL;
3769 }
3770 b1 = PyString_AS_STRING(r1);
3771 for (i = 0; i < numnondigits; ++i)
3772 *b1++ = *buf++;
3773 for (i = 0; i < prec - numdigits; i++)
3774 *b1++ = '0';
3775 for (i = 0; i < numdigits; i++)
3776 *b1++ = *buf++;
3777 *b1 = '\0';
3778 Py_DECREF(result);
3779 result = r1;
3780 buf = PyString_AS_STRING(result);
3781 len = numnondigits + prec;
3782 }
3783
3784 /* Fix up case for hex conversions. */
Raymond Hettinger3296e692005-06-29 23:29:56 +00003785 if (type == 'X') {
3786 /* Need to convert all lower case letters to upper case.
3787 and need to convert 0x to 0X (and -0x to -0X). */
Tim Peters38fd5b62000-09-21 05:43:11 +00003788 for (i = 0; i < len; i++)
Raymond Hettinger3296e692005-06-29 23:29:56 +00003789 if (buf[i] >= 'a' && buf[i] <= 'x')
3790 buf[i] -= 'a'-'A';
Tim Peters38fd5b62000-09-21 05:43:11 +00003791 }
3792 *pbuf = buf;
3793 *plen = len;
3794 return result;
3795}
3796
Guido van Rossuma04d47b1997-01-21 16:12:09 +00003797static int
Fred Drakeba096332000-07-09 07:04:36 +00003798formatint(char *buf, size_t buflen, int flags,
3799 int prec, int type, PyObject *v)
Guido van Rossume5372401993-03-16 12:15:04 +00003800{
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00003801 /* fmt = '%#.' + `prec` + 'l' + `type`
Tim Peters38fd5b62000-09-21 05:43:11 +00003802 worst case length = 3 + 19 (worst len of INT_MAX on 64-bit machine)
3803 + 1 + 1 = 24 */
3804 char fmt[64]; /* plenty big enough! */
Guido van Rossum6c9e1302003-11-29 23:52:13 +00003805 char *sign;
Guido van Rossume5372401993-03-16 12:15:04 +00003806 long x;
Andrew MacIntyre5e9c80d2002-02-28 11:38:24 +00003807
Neal Norwitz88fe4ff2002-07-28 16:44:23 +00003808 x = PyInt_AsLong(v);
3809 if (x == -1 && PyErr_Occurred()) {
3810 PyErr_SetString(PyExc_TypeError, "int argument required");
Guido van Rossuma04d47b1997-01-21 16:12:09 +00003811 return -1;
Neal Norwitz88fe4ff2002-07-28 16:44:23 +00003812 }
Guido van Rossum6c9e1302003-11-29 23:52:13 +00003813 if (x < 0 && type == 'u') {
3814 type = 'd';
Guido van Rossum078151d2002-08-11 04:24:12 +00003815 }
Guido van Rossum6c9e1302003-11-29 23:52:13 +00003816 if (x < 0 && (type == 'x' || type == 'X' || type == 'o'))
3817 sign = "-";
3818 else
3819 sign = "";
Guido van Rossume5372401993-03-16 12:15:04 +00003820 if (prec < 0)
3821 prec = 1;
Andrew MacIntyre5e9c80d2002-02-28 11:38:24 +00003822
3823 if ((flags & F_ALT) &&
3824 (type == 'x' || type == 'X')) {
Guido van Rossum3aa3fc42002-04-15 13:48:52 +00003825 /* When converting under %#x or %#X, there are a number
Andrew MacIntyre5e9c80d2002-02-28 11:38:24 +00003826 * of issues that cause pain:
3827 * - when 0 is being converted, the C standard leaves off
3828 * the '0x' or '0X', which is inconsistent with other
3829 * %#x/%#X conversions and inconsistent with Python's
3830 * hex() function
3831 * - there are platforms that violate the standard and
3832 * convert 0 with the '0x' or '0X'
3833 * (Metrowerks, Compaq Tru64)
3834 * - there are platforms that give '0x' when converting
Guido van Rossum3aa3fc42002-04-15 13:48:52 +00003835 * under %#X, but convert 0 in accordance with the
Andrew MacIntyre5e9c80d2002-02-28 11:38:24 +00003836 * standard (OS/2 EMX)
Guido van Rossum3aa3fc42002-04-15 13:48:52 +00003837 *
Andrew MacIntyre5e9c80d2002-02-28 11:38:24 +00003838 * We can achieve the desired consistency by inserting our
3839 * own '0x' or '0X' prefix, and substituting %x/%X in place
3840 * of %#x/%#X.
3841 *
3842 * Note that this is the same approach as used in
3843 * formatint() in unicodeobject.c
3844 */
Guido van Rossum6c9e1302003-11-29 23:52:13 +00003845 PyOS_snprintf(fmt, sizeof(fmt), "%s0%c%%.%dl%c",
3846 sign, type, prec, type);
Andrew MacIntyre5e9c80d2002-02-28 11:38:24 +00003847 }
3848 else {
Guido van Rossum6c9e1302003-11-29 23:52:13 +00003849 PyOS_snprintf(fmt, sizeof(fmt), "%s%%%s.%dl%c",
3850 sign, (flags&F_ALT) ? "#" : "",
Andrew MacIntyre5e9c80d2002-02-28 11:38:24 +00003851 prec, type);
3852 }
3853
Guido van Rossum6c9e1302003-11-29 23:52:13 +00003854 /* buf = '+'/'-'/'' + '0'/'0x'/'' + '[0-9]'*max(prec, len(x in octal))
3855 * worst case buf = '-0x' + [0-9]*prec, where prec >= 11
Andrew MacIntyre5e9c80d2002-02-28 11:38:24 +00003856 */
Guido van Rossum6c9e1302003-11-29 23:52:13 +00003857 if (buflen <= 14 || buflen <= (size_t)3 + (size_t)prec) {
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00003858 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum3aa3fc42002-04-15 13:48:52 +00003859 "formatted integer is too long (precision too large?)");
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00003860 return -1;
3861 }
Guido van Rossum6c9e1302003-11-29 23:52:13 +00003862 if (sign[0])
3863 PyOS_snprintf(buf, buflen, fmt, -x);
3864 else
3865 PyOS_snprintf(buf, buflen, fmt, x);
Martin v. Löwis18e16552006-02-15 17:27:45 +00003866 return (int)strlen(buf);
Guido van Rossume5372401993-03-16 12:15:04 +00003867}
3868
Guido van Rossuma04d47b1997-01-21 16:12:09 +00003869static int
Fred Drakeba096332000-07-09 07:04:36 +00003870formatchar(char *buf, size_t buflen, PyObject *v)
Guido van Rossume5372401993-03-16 12:15:04 +00003871{
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00003872 /* presume that the buffer is at least 2 characters long */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003873 if (PyString_Check(v)) {
3874 if (!PyArg_Parse(v, "c;%c requires int or char", &buf[0]))
Guido van Rossuma04d47b1997-01-21 16:12:09 +00003875 return -1;
Guido van Rossume5372401993-03-16 12:15:04 +00003876 }
3877 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003878 if (!PyArg_Parse(v, "b;%c requires int or char", &buf[0]))
Guido van Rossuma04d47b1997-01-21 16:12:09 +00003879 return -1;
Guido van Rossume5372401993-03-16 12:15:04 +00003880 }
3881 buf[1] = '\0';
Guido van Rossuma04d47b1997-01-21 16:12:09 +00003882 return 1;
Guido van Rossume5372401993-03-16 12:15:04 +00003883}
3884
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00003885/* fmt%(v1,v2,...) is roughly equivalent to sprintf(fmt, v1, v2, ...)
3886
3887 FORMATBUFLEN is the length of the buffer in which the floats, ints, &
3888 chars are formatted. XXX This is a magic number. Each formatting
3889 routine does bounds checking to ensure no overflow, but a better
3890 solution may be to malloc a buffer of appropriate size for each
3891 format. For now, the current solution is sufficient.
3892*/
3893#define FORMATBUFLEN (size_t)120
Guido van Rossume5372401993-03-16 12:15:04 +00003894
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003895PyObject *
Fred Drakeba096332000-07-09 07:04:36 +00003896PyString_Format(PyObject *format, PyObject *args)
Guido van Rossume5372401993-03-16 12:15:04 +00003897{
3898 char *fmt, *res;
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003899 Py_ssize_t arglen, argidx;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003900 Py_ssize_t reslen, rescnt, fmtcnt;
Guido van Rossum993952b1996-05-21 22:44:20 +00003901 int args_owned = 0;
Martin v. Löwis339d0f72001-08-17 18:39:25 +00003902 PyObject *result, *orig_args;
3903#ifdef Py_USING_UNICODE
3904 PyObject *v, *w;
3905#endif
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003906 PyObject *dict = NULL;
3907 if (format == NULL || !PyString_Check(format) || args == NULL) {
3908 PyErr_BadInternalCall();
Guido van Rossume5372401993-03-16 12:15:04 +00003909 return NULL;
3910 }
Guido van Rossum90daa872000-04-10 13:47:21 +00003911 orig_args = args;
Jeremy Hylton7802a532001-12-06 15:18:48 +00003912 fmt = PyString_AS_STRING(format);
3913 fmtcnt = PyString_GET_SIZE(format);
Guido van Rossum6ac258d1993-05-12 08:24:20 +00003914 reslen = rescnt = fmtcnt + 100;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003915 result = PyString_FromStringAndSize((char *)NULL, reslen);
Guido van Rossume5372401993-03-16 12:15:04 +00003916 if (result == NULL)
3917 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003918 res = PyString_AsString(result);
3919 if (PyTuple_Check(args)) {
Jeremy Hylton7802a532001-12-06 15:18:48 +00003920 arglen = PyTuple_GET_SIZE(args);
Guido van Rossume5372401993-03-16 12:15:04 +00003921 argidx = 0;
3922 }
3923 else {
3924 arglen = -1;
3925 argidx = -2;
3926 }
Neal Norwitz80a1bf42002-11-12 23:01:12 +00003927 if (args->ob_type->tp_as_mapping && !PyTuple_Check(args) &&
3928 !PyObject_TypeCheck(args, &PyBaseString_Type))
Guido van Rossum013142a1994-08-30 08:19:36 +00003929 dict = args;
Guido van Rossume5372401993-03-16 12:15:04 +00003930 while (--fmtcnt >= 0) {
3931 if (*fmt != '%') {
3932 if (--rescnt < 0) {
Guido van Rossum6ac258d1993-05-12 08:24:20 +00003933 rescnt = fmtcnt + 100;
3934 reslen += rescnt;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003935 if (_PyString_Resize(&result, reslen) < 0)
Guido van Rossume5372401993-03-16 12:15:04 +00003936 return NULL;
Jeremy Hylton7802a532001-12-06 15:18:48 +00003937 res = PyString_AS_STRING(result)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003938 + reslen - rescnt;
Guido van Rossum013142a1994-08-30 08:19:36 +00003939 --rescnt;
Guido van Rossume5372401993-03-16 12:15:04 +00003940 }
3941 *res++ = *fmt++;
3942 }
3943 else {
3944 /* Got a format specifier */
3945 int flags = 0;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003946 Py_ssize_t width = -1;
Guido van Rossume5372401993-03-16 12:15:04 +00003947 int prec = -1;
Guido van Rossum6938a291993-11-11 14:51:57 +00003948 int c = '\0';
Guido van Rossume5372401993-03-16 12:15:04 +00003949 int fill;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003950 PyObject *v = NULL;
3951 PyObject *temp = NULL;
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00003952 char *pbuf;
Guido van Rossume5372401993-03-16 12:15:04 +00003953 int sign;
Martin v. Löwis725507b2006-03-07 12:08:51 +00003954 Py_ssize_t len;
Guido van Rossum3aa3fc42002-04-15 13:48:52 +00003955 char formatbuf[FORMATBUFLEN];
3956 /* For format{float,int,char}() */
Martin v. Löwis339d0f72001-08-17 18:39:25 +00003957#ifdef Py_USING_UNICODE
Guido van Rossum90daa872000-04-10 13:47:21 +00003958 char *fmt_start = fmt;
Martin v. Löwis725507b2006-03-07 12:08:51 +00003959 Py_ssize_t argidx_start = argidx;
Martin v. Löwis339d0f72001-08-17 18:39:25 +00003960#endif
Tim Petersb3d8d1f2001-04-28 05:38:26 +00003961
Guido van Rossumda9c2711996-12-05 21:58:58 +00003962 fmt++;
Guido van Rossum013142a1994-08-30 08:19:36 +00003963 if (*fmt == '(') {
3964 char *keystart;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003965 Py_ssize_t keylen;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003966 PyObject *key;
Guido van Rossum045e6881997-09-08 18:30:11 +00003967 int pcount = 1;
Guido van Rossum013142a1994-08-30 08:19:36 +00003968
3969 if (dict == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003970 PyErr_SetString(PyExc_TypeError,
Tim Petersb3d8d1f2001-04-28 05:38:26 +00003971 "format requires a mapping");
Guido van Rossum013142a1994-08-30 08:19:36 +00003972 goto error;
3973 }
3974 ++fmt;
3975 --fmtcnt;
3976 keystart = fmt;
Guido van Rossum045e6881997-09-08 18:30:11 +00003977 /* Skip over balanced parentheses */
3978 while (pcount > 0 && --fmtcnt >= 0) {
3979 if (*fmt == ')')
3980 --pcount;
3981 else if (*fmt == '(')
3982 ++pcount;
Guido van Rossum013142a1994-08-30 08:19:36 +00003983 fmt++;
Guido van Rossum045e6881997-09-08 18:30:11 +00003984 }
3985 keylen = fmt - keystart - 1;
3986 if (fmtcnt < 0 || pcount > 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003987 PyErr_SetString(PyExc_ValueError,
Guido van Rossum013142a1994-08-30 08:19:36 +00003988 "incomplete format key");
3989 goto error;
3990 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003991 key = PyString_FromStringAndSize(keystart,
3992 keylen);
Guido van Rossum013142a1994-08-30 08:19:36 +00003993 if (key == NULL)
3994 goto error;
Guido van Rossum993952b1996-05-21 22:44:20 +00003995 if (args_owned) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003996 Py_DECREF(args);
Guido van Rossum993952b1996-05-21 22:44:20 +00003997 args_owned = 0;
3998 }
3999 args = PyObject_GetItem(dict, key);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004000 Py_DECREF(key);
Guido van Rossum013142a1994-08-30 08:19:36 +00004001 if (args == NULL) {
4002 goto error;
4003 }
Guido van Rossum993952b1996-05-21 22:44:20 +00004004 args_owned = 1;
Guido van Rossum013142a1994-08-30 08:19:36 +00004005 arglen = -1;
4006 argidx = -2;
4007 }
Guido van Rossume5372401993-03-16 12:15:04 +00004008 while (--fmtcnt >= 0) {
4009 switch (c = *fmt++) {
4010 case '-': flags |= F_LJUST; continue;
4011 case '+': flags |= F_SIGN; continue;
4012 case ' ': flags |= F_BLANK; continue;
4013 case '#': flags |= F_ALT; continue;
4014 case '0': flags |= F_ZERO; continue;
4015 }
4016 break;
4017 }
4018 if (c == '*') {
4019 v = getnextarg(args, arglen, &argidx);
4020 if (v == NULL)
4021 goto error;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004022 if (!PyInt_Check(v)) {
4023 PyErr_SetString(PyExc_TypeError,
4024 "* wants int");
Guido van Rossume5372401993-03-16 12:15:04 +00004025 goto error;
4026 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004027 width = PyInt_AsLong(v);
Guido van Rossum98c9eba1999-06-07 15:12:32 +00004028 if (width < 0) {
4029 flags |= F_LJUST;
4030 width = -width;
4031 }
Guido van Rossume5372401993-03-16 12:15:04 +00004032 if (--fmtcnt >= 0)
4033 c = *fmt++;
4034 }
Guido van Rossum9fa2c111995-02-10 17:00:37 +00004035 else if (c >= 0 && isdigit(c)) {
Guido van Rossume5372401993-03-16 12:15:04 +00004036 width = c - '0';
4037 while (--fmtcnt >= 0) {
Guido van Rossum9fa2c111995-02-10 17:00:37 +00004038 c = Py_CHARMASK(*fmt++);
Guido van Rossume5372401993-03-16 12:15:04 +00004039 if (!isdigit(c))
4040 break;
4041 if ((width*10) / 10 != width) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004042 PyErr_SetString(
4043 PyExc_ValueError,
4044 "width too big");
Guido van Rossume5372401993-03-16 12:15:04 +00004045 goto error;
4046 }
4047 width = width*10 + (c - '0');
4048 }
4049 }
4050 if (c == '.') {
4051 prec = 0;
4052 if (--fmtcnt >= 0)
4053 c = *fmt++;
4054 if (c == '*') {
4055 v = getnextarg(args, arglen, &argidx);
4056 if (v == NULL)
4057 goto error;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004058 if (!PyInt_Check(v)) {
4059 PyErr_SetString(
4060 PyExc_TypeError,
4061 "* wants int");
Guido van Rossume5372401993-03-16 12:15:04 +00004062 goto error;
4063 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004064 prec = PyInt_AsLong(v);
Guido van Rossume5372401993-03-16 12:15:04 +00004065 if (prec < 0)
4066 prec = 0;
4067 if (--fmtcnt >= 0)
4068 c = *fmt++;
4069 }
Guido van Rossum9fa2c111995-02-10 17:00:37 +00004070 else if (c >= 0 && isdigit(c)) {
Guido van Rossume5372401993-03-16 12:15:04 +00004071 prec = c - '0';
4072 while (--fmtcnt >= 0) {
Guido van Rossum9fa2c111995-02-10 17:00:37 +00004073 c = Py_CHARMASK(*fmt++);
Guido van Rossume5372401993-03-16 12:15:04 +00004074 if (!isdigit(c))
4075 break;
4076 if ((prec*10) / 10 != prec) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004077 PyErr_SetString(
4078 PyExc_ValueError,
Guido van Rossume5372401993-03-16 12:15:04 +00004079 "prec too big");
4080 goto error;
4081 }
4082 prec = prec*10 + (c - '0');
4083 }
4084 }
4085 } /* prec */
4086 if (fmtcnt >= 0) {
4087 if (c == 'h' || c == 'l' || c == 'L') {
Guido van Rossume5372401993-03-16 12:15:04 +00004088 if (--fmtcnt >= 0)
4089 c = *fmt++;
4090 }
4091 }
4092 if (fmtcnt < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004093 PyErr_SetString(PyExc_ValueError,
4094 "incomplete format");
Guido van Rossume5372401993-03-16 12:15:04 +00004095 goto error;
4096 }
4097 if (c != '%') {
4098 v = getnextarg(args, arglen, &argidx);
4099 if (v == NULL)
4100 goto error;
4101 }
4102 sign = 0;
4103 fill = ' ';
4104 switch (c) {
4105 case '%':
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00004106 pbuf = "%";
Guido van Rossume5372401993-03-16 12:15:04 +00004107 len = 1;
4108 break;
4109 case 's':
Martin v. Löwis339d0f72001-08-17 18:39:25 +00004110#ifdef Py_USING_UNICODE
Neil Schemenauerab619232005-08-31 23:02:05 +00004111 if (PyUnicode_Check(v)) {
4112 fmt = fmt_start;
4113 argidx = argidx_start;
4114 goto unicode;
4115 }
Georg Brandld45014b2005-10-01 17:06:00 +00004116#endif
Neil Schemenauercf52c072005-08-12 17:34:58 +00004117 temp = _PyObject_Str(v);
Georg Brandld45014b2005-10-01 17:06:00 +00004118#ifdef Py_USING_UNICODE
Neil Schemenauercf52c072005-08-12 17:34:58 +00004119 if (temp != NULL && PyUnicode_Check(temp)) {
4120 Py_DECREF(temp);
Guido van Rossum90daa872000-04-10 13:47:21 +00004121 fmt = fmt_start;
Marc-André Lemburg542fe562001-05-02 14:21:53 +00004122 argidx = argidx_start;
Guido van Rossum90daa872000-04-10 13:47:21 +00004123 goto unicode;
4124 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00004125#endif
Guido van Rossumb00c07f2002-10-09 19:07:53 +00004126 /* Fall through */
Walter Dörwald9ff3f032003-06-18 14:17:01 +00004127 case 'r':
Neil Schemenauercf52c072005-08-12 17:34:58 +00004128 if (c == 'r')
Guido van Rossumf0b7b042000-04-11 15:39:26 +00004129 temp = PyObject_Repr(v);
Guido van Rossum013142a1994-08-30 08:19:36 +00004130 if (temp == NULL)
Guido van Rossume5372401993-03-16 12:15:04 +00004131 goto error;
Guido van Rossum4a0144c1998-06-09 15:08:41 +00004132 if (!PyString_Check(temp)) {
4133 PyErr_SetString(PyExc_TypeError,
Guido van Rossum8052f892002-10-09 19:14:30 +00004134 "%s argument has non-string str()");
Jeremy Hylton7802a532001-12-06 15:18:48 +00004135 Py_DECREF(temp);
Guido van Rossum4a0144c1998-06-09 15:08:41 +00004136 goto error;
4137 }
Jeremy Hylton7802a532001-12-06 15:18:48 +00004138 pbuf = PyString_AS_STRING(temp);
4139 len = PyString_GET_SIZE(temp);
Guido van Rossume5372401993-03-16 12:15:04 +00004140 if (prec >= 0 && len > prec)
4141 len = prec;
4142 break;
4143 case 'i':
4144 case 'd':
4145 case 'u':
4146 case 'o':
4147 case 'x':
4148 case 'X':
4149 if (c == 'i')
4150 c = 'd';
Tim Petersa3a3a032000-11-30 05:22:44 +00004151 if (PyLong_Check(v)) {
Martin v. Löwis725507b2006-03-07 12:08:51 +00004152 int ilen;
Tim Peters38fd5b62000-09-21 05:43:11 +00004153 temp = _PyString_FormatLong(v, flags,
Martin v. Löwis725507b2006-03-07 12:08:51 +00004154 prec, c, &pbuf, &ilen);
4155 len = ilen;
Tim Peters38fd5b62000-09-21 05:43:11 +00004156 if (!temp)
4157 goto error;
Tim Peters38fd5b62000-09-21 05:43:11 +00004158 sign = 1;
Guido van Rossum4acdc231997-01-29 06:00:24 +00004159 }
Tim Peters38fd5b62000-09-21 05:43:11 +00004160 else {
4161 pbuf = formatbuf;
Guido van Rossum3aa3fc42002-04-15 13:48:52 +00004162 len = formatint(pbuf,
4163 sizeof(formatbuf),
Tim Peters38fd5b62000-09-21 05:43:11 +00004164 flags, prec, c, v);
4165 if (len < 0)
4166 goto error;
Guido van Rossum6c9e1302003-11-29 23:52:13 +00004167 sign = 1;
Tim Peters38fd5b62000-09-21 05:43:11 +00004168 }
4169 if (flags & F_ZERO)
4170 fill = '0';
Guido van Rossume5372401993-03-16 12:15:04 +00004171 break;
4172 case 'e':
4173 case 'E':
4174 case 'f':
Raymond Hettinger9bfe5332003-08-27 04:55:52 +00004175 case 'F':
Guido van Rossume5372401993-03-16 12:15:04 +00004176 case 'g':
4177 case 'G':
Raymond Hettinger9bfe5332003-08-27 04:55:52 +00004178 if (c == 'F')
4179 c = 'f';
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00004180 pbuf = formatbuf;
Guido van Rossum3aa3fc42002-04-15 13:48:52 +00004181 len = formatfloat(pbuf, sizeof(formatbuf),
4182 flags, prec, c, v);
Guido van Rossuma04d47b1997-01-21 16:12:09 +00004183 if (len < 0)
Guido van Rossume5372401993-03-16 12:15:04 +00004184 goto error;
Guido van Rossume5372401993-03-16 12:15:04 +00004185 sign = 1;
Tim Peters38fd5b62000-09-21 05:43:11 +00004186 if (flags & F_ZERO)
Guido van Rossume5372401993-03-16 12:15:04 +00004187 fill = '0';
4188 break;
4189 case 'c':
Walter Dörwald43440a62003-03-31 18:07:50 +00004190#ifdef Py_USING_UNICODE
4191 if (PyUnicode_Check(v)) {
4192 fmt = fmt_start;
4193 argidx = argidx_start;
4194 goto unicode;
4195 }
4196#endif
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00004197 pbuf = formatbuf;
4198 len = formatchar(pbuf, sizeof(formatbuf), v);
Guido van Rossuma04d47b1997-01-21 16:12:09 +00004199 if (len < 0)
Guido van Rossume5372401993-03-16 12:15:04 +00004200 goto error;
Guido van Rossume5372401993-03-16 12:15:04 +00004201 break;
4202 default:
Guido van Rossum045e6881997-09-08 18:30:11 +00004203 PyErr_Format(PyExc_ValueError,
Andrew M. Kuchling6ca89172000-12-15 13:07:46 +00004204 "unsupported format character '%c' (0x%x) "
4205 "at index %i",
Guido van Rossumefc11882002-09-12 14:43:41 +00004206 c, c,
4207 (int)(fmt - 1 - PyString_AsString(format)));
Guido van Rossume5372401993-03-16 12:15:04 +00004208 goto error;
4209 }
4210 if (sign) {
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00004211 if (*pbuf == '-' || *pbuf == '+') {
4212 sign = *pbuf++;
Guido van Rossume5372401993-03-16 12:15:04 +00004213 len--;
4214 }
4215 else if (flags & F_SIGN)
4216 sign = '+';
4217 else if (flags & F_BLANK)
4218 sign = ' ';
4219 else
Tim Peters38fd5b62000-09-21 05:43:11 +00004220 sign = 0;
Guido van Rossume5372401993-03-16 12:15:04 +00004221 }
4222 if (width < len)
4223 width = len;
Guido van Rossum049cd6b2002-10-11 00:43:48 +00004224 if (rescnt - (sign != 0) < width) {
Guido van Rossum6ac258d1993-05-12 08:24:20 +00004225 reslen -= rescnt;
4226 rescnt = width + fmtcnt + 100;
4227 reslen += rescnt;
Guido van Rossum049cd6b2002-10-11 00:43:48 +00004228 if (reslen < 0) {
4229 Py_DECREF(result);
4230 return PyErr_NoMemory();
4231 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004232 if (_PyString_Resize(&result, reslen) < 0)
Guido van Rossume5372401993-03-16 12:15:04 +00004233 return NULL;
Jeremy Hylton7802a532001-12-06 15:18:48 +00004234 res = PyString_AS_STRING(result)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004235 + reslen - rescnt;
Guido van Rossume5372401993-03-16 12:15:04 +00004236 }
4237 if (sign) {
Guido van Rossum71e57d01993-11-11 15:03:51 +00004238 if (fill != ' ')
4239 *res++ = sign;
Guido van Rossume5372401993-03-16 12:15:04 +00004240 rescnt--;
4241 if (width > len)
4242 width--;
4243 }
Tim Peters38fd5b62000-09-21 05:43:11 +00004244 if ((flags & F_ALT) && (c == 'x' || c == 'X')) {
4245 assert(pbuf[0] == '0');
Tim Petersfff53252001-04-12 18:38:48 +00004246 assert(pbuf[1] == c);
4247 if (fill != ' ') {
4248 *res++ = *pbuf++;
4249 *res++ = *pbuf++;
Tim Peters38fd5b62000-09-21 05:43:11 +00004250 }
Tim Petersfff53252001-04-12 18:38:48 +00004251 rescnt -= 2;
4252 width -= 2;
4253 if (width < 0)
4254 width = 0;
4255 len -= 2;
Tim Peters38fd5b62000-09-21 05:43:11 +00004256 }
4257 if (width > len && !(flags & F_LJUST)) {
Guido van Rossume5372401993-03-16 12:15:04 +00004258 do {
4259 --rescnt;
4260 *res++ = fill;
4261 } while (--width > len);
4262 }
Tim Peters38fd5b62000-09-21 05:43:11 +00004263 if (fill == ' ') {
4264 if (sign)
4265 *res++ = sign;
4266 if ((flags & F_ALT) &&
Tim Petersfff53252001-04-12 18:38:48 +00004267 (c == 'x' || c == 'X')) {
4268 assert(pbuf[0] == '0');
4269 assert(pbuf[1] == c);
Tim Peters38fd5b62000-09-21 05:43:11 +00004270 *res++ = *pbuf++;
4271 *res++ = *pbuf++;
4272 }
4273 }
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00004274 memcpy(res, pbuf, len);
Guido van Rossume5372401993-03-16 12:15:04 +00004275 res += len;
4276 rescnt -= len;
4277 while (--width >= len) {
4278 --rescnt;
4279 *res++ = ' ';
4280 }
Guido van Rossum9fa2c111995-02-10 17:00:37 +00004281 if (dict && (argidx < arglen) && c != '%') {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004282 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger0ebac972002-05-21 15:14:57 +00004283 "not all arguments converted during string formatting");
Guido van Rossum013142a1994-08-30 08:19:36 +00004284 goto error;
4285 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004286 Py_XDECREF(temp);
Guido van Rossume5372401993-03-16 12:15:04 +00004287 } /* '%' */
4288 } /* until end */
Guido van Rossumcaeaafc1995-02-27 10:13:23 +00004289 if (argidx < arglen && !dict) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004290 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger0ebac972002-05-21 15:14:57 +00004291 "not all arguments converted during string formatting");
Guido van Rossume5372401993-03-16 12:15:04 +00004292 goto error;
4293 }
Guido van Rossum1109fbc1998-04-10 22:16:39 +00004294 if (args_owned) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004295 Py_DECREF(args);
Guido van Rossum1109fbc1998-04-10 22:16:39 +00004296 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004297 _PyString_Resize(&result, reslen - rescnt);
Guido van Rossume5372401993-03-16 12:15:04 +00004298 return result;
Guido van Rossum90daa872000-04-10 13:47:21 +00004299
Martin v. Löwis339d0f72001-08-17 18:39:25 +00004300#ifdef Py_USING_UNICODE
Guido van Rossum90daa872000-04-10 13:47:21 +00004301 unicode:
4302 if (args_owned) {
4303 Py_DECREF(args);
4304 args_owned = 0;
4305 }
Marc-André Lemburg542fe562001-05-02 14:21:53 +00004306 /* Fiddle args right (remove the first argidx arguments) */
Guido van Rossum90daa872000-04-10 13:47:21 +00004307 if (PyTuple_Check(orig_args) && argidx > 0) {
4308 PyObject *v;
Martin v. Löwiseb079f12006-02-16 14:32:27 +00004309 Py_ssize_t n = PyTuple_GET_SIZE(orig_args) - argidx;
Guido van Rossum90daa872000-04-10 13:47:21 +00004310 v = PyTuple_New(n);
4311 if (v == NULL)
4312 goto error;
4313 while (--n >= 0) {
4314 PyObject *w = PyTuple_GET_ITEM(orig_args, n + argidx);
4315 Py_INCREF(w);
4316 PyTuple_SET_ITEM(v, n, w);
4317 }
4318 args = v;
4319 } else {
4320 Py_INCREF(orig_args);
4321 args = orig_args;
4322 }
Marc-André Lemburg53f3d4a2000-10-07 08:54:09 +00004323 args_owned = 1;
4324 /* Take what we have of the result and let the Unicode formatting
4325 function format the rest of the input. */
Guido van Rossum90daa872000-04-10 13:47:21 +00004326 rescnt = res - PyString_AS_STRING(result);
Marc-André Lemburg53f3d4a2000-10-07 08:54:09 +00004327 if (_PyString_Resize(&result, rescnt))
4328 goto error;
Guido van Rossum90daa872000-04-10 13:47:21 +00004329 fmtcnt = PyString_GET_SIZE(format) - \
4330 (fmt - PyString_AS_STRING(format));
Marc-André Lemburg53f3d4a2000-10-07 08:54:09 +00004331 format = PyUnicode_Decode(fmt, fmtcnt, NULL, NULL);
4332 if (format == NULL)
Guido van Rossum90daa872000-04-10 13:47:21 +00004333 goto error;
Marc-André Lemburg53f3d4a2000-10-07 08:54:09 +00004334 v = PyUnicode_Format(format, args);
Guido van Rossum90daa872000-04-10 13:47:21 +00004335 Py_DECREF(format);
Marc-André Lemburg53f3d4a2000-10-07 08:54:09 +00004336 if (v == NULL)
4337 goto error;
4338 /* Paste what we have (result) to what the Unicode formatting
4339 function returned (v) and return the result (or error) */
4340 w = PyUnicode_Concat(result, v);
4341 Py_DECREF(result);
4342 Py_DECREF(v);
Guido van Rossum90daa872000-04-10 13:47:21 +00004343 Py_DECREF(args);
Marc-André Lemburg53f3d4a2000-10-07 08:54:09 +00004344 return w;
Martin v. Löwis339d0f72001-08-17 18:39:25 +00004345#endif /* Py_USING_UNICODE */
Tim Petersb3d8d1f2001-04-28 05:38:26 +00004346
Guido van Rossume5372401993-03-16 12:15:04 +00004347 error:
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004348 Py_DECREF(result);
Guido van Rossum1109fbc1998-04-10 22:16:39 +00004349 if (args_owned) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004350 Py_DECREF(args);
Guido van Rossum1109fbc1998-04-10 22:16:39 +00004351 }
Guido van Rossume5372401993-03-16 12:15:04 +00004352 return NULL;
4353}
Guido van Rossum2a61e741997-01-18 07:55:05 +00004354
Guido van Rossum2a61e741997-01-18 07:55:05 +00004355void
Fred Drakeba096332000-07-09 07:04:36 +00004356PyString_InternInPlace(PyObject **p)
Guido van Rossum2a61e741997-01-18 07:55:05 +00004357{
4358 register PyStringObject *s = (PyStringObject *)(*p);
4359 PyObject *t;
4360 if (s == NULL || !PyString_Check(s))
4361 Py_FatalError("PyString_InternInPlace: strings only please!");
Jeremy Hylton4c989dd2004-08-07 19:20:05 +00004362 /* If it's a string subclass, we don't really know what putting
4363 it in the interned dict might do. */
4364 if (!PyString_CheckExact(s))
4365 return;
Guido van Rossum45ec02a2002-08-19 21:43:18 +00004366 if (PyString_CHECK_INTERNED(s))
Guido van Rossum2a61e741997-01-18 07:55:05 +00004367 return;
Guido van Rossum2a61e741997-01-18 07:55:05 +00004368 if (interned == NULL) {
4369 interned = PyDict_New();
Guido van Rossum45ec02a2002-08-19 21:43:18 +00004370 if (interned == NULL) {
4371 PyErr_Clear(); /* Don't leave an exception */
Guido van Rossum2a61e741997-01-18 07:55:05 +00004372 return;
Guido van Rossum45ec02a2002-08-19 21:43:18 +00004373 }
Guido van Rossum2a61e741997-01-18 07:55:05 +00004374 }
Jeremy Hylton4c989dd2004-08-07 19:20:05 +00004375 t = PyDict_GetItem(interned, (PyObject *)s);
4376 if (t) {
Guido van Rossum2a61e741997-01-18 07:55:05 +00004377 Py_INCREF(t);
Guido van Rossum45ec02a2002-08-19 21:43:18 +00004378 Py_DECREF(*p);
4379 *p = t;
Guido van Rossum2a61e741997-01-18 07:55:05 +00004380 return;
4381 }
Guido van Rossum45ec02a2002-08-19 21:43:18 +00004382
Armin Rigo79f7ad22004-08-07 19:27:39 +00004383 if (PyDict_SetItem(interned, (PyObject *)s, (PyObject *)s) < 0) {
Jeremy Hylton4c989dd2004-08-07 19:20:05 +00004384 PyErr_Clear();
Guido van Rossum45ec02a2002-08-19 21:43:18 +00004385 return;
4386 }
Jeremy Hylton4c989dd2004-08-07 19:20:05 +00004387 /* The two references in interned are not counted by refcnt.
4388 The string deallocator will take care of this */
Armin Rigo79f7ad22004-08-07 19:27:39 +00004389 s->ob_refcnt -= 2;
Jeremy Hylton4c989dd2004-08-07 19:20:05 +00004390 PyString_CHECK_INTERNED(s) = SSTATE_INTERNED_MORTAL;
Guido van Rossum2a61e741997-01-18 07:55:05 +00004391}
4392
Guido van Rossum45ec02a2002-08-19 21:43:18 +00004393void
4394PyString_InternImmortal(PyObject **p)
4395{
4396 PyString_InternInPlace(p);
4397 if (PyString_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
4398 PyString_CHECK_INTERNED(*p) = SSTATE_INTERNED_IMMORTAL;
4399 Py_INCREF(*p);
4400 }
4401}
4402
Guido van Rossum2a61e741997-01-18 07:55:05 +00004403
4404PyObject *
Fred Drakeba096332000-07-09 07:04:36 +00004405PyString_InternFromString(const char *cp)
Guido van Rossum2a61e741997-01-18 07:55:05 +00004406{
4407 PyObject *s = PyString_FromString(cp);
4408 if (s == NULL)
4409 return NULL;
4410 PyString_InternInPlace(&s);
4411 return s;
4412}
4413
Guido van Rossum8cf04761997-08-02 02:57:45 +00004414void
Fred Drakeba096332000-07-09 07:04:36 +00004415PyString_Fini(void)
Guido van Rossum8cf04761997-08-02 02:57:45 +00004416{
4417 int i;
Guido van Rossum8cf04761997-08-02 02:57:45 +00004418 for (i = 0; i < UCHAR_MAX + 1; i++) {
4419 Py_XDECREF(characters[i]);
4420 characters[i] = NULL;
4421 }
Guido van Rossum8cf04761997-08-02 02:57:45 +00004422 Py_XDECREF(nullstring);
4423 nullstring = NULL;
Guido van Rossum8cf04761997-08-02 02:57:45 +00004424}
Barry Warsawa903ad982001-02-23 16:40:48 +00004425
Barry Warsawa903ad982001-02-23 16:40:48 +00004426void _Py_ReleaseInternedStrings(void)
4427{
Guido van Rossum45ec02a2002-08-19 21:43:18 +00004428 PyObject *keys;
4429 PyStringObject *s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004430 Py_ssize_t i, n;
Guido van Rossum45ec02a2002-08-19 21:43:18 +00004431
4432 if (interned == NULL || !PyDict_Check(interned))
4433 return;
4434 keys = PyDict_Keys(interned);
4435 if (keys == NULL || !PyList_Check(keys)) {
4436 PyErr_Clear();
4437 return;
Barry Warsawa903ad982001-02-23 16:40:48 +00004438 }
Guido van Rossum45ec02a2002-08-19 21:43:18 +00004439
4440 /* Since _Py_ReleaseInternedStrings() is intended to help a leak
4441 detector, interned strings are not forcibly deallocated; rather, we
4442 give them their stolen references back, and then clear and DECREF
4443 the interned dict. */
Tim Petersae1d0c92006-03-17 03:29:34 +00004444
Guido van Rossum45ec02a2002-08-19 21:43:18 +00004445 fprintf(stderr, "releasing interned strings\n");
4446 n = PyList_GET_SIZE(keys);
4447 for (i = 0; i < n; i++) {
4448 s = (PyStringObject *) PyList_GET_ITEM(keys, i);
4449 switch (s->ob_sstate) {
4450 case SSTATE_NOT_INTERNED:
4451 /* XXX Shouldn't happen */
4452 break;
4453 case SSTATE_INTERNED_IMMORTAL:
4454 s->ob_refcnt += 1;
4455 break;
4456 case SSTATE_INTERNED_MORTAL:
4457 s->ob_refcnt += 2;
4458 break;
4459 default:
4460 Py_FatalError("Inconsistent interned string state.");
4461 }
4462 s->ob_sstate = SSTATE_NOT_INTERNED;
4463 }
4464 Py_DECREF(keys);
4465 PyDict_Clear(interned);
4466 Py_DECREF(interned);
4467 interned = NULL;
Barry Warsawa903ad982001-02-23 16:40:48 +00004468}