blob: 7bddeaa99ea12fb4e7bae0d1b346a0aa81a37a32 [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
Fredrik Lundhdfe503d2006-05-25 16:10:12 +00002036/* _tolower and _toupper are defined by SUSv2, but they're not ISO C */
2037#ifndef _tolower
2038#define _tolower tolower
2039#endif
2040
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002041static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002042string_lower(PyStringObject *self)
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002043{
Fredrik Lundh39ccef62006-05-25 15:22:03 +00002044 char *s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002045 Py_ssize_t i, n = PyString_GET_SIZE(self);
Anthony Baxtera6286212006-04-11 07:42:36 +00002046 PyObject *newobj;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002047
Fredrik Lundh4b4e33e2006-05-25 15:49:45 +00002048 newobj = PyString_FromStringAndSize(NULL, n);
Fredrik Lundh39ccef62006-05-25 15:22:03 +00002049 if (!newobj)
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002050 return NULL;
Fredrik Lundh39ccef62006-05-25 15:22:03 +00002051
2052 s = PyString_AS_STRING(newobj);
2053
Fredrik Lundh4b4e33e2006-05-25 15:49:45 +00002054 memcpy(s, PyString_AS_STRING(self), n);
2055
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002056 for (i = 0; i < n; i++) {
Fredrik Lundh4b4e33e2006-05-25 15:49:45 +00002057 int c = Py_CHARMASK(s[i]);
Fredrik Lundh39ccef62006-05-25 15:22:03 +00002058 if (isupper(c))
2059 s[i] = _tolower(c);
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002060 }
Fredrik Lundh39ccef62006-05-25 15:22:03 +00002061
Anthony Baxtera6286212006-04-11 07:42:36 +00002062 return newobj;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002063}
2064
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002065PyDoc_STRVAR(upper__doc__,
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002066"S.upper() -> string\n\
2067\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002068Return a copy of the string S converted to uppercase.");
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002069
Fredrik Lundhdfe503d2006-05-25 16:10:12 +00002070#ifndef _toupper
2071#define _toupper toupper
2072#endif
2073
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002074static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002075string_upper(PyStringObject *self)
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002076{
Fredrik Lundh39ccef62006-05-25 15:22:03 +00002077 char *s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002078 Py_ssize_t i, n = PyString_GET_SIZE(self);
Anthony Baxtera6286212006-04-11 07:42:36 +00002079 PyObject *newobj;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002080
Fredrik Lundh4b4e33e2006-05-25 15:49:45 +00002081 newobj = PyString_FromStringAndSize(NULL, n);
Fredrik Lundh39ccef62006-05-25 15:22:03 +00002082 if (!newobj)
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002083 return NULL;
Fredrik Lundh39ccef62006-05-25 15:22:03 +00002084
2085 s = PyString_AS_STRING(newobj);
2086
Fredrik Lundh4b4e33e2006-05-25 15:49:45 +00002087 memcpy(s, PyString_AS_STRING(self), n);
2088
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002089 for (i = 0; i < n; i++) {
Fredrik Lundh4b4e33e2006-05-25 15:49:45 +00002090 int c = Py_CHARMASK(s[i]);
Fredrik Lundh39ccef62006-05-25 15:22:03 +00002091 if (islower(c))
2092 s[i] = _toupper(c);
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002093 }
Fredrik Lundh39ccef62006-05-25 15:22:03 +00002094
Anthony Baxtera6286212006-04-11 07:42:36 +00002095 return newobj;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002096}
2097
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002098PyDoc_STRVAR(title__doc__,
Guido van Rossum4c08d552000-03-10 22:55:18 +00002099"S.title() -> string\n\
2100\n\
2101Return a titlecased version of S, i.e. words start with uppercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002102characters, all remaining cased characters have lowercase.");
Guido van Rossum4c08d552000-03-10 22:55:18 +00002103
2104static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002105string_title(PyStringObject *self)
Guido van Rossum4c08d552000-03-10 22:55:18 +00002106{
2107 char *s = PyString_AS_STRING(self), *s_new;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002108 Py_ssize_t i, n = PyString_GET_SIZE(self);
Guido van Rossum4c08d552000-03-10 22:55:18 +00002109 int previous_is_cased = 0;
Anthony Baxtera6286212006-04-11 07:42:36 +00002110 PyObject *newobj;
Guido van Rossum4c08d552000-03-10 22:55:18 +00002111
Anthony Baxtera6286212006-04-11 07:42:36 +00002112 newobj = PyString_FromStringAndSize(NULL, n);
2113 if (newobj == NULL)
Guido van Rossum4c08d552000-03-10 22:55:18 +00002114 return NULL;
Anthony Baxtera6286212006-04-11 07:42:36 +00002115 s_new = PyString_AsString(newobj);
Guido van Rossum4c08d552000-03-10 22:55:18 +00002116 for (i = 0; i < n; i++) {
2117 int c = Py_CHARMASK(*s++);
2118 if (islower(c)) {
2119 if (!previous_is_cased)
2120 c = toupper(c);
2121 previous_is_cased = 1;
2122 } else if (isupper(c)) {
2123 if (previous_is_cased)
2124 c = tolower(c);
2125 previous_is_cased = 1;
2126 } else
2127 previous_is_cased = 0;
2128 *s_new++ = c;
2129 }
Anthony Baxtera6286212006-04-11 07:42:36 +00002130 return newobj;
Guido van Rossum4c08d552000-03-10 22:55:18 +00002131}
2132
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002133PyDoc_STRVAR(capitalize__doc__,
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002134"S.capitalize() -> string\n\
2135\n\
2136Return a copy of the string S with only its first character\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002137capitalized.");
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002138
2139static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002140string_capitalize(PyStringObject *self)
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002141{
2142 char *s = PyString_AS_STRING(self), *s_new;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002143 Py_ssize_t i, n = PyString_GET_SIZE(self);
Anthony Baxtera6286212006-04-11 07:42:36 +00002144 PyObject *newobj;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002145
Anthony Baxtera6286212006-04-11 07:42:36 +00002146 newobj = PyString_FromStringAndSize(NULL, n);
2147 if (newobj == NULL)
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002148 return NULL;
Anthony Baxtera6286212006-04-11 07:42:36 +00002149 s_new = PyString_AsString(newobj);
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002150 if (0 < n) {
2151 int c = Py_CHARMASK(*s++);
2152 if (islower(c))
2153 *s_new = toupper(c);
2154 else
2155 *s_new = c;
2156 s_new++;
2157 }
2158 for (i = 1; i < n; i++) {
2159 int c = Py_CHARMASK(*s++);
2160 if (isupper(c))
2161 *s_new = tolower(c);
2162 else
2163 *s_new = c;
2164 s_new++;
2165 }
Anthony Baxtera6286212006-04-11 07:42:36 +00002166 return newobj;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002167}
2168
2169
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002170PyDoc_STRVAR(count__doc__,
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002171"S.count(sub[, start[, end]]) -> int\n\
2172\n\
Fredrik Lundh763b50f2006-05-22 15:35:12 +00002173Return the number of non-overlapping occurrences of substring sub in\n\
2174string S[start:end]. Optional arguments start and end are interpreted\n\
2175as in slice notation.");
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002176
2177static PyObject *
Fred Drakeba096332000-07-09 07:04:36 +00002178string_count(PyStringObject *self, PyObject *args)
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002179{
Raymond Hettinger57e74472005-02-20 09:54:53 +00002180 const char *s = PyString_AS_STRING(self), *sub, *t;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002181 Py_ssize_t len = PyString_GET_SIZE(self), n;
Martin v. Löwis8ce358f2006-04-13 07:22:51 +00002182 Py_ssize_t i = 0, last = PY_SSIZE_T_MAX;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002183 Py_ssize_t m, r;
Guido van Rossum4c08d552000-03-10 22:55:18 +00002184 PyObject *subobj;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002185
Guido van Rossumc6821402000-05-08 14:08:05 +00002186 if (!PyArg_ParseTuple(args, "O|O&O&:count", &subobj,
2187 _PyEval_SliceIndex, &i, _PyEval_SliceIndex, &last))
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002188 return NULL;
Guido van Rossumc6821402000-05-08 14:08:05 +00002189
Guido van Rossum4c08d552000-03-10 22:55:18 +00002190 if (PyString_Check(subobj)) {
2191 sub = PyString_AS_STRING(subobj);
2192 n = PyString_GET_SIZE(subobj);
2193 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002194#ifdef Py_USING_UNICODE
Marc-André Lemburg3a645e42001-01-16 11:54:12 +00002195 else if (PyUnicode_Check(subobj)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002196 Py_ssize_t count;
Marc-André Lemburg3a645e42001-01-16 11:54:12 +00002197 count = PyUnicode_Count((PyObject *)self, subobj, i, last);
2198 if (count == -1)
2199 return NULL;
2200 else
2201 return PyInt_FromLong((long) count);
2202 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002203#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +00002204 else if (PyObject_AsCharBuffer(subobj, &sub, &n))
2205 return NULL;
2206
Neal Norwitz1f68fc72002-06-14 00:50:42 +00002207 string_adjust_indices(&i, &last, len);
2208
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002209 m = last + 1 - n;
2210 if (n == 0)
Martin v. Löwis18e16552006-02-15 17:27:45 +00002211 return PyInt_FromSsize_t(m-i);
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002212
2213 r = 0;
2214 while (i < m) {
2215 if (!memcmp(s+i, sub, n)) {
2216 r++;
2217 i += n;
2218 } else {
2219 i++;
2220 }
Raymond Hettinger57e74472005-02-20 09:54:53 +00002221 if (i >= m)
2222 break;
Anthony Baxtera6286212006-04-11 07:42:36 +00002223 t = (const char *)memchr(s+i, sub[0], m-i);
Raymond Hettinger57e74472005-02-20 09:54:53 +00002224 if (t == NULL)
2225 break;
2226 i = t - s;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002227 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002228 return PyInt_FromSsize_t(r);
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002229}
2230
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002231PyDoc_STRVAR(swapcase__doc__,
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002232"S.swapcase() -> string\n\
2233\n\
Guido van Rossum4c08d552000-03-10 22:55:18 +00002234Return a copy of the string S with uppercase characters\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002235converted to lowercase and vice versa.");
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002236
2237static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002238string_swapcase(PyStringObject *self)
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002239{
2240 char *s = PyString_AS_STRING(self), *s_new;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002241 Py_ssize_t i, n = PyString_GET_SIZE(self);
Anthony Baxtera6286212006-04-11 07:42:36 +00002242 PyObject *newobj;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002243
Anthony Baxtera6286212006-04-11 07:42:36 +00002244 newobj = PyString_FromStringAndSize(NULL, n);
2245 if (newobj == NULL)
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002246 return NULL;
Anthony Baxtera6286212006-04-11 07:42:36 +00002247 s_new = PyString_AsString(newobj);
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002248 for (i = 0; i < n; i++) {
2249 int c = Py_CHARMASK(*s++);
2250 if (islower(c)) {
2251 *s_new = toupper(c);
2252 }
2253 else if (isupper(c)) {
2254 *s_new = tolower(c);
2255 }
2256 else
2257 *s_new = c;
2258 s_new++;
2259 }
Anthony Baxtera6286212006-04-11 07:42:36 +00002260 return newobj;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002261}
2262
2263
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002264PyDoc_STRVAR(translate__doc__,
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002265"S.translate(table [,deletechars]) -> string\n\
2266\n\
2267Return a copy of the string S, where all characters occurring\n\
2268in the optional argument deletechars are removed, and the\n\
2269remaining characters have been mapped through the given\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002270translation table, which must be a string of length 256.");
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002271
2272static PyObject *
Fred Drakeba096332000-07-09 07:04:36 +00002273string_translate(PyStringObject *self, PyObject *args)
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002274{
Guido van Rossum4c08d552000-03-10 22:55:18 +00002275 register char *input, *output;
2276 register const char *table;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002277 register Py_ssize_t i, c, changed = 0;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002278 PyObject *input_obj = (PyObject*)self;
Guido van Rossum4c08d552000-03-10 22:55:18 +00002279 const char *table1, *output_start, *del_table=NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002280 Py_ssize_t inlen, tablen, dellen = 0;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002281 PyObject *result;
2282 int trans_table[256];
Guido van Rossum4c08d552000-03-10 22:55:18 +00002283 PyObject *tableobj, *delobj = NULL;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002284
Raymond Hettingerea3fdf42002-12-29 16:33:45 +00002285 if (!PyArg_UnpackTuple(args, "translate", 1, 2,
Guido van Rossum4c08d552000-03-10 22:55:18 +00002286 &tableobj, &delobj))
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002287 return NULL;
Guido van Rossum4c08d552000-03-10 22:55:18 +00002288
2289 if (PyString_Check(tableobj)) {
2290 table1 = PyString_AS_STRING(tableobj);
2291 tablen = PyString_GET_SIZE(tableobj);
2292 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002293#ifdef Py_USING_UNICODE
Guido van Rossum4c08d552000-03-10 22:55:18 +00002294 else if (PyUnicode_Check(tableobj)) {
Tim Petersb3d8d1f2001-04-28 05:38:26 +00002295 /* Unicode .translate() does not support the deletechars
Guido van Rossum4c08d552000-03-10 22:55:18 +00002296 parameter; instead a mapping to None will cause characters
2297 to be deleted. */
2298 if (delobj != NULL) {
2299 PyErr_SetString(PyExc_TypeError,
2300 "deletions are implemented differently for unicode");
2301 return NULL;
2302 }
2303 return PyUnicode_Translate((PyObject *)self, tableobj, NULL);
2304 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002305#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +00002306 else if (PyObject_AsCharBuffer(tableobj, &table1, &tablen))
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002307 return NULL;
Guido van Rossum4c08d552000-03-10 22:55:18 +00002308
Martin v. Löwis00b61272002-12-12 20:03:19 +00002309 if (tablen != 256) {
2310 PyErr_SetString(PyExc_ValueError,
2311 "translation table must be 256 characters long");
2312 return NULL;
2313 }
2314
Guido van Rossum4c08d552000-03-10 22:55:18 +00002315 if (delobj != NULL) {
2316 if (PyString_Check(delobj)) {
2317 del_table = PyString_AS_STRING(delobj);
2318 dellen = PyString_GET_SIZE(delobj);
2319 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002320#ifdef Py_USING_UNICODE
Guido van Rossum4c08d552000-03-10 22:55:18 +00002321 else if (PyUnicode_Check(delobj)) {
2322 PyErr_SetString(PyExc_TypeError,
2323 "deletions are implemented differently for unicode");
2324 return NULL;
2325 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002326#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +00002327 else if (PyObject_AsCharBuffer(delobj, &del_table, &dellen))
2328 return NULL;
Guido van Rossum4c08d552000-03-10 22:55:18 +00002329 }
2330 else {
2331 del_table = NULL;
2332 dellen = 0;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002333 }
2334
2335 table = table1;
Neal Norwitz2aa9a5d2006-03-20 01:53:23 +00002336 inlen = PyString_GET_SIZE(input_obj);
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002337 result = PyString_FromStringAndSize((char *)NULL, inlen);
2338 if (result == NULL)
2339 return NULL;
2340 output_start = output = PyString_AsString(result);
Neal Norwitz2aa9a5d2006-03-20 01:53:23 +00002341 input = PyString_AS_STRING(input_obj);
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002342
2343 if (dellen == 0) {
2344 /* If no deletions are required, use faster code */
2345 for (i = inlen; --i >= 0; ) {
2346 c = Py_CHARMASK(*input++);
2347 if (Py_CHARMASK((*output++ = table[c])) != c)
2348 changed = 1;
2349 }
Tim Peters8fa5dd02001-09-12 02:18:30 +00002350 if (changed || !PyString_CheckExact(input_obj))
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002351 return result;
2352 Py_DECREF(result);
2353 Py_INCREF(input_obj);
2354 return input_obj;
2355 }
2356
2357 for (i = 0; i < 256; i++)
2358 trans_table[i] = Py_CHARMASK(table[i]);
2359
2360 for (i = 0; i < dellen; i++)
2361 trans_table[(int) Py_CHARMASK(del_table[i])] = -1;
2362
2363 for (i = inlen; --i >= 0; ) {
2364 c = Py_CHARMASK(*input++);
2365 if (trans_table[c] != -1)
2366 if (Py_CHARMASK(*output++ = (char)trans_table[c]) == c)
2367 continue;
2368 changed = 1;
2369 }
Tim Peters8fa5dd02001-09-12 02:18:30 +00002370 if (!changed && PyString_CheckExact(input_obj)) {
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002371 Py_DECREF(result);
2372 Py_INCREF(input_obj);
2373 return input_obj;
2374 }
2375 /* Fix the size of the resulting string */
Tim Peters5de98422002-04-27 18:44:32 +00002376 if (inlen > 0)
2377 _PyString_Resize(&result, output - output_start);
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002378 return result;
2379}
2380
2381
2382/* What follows is used for implementing replace(). Perry Stoll. */
2383
2384/*
2385 mymemfind
2386
2387 strstr replacement for arbitrary blocks of memory.
2388
Barry Warsaw51ac5802000-03-20 16:36:48 +00002389 Locates the first occurrence in the memory pointed to by MEM of the
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002390 contents of memory pointed to by PAT. Returns the index into MEM if
2391 found, or -1 if not found. If len of PAT is greater than length of
2392 MEM, the function returns -1.
2393*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00002394static Py_ssize_t
2395mymemfind(const char *mem, Py_ssize_t len, const char *pat, Py_ssize_t pat_len)
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002396{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002397 register Py_ssize_t ii;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002398
2399 /* pattern can not occur in the last pat_len-1 chars */
2400 len -= pat_len;
2401
2402 for (ii = 0; ii <= len; ii++) {
Fred Drake396f6e02000-06-20 15:47:54 +00002403 if (mem[ii] == pat[0] && memcmp(&mem[ii], pat, pat_len) == 0) {
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002404 return ii;
2405 }
2406 }
2407 return -1;
2408}
2409
2410/*
2411 mymemcnt
2412
2413 Return the number of distinct times PAT is found in MEM.
2414 meaning mem=1111 and pat==11 returns 2.
2415 mem=11111 and pat==11 also return 2.
2416 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002417static Py_ssize_t
2418mymemcnt(const char *mem, Py_ssize_t len, const char *pat, Py_ssize_t pat_len)
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002419{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002420 register Py_ssize_t offset = 0;
2421 Py_ssize_t nfound = 0;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002422
2423 while (len >= 0) {
2424 offset = mymemfind(mem, len, pat, pat_len);
2425 if (offset == -1)
2426 break;
2427 mem += offset + pat_len;
2428 len -= offset + pat_len;
2429 nfound++;
2430 }
2431 return nfound;
2432}
2433
2434/*
2435 mymemreplace
2436
Thomas Wouters7e474022000-07-16 12:04:32 +00002437 Return a string in which all occurrences of PAT in memory STR are
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002438 replaced with SUB.
2439
Thomas Wouters7e474022000-07-16 12:04:32 +00002440 If length of PAT is less than length of STR or there are no occurrences
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002441 of PAT in STR, then the original string is returned. Otherwise, a new
2442 string is allocated here and returned.
2443
2444 on return, out_len is:
2445 the length of output string, or
2446 -1 if the input string is returned, or
2447 unchanged if an error occurs (no memory).
2448
2449 return value is:
2450 the new string allocated locally, or
2451 NULL if an error occurred.
2452*/
2453static char *
Martin v. Löwis18e16552006-02-15 17:27:45 +00002454mymemreplace(const char *str, Py_ssize_t len, /* input string */
2455 const char *pat, Py_ssize_t pat_len, /* pattern string to find */
2456 const char *sub, Py_ssize_t sub_len, /* substitution string */
2457 Py_ssize_t count, /* number of replacements */
2458 Py_ssize_t *out_len)
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002459{
2460 char *out_s;
2461 char *new_s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002462 Py_ssize_t nfound, offset, new_len;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002463
Guido van Rossum8b1a6d62002-08-23 18:21:28 +00002464 if (len == 0 || (pat_len == 0 && sub_len == 0) || pat_len > len)
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002465 goto return_same;
2466
2467 /* find length of output string */
Guido van Rossum8b1a6d62002-08-23 18:21:28 +00002468 nfound = (pat_len > 0) ? mymemcnt(str, len, pat, pat_len) : len + 1;
Tim Peters9c012af2001-05-10 00:32:57 +00002469 if (count < 0)
Martin v. Löwis8ce358f2006-04-13 07:22:51 +00002470 count = PY_SSIZE_T_MAX;
Tim Peters9c012af2001-05-10 00:32:57 +00002471 else if (nfound > count)
2472 nfound = count;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002473 if (nfound == 0)
2474 goto return_same;
Tim Peters4cd44ef2001-05-10 00:05:33 +00002475
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002476 new_len = len + nfound*(sub_len - pat_len);
Tim Peters4cd44ef2001-05-10 00:05:33 +00002477 if (new_len == 0) {
2478 /* Have to allocate something for the caller to free(). */
2479 out_s = (char *)PyMem_MALLOC(1);
Tim Peters9c012af2001-05-10 00:32:57 +00002480 if (out_s == NULL)
Tim Peters4cd44ef2001-05-10 00:05:33 +00002481 return NULL;
2482 out_s[0] = '\0';
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002483 }
Tim Peters4cd44ef2001-05-10 00:05:33 +00002484 else {
2485 assert(new_len > 0);
2486 new_s = (char *)PyMem_MALLOC(new_len);
2487 if (new_s == NULL)
2488 return NULL;
2489 out_s = new_s;
2490
Guido van Rossum8b1a6d62002-08-23 18:21:28 +00002491 if (pat_len > 0) {
2492 for (; nfound > 0; --nfound) {
2493 /* find index of next instance of pattern */
2494 offset = mymemfind(str, len, pat, pat_len);
2495 if (offset == -1)
2496 break;
Tim Peters4cd44ef2001-05-10 00:05:33 +00002497
Guido van Rossum8b1a6d62002-08-23 18:21:28 +00002498 /* copy non matching part of input string */
2499 memcpy(new_s, str, offset);
2500 str += offset + pat_len;
2501 len -= offset + pat_len;
Tim Peters4cd44ef2001-05-10 00:05:33 +00002502
Guido van Rossum8b1a6d62002-08-23 18:21:28 +00002503 /* copy substitute into the output string */
2504 new_s += offset;
2505 memcpy(new_s, sub, sub_len);
2506 new_s += sub_len;
2507 }
2508 /* copy any remaining values into output string */
2509 if (len > 0)
2510 memcpy(new_s, str, len);
Tim Peters4cd44ef2001-05-10 00:05:33 +00002511 }
Guido van Rossum8b1a6d62002-08-23 18:21:28 +00002512 else {
2513 for (;;++str, --len) {
2514 memcpy(new_s, sub, sub_len);
2515 new_s += sub_len;
2516 if (--nfound <= 0) {
2517 memcpy(new_s, str, len);
2518 break;
2519 }
2520 *new_s++ = *str;
2521 }
2522 }
Tim Peters4cd44ef2001-05-10 00:05:33 +00002523 }
2524 *out_len = new_len;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002525 return out_s;
2526
2527 return_same:
2528 *out_len = -1;
Tim Peters4cd44ef2001-05-10 00:05:33 +00002529 return (char *)str; /* cast away const */
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002530}
2531
2532
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002533PyDoc_STRVAR(replace__doc__,
Fred Draked22bb652003-10-22 02:56:40 +00002534"S.replace (old, new[, count]) -> string\n\
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002535\n\
2536Return a copy of string S with all occurrences of substring\n\
Fred Draked22bb652003-10-22 02:56:40 +00002537old replaced by new. If the optional argument count is\n\
2538given, only the first count occurrences are replaced.");
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002539
2540static PyObject *
Fred Drakeba096332000-07-09 07:04:36 +00002541string_replace(PyStringObject *self, PyObject *args)
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002542{
Guido van Rossum4c08d552000-03-10 22:55:18 +00002543 const char *str = PyString_AS_STRING(self), *sub, *repl;
2544 char *new_s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002545 const Py_ssize_t len = PyString_GET_SIZE(self);
2546 Py_ssize_t sub_len, repl_len, out_len;
Thomas Woutersdc5f8082006-04-19 15:38:01 +00002547 Py_ssize_t count = -1;
Anthony Baxtera6286212006-04-11 07:42:36 +00002548 PyObject *newobj;
Guido van Rossum4c08d552000-03-10 22:55:18 +00002549 PyObject *subobj, *replobj;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002550
Thomas Woutersdc5f8082006-04-19 15:38:01 +00002551 if (!PyArg_ParseTuple(args, "OO|n:replace",
Guido van Rossum4c08d552000-03-10 22:55:18 +00002552 &subobj, &replobj, &count))
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002553 return NULL;
Guido van Rossum4c08d552000-03-10 22:55:18 +00002554
2555 if (PyString_Check(subobj)) {
2556 sub = PyString_AS_STRING(subobj);
2557 sub_len = PyString_GET_SIZE(subobj);
2558 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002559#ifdef Py_USING_UNICODE
Guido van Rossum4c08d552000-03-10 22:55:18 +00002560 else if (PyUnicode_Check(subobj))
Tim Petersb3d8d1f2001-04-28 05:38:26 +00002561 return PyUnicode_Replace((PyObject *)self,
Guido van Rossum4c08d552000-03-10 22:55:18 +00002562 subobj, replobj, count);
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002563#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +00002564 else if (PyObject_AsCharBuffer(subobj, &sub, &sub_len))
2565 return NULL;
2566
2567 if (PyString_Check(replobj)) {
2568 repl = PyString_AS_STRING(replobj);
2569 repl_len = PyString_GET_SIZE(replobj);
2570 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002571#ifdef Py_USING_UNICODE
Guido van Rossum4c08d552000-03-10 22:55:18 +00002572 else if (PyUnicode_Check(replobj))
Tim Petersb3d8d1f2001-04-28 05:38:26 +00002573 return PyUnicode_Replace((PyObject *)self,
Guido van Rossum4c08d552000-03-10 22:55:18 +00002574 subobj, replobj, count);
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002575#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +00002576 else if (PyObject_AsCharBuffer(replobj, &repl, &repl_len))
2577 return NULL;
2578
Guido van Rossum4c08d552000-03-10 22:55:18 +00002579 new_s = mymemreplace(str,len,sub,sub_len,repl,repl_len,count,&out_len);
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002580 if (new_s == NULL) {
2581 PyErr_NoMemory();
2582 return NULL;
2583 }
2584 if (out_len == -1) {
Tim Peters8fa5dd02001-09-12 02:18:30 +00002585 if (PyString_CheckExact(self)) {
2586 /* we're returning another reference to self */
Anthony Baxtera6286212006-04-11 07:42:36 +00002587 newobj = (PyObject*)self;
2588 Py_INCREF(newobj);
Tim Peters8fa5dd02001-09-12 02:18:30 +00002589 }
2590 else {
Anthony Baxtera6286212006-04-11 07:42:36 +00002591 newobj = PyString_FromStringAndSize(str, len);
2592 if (newobj == NULL)
Tim Peters8fa5dd02001-09-12 02:18:30 +00002593 return NULL;
2594 }
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002595 }
2596 else {
Anthony Baxtera6286212006-04-11 07:42:36 +00002597 newobj = PyString_FromStringAndSize(new_s, out_len);
Guido van Rossumb18618d2000-05-03 23:44:39 +00002598 PyMem_FREE(new_s);
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002599 }
Anthony Baxtera6286212006-04-11 07:42:36 +00002600 return newobj;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002601}
2602
2603
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002604PyDoc_STRVAR(startswith__doc__,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002605"S.startswith(prefix[, start[, end]]) -> bool\n\
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002606\n\
Guido van Rossuma7132182003-04-09 19:32:45 +00002607Return True if S starts with the specified prefix, False otherwise.\n\
2608With optional start, test S beginning at that position.\n\
2609With optional end, stop comparing S at that position.");
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002610
2611static PyObject *
Fred Drakeba096332000-07-09 07:04:36 +00002612string_startswith(PyStringObject *self, PyObject *args)
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002613{
Guido van Rossum4c08d552000-03-10 22:55:18 +00002614 const char* str = PyString_AS_STRING(self);
Martin v. Löwis18e16552006-02-15 17:27:45 +00002615 Py_ssize_t len = PyString_GET_SIZE(self);
Guido van Rossum4c08d552000-03-10 22:55:18 +00002616 const char* prefix;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002617 Py_ssize_t plen;
2618 Py_ssize_t start = 0;
Martin v. Löwis8ce358f2006-04-13 07:22:51 +00002619 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossum4c08d552000-03-10 22:55:18 +00002620 PyObject *subobj;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002621
Guido van Rossumc6821402000-05-08 14:08:05 +00002622 if (!PyArg_ParseTuple(args, "O|O&O&:startswith", &subobj,
2623 _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
Guido van Rossum4c08d552000-03-10 22:55:18 +00002624 return NULL;
2625 if (PyString_Check(subobj)) {
2626 prefix = PyString_AS_STRING(subobj);
2627 plen = PyString_GET_SIZE(subobj);
2628 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002629#ifdef Py_USING_UNICODE
Marc-André Lemburg3a645e42001-01-16 11:54:12 +00002630 else if (PyUnicode_Check(subobj)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002631 Py_ssize_t rc;
Tim Petersb3d8d1f2001-04-28 05:38:26 +00002632 rc = PyUnicode_Tailmatch((PyObject *)self,
Marc-André Lemburg3a645e42001-01-16 11:54:12 +00002633 subobj, start, end, -1);
2634 if (rc == -1)
2635 return NULL;
2636 else
Guido van Rossum77f6a652002-04-03 22:41:51 +00002637 return PyBool_FromLong((long) rc);
Marc-André Lemburg3a645e42001-01-16 11:54:12 +00002638 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002639#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +00002640 else if (PyObject_AsCharBuffer(subobj, &prefix, &plen))
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002641 return NULL;
2642
Neal Norwitz1f68fc72002-06-14 00:50:42 +00002643 string_adjust_indices(&start, &end, len);
2644
2645 if (start+plen > len)
Guido van Rossum77f6a652002-04-03 22:41:51 +00002646 return PyBool_FromLong(0);
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002647
Neal Norwitz1f68fc72002-06-14 00:50:42 +00002648 if (end-start >= plen)
2649 return PyBool_FromLong(!memcmp(str+start, prefix, plen));
2650 else
2651 return PyBool_FromLong(0);
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002652}
2653
2654
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002655PyDoc_STRVAR(endswith__doc__,
Guido van Rossum77f6a652002-04-03 22:41:51 +00002656"S.endswith(suffix[, start[, end]]) -> bool\n\
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002657\n\
Guido van Rossuma7132182003-04-09 19:32:45 +00002658Return True if S ends with the specified suffix, False otherwise.\n\
2659With optional start, test S beginning at that position.\n\
2660With optional end, stop comparing S at that position.");
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002661
2662static PyObject *
Fred Drakeba096332000-07-09 07:04:36 +00002663string_endswith(PyStringObject *self, PyObject *args)
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002664{
Guido van Rossum4c08d552000-03-10 22:55:18 +00002665 const char* str = PyString_AS_STRING(self);
Martin v. Löwis18e16552006-02-15 17:27:45 +00002666 Py_ssize_t len = PyString_GET_SIZE(self);
Guido van Rossum4c08d552000-03-10 22:55:18 +00002667 const char* suffix;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002668 Py_ssize_t slen;
2669 Py_ssize_t start = 0;
Martin v. Löwis8ce358f2006-04-13 07:22:51 +00002670 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossum4c08d552000-03-10 22:55:18 +00002671 PyObject *subobj;
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002672
Guido van Rossumc6821402000-05-08 14:08:05 +00002673 if (!PyArg_ParseTuple(args, "O|O&O&:endswith", &subobj,
2674 _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
Guido van Rossum4c08d552000-03-10 22:55:18 +00002675 return NULL;
2676 if (PyString_Check(subobj)) {
2677 suffix = PyString_AS_STRING(subobj);
2678 slen = PyString_GET_SIZE(subobj);
2679 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002680#ifdef Py_USING_UNICODE
Marc-André Lemburg3a645e42001-01-16 11:54:12 +00002681 else if (PyUnicode_Check(subobj)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002682 Py_ssize_t rc;
Tim Petersb3d8d1f2001-04-28 05:38:26 +00002683 rc = PyUnicode_Tailmatch((PyObject *)self,
Marc-André Lemburg3a645e42001-01-16 11:54:12 +00002684 subobj, start, end, +1);
2685 if (rc == -1)
2686 return NULL;
2687 else
Guido van Rossum77f6a652002-04-03 22:41:51 +00002688 return PyBool_FromLong((long) rc);
Marc-André Lemburg3a645e42001-01-16 11:54:12 +00002689 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00002690#endif
Guido van Rossum4c08d552000-03-10 22:55:18 +00002691 else if (PyObject_AsCharBuffer(subobj, &suffix, &slen))
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002692 return NULL;
2693
Neal Norwitz1f68fc72002-06-14 00:50:42 +00002694 string_adjust_indices(&start, &end, len);
2695
2696 if (end-start < slen || start > len)
Guido van Rossum77f6a652002-04-03 22:41:51 +00002697 return PyBool_FromLong(0);
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002698
Neal Norwitz1f68fc72002-06-14 00:50:42 +00002699 if (end-slen > start)
2700 start = end - slen;
2701 if (end-start >= slen)
2702 return PyBool_FromLong(!memcmp(str+start, suffix, slen));
2703 else
2704 return PyBool_FromLong(0);
Barry Warsaw226ae6c1999-10-12 19:54:53 +00002705}
2706
2707
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002708PyDoc_STRVAR(encode__doc__,
Marc-André Lemburg2d920412001-05-15 12:00:02 +00002709"S.encode([encoding[,errors]]) -> object\n\
Marc-André Lemburg63f3d172000-07-06 11:29:01 +00002710\n\
Marc-André Lemburg2d920412001-05-15 12:00:02 +00002711Encodes S using the codec registered for encoding. encoding defaults\n\
2712to the default encoding. errors may be given to set a different error\n\
Marc-André Lemburg63f3d172000-07-06 11:29:01 +00002713handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002714a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
2715'xmlcharrefreplace' as well as any other name registered with\n\
2716codecs.register_error that is able to handle UnicodeEncodeErrors.");
Marc-André Lemburg63f3d172000-07-06 11:29:01 +00002717
2718static PyObject *
2719string_encode(PyStringObject *self, PyObject *args)
2720{
2721 char *encoding = NULL;
2722 char *errors = NULL;
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002723 PyObject *v;
Tim Petersae1d0c92006-03-17 03:29:34 +00002724
Marc-André Lemburg63f3d172000-07-06 11:29:01 +00002725 if (!PyArg_ParseTuple(args, "|ss:encode", &encoding, &errors))
2726 return NULL;
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002727 v = PyString_AsEncodedObject((PyObject *)self, encoding, errors);
Marc-André Lemburg1dffb122004-07-08 19:13:55 +00002728 if (v == NULL)
2729 goto onError;
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002730 if (!PyString_Check(v) && !PyUnicode_Check(v)) {
2731 PyErr_Format(PyExc_TypeError,
2732 "encoder did not return a string/unicode object "
2733 "(type=%.400s)",
2734 v->ob_type->tp_name);
2735 Py_DECREF(v);
2736 return NULL;
2737 }
2738 return v;
Marc-André Lemburg1dffb122004-07-08 19:13:55 +00002739
2740 onError:
2741 return NULL;
Marc-André Lemburg2d920412001-05-15 12:00:02 +00002742}
2743
2744
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002745PyDoc_STRVAR(decode__doc__,
Marc-André Lemburg2d920412001-05-15 12:00:02 +00002746"S.decode([encoding[,errors]]) -> object\n\
2747\n\
2748Decodes S using the codec registered for encoding. encoding defaults\n\
2749to the default encoding. errors may be given to set a different error\n\
2750handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002751a UnicodeDecodeError. Other possible values are 'ignore' and 'replace'\n\
2752as well as any other name registerd with codecs.register_error that is\n\
2753able to handle UnicodeDecodeErrors.");
Marc-André Lemburg2d920412001-05-15 12:00:02 +00002754
2755static PyObject *
2756string_decode(PyStringObject *self, PyObject *args)
2757{
2758 char *encoding = NULL;
2759 char *errors = NULL;
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002760 PyObject *v;
Tim Petersae1d0c92006-03-17 03:29:34 +00002761
Marc-André Lemburg2d920412001-05-15 12:00:02 +00002762 if (!PyArg_ParseTuple(args, "|ss:decode", &encoding, &errors))
2763 return NULL;
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002764 v = PyString_AsDecodedObject((PyObject *)self, encoding, errors);
Marc-André Lemburg1dffb122004-07-08 19:13:55 +00002765 if (v == NULL)
2766 goto onError;
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002767 if (!PyString_Check(v) && !PyUnicode_Check(v)) {
2768 PyErr_Format(PyExc_TypeError,
2769 "decoder did not return a string/unicode object "
2770 "(type=%.400s)",
2771 v->ob_type->tp_name);
2772 Py_DECREF(v);
2773 return NULL;
2774 }
2775 return v;
Marc-André Lemburg1dffb122004-07-08 19:13:55 +00002776
2777 onError:
2778 return NULL;
Marc-André Lemburg63f3d172000-07-06 11:29:01 +00002779}
2780
2781
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002782PyDoc_STRVAR(expandtabs__doc__,
Guido van Rossum4c08d552000-03-10 22:55:18 +00002783"S.expandtabs([tabsize]) -> string\n\
2784\n\
2785Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002786If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossum4c08d552000-03-10 22:55:18 +00002787
2788static PyObject*
2789string_expandtabs(PyStringObject *self, PyObject *args)
2790{
2791 const char *e, *p;
2792 char *q;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002793 Py_ssize_t i, j;
Guido van Rossum4c08d552000-03-10 22:55:18 +00002794 PyObject *u;
2795 int tabsize = 8;
2796
2797 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
2798 return NULL;
2799
Thomas Wouters7e474022000-07-16 12:04:32 +00002800 /* First pass: determine size of output string */
Guido van Rossum4c08d552000-03-10 22:55:18 +00002801 i = j = 0;
2802 e = PyString_AS_STRING(self) + PyString_GET_SIZE(self);
2803 for (p = PyString_AS_STRING(self); p < e; p++)
2804 if (*p == '\t') {
2805 if (tabsize > 0)
2806 j += tabsize - (j % tabsize);
2807 }
2808 else {
2809 j++;
2810 if (*p == '\n' || *p == '\r') {
2811 i += j;
2812 j = 0;
2813 }
2814 }
2815
2816 /* Second pass: create output string and fill it */
2817 u = PyString_FromStringAndSize(NULL, i + j);
2818 if (!u)
2819 return NULL;
2820
2821 j = 0;
2822 q = PyString_AS_STRING(u);
2823
2824 for (p = PyString_AS_STRING(self); p < e; p++)
2825 if (*p == '\t') {
2826 if (tabsize > 0) {
2827 i = tabsize - (j % tabsize);
2828 j += i;
2829 while (i--)
2830 *q++ = ' ';
2831 }
2832 }
2833 else {
2834 j++;
2835 *q++ = *p;
2836 if (*p == '\n' || *p == '\r')
2837 j = 0;
2838 }
2839
2840 return u;
2841}
2842
Tim Peters8fa5dd02001-09-12 02:18:30 +00002843static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00002844pad(PyStringObject *self, Py_ssize_t left, Py_ssize_t right, char fill)
Guido van Rossum4c08d552000-03-10 22:55:18 +00002845{
2846 PyObject *u;
2847
2848 if (left < 0)
2849 left = 0;
2850 if (right < 0)
2851 right = 0;
2852
Tim Peters8fa5dd02001-09-12 02:18:30 +00002853 if (left == 0 && right == 0 && PyString_CheckExact(self)) {
Guido van Rossum4c08d552000-03-10 22:55:18 +00002854 Py_INCREF(self);
2855 return (PyObject *)self;
2856 }
2857
Tim Petersb3d8d1f2001-04-28 05:38:26 +00002858 u = PyString_FromStringAndSize(NULL,
Guido van Rossum4c08d552000-03-10 22:55:18 +00002859 left + PyString_GET_SIZE(self) + right);
2860 if (u) {
2861 if (left)
2862 memset(PyString_AS_STRING(u), fill, left);
Tim Petersb3d8d1f2001-04-28 05:38:26 +00002863 memcpy(PyString_AS_STRING(u) + left,
2864 PyString_AS_STRING(self),
Guido van Rossum4c08d552000-03-10 22:55:18 +00002865 PyString_GET_SIZE(self));
2866 if (right)
2867 memset(PyString_AS_STRING(u) + left + PyString_GET_SIZE(self),
2868 fill, right);
2869 }
2870
2871 return u;
2872}
2873
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002874PyDoc_STRVAR(ljust__doc__,
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00002875"S.ljust(width[, fillchar]) -> string\n"
Tim Peters8fa5dd02001-09-12 02:18:30 +00002876"\n"
2877"Return S left justified in a string of length width. Padding is\n"
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00002878"done using the specified fill character (default is a space).");
Guido van Rossum4c08d552000-03-10 22:55:18 +00002879
2880static PyObject *
2881string_ljust(PyStringObject *self, PyObject *args)
2882{
Thomas Wouters4abb3662006-04-19 14:50:15 +00002883 Py_ssize_t width;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00002884 char fillchar = ' ';
2885
Thomas Wouters4abb3662006-04-19 14:50:15 +00002886 if (!PyArg_ParseTuple(args, "n|c:ljust", &width, &fillchar))
Guido van Rossum4c08d552000-03-10 22:55:18 +00002887 return NULL;
2888
Tim Peters8fa5dd02001-09-12 02:18:30 +00002889 if (PyString_GET_SIZE(self) >= width && PyString_CheckExact(self)) {
Guido van Rossum4c08d552000-03-10 22:55:18 +00002890 Py_INCREF(self);
2891 return (PyObject*) self;
2892 }
2893
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00002894 return pad(self, 0, width - PyString_GET_SIZE(self), fillchar);
Guido van Rossum4c08d552000-03-10 22:55:18 +00002895}
2896
2897
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002898PyDoc_STRVAR(rjust__doc__,
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00002899"S.rjust(width[, fillchar]) -> string\n"
Tim Peters8fa5dd02001-09-12 02:18:30 +00002900"\n"
2901"Return S right justified in a string of length width. Padding is\n"
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00002902"done using the specified fill character (default is a space)");
Guido van Rossum4c08d552000-03-10 22:55:18 +00002903
2904static PyObject *
2905string_rjust(PyStringObject *self, PyObject *args)
2906{
Thomas Wouters4abb3662006-04-19 14:50:15 +00002907 Py_ssize_t width;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00002908 char fillchar = ' ';
2909
Thomas Wouters4abb3662006-04-19 14:50:15 +00002910 if (!PyArg_ParseTuple(args, "n|c:rjust", &width, &fillchar))
Guido van Rossum4c08d552000-03-10 22:55:18 +00002911 return NULL;
2912
Tim Peters8fa5dd02001-09-12 02:18:30 +00002913 if (PyString_GET_SIZE(self) >= width && PyString_CheckExact(self)) {
Guido van Rossum4c08d552000-03-10 22:55:18 +00002914 Py_INCREF(self);
2915 return (PyObject*) self;
2916 }
2917
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00002918 return pad(self, width - PyString_GET_SIZE(self), 0, fillchar);
Guido van Rossum4c08d552000-03-10 22:55:18 +00002919}
2920
2921
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002922PyDoc_STRVAR(center__doc__,
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00002923"S.center(width[, fillchar]) -> string\n"
Tim Peters8fa5dd02001-09-12 02:18:30 +00002924"\n"
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00002925"Return S centered in a string of length width. Padding is\n"
2926"done using the specified fill character (default is a space)");
Guido van Rossum4c08d552000-03-10 22:55:18 +00002927
2928static PyObject *
2929string_center(PyStringObject *self, PyObject *args)
2930{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002931 Py_ssize_t marg, left;
Thomas Wouters4abb3662006-04-19 14:50:15 +00002932 Py_ssize_t width;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00002933 char fillchar = ' ';
Guido van Rossum4c08d552000-03-10 22:55:18 +00002934
Thomas Wouters4abb3662006-04-19 14:50:15 +00002935 if (!PyArg_ParseTuple(args, "n|c:center", &width, &fillchar))
Guido van Rossum4c08d552000-03-10 22:55:18 +00002936 return NULL;
2937
Tim Peters8fa5dd02001-09-12 02:18:30 +00002938 if (PyString_GET_SIZE(self) >= width && PyString_CheckExact(self)) {
Guido van Rossum4c08d552000-03-10 22:55:18 +00002939 Py_INCREF(self);
2940 return (PyObject*) self;
2941 }
2942
2943 marg = width - PyString_GET_SIZE(self);
2944 left = marg / 2 + (marg & width & 1);
2945
Raymond Hettinger4f8f9762003-11-26 08:21:35 +00002946 return pad(self, left, marg - left, fillchar);
Guido van Rossum4c08d552000-03-10 22:55:18 +00002947}
2948
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002949PyDoc_STRVAR(zfill__doc__,
Walter Dörwald068325e2002-04-15 13:36:47 +00002950"S.zfill(width) -> string\n"
2951"\n"
2952"Pad a numeric string S with zeros on the left, to fill a field\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002953"of the specified width. The string S is never truncated.");
Walter Dörwald068325e2002-04-15 13:36:47 +00002954
2955static PyObject *
2956string_zfill(PyStringObject *self, PyObject *args)
2957{
Martin v. Löwiseb079f12006-02-16 14:32:27 +00002958 Py_ssize_t fill;
Walter Dörwald068325e2002-04-15 13:36:47 +00002959 PyObject *s;
Guido van Rossum3aa3fc42002-04-15 13:48:52 +00002960 char *p;
Thomas Wouters4abb3662006-04-19 14:50:15 +00002961 Py_ssize_t width;
Walter Dörwald068325e2002-04-15 13:36:47 +00002962
Thomas Wouters4abb3662006-04-19 14:50:15 +00002963 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Walter Dörwald068325e2002-04-15 13:36:47 +00002964 return NULL;
2965
2966 if (PyString_GET_SIZE(self) >= width) {
Walter Dörwald0fe940c2002-04-15 18:42:15 +00002967 if (PyString_CheckExact(self)) {
2968 Py_INCREF(self);
2969 return (PyObject*) self;
2970 }
2971 else
2972 return PyString_FromStringAndSize(
2973 PyString_AS_STRING(self),
2974 PyString_GET_SIZE(self)
2975 );
Walter Dörwald068325e2002-04-15 13:36:47 +00002976 }
2977
2978 fill = width - PyString_GET_SIZE(self);
2979
2980 s = pad(self, fill, 0, '0');
2981
2982 if (s == NULL)
2983 return NULL;
2984
2985 p = PyString_AS_STRING(s);
2986 if (p[fill] == '+' || p[fill] == '-') {
2987 /* move sign to beginning of string */
2988 p[0] = p[fill];
2989 p[fill] = '0';
2990 }
2991
2992 return (PyObject*) s;
2993}
2994
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002995PyDoc_STRVAR(isspace__doc__,
Martin v. Löwis6828e182003-10-18 09:55:08 +00002996"S.isspace() -> bool\n\
2997\n\
2998Return True if all characters in S are whitespace\n\
2999and there is at least one character in S, False otherwise.");
Guido van Rossum4c08d552000-03-10 22:55:18 +00003000
3001static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00003002string_isspace(PyStringObject *self)
Guido van Rossum4c08d552000-03-10 22:55:18 +00003003{
Fred Drakeba096332000-07-09 07:04:36 +00003004 register const unsigned char *p
3005 = (unsigned char *) PyString_AS_STRING(self);
Guido van Rossumb8f820c2000-05-05 20:44:24 +00003006 register const unsigned char *e;
Guido van Rossum4c08d552000-03-10 22:55:18 +00003007
Guido van Rossum4c08d552000-03-10 22:55:18 +00003008 /* Shortcut for single character strings */
3009 if (PyString_GET_SIZE(self) == 1 &&
3010 isspace(*p))
Guido van Rossum77f6a652002-04-03 22:41:51 +00003011 return PyBool_FromLong(1);
Guido van Rossum4c08d552000-03-10 22:55:18 +00003012
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00003013 /* Special case for empty strings */
3014 if (PyString_GET_SIZE(self) == 0)
Guido van Rossum77f6a652002-04-03 22:41:51 +00003015 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00003016
Guido van Rossum4c08d552000-03-10 22:55:18 +00003017 e = p + PyString_GET_SIZE(self);
3018 for (; p < e; p++) {
3019 if (!isspace(*p))
Guido van Rossum77f6a652002-04-03 22:41:51 +00003020 return PyBool_FromLong(0);
Guido van Rossum4c08d552000-03-10 22:55:18 +00003021 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00003022 return PyBool_FromLong(1);
Guido van Rossum4c08d552000-03-10 22:55:18 +00003023}
3024
3025
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003026PyDoc_STRVAR(isalpha__doc__,
Guido van Rossum77f6a652002-04-03 22:41:51 +00003027"S.isalpha() -> bool\n\
Marc-André Lemburg4027f8f2000-07-05 09:47:46 +00003028\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00003029Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003030and there is at least one character in S, False otherwise.");
Marc-André Lemburg4027f8f2000-07-05 09:47:46 +00003031
3032static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00003033string_isalpha(PyStringObject *self)
Marc-André Lemburg4027f8f2000-07-05 09:47:46 +00003034{
Fred Drakeba096332000-07-09 07:04:36 +00003035 register const unsigned char *p
3036 = (unsigned char *) PyString_AS_STRING(self);
Marc-André Lemburg4027f8f2000-07-05 09:47:46 +00003037 register const unsigned char *e;
3038
Marc-André Lemburg4027f8f2000-07-05 09:47:46 +00003039 /* Shortcut for single character strings */
3040 if (PyString_GET_SIZE(self) == 1 &&
3041 isalpha(*p))
Guido van Rossum77f6a652002-04-03 22:41:51 +00003042 return PyBool_FromLong(1);
Marc-André Lemburg4027f8f2000-07-05 09:47:46 +00003043
3044 /* Special case for empty strings */
3045 if (PyString_GET_SIZE(self) == 0)
Guido van Rossum77f6a652002-04-03 22:41:51 +00003046 return PyBool_FromLong(0);
Marc-André Lemburg4027f8f2000-07-05 09:47:46 +00003047
3048 e = p + PyString_GET_SIZE(self);
3049 for (; p < e; p++) {
3050 if (!isalpha(*p))
Guido van Rossum77f6a652002-04-03 22:41:51 +00003051 return PyBool_FromLong(0);
Marc-André Lemburg4027f8f2000-07-05 09:47:46 +00003052 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00003053 return PyBool_FromLong(1);
Marc-André Lemburg4027f8f2000-07-05 09:47:46 +00003054}
3055
3056
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003057PyDoc_STRVAR(isalnum__doc__,
Guido van Rossum77f6a652002-04-03 22:41:51 +00003058"S.isalnum() -> bool\n\
Marc-André Lemburg4027f8f2000-07-05 09:47:46 +00003059\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00003060Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003061and there is at least one character in S, False otherwise.");
Marc-André Lemburg4027f8f2000-07-05 09:47:46 +00003062
3063static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00003064string_isalnum(PyStringObject *self)
Marc-André Lemburg4027f8f2000-07-05 09:47:46 +00003065{
Fred Drakeba096332000-07-09 07:04:36 +00003066 register const unsigned char *p
3067 = (unsigned char *) PyString_AS_STRING(self);
Marc-André Lemburg4027f8f2000-07-05 09:47:46 +00003068 register const unsigned char *e;
3069
Marc-André Lemburg4027f8f2000-07-05 09:47:46 +00003070 /* Shortcut for single character strings */
3071 if (PyString_GET_SIZE(self) == 1 &&
3072 isalnum(*p))
Guido van Rossum77f6a652002-04-03 22:41:51 +00003073 return PyBool_FromLong(1);
Marc-André Lemburg4027f8f2000-07-05 09:47:46 +00003074
3075 /* Special case for empty strings */
3076 if (PyString_GET_SIZE(self) == 0)
Guido van Rossum77f6a652002-04-03 22:41:51 +00003077 return PyBool_FromLong(0);
Marc-André Lemburg4027f8f2000-07-05 09:47:46 +00003078
3079 e = p + PyString_GET_SIZE(self);
3080 for (; p < e; p++) {
3081 if (!isalnum(*p))
Guido van Rossum77f6a652002-04-03 22:41:51 +00003082 return PyBool_FromLong(0);
Marc-André Lemburg4027f8f2000-07-05 09:47:46 +00003083 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00003084 return PyBool_FromLong(1);
Marc-André Lemburg4027f8f2000-07-05 09:47:46 +00003085}
3086
3087
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003088PyDoc_STRVAR(isdigit__doc__,
Guido van Rossum77f6a652002-04-03 22:41:51 +00003089"S.isdigit() -> bool\n\
Guido van Rossum4c08d552000-03-10 22:55:18 +00003090\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00003091Return True if all characters in S are digits\n\
3092and there is at least one character in S, False otherwise.");
Guido van Rossum4c08d552000-03-10 22:55:18 +00003093
3094static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00003095string_isdigit(PyStringObject *self)
Guido van Rossum4c08d552000-03-10 22:55:18 +00003096{
Fred Drakeba096332000-07-09 07:04:36 +00003097 register const unsigned char *p
3098 = (unsigned char *) PyString_AS_STRING(self);
Guido van Rossumb8f820c2000-05-05 20:44:24 +00003099 register const unsigned char *e;
Guido van Rossum4c08d552000-03-10 22:55:18 +00003100
Guido van Rossum4c08d552000-03-10 22:55:18 +00003101 /* Shortcut for single character strings */
3102 if (PyString_GET_SIZE(self) == 1 &&
3103 isdigit(*p))
Guido van Rossum77f6a652002-04-03 22:41:51 +00003104 return PyBool_FromLong(1);
Guido van Rossum4c08d552000-03-10 22:55:18 +00003105
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00003106 /* Special case for empty strings */
3107 if (PyString_GET_SIZE(self) == 0)
Guido van Rossum77f6a652002-04-03 22:41:51 +00003108 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00003109
Guido van Rossum4c08d552000-03-10 22:55:18 +00003110 e = p + PyString_GET_SIZE(self);
3111 for (; p < e; p++) {
3112 if (!isdigit(*p))
Guido van Rossum77f6a652002-04-03 22:41:51 +00003113 return PyBool_FromLong(0);
Guido van Rossum4c08d552000-03-10 22:55:18 +00003114 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00003115 return PyBool_FromLong(1);
Guido van Rossum4c08d552000-03-10 22:55:18 +00003116}
3117
3118
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003119PyDoc_STRVAR(islower__doc__,
Guido van Rossum77f6a652002-04-03 22:41:51 +00003120"S.islower() -> bool\n\
Guido van Rossum4c08d552000-03-10 22:55:18 +00003121\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +00003122Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003123at least one cased character in S, False otherwise.");
Guido van Rossum4c08d552000-03-10 22:55:18 +00003124
3125static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00003126string_islower(PyStringObject *self)
Guido van Rossum4c08d552000-03-10 22:55:18 +00003127{
Fred Drakeba096332000-07-09 07:04:36 +00003128 register const unsigned char *p
3129 = (unsigned char *) PyString_AS_STRING(self);
Guido van Rossumb8f820c2000-05-05 20:44:24 +00003130 register const unsigned char *e;
Guido van Rossum4c08d552000-03-10 22:55:18 +00003131 int cased;
3132
Guido van Rossum4c08d552000-03-10 22:55:18 +00003133 /* Shortcut for single character strings */
3134 if (PyString_GET_SIZE(self) == 1)
Guido van Rossum77f6a652002-04-03 22:41:51 +00003135 return PyBool_FromLong(islower(*p) != 0);
Guido van Rossum4c08d552000-03-10 22:55:18 +00003136
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00003137 /* Special case for empty strings */
3138 if (PyString_GET_SIZE(self) == 0)
Guido van Rossum77f6a652002-04-03 22:41:51 +00003139 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00003140
Guido van Rossum4c08d552000-03-10 22:55:18 +00003141 e = p + PyString_GET_SIZE(self);
3142 cased = 0;
3143 for (; p < e; p++) {
3144 if (isupper(*p))
Guido van Rossum77f6a652002-04-03 22:41:51 +00003145 return PyBool_FromLong(0);
Guido van Rossum4c08d552000-03-10 22:55:18 +00003146 else if (!cased && islower(*p))
3147 cased = 1;
3148 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00003149 return PyBool_FromLong(cased);
Guido van Rossum4c08d552000-03-10 22:55:18 +00003150}
3151
3152
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003153PyDoc_STRVAR(isupper__doc__,
Guido van Rossum77f6a652002-04-03 22:41:51 +00003154"S.isupper() -> bool\n\
Guido van Rossum4c08d552000-03-10 22:55:18 +00003155\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00003156Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003157at least one cased character in S, False otherwise.");
Guido van Rossum4c08d552000-03-10 22:55:18 +00003158
3159static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00003160string_isupper(PyStringObject *self)
Guido van Rossum4c08d552000-03-10 22:55:18 +00003161{
Fred Drakeba096332000-07-09 07:04:36 +00003162 register const unsigned char *p
3163 = (unsigned char *) PyString_AS_STRING(self);
Guido van Rossumb8f820c2000-05-05 20:44:24 +00003164 register const unsigned char *e;
Guido van Rossum4c08d552000-03-10 22:55:18 +00003165 int cased;
3166
Guido van Rossum4c08d552000-03-10 22:55:18 +00003167 /* Shortcut for single character strings */
3168 if (PyString_GET_SIZE(self) == 1)
Guido van Rossum77f6a652002-04-03 22:41:51 +00003169 return PyBool_FromLong(isupper(*p) != 0);
Guido van Rossum4c08d552000-03-10 22:55:18 +00003170
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00003171 /* Special case for empty strings */
3172 if (PyString_GET_SIZE(self) == 0)
Guido van Rossum77f6a652002-04-03 22:41:51 +00003173 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00003174
Guido van Rossum4c08d552000-03-10 22:55:18 +00003175 e = p + PyString_GET_SIZE(self);
3176 cased = 0;
3177 for (; p < e; p++) {
3178 if (islower(*p))
Guido van Rossum77f6a652002-04-03 22:41:51 +00003179 return PyBool_FromLong(0);
Guido van Rossum4c08d552000-03-10 22:55:18 +00003180 else if (!cased && isupper(*p))
3181 cased = 1;
3182 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00003183 return PyBool_FromLong(cased);
Guido van Rossum4c08d552000-03-10 22:55:18 +00003184}
3185
3186
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003187PyDoc_STRVAR(istitle__doc__,
Guido van Rossum77f6a652002-04-03 22:41:51 +00003188"S.istitle() -> bool\n\
Guido van Rossum4c08d552000-03-10 22:55:18 +00003189\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +00003190Return True if S is a titlecased string and there is at least one\n\
3191character in S, i.e. uppercase characters may only follow uncased\n\
3192characters and lowercase characters only cased ones. Return False\n\
3193otherwise.");
Guido van Rossum4c08d552000-03-10 22:55:18 +00003194
3195static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00003196string_istitle(PyStringObject *self, PyObject *uncased)
Guido van Rossum4c08d552000-03-10 22:55:18 +00003197{
Fred Drakeba096332000-07-09 07:04:36 +00003198 register const unsigned char *p
3199 = (unsigned char *) PyString_AS_STRING(self);
Guido van Rossumb8f820c2000-05-05 20:44:24 +00003200 register const unsigned char *e;
Guido van Rossum4c08d552000-03-10 22:55:18 +00003201 int cased, previous_is_cased;
3202
Guido van Rossum4c08d552000-03-10 22:55:18 +00003203 /* Shortcut for single character strings */
3204 if (PyString_GET_SIZE(self) == 1)
Guido van Rossum77f6a652002-04-03 22:41:51 +00003205 return PyBool_FromLong(isupper(*p) != 0);
Guido van Rossum4c08d552000-03-10 22:55:18 +00003206
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00003207 /* Special case for empty strings */
3208 if (PyString_GET_SIZE(self) == 0)
Guido van Rossum77f6a652002-04-03 22:41:51 +00003209 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +00003210
Guido van Rossum4c08d552000-03-10 22:55:18 +00003211 e = p + PyString_GET_SIZE(self);
3212 cased = 0;
3213 previous_is_cased = 0;
3214 for (; p < e; p++) {
Guido van Rossumb8f820c2000-05-05 20:44:24 +00003215 register const unsigned char ch = *p;
Guido van Rossum4c08d552000-03-10 22:55:18 +00003216
3217 if (isupper(ch)) {
3218 if (previous_is_cased)
Guido van Rossum77f6a652002-04-03 22:41:51 +00003219 return PyBool_FromLong(0);
Guido van Rossum4c08d552000-03-10 22:55:18 +00003220 previous_is_cased = 1;
3221 cased = 1;
3222 }
3223 else if (islower(ch)) {
3224 if (!previous_is_cased)
Guido van Rossum77f6a652002-04-03 22:41:51 +00003225 return PyBool_FromLong(0);
Guido van Rossum4c08d552000-03-10 22:55:18 +00003226 previous_is_cased = 1;
3227 cased = 1;
3228 }
3229 else
3230 previous_is_cased = 0;
3231 }
Guido van Rossum77f6a652002-04-03 22:41:51 +00003232 return PyBool_FromLong(cased);
Guido van Rossum4c08d552000-03-10 22:55:18 +00003233}
3234
3235
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003236PyDoc_STRVAR(splitlines__doc__,
Fred Drake2bae4fa2001-10-13 15:57:55 +00003237"S.splitlines([keepends]) -> list of strings\n\
Guido van Rossum4c08d552000-03-10 22:55:18 +00003238\n\
3239Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossumf0b7b042000-04-11 15:39:26 +00003240Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003241is given and true.");
Guido van Rossum4c08d552000-03-10 22:55:18 +00003242
Guido van Rossum4c08d552000-03-10 22:55:18 +00003243static PyObject*
3244string_splitlines(PyStringObject *self, PyObject *args)
3245{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003246 register Py_ssize_t i;
3247 register Py_ssize_t j;
3248 Py_ssize_t len;
Guido van Rossumf0b7b042000-04-11 15:39:26 +00003249 int keepends = 0;
Guido van Rossum4c08d552000-03-10 22:55:18 +00003250 PyObject *list;
3251 PyObject *str;
3252 char *data;
3253
Guido van Rossumf0b7b042000-04-11 15:39:26 +00003254 if (!PyArg_ParseTuple(args, "|i:splitlines", &keepends))
Guido van Rossum4c08d552000-03-10 22:55:18 +00003255 return NULL;
3256
3257 data = PyString_AS_STRING(self);
3258 len = PyString_GET_SIZE(self);
3259
Guido van Rossum4c08d552000-03-10 22:55:18 +00003260 list = PyList_New(0);
3261 if (!list)
3262 goto onError;
3263
3264 for (i = j = 0; i < len; ) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00003265 Py_ssize_t eol;
Guido van Rossumf0b7b042000-04-11 15:39:26 +00003266
Guido van Rossum4c08d552000-03-10 22:55:18 +00003267 /* Find a line and append it */
3268 while (i < len && data[i] != '\n' && data[i] != '\r')
3269 i++;
Guido van Rossum4c08d552000-03-10 22:55:18 +00003270
3271 /* Skip the line break reading CRLF as one line break */
Guido van Rossumf0b7b042000-04-11 15:39:26 +00003272 eol = i;
Guido van Rossum4c08d552000-03-10 22:55:18 +00003273 if (i < len) {
3274 if (data[i] == '\r' && i + 1 < len &&
3275 data[i+1] == '\n')
3276 i += 2;
3277 else
3278 i++;
Guido van Rossumf0b7b042000-04-11 15:39:26 +00003279 if (keepends)
3280 eol = i;
Guido van Rossum4c08d552000-03-10 22:55:18 +00003281 }
Guido van Rossumf0b7b042000-04-11 15:39:26 +00003282 SPLIT_APPEND(data, j, eol);
Guido van Rossum4c08d552000-03-10 22:55:18 +00003283 j = i;
3284 }
3285 if (j < len) {
3286 SPLIT_APPEND(data, j, len);
3287 }
3288
3289 return list;
3290
3291 onError:
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00003292 Py_XDECREF(list);
Guido van Rossum4c08d552000-03-10 22:55:18 +00003293 return NULL;
3294}
3295
3296#undef SPLIT_APPEND
3297
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003298static PyObject *
3299string_getnewargs(PyStringObject *v)
3300{
3301 return Py_BuildValue("(s#)", v->ob_sval, v->ob_size);
3302}
3303
Barry Warsaw226ae6c1999-10-12 19:54:53 +00003304
Tim Petersb3d8d1f2001-04-28 05:38:26 +00003305static PyMethodDef
Barry Warsaw226ae6c1999-10-12 19:54:53 +00003306string_methods[] = {
Guido van Rossum4c08d552000-03-10 22:55:18 +00003307 /* Counterparts of the obsolete stropmodule functions; except
3308 string.maketrans(). */
Guido van Rossum3aa3fc42002-04-15 13:48:52 +00003309 {"join", (PyCFunction)string_join, METH_O, join__doc__},
3310 {"split", (PyCFunction)string_split, METH_VARARGS, split__doc__},
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00003311 {"rsplit", (PyCFunction)string_rsplit, METH_VARARGS, rsplit__doc__},
Guido van Rossum3aa3fc42002-04-15 13:48:52 +00003312 {"lower", (PyCFunction)string_lower, METH_NOARGS, lower__doc__},
3313 {"upper", (PyCFunction)string_upper, METH_NOARGS, upper__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00003314 {"islower", (PyCFunction)string_islower, METH_NOARGS, islower__doc__},
3315 {"isupper", (PyCFunction)string_isupper, METH_NOARGS, isupper__doc__},
3316 {"isspace", (PyCFunction)string_isspace, METH_NOARGS, isspace__doc__},
3317 {"isdigit", (PyCFunction)string_isdigit, METH_NOARGS, isdigit__doc__},
3318 {"istitle", (PyCFunction)string_istitle, METH_NOARGS, istitle__doc__},
3319 {"isalpha", (PyCFunction)string_isalpha, METH_NOARGS, isalpha__doc__},
3320 {"isalnum", (PyCFunction)string_isalnum, METH_NOARGS, isalnum__doc__},
Guido van Rossum3aa3fc42002-04-15 13:48:52 +00003321 {"capitalize", (PyCFunction)string_capitalize, METH_NOARGS,
3322 capitalize__doc__},
3323 {"count", (PyCFunction)string_count, METH_VARARGS, count__doc__},
3324 {"endswith", (PyCFunction)string_endswith, METH_VARARGS,
3325 endswith__doc__},
3326 {"find", (PyCFunction)string_find, METH_VARARGS, find__doc__},
3327 {"index", (PyCFunction)string_index, METH_VARARGS, index__doc__},
3328 {"lstrip", (PyCFunction)string_lstrip, METH_VARARGS, lstrip__doc__},
3329 {"replace", (PyCFunction)string_replace, METH_VARARGS, replace__doc__},
3330 {"rfind", (PyCFunction)string_rfind, METH_VARARGS, rfind__doc__},
3331 {"rindex", (PyCFunction)string_rindex, METH_VARARGS, rindex__doc__},
3332 {"rstrip", (PyCFunction)string_rstrip, METH_VARARGS, rstrip__doc__},
3333 {"startswith", (PyCFunction)string_startswith, METH_VARARGS,
3334 startswith__doc__},
3335 {"strip", (PyCFunction)string_strip, METH_VARARGS, strip__doc__},
3336 {"swapcase", (PyCFunction)string_swapcase, METH_NOARGS,
3337 swapcase__doc__},
3338 {"translate", (PyCFunction)string_translate, METH_VARARGS,
3339 translate__doc__},
3340 {"title", (PyCFunction)string_title, METH_NOARGS, title__doc__},
3341 {"ljust", (PyCFunction)string_ljust, METH_VARARGS, ljust__doc__},
3342 {"rjust", (PyCFunction)string_rjust, METH_VARARGS, rjust__doc__},
3343 {"center", (PyCFunction)string_center, METH_VARARGS, center__doc__},
3344 {"zfill", (PyCFunction)string_zfill, METH_VARARGS, zfill__doc__},
3345 {"encode", (PyCFunction)string_encode, METH_VARARGS, encode__doc__},
3346 {"decode", (PyCFunction)string_decode, METH_VARARGS, decode__doc__},
3347 {"expandtabs", (PyCFunction)string_expandtabs, METH_VARARGS,
3348 expandtabs__doc__},
3349 {"splitlines", (PyCFunction)string_splitlines, METH_VARARGS,
3350 splitlines__doc__},
Guido van Rossum5d9113d2003-01-29 17:58:45 +00003351 {"__getnewargs__", (PyCFunction)string_getnewargs, METH_NOARGS},
Barry Warsaw226ae6c1999-10-12 19:54:53 +00003352 {NULL, NULL} /* sentinel */
3353};
3354
Jeremy Hylton938ace62002-07-17 16:30:39 +00003355static PyObject *
Guido van Rossumae960af2001-08-30 03:11:59 +00003356str_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
3357
Barry Warsaw226ae6c1999-10-12 19:54:53 +00003358static PyObject *
Tim Peters6d6c1a32001-08-02 04:15:00 +00003359string_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Barry Warsaw226ae6c1999-10-12 19:54:53 +00003360{
Tim Peters6d6c1a32001-08-02 04:15:00 +00003361 PyObject *x = NULL;
Martin v. Löwis15e62742006-02-27 16:46:16 +00003362 static char *kwlist[] = {"object", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00003363
Guido van Rossumae960af2001-08-30 03:11:59 +00003364 if (type != &PyString_Type)
3365 return str_subtype_new(type, args, kwds);
Tim Peters6d6c1a32001-08-02 04:15:00 +00003366 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:str", kwlist, &x))
3367 return NULL;
3368 if (x == NULL)
3369 return PyString_FromString("");
3370 return PyObject_Str(x);
Barry Warsaw226ae6c1999-10-12 19:54:53 +00003371}
3372
Guido van Rossumae960af2001-08-30 03:11:59 +00003373static PyObject *
3374str_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3375{
Tim Petersaf90b3e2001-09-12 05:18:58 +00003376 PyObject *tmp, *pnew;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003377 Py_ssize_t n;
Guido van Rossumae960af2001-08-30 03:11:59 +00003378
3379 assert(PyType_IsSubtype(type, &PyString_Type));
3380 tmp = string_new(&PyString_Type, args, kwds);
3381 if (tmp == NULL)
3382 return NULL;
Tim Peters5a49ade2001-09-11 01:41:59 +00003383 assert(PyString_CheckExact(tmp));
Tim Petersaf90b3e2001-09-12 05:18:58 +00003384 n = PyString_GET_SIZE(tmp);
3385 pnew = type->tp_alloc(type, n);
3386 if (pnew != NULL) {
3387 memcpy(PyString_AS_STRING(pnew), PyString_AS_STRING(tmp), n+1);
Tim Petersaf90b3e2001-09-12 05:18:58 +00003388 ((PyStringObject *)pnew)->ob_shash =
3389 ((PyStringObject *)tmp)->ob_shash;
Guido van Rossum45ec02a2002-08-19 21:43:18 +00003390 ((PyStringObject *)pnew)->ob_sstate = SSTATE_NOT_INTERNED;
Tim Petersaf90b3e2001-09-12 05:18:58 +00003391 }
Guido van Rossum29d55a32001-08-31 16:11:15 +00003392 Py_DECREF(tmp);
Tim Petersaf90b3e2001-09-12 05:18:58 +00003393 return pnew;
Guido van Rossumae960af2001-08-30 03:11:59 +00003394}
3395
Guido van Rossumcacfc072002-05-24 19:01:59 +00003396static PyObject *
3397basestring_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3398{
3399 PyErr_SetString(PyExc_TypeError,
Neal Norwitz32a7e7f2002-05-31 19:58:02 +00003400 "The basestring type cannot be instantiated");
Guido van Rossumcacfc072002-05-24 19:01:59 +00003401 return NULL;
3402}
3403
Neil Schemenauera6cd4e62002-11-18 16:09:38 +00003404static PyObject *
3405string_mod(PyObject *v, PyObject *w)
3406{
3407 if (!PyString_Check(v)) {
3408 Py_INCREF(Py_NotImplemented);
3409 return Py_NotImplemented;
3410 }
3411 return PyString_Format(v, w);
3412}
3413
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003414PyDoc_STRVAR(basestring_doc,
3415"Type basestring cannot be instantiated; it is the base for str and unicode.");
Guido van Rossumcacfc072002-05-24 19:01:59 +00003416
Neil Schemenauera6cd4e62002-11-18 16:09:38 +00003417static PyNumberMethods string_as_number = {
3418 0, /*nb_add*/
3419 0, /*nb_subtract*/
3420 0, /*nb_multiply*/
3421 0, /*nb_divide*/
3422 string_mod, /*nb_remainder*/
3423};
3424
3425
Guido van Rossumcacfc072002-05-24 19:01:59 +00003426PyTypeObject PyBaseString_Type = {
3427 PyObject_HEAD_INIT(&PyType_Type)
3428 0,
Neal Norwitz32a7e7f2002-05-31 19:58:02 +00003429 "basestring",
Guido van Rossumcacfc072002-05-24 19:01:59 +00003430 0,
3431 0,
3432 0, /* tp_dealloc */
3433 0, /* tp_print */
3434 0, /* tp_getattr */
3435 0, /* tp_setattr */
3436 0, /* tp_compare */
3437 0, /* tp_repr */
3438 0, /* tp_as_number */
3439 0, /* tp_as_sequence */
3440 0, /* tp_as_mapping */
3441 0, /* tp_hash */
3442 0, /* tp_call */
3443 0, /* tp_str */
3444 0, /* tp_getattro */
3445 0, /* tp_setattro */
3446 0, /* tp_as_buffer */
3447 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
3448 basestring_doc, /* tp_doc */
3449 0, /* tp_traverse */
3450 0, /* tp_clear */
3451 0, /* tp_richcompare */
3452 0, /* tp_weaklistoffset */
3453 0, /* tp_iter */
3454 0, /* tp_iternext */
3455 0, /* tp_methods */
3456 0, /* tp_members */
3457 0, /* tp_getset */
3458 &PyBaseObject_Type, /* tp_base */
3459 0, /* tp_dict */
3460 0, /* tp_descr_get */
3461 0, /* tp_descr_set */
3462 0, /* tp_dictoffset */
3463 0, /* tp_init */
3464 0, /* tp_alloc */
3465 basestring_new, /* tp_new */
3466 0, /* tp_free */
3467};
3468
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003469PyDoc_STRVAR(string_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00003470"str(object) -> string\n\
3471\n\
3472Return a nice string representation of the object.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003473If the argument is a string, the return value is the same object.");
Barry Warsaw226ae6c1999-10-12 19:54:53 +00003474
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003475PyTypeObject PyString_Type = {
3476 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003477 0,
Tim Peters6d6c1a32001-08-02 04:15:00 +00003478 "str",
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003479 sizeof(PyStringObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003480 sizeof(char),
Georg Brandl347b3002006-03-30 11:57:00 +00003481 string_dealloc, /* tp_dealloc */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003482 (printfunc)string_print, /* tp_print */
3483 0, /* tp_getattr */
3484 0, /* tp_setattr */
3485 0, /* tp_compare */
Georg Brandl347b3002006-03-30 11:57:00 +00003486 string_repr, /* tp_repr */
Neil Schemenauera6cd4e62002-11-18 16:09:38 +00003487 &string_as_number, /* tp_as_number */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003488 &string_as_sequence, /* tp_as_sequence */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00003489 &string_as_mapping, /* tp_as_mapping */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003490 (hashfunc)string_hash, /* tp_hash */
3491 0, /* tp_call */
Georg Brandl347b3002006-03-30 11:57:00 +00003492 string_str, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003493 PyObject_GenericGetAttr, /* tp_getattro */
3494 0, /* tp_setattro */
3495 &string_as_buffer, /* tp_as_buffer */
Tim Petersae1d0c92006-03-17 03:29:34 +00003496 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
Neil Schemenauera6cd4e62002-11-18 16:09:38 +00003497 Py_TPFLAGS_BASETYPE, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003498 string_doc, /* tp_doc */
3499 0, /* tp_traverse */
3500 0, /* tp_clear */
3501 (richcmpfunc)string_richcompare, /* tp_richcompare */
3502 0, /* tp_weaklistoffset */
3503 0, /* tp_iter */
3504 0, /* tp_iternext */
3505 string_methods, /* tp_methods */
3506 0, /* tp_members */
3507 0, /* tp_getset */
Guido van Rossumcacfc072002-05-24 19:01:59 +00003508 &PyBaseString_Type, /* tp_base */
Tim Peters6d6c1a32001-08-02 04:15:00 +00003509 0, /* tp_dict */
3510 0, /* tp_descr_get */
3511 0, /* tp_descr_set */
3512 0, /* tp_dictoffset */
3513 0, /* tp_init */
3514 0, /* tp_alloc */
3515 string_new, /* tp_new */
Neil Schemenauer510492e2002-04-12 03:05:19 +00003516 PyObject_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003517};
3518
3519void
Fred Drakeba096332000-07-09 07:04:36 +00003520PyString_Concat(register PyObject **pv, register PyObject *w)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003521{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003522 register PyObject *v;
Guido van Rossum013142a1994-08-30 08:19:36 +00003523 if (*pv == NULL)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003524 return;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003525 if (w == NULL || !PyString_Check(*pv)) {
3526 Py_DECREF(*pv);
Guido van Rossum013142a1994-08-30 08:19:36 +00003527 *pv = NULL;
3528 return;
3529 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003530 v = string_concat((PyStringObject *) *pv, w);
3531 Py_DECREF(*pv);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003532 *pv = v;
3533}
3534
Guido van Rossum013142a1994-08-30 08:19:36 +00003535void
Fred Drakeba096332000-07-09 07:04:36 +00003536PyString_ConcatAndDel(register PyObject **pv, register PyObject *w)
Guido van Rossum013142a1994-08-30 08:19:36 +00003537{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003538 PyString_Concat(pv, w);
3539 Py_XDECREF(w);
Guido van Rossum013142a1994-08-30 08:19:36 +00003540}
3541
3542
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003543/* The following function breaks the notion that strings are immutable:
3544 it changes the size of a string. We get away with this only if there
3545 is only one module referencing the object. You can also think of it
3546 as creating a new string object and destroying the old one, only
3547 more efficiently. In any case, don't use this if the string may
Tim Peters5de98422002-04-27 18:44:32 +00003548 already be known to some other part of the code...
3549 Note that if there's not enough memory to resize the string, the original
3550 string object at *pv is deallocated, *pv is set to NULL, an "out of
3551 memory" exception is set, and -1 is returned. Else (on success) 0 is
3552 returned, and the value in *pv may or may not be the same as on input.
3553 As always, an extra byte is allocated for a trailing \0 byte (newsize
3554 does *not* include that), and a trailing \0 byte is stored.
3555*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003556
3557int
Martin v. Löwis18e16552006-02-15 17:27:45 +00003558_PyString_Resize(PyObject **pv, Py_ssize_t newsize)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003559{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003560 register PyObject *v;
3561 register PyStringObject *sv;
Guido van Rossum921842f1990-11-18 17:30:23 +00003562 v = *pv;
Armin Rigo618fbf52004-08-07 20:58:32 +00003563 if (!PyString_Check(v) || v->ob_refcnt != 1 || newsize < 0 ||
3564 PyString_CHECK_INTERNED(v)) {
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003565 *pv = 0;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003566 Py_DECREF(v);
3567 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +00003568 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003569 }
Guido van Rossum921842f1990-11-18 17:30:23 +00003570 /* XXX UNREF/NEWREF interface should be more symmetrical */
Tim Peters34592512002-07-11 06:23:50 +00003571 _Py_DEC_REFTOTAL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003572 _Py_ForgetReference(v);
3573 *pv = (PyObject *)
Tim Peterse7c05322004-06-27 17:24:49 +00003574 PyObject_REALLOC((char *)v, sizeof(PyStringObject) + newsize);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003575 if (*pv == NULL) {
Neil Schemenauer510492e2002-04-12 03:05:19 +00003576 PyObject_Del(v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003577 PyErr_NoMemory();
Guido van Rossum2a9096b1990-10-21 22:15:08 +00003578 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003579 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003580 _Py_NewReference(*pv);
3581 sv = (PyStringObject *) *pv;
Guido van Rossum921842f1990-11-18 17:30:23 +00003582 sv->ob_size = newsize;
3583 sv->ob_sval[newsize] = '\0';
Raymond Hettinger561fbf12004-10-26 01:52:37 +00003584 sv->ob_shash = -1; /* invalidate cached hash value */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003585 return 0;
3586}
Guido van Rossume5372401993-03-16 12:15:04 +00003587
3588/* Helpers for formatstring */
3589
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003590static PyObject *
Thomas Wouters977485d2006-02-16 15:59:12 +00003591getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
Guido van Rossume5372401993-03-16 12:15:04 +00003592{
Thomas Wouters977485d2006-02-16 15:59:12 +00003593 Py_ssize_t argidx = *p_argidx;
Guido van Rossume5372401993-03-16 12:15:04 +00003594 if (argidx < arglen) {
3595 (*p_argidx)++;
3596 if (arglen < 0)
3597 return args;
3598 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003599 return PyTuple_GetItem(args, argidx);
Guido van Rossume5372401993-03-16 12:15:04 +00003600 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003601 PyErr_SetString(PyExc_TypeError,
3602 "not enough arguments for format string");
Guido van Rossume5372401993-03-16 12:15:04 +00003603 return NULL;
3604}
3605
Tim Peters38fd5b62000-09-21 05:43:11 +00003606/* Format codes
3607 * F_LJUST '-'
3608 * F_SIGN '+'
3609 * F_BLANK ' '
3610 * F_ALT '#'
3611 * F_ZERO '0'
3612 */
Guido van Rossume5372401993-03-16 12:15:04 +00003613#define F_LJUST (1<<0)
3614#define F_SIGN (1<<1)
3615#define F_BLANK (1<<2)
3616#define F_ALT (1<<3)
3617#define F_ZERO (1<<4)
3618
Guido van Rossuma04d47b1997-01-21 16:12:09 +00003619static int
Fred Drakeba096332000-07-09 07:04:36 +00003620formatfloat(char *buf, size_t buflen, int flags,
3621 int prec, int type, PyObject *v)
Guido van Rossume5372401993-03-16 12:15:04 +00003622{
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00003623 /* fmt = '%#.' + `prec` + `type`
3624 worst case length = 3 + 10 (len of INT_MAX) + 1 = 14 (use 20)*/
Guido van Rossume5372401993-03-16 12:15:04 +00003625 char fmt[20];
Guido van Rossume5372401993-03-16 12:15:04 +00003626 double x;
Neal Norwitz88fe4ff2002-07-28 16:44:23 +00003627 x = PyFloat_AsDouble(v);
3628 if (x == -1.0 && PyErr_Occurred()) {
3629 PyErr_SetString(PyExc_TypeError, "float argument required");
Guido van Rossuma04d47b1997-01-21 16:12:09 +00003630 return -1;
Neal Norwitz88fe4ff2002-07-28 16:44:23 +00003631 }
Guido van Rossume5372401993-03-16 12:15:04 +00003632 if (prec < 0)
3633 prec = 6;
Guido van Rossume5372401993-03-16 12:15:04 +00003634 if (type == 'f' && fabs(x)/1e25 >= 1e25)
3635 type = 'g';
Marc-André Lemburg79f57832002-12-29 19:44:06 +00003636 /* Worst case length calc to ensure no buffer overrun:
3637
3638 'g' formats:
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00003639 fmt = %#.<prec>g
3640 buf = '-' + [0-9]*prec + '.' + 'e+' + (longest exp
Tim Petersb3d8d1f2001-04-28 05:38:26 +00003641 for any double rep.)
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00003642 len = 1 + prec + 1 + 2 + 5 = 9 + prec
Marc-André Lemburg79f57832002-12-29 19:44:06 +00003643
3644 'f' formats:
3645 buf = '-' + [0-9]*x + '.' + [0-9]*prec (with x < 50)
3646 len = 1 + 50 + 1 + prec = 52 + prec
3647
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00003648 If prec=0 the effective precision is 1 (the leading digit is
Tim Petersae1d0c92006-03-17 03:29:34 +00003649 always given), therefore increase the length by one.
Marc-André Lemburg79f57832002-12-29 19:44:06 +00003650
3651 */
3652 if ((type == 'g' && buflen <= (size_t)10 + (size_t)prec) ||
3653 (type == 'f' && buflen <= (size_t)53 + (size_t)prec)) {
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00003654 PyErr_SetString(PyExc_OverflowError,
Fred Drake661ea262000-10-24 19:57:45 +00003655 "formatted float is too long (precision too large?)");
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00003656 return -1;
3657 }
Marc-André Lemburg79f57832002-12-29 19:44:06 +00003658 PyOS_snprintf(fmt, sizeof(fmt), "%%%s.%d%c",
3659 (flags&F_ALT) ? "#" : "",
3660 prec, type);
Martin v. Löwis737ea822004-06-08 18:52:54 +00003661 PyOS_ascii_formatd(buf, buflen, fmt, x);
Martin v. Löwis18e16552006-02-15 17:27:45 +00003662 return (int)strlen(buf);
Guido van Rossume5372401993-03-16 12:15:04 +00003663}
3664
Tim Peters38fd5b62000-09-21 05:43:11 +00003665/* _PyString_FormatLong emulates the format codes d, u, o, x and X, and
3666 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
3667 * Python's regular ints.
3668 * Return value: a new PyString*, or NULL if error.
3669 * . *pbuf is set to point into it,
3670 * *plen set to the # of chars following that.
3671 * Caller must decref it when done using pbuf.
3672 * The string starting at *pbuf is of the form
3673 * "-"? ("0x" | "0X")? digit+
3674 * "0x"/"0X" are present only for x and X conversions, with F_ALT
Tim Petersb3d8d1f2001-04-28 05:38:26 +00003675 * set in flags. The case of hex digits will be correct,
Tim Peters38fd5b62000-09-21 05:43:11 +00003676 * There will be at least prec digits, zero-filled on the left if
3677 * necessary to get that many.
3678 * val object to be converted
3679 * flags bitmask of format flags; only F_ALT is looked at
3680 * prec minimum number of digits; 0-fill on left if needed
3681 * type a character in [duoxX]; u acts the same as d
3682 *
3683 * CAUTION: o, x and X conversions on regular ints can never
3684 * produce a '-' sign, but can for Python's unbounded ints.
3685 */
3686PyObject*
3687_PyString_FormatLong(PyObject *val, int flags, int prec, int type,
3688 char **pbuf, int *plen)
3689{
3690 PyObject *result = NULL;
3691 char *buf;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003692 Py_ssize_t i;
Tim Peters38fd5b62000-09-21 05:43:11 +00003693 int sign; /* 1 if '-', else 0 */
3694 int len; /* number of characters */
Martin v. Löwis725507b2006-03-07 12:08:51 +00003695 Py_ssize_t llen;
Tim Peters38fd5b62000-09-21 05:43:11 +00003696 int numdigits; /* len == numnondigits + numdigits */
3697 int numnondigits = 0;
3698
3699 switch (type) {
3700 case 'd':
3701 case 'u':
3702 result = val->ob_type->tp_str(val);
3703 break;
3704 case 'o':
3705 result = val->ob_type->tp_as_number->nb_oct(val);
3706 break;
3707 case 'x':
3708 case 'X':
3709 numnondigits = 2;
3710 result = val->ob_type->tp_as_number->nb_hex(val);
3711 break;
3712 default:
3713 assert(!"'type' not in [duoxX]");
3714 }
3715 if (!result)
3716 return NULL;
3717
3718 /* To modify the string in-place, there can only be one reference. */
3719 if (result->ob_refcnt != 1) {
3720 PyErr_BadInternalCall();
3721 return NULL;
3722 }
3723 buf = PyString_AsString(result);
Martin v. Löwis725507b2006-03-07 12:08:51 +00003724 llen = PyString_Size(result);
Martin v. Löwis8ce358f2006-04-13 07:22:51 +00003725 if (llen > PY_SSIZE_T_MAX) {
Martin v. Löwis725507b2006-03-07 12:08:51 +00003726 PyErr_SetString(PyExc_ValueError, "string too large in _PyString_FormatLong");
3727 return NULL;
3728 }
3729 len = (int)llen;
Tim Peters38fd5b62000-09-21 05:43:11 +00003730 if (buf[len-1] == 'L') {
3731 --len;
3732 buf[len] = '\0';
3733 }
3734 sign = buf[0] == '-';
3735 numnondigits += sign;
3736 numdigits = len - numnondigits;
3737 assert(numdigits > 0);
3738
Tim Petersfff53252001-04-12 18:38:48 +00003739 /* Get rid of base marker unless F_ALT */
3740 if ((flags & F_ALT) == 0) {
Tim Peters38fd5b62000-09-21 05:43:11 +00003741 /* Need to skip 0x, 0X or 0. */
3742 int skipped = 0;
3743 switch (type) {
3744 case 'o':
3745 assert(buf[sign] == '0');
3746 /* If 0 is only digit, leave it alone. */
3747 if (numdigits > 1) {
3748 skipped = 1;
3749 --numdigits;
3750 }
3751 break;
3752 case 'x':
3753 case 'X':
3754 assert(buf[sign] == '0');
3755 assert(buf[sign + 1] == 'x');
3756 skipped = 2;
3757 numnondigits -= 2;
3758 break;
3759 }
3760 if (skipped) {
3761 buf += skipped;
3762 len -= skipped;
3763 if (sign)
3764 buf[0] = '-';
3765 }
3766 assert(len == numnondigits + numdigits);
3767 assert(numdigits > 0);
3768 }
3769
3770 /* Fill with leading zeroes to meet minimum width. */
3771 if (prec > numdigits) {
3772 PyObject *r1 = PyString_FromStringAndSize(NULL,
3773 numnondigits + prec);
3774 char *b1;
3775 if (!r1) {
3776 Py_DECREF(result);
3777 return NULL;
3778 }
3779 b1 = PyString_AS_STRING(r1);
3780 for (i = 0; i < numnondigits; ++i)
3781 *b1++ = *buf++;
3782 for (i = 0; i < prec - numdigits; i++)
3783 *b1++ = '0';
3784 for (i = 0; i < numdigits; i++)
3785 *b1++ = *buf++;
3786 *b1 = '\0';
3787 Py_DECREF(result);
3788 result = r1;
3789 buf = PyString_AS_STRING(result);
3790 len = numnondigits + prec;
3791 }
3792
3793 /* Fix up case for hex conversions. */
Raymond Hettinger3296e692005-06-29 23:29:56 +00003794 if (type == 'X') {
3795 /* Need to convert all lower case letters to upper case.
3796 and need to convert 0x to 0X (and -0x to -0X). */
Tim Peters38fd5b62000-09-21 05:43:11 +00003797 for (i = 0; i < len; i++)
Raymond Hettinger3296e692005-06-29 23:29:56 +00003798 if (buf[i] >= 'a' && buf[i] <= 'x')
3799 buf[i] -= 'a'-'A';
Tim Peters38fd5b62000-09-21 05:43:11 +00003800 }
3801 *pbuf = buf;
3802 *plen = len;
3803 return result;
3804}
3805
Guido van Rossuma04d47b1997-01-21 16:12:09 +00003806static int
Fred Drakeba096332000-07-09 07:04:36 +00003807formatint(char *buf, size_t buflen, int flags,
3808 int prec, int type, PyObject *v)
Guido van Rossume5372401993-03-16 12:15:04 +00003809{
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00003810 /* fmt = '%#.' + `prec` + 'l' + `type`
Tim Peters38fd5b62000-09-21 05:43:11 +00003811 worst case length = 3 + 19 (worst len of INT_MAX on 64-bit machine)
3812 + 1 + 1 = 24 */
3813 char fmt[64]; /* plenty big enough! */
Guido van Rossum6c9e1302003-11-29 23:52:13 +00003814 char *sign;
Guido van Rossume5372401993-03-16 12:15:04 +00003815 long x;
Andrew MacIntyre5e9c80d2002-02-28 11:38:24 +00003816
Neal Norwitz88fe4ff2002-07-28 16:44:23 +00003817 x = PyInt_AsLong(v);
3818 if (x == -1 && PyErr_Occurred()) {
3819 PyErr_SetString(PyExc_TypeError, "int argument required");
Guido van Rossuma04d47b1997-01-21 16:12:09 +00003820 return -1;
Neal Norwitz88fe4ff2002-07-28 16:44:23 +00003821 }
Guido van Rossum6c9e1302003-11-29 23:52:13 +00003822 if (x < 0 && type == 'u') {
3823 type = 'd';
Guido van Rossum078151d2002-08-11 04:24:12 +00003824 }
Guido van Rossum6c9e1302003-11-29 23:52:13 +00003825 if (x < 0 && (type == 'x' || type == 'X' || type == 'o'))
3826 sign = "-";
3827 else
3828 sign = "";
Guido van Rossume5372401993-03-16 12:15:04 +00003829 if (prec < 0)
3830 prec = 1;
Andrew MacIntyre5e9c80d2002-02-28 11:38:24 +00003831
3832 if ((flags & F_ALT) &&
3833 (type == 'x' || type == 'X')) {
Guido van Rossum3aa3fc42002-04-15 13:48:52 +00003834 /* When converting under %#x or %#X, there are a number
Andrew MacIntyre5e9c80d2002-02-28 11:38:24 +00003835 * of issues that cause pain:
3836 * - when 0 is being converted, the C standard leaves off
3837 * the '0x' or '0X', which is inconsistent with other
3838 * %#x/%#X conversions and inconsistent with Python's
3839 * hex() function
3840 * - there are platforms that violate the standard and
3841 * convert 0 with the '0x' or '0X'
3842 * (Metrowerks, Compaq Tru64)
3843 * - there are platforms that give '0x' when converting
Guido van Rossum3aa3fc42002-04-15 13:48:52 +00003844 * under %#X, but convert 0 in accordance with the
Andrew MacIntyre5e9c80d2002-02-28 11:38:24 +00003845 * standard (OS/2 EMX)
Guido van Rossum3aa3fc42002-04-15 13:48:52 +00003846 *
Andrew MacIntyre5e9c80d2002-02-28 11:38:24 +00003847 * We can achieve the desired consistency by inserting our
3848 * own '0x' or '0X' prefix, and substituting %x/%X in place
3849 * of %#x/%#X.
3850 *
3851 * Note that this is the same approach as used in
3852 * formatint() in unicodeobject.c
3853 */
Guido van Rossum6c9e1302003-11-29 23:52:13 +00003854 PyOS_snprintf(fmt, sizeof(fmt), "%s0%c%%.%dl%c",
3855 sign, type, prec, type);
Andrew MacIntyre5e9c80d2002-02-28 11:38:24 +00003856 }
3857 else {
Guido van Rossum6c9e1302003-11-29 23:52:13 +00003858 PyOS_snprintf(fmt, sizeof(fmt), "%s%%%s.%dl%c",
3859 sign, (flags&F_ALT) ? "#" : "",
Andrew MacIntyre5e9c80d2002-02-28 11:38:24 +00003860 prec, type);
3861 }
3862
Guido van Rossum6c9e1302003-11-29 23:52:13 +00003863 /* buf = '+'/'-'/'' + '0'/'0x'/'' + '[0-9]'*max(prec, len(x in octal))
3864 * worst case buf = '-0x' + [0-9]*prec, where prec >= 11
Andrew MacIntyre5e9c80d2002-02-28 11:38:24 +00003865 */
Guido van Rossum6c9e1302003-11-29 23:52:13 +00003866 if (buflen <= 14 || buflen <= (size_t)3 + (size_t)prec) {
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00003867 PyErr_SetString(PyExc_OverflowError,
Guido van Rossum3aa3fc42002-04-15 13:48:52 +00003868 "formatted integer is too long (precision too large?)");
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00003869 return -1;
3870 }
Guido van Rossum6c9e1302003-11-29 23:52:13 +00003871 if (sign[0])
3872 PyOS_snprintf(buf, buflen, fmt, -x);
3873 else
3874 PyOS_snprintf(buf, buflen, fmt, x);
Martin v. Löwis18e16552006-02-15 17:27:45 +00003875 return (int)strlen(buf);
Guido van Rossume5372401993-03-16 12:15:04 +00003876}
3877
Guido van Rossuma04d47b1997-01-21 16:12:09 +00003878static int
Fred Drakeba096332000-07-09 07:04:36 +00003879formatchar(char *buf, size_t buflen, PyObject *v)
Guido van Rossume5372401993-03-16 12:15:04 +00003880{
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00003881 /* presume that the buffer is at least 2 characters long */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003882 if (PyString_Check(v)) {
3883 if (!PyArg_Parse(v, "c;%c requires int or char", &buf[0]))
Guido van Rossuma04d47b1997-01-21 16:12:09 +00003884 return -1;
Guido van Rossume5372401993-03-16 12:15:04 +00003885 }
3886 else {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003887 if (!PyArg_Parse(v, "b;%c requires int or char", &buf[0]))
Guido van Rossuma04d47b1997-01-21 16:12:09 +00003888 return -1;
Guido van Rossume5372401993-03-16 12:15:04 +00003889 }
3890 buf[1] = '\0';
Guido van Rossuma04d47b1997-01-21 16:12:09 +00003891 return 1;
Guido van Rossume5372401993-03-16 12:15:04 +00003892}
3893
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00003894/* fmt%(v1,v2,...) is roughly equivalent to sprintf(fmt, v1, v2, ...)
3895
3896 FORMATBUFLEN is the length of the buffer in which the floats, ints, &
3897 chars are formatted. XXX This is a magic number. Each formatting
3898 routine does bounds checking to ensure no overflow, but a better
3899 solution may be to malloc a buffer of appropriate size for each
3900 format. For now, the current solution is sufficient.
3901*/
3902#define FORMATBUFLEN (size_t)120
Guido van Rossume5372401993-03-16 12:15:04 +00003903
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003904PyObject *
Fred Drakeba096332000-07-09 07:04:36 +00003905PyString_Format(PyObject *format, PyObject *args)
Guido van Rossume5372401993-03-16 12:15:04 +00003906{
3907 char *fmt, *res;
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003908 Py_ssize_t arglen, argidx;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003909 Py_ssize_t reslen, rescnt, fmtcnt;
Guido van Rossum993952b1996-05-21 22:44:20 +00003910 int args_owned = 0;
Martin v. Löwis339d0f72001-08-17 18:39:25 +00003911 PyObject *result, *orig_args;
3912#ifdef Py_USING_UNICODE
3913 PyObject *v, *w;
3914#endif
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003915 PyObject *dict = NULL;
3916 if (format == NULL || !PyString_Check(format) || args == NULL) {
3917 PyErr_BadInternalCall();
Guido van Rossume5372401993-03-16 12:15:04 +00003918 return NULL;
3919 }
Guido van Rossum90daa872000-04-10 13:47:21 +00003920 orig_args = args;
Jeremy Hylton7802a532001-12-06 15:18:48 +00003921 fmt = PyString_AS_STRING(format);
3922 fmtcnt = PyString_GET_SIZE(format);
Guido van Rossum6ac258d1993-05-12 08:24:20 +00003923 reslen = rescnt = fmtcnt + 100;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003924 result = PyString_FromStringAndSize((char *)NULL, reslen);
Guido van Rossume5372401993-03-16 12:15:04 +00003925 if (result == NULL)
3926 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003927 res = PyString_AsString(result);
3928 if (PyTuple_Check(args)) {
Jeremy Hylton7802a532001-12-06 15:18:48 +00003929 arglen = PyTuple_GET_SIZE(args);
Guido van Rossume5372401993-03-16 12:15:04 +00003930 argidx = 0;
3931 }
3932 else {
3933 arglen = -1;
3934 argidx = -2;
3935 }
Neal Norwitz80a1bf42002-11-12 23:01:12 +00003936 if (args->ob_type->tp_as_mapping && !PyTuple_Check(args) &&
3937 !PyObject_TypeCheck(args, &PyBaseString_Type))
Guido van Rossum013142a1994-08-30 08:19:36 +00003938 dict = args;
Guido van Rossume5372401993-03-16 12:15:04 +00003939 while (--fmtcnt >= 0) {
3940 if (*fmt != '%') {
3941 if (--rescnt < 0) {
Guido van Rossum6ac258d1993-05-12 08:24:20 +00003942 rescnt = fmtcnt + 100;
3943 reslen += rescnt;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003944 if (_PyString_Resize(&result, reslen) < 0)
Guido van Rossume5372401993-03-16 12:15:04 +00003945 return NULL;
Jeremy Hylton7802a532001-12-06 15:18:48 +00003946 res = PyString_AS_STRING(result)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003947 + reslen - rescnt;
Guido van Rossum013142a1994-08-30 08:19:36 +00003948 --rescnt;
Guido van Rossume5372401993-03-16 12:15:04 +00003949 }
3950 *res++ = *fmt++;
3951 }
3952 else {
3953 /* Got a format specifier */
3954 int flags = 0;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003955 Py_ssize_t width = -1;
Guido van Rossume5372401993-03-16 12:15:04 +00003956 int prec = -1;
Guido van Rossum6938a291993-11-11 14:51:57 +00003957 int c = '\0';
Guido van Rossume5372401993-03-16 12:15:04 +00003958 int fill;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003959 PyObject *v = NULL;
3960 PyObject *temp = NULL;
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00003961 char *pbuf;
Guido van Rossume5372401993-03-16 12:15:04 +00003962 int sign;
Martin v. Löwis725507b2006-03-07 12:08:51 +00003963 Py_ssize_t len;
Guido van Rossum3aa3fc42002-04-15 13:48:52 +00003964 char formatbuf[FORMATBUFLEN];
3965 /* For format{float,int,char}() */
Martin v. Löwis339d0f72001-08-17 18:39:25 +00003966#ifdef Py_USING_UNICODE
Guido van Rossum90daa872000-04-10 13:47:21 +00003967 char *fmt_start = fmt;
Martin v. Löwis725507b2006-03-07 12:08:51 +00003968 Py_ssize_t argidx_start = argidx;
Martin v. Löwis339d0f72001-08-17 18:39:25 +00003969#endif
Tim Petersb3d8d1f2001-04-28 05:38:26 +00003970
Guido van Rossumda9c2711996-12-05 21:58:58 +00003971 fmt++;
Guido van Rossum013142a1994-08-30 08:19:36 +00003972 if (*fmt == '(') {
3973 char *keystart;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003974 Py_ssize_t keylen;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003975 PyObject *key;
Guido van Rossum045e6881997-09-08 18:30:11 +00003976 int pcount = 1;
Guido van Rossum013142a1994-08-30 08:19:36 +00003977
3978 if (dict == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003979 PyErr_SetString(PyExc_TypeError,
Tim Petersb3d8d1f2001-04-28 05:38:26 +00003980 "format requires a mapping");
Guido van Rossum013142a1994-08-30 08:19:36 +00003981 goto error;
3982 }
3983 ++fmt;
3984 --fmtcnt;
3985 keystart = fmt;
Guido van Rossum045e6881997-09-08 18:30:11 +00003986 /* Skip over balanced parentheses */
3987 while (pcount > 0 && --fmtcnt >= 0) {
3988 if (*fmt == ')')
3989 --pcount;
3990 else if (*fmt == '(')
3991 ++pcount;
Guido van Rossum013142a1994-08-30 08:19:36 +00003992 fmt++;
Guido van Rossum045e6881997-09-08 18:30:11 +00003993 }
3994 keylen = fmt - keystart - 1;
3995 if (fmtcnt < 0 || pcount > 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003996 PyErr_SetString(PyExc_ValueError,
Guido van Rossum013142a1994-08-30 08:19:36 +00003997 "incomplete format key");
3998 goto error;
3999 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004000 key = PyString_FromStringAndSize(keystart,
4001 keylen);
Guido van Rossum013142a1994-08-30 08:19:36 +00004002 if (key == NULL)
4003 goto error;
Guido van Rossum993952b1996-05-21 22:44:20 +00004004 if (args_owned) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004005 Py_DECREF(args);
Guido van Rossum993952b1996-05-21 22:44:20 +00004006 args_owned = 0;
4007 }
4008 args = PyObject_GetItem(dict, key);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004009 Py_DECREF(key);
Guido van Rossum013142a1994-08-30 08:19:36 +00004010 if (args == NULL) {
4011 goto error;
4012 }
Guido van Rossum993952b1996-05-21 22:44:20 +00004013 args_owned = 1;
Guido van Rossum013142a1994-08-30 08:19:36 +00004014 arglen = -1;
4015 argidx = -2;
4016 }
Guido van Rossume5372401993-03-16 12:15:04 +00004017 while (--fmtcnt >= 0) {
4018 switch (c = *fmt++) {
4019 case '-': flags |= F_LJUST; continue;
4020 case '+': flags |= F_SIGN; continue;
4021 case ' ': flags |= F_BLANK; continue;
4022 case '#': flags |= F_ALT; continue;
4023 case '0': flags |= F_ZERO; continue;
4024 }
4025 break;
4026 }
4027 if (c == '*') {
4028 v = getnextarg(args, arglen, &argidx);
4029 if (v == NULL)
4030 goto error;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004031 if (!PyInt_Check(v)) {
4032 PyErr_SetString(PyExc_TypeError,
4033 "* wants int");
Guido van Rossume5372401993-03-16 12:15:04 +00004034 goto error;
4035 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004036 width = PyInt_AsLong(v);
Guido van Rossum98c9eba1999-06-07 15:12:32 +00004037 if (width < 0) {
4038 flags |= F_LJUST;
4039 width = -width;
4040 }
Guido van Rossume5372401993-03-16 12:15:04 +00004041 if (--fmtcnt >= 0)
4042 c = *fmt++;
4043 }
Guido van Rossum9fa2c111995-02-10 17:00:37 +00004044 else if (c >= 0 && isdigit(c)) {
Guido van Rossume5372401993-03-16 12:15:04 +00004045 width = c - '0';
4046 while (--fmtcnt >= 0) {
Guido van Rossum9fa2c111995-02-10 17:00:37 +00004047 c = Py_CHARMASK(*fmt++);
Guido van Rossume5372401993-03-16 12:15:04 +00004048 if (!isdigit(c))
4049 break;
4050 if ((width*10) / 10 != width) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004051 PyErr_SetString(
4052 PyExc_ValueError,
4053 "width too big");
Guido van Rossume5372401993-03-16 12:15:04 +00004054 goto error;
4055 }
4056 width = width*10 + (c - '0');
4057 }
4058 }
4059 if (c == '.') {
4060 prec = 0;
4061 if (--fmtcnt >= 0)
4062 c = *fmt++;
4063 if (c == '*') {
4064 v = getnextarg(args, arglen, &argidx);
4065 if (v == NULL)
4066 goto error;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004067 if (!PyInt_Check(v)) {
4068 PyErr_SetString(
4069 PyExc_TypeError,
4070 "* wants int");
Guido van Rossume5372401993-03-16 12:15:04 +00004071 goto error;
4072 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004073 prec = PyInt_AsLong(v);
Guido van Rossume5372401993-03-16 12:15:04 +00004074 if (prec < 0)
4075 prec = 0;
4076 if (--fmtcnt >= 0)
4077 c = *fmt++;
4078 }
Guido van Rossum9fa2c111995-02-10 17:00:37 +00004079 else if (c >= 0 && isdigit(c)) {
Guido van Rossume5372401993-03-16 12:15:04 +00004080 prec = c - '0';
4081 while (--fmtcnt >= 0) {
Guido van Rossum9fa2c111995-02-10 17:00:37 +00004082 c = Py_CHARMASK(*fmt++);
Guido van Rossume5372401993-03-16 12:15:04 +00004083 if (!isdigit(c))
4084 break;
4085 if ((prec*10) / 10 != prec) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004086 PyErr_SetString(
4087 PyExc_ValueError,
Guido van Rossume5372401993-03-16 12:15:04 +00004088 "prec too big");
4089 goto error;
4090 }
4091 prec = prec*10 + (c - '0');
4092 }
4093 }
4094 } /* prec */
4095 if (fmtcnt >= 0) {
4096 if (c == 'h' || c == 'l' || c == 'L') {
Guido van Rossume5372401993-03-16 12:15:04 +00004097 if (--fmtcnt >= 0)
4098 c = *fmt++;
4099 }
4100 }
4101 if (fmtcnt < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004102 PyErr_SetString(PyExc_ValueError,
4103 "incomplete format");
Guido van Rossume5372401993-03-16 12:15:04 +00004104 goto error;
4105 }
4106 if (c != '%') {
4107 v = getnextarg(args, arglen, &argidx);
4108 if (v == NULL)
4109 goto error;
4110 }
4111 sign = 0;
4112 fill = ' ';
4113 switch (c) {
4114 case '%':
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00004115 pbuf = "%";
Guido van Rossume5372401993-03-16 12:15:04 +00004116 len = 1;
4117 break;
4118 case 's':
Martin v. Löwis339d0f72001-08-17 18:39:25 +00004119#ifdef Py_USING_UNICODE
Neil Schemenauerab619232005-08-31 23:02:05 +00004120 if (PyUnicode_Check(v)) {
4121 fmt = fmt_start;
4122 argidx = argidx_start;
4123 goto unicode;
4124 }
Georg Brandld45014b2005-10-01 17:06:00 +00004125#endif
Neil Schemenauercf52c072005-08-12 17:34:58 +00004126 temp = _PyObject_Str(v);
Georg Brandld45014b2005-10-01 17:06:00 +00004127#ifdef Py_USING_UNICODE
Neil Schemenauercf52c072005-08-12 17:34:58 +00004128 if (temp != NULL && PyUnicode_Check(temp)) {
4129 Py_DECREF(temp);
Guido van Rossum90daa872000-04-10 13:47:21 +00004130 fmt = fmt_start;
Marc-André Lemburg542fe562001-05-02 14:21:53 +00004131 argidx = argidx_start;
Guido van Rossum90daa872000-04-10 13:47:21 +00004132 goto unicode;
4133 }
Martin v. Löwis339d0f72001-08-17 18:39:25 +00004134#endif
Guido van Rossumb00c07f2002-10-09 19:07:53 +00004135 /* Fall through */
Walter Dörwald9ff3f032003-06-18 14:17:01 +00004136 case 'r':
Neil Schemenauercf52c072005-08-12 17:34:58 +00004137 if (c == 'r')
Guido van Rossumf0b7b042000-04-11 15:39:26 +00004138 temp = PyObject_Repr(v);
Guido van Rossum013142a1994-08-30 08:19:36 +00004139 if (temp == NULL)
Guido van Rossume5372401993-03-16 12:15:04 +00004140 goto error;
Guido van Rossum4a0144c1998-06-09 15:08:41 +00004141 if (!PyString_Check(temp)) {
4142 PyErr_SetString(PyExc_TypeError,
Guido van Rossum8052f892002-10-09 19:14:30 +00004143 "%s argument has non-string str()");
Jeremy Hylton7802a532001-12-06 15:18:48 +00004144 Py_DECREF(temp);
Guido van Rossum4a0144c1998-06-09 15:08:41 +00004145 goto error;
4146 }
Jeremy Hylton7802a532001-12-06 15:18:48 +00004147 pbuf = PyString_AS_STRING(temp);
4148 len = PyString_GET_SIZE(temp);
Guido van Rossume5372401993-03-16 12:15:04 +00004149 if (prec >= 0 && len > prec)
4150 len = prec;
4151 break;
4152 case 'i':
4153 case 'd':
4154 case 'u':
4155 case 'o':
4156 case 'x':
4157 case 'X':
4158 if (c == 'i')
4159 c = 'd';
Tim Petersa3a3a032000-11-30 05:22:44 +00004160 if (PyLong_Check(v)) {
Martin v. Löwis725507b2006-03-07 12:08:51 +00004161 int ilen;
Tim Peters38fd5b62000-09-21 05:43:11 +00004162 temp = _PyString_FormatLong(v, flags,
Martin v. Löwis725507b2006-03-07 12:08:51 +00004163 prec, c, &pbuf, &ilen);
4164 len = ilen;
Tim Peters38fd5b62000-09-21 05:43:11 +00004165 if (!temp)
4166 goto error;
Tim Peters38fd5b62000-09-21 05:43:11 +00004167 sign = 1;
Guido van Rossum4acdc231997-01-29 06:00:24 +00004168 }
Tim Peters38fd5b62000-09-21 05:43:11 +00004169 else {
4170 pbuf = formatbuf;
Guido van Rossum3aa3fc42002-04-15 13:48:52 +00004171 len = formatint(pbuf,
4172 sizeof(formatbuf),
Tim Peters38fd5b62000-09-21 05:43:11 +00004173 flags, prec, c, v);
4174 if (len < 0)
4175 goto error;
Guido van Rossum6c9e1302003-11-29 23:52:13 +00004176 sign = 1;
Tim Peters38fd5b62000-09-21 05:43:11 +00004177 }
4178 if (flags & F_ZERO)
4179 fill = '0';
Guido van Rossume5372401993-03-16 12:15:04 +00004180 break;
4181 case 'e':
4182 case 'E':
4183 case 'f':
Raymond Hettinger9bfe5332003-08-27 04:55:52 +00004184 case 'F':
Guido van Rossume5372401993-03-16 12:15:04 +00004185 case 'g':
4186 case 'G':
Raymond Hettinger9bfe5332003-08-27 04:55:52 +00004187 if (c == 'F')
4188 c = 'f';
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00004189 pbuf = formatbuf;
Guido van Rossum3aa3fc42002-04-15 13:48:52 +00004190 len = formatfloat(pbuf, sizeof(formatbuf),
4191 flags, prec, c, v);
Guido van Rossuma04d47b1997-01-21 16:12:09 +00004192 if (len < 0)
Guido van Rossume5372401993-03-16 12:15:04 +00004193 goto error;
Guido van Rossume5372401993-03-16 12:15:04 +00004194 sign = 1;
Tim Peters38fd5b62000-09-21 05:43:11 +00004195 if (flags & F_ZERO)
Guido van Rossume5372401993-03-16 12:15:04 +00004196 fill = '0';
4197 break;
4198 case 'c':
Walter Dörwald43440a62003-03-31 18:07:50 +00004199#ifdef Py_USING_UNICODE
4200 if (PyUnicode_Check(v)) {
4201 fmt = fmt_start;
4202 argidx = argidx_start;
4203 goto unicode;
4204 }
4205#endif
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00004206 pbuf = formatbuf;
4207 len = formatchar(pbuf, sizeof(formatbuf), v);
Guido van Rossuma04d47b1997-01-21 16:12:09 +00004208 if (len < 0)
Guido van Rossume5372401993-03-16 12:15:04 +00004209 goto error;
Guido van Rossume5372401993-03-16 12:15:04 +00004210 break;
4211 default:
Guido van Rossum045e6881997-09-08 18:30:11 +00004212 PyErr_Format(PyExc_ValueError,
Andrew M. Kuchling6ca89172000-12-15 13:07:46 +00004213 "unsupported format character '%c' (0x%x) "
4214 "at index %i",
Guido van Rossumefc11882002-09-12 14:43:41 +00004215 c, c,
4216 (int)(fmt - 1 - PyString_AsString(format)));
Guido van Rossume5372401993-03-16 12:15:04 +00004217 goto error;
4218 }
4219 if (sign) {
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00004220 if (*pbuf == '-' || *pbuf == '+') {
4221 sign = *pbuf++;
Guido van Rossume5372401993-03-16 12:15:04 +00004222 len--;
4223 }
4224 else if (flags & F_SIGN)
4225 sign = '+';
4226 else if (flags & F_BLANK)
4227 sign = ' ';
4228 else
Tim Peters38fd5b62000-09-21 05:43:11 +00004229 sign = 0;
Guido van Rossume5372401993-03-16 12:15:04 +00004230 }
4231 if (width < len)
4232 width = len;
Guido van Rossum049cd6b2002-10-11 00:43:48 +00004233 if (rescnt - (sign != 0) < width) {
Guido van Rossum6ac258d1993-05-12 08:24:20 +00004234 reslen -= rescnt;
4235 rescnt = width + fmtcnt + 100;
4236 reslen += rescnt;
Guido van Rossum049cd6b2002-10-11 00:43:48 +00004237 if (reslen < 0) {
4238 Py_DECREF(result);
4239 return PyErr_NoMemory();
4240 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004241 if (_PyString_Resize(&result, reslen) < 0)
Guido van Rossume5372401993-03-16 12:15:04 +00004242 return NULL;
Jeremy Hylton7802a532001-12-06 15:18:48 +00004243 res = PyString_AS_STRING(result)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004244 + reslen - rescnt;
Guido van Rossume5372401993-03-16 12:15:04 +00004245 }
4246 if (sign) {
Guido van Rossum71e57d01993-11-11 15:03:51 +00004247 if (fill != ' ')
4248 *res++ = sign;
Guido van Rossume5372401993-03-16 12:15:04 +00004249 rescnt--;
4250 if (width > len)
4251 width--;
4252 }
Tim Peters38fd5b62000-09-21 05:43:11 +00004253 if ((flags & F_ALT) && (c == 'x' || c == 'X')) {
4254 assert(pbuf[0] == '0');
Tim Petersfff53252001-04-12 18:38:48 +00004255 assert(pbuf[1] == c);
4256 if (fill != ' ') {
4257 *res++ = *pbuf++;
4258 *res++ = *pbuf++;
Tim Peters38fd5b62000-09-21 05:43:11 +00004259 }
Tim Petersfff53252001-04-12 18:38:48 +00004260 rescnt -= 2;
4261 width -= 2;
4262 if (width < 0)
4263 width = 0;
4264 len -= 2;
Tim Peters38fd5b62000-09-21 05:43:11 +00004265 }
4266 if (width > len && !(flags & F_LJUST)) {
Guido van Rossume5372401993-03-16 12:15:04 +00004267 do {
4268 --rescnt;
4269 *res++ = fill;
4270 } while (--width > len);
4271 }
Tim Peters38fd5b62000-09-21 05:43:11 +00004272 if (fill == ' ') {
4273 if (sign)
4274 *res++ = sign;
4275 if ((flags & F_ALT) &&
Tim Petersfff53252001-04-12 18:38:48 +00004276 (c == 'x' || c == 'X')) {
4277 assert(pbuf[0] == '0');
4278 assert(pbuf[1] == c);
Tim Peters38fd5b62000-09-21 05:43:11 +00004279 *res++ = *pbuf++;
4280 *res++ = *pbuf++;
4281 }
4282 }
Marc-André Lemburgf28dd832000-06-30 10:29:57 +00004283 memcpy(res, pbuf, len);
Guido van Rossume5372401993-03-16 12:15:04 +00004284 res += len;
4285 rescnt -= len;
4286 while (--width >= len) {
4287 --rescnt;
4288 *res++ = ' ';
4289 }
Guido van Rossum9fa2c111995-02-10 17:00:37 +00004290 if (dict && (argidx < arglen) && c != '%') {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004291 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger0ebac972002-05-21 15:14:57 +00004292 "not all arguments converted during string formatting");
Guido van Rossum013142a1994-08-30 08:19:36 +00004293 goto error;
4294 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004295 Py_XDECREF(temp);
Guido van Rossume5372401993-03-16 12:15:04 +00004296 } /* '%' */
4297 } /* until end */
Guido van Rossumcaeaafc1995-02-27 10:13:23 +00004298 if (argidx < arglen && !dict) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004299 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger0ebac972002-05-21 15:14:57 +00004300 "not all arguments converted during string formatting");
Guido van Rossume5372401993-03-16 12:15:04 +00004301 goto error;
4302 }
Guido van Rossum1109fbc1998-04-10 22:16:39 +00004303 if (args_owned) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004304 Py_DECREF(args);
Guido van Rossum1109fbc1998-04-10 22:16:39 +00004305 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004306 _PyString_Resize(&result, reslen - rescnt);
Guido van Rossume5372401993-03-16 12:15:04 +00004307 return result;
Guido van Rossum90daa872000-04-10 13:47:21 +00004308
Martin v. Löwis339d0f72001-08-17 18:39:25 +00004309#ifdef Py_USING_UNICODE
Guido van Rossum90daa872000-04-10 13:47:21 +00004310 unicode:
4311 if (args_owned) {
4312 Py_DECREF(args);
4313 args_owned = 0;
4314 }
Marc-André Lemburg542fe562001-05-02 14:21:53 +00004315 /* Fiddle args right (remove the first argidx arguments) */
Guido van Rossum90daa872000-04-10 13:47:21 +00004316 if (PyTuple_Check(orig_args) && argidx > 0) {
4317 PyObject *v;
Martin v. Löwiseb079f12006-02-16 14:32:27 +00004318 Py_ssize_t n = PyTuple_GET_SIZE(orig_args) - argidx;
Guido van Rossum90daa872000-04-10 13:47:21 +00004319 v = PyTuple_New(n);
4320 if (v == NULL)
4321 goto error;
4322 while (--n >= 0) {
4323 PyObject *w = PyTuple_GET_ITEM(orig_args, n + argidx);
4324 Py_INCREF(w);
4325 PyTuple_SET_ITEM(v, n, w);
4326 }
4327 args = v;
4328 } else {
4329 Py_INCREF(orig_args);
4330 args = orig_args;
4331 }
Marc-André Lemburg53f3d4a2000-10-07 08:54:09 +00004332 args_owned = 1;
4333 /* Take what we have of the result and let the Unicode formatting
4334 function format the rest of the input. */
Guido van Rossum90daa872000-04-10 13:47:21 +00004335 rescnt = res - PyString_AS_STRING(result);
Marc-André Lemburg53f3d4a2000-10-07 08:54:09 +00004336 if (_PyString_Resize(&result, rescnt))
4337 goto error;
Guido van Rossum90daa872000-04-10 13:47:21 +00004338 fmtcnt = PyString_GET_SIZE(format) - \
4339 (fmt - PyString_AS_STRING(format));
Marc-André Lemburg53f3d4a2000-10-07 08:54:09 +00004340 format = PyUnicode_Decode(fmt, fmtcnt, NULL, NULL);
4341 if (format == NULL)
Guido van Rossum90daa872000-04-10 13:47:21 +00004342 goto error;
Marc-André Lemburg53f3d4a2000-10-07 08:54:09 +00004343 v = PyUnicode_Format(format, args);
Guido van Rossum90daa872000-04-10 13:47:21 +00004344 Py_DECREF(format);
Marc-André Lemburg53f3d4a2000-10-07 08:54:09 +00004345 if (v == NULL)
4346 goto error;
4347 /* Paste what we have (result) to what the Unicode formatting
4348 function returned (v) and return the result (or error) */
4349 w = PyUnicode_Concat(result, v);
4350 Py_DECREF(result);
4351 Py_DECREF(v);
Guido van Rossum90daa872000-04-10 13:47:21 +00004352 Py_DECREF(args);
Marc-André Lemburg53f3d4a2000-10-07 08:54:09 +00004353 return w;
Martin v. Löwis339d0f72001-08-17 18:39:25 +00004354#endif /* Py_USING_UNICODE */
Tim Petersb3d8d1f2001-04-28 05:38:26 +00004355
Guido van Rossume5372401993-03-16 12:15:04 +00004356 error:
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004357 Py_DECREF(result);
Guido van Rossum1109fbc1998-04-10 22:16:39 +00004358 if (args_owned) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004359 Py_DECREF(args);
Guido van Rossum1109fbc1998-04-10 22:16:39 +00004360 }
Guido van Rossume5372401993-03-16 12:15:04 +00004361 return NULL;
4362}
Guido van Rossum2a61e741997-01-18 07:55:05 +00004363
Guido van Rossum2a61e741997-01-18 07:55:05 +00004364void
Fred Drakeba096332000-07-09 07:04:36 +00004365PyString_InternInPlace(PyObject **p)
Guido van Rossum2a61e741997-01-18 07:55:05 +00004366{
4367 register PyStringObject *s = (PyStringObject *)(*p);
4368 PyObject *t;
4369 if (s == NULL || !PyString_Check(s))
4370 Py_FatalError("PyString_InternInPlace: strings only please!");
Jeremy Hylton4c989dd2004-08-07 19:20:05 +00004371 /* If it's a string subclass, we don't really know what putting
4372 it in the interned dict might do. */
4373 if (!PyString_CheckExact(s))
4374 return;
Guido van Rossum45ec02a2002-08-19 21:43:18 +00004375 if (PyString_CHECK_INTERNED(s))
Guido van Rossum2a61e741997-01-18 07:55:05 +00004376 return;
Guido van Rossum2a61e741997-01-18 07:55:05 +00004377 if (interned == NULL) {
4378 interned = PyDict_New();
Guido van Rossum45ec02a2002-08-19 21:43:18 +00004379 if (interned == NULL) {
4380 PyErr_Clear(); /* Don't leave an exception */
Guido van Rossum2a61e741997-01-18 07:55:05 +00004381 return;
Guido van Rossum45ec02a2002-08-19 21:43:18 +00004382 }
Guido van Rossum2a61e741997-01-18 07:55:05 +00004383 }
Jeremy Hylton4c989dd2004-08-07 19:20:05 +00004384 t = PyDict_GetItem(interned, (PyObject *)s);
4385 if (t) {
Guido van Rossum2a61e741997-01-18 07:55:05 +00004386 Py_INCREF(t);
Guido van Rossum45ec02a2002-08-19 21:43:18 +00004387 Py_DECREF(*p);
4388 *p = t;
Guido van Rossum2a61e741997-01-18 07:55:05 +00004389 return;
4390 }
Guido van Rossum45ec02a2002-08-19 21:43:18 +00004391
Armin Rigo79f7ad22004-08-07 19:27:39 +00004392 if (PyDict_SetItem(interned, (PyObject *)s, (PyObject *)s) < 0) {
Jeremy Hylton4c989dd2004-08-07 19:20:05 +00004393 PyErr_Clear();
Guido van Rossum45ec02a2002-08-19 21:43:18 +00004394 return;
4395 }
Jeremy Hylton4c989dd2004-08-07 19:20:05 +00004396 /* The two references in interned are not counted by refcnt.
4397 The string deallocator will take care of this */
Armin Rigo79f7ad22004-08-07 19:27:39 +00004398 s->ob_refcnt -= 2;
Jeremy Hylton4c989dd2004-08-07 19:20:05 +00004399 PyString_CHECK_INTERNED(s) = SSTATE_INTERNED_MORTAL;
Guido van Rossum2a61e741997-01-18 07:55:05 +00004400}
4401
Guido van Rossum45ec02a2002-08-19 21:43:18 +00004402void
4403PyString_InternImmortal(PyObject **p)
4404{
4405 PyString_InternInPlace(p);
4406 if (PyString_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
4407 PyString_CHECK_INTERNED(*p) = SSTATE_INTERNED_IMMORTAL;
4408 Py_INCREF(*p);
4409 }
4410}
4411
Guido van Rossum2a61e741997-01-18 07:55:05 +00004412
4413PyObject *
Fred Drakeba096332000-07-09 07:04:36 +00004414PyString_InternFromString(const char *cp)
Guido van Rossum2a61e741997-01-18 07:55:05 +00004415{
4416 PyObject *s = PyString_FromString(cp);
4417 if (s == NULL)
4418 return NULL;
4419 PyString_InternInPlace(&s);
4420 return s;
4421}
4422
Guido van Rossum8cf04761997-08-02 02:57:45 +00004423void
Fred Drakeba096332000-07-09 07:04:36 +00004424PyString_Fini(void)
Guido van Rossum8cf04761997-08-02 02:57:45 +00004425{
4426 int i;
Guido van Rossum8cf04761997-08-02 02:57:45 +00004427 for (i = 0; i < UCHAR_MAX + 1; i++) {
4428 Py_XDECREF(characters[i]);
4429 characters[i] = NULL;
4430 }
Guido van Rossum8cf04761997-08-02 02:57:45 +00004431 Py_XDECREF(nullstring);
4432 nullstring = NULL;
Guido van Rossum8cf04761997-08-02 02:57:45 +00004433}
Barry Warsawa903ad982001-02-23 16:40:48 +00004434
Barry Warsawa903ad982001-02-23 16:40:48 +00004435void _Py_ReleaseInternedStrings(void)
4436{
Guido van Rossum45ec02a2002-08-19 21:43:18 +00004437 PyObject *keys;
4438 PyStringObject *s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004439 Py_ssize_t i, n;
Guido van Rossum45ec02a2002-08-19 21:43:18 +00004440
4441 if (interned == NULL || !PyDict_Check(interned))
4442 return;
4443 keys = PyDict_Keys(interned);
4444 if (keys == NULL || !PyList_Check(keys)) {
4445 PyErr_Clear();
4446 return;
Barry Warsawa903ad982001-02-23 16:40:48 +00004447 }
Guido van Rossum45ec02a2002-08-19 21:43:18 +00004448
4449 /* Since _Py_ReleaseInternedStrings() is intended to help a leak
4450 detector, interned strings are not forcibly deallocated; rather, we
4451 give them their stolen references back, and then clear and DECREF
4452 the interned dict. */
Tim Petersae1d0c92006-03-17 03:29:34 +00004453
Guido van Rossum45ec02a2002-08-19 21:43:18 +00004454 fprintf(stderr, "releasing interned strings\n");
4455 n = PyList_GET_SIZE(keys);
4456 for (i = 0; i < n; i++) {
4457 s = (PyStringObject *) PyList_GET_ITEM(keys, i);
4458 switch (s->ob_sstate) {
4459 case SSTATE_NOT_INTERNED:
4460 /* XXX Shouldn't happen */
4461 break;
4462 case SSTATE_INTERNED_IMMORTAL:
4463 s->ob_refcnt += 1;
4464 break;
4465 case SSTATE_INTERNED_MORTAL:
4466 s->ob_refcnt += 2;
4467 break;
4468 default:
4469 Py_FatalError("Inconsistent interned string state.");
4470 }
4471 s->ob_sstate = SSTATE_NOT_INTERNED;
4472 }
4473 Py_DECREF(keys);
4474 PyDict_Clear(interned);
4475 Py_DECREF(interned);
4476 interned = NULL;
Barry Warsawa903ad982001-02-23 16:40:48 +00004477}