1 /* String object implementation */
3 #define PY_SSIZE_T_CLEAN
10 int null_strings
, one_strings
;
13 static PyStringObject
*characters
[UCHAR_MAX
+ 1];
14 static PyStringObject
*nullstring
;
16 /* This dictionary holds all interned strings. Note that references to
17 strings in this dictionary are *not* counted in the string's ob_refcnt.
18 When the interned string reaches a refcnt of 0 the string deallocation
19 function will delete the reference from this dictionary.
21 Another way to look at this is that to say that the actual reference
22 count of a string is: s->ob_refcnt + (s->ob_sstate?2:0)
24 static PyObject
*interned
;
27 For both PyString_FromString() and PyString_FromStringAndSize(), the
28 parameter `size' denotes number of characters to allocate, not counting any
29 null terminating character.
31 For PyString_FromString(), the parameter `str' points to a null-terminated
32 string containing exactly `size' bytes.
34 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.
45 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()).
53 PyString_FromStringAndSize(const char *str
, Py_ssize_t size
)
55 register PyStringObject
*op
;
57 if (size
== 0 && (op
= nullstring
) != NULL
) {
62 return (PyObject
*)op
;
64 if (size
== 1 && str
!= NULL
&&
65 (op
= characters
[*str
& UCHAR_MAX
]) != NULL
)
71 return (PyObject
*)op
;
74 /* Inline PyObject_NewVar */
75 op
= (PyStringObject
*)PyObject_MALLOC(sizeof(PyStringObject
) + size
);
77 return PyErr_NoMemory();
78 PyObject_INIT_VAR(op
, &PyString_Type
, size
);
80 op
->ob_sstate
= SSTATE_NOT_INTERNED
;
82 Py_MEMCPY(op
->ob_sval
, str
, size
);
83 op
->ob_sval
[size
] = '\0';
84 /* share short strings */
86 PyObject
*t
= (PyObject
*)op
;
87 PyString_InternInPlace(&t
);
88 op
= (PyStringObject
*)t
;
91 } else if (size
== 1 && str
!= NULL
) {
92 PyObject
*t
= (PyObject
*)op
;
93 PyString_InternInPlace(&t
);
94 op
= (PyStringObject
*)t
;
95 characters
[*str
& UCHAR_MAX
] = op
;
98 return (PyObject
*) op
;
102 PyString_FromString(const char *str
)
104 register size_t size
;
105 register PyStringObject
*op
;
109 if (size
> PY_SSIZE_T_MAX
) {
110 PyErr_SetString(PyExc_OverflowError
,
111 "string is too long for a Python string");
114 if (size
== 0 && (op
= nullstring
) != NULL
) {
119 return (PyObject
*)op
;
121 if (size
== 1 && (op
= characters
[*str
& UCHAR_MAX
]) != NULL
) {
126 return (PyObject
*)op
;
129 /* Inline PyObject_NewVar */
130 op
= (PyStringObject
*)PyObject_MALLOC(sizeof(PyStringObject
) + size
);
132 return PyErr_NoMemory();
133 PyObject_INIT_VAR(op
, &PyString_Type
, size
);
135 op
->ob_sstate
= SSTATE_NOT_INTERNED
;
136 Py_MEMCPY(op
->ob_sval
, str
, size
+1);
137 /* share short strings */
139 PyObject
*t
= (PyObject
*)op
;
140 PyString_InternInPlace(&t
);
141 op
= (PyStringObject
*)t
;
144 } else if (size
== 1) {
145 PyObject
*t
= (PyObject
*)op
;
146 PyString_InternInPlace(&t
);
147 op
= (PyStringObject
*)t
;
148 characters
[*str
& UCHAR_MAX
] = op
;
151 return (PyObject
*) op
;
155 PyString_FromFormatV(const char *format
, va_list vargs
)
163 #ifdef VA_LIST_IS_ARRAY
164 Py_MEMCPY(count
, vargs
, sizeof(va_list));
167 __va_copy(count
, vargs
);
172 /* step 1: figure out how large a buffer we need */
173 for (f
= format
; *f
; f
++) {
176 while (*++f
&& *f
!= '%' && !isalpha(Py_CHARMASK(*f
)))
179 /* skip the 'l' or 'z' in {%ld, %zd, %lu, %zu} since
180 * they don't affect the amount of space we reserve.
182 if ((*f
== 'l' || *f
== 'z') &&
183 (f
[1] == 'd' || f
[1] == 'u'))
188 (void)va_arg(count
, int);
189 /* fall through... */
193 case 'd': case 'u': case 'i': case 'x':
194 (void) va_arg(count
, int);
195 /* 20 bytes is enough to hold a 64-bit
196 integer. Decimal takes the most space.
197 This isn't enough for octal. */
201 s
= va_arg(count
, char*);
205 (void) va_arg(count
, int);
206 /* maximum 64-bit pointer representation:
208 * so 19 characters is enough.
209 * XXX I count 18 -- what's the extra for?
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
219 what's in the argument list) */
227 /* step 2: fill the buffer */
228 /* Since we've analyzed how much space we need for the worst case,
229 use sprintf directly instead of the slower PyOS_snprintf. */
230 string
= PyString_FromStringAndSize(NULL
, n
);
234 s
= PyString_AsString(string
);
236 for (f
= format
; *f
; f
++) {
242 /* parse the width.precision part (we're only
243 interested in the precision value, if any) */
245 while (isdigit(Py_CHARMASK(*f
)))
246 n
= (n
*10) + *f
++ - '0';
250 while (isdigit(Py_CHARMASK(*f
)))
251 n
= (n
*10) + *f
++ - '0';
253 while (*f
&& *f
!= '%' && !isalpha(Py_CHARMASK(*f
)))
255 /* 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')) {
261 /* handle the size_t flag. */
262 if (*f
== 'z' && (f
[1] == 'd' || f
[1] == 'u')) {
269 *s
++ = va_arg(vargs
, int);
273 sprintf(s
, "%ld", va_arg(vargs
, long));
275 sprintf(s
, "%" PY_FORMAT_SIZE_T
"d",
276 va_arg(vargs
, Py_ssize_t
));
278 sprintf(s
, "%d", va_arg(vargs
, int));
284 va_arg(vargs
, unsigned long));
286 sprintf(s
, "%" PY_FORMAT_SIZE_T
"u",
287 va_arg(vargs
, size_t));
290 va_arg(vargs
, unsigned int));
294 sprintf(s
, "%i", va_arg(vargs
, int));
298 sprintf(s
, "%x", va_arg(vargs
, int));
302 p
= va_arg(vargs
, char*);
310 sprintf(s
, "%p", va_arg(vargs
, void*));
311 /* %p is ill-defined: ensure leading 0x. */
314 else if (s
[1] != 'x') {
315 memmove(s
+2, s
, strlen(s
)+1);
334 _PyString_Resize(&string
, s
- PyString_AS_STRING(string
));
339 PyString_FromFormat(const char *format
, ...)
344 #ifdef HAVE_STDARG_PROTOTYPES
345 va_start(vargs
, format
);
349 ret
= PyString_FromFormatV(format
, vargs
);
355 PyObject
*PyString_Decode(const char *s
,
357 const char *encoding
,
362 str
= PyString_FromStringAndSize(s
, size
);
365 v
= PyString_AsDecodedString(str
, encoding
, errors
);
370 PyObject
*PyString_AsDecodedObject(PyObject
*str
,
371 const char *encoding
,
376 if (!PyString_Check(str
)) {
381 if (encoding
== NULL
) {
382 #ifdef Py_USING_UNICODE
383 encoding
= PyUnicode_GetDefaultEncoding();
385 PyErr_SetString(PyExc_ValueError
, "no encoding specified");
390 /* Decode via the codec registry */
391 v
= PyCodec_Decode(str
, encoding
, errors
);
401 PyObject
*PyString_AsDecodedString(PyObject
*str
,
402 const char *encoding
,
407 v
= PyString_AsDecodedObject(str
, encoding
, errors
);
411 #ifdef Py_USING_UNICODE
412 /* Convert Unicode to a string using the default encoding */
413 if (PyUnicode_Check(v
)) {
415 v
= PyUnicode_AsEncodedString(v
, NULL
, NULL
);
421 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
);
435 PyObject
*PyString_Encode(const char *s
,
437 const char *encoding
,
442 str
= PyString_FromStringAndSize(s
, size
);
445 v
= PyString_AsEncodedString(str
, encoding
, errors
);
450 PyObject
*PyString_AsEncodedObject(PyObject
*str
,
451 const char *encoding
,
456 if (!PyString_Check(str
)) {
461 if (encoding
== NULL
) {
462 #ifdef Py_USING_UNICODE
463 encoding
= PyUnicode_GetDefaultEncoding();
465 PyErr_SetString(PyExc_ValueError
, "no encoding specified");
470 /* Encode via the codec registry */
471 v
= PyCodec_Encode(str
, encoding
, errors
);
481 PyObject
*PyString_AsEncodedString(PyObject
*str
,
482 const char *encoding
,
487 v
= PyString_AsEncodedObject(str
, encoding
, errors
);
491 #ifdef Py_USING_UNICODE
492 /* Convert Unicode to a string using the default encoding */
493 if (PyUnicode_Check(v
)) {
495 v
= PyUnicode_AsEncodedString(v
, NULL
, NULL
);
501 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
);
516 string_dealloc(PyObject
*op
)
518 switch (PyString_CHECK_INTERNED(op
)) {
519 case SSTATE_NOT_INTERNED
:
522 case SSTATE_INTERNED_MORTAL
:
523 /* revive dead object temporarily for DelItem */
525 if (PyDict_DelItem(interned
, op
) != 0)
527 "deletion of interned string failed");
530 case SSTATE_INTERNED_IMMORTAL
:
531 Py_FatalError("Immortal interned string died.");
534 Py_FatalError("Inconsistent interned string state.");
536 op
->ob_type
->tp_free(op
);
539 /* 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. */
544 PyObject
*PyString_DecodeEscape(const char *s
,
548 const char *recode_encoding
)
554 Py_ssize_t newlen
= recode_encoding
? 4*len
:len
;
555 v
= PyString_FromStringAndSize((char *)NULL
, newlen
);
558 p
= buf
= PyString_AsString(v
);
563 #ifdef Py_USING_UNICODE
564 if (recode_encoding
&& (*s
& 0x80)) {
570 /* Decode non-ASCII bytes as UTF-8. */
571 while (t
< end
&& (*t
& 0x80)) t
++;
572 u
= PyUnicode_DecodeUTF8(s
, t
- s
, errors
);
575 /* Recode them in target encoding. */
576 w
= PyUnicode_AsEncodedString(
577 u
, recode_encoding
, errors
);
581 /* Append bytes to output buffer. */
582 assert(PyString_Check(w
));
583 r
= PyString_AS_STRING(w
);
584 rn
= PyString_GET_SIZE(w
);
599 PyErr_SetString(PyExc_ValueError
,
600 "Trailing \\ in string");
604 /* XXX This assumes ASCII! */
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':
619 if ('0' <= *s
&& *s
<= '7') {
620 c
= (c
<<3) + *s
++ - '0';
621 if ('0' <= *s
&& *s
<= '7')
622 c
= (c
<<3) + *s
++ - '0';
627 if (isxdigit(Py_CHARMASK(s
[0]))
628 && isxdigit(Py_CHARMASK(s
[1]))) {
650 if (!errors
|| strcmp(errors
, "strict") == 0) {
651 PyErr_SetString(PyExc_ValueError
,
652 "invalid \\x escape");
655 if (strcmp(errors
, "replace") == 0) {
657 } else if (strcmp(errors
, "ignore") == 0)
660 PyErr_Format(PyExc_ValueError
,
662 "unknown error handling code: %.400s",
666 #ifndef Py_USING_UNICODE
671 PyErr_SetString(PyExc_ValueError
,
672 "Unicode escapes not legal "
673 "when Unicode disabled");
680 goto non_esc
; /* an arbitry number of unescaped
681 UTF-8 bytes may follow. */
685 _PyString_Resize(&v
, p
- buf
);
692 /* -------------------------------------------------------------------- */
696 string_getsize(register PyObject
*op
)
700 if (PyString_AsStringAndSize(op
, &s
, &len
))
705 static /*const*/ char *
706 string_getbuffer(register PyObject
*op
)
710 if (PyString_AsStringAndSize(op
, &s
, &len
))
716 PyString_Size(register PyObject
*op
)
718 if (!PyString_Check(op
))
719 return string_getsize(op
);
720 return ((PyStringObject
*)op
) -> ob_size
;
724 PyString_AsString(register PyObject
*op
)
726 if (!PyString_Check(op
))
727 return string_getbuffer(op
);
728 return ((PyStringObject
*)op
) -> ob_sval
;
732 PyString_AsStringAndSize(register PyObject
*obj
,
734 register Py_ssize_t
*len
)
737 PyErr_BadInternalCall();
741 if (!PyString_Check(obj
)) {
742 #ifdef Py_USING_UNICODE
743 if (PyUnicode_Check(obj
)) {
744 obj
= _PyUnicode_AsDefaultEncodedString(obj
, NULL
);
751 PyErr_Format(PyExc_TypeError
,
752 "expected string or Unicode object, "
753 "%.200s found", obj
->ob_type
->tp_name
);
758 *s
= PyString_AS_STRING(obj
);
760 *len
= PyString_GET_SIZE(obj
);
761 else if (strlen(*s
) != (size_t)PyString_GET_SIZE(obj
)) {
762 PyErr_SetString(PyExc_TypeError
,
763 "expected string without null bytes");
769 /* -------------------------------------------------------------------- */
772 #define STRINGLIB_CHAR char
774 #define STRINGLIB_CMP memcmp
775 #define STRINGLIB_LEN PyString_GET_SIZE
776 #define STRINGLIB_NEW PyString_FromStringAndSize
777 #define STRINGLIB_STR PyString_AS_STRING
779 #define STRINGLIB_EMPTY nullstring
781 #include "stringlib/fastsearch.h"
783 #include "stringlib/count.h"
784 #include "stringlib/find.h"
785 #include "stringlib/partition.h"
789 string_print(PyStringObject
*op
, FILE *fp
, int flags
)
795 /* XXX Ought to check for interrupts when writing long strings */
796 if (! PyString_CheckExact(op
)) {
798 /* A str subclass may have its own __str__ method. */
799 op
= (PyStringObject
*) PyObject_Str((PyObject
*)op
);
802 ret
= string_print(op
, fp
, flags
);
806 if (flags
& Py_PRINT_RAW
) {
808 if (op
->ob_size
) fwrite(op
->ob_sval
, (int) op
->ob_size
, 1, fp
);
810 fwrite(op
->ob_sval
, 1, (int) op
->ob_size
, fp
);
815 /* figure out which quote to use; single is preferred */
817 if (memchr(op
->ob_sval
, '\'', op
->ob_size
) &&
818 !memchr(op
->ob_sval
, '"', op
->ob_size
))
822 for (i
= 0; i
< op
->ob_size
; i
++) {
824 if (c
== quote
|| c
== '\\')
825 fprintf(fp
, "\\%c", c
);
832 else if (c
< ' ' || c
>= 0x7f)
833 fprintf(fp
, "\\x%02x", c
& 0xff);
842 PyString_Repr(PyObject
*obj
, int smartquotes
)
844 register PyStringObject
* op
= (PyStringObject
*) obj
;
845 size_t newsize
= 2 + 4 * op
->ob_size
;
847 if (newsize
> PY_SSIZE_T_MAX
) {
848 PyErr_SetString(PyExc_OverflowError
,
849 "string is too large to make repr");
851 v
= PyString_FromStringAndSize((char *)NULL
, newsize
);
856 register Py_ssize_t i
;
861 /* figure out which quote to use; single is preferred */
864 memchr(op
->ob_sval
, '\'', op
->ob_size
) &&
865 !memchr(op
->ob_sval
, '"', op
->ob_size
))
868 p
= PyString_AS_STRING(v
);
870 for (i
= 0; i
< op
->ob_size
; i
++) {
871 /* There's at least enough room for a hex escape
872 and a closing quote. */
873 assert(newsize
- (p
- PyString_AS_STRING(v
)) >= 5);
875 if (c
== quote
|| c
== '\\')
876 *p
++ = '\\', *p
++ = c
;
878 *p
++ = '\\', *p
++ = 't';
880 *p
++ = '\\', *p
++ = 'n';
882 *p
++ = '\\', *p
++ = 'r';
883 else if (c
< ' ' || c
>= 0x7f) {
884 /* For performance, we don't want to call
885 PyOS_snprintf here (extra layers of
887 sprintf(p
, "\\x%02x", c
& 0xff);
893 assert(newsize
- (p
- PyString_AS_STRING(v
)) >= 1);
897 &v
, (p
- PyString_AS_STRING(v
)));
903 string_repr(PyObject
*op
)
905 return PyString_Repr(op
, 1);
909 string_str(PyObject
*s
)
911 assert(PyString_Check(s
));
912 if (PyString_CheckExact(s
)) {
917 /* Subtype -- return genuine string with the same value. */
918 PyStringObject
*t
= (PyStringObject
*) s
;
919 return PyString_FromStringAndSize(t
->ob_sval
, t
->ob_size
);
924 string_length(PyStringObject
*a
)
930 string_concat(register PyStringObject
*a
, register PyObject
*bb
)
932 register Py_ssize_t size
;
933 register PyStringObject
*op
;
934 if (!PyString_Check(bb
)) {
935 #ifdef Py_USING_UNICODE
936 if (PyUnicode_Check(bb
))
937 return PyUnicode_Concat((PyObject
*)a
, bb
);
939 PyErr_Format(PyExc_TypeError
,
940 "cannot concatenate 'str' and '%.200s' objects",
941 bb
->ob_type
->tp_name
);
944 #define b ((PyStringObject *)bb)
945 /* Optimize cases with empty left or right operand */
946 if ((a
->ob_size
== 0 || b
->ob_size
== 0) &&
947 PyString_CheckExact(a
) && PyString_CheckExact(b
)) {
948 if (a
->ob_size
== 0) {
953 return (PyObject
*)a
;
955 size
= a
->ob_size
+ b
->ob_size
;
957 PyErr_SetString(PyExc_OverflowError
,
958 "strings are too large to concat");
962 /* Inline PyObject_NewVar */
963 op
= (PyStringObject
*)PyObject_MALLOC(sizeof(PyStringObject
) + size
);
965 return PyErr_NoMemory();
966 PyObject_INIT_VAR(op
, &PyString_Type
, size
);
968 op
->ob_sstate
= SSTATE_NOT_INTERNED
;
969 Py_MEMCPY(op
->ob_sval
, a
->ob_sval
, a
->ob_size
);
970 Py_MEMCPY(op
->ob_sval
+ a
->ob_size
, b
->ob_sval
, b
->ob_size
);
971 op
->ob_sval
[size
] = '\0';
972 return (PyObject
*) op
;
977 string_repeat(register PyStringObject
*a
, register Py_ssize_t n
)
979 register Py_ssize_t i
;
980 register Py_ssize_t j
;
981 register Py_ssize_t size
;
982 register PyStringObject
*op
;
986 /* watch out for overflows: the size can overflow int,
987 * and the # of bytes needed can overflow size_t
989 size
= a
->ob_size
* n
;
990 if (n
&& size
/ n
!= a
->ob_size
) {
991 PyErr_SetString(PyExc_OverflowError
,
992 "repeated string is too long");
995 if (size
== a
->ob_size
&& PyString_CheckExact(a
)) {
997 return (PyObject
*)a
;
999 nbytes
= (size_t)size
;
1000 if (nbytes
+ sizeof(PyStringObject
) <= nbytes
) {
1001 PyErr_SetString(PyExc_OverflowError
,
1002 "repeated string is too long");
1005 op
= (PyStringObject
*)
1006 PyObject_MALLOC(sizeof(PyStringObject
) + nbytes
);
1008 return PyErr_NoMemory();
1009 PyObject_INIT_VAR(op
, &PyString_Type
, size
);
1011 op
->ob_sstate
= SSTATE_NOT_INTERNED
;
1012 op
->ob_sval
[size
] = '\0';
1013 if (a
->ob_size
== 1 && n
> 0) {
1014 memset(op
->ob_sval
, a
->ob_sval
[0] , n
);
1015 return (PyObject
*) op
;
1019 Py_MEMCPY(op
->ob_sval
, a
->ob_sval
, a
->ob_size
);
1023 j
= (i
<= size
-i
) ? i
: size
-i
;
1024 Py_MEMCPY(op
->ob_sval
+i
, op
->ob_sval
, j
);
1027 return (PyObject
*) op
;
1030 /* String slice a[i:j] consists of characters a[i] ... a[j-1] */
1033 string_slice(register PyStringObject
*a
, register Py_ssize_t i
,
1034 register Py_ssize_t j
)
1035 /* j -- may be negative! */
1040 j
= 0; /* Avoid signed/unsigned bug in next line */
1043 if (i
== 0 && j
== a
->ob_size
&& PyString_CheckExact(a
)) {
1044 /* It's the same as a */
1046 return (PyObject
*)a
;
1050 return PyString_FromStringAndSize(a
->ob_sval
+ i
, j
-i
);
1054 string_contains(PyObject
*str_obj
, PyObject
*sub_obj
)
1056 if (!PyString_CheckExact(sub_obj
)) {
1057 #ifdef Py_USING_UNICODE
1058 if (PyUnicode_Check(sub_obj
))
1059 return PyUnicode_Contains(str_obj
, sub_obj
);
1061 if (!PyString_Check(sub_obj
)) {
1062 PyErr_SetString(PyExc_TypeError
,
1063 "'in <string>' requires string as left operand");
1068 return stringlib_contains_obj(str_obj
, sub_obj
);
1072 string_item(PyStringObject
*a
, register Py_ssize_t i
)
1076 if (i
< 0 || i
>= a
->ob_size
) {
1077 PyErr_SetString(PyExc_IndexError
, "string index out of range");
1080 pchar
= a
->ob_sval
[i
];
1081 v
= (PyObject
*)characters
[pchar
& UCHAR_MAX
];
1083 v
= PyString_FromStringAndSize(&pchar
, 1);
1094 string_richcompare(PyStringObject
*a
, PyStringObject
*b
, int op
)
1097 Py_ssize_t len_a
, len_b
;
1101 /* Make sure both arguments are strings. */
1102 if (!(PyString_Check(a
) && PyString_Check(b
))) {
1103 result
= Py_NotImplemented
;
1108 case Py_EQ
:case Py_LE
:case Py_GE
:
1111 case Py_NE
:case Py_LT
:case Py_GT
:
1117 /* Supporting Py_NE here as well does not save
1118 much time, since Py_NE is rarely used. */
1119 if (a
->ob_size
== b
->ob_size
1120 && (a
->ob_sval
[0] == b
->ob_sval
[0]
1121 && memcmp(a
->ob_sval
, b
->ob_sval
,
1122 a
->ob_size
) == 0)) {
1129 len_a
= a
->ob_size
; len_b
= b
->ob_size
;
1130 min_len
= (len_a
< len_b
) ? len_a
: len_b
;
1132 c
= Py_CHARMASK(*a
->ob_sval
) - Py_CHARMASK(*b
->ob_sval
);
1134 c
= memcmp(a
->ob_sval
, b
->ob_sval
, min_len
);
1138 c
= (len_a
< len_b
) ? -1 : (len_a
> len_b
) ? 1 : 0;
1140 case Py_LT
: c
= c
< 0; break;
1141 case Py_LE
: c
= c
<= 0; break;
1142 case Py_EQ
: assert(0); break; /* unreachable */
1143 case Py_NE
: c
= c
!= 0; break;
1144 case Py_GT
: c
= c
> 0; break;
1145 case Py_GE
: c
= c
>= 0; break;
1147 result
= Py_NotImplemented
;
1150 result
= c
? Py_True
: Py_False
;
1157 _PyString_Eq(PyObject
*o1
, PyObject
*o2
)
1159 PyStringObject
*a
= (PyStringObject
*) o1
;
1160 PyStringObject
*b
= (PyStringObject
*) o2
;
1161 return a
->ob_size
== b
->ob_size
1162 && *a
->ob_sval
== *b
->ob_sval
1163 && memcmp(a
->ob_sval
, b
->ob_sval
, a
->ob_size
) == 0;
1167 string_hash(PyStringObject
*a
)
1169 register Py_ssize_t len
;
1170 register unsigned char *p
;
1173 if (a
->ob_shash
!= -1)
1176 p
= (unsigned char *) a
->ob_sval
;
1179 x
= (1000003*x
) ^ *p
++;
1187 #define HASINDEX(o) PyType_HasFeature((o)->ob_type, Py_TPFLAGS_HAVE_INDEX)
1190 string_subscript(PyStringObject
* self
, PyObject
* item
)
1192 PyNumberMethods
*nb
= item
->ob_type
->tp_as_number
;
1193 if (nb
!= NULL
&& HASINDEX(item
) && nb
->nb_index
!= NULL
) {
1194 Py_ssize_t i
= nb
->nb_index(item
);
1195 if (i
== -1 && PyErr_Occurred())
1198 i
+= PyString_GET_SIZE(self
);
1199 return string_item(self
, i
);
1201 else if (PySlice_Check(item
)) {
1202 Py_ssize_t start
, stop
, step
, slicelength
, cur
, i
;
1207 if (PySlice_GetIndicesEx((PySliceObject
*)item
,
1208 PyString_GET_SIZE(self
),
1209 &start
, &stop
, &step
, &slicelength
) < 0) {
1213 if (slicelength
<= 0) {
1214 return PyString_FromStringAndSize("", 0);
1217 source_buf
= PyString_AsString((PyObject
*)self
);
1218 result_buf
= (char *)PyMem_Malloc(slicelength
);
1219 if (result_buf
== NULL
)
1220 return PyErr_NoMemory();
1222 for (cur
= start
, i
= 0; i
< slicelength
;
1224 result_buf
[i
] = source_buf
[cur
];
1227 result
= PyString_FromStringAndSize(result_buf
,
1229 PyMem_Free(result_buf
);
1234 PyErr_SetString(PyExc_TypeError
,
1235 "string indices must be integers");
1241 string_buffer_getreadbuf(PyStringObject
*self
, Py_ssize_t index
, const void **ptr
)
1244 PyErr_SetString(PyExc_SystemError
,
1245 "accessing non-existent string segment");
1248 *ptr
= (void *)self
->ob_sval
;
1249 return self
->ob_size
;
1253 string_buffer_getwritebuf(PyStringObject
*self
, Py_ssize_t index
, const void **ptr
)
1255 PyErr_SetString(PyExc_TypeError
,
1256 "Cannot use string as modifiable buffer");
1261 string_buffer_getsegcount(PyStringObject
*self
, Py_ssize_t
*lenp
)
1264 *lenp
= self
->ob_size
;
1269 string_buffer_getcharbuf(PyStringObject
*self
, Py_ssize_t index
, const char **ptr
)
1272 PyErr_SetString(PyExc_SystemError
,
1273 "accessing non-existent string segment");
1276 *ptr
= self
->ob_sval
;
1277 return self
->ob_size
;
1280 static PySequenceMethods string_as_sequence
= {
1281 (lenfunc
)string_length
, /*sq_length*/
1282 (binaryfunc
)string_concat
, /*sq_concat*/
1283 (ssizeargfunc
)string_repeat
, /*sq_repeat*/
1284 (ssizeargfunc
)string_item
, /*sq_item*/
1285 (ssizessizeargfunc
)string_slice
, /*sq_slice*/
1288 (objobjproc
)string_contains
/*sq_contains*/
1291 static PyMappingMethods string_as_mapping
= {
1292 (lenfunc
)string_length
,
1293 (binaryfunc
)string_subscript
,
1297 static PyBufferProcs string_as_buffer
= {
1298 (readbufferproc
)string_buffer_getreadbuf
,
1299 (writebufferproc
)string_buffer_getwritebuf
,
1300 (segcountproc
)string_buffer_getsegcount
,
1301 (charbufferproc
)string_buffer_getcharbuf
,
1307 #define RIGHTSTRIP 1
1310 /* Arrays indexed by above */
1311 static const char *stripformat
[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
1313 #define STRIPNAME(i) (stripformat[i]+3)
1316 /* Don't call if length < 2 */
1317 #define Py_STRING_MATCH(target, offset, pattern, length) \
1318 (target[offset] == pattern[0] && \
1319 target[offset+length-1] == pattern[length-1] && \
1320 !memcmp(target+offset+1, pattern+1, length-2) )
1323 /* Overallocate the initial list to reduce the number of reallocs for small
1324 split sizes. Eg, "A A A A A A A A A A".split() (10 elements) has three
1325 resizes, to sizes 4, 8, then 16. Most observed string splits are for human
1326 text (roughly 11 words per line) and field delimited data (usually 1-10
1327 fields). For large strings the split algorithms are bandwidth limited
1328 so increasing the preallocation likely will not improve things.*/
1330 #define MAX_PREALLOC 12
1332 /* 5 splits gives 6 elements */
1333 #define PREALLOC_SIZE(maxsplit) \
1334 (maxsplit >= MAX_PREALLOC ? MAX_PREALLOC : maxsplit+1)
1336 #define SPLIT_APPEND(data, left, right) \
1337 str = PyString_FromStringAndSize((data) + (left), \
1338 (right) - (left)); \
1341 if (PyList_Append(list, str)) { \
1348 #define SPLIT_ADD(data, left, right) { \
1349 str = PyString_FromStringAndSize((data) + (left), \
1350 (right) - (left)); \
1353 if (count < MAX_PREALLOC) { \
1354 PyList_SET_ITEM(list, count, str); \
1356 if (PyList_Append(list, str)) { \
1365 /* Always force the list to the expected size. */
1366 #define FIX_PREALLOC_SIZE(list) ((PyListObject *)list)->ob_size = count
1368 #define SKIP_SPACE(s, i, len) { while (i<len && isspace(Py_CHARMASK(s[i]))) i++; }
1369 #define SKIP_NONSPACE(s, i, len) { while (i<len && !isspace(Py_CHARMASK(s[i]))) i++; }
1370 #define RSKIP_SPACE(s, i) { while (i>=0 && isspace(Py_CHARMASK(s[i]))) i--; }
1371 #define RSKIP_NONSPACE(s, i) { while (i>=0 && !isspace(Py_CHARMASK(s[i]))) i--; }
1373 Py_LOCAL_INLINE(PyObject
*)
1374 split_whitespace(const char *s
, Py_ssize_t len
, Py_ssize_t maxsplit
)
1376 Py_ssize_t i
, j
, count
=0;
1378 PyObject
*list
= PyList_New(PREALLOC_SIZE(maxsplit
));
1385 while (maxsplit
-- > 0) {
1386 SKIP_SPACE(s
, i
, len
);
1389 SKIP_NONSPACE(s
, i
, len
);
1394 /* Only occurs when maxsplit was reached */
1395 /* Skip any remaining whitespace and copy to end of string */
1396 SKIP_SPACE(s
, i
, len
);
1398 SPLIT_ADD(s
, i
, len
);
1400 FIX_PREALLOC_SIZE(list
);
1407 Py_LOCAL_INLINE(PyObject
*)
1408 split_char(const char *s
, Py_ssize_t len
, char ch
, Py_ssize_t maxcount
)
1410 register Py_ssize_t i
, j
, count
=0;
1412 PyObject
*list
= PyList_New(PREALLOC_SIZE(maxcount
));
1418 while ((j
< len
) && (maxcount
-- > 0)) {
1420 /* I found that using memchr makes no difference */
1429 SPLIT_ADD(s
, i
, len
);
1431 FIX_PREALLOC_SIZE(list
);
1439 PyDoc_STRVAR(split__doc__
,
1440 "S.split([sep [,maxsplit]]) -> list of strings\n\
1442 Return a list of the words in the string S, using sep as the\n\
1443 delimiter string. If maxsplit is given, at most maxsplit\n\
1444 splits are done. If sep is not specified or is None, any\n\
1445 whitespace string is a separator.");
1448 string_split(PyStringObject
*self
, PyObject
*args
)
1450 Py_ssize_t len
= PyString_GET_SIZE(self
), n
, i
, j
;
1451 Py_ssize_t maxsplit
= -1, count
=0;
1452 const char *s
= PyString_AS_STRING(self
), *sub
;
1453 PyObject
*list
, *str
, *subobj
= Py_None
;
1458 if (!PyArg_ParseTuple(args
, "|On:split", &subobj
, &maxsplit
))
1461 maxsplit
= PY_SSIZE_T_MAX
;
1462 if (subobj
== Py_None
)
1463 return split_whitespace(s
, len
, maxsplit
);
1464 if (PyString_Check(subobj
)) {
1465 sub
= PyString_AS_STRING(subobj
);
1466 n
= PyString_GET_SIZE(subobj
);
1468 #ifdef Py_USING_UNICODE
1469 else if (PyUnicode_Check(subobj
))
1470 return PyUnicode_Split((PyObject
*)self
, subobj
, maxsplit
);
1472 else if (PyObject_AsCharBuffer(subobj
, &sub
, &n
))
1476 PyErr_SetString(PyExc_ValueError
, "empty separator");
1480 return split_char(s
, len
, sub
[0], maxsplit
);
1482 list
= PyList_New(PREALLOC_SIZE(maxsplit
));
1488 while (maxsplit
-- > 0) {
1489 pos
= fastsearch(s
+i
, len
-i
, sub
, n
, FAST_SEARCH
);
1499 while ((j
+n
<= len
) && (maxsplit
-- > 0)) {
1500 for (; j
+n
<= len
; j
++) {
1501 if (Py_STRING_MATCH(s
, j
, sub
, n
)) {
1509 SPLIT_ADD(s
, i
, len
);
1510 FIX_PREALLOC_SIZE(list
);
1518 PyDoc_STRVAR(partition__doc__
,
1519 "S.partition(sep) -> (head, sep, tail)\n\
1521 Searches for the separator sep in S, and returns the part before it,\n\
1522 the separator itself, and the part after it. If the separator is not\n\
1523 found, returns S and two empty strings.");
1526 string_partition(PyStringObject
*self
, PyObject
*sep_obj
)
1531 if (PyString_Check(sep_obj
)) {
1532 sep
= PyString_AS_STRING(sep_obj
);
1533 sep_len
= PyString_GET_SIZE(sep_obj
);
1535 #ifdef Py_USING_UNICODE
1536 else if (PyUnicode_Check(sep_obj
))
1537 return PyUnicode_Partition((PyObject
*) self
, sep_obj
);
1539 else if (PyObject_AsCharBuffer(sep_obj
, &sep
, &sep_len
))
1542 return stringlib_partition(
1544 PyString_AS_STRING(self
), PyString_GET_SIZE(self
),
1545 sep_obj
, sep
, sep_len
1549 PyDoc_STRVAR(rpartition__doc__
,
1550 "S.rpartition(sep) -> (head, sep, tail)\n\
1552 Searches for the separator sep in S, starting at the end of S, and returns\n\
1553 the part before it, the separator itself, and the part after it. If the\n\
1554 separator is not found, returns S and two empty strings.");
1557 string_rpartition(PyStringObject
*self
, PyObject
*sep_obj
)
1562 if (PyString_Check(sep_obj
)) {
1563 sep
= PyString_AS_STRING(sep_obj
);
1564 sep_len
= PyString_GET_SIZE(sep_obj
);
1566 #ifdef Py_USING_UNICODE
1567 else if (PyUnicode_Check(sep_obj
))
1568 return PyUnicode_Partition((PyObject
*) self
, sep_obj
);
1570 else if (PyObject_AsCharBuffer(sep_obj
, &sep
, &sep_len
))
1573 return stringlib_rpartition(
1575 PyString_AS_STRING(self
), PyString_GET_SIZE(self
),
1576 sep_obj
, sep
, sep_len
1580 Py_LOCAL_INLINE(PyObject
*)
1581 rsplit_whitespace(const char *s
, Py_ssize_t len
, Py_ssize_t maxsplit
)
1583 Py_ssize_t i
, j
, count
=0;
1585 PyObject
*list
= PyList_New(PREALLOC_SIZE(maxsplit
));
1592 while (maxsplit
-- > 0) {
1596 RSKIP_NONSPACE(s
, i
);
1597 SPLIT_ADD(s
, i
+ 1, j
+ 1);
1600 /* Only occurs when maxsplit was reached */
1601 /* Skip any remaining whitespace and copy to beginning of string */
1604 SPLIT_ADD(s
, 0, i
+ 1);
1607 FIX_PREALLOC_SIZE(list
);
1608 if (PyList_Reverse(list
) < 0)
1616 Py_LOCAL_INLINE(PyObject
*)
1617 rsplit_char(const char *s
, Py_ssize_t len
, char ch
, Py_ssize_t maxcount
)
1619 register Py_ssize_t i
, j
, count
=0;
1621 PyObject
*list
= PyList_New(PREALLOC_SIZE(maxcount
));
1627 while ((i
>= 0) && (maxcount
-- > 0)) {
1628 for (; i
>= 0; i
--) {
1630 SPLIT_ADD(s
, i
+ 1, j
+ 1);
1637 SPLIT_ADD(s
, 0, j
+ 1);
1639 FIX_PREALLOC_SIZE(list
);
1640 if (PyList_Reverse(list
) < 0)
1649 PyDoc_STRVAR(rsplit__doc__
,
1650 "S.rsplit([sep [,maxsplit]]) -> list of strings\n\
1652 Return a list of the words in the string S, using sep as the\n\
1653 delimiter string, starting at the end of the string and working\n\
1654 to the front. If maxsplit is given, at most maxsplit splits are\n\
1655 done. If sep is not specified or is None, any whitespace string\n\
1659 string_rsplit(PyStringObject
*self
, PyObject
*args
)
1661 Py_ssize_t len
= PyString_GET_SIZE(self
), n
, i
, j
;
1662 Py_ssize_t maxsplit
= -1, count
=0;
1663 const char *s
= PyString_AS_STRING(self
), *sub
;
1664 PyObject
*list
, *str
, *subobj
= Py_None
;
1666 if (!PyArg_ParseTuple(args
, "|On:rsplit", &subobj
, &maxsplit
))
1669 maxsplit
= PY_SSIZE_T_MAX
;
1670 if (subobj
== Py_None
)
1671 return rsplit_whitespace(s
, len
, maxsplit
);
1672 if (PyString_Check(subobj
)) {
1673 sub
= PyString_AS_STRING(subobj
);
1674 n
= PyString_GET_SIZE(subobj
);
1676 #ifdef Py_USING_UNICODE
1677 else if (PyUnicode_Check(subobj
))
1678 return PyUnicode_RSplit((PyObject
*)self
, subobj
, maxsplit
);
1680 else if (PyObject_AsCharBuffer(subobj
, &sub
, &n
))
1684 PyErr_SetString(PyExc_ValueError
, "empty separator");
1688 return rsplit_char(s
, len
, sub
[0], maxsplit
);
1690 list
= PyList_New(PREALLOC_SIZE(maxsplit
));
1697 while ( (i
>= 0) && (maxsplit
-- > 0) ) {
1699 if (Py_STRING_MATCH(s
, i
, sub
, n
)) {
1700 SPLIT_ADD(s
, i
+ n
, j
);
1708 FIX_PREALLOC_SIZE(list
);
1709 if (PyList_Reverse(list
) < 0)
1719 PyDoc_STRVAR(join__doc__
,
1720 "S.join(sequence) -> string\n\
1722 Return a string which is the concatenation of the strings in the\n\
1723 sequence. The separator between elements is S.");
1726 string_join(PyStringObject
*self
, PyObject
*orig
)
1728 char *sep
= PyString_AS_STRING(self
);
1729 const Py_ssize_t seplen
= PyString_GET_SIZE(self
);
1730 PyObject
*res
= NULL
;
1732 Py_ssize_t seqlen
= 0;
1735 PyObject
*seq
, *item
;
1737 seq
= PySequence_Fast(orig
, "");
1742 seqlen
= PySequence_Size(seq
);
1745 return PyString_FromString("");
1748 item
= PySequence_Fast_GET_ITEM(seq
, 0);
1749 if (PyString_CheckExact(item
) || PyUnicode_CheckExact(item
)) {
1756 /* There are at least two things to join, or else we have a subclass
1757 * of the builtin types in the sequence.
1758 * Do a pre-pass to figure out the total amount of space we'll
1759 * need (sz), see whether any argument is absurd, and defer to
1760 * the Unicode join if appropriate.
1762 for (i
= 0; i
< seqlen
; i
++) {
1763 const size_t old_sz
= sz
;
1764 item
= PySequence_Fast_GET_ITEM(seq
, i
);
1765 if (!PyString_Check(item
)){
1766 #ifdef Py_USING_UNICODE
1767 if (PyUnicode_Check(item
)) {
1768 /* Defer to Unicode join.
1769 * CAUTION: There's no gurantee that the
1770 * original sequence can be iterated over
1771 * again, so we must pass seq here.
1774 result
= PyUnicode_Join((PyObject
*)self
, seq
);
1779 PyErr_Format(PyExc_TypeError
,
1780 "sequence item %zd: expected string,"
1782 i
, item
->ob_type
->tp_name
);
1786 sz
+= PyString_GET_SIZE(item
);
1789 if (sz
< old_sz
|| sz
> PY_SSIZE_T_MAX
) {
1790 PyErr_SetString(PyExc_OverflowError
,
1791 "join() result is too long for a Python string");
1797 /* Allocate result space. */
1798 res
= PyString_FromStringAndSize((char*)NULL
, sz
);
1804 /* Catenate everything. */
1805 p
= PyString_AS_STRING(res
);
1806 for (i
= 0; i
< seqlen
; ++i
) {
1808 item
= PySequence_Fast_GET_ITEM(seq
, i
);
1809 n
= PyString_GET_SIZE(item
);
1810 Py_MEMCPY(p
, PyString_AS_STRING(item
), n
);
1812 if (i
< seqlen
- 1) {
1813 Py_MEMCPY(p
, sep
, seplen
);
1823 _PyString_Join(PyObject
*sep
, PyObject
*x
)
1825 assert(sep
!= NULL
&& PyString_Check(sep
));
1827 return string_join((PyStringObject
*)sep
, x
);
1830 Py_LOCAL_INLINE(void)
1831 string_adjust_indices(Py_ssize_t
*start
, Py_ssize_t
*end
, Py_ssize_t len
)
1845 Py_LOCAL_INLINE(Py_ssize_t
)
1846 string_find_internal(PyStringObject
*self
, PyObject
*args
, int dir
)
1851 Py_ssize_t start
=0, end
=PY_SSIZE_T_MAX
;
1853 if (!PyArg_ParseTuple(args
, "O|O&O&:find/rfind/index/rindex", &subobj
,
1854 _PyEval_SliceIndex
, &start
, _PyEval_SliceIndex
, &end
))
1856 if (PyString_Check(subobj
)) {
1857 sub
= PyString_AS_STRING(subobj
);
1858 sub_len
= PyString_GET_SIZE(subobj
);
1860 #ifdef Py_USING_UNICODE
1861 else if (PyUnicode_Check(subobj
))
1862 return PyUnicode_Find(
1863 (PyObject
*)self
, subobj
, start
, end
, dir
);
1865 else if (PyObject_AsCharBuffer(subobj
, &sub
, &sub_len
))
1866 /* XXX - the "expected a character buffer object" is pretty
1867 confusing for a non-expert. remap to something else ? */
1871 return stringlib_find_slice(
1872 PyString_AS_STRING(self
), PyString_GET_SIZE(self
),
1873 sub
, sub_len
, start
, end
);
1875 return stringlib_rfind_slice(
1876 PyString_AS_STRING(self
), PyString_GET_SIZE(self
),
1877 sub
, sub_len
, start
, end
);
1881 PyDoc_STRVAR(find__doc__
,
1882 "S.find(sub [,start [,end]]) -> int\n\
1884 Return the lowest index in S where substring sub is found,\n\
1885 such that sub is contained within s[start,end]. Optional\n\
1886 arguments start and end are interpreted as in slice notation.\n\
1888 Return -1 on failure.");
1891 string_find(PyStringObject
*self
, PyObject
*args
)
1893 Py_ssize_t result
= string_find_internal(self
, args
, +1);
1896 return PyInt_FromSsize_t(result
);
1900 PyDoc_STRVAR(index__doc__
,
1901 "S.index(sub [,start [,end]]) -> int\n\
1903 Like S.find() but raise ValueError when the substring is not found.");
1906 string_index(PyStringObject
*self
, PyObject
*args
)
1908 Py_ssize_t result
= string_find_internal(self
, args
, +1);
1912 PyErr_SetString(PyExc_ValueError
,
1913 "substring not found");
1916 return PyInt_FromSsize_t(result
);
1920 PyDoc_STRVAR(rfind__doc__
,
1921 "S.rfind(sub [,start [,end]]) -> int\n\
1923 Return the highest index in S where substring sub is found,\n\
1924 such that sub is contained within s[start,end]. Optional\n\
1925 arguments start and end are interpreted as in slice notation.\n\
1927 Return -1 on failure.");
1930 string_rfind(PyStringObject
*self
, PyObject
*args
)
1932 Py_ssize_t result
= string_find_internal(self
, args
, -1);
1935 return PyInt_FromSsize_t(result
);
1939 PyDoc_STRVAR(rindex__doc__
,
1940 "S.rindex(sub [,start [,end]]) -> int\n\
1942 Like S.rfind() but raise ValueError when the substring is not found.");
1945 string_rindex(PyStringObject
*self
, PyObject
*args
)
1947 Py_ssize_t result
= string_find_internal(self
, args
, -1);
1951 PyErr_SetString(PyExc_ValueError
,
1952 "substring not found");
1955 return PyInt_FromSsize_t(result
);
1959 Py_LOCAL_INLINE(PyObject
*)
1960 do_xstrip(PyStringObject
*self
, int striptype
, PyObject
*sepobj
)
1962 char *s
= PyString_AS_STRING(self
);
1963 Py_ssize_t len
= PyString_GET_SIZE(self
);
1964 char *sep
= PyString_AS_STRING(sepobj
);
1965 Py_ssize_t seplen
= PyString_GET_SIZE(sepobj
);
1969 if (striptype
!= RIGHTSTRIP
) {
1970 while (i
< len
&& memchr(sep
, Py_CHARMASK(s
[i
]), seplen
)) {
1976 if (striptype
!= LEFTSTRIP
) {
1979 } while (j
>= i
&& memchr(sep
, Py_CHARMASK(s
[j
]), seplen
));
1983 if (i
== 0 && j
== len
&& PyString_CheckExact(self
)) {
1985 return (PyObject
*)self
;
1988 return PyString_FromStringAndSize(s
+i
, j
-i
);
1992 Py_LOCAL_INLINE(PyObject
*)
1993 do_strip(PyStringObject
*self
, int striptype
)
1995 char *s
= PyString_AS_STRING(self
);
1996 Py_ssize_t len
= PyString_GET_SIZE(self
), i
, j
;
1999 if (striptype
!= RIGHTSTRIP
) {
2000 while (i
< len
&& isspace(Py_CHARMASK(s
[i
]))) {
2006 if (striptype
!= LEFTSTRIP
) {
2009 } while (j
>= i
&& isspace(Py_CHARMASK(s
[j
])));
2013 if (i
== 0 && j
== len
&& PyString_CheckExact(self
)) {
2015 return (PyObject
*)self
;
2018 return PyString_FromStringAndSize(s
+i
, j
-i
);
2022 Py_LOCAL_INLINE(PyObject
*)
2023 do_argstrip(PyStringObject
*self
, int striptype
, PyObject
*args
)
2025 PyObject
*sep
= NULL
;
2027 if (!PyArg_ParseTuple(args
, (char *)stripformat
[striptype
], &sep
))
2030 if (sep
!= NULL
&& sep
!= Py_None
) {
2031 if (PyString_Check(sep
))
2032 return do_xstrip(self
, striptype
, sep
);
2033 #ifdef Py_USING_UNICODE
2034 else if (PyUnicode_Check(sep
)) {
2035 PyObject
*uniself
= PyUnicode_FromObject((PyObject
*)self
);
2039 res
= _PyUnicode_XStrip((PyUnicodeObject
*)uniself
,
2045 PyErr_Format(PyExc_TypeError
,
2046 #ifdef Py_USING_UNICODE
2047 "%s arg must be None, str or unicode",
2049 "%s arg must be None or str",
2051 STRIPNAME(striptype
));
2055 return do_strip(self
, striptype
);
2059 PyDoc_STRVAR(strip__doc__
,
2060 "S.strip([chars]) -> string or unicode\n\
2062 Return a copy of the string S with leading and trailing\n\
2063 whitespace removed.\n\
2064 If chars is given and not None, remove characters in chars instead.\n\
2065 If chars is unicode, S will be converted to unicode before stripping");
2068 string_strip(PyStringObject
*self
, PyObject
*args
)
2070 if (PyTuple_GET_SIZE(args
) == 0)
2071 return do_strip(self
, BOTHSTRIP
); /* Common case */
2073 return do_argstrip(self
, BOTHSTRIP
, args
);
2077 PyDoc_STRVAR(lstrip__doc__
,
2078 "S.lstrip([chars]) -> string or unicode\n\
2080 Return a copy of the string S with leading whitespace removed.\n\
2081 If chars is given and not None, remove characters in chars instead.\n\
2082 If chars is unicode, S will be converted to unicode before stripping");
2085 string_lstrip(PyStringObject
*self
, PyObject
*args
)
2087 if (PyTuple_GET_SIZE(args
) == 0)
2088 return do_strip(self
, LEFTSTRIP
); /* Common case */
2090 return do_argstrip(self
, LEFTSTRIP
, args
);
2094 PyDoc_STRVAR(rstrip__doc__
,
2095 "S.rstrip([chars]) -> string or unicode\n\
2097 Return a copy of the string S with trailing whitespace removed.\n\
2098 If chars is given and not None, remove characters in chars instead.\n\
2099 If chars is unicode, S will be converted to unicode before stripping");
2102 string_rstrip(PyStringObject
*self
, PyObject
*args
)
2104 if (PyTuple_GET_SIZE(args
) == 0)
2105 return do_strip(self
, RIGHTSTRIP
); /* Common case */
2107 return do_argstrip(self
, RIGHTSTRIP
, args
);
2111 PyDoc_STRVAR(lower__doc__
,
2112 "S.lower() -> string\n\
2114 Return a copy of the string S converted to lowercase.");
2116 /* _tolower and _toupper are defined by SUSv2, but they're not ISO C */
2118 #define _tolower tolower
2122 string_lower(PyStringObject
*self
)
2125 Py_ssize_t i
, n
= PyString_GET_SIZE(self
);
2128 newobj
= PyString_FromStringAndSize(NULL
, n
);
2132 s
= PyString_AS_STRING(newobj
);
2134 Py_MEMCPY(s
, PyString_AS_STRING(self
), n
);
2136 for (i
= 0; i
< n
; i
++) {
2137 int c
= Py_CHARMASK(s
[i
]);
2145 PyDoc_STRVAR(upper__doc__
,
2146 "S.upper() -> string\n\
2148 Return a copy of the string S converted to uppercase.");
2151 #define _toupper toupper
2155 string_upper(PyStringObject
*self
)
2158 Py_ssize_t i
, n
= PyString_GET_SIZE(self
);
2161 newobj
= PyString_FromStringAndSize(NULL
, n
);
2165 s
= PyString_AS_STRING(newobj
);
2167 Py_MEMCPY(s
, PyString_AS_STRING(self
), n
);
2169 for (i
= 0; i
< n
; i
++) {
2170 int c
= Py_CHARMASK(s
[i
]);
2178 PyDoc_STRVAR(title__doc__
,
2179 "S.title() -> string\n\
2181 Return a titlecased version of S, i.e. words start with uppercase\n\
2182 characters, all remaining cased characters have lowercase.");
2185 string_title(PyStringObject
*self
)
2187 char *s
= PyString_AS_STRING(self
), *s_new
;
2188 Py_ssize_t i
, n
= PyString_GET_SIZE(self
);
2189 int previous_is_cased
= 0;
2192 newobj
= PyString_FromStringAndSize(NULL
, n
);
2195 s_new
= PyString_AsString(newobj
);
2196 for (i
= 0; i
< n
; i
++) {
2197 int c
= Py_CHARMASK(*s
++);
2199 if (!previous_is_cased
)
2201 previous_is_cased
= 1;
2202 } else if (isupper(c
)) {
2203 if (previous_is_cased
)
2205 previous_is_cased
= 1;
2207 previous_is_cased
= 0;
2213 PyDoc_STRVAR(capitalize__doc__
,
2214 "S.capitalize() -> string\n\
2216 Return a copy of the string S with only its first character\n\
2220 string_capitalize(PyStringObject
*self
)
2222 char *s
= PyString_AS_STRING(self
), *s_new
;
2223 Py_ssize_t i
, n
= PyString_GET_SIZE(self
);
2226 newobj
= PyString_FromStringAndSize(NULL
, n
);
2229 s_new
= PyString_AsString(newobj
);
2231 int c
= Py_CHARMASK(*s
++);
2233 *s_new
= toupper(c
);
2238 for (i
= 1; i
< n
; i
++) {
2239 int c
= Py_CHARMASK(*s
++);
2241 *s_new
= tolower(c
);
2250 PyDoc_STRVAR(count__doc__
,
2251 "S.count(sub[, start[, end]]) -> int\n\
2253 Return the number of non-overlapping occurrences of substring sub in\n\
2254 string S[start:end]. Optional arguments start and end are interpreted\n\
2255 as in slice notation.");
2258 string_count(PyStringObject
*self
, PyObject
*args
)
2261 const char *str
= PyString_AS_STRING(self
), *sub
;
2263 Py_ssize_t start
= 0, end
= PY_SSIZE_T_MAX
;
2265 if (!PyArg_ParseTuple(args
, "O|O&O&:count", &sub_obj
,
2266 _PyEval_SliceIndex
, &start
, _PyEval_SliceIndex
, &end
))
2269 if (PyString_Check(sub_obj
)) {
2270 sub
= PyString_AS_STRING(sub_obj
);
2271 sub_len
= PyString_GET_SIZE(sub_obj
);
2273 #ifdef Py_USING_UNICODE
2274 else if (PyUnicode_Check(sub_obj
)) {
2276 count
= PyUnicode_Count((PyObject
*)self
, sub_obj
, start
, end
);
2280 return PyInt_FromSsize_t(count
);
2283 else if (PyObject_AsCharBuffer(sub_obj
, &sub
, &sub_len
))
2286 string_adjust_indices(&start
, &end
, PyString_GET_SIZE(self
));
2288 return PyInt_FromSsize_t(
2289 stringlib_count(str
+ start
, end
- start
, sub
, sub_len
)
2293 PyDoc_STRVAR(swapcase__doc__
,
2294 "S.swapcase() -> string\n\
2296 Return a copy of the string S with uppercase characters\n\
2297 converted to lowercase and vice versa.");
2300 string_swapcase(PyStringObject
*self
)
2302 char *s
= PyString_AS_STRING(self
), *s_new
;
2303 Py_ssize_t i
, n
= PyString_GET_SIZE(self
);
2306 newobj
= PyString_FromStringAndSize(NULL
, n
);
2309 s_new
= PyString_AsString(newobj
);
2310 for (i
= 0; i
< n
; i
++) {
2311 int c
= Py_CHARMASK(*s
++);
2313 *s_new
= toupper(c
);
2315 else if (isupper(c
)) {
2316 *s_new
= tolower(c
);
2326 PyDoc_STRVAR(translate__doc__
,
2327 "S.translate(table [,deletechars]) -> string\n\
2329 Return a copy of the string S, where all characters occurring\n\
2330 in the optional argument deletechars are removed, and the\n\
2331 remaining characters have been mapped through the given\n\
2332 translation table, which must be a string of length 256.");
2335 string_translate(PyStringObject
*self
, PyObject
*args
)
2337 register char *input
, *output
;
2338 register const char *table
;
2339 register Py_ssize_t i
, c
, changed
= 0;
2340 PyObject
*input_obj
= (PyObject
*)self
;
2341 const char *table1
, *output_start
, *del_table
=NULL
;
2342 Py_ssize_t inlen
, tablen
, dellen
= 0;
2344 int trans_table
[256];
2345 PyObject
*tableobj
, *delobj
= NULL
;
2347 if (!PyArg_UnpackTuple(args
, "translate", 1, 2,
2348 &tableobj
, &delobj
))
2351 if (PyString_Check(tableobj
)) {
2352 table1
= PyString_AS_STRING(tableobj
);
2353 tablen
= PyString_GET_SIZE(tableobj
);
2355 #ifdef Py_USING_UNICODE
2356 else if (PyUnicode_Check(tableobj
)) {
2357 /* Unicode .translate() does not support the deletechars
2358 parameter; instead a mapping to None will cause characters
2360 if (delobj
!= NULL
) {
2361 PyErr_SetString(PyExc_TypeError
,
2362 "deletions are implemented differently for unicode");
2365 return PyUnicode_Translate((PyObject
*)self
, tableobj
, NULL
);
2368 else if (PyObject_AsCharBuffer(tableobj
, &table1
, &tablen
))
2371 if (tablen
!= 256) {
2372 PyErr_SetString(PyExc_ValueError
,
2373 "translation table must be 256 characters long");
2377 if (delobj
!= NULL
) {
2378 if (PyString_Check(delobj
)) {
2379 del_table
= PyString_AS_STRING(delobj
);
2380 dellen
= PyString_GET_SIZE(delobj
);
2382 #ifdef Py_USING_UNICODE
2383 else if (PyUnicode_Check(delobj
)) {
2384 PyErr_SetString(PyExc_TypeError
,
2385 "deletions are implemented differently for unicode");
2389 else if (PyObject_AsCharBuffer(delobj
, &del_table
, &dellen
))
2398 inlen
= PyString_GET_SIZE(input_obj
);
2399 result
= PyString_FromStringAndSize((char *)NULL
, inlen
);
2402 output_start
= output
= PyString_AsString(result
);
2403 input
= PyString_AS_STRING(input_obj
);
2406 /* If no deletions are required, use faster code */
2407 for (i
= inlen
; --i
>= 0; ) {
2408 c
= Py_CHARMASK(*input
++);
2409 if (Py_CHARMASK((*output
++ = table
[c
])) != c
)
2412 if (changed
|| !PyString_CheckExact(input_obj
))
2415 Py_INCREF(input_obj
);
2419 for (i
= 0; i
< 256; i
++)
2420 trans_table
[i
] = Py_CHARMASK(table
[i
]);
2422 for (i
= 0; i
< dellen
; i
++)
2423 trans_table
[(int) Py_CHARMASK(del_table
[i
])] = -1;
2425 for (i
= inlen
; --i
>= 0; ) {
2426 c
= Py_CHARMASK(*input
++);
2427 if (trans_table
[c
] != -1)
2428 if (Py_CHARMASK(*output
++ = (char)trans_table
[c
]) == c
)
2432 if (!changed
&& PyString_CheckExact(input_obj
)) {
2434 Py_INCREF(input_obj
);
2437 /* Fix the size of the resulting string */
2439 _PyString_Resize(&result
, output
- output_start
);
2447 /* find and count characters and substrings */
2449 #define findchar(target, target_len, c) \
2450 ((char *)memchr((const void *)(target), c, target_len))
2452 /* String ops must return a string. */
2453 /* If the object is subclass of string, create a copy */
2454 Py_LOCAL(PyStringObject
*)
2455 return_self(PyStringObject
*self
)
2457 if (PyString_CheckExact(self
)) {
2461 return (PyStringObject
*)PyString_FromStringAndSize(
2462 PyString_AS_STRING(self
),
2463 PyString_GET_SIZE(self
));
2466 Py_LOCAL_INLINE(Py_ssize_t
)
2467 countchar(char *target
, int target_len
, char c
, Py_ssize_t maxcount
)
2471 char *end
=target
+target_len
;
2473 while ( (start
=findchar(start
, end
-start
, c
)) != NULL
) {
2475 if (count
>= maxcount
)
2482 Py_LOCAL(Py_ssize_t
)
2483 findstring(char *target
, Py_ssize_t target_len
,
2484 char *pattern
, Py_ssize_t pattern_len
,
2490 start
+= target_len
;
2494 if (end
> target_len
) {
2496 } else if (end
< 0) {
2502 /* zero-length substrings always match at the first attempt */
2503 if (pattern_len
== 0)
2504 return (direction
> 0) ? start
: end
;
2508 if (direction
< 0) {
2509 for (; end
>= start
; end
--)
2510 if (Py_STRING_MATCH(target
, end
, pattern
, pattern_len
))
2513 for (; start
<= end
; start
++)
2514 if (Py_STRING_MATCH(target
, start
, pattern
, pattern_len
))
2520 Py_LOCAL_INLINE(Py_ssize_t
)
2521 countstring(char *target
, Py_ssize_t target_len
,
2522 char *pattern
, Py_ssize_t pattern_len
,
2525 int direction
, Py_ssize_t maxcount
)
2530 start
+= target_len
;
2534 if (end
> target_len
) {
2536 } else if (end
< 0) {
2542 /* zero-length substrings match everywhere */
2543 if (pattern_len
== 0 || maxcount
== 0) {
2544 if (target_len
+1 < maxcount
)
2545 return target_len
+1;
2550 if (direction
< 0) {
2551 for (; (end
>= start
); end
--)
2552 if (Py_STRING_MATCH(target
, end
, pattern
, pattern_len
)) {
2554 if (--maxcount
<= 0) break;
2555 end
-= pattern_len
-1;
2558 for (; (start
<= end
); start
++)
2559 if (Py_STRING_MATCH(target
, start
, pattern
, pattern_len
)) {
2561 if (--maxcount
<= 0)
2563 start
+= pattern_len
-1;
2570 /* Algorithms for different cases of string replacement */
2572 /* len(self)>=1, from="", len(to)>=1, maxcount>=1 */
2573 Py_LOCAL(PyStringObject
*)
2574 replace_interleave(PyStringObject
*self
,
2576 Py_ssize_t maxcount
)
2578 char *self_s
, *to_s
, *result_s
;
2579 Py_ssize_t self_len
, to_len
, result_len
;
2580 Py_ssize_t count
, i
, product
;
2581 PyStringObject
*result
;
2583 self_len
= PyString_GET_SIZE(self
);
2584 to_len
= PyString_GET_SIZE(to
);
2586 /* 1 at the end plus 1 after every character */
2588 if (maxcount
< count
)
2591 /* Check for overflow */
2592 /* result_len = count * to_len + self_len; */
2593 product
= count
* to_len
;
2594 if (product
/ to_len
!= count
) {
2595 PyErr_SetString(PyExc_OverflowError
,
2596 "replace string is too long");
2599 result_len
= product
+ self_len
;
2600 if (result_len
< 0) {
2601 PyErr_SetString(PyExc_OverflowError
,
2602 "replace string is too long");
2606 if (! (result
= (PyStringObject
*)
2607 PyString_FromStringAndSize(NULL
, result_len
)) )
2610 self_s
= PyString_AS_STRING(self
);
2611 to_s
= PyString_AS_STRING(to
);
2612 to_len
= PyString_GET_SIZE(to
);
2613 result_s
= PyString_AS_STRING(result
);
2615 /* TODO: special case single character, which doesn't need memcpy */
2617 /* Lay the first one down (guaranteed this will occur) */
2618 Py_MEMCPY(result_s
, to_s
, to_len
);
2622 for (i
=0; i
<count
; i
++) {
2623 *result_s
++ = *self_s
++;
2624 Py_MEMCPY(result_s
, to_s
, to_len
);
2628 /* Copy the rest of the original string */
2629 Py_MEMCPY(result_s
, self_s
, self_len
-i
);
2634 /* Special case for deleting a single character */
2635 /* len(self)>=1, len(from)==1, to="", maxcount>=1 */
2636 Py_LOCAL(PyStringObject
*)
2637 replace_delete_single_character(PyStringObject
*self
,
2638 char from_c
, Py_ssize_t maxcount
)
2640 char *self_s
, *result_s
;
2641 char *start
, *next
, *end
;
2642 Py_ssize_t self_len
, result_len
;
2644 PyStringObject
*result
;
2646 self_len
= PyString_GET_SIZE(self
);
2647 self_s
= PyString_AS_STRING(self
);
2649 count
= countchar(self_s
, self_len
, from_c
, maxcount
);
2651 return return_self(self
);
2654 result_len
= self_len
- count
; /* from_len == 1 */
2655 assert(result_len
>=0);
2657 if ( (result
= (PyStringObject
*)
2658 PyString_FromStringAndSize(NULL
, result_len
)) == NULL
)
2660 result_s
= PyString_AS_STRING(result
);
2663 end
= self_s
+ self_len
;
2664 while (count
-- > 0) {
2665 next
= findchar(start
, end
-start
, from_c
);
2668 Py_MEMCPY(result_s
, start
, next
-start
);
2669 result_s
+= (next
-start
);
2672 Py_MEMCPY(result_s
, start
, end
-start
);
2677 /* len(self)>=1, len(from)>=2, to="", maxcount>=1 */
2679 Py_LOCAL(PyStringObject
*)
2680 replace_delete_substring(PyStringObject
*self
, PyStringObject
*from
,
2681 Py_ssize_t maxcount
) {
2682 char *self_s
, *from_s
, *result_s
;
2683 char *start
, *next
, *end
;
2684 Py_ssize_t self_len
, from_len
, result_len
;
2685 Py_ssize_t count
, offset
;
2686 PyStringObject
*result
;
2688 self_len
= PyString_GET_SIZE(self
);
2689 self_s
= PyString_AS_STRING(self
);
2690 from_len
= PyString_GET_SIZE(from
);
2691 from_s
= PyString_AS_STRING(from
);
2693 count
= countstring(self_s
, self_len
,
2700 return return_self(self
);
2703 result_len
= self_len
- (count
* from_len
);
2704 assert (result_len
>=0);
2706 if ( (result
= (PyStringObject
*)
2707 PyString_FromStringAndSize(NULL
, result_len
)) == NULL
)
2710 result_s
= PyString_AS_STRING(result
);
2713 end
= self_s
+ self_len
;
2714 while (count
-- > 0) {
2715 offset
= findstring(start
, end
-start
,
2717 0, end
-start
, FORWARD
);
2720 next
= start
+ offset
;
2722 Py_MEMCPY(result_s
, start
, next
-start
);
2724 result_s
+= (next
-start
);
2725 start
= next
+from_len
;
2727 Py_MEMCPY(result_s
, start
, end
-start
);
2731 /* len(self)>=1, len(from)==len(to)==1, maxcount>=1 */
2732 Py_LOCAL(PyStringObject
*)
2733 replace_single_character_in_place(PyStringObject
*self
,
2734 char from_c
, char to_c
,
2735 Py_ssize_t maxcount
)
2737 char *self_s
, *result_s
, *start
, *end
, *next
;
2738 Py_ssize_t self_len
;
2739 PyStringObject
*result
;
2741 /* The result string will be the same size */
2742 self_s
= PyString_AS_STRING(self
);
2743 self_len
= PyString_GET_SIZE(self
);
2745 next
= findchar(self_s
, self_len
, from_c
);
2748 /* No matches; return the original string */
2749 return return_self(self
);
2752 /* Need to make a new string */
2753 result
= (PyStringObject
*) PyString_FromStringAndSize(NULL
, self_len
);
2756 result_s
= PyString_AS_STRING(result
);
2757 Py_MEMCPY(result_s
, self_s
, self_len
);
2759 /* change everything in-place, starting with this one */
2760 start
= result_s
+ (next
-self_s
);
2763 end
= result_s
+ self_len
;
2765 while (--maxcount
> 0) {
2766 next
= findchar(start
, end
-start
, from_c
);
2776 /* len(self)>=1, len(from)==len(to)>=2, maxcount>=1 */
2777 Py_LOCAL(PyStringObject
*)
2778 replace_substring_in_place(PyStringObject
*self
,
2779 PyStringObject
*from
,
2781 Py_ssize_t maxcount
)
2783 char *result_s
, *start
, *end
;
2784 char *self_s
, *from_s
, *to_s
;
2785 Py_ssize_t self_len
, from_len
, offset
;
2786 PyStringObject
*result
;
2788 /* The result string will be the same size */
2790 self_s
= PyString_AS_STRING(self
);
2791 self_len
= PyString_GET_SIZE(self
);
2793 from_s
= PyString_AS_STRING(from
);
2794 from_len
= PyString_GET_SIZE(from
);
2795 to_s
= PyString_AS_STRING(to
);
2797 offset
= findstring(self_s
, self_len
,
2799 0, self_len
, FORWARD
);
2802 /* No matches; return the original string */
2803 return return_self(self
);
2806 /* Need to make a new string */
2807 result
= (PyStringObject
*) PyString_FromStringAndSize(NULL
, self_len
);
2810 result_s
= PyString_AS_STRING(result
);
2811 Py_MEMCPY(result_s
, self_s
, self_len
);
2814 /* change everything in-place, starting with this one */
2815 start
= result_s
+ offset
;
2816 Py_MEMCPY(start
, to_s
, from_len
);
2818 end
= result_s
+ self_len
;
2820 while ( --maxcount
> 0) {
2821 offset
= findstring(start
, end
-start
,
2823 0, end
-start
, FORWARD
);
2826 Py_MEMCPY(start
+offset
, to_s
, from_len
);
2827 start
+= offset
+from_len
;
2833 /* len(self)>=1, len(from)==1, len(to)>=2, maxcount>=1 */
2834 Py_LOCAL(PyStringObject
*)
2835 replace_single_character(PyStringObject
*self
,
2838 Py_ssize_t maxcount
)
2840 char *self_s
, *to_s
, *result_s
;
2841 char *start
, *next
, *end
;
2842 Py_ssize_t self_len
, to_len
, result_len
;
2843 Py_ssize_t count
, product
;
2844 PyStringObject
*result
;
2846 self_s
= PyString_AS_STRING(self
);
2847 self_len
= PyString_GET_SIZE(self
);
2849 count
= countchar(self_s
, self_len
, from_c
, maxcount
);
2852 /* no matches, return unchanged */
2853 return return_self(self
);
2856 to_s
= PyString_AS_STRING(to
);
2857 to_len
= PyString_GET_SIZE(to
);
2859 /* use the difference between current and new, hence the "-1" */
2860 /* result_len = self_len + count * (to_len-1) */
2861 product
= count
* (to_len
-1);
2862 if (product
/ (to_len
-1) != count
) {
2863 PyErr_SetString(PyExc_OverflowError
, "replace string is too long");
2866 result_len
= self_len
+ product
;
2867 if (result_len
< 0) {
2868 PyErr_SetString(PyExc_OverflowError
, "replace string is too long");
2872 if ( (result
= (PyStringObject
*)
2873 PyString_FromStringAndSize(NULL
, result_len
)) == NULL
)
2875 result_s
= PyString_AS_STRING(result
);
2878 end
= self_s
+ self_len
;
2879 while (count
-- > 0) {
2880 next
= findchar(start
, end
-start
, from_c
);
2884 if (next
== start
) {
2885 /* replace with the 'to' */
2886 Py_MEMCPY(result_s
, to_s
, to_len
);
2890 /* copy the unchanged old then the 'to' */
2891 Py_MEMCPY(result_s
, start
, next
-start
);
2892 result_s
+= (next
-start
);
2893 Py_MEMCPY(result_s
, to_s
, to_len
);
2898 /* Copy the remainder of the remaining string */
2899 Py_MEMCPY(result_s
, start
, end
-start
);
2904 /* len(self)>=1, len(from)>=2, len(to)>=2, maxcount>=1 */
2905 Py_LOCAL(PyStringObject
*)
2906 replace_substring(PyStringObject
*self
,
2907 PyStringObject
*from
,
2909 Py_ssize_t maxcount
) {
2910 char *self_s
, *from_s
, *to_s
, *result_s
;
2911 char *start
, *next
, *end
;
2912 Py_ssize_t self_len
, from_len
, to_len
, result_len
;
2913 Py_ssize_t count
, offset
, product
;
2914 PyStringObject
*result
;
2916 self_s
= PyString_AS_STRING(self
);
2917 self_len
= PyString_GET_SIZE(self
);
2918 from_s
= PyString_AS_STRING(from
);
2919 from_len
= PyString_GET_SIZE(from
);
2921 count
= countstring(self_s
, self_len
,
2923 0, self_len
, FORWARD
, maxcount
);
2925 /* no matches, return unchanged */
2926 return return_self(self
);
2929 to_s
= PyString_AS_STRING(to
);
2930 to_len
= PyString_GET_SIZE(to
);
2932 /* Check for overflow */
2933 /* result_len = self_len + count * (to_len-from_len) */
2934 product
= count
* (to_len
-from_len
);
2935 if (product
/ (to_len
-from_len
) != count
) {
2936 PyErr_SetString(PyExc_OverflowError
, "replace string is too long");
2939 result_len
= self_len
+ product
;
2940 if (result_len
< 0) {
2941 PyErr_SetString(PyExc_OverflowError
, "replace string is too long");
2945 if ( (result
= (PyStringObject
*)
2946 PyString_FromStringAndSize(NULL
, result_len
)) == NULL
)
2948 result_s
= PyString_AS_STRING(result
);
2951 end
= self_s
+ self_len
;
2952 while (count
-- > 0) {
2953 offset
= findstring(start
, end
-start
,
2955 0, end
-start
, FORWARD
);
2958 next
= start
+offset
;
2959 if (next
== start
) {
2960 /* replace with the 'to' */
2961 Py_MEMCPY(result_s
, to_s
, to_len
);
2965 /* copy the unchanged old then the 'to' */
2966 Py_MEMCPY(result_s
, start
, next
-start
);
2967 result_s
+= (next
-start
);
2968 Py_MEMCPY(result_s
, to_s
, to_len
);
2970 start
= next
+from_len
;
2973 /* Copy the remainder of the remaining string */
2974 Py_MEMCPY(result_s
, start
, end
-start
);
2980 Py_LOCAL(PyStringObject
*)
2981 replace(PyStringObject
*self
,
2982 PyStringObject
*from
,
2984 Py_ssize_t maxcount
)
2986 Py_ssize_t from_len
, to_len
;
2989 maxcount
= PY_SSIZE_T_MAX
;
2990 } else if (maxcount
== 0 || PyString_GET_SIZE(self
) == 0) {
2991 /* nothing to do; return the original string */
2992 return return_self(self
);
2995 from_len
= PyString_GET_SIZE(from
);
2996 to_len
= PyString_GET_SIZE(to
);
2998 if (maxcount
== 0 ||
2999 (from_len
== 0 && to_len
== 0)) {
3000 /* nothing to do; return the original string */
3001 return return_self(self
);
3004 /* Handle zero-length special cases */
3006 if (from_len
== 0) {
3007 /* insert the 'to' string everywhere. */
3008 /* >>> "Python".replace("", ".") */
3009 /* '.P.y.t.h.o.n.' */
3010 return replace_interleave(self
, to
, maxcount
);
3013 /* Except for "".replace("", "A") == "A" there is no way beyond this */
3014 /* point for an empty self string to generate a non-empty string */
3015 /* Special case so the remaining code always gets a non-empty string */
3016 if (PyString_GET_SIZE(self
) == 0) {
3017 return return_self(self
);
3021 /* delete all occurances of 'from' string */
3022 if (from_len
== 1) {
3023 return replace_delete_single_character(
3024 self
, PyString_AS_STRING(from
)[0], maxcount
);
3026 return replace_delete_substring(self
, from
, maxcount
);
3030 /* Handle special case where both strings have the same length */
3032 if (from_len
== to_len
) {
3033 if (from_len
== 1) {
3034 return replace_single_character_in_place(
3036 PyString_AS_STRING(from
)[0],
3037 PyString_AS_STRING(to
)[0],
3040 return replace_substring_in_place(
3041 self
, from
, to
, maxcount
);
3045 /* Otherwise use the more generic algorithms */
3046 if (from_len
== 1) {
3047 return replace_single_character(self
, PyString_AS_STRING(from
)[0],
3050 /* len('from')>=2, len('to')>=1 */
3051 return replace_substring(self
, from
, to
, maxcount
);
3055 PyDoc_STRVAR(replace__doc__
,
3056 "S.replace (old, new[, count]) -> string\n\
3058 Return a copy of string S with all occurrences of substring\n\
3059 old replaced by new. If the optional argument count is\n\
3060 given, only the first count occurrences are replaced.");
3063 string_replace(PyStringObject
*self
, PyObject
*args
)
3065 Py_ssize_t count
= -1;
3066 PyObject
*from
, *to
;
3070 if (!PyArg_ParseTuple(args
, "OO|n:replace", &from
, &to
, &count
))
3073 if (PyString_Check(from
)) {
3074 /* Can this be made a '!check' after the Unicode check? */
3076 #ifdef Py_USING_UNICODE
3077 if (PyUnicode_Check(from
))
3078 return PyUnicode_Replace((PyObject
*)self
,
3081 else if (PyObject_AsCharBuffer(from
, &tmp_s
, &tmp_len
))
3084 if (PyString_Check(to
)) {
3085 /* Can this be made a '!check' after the Unicode check? */
3087 #ifdef Py_USING_UNICODE
3088 else if (PyUnicode_Check(to
))
3089 return PyUnicode_Replace((PyObject
*)self
,
3092 else if (PyObject_AsCharBuffer(to
, &tmp_s
, &tmp_len
))
3095 return (PyObject
*)replace((PyStringObject
*) self
,
3096 (PyStringObject
*) from
,
3097 (PyStringObject
*) to
, count
);
3102 /* Matches the end (direction >= 0) or start (direction < 0) of self
3103 * against substr, using the start and end arguments. Returns
3104 * -1 on error, 0 if not found and 1 if found.
3107 _string_tailmatch(PyStringObject
*self
, PyObject
*substr
, Py_ssize_t start
,
3108 Py_ssize_t end
, int direction
)
3110 Py_ssize_t len
= PyString_GET_SIZE(self
);
3115 if (PyString_Check(substr
)) {
3116 sub
= PyString_AS_STRING(substr
);
3117 slen
= PyString_GET_SIZE(substr
);
3119 #ifdef Py_USING_UNICODE
3120 else if (PyUnicode_Check(substr
))
3121 return PyUnicode_Tailmatch((PyObject
*)self
,
3122 substr
, start
, end
, direction
);
3124 else if (PyObject_AsCharBuffer(substr
, &sub
, &slen
))
3126 str
= PyString_AS_STRING(self
);
3128 string_adjust_indices(&start
, &end
, len
);
3130 if (direction
< 0) {
3132 if (start
+slen
> len
)
3136 if (end
-start
< slen
|| start
> len
)
3139 if (end
-slen
> start
)
3142 if (end
-start
>= slen
)
3143 return ! memcmp(str
+start
, sub
, slen
);
3148 PyDoc_STRVAR(startswith__doc__
,
3149 "S.startswith(prefix[, start[, end]]) -> bool\n\
3151 Return True if S starts with the specified prefix, False otherwise.\n\
3152 With optional start, test S beginning at that position.\n\
3153 With optional end, stop comparing S at that position.\n\
3154 prefix can also be a tuple of strings to try.");
3157 string_startswith(PyStringObject
*self
, PyObject
*args
)
3159 Py_ssize_t start
= 0;
3160 Py_ssize_t end
= PY_SSIZE_T_MAX
;
3164 if (!PyArg_ParseTuple(args
, "O|O&O&:startswith", &subobj
,
3165 _PyEval_SliceIndex
, &start
, _PyEval_SliceIndex
, &end
))
3167 if (PyTuple_Check(subobj
)) {
3169 for (i
= 0; i
< PyTuple_GET_SIZE(subobj
); i
++) {
3170 result
= _string_tailmatch(self
,
3171 PyTuple_GET_ITEM(subobj
, i
),
3181 result
= _string_tailmatch(self
, subobj
, start
, end
, -1);
3185 return PyBool_FromLong(result
);
3189 PyDoc_STRVAR(endswith__doc__
,
3190 "S.endswith(suffix[, start[, end]]) -> bool\n\
3192 Return True if S ends with the specified suffix, False otherwise.\n\
3193 With optional start, test S beginning at that position.\n\
3194 With optional end, stop comparing S at that position.\n\
3195 suffix can also be a tuple of strings to try.");
3198 string_endswith(PyStringObject
*self
, PyObject
*args
)
3200 Py_ssize_t start
= 0;
3201 Py_ssize_t end
= PY_SSIZE_T_MAX
;
3205 if (!PyArg_ParseTuple(args
, "O|O&O&:endswith", &subobj
,
3206 _PyEval_SliceIndex
, &start
, _PyEval_SliceIndex
, &end
))
3208 if (PyTuple_Check(subobj
)) {
3210 for (i
= 0; i
< PyTuple_GET_SIZE(subobj
); i
++) {
3211 result
= _string_tailmatch(self
,
3212 PyTuple_GET_ITEM(subobj
, i
),
3222 result
= _string_tailmatch(self
, subobj
, start
, end
, +1);
3226 return PyBool_FromLong(result
);
3230 PyDoc_STRVAR(encode__doc__
,
3231 "S.encode([encoding[,errors]]) -> object\n\
3233 Encodes S using the codec registered for encoding. encoding defaults\n\
3234 to the default encoding. errors may be given to set a different error\n\
3235 handling scheme. Default is 'strict' meaning that encoding errors raise\n\
3236 a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
3237 'xmlcharrefreplace' as well as any other name registered with\n\
3238 codecs.register_error that is able to handle UnicodeEncodeErrors.");
3241 string_encode(PyStringObject
*self
, PyObject
*args
)
3243 char *encoding
= NULL
;
3244 char *errors
= NULL
;
3247 if (!PyArg_ParseTuple(args
, "|ss:encode", &encoding
, &errors
))
3249 v
= PyString_AsEncodedObject((PyObject
*)self
, encoding
, errors
);
3252 if (!PyString_Check(v
) && !PyUnicode_Check(v
)) {
3253 PyErr_Format(PyExc_TypeError
,
3254 "encoder did not return a string/unicode object "
3256 v
->ob_type
->tp_name
);
3267 PyDoc_STRVAR(decode__doc__
,
3268 "S.decode([encoding[,errors]]) -> object\n\
3270 Decodes S using the codec registered for encoding. encoding defaults\n\
3271 to the default encoding. errors may be given to set a different error\n\
3272 handling scheme. Default is 'strict' meaning that encoding errors raise\n\
3273 a UnicodeDecodeError. Other possible values are 'ignore' and 'replace'\n\
3274 as well as any other name registerd with codecs.register_error that is\n\
3275 able to handle UnicodeDecodeErrors.");
3278 string_decode(PyStringObject
*self
, PyObject
*args
)
3280 char *encoding
= NULL
;
3281 char *errors
= NULL
;
3284 if (!PyArg_ParseTuple(args
, "|ss:decode", &encoding
, &errors
))
3286 v
= PyString_AsDecodedObject((PyObject
*)self
, encoding
, errors
);
3289 if (!PyString_Check(v
) && !PyUnicode_Check(v
)) {
3290 PyErr_Format(PyExc_TypeError
,
3291 "decoder did not return a string/unicode object "
3293 v
->ob_type
->tp_name
);
3304 PyDoc_STRVAR(expandtabs__doc__
,
3305 "S.expandtabs([tabsize]) -> string\n\
3307 Return a copy of S where all tab characters are expanded using spaces.\n\
3308 If tabsize is not given, a tab size of 8 characters is assumed.");
3311 string_expandtabs(PyStringObject
*self
, PyObject
*args
)
3319 if (!PyArg_ParseTuple(args
, "|i:expandtabs", &tabsize
))
3322 /* First pass: determine size of output string */
3324 e
= PyString_AS_STRING(self
) + PyString_GET_SIZE(self
);
3325 for (p
= PyString_AS_STRING(self
); p
< e
; p
++)
3328 j
+= tabsize
- (j
% tabsize
);
3332 if (*p
== '\n' || *p
== '\r') {
3338 /* Second pass: create output string and fill it */
3339 u
= PyString_FromStringAndSize(NULL
, i
+ j
);
3344 q
= PyString_AS_STRING(u
);
3346 for (p
= PyString_AS_STRING(self
); p
< e
; p
++)
3349 i
= tabsize
- (j
% tabsize
);
3358 if (*p
== '\n' || *p
== '\r')
3365 Py_LOCAL_INLINE(PyObject
*)
3366 pad(PyStringObject
*self
, Py_ssize_t left
, Py_ssize_t right
, char fill
)
3375 if (left
== 0 && right
== 0 && PyString_CheckExact(self
)) {
3377 return (PyObject
*)self
;
3380 u
= PyString_FromStringAndSize(NULL
,
3381 left
+ PyString_GET_SIZE(self
) + right
);
3384 memset(PyString_AS_STRING(u
), fill
, left
);
3385 Py_MEMCPY(PyString_AS_STRING(u
) + left
,
3386 PyString_AS_STRING(self
),
3387 PyString_GET_SIZE(self
));
3389 memset(PyString_AS_STRING(u
) + left
+ PyString_GET_SIZE(self
),
3396 PyDoc_STRVAR(ljust__doc__
,
3397 "S.ljust(width[, fillchar]) -> string\n"
3399 "Return S left justified in a string of length width. Padding is\n"
3400 "done using the specified fill character (default is a space).");
3403 string_ljust(PyStringObject
*self
, PyObject
*args
)
3406 char fillchar
= ' ';
3408 if (!PyArg_ParseTuple(args
, "n|c:ljust", &width
, &fillchar
))
3411 if (PyString_GET_SIZE(self
) >= width
&& PyString_CheckExact(self
)) {
3413 return (PyObject
*) self
;
3416 return pad(self
, 0, width
- PyString_GET_SIZE(self
), fillchar
);
3420 PyDoc_STRVAR(rjust__doc__
,
3421 "S.rjust(width[, fillchar]) -> string\n"
3423 "Return S right justified in a string of length width. Padding is\n"
3424 "done using the specified fill character (default is a space)");
3427 string_rjust(PyStringObject
*self
, PyObject
*args
)
3430 char fillchar
= ' ';
3432 if (!PyArg_ParseTuple(args
, "n|c:rjust", &width
, &fillchar
))
3435 if (PyString_GET_SIZE(self
) >= width
&& PyString_CheckExact(self
)) {
3437 return (PyObject
*) self
;
3440 return pad(self
, width
- PyString_GET_SIZE(self
), 0, fillchar
);
3444 PyDoc_STRVAR(center__doc__
,
3445 "S.center(width[, fillchar]) -> string\n"
3447 "Return S centered in a string of length width. Padding is\n"
3448 "done using the specified fill character (default is a space)");
3451 string_center(PyStringObject
*self
, PyObject
*args
)
3453 Py_ssize_t marg
, left
;
3455 char fillchar
= ' ';
3457 if (!PyArg_ParseTuple(args
, "n|c:center", &width
, &fillchar
))
3460 if (PyString_GET_SIZE(self
) >= width
&& PyString_CheckExact(self
)) {
3462 return (PyObject
*) self
;
3465 marg
= width
- PyString_GET_SIZE(self
);
3466 left
= marg
/ 2 + (marg
& width
& 1);
3468 return pad(self
, left
, marg
- left
, fillchar
);
3471 PyDoc_STRVAR(zfill__doc__
,
3472 "S.zfill(width) -> string\n"
3474 "Pad a numeric string S with zeros on the left, to fill a field\n"
3475 "of the specified width. The string S is never truncated.");
3478 string_zfill(PyStringObject
*self
, PyObject
*args
)
3485 if (!PyArg_ParseTuple(args
, "n:zfill", &width
))
3488 if (PyString_GET_SIZE(self
) >= width
) {
3489 if (PyString_CheckExact(self
)) {
3491 return (PyObject
*) self
;
3494 return PyString_FromStringAndSize(
3495 PyString_AS_STRING(self
),
3496 PyString_GET_SIZE(self
)
3500 fill
= width
- PyString_GET_SIZE(self
);
3502 s
= pad(self
, fill
, 0, '0');
3507 p
= PyString_AS_STRING(s
);
3508 if (p
[fill
] == '+' || p
[fill
] == '-') {
3509 /* move sign to beginning of string */
3514 return (PyObject
*) s
;
3517 PyDoc_STRVAR(isspace__doc__
,
3518 "S.isspace() -> bool\n\
3520 Return True if all characters in S are whitespace\n\
3521 and there is at least one character in S, False otherwise.");
3524 string_isspace(PyStringObject
*self
)
3526 register const unsigned char *p
3527 = (unsigned char *) PyString_AS_STRING(self
);
3528 register const unsigned char *e
;
3530 /* Shortcut for single character strings */
3531 if (PyString_GET_SIZE(self
) == 1 &&
3533 return PyBool_FromLong(1);
3535 /* Special case for empty strings */
3536 if (PyString_GET_SIZE(self
) == 0)
3537 return PyBool_FromLong(0);
3539 e
= p
+ PyString_GET_SIZE(self
);
3540 for (; p
< e
; p
++) {
3542 return PyBool_FromLong(0);
3544 return PyBool_FromLong(1);
3548 PyDoc_STRVAR(isalpha__doc__
,
3549 "S.isalpha() -> bool\n\
3551 Return True if all characters in S are alphabetic\n\
3552 and there is at least one character in S, False otherwise.");
3555 string_isalpha(PyStringObject
*self
)
3557 register const unsigned char *p
3558 = (unsigned char *) PyString_AS_STRING(self
);
3559 register const unsigned char *e
;
3561 /* Shortcut for single character strings */
3562 if (PyString_GET_SIZE(self
) == 1 &&
3564 return PyBool_FromLong(1);
3566 /* Special case for empty strings */
3567 if (PyString_GET_SIZE(self
) == 0)
3568 return PyBool_FromLong(0);
3570 e
= p
+ PyString_GET_SIZE(self
);
3571 for (; p
< e
; p
++) {
3573 return PyBool_FromLong(0);
3575 return PyBool_FromLong(1);
3579 PyDoc_STRVAR(isalnum__doc__
,
3580 "S.isalnum() -> bool\n\
3582 Return True if all characters in S are alphanumeric\n\
3583 and there is at least one character in S, False otherwise.");
3586 string_isalnum(PyStringObject
*self
)
3588 register const unsigned char *p
3589 = (unsigned char *) PyString_AS_STRING(self
);
3590 register const unsigned char *e
;
3592 /* Shortcut for single character strings */
3593 if (PyString_GET_SIZE(self
) == 1 &&
3595 return PyBool_FromLong(1);
3597 /* Special case for empty strings */
3598 if (PyString_GET_SIZE(self
) == 0)
3599 return PyBool_FromLong(0);
3601 e
= p
+ PyString_GET_SIZE(self
);
3602 for (; p
< e
; p
++) {
3604 return PyBool_FromLong(0);
3606 return PyBool_FromLong(1);
3610 PyDoc_STRVAR(isdigit__doc__
,
3611 "S.isdigit() -> bool\n\
3613 Return True if all characters in S are digits\n\
3614 and there is at least one character in S, False otherwise.");
3617 string_isdigit(PyStringObject
*self
)
3619 register const unsigned char *p
3620 = (unsigned char *) PyString_AS_STRING(self
);
3621 register const unsigned char *e
;
3623 /* Shortcut for single character strings */
3624 if (PyString_GET_SIZE(self
) == 1 &&
3626 return PyBool_FromLong(1);
3628 /* Special case for empty strings */
3629 if (PyString_GET_SIZE(self
) == 0)
3630 return PyBool_FromLong(0);
3632 e
= p
+ PyString_GET_SIZE(self
);
3633 for (; p
< e
; p
++) {
3635 return PyBool_FromLong(0);
3637 return PyBool_FromLong(1);
3641 PyDoc_STRVAR(islower__doc__
,
3642 "S.islower() -> bool\n\
3644 Return True if all cased characters in S are lowercase and there is\n\
3645 at least one cased character in S, False otherwise.");
3648 string_islower(PyStringObject
*self
)
3650 register const unsigned char *p
3651 = (unsigned char *) PyString_AS_STRING(self
);
3652 register const unsigned char *e
;
3655 /* Shortcut for single character strings */
3656 if (PyString_GET_SIZE(self
) == 1)
3657 return PyBool_FromLong(islower(*p
) != 0);
3659 /* Special case for empty strings */
3660 if (PyString_GET_SIZE(self
) == 0)
3661 return PyBool_FromLong(0);
3663 e
= p
+ PyString_GET_SIZE(self
);
3665 for (; p
< e
; p
++) {
3667 return PyBool_FromLong(0);
3668 else if (!cased
&& islower(*p
))
3671 return PyBool_FromLong(cased
);
3675 PyDoc_STRVAR(isupper__doc__
,
3676 "S.isupper() -> bool\n\
3678 Return True if all cased characters in S are uppercase and there is\n\
3679 at least one cased character in S, False otherwise.");
3682 string_isupper(PyStringObject
*self
)
3684 register const unsigned char *p
3685 = (unsigned char *) PyString_AS_STRING(self
);
3686 register const unsigned char *e
;
3689 /* Shortcut for single character strings */
3690 if (PyString_GET_SIZE(self
) == 1)
3691 return PyBool_FromLong(isupper(*p
) != 0);
3693 /* Special case for empty strings */
3694 if (PyString_GET_SIZE(self
) == 0)
3695 return PyBool_FromLong(0);
3697 e
= p
+ PyString_GET_SIZE(self
);
3699 for (; p
< e
; p
++) {
3701 return PyBool_FromLong(0);
3702 else if (!cased
&& isupper(*p
))
3705 return PyBool_FromLong(cased
);
3709 PyDoc_STRVAR(istitle__doc__
,
3710 "S.istitle() -> bool\n\
3712 Return True if S is a titlecased string and there is at least one\n\
3713 character in S, i.e. uppercase characters may only follow uncased\n\
3714 characters and lowercase characters only cased ones. Return False\n\
3718 string_istitle(PyStringObject
*self
, PyObject
*uncased
)
3720 register const unsigned char *p
3721 = (unsigned char *) PyString_AS_STRING(self
);
3722 register const unsigned char *e
;
3723 int cased
, previous_is_cased
;
3725 /* Shortcut for single character strings */
3726 if (PyString_GET_SIZE(self
) == 1)
3727 return PyBool_FromLong(isupper(*p
) != 0);
3729 /* Special case for empty strings */
3730 if (PyString_GET_SIZE(self
) == 0)
3731 return PyBool_FromLong(0);
3733 e
= p
+ PyString_GET_SIZE(self
);
3735 previous_is_cased
= 0;
3736 for (; p
< e
; p
++) {
3737 register const unsigned char ch
= *p
;
3740 if (previous_is_cased
)
3741 return PyBool_FromLong(0);
3742 previous_is_cased
= 1;
3745 else if (islower(ch
)) {
3746 if (!previous_is_cased
)
3747 return PyBool_FromLong(0);
3748 previous_is_cased
= 1;
3752 previous_is_cased
= 0;
3754 return PyBool_FromLong(cased
);
3758 PyDoc_STRVAR(splitlines__doc__
,
3759 "S.splitlines([keepends]) -> list of strings\n\
3761 Return a list of the lines in S, breaking at line boundaries.\n\
3762 Line breaks are not included in the resulting list unless keepends\n\
3763 is given and true.");
3766 string_splitlines(PyStringObject
*self
, PyObject
*args
)
3768 register Py_ssize_t i
;
3769 register Py_ssize_t j
;
3776 if (!PyArg_ParseTuple(args
, "|i:splitlines", &keepends
))
3779 data
= PyString_AS_STRING(self
);
3780 len
= PyString_GET_SIZE(self
);
3782 /* This does not use the preallocated list because splitlines is
3783 usually run with hundreds of newlines. The overhead of
3784 switching between PyList_SET_ITEM and append causes about a
3785 2-3% slowdown for that common case. A smarter implementation
3786 could move the if check out, so the SET_ITEMs are done first
3787 and the appends only done when the prealloc buffer is full.
3788 That's too much work for little gain.*/
3790 list
= PyList_New(0);
3794 for (i
= j
= 0; i
< len
; ) {
3797 /* Find a line and append it */
3798 while (i
< len
&& data
[i
] != '\n' && data
[i
] != '\r')
3801 /* Skip the line break reading CRLF as one line break */
3804 if (data
[i
] == '\r' && i
+ 1 < len
&&
3812 SPLIT_APPEND(data
, j
, eol
);
3816 SPLIT_APPEND(data
, j
, len
);
3829 #undef PREALLOC_SIZE
3832 string_getnewargs(PyStringObject
*v
)
3834 return Py_BuildValue("(s#)", v
->ob_sval
, v
->ob_size
);
3839 string_methods
[] = {
3840 /* Counterparts of the obsolete stropmodule functions; except
3841 string.maketrans(). */
3842 {"join", (PyCFunction
)string_join
, METH_O
, join__doc__
},
3843 {"split", (PyCFunction
)string_split
, METH_VARARGS
, split__doc__
},
3844 {"rsplit", (PyCFunction
)string_rsplit
, METH_VARARGS
, rsplit__doc__
},
3845 {"lower", (PyCFunction
)string_lower
, METH_NOARGS
, lower__doc__
},
3846 {"upper", (PyCFunction
)string_upper
, METH_NOARGS
, upper__doc__
},
3847 {"islower", (PyCFunction
)string_islower
, METH_NOARGS
, islower__doc__
},
3848 {"isupper", (PyCFunction
)string_isupper
, METH_NOARGS
, isupper__doc__
},
3849 {"isspace", (PyCFunction
)string_isspace
, METH_NOARGS
, isspace__doc__
},
3850 {"isdigit", (PyCFunction
)string_isdigit
, METH_NOARGS
, isdigit__doc__
},
3851 {"istitle", (PyCFunction
)string_istitle
, METH_NOARGS
, istitle__doc__
},
3852 {"isalpha", (PyCFunction
)string_isalpha
, METH_NOARGS
, isalpha__doc__
},
3853 {"isalnum", (PyCFunction
)string_isalnum
, METH_NOARGS
, isalnum__doc__
},
3854 {"capitalize", (PyCFunction
)string_capitalize
, METH_NOARGS
,
3856 {"count", (PyCFunction
)string_count
, METH_VARARGS
, count__doc__
},
3857 {"endswith", (PyCFunction
)string_endswith
, METH_VARARGS
,
3859 {"partition", (PyCFunction
)string_partition
, METH_O
, partition__doc__
},
3860 {"find", (PyCFunction
)string_find
, METH_VARARGS
, find__doc__
},
3861 {"index", (PyCFunction
)string_index
, METH_VARARGS
, index__doc__
},
3862 {"lstrip", (PyCFunction
)string_lstrip
, METH_VARARGS
, lstrip__doc__
},
3863 {"replace", (PyCFunction
)string_replace
, METH_VARARGS
, replace__doc__
},
3864 {"rfind", (PyCFunction
)string_rfind
, METH_VARARGS
, rfind__doc__
},
3865 {"rindex", (PyCFunction
)string_rindex
, METH_VARARGS
, rindex__doc__
},
3866 {"rstrip", (PyCFunction
)string_rstrip
, METH_VARARGS
, rstrip__doc__
},
3867 {"rpartition", (PyCFunction
)string_rpartition
, METH_O
,
3869 {"startswith", (PyCFunction
)string_startswith
, METH_VARARGS
,
3871 {"strip", (PyCFunction
)string_strip
, METH_VARARGS
, strip__doc__
},
3872 {"swapcase", (PyCFunction
)string_swapcase
, METH_NOARGS
,
3874 {"translate", (PyCFunction
)string_translate
, METH_VARARGS
,
3876 {"title", (PyCFunction
)string_title
, METH_NOARGS
, title__doc__
},
3877 {"ljust", (PyCFunction
)string_ljust
, METH_VARARGS
, ljust__doc__
},
3878 {"rjust", (PyCFunction
)string_rjust
, METH_VARARGS
, rjust__doc__
},
3879 {"center", (PyCFunction
)string_center
, METH_VARARGS
, center__doc__
},
3880 {"zfill", (PyCFunction
)string_zfill
, METH_VARARGS
, zfill__doc__
},
3881 {"encode", (PyCFunction
)string_encode
, METH_VARARGS
, encode__doc__
},
3882 {"decode", (PyCFunction
)string_decode
, METH_VARARGS
, decode__doc__
},
3883 {"expandtabs", (PyCFunction
)string_expandtabs
, METH_VARARGS
,
3885 {"splitlines", (PyCFunction
)string_splitlines
, METH_VARARGS
,
3887 {"__getnewargs__", (PyCFunction
)string_getnewargs
, METH_NOARGS
},
3888 {NULL
, NULL
} /* sentinel */
3892 str_subtype_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
);
3895 string_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
3898 static char *kwlist
[] = {"object", 0};
3900 if (type
!= &PyString_Type
)
3901 return str_subtype_new(type
, args
, kwds
);
3902 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "|O:str", kwlist
, &x
))
3905 return PyString_FromString("");
3906 return PyObject_Str(x
);
3910 str_subtype_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
3912 PyObject
*tmp
, *pnew
;
3915 assert(PyType_IsSubtype(type
, &PyString_Type
));
3916 tmp
= string_new(&PyString_Type
, args
, kwds
);
3919 assert(PyString_CheckExact(tmp
));
3920 n
= PyString_GET_SIZE(tmp
);
3921 pnew
= type
->tp_alloc(type
, n
);
3923 Py_MEMCPY(PyString_AS_STRING(pnew
), PyString_AS_STRING(tmp
), n
+1);
3924 ((PyStringObject
*)pnew
)->ob_shash
=
3925 ((PyStringObject
*)tmp
)->ob_shash
;
3926 ((PyStringObject
*)pnew
)->ob_sstate
= SSTATE_NOT_INTERNED
;
3933 basestring_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
3935 PyErr_SetString(PyExc_TypeError
,
3936 "The basestring type cannot be instantiated");
3941 string_mod(PyObject
*v
, PyObject
*w
)
3943 if (!PyString_Check(v
)) {
3944 Py_INCREF(Py_NotImplemented
);
3945 return Py_NotImplemented
;
3947 return PyString_Format(v
, w
);
3950 PyDoc_STRVAR(basestring_doc
,
3951 "Type basestring cannot be instantiated; it is the base for str and unicode.");
3953 static PyNumberMethods string_as_number
= {
3958 string_mod
, /*nb_remainder*/
3962 PyTypeObject PyBaseString_Type
= {
3963 PyObject_HEAD_INIT(&PyType_Type
)
3974 0, /* tp_as_number */
3975 0, /* tp_as_sequence */
3976 0, /* tp_as_mapping */
3980 0, /* tp_getattro */
3981 0, /* tp_setattro */
3982 0, /* tp_as_buffer */
3983 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
, /* tp_flags */
3984 basestring_doc
, /* tp_doc */
3985 0, /* tp_traverse */
3987 0, /* tp_richcompare */
3988 0, /* tp_weaklistoffset */
3990 0, /* tp_iternext */
3994 &PyBaseObject_Type
, /* tp_base */
3996 0, /* tp_descr_get */
3997 0, /* tp_descr_set */
3998 0, /* tp_dictoffset */
4001 basestring_new
, /* tp_new */
4005 PyDoc_STRVAR(string_doc
,
4006 "str(object) -> string\n\
4008 Return a nice string representation of the object.\n\
4009 If the argument is a string, the return value is the same object.");
4011 PyTypeObject PyString_Type
= {
4012 PyObject_HEAD_INIT(&PyType_Type
)
4015 sizeof(PyStringObject
),
4017 string_dealloc
, /* tp_dealloc */
4018 (printfunc
)string_print
, /* tp_print */
4022 string_repr
, /* tp_repr */
4023 &string_as_number
, /* tp_as_number */
4024 &string_as_sequence
, /* tp_as_sequence */
4025 &string_as_mapping
, /* tp_as_mapping */
4026 (hashfunc
)string_hash
, /* tp_hash */
4028 string_str
, /* tp_str */
4029 PyObject_GenericGetAttr
, /* tp_getattro */
4030 0, /* tp_setattro */
4031 &string_as_buffer
, /* tp_as_buffer */
4032 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_CHECKTYPES
|
4033 Py_TPFLAGS_BASETYPE
, /* tp_flags */
4034 string_doc
, /* tp_doc */
4035 0, /* tp_traverse */
4037 (richcmpfunc
)string_richcompare
, /* tp_richcompare */
4038 0, /* tp_weaklistoffset */
4040 0, /* tp_iternext */
4041 string_methods
, /* tp_methods */
4044 &PyBaseString_Type
, /* tp_base */
4046 0, /* tp_descr_get */
4047 0, /* tp_descr_set */
4048 0, /* tp_dictoffset */
4051 string_new
, /* tp_new */
4052 PyObject_Del
, /* tp_free */
4056 PyString_Concat(register PyObject
**pv
, register PyObject
*w
)
4058 register PyObject
*v
;
4061 if (w
== NULL
|| !PyString_Check(*pv
)) {
4066 v
= string_concat((PyStringObject
*) *pv
, w
);
4072 PyString_ConcatAndDel(register PyObject
**pv
, register PyObject
*w
)
4074 PyString_Concat(pv
, w
);
4079 /* The following function breaks the notion that strings are immutable:
4080 it changes the size of a string. We get away with this only if there
4081 is only one module referencing the object. You can also think of it
4082 as creating a new string object and destroying the old one, only
4083 more efficiently. In any case, don't use this if the string may
4084 already be known to some other part of the code...
4085 Note that if there's not enough memory to resize the string, the original
4086 string object at *pv is deallocated, *pv is set to NULL, an "out of
4087 memory" exception is set, and -1 is returned. Else (on success) 0 is
4088 returned, and the value in *pv may or may not be the same as on input.
4089 As always, an extra byte is allocated for a trailing \0 byte (newsize
4090 does *not* include that), and a trailing \0 byte is stored.
4094 _PyString_Resize(PyObject
**pv
, Py_ssize_t newsize
)
4096 register PyObject
*v
;
4097 register PyStringObject
*sv
;
4099 if (!PyString_Check(v
) || v
->ob_refcnt
!= 1 || newsize
< 0 ||
4100 PyString_CHECK_INTERNED(v
)) {
4103 PyErr_BadInternalCall();
4106 /* XXX UNREF/NEWREF interface should be more symmetrical */
4108 _Py_ForgetReference(v
);
4110 PyObject_REALLOC((char *)v
, sizeof(PyStringObject
) + newsize
);
4116 _Py_NewReference(*pv
);
4117 sv
= (PyStringObject
*) *pv
;
4118 sv
->ob_size
= newsize
;
4119 sv
->ob_sval
[newsize
] = '\0';
4120 sv
->ob_shash
= -1; /* invalidate cached hash value */
4124 /* Helpers for formatstring */
4126 Py_LOCAL_INLINE(PyObject
*)
4127 getnextarg(PyObject
*args
, Py_ssize_t arglen
, Py_ssize_t
*p_argidx
)
4129 Py_ssize_t argidx
= *p_argidx
;
4130 if (argidx
< arglen
) {
4135 return PyTuple_GetItem(args
, argidx
);
4137 PyErr_SetString(PyExc_TypeError
,
4138 "not enough arguments for format string");
4149 #define F_LJUST (1<<0)
4150 #define F_SIGN (1<<1)
4151 #define F_BLANK (1<<2)
4152 #define F_ALT (1<<3)
4153 #define F_ZERO (1<<4)
4155 Py_LOCAL_INLINE(int)
4156 formatfloat(char *buf
, size_t buflen
, int flags
,
4157 int prec
, int type
, PyObject
*v
)
4159 /* fmt = '%#.' + `prec` + `type`
4160 worst case length = 3 + 10 (len of INT_MAX) + 1 = 14 (use 20)*/
4163 x
= PyFloat_AsDouble(v
);
4164 if (x
== -1.0 && PyErr_Occurred()) {
4165 PyErr_SetString(PyExc_TypeError
, "float argument required");
4170 if (type
== 'f' && fabs(x
)/1e25
>= 1e25
)
4172 /* Worst case length calc to ensure no buffer overrun:
4176 buf = '-' + [0-9]*prec + '.' + 'e+' + (longest exp
4177 for any double rep.)
4178 len = 1 + prec + 1 + 2 + 5 = 9 + prec
4181 buf = '-' + [0-9]*x + '.' + [0-9]*prec (with x < 50)
4182 len = 1 + 50 + 1 + prec = 52 + prec
4184 If prec=0 the effective precision is 1 (the leading digit is
4185 always given), therefore increase the length by one.
4188 if ((type
== 'g' && buflen
<= (size_t)10 + (size_t)prec
) ||
4189 (type
== 'f' && buflen
<= (size_t)53 + (size_t)prec
)) {
4190 PyErr_SetString(PyExc_OverflowError
,
4191 "formatted float is too long (precision too large?)");
4194 PyOS_snprintf(fmt
, sizeof(fmt
), "%%%s.%d%c",
4195 (flags
&F_ALT
) ? "#" : "",
4197 PyOS_ascii_formatd(buf
, buflen
, fmt
, x
);
4198 return (int)strlen(buf
);
4201 /* _PyString_FormatLong emulates the format codes d, u, o, x and X, and
4202 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
4203 * Python's regular ints.
4204 * Return value: a new PyString*, or NULL if error.
4205 * . *pbuf is set to point into it,
4206 * *plen set to the # of chars following that.
4207 * Caller must decref it when done using pbuf.
4208 * The string starting at *pbuf is of the form
4209 * "-"? ("0x" | "0X")? digit+
4210 * "0x"/"0X" are present only for x and X conversions, with F_ALT
4211 * set in flags. The case of hex digits will be correct,
4212 * There will be at least prec digits, zero-filled on the left if
4213 * necessary to get that many.
4214 * val object to be converted
4215 * flags bitmask of format flags; only F_ALT is looked at
4216 * prec minimum number of digits; 0-fill on left if needed
4217 * type a character in [duoxX]; u acts the same as d
4219 * CAUTION: o, x and X conversions on regular ints can never
4220 * produce a '-' sign, but can for Python's unbounded ints.
4223 _PyString_FormatLong(PyObject
*val
, int flags
, int prec
, int type
,
4224 char **pbuf
, int *plen
)
4226 PyObject
*result
= NULL
;
4229 int sign
; /* 1 if '-', else 0 */
4230 int len
; /* number of characters */
4232 int numdigits
; /* len == numnondigits + numdigits */
4233 int numnondigits
= 0;
4238 result
= val
->ob_type
->tp_str(val
);
4241 result
= val
->ob_type
->tp_as_number
->nb_oct(val
);
4246 result
= val
->ob_type
->tp_as_number
->nb_hex(val
);
4249 assert(!"'type' not in [duoxX]");
4254 /* To modify the string in-place, there can only be one reference. */
4255 if (result
->ob_refcnt
!= 1) {
4256 PyErr_BadInternalCall();
4259 buf
= PyString_AsString(result
);
4260 llen
= PyString_Size(result
);
4261 if (llen
> PY_SSIZE_T_MAX
) {
4262 PyErr_SetString(PyExc_ValueError
, "string too large in _PyString_FormatLong");
4266 if (buf
[len
-1] == 'L') {
4270 sign
= buf
[0] == '-';
4271 numnondigits
+= sign
;
4272 numdigits
= len
- numnondigits
;
4273 assert(numdigits
> 0);
4275 /* Get rid of base marker unless F_ALT */
4276 if ((flags
& F_ALT
) == 0) {
4277 /* Need to skip 0x, 0X or 0. */
4281 assert(buf
[sign
] == '0');
4282 /* If 0 is only digit, leave it alone. */
4283 if (numdigits
> 1) {
4290 assert(buf
[sign
] == '0');
4291 assert(buf
[sign
+ 1] == 'x');
4302 assert(len
== numnondigits
+ numdigits
);
4303 assert(numdigits
> 0);
4306 /* Fill with leading zeroes to meet minimum width. */
4307 if (prec
> numdigits
) {
4308 PyObject
*r1
= PyString_FromStringAndSize(NULL
,
4309 numnondigits
+ prec
);
4315 b1
= PyString_AS_STRING(r1
);
4316 for (i
= 0; i
< numnondigits
; ++i
)
4318 for (i
= 0; i
< prec
- numdigits
; i
++)
4320 for (i
= 0; i
< numdigits
; i
++)
4325 buf
= PyString_AS_STRING(result
);
4326 len
= numnondigits
+ prec
;
4329 /* Fix up case for hex conversions. */
4331 /* Need to convert all lower case letters to upper case.
4332 and need to convert 0x to 0X (and -0x to -0X). */
4333 for (i
= 0; i
< len
; i
++)
4334 if (buf
[i
] >= 'a' && buf
[i
] <= 'x')
4342 Py_LOCAL_INLINE(int)
4343 formatint(char *buf
, size_t buflen
, int flags
,
4344 int prec
, int type
, PyObject
*v
)
4346 /* fmt = '%#.' + `prec` + 'l' + `type`
4347 worst case length = 3 + 19 (worst len of INT_MAX on 64-bit machine)
4349 char fmt
[64]; /* plenty big enough! */
4353 x
= PyInt_AsLong(v
);
4354 if (x
== -1 && PyErr_Occurred()) {
4355 PyErr_SetString(PyExc_TypeError
, "int argument required");
4358 if (x
< 0 && type
== 'u') {
4361 if (x
< 0 && (type
== 'x' || type
== 'X' || type
== 'o'))
4368 if ((flags
& F_ALT
) &&
4369 (type
== 'x' || type
== 'X')) {
4370 /* When converting under %#x or %#X, there are a number
4371 * of issues that cause pain:
4372 * - when 0 is being converted, the C standard leaves off
4373 * the '0x' or '0X', which is inconsistent with other
4374 * %#x/%#X conversions and inconsistent with Python's
4376 * - there are platforms that violate the standard and
4377 * convert 0 with the '0x' or '0X'
4378 * (Metrowerks, Compaq Tru64)
4379 * - there are platforms that give '0x' when converting
4380 * under %#X, but convert 0 in accordance with the
4381 * standard (OS/2 EMX)
4383 * We can achieve the desired consistency by inserting our
4384 * own '0x' or '0X' prefix, and substituting %x/%X in place
4387 * Note that this is the same approach as used in
4388 * formatint() in unicodeobject.c
4390 PyOS_snprintf(fmt
, sizeof(fmt
), "%s0%c%%.%dl%c",
4391 sign
, type
, prec
, type
);
4394 PyOS_snprintf(fmt
, sizeof(fmt
), "%s%%%s.%dl%c",
4395 sign
, (flags
&F_ALT
) ? "#" : "",
4399 /* buf = '+'/'-'/'' + '0'/'0x'/'' + '[0-9]'*max(prec, len(x in octal))
4400 * worst case buf = '-0x' + [0-9]*prec, where prec >= 11
4402 if (buflen
<= 14 || buflen
<= (size_t)3 + (size_t)prec
) {
4403 PyErr_SetString(PyExc_OverflowError
,
4404 "formatted integer is too long (precision too large?)");
4408 PyOS_snprintf(buf
, buflen
, fmt
, -x
);
4410 PyOS_snprintf(buf
, buflen
, fmt
, x
);
4411 return (int)strlen(buf
);
4414 Py_LOCAL_INLINE(int)
4415 formatchar(char *buf
, size_t buflen
, PyObject
*v
)
4417 /* presume that the buffer is at least 2 characters long */
4418 if (PyString_Check(v
)) {
4419 if (!PyArg_Parse(v
, "c;%c requires int or char", &buf
[0]))
4423 if (!PyArg_Parse(v
, "b;%c requires int or char", &buf
[0]))
4430 /* fmt%(v1,v2,...) is roughly equivalent to sprintf(fmt, v1, v2, ...)
4432 FORMATBUFLEN is the length of the buffer in which the floats, ints, &
4433 chars are formatted. XXX This is a magic number. Each formatting
4434 routine does bounds checking to ensure no overflow, but a better
4435 solution may be to malloc a buffer of appropriate size for each
4436 format. For now, the current solution is sufficient.
4438 #define FORMATBUFLEN (size_t)120
4441 PyString_Format(PyObject
*format
, PyObject
*args
)
4444 Py_ssize_t arglen
, argidx
;
4445 Py_ssize_t reslen
, rescnt
, fmtcnt
;
4447 PyObject
*result
, *orig_args
;
4448 #ifdef Py_USING_UNICODE
4451 PyObject
*dict
= NULL
;
4452 if (format
== NULL
|| !PyString_Check(format
) || args
== NULL
) {
4453 PyErr_BadInternalCall();
4457 fmt
= PyString_AS_STRING(format
);
4458 fmtcnt
= PyString_GET_SIZE(format
);
4459 reslen
= rescnt
= fmtcnt
+ 100;
4460 result
= PyString_FromStringAndSize((char *)NULL
, reslen
);
4463 res
= PyString_AsString(result
);
4464 if (PyTuple_Check(args
)) {
4465 arglen
= PyTuple_GET_SIZE(args
);
4472 if (args
->ob_type
->tp_as_mapping
&& !PyTuple_Check(args
) &&
4473 !PyObject_TypeCheck(args
, &PyBaseString_Type
))
4475 while (--fmtcnt
>= 0) {
4478 rescnt
= fmtcnt
+ 100;
4480 if (_PyString_Resize(&result
, reslen
) < 0)
4482 res
= PyString_AS_STRING(result
)
4489 /* Got a format specifier */
4491 Py_ssize_t width
= -1;
4496 PyObject
*temp
= NULL
;
4500 char formatbuf
[FORMATBUFLEN
];
4501 /* For format{float,int,char}() */
4502 #ifdef Py_USING_UNICODE
4503 char *fmt_start
= fmt
;
4504 Py_ssize_t argidx_start
= argidx
;
4515 PyErr_SetString(PyExc_TypeError
,
4516 "format requires a mapping");
4522 /* Skip over balanced parentheses */
4523 while (pcount
> 0 && --fmtcnt
>= 0) {
4526 else if (*fmt
== '(')
4530 keylen
= fmt
- keystart
- 1;
4531 if (fmtcnt
< 0 || pcount
> 0) {
4532 PyErr_SetString(PyExc_ValueError
,
4533 "incomplete format key");
4536 key
= PyString_FromStringAndSize(keystart
,
4544 args
= PyObject_GetItem(dict
, key
);
4553 while (--fmtcnt
>= 0) {
4554 switch (c
= *fmt
++) {
4555 case '-': flags
|= F_LJUST
; continue;
4556 case '+': flags
|= F_SIGN
; continue;
4557 case ' ': flags
|= F_BLANK
; continue;
4558 case '#': flags
|= F_ALT
; continue;
4559 case '0': flags
|= F_ZERO
; continue;
4564 v
= getnextarg(args
, arglen
, &argidx
);
4567 if (!PyInt_Check(v
)) {
4568 PyErr_SetString(PyExc_TypeError
,
4572 width
= PyInt_AsLong(v
);
4580 else if (c
>= 0 && isdigit(c
)) {
4582 while (--fmtcnt
>= 0) {
4583 c
= Py_CHARMASK(*fmt
++);
4586 if ((width
*10) / 10 != width
) {
4592 width
= width
*10 + (c
- '0');
4600 v
= getnextarg(args
, arglen
, &argidx
);
4603 if (!PyInt_Check(v
)) {
4609 prec
= PyInt_AsLong(v
);
4615 else if (c
>= 0 && isdigit(c
)) {
4617 while (--fmtcnt
>= 0) {
4618 c
= Py_CHARMASK(*fmt
++);
4621 if ((prec
*10) / 10 != prec
) {
4627 prec
= prec
*10 + (c
- '0');
4632 if (c
== 'h' || c
== 'l' || c
== 'L') {
4638 PyErr_SetString(PyExc_ValueError
,
4639 "incomplete format");
4643 v
= getnextarg(args
, arglen
, &argidx
);
4655 #ifdef Py_USING_UNICODE
4656 if (PyUnicode_Check(v
)) {
4658 argidx
= argidx_start
;
4662 temp
= _PyObject_Str(v
);
4663 #ifdef Py_USING_UNICODE
4664 if (temp
!= NULL
&& PyUnicode_Check(temp
)) {
4667 argidx
= argidx_start
;
4674 temp
= PyObject_Repr(v
);
4677 if (!PyString_Check(temp
)) {
4678 PyErr_SetString(PyExc_TypeError
,
4679 "%s argument has non-string str()");
4683 pbuf
= PyString_AS_STRING(temp
);
4684 len
= PyString_GET_SIZE(temp
);
4685 if (prec
>= 0 && len
> prec
)
4696 if (PyLong_Check(v
)) {
4698 temp
= _PyString_FormatLong(v
, flags
,
4699 prec
, c
, &pbuf
, &ilen
);
4707 len
= formatint(pbuf
,
4726 len
= formatfloat(pbuf
, sizeof(formatbuf
),
4735 #ifdef Py_USING_UNICODE
4736 if (PyUnicode_Check(v
)) {
4738 argidx
= argidx_start
;
4743 len
= formatchar(pbuf
, sizeof(formatbuf
), v
);
4748 PyErr_Format(PyExc_ValueError
,
4749 "unsupported format character '%c' (0x%x) "
4752 (int)(fmt
- 1 - PyString_AsString(format
)));
4756 if (*pbuf
== '-' || *pbuf
== '+') {
4760 else if (flags
& F_SIGN
)
4762 else if (flags
& F_BLANK
)
4769 if (rescnt
- (sign
!= 0) < width
) {
4771 rescnt
= width
+ fmtcnt
+ 100;
4775 return PyErr_NoMemory();
4777 if (_PyString_Resize(&result
, reslen
) < 0)
4779 res
= PyString_AS_STRING(result
)
4789 if ((flags
& F_ALT
) && (c
== 'x' || c
== 'X')) {
4790 assert(pbuf
[0] == '0');
4791 assert(pbuf
[1] == c
);
4802 if (width
> len
&& !(flags
& F_LJUST
)) {
4806 } while (--width
> len
);
4811 if ((flags
& F_ALT
) &&
4812 (c
== 'x' || c
== 'X')) {
4813 assert(pbuf
[0] == '0');
4814 assert(pbuf
[1] == c
);
4819 Py_MEMCPY(res
, pbuf
, len
);
4822 while (--width
>= len
) {
4826 if (dict
&& (argidx
< arglen
) && c
!= '%') {
4827 PyErr_SetString(PyExc_TypeError
,
4828 "not all arguments converted during string formatting");
4834 if (argidx
< arglen
&& !dict
) {
4835 PyErr_SetString(PyExc_TypeError
,
4836 "not all arguments converted during string formatting");
4842 _PyString_Resize(&result
, reslen
- rescnt
);
4845 #ifdef Py_USING_UNICODE
4851 /* Fiddle args right (remove the first argidx arguments) */
4852 if (PyTuple_Check(orig_args
) && argidx
> 0) {
4854 Py_ssize_t n
= PyTuple_GET_SIZE(orig_args
) - argidx
;
4859 PyObject
*w
= PyTuple_GET_ITEM(orig_args
, n
+ argidx
);
4861 PyTuple_SET_ITEM(v
, n
, w
);
4865 Py_INCREF(orig_args
);
4869 /* Take what we have of the result and let the Unicode formatting
4870 function format the rest of the input. */
4871 rescnt
= res
- PyString_AS_STRING(result
);
4872 if (_PyString_Resize(&result
, rescnt
))
4874 fmtcnt
= PyString_GET_SIZE(format
) - \
4875 (fmt
- PyString_AS_STRING(format
));
4876 format
= PyUnicode_Decode(fmt
, fmtcnt
, NULL
, NULL
);
4879 v
= PyUnicode_Format(format
, args
);
4883 /* Paste what we have (result) to what the Unicode formatting
4884 function returned (v) and return the result (or error) */
4885 w
= PyUnicode_Concat(result
, v
);
4890 #endif /* Py_USING_UNICODE */
4901 PyString_InternInPlace(PyObject
**p
)
4903 register PyStringObject
*s
= (PyStringObject
*)(*p
);
4905 if (s
== NULL
|| !PyString_Check(s
))
4906 Py_FatalError("PyString_InternInPlace: strings only please!");
4907 /* If it's a string subclass, we don't really know what putting
4908 it in the interned dict might do. */
4909 if (!PyString_CheckExact(s
))
4911 if (PyString_CHECK_INTERNED(s
))
4913 if (interned
== NULL
) {
4914 interned
= PyDict_New();
4915 if (interned
== NULL
) {
4916 PyErr_Clear(); /* Don't leave an exception */
4920 t
= PyDict_GetItem(interned
, (PyObject
*)s
);
4928 if (PyDict_SetItem(interned
, (PyObject
*)s
, (PyObject
*)s
) < 0) {
4932 /* The two references in interned are not counted by refcnt.
4933 The string deallocator will take care of this */
4935 PyString_CHECK_INTERNED(s
) = SSTATE_INTERNED_MORTAL
;
4939 PyString_InternImmortal(PyObject
**p
)
4941 PyString_InternInPlace(p
);
4942 if (PyString_CHECK_INTERNED(*p
) != SSTATE_INTERNED_IMMORTAL
) {
4943 PyString_CHECK_INTERNED(*p
) = SSTATE_INTERNED_IMMORTAL
;
4950 PyString_InternFromString(const char *cp
)
4952 PyObject
*s
= PyString_FromString(cp
);
4955 PyString_InternInPlace(&s
);
4963 for (i
= 0; i
< UCHAR_MAX
+ 1; i
++) {
4964 Py_XDECREF(characters
[i
]);
4965 characters
[i
] = NULL
;
4967 Py_XDECREF(nullstring
);
4971 void _Py_ReleaseInternedStrings(void)
4977 if (interned
== NULL
|| !PyDict_Check(interned
))
4979 keys
= PyDict_Keys(interned
);
4980 if (keys
== NULL
|| !PyList_Check(keys
)) {
4985 /* Since _Py_ReleaseInternedStrings() is intended to help a leak
4986 detector, interned strings are not forcibly deallocated; rather, we
4987 give them their stolen references back, and then clear and DECREF
4988 the interned dict. */
4990 fprintf(stderr
, "releasing interned strings\n");
4991 n
= PyList_GET_SIZE(keys
);
4992 for (i
= 0; i
< n
; i
++) {
4993 s
= (PyStringObject
*) PyList_GET_ITEM(keys
, i
);
4994 switch (s
->ob_sstate
) {
4995 case SSTATE_NOT_INTERNED
:
4996 /* XXX Shouldn't happen */
4998 case SSTATE_INTERNED_IMMORTAL
:
5001 case SSTATE_INTERNED_MORTAL
:
5005 Py_FatalError("Inconsistent interned string state.");
5007 s
->ob_sstate
= SSTATE_NOT_INTERNED
;
5010 PyDict_Clear(interned
);
5011 Py_DECREF(interned
);