blob: 1a44f4a8eeaf6a50781108b5ce49ed596b014842 [file] [log] [blame]
Tim Petersced69f82003-09-16 20:30:58 +00001/*
Guido van Rossumd57fd912000-03-10 22:53:23 +00002
3Unicode implementation based on original code by Fredrik Lundh,
Benjamin Peterson31616ea2011-10-01 00:11:09 -04004modified by Marc-Andre Lemburg <mal@lemburg.com>.
Guido van Rossumd57fd912000-03-10 22:53:23 +00005
Thomas Wouters477c8d52006-05-27 19:21:47 +00006Major speed upgrades to the method implementations at the Reykjavik
7NeedForSpeed sprint, by Fredrik Lundh and Andrew Dalke.
8
Guido van Rossum16b1ad92000-08-03 16:24:25 +00009Copyright (c) Corporation for National Research Initiatives.
Guido van Rossumd57fd912000-03-10 22:53:23 +000010
Fredrik Lundh0fdb90c2001-01-19 09:45:02 +000011--------------------------------------------------------------------
12The original string type implementation is:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013
Benjamin Peterson29060642009-01-31 22:14:21 +000014 Copyright (c) 1999 by Secret Labs AB
15 Copyright (c) 1999 by Fredrik Lundh
Guido van Rossumd57fd912000-03-10 22:53:23 +000016
Fredrik Lundh0fdb90c2001-01-19 09:45:02 +000017By obtaining, using, and/or copying this software and/or its
18associated documentation, you agree that you have read, understood,
19and will comply with the following terms and conditions:
20
21Permission to use, copy, modify, and distribute this software and its
22associated documentation for any purpose and without fee is hereby
23granted, provided that the above copyright notice appears in all
24copies, and that both that copyright notice and this permission notice
25appear in supporting documentation, and that the name of Secret Labs
26AB or the author not be used in advertising or publicity pertaining to
27distribution of the software without specific, written prior
28permission.
29
30SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO
31THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
32FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR
33ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
34WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
35ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
36OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
37--------------------------------------------------------------------
38
39*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000040
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000041#define PY_SSIZE_T_CLEAN
Guido van Rossumd57fd912000-03-10 22:53:23 +000042#include "Python.h"
Marc-André Lemburgd49e5b42000-06-30 14:58:20 +000043#include "ucnhash.h"
Guido van Rossumd57fd912000-03-10 22:53:23 +000044
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000045#ifdef MS_WINDOWS
Guido van Rossumb7a40ba2000-03-28 02:01:52 +000046#include <windows.h>
47#endif
Guido van Rossumfd4b9572000-04-10 13:51:10 +000048
Victor Stinnerce5faf62011-10-05 00:42:43 +020049#ifdef Py_DEBUG
50# define DONT_MAKE_RESULT_READY
51#endif
52
Guido van Rossumd57fd912000-03-10 22:53:23 +000053/* Endianness switches; defaults to little endian */
54
55#ifdef WORDS_BIGENDIAN
56# define BYTEORDER_IS_BIG_ENDIAN
57#else
58# define BYTEORDER_IS_LITTLE_ENDIAN
59#endif
60
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000061/* --- Globals ------------------------------------------------------------
62
63 The globals are initialized by the _PyUnicode_Init() API and should
64 not be used before calling that API.
65
66*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000067
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000068
69#ifdef __cplusplus
70extern "C" {
71#endif
72
Victor Stinner910337b2011-10-03 03:20:16 +020073#ifdef Py_DEBUG
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020074# define _PyUnicode_CHECK(op) _PyUnicode_CheckConsistency(op, 0)
Victor Stinner910337b2011-10-03 03:20:16 +020075#else
76# define _PyUnicode_CHECK(op) PyUnicode_Check(op)
77#endif
Victor Stinnerfb5f5f22011-09-28 21:39:49 +020078
Victor Stinnere90fe6a2011-10-01 16:48:13 +020079#define _PyUnicode_UTF8(op) \
80 (((PyCompactUnicodeObject*)(op))->utf8)
81#define PyUnicode_UTF8(op) \
Victor Stinner910337b2011-10-03 03:20:16 +020082 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020083 assert(PyUnicode_IS_READY(op)), \
84 PyUnicode_IS_COMPACT_ASCII(op) ? \
85 ((char*)((PyASCIIObject*)(op) + 1)) : \
86 _PyUnicode_UTF8(op))
Victor Stinnerbc8b81b2011-09-29 19:31:34 +020087#define _PyUnicode_UTF8_LENGTH(op) \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020088 (((PyCompactUnicodeObject*)(op))->utf8_length)
89#define PyUnicode_UTF8_LENGTH(op) \
Victor Stinner910337b2011-10-03 03:20:16 +020090 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020091 assert(PyUnicode_IS_READY(op)), \
92 PyUnicode_IS_COMPACT_ASCII(op) ? \
93 ((PyASCIIObject*)(op))->length : \
94 _PyUnicode_UTF8_LENGTH(op))
Victor Stinnera5f91632011-10-04 01:07:11 +020095#define _PyUnicode_WSTR(op) \
96 (((PyASCIIObject*)(op))->wstr)
97#define _PyUnicode_WSTR_LENGTH(op) \
98 (((PyCompactUnicodeObject*)(op))->wstr_length)
99#define _PyUnicode_LENGTH(op) \
100 (((PyASCIIObject *)(op))->length)
101#define _PyUnicode_STATE(op) \
102 (((PyASCIIObject *)(op))->state)
103#define _PyUnicode_HASH(op) \
104 (((PyASCIIObject *)(op))->hash)
Victor Stinner910337b2011-10-03 03:20:16 +0200105#define _PyUnicode_KIND(op) \
106 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200107 ((PyASCIIObject *)(op))->state.kind)
Victor Stinner910337b2011-10-03 03:20:16 +0200108#define _PyUnicode_GET_LENGTH(op) \
109 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200110 ((PyASCIIObject *)(op))->length)
Victor Stinnera5f91632011-10-04 01:07:11 +0200111#define _PyUnicode_DATA_ANY(op) \
112 (((PyUnicodeObject*)(op))->data.any)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200113
Victor Stinner910337b2011-10-03 03:20:16 +0200114#undef PyUnicode_READY
115#define PyUnicode_READY(op) \
116 (assert(_PyUnicode_CHECK(op)), \
117 (PyUnicode_IS_READY(op) ? \
Victor Stinnera5f91632011-10-04 01:07:11 +0200118 0 : \
Victor Stinner7931d9a2011-11-04 00:22:48 +0100119 _PyUnicode_Ready(op)))
Victor Stinner910337b2011-10-03 03:20:16 +0200120
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200121#define _PyUnicode_READY_REPLACE(p_obj) \
122 (assert(_PyUnicode_CHECK(*p_obj)), \
123 (PyUnicode_IS_READY(*p_obj) ? \
124 0 : _PyUnicode_ReadyReplace((PyObject **)(p_obj))))
125
Victor Stinnerc379ead2011-10-03 12:52:27 +0200126#define _PyUnicode_SHARE_UTF8(op) \
127 (assert(_PyUnicode_CHECK(op)), \
128 assert(!PyUnicode_IS_COMPACT_ASCII(op)), \
129 (_PyUnicode_UTF8(op) == PyUnicode_DATA(op)))
130#define _PyUnicode_SHARE_WSTR(op) \
131 (assert(_PyUnicode_CHECK(op)), \
132 (_PyUnicode_WSTR(unicode) == PyUnicode_DATA(op)))
133
Victor Stinner829c0ad2011-10-03 01:08:02 +0200134/* true if the Unicode object has an allocated UTF-8 memory block
135 (not shared with other data) */
Victor Stinner910337b2011-10-03 03:20:16 +0200136#define _PyUnicode_HAS_UTF8_MEMORY(op) \
137 (assert(_PyUnicode_CHECK(op)), \
138 (!PyUnicode_IS_COMPACT_ASCII(op) \
139 && _PyUnicode_UTF8(op) \
Victor Stinner829c0ad2011-10-03 01:08:02 +0200140 && _PyUnicode_UTF8(op) != PyUnicode_DATA(op)))
141
Victor Stinner03490912011-10-03 23:45:12 +0200142/* true if the Unicode object has an allocated wstr memory block
143 (not shared with other data) */
144#define _PyUnicode_HAS_WSTR_MEMORY(op) \
145 (assert(_PyUnicode_CHECK(op)), \
146 (_PyUnicode_WSTR(op) && \
147 (!PyUnicode_IS_READY(op) || \
148 _PyUnicode_WSTR(op) != PyUnicode_DATA(op))))
149
Victor Stinner910337b2011-10-03 03:20:16 +0200150/* Generic helper macro to convert characters of different types.
151 from_type and to_type have to be valid type names, begin and end
152 are pointers to the source characters which should be of type
153 "from_type *". to is a pointer of type "to_type *" and points to the
154 buffer where the result characters are written to. */
155#define _PyUnicode_CONVERT_BYTES(from_type, to_type, begin, end, to) \
156 do { \
Antoine Pitroue459a082011-10-11 20:58:41 +0200157 to_type *_to = (to_type *) to; \
158 const from_type *_iter = (begin); \
159 const from_type *_end = (end); \
160 Py_ssize_t n = (_end) - (_iter); \
161 const from_type *_unrolled_end = \
162 _iter + (n & ~ (Py_ssize_t) 3); \
163 while (_iter < (_unrolled_end)) { \
164 _to[0] = (to_type) _iter[0]; \
165 _to[1] = (to_type) _iter[1]; \
166 _to[2] = (to_type) _iter[2]; \
167 _to[3] = (to_type) _iter[3]; \
168 _iter += 4; _to += 4; \
Victor Stinner910337b2011-10-03 03:20:16 +0200169 } \
Antoine Pitroue459a082011-10-11 20:58:41 +0200170 while (_iter < (_end)) \
171 *_to++ = (to_type) *_iter++; \
Victor Stinner910337b2011-10-03 03:20:16 +0200172 } while (0)
Victor Stinner829c0ad2011-10-03 01:08:02 +0200173
Victor Stinnerb15d4d82011-09-28 23:59:20 +0200174/* The Unicode string has been modified: reset the hash */
175#define _PyUnicode_DIRTY(op) do { _PyUnicode_HASH(op) = -1; } while (0)
176
Walter Dörwald16807132007-05-25 13:52:07 +0000177/* This dictionary holds all interned unicode strings. Note that references
178 to strings in this dictionary are *not* counted in the string's ob_refcnt.
179 When the interned string reaches a refcnt of 0 the string deallocation
180 function will delete the reference from this dictionary.
181
182 Another way to look at this is that to say that the actual reference
Guido van Rossum98297ee2007-11-06 21:34:58 +0000183 count of a string is: s->ob_refcnt + (s->state ? 2 : 0)
Walter Dörwald16807132007-05-25 13:52:07 +0000184*/
185static PyObject *interned;
186
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000187/* The empty Unicode object is shared to improve performance. */
Victor Stinnera464fc12011-10-02 20:39:30 +0200188static PyObject *unicode_empty;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000189
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200190/* List of static strings. */
191static _Py_Identifier *static_strings;
192
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000193/* Single character Unicode strings in the Latin-1 range are being
194 shared as well. */
Victor Stinnera464fc12011-10-02 20:39:30 +0200195static PyObject *unicode_latin1[256];
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000196
Christian Heimes190d79e2008-01-30 11:58:22 +0000197/* Fast detection of the most frequent whitespace characters */
198const unsigned char _Py_ascii_whitespace[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000199 0, 0, 0, 0, 0, 0, 0, 0,
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000200/* case 0x0009: * CHARACTER TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000201/* case 0x000A: * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000202/* case 0x000B: * LINE TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000203/* case 0x000C: * FORM FEED */
204/* case 0x000D: * CARRIAGE RETURN */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000205 0, 1, 1, 1, 1, 1, 0, 0,
206 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000207/* case 0x001C: * FILE SEPARATOR */
208/* case 0x001D: * GROUP SEPARATOR */
209/* case 0x001E: * RECORD SEPARATOR */
210/* case 0x001F: * UNIT SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000211 0, 0, 0, 0, 1, 1, 1, 1,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000212/* case 0x0020: * SPACE */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000213 1, 0, 0, 0, 0, 0, 0, 0,
214 0, 0, 0, 0, 0, 0, 0, 0,
215 0, 0, 0, 0, 0, 0, 0, 0,
216 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000217
Benjamin Peterson14339b62009-01-31 16:36:08 +0000218 0, 0, 0, 0, 0, 0, 0, 0,
219 0, 0, 0, 0, 0, 0, 0, 0,
220 0, 0, 0, 0, 0, 0, 0, 0,
221 0, 0, 0, 0, 0, 0, 0, 0,
222 0, 0, 0, 0, 0, 0, 0, 0,
223 0, 0, 0, 0, 0, 0, 0, 0,
224 0, 0, 0, 0, 0, 0, 0, 0,
225 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000226};
227
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200228/* forward */
Victor Stinnerfe226c02011-10-03 03:52:20 +0200229static PyUnicodeObject *_PyUnicode_New(Py_ssize_t length);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200230static PyObject* get_latin1_char(unsigned char ch);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200231static void copy_characters(
232 PyObject *to, Py_ssize_t to_start,
233 PyObject *from, Py_ssize_t from_start,
234 Py_ssize_t how_many);
Victor Stinnerc729b8e2011-10-06 02:36:59 +0200235#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200236static int unicode_is_singleton(PyObject *unicode);
Victor Stinnerc729b8e2011-10-06 02:36:59 +0200237#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200238
Alexander Belopolsky40018472011-02-26 01:02:56 +0000239static PyObject *
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200240unicode_fromascii(const unsigned char *s, Py_ssize_t size);
241static PyObject *
242_PyUnicode_FromUCS1(const unsigned char *s, Py_ssize_t size);
243static PyObject *
244_PyUnicode_FromUCS2(const Py_UCS2 *s, Py_ssize_t size);
245static PyObject *
246_PyUnicode_FromUCS4(const Py_UCS4 *s, Py_ssize_t size);
247
248static PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +0000249unicode_encode_call_errorhandler(const char *errors,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000250 PyObject **errorHandler,const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +0100251 PyObject *unicode, PyObject **exceptionObject,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000252 Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos);
253
Alexander Belopolsky40018472011-02-26 01:02:56 +0000254static void
255raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +0300256 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +0100257 PyObject *unicode,
258 Py_ssize_t startpos, Py_ssize_t endpos,
259 const char *reason);
Victor Stinner31be90b2010-04-22 19:38:16 +0000260
Christian Heimes190d79e2008-01-30 11:58:22 +0000261/* Same for linebreaks */
262static unsigned char ascii_linebreak[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000263 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000264/* 0x000A, * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000265/* 0x000B, * LINE TABULATION */
266/* 0x000C, * FORM FEED */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000267/* 0x000D, * CARRIAGE RETURN */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000268 0, 0, 1, 1, 1, 1, 0, 0,
Benjamin Peterson14339b62009-01-31 16:36:08 +0000269 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000270/* 0x001C, * FILE SEPARATOR */
271/* 0x001D, * GROUP SEPARATOR */
272/* 0x001E, * RECORD SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000273 0, 0, 0, 0, 1, 1, 1, 0,
274 0, 0, 0, 0, 0, 0, 0, 0,
275 0, 0, 0, 0, 0, 0, 0, 0,
276 0, 0, 0, 0, 0, 0, 0, 0,
277 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000278
Benjamin Peterson14339b62009-01-31 16:36:08 +0000279 0, 0, 0, 0, 0, 0, 0, 0,
280 0, 0, 0, 0, 0, 0, 0, 0,
281 0, 0, 0, 0, 0, 0, 0, 0,
282 0, 0, 0, 0, 0, 0, 0, 0,
283 0, 0, 0, 0, 0, 0, 0, 0,
284 0, 0, 0, 0, 0, 0, 0, 0,
285 0, 0, 0, 0, 0, 0, 0, 0,
286 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000287};
288
Ezio Melotti48a2f8f2011-09-29 00:18:19 +0300289/* The max unicode value is always 0x10FFFF while using the PEP-393 API.
290 This function is kept for backward compatibility with the old API. */
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000291Py_UNICODE
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +0000292PyUnicode_GetMax(void)
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000293{
Fredrik Lundh8f455852001-06-27 18:59:43 +0000294#ifdef Py_UNICODE_WIDE
Benjamin Peterson14339b62009-01-31 16:36:08 +0000295 return 0x10FFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000296#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000297 /* This is actually an illegal character, so it should
298 not be passed to unichr. */
299 return 0xFFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000300#endif
301}
302
Victor Stinner910337b2011-10-03 03:20:16 +0200303#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200304int
Victor Stinner7931d9a2011-11-04 00:22:48 +0100305_PyUnicode_CheckConsistency(PyObject *op, int check_content)
Victor Stinner910337b2011-10-03 03:20:16 +0200306{
307 PyASCIIObject *ascii;
308 unsigned int kind;
309
310 assert(PyUnicode_Check(op));
311
312 ascii = (PyASCIIObject *)op;
313 kind = ascii->state.kind;
314
Victor Stinnera3b334d2011-10-03 13:53:37 +0200315 if (ascii->state.ascii == 1 && ascii->state.compact == 1) {
Victor Stinner910337b2011-10-03 03:20:16 +0200316 assert(kind == PyUnicode_1BYTE_KIND);
Victor Stinner910337b2011-10-03 03:20:16 +0200317 assert(ascii->state.ready == 1);
318 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200319 else {
Victor Stinner85041a52011-10-03 14:42:39 +0200320 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
Victor Stinner7f11ad42011-10-04 00:00:20 +0200321 void *data;
Victor Stinner910337b2011-10-03 03:20:16 +0200322
Victor Stinnera41463c2011-10-04 01:05:08 +0200323 if (ascii->state.compact == 1) {
324 data = compact + 1;
Victor Stinner910337b2011-10-03 03:20:16 +0200325 assert(kind == PyUnicode_1BYTE_KIND
326 || kind == PyUnicode_2BYTE_KIND
327 || kind == PyUnicode_4BYTE_KIND);
Victor Stinnera41463c2011-10-04 01:05:08 +0200328 assert(ascii->state.ascii == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200329 assert(ascii->state.ready == 1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200330 assert (compact->utf8 != data);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100331 }
332 else {
Victor Stinnera41463c2011-10-04 01:05:08 +0200333 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
334
335 data = unicode->data.any;
336 if (kind == PyUnicode_WCHAR_KIND) {
Victor Stinnere30c0a12011-11-04 20:54:05 +0100337 assert(ascii->length == 0);
338 assert(ascii->hash == -1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200339 assert(ascii->state.compact == 0);
340 assert(ascii->state.ascii == 0);
341 assert(ascii->state.ready == 0);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100342 assert(ascii->state.interned == SSTATE_NOT_INTERNED);
Victor Stinnera41463c2011-10-04 01:05:08 +0200343 assert(ascii->wstr != NULL);
344 assert(data == NULL);
345 assert(compact->utf8 == NULL);
Victor Stinnera41463c2011-10-04 01:05:08 +0200346 }
347 else {
348 assert(kind == PyUnicode_1BYTE_KIND
349 || kind == PyUnicode_2BYTE_KIND
350 || kind == PyUnicode_4BYTE_KIND);
351 assert(ascii->state.compact == 0);
352 assert(ascii->state.ready == 1);
353 assert(data != NULL);
354 if (ascii->state.ascii) {
355 assert (compact->utf8 == data);
356 assert (compact->utf8_length == ascii->length);
357 }
358 else
359 assert (compact->utf8 != data);
360 }
361 }
362 if (kind != PyUnicode_WCHAR_KIND) {
Victor Stinner7f11ad42011-10-04 00:00:20 +0200363 if (
364#if SIZEOF_WCHAR_T == 2
365 kind == PyUnicode_2BYTE_KIND
366#else
367 kind == PyUnicode_4BYTE_KIND
368#endif
369 )
Victor Stinnera41463c2011-10-04 01:05:08 +0200370 {
371 assert(ascii->wstr == data);
372 assert(compact->wstr_length == ascii->length);
373 } else
374 assert(ascii->wstr != data);
Victor Stinner910337b2011-10-03 03:20:16 +0200375 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200376
377 if (compact->utf8 == NULL)
378 assert(compact->utf8_length == 0);
379 if (ascii->wstr == NULL)
380 assert(compact->wstr_length == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200381 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200382 /* check that the best kind is used */
383 if (check_content && kind != PyUnicode_WCHAR_KIND)
384 {
385 Py_ssize_t i;
386 Py_UCS4 maxchar = 0;
387 void *data = PyUnicode_DATA(ascii);
388 for (i=0; i < ascii->length; i++)
389 {
390 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
391 if (ch > maxchar)
392 maxchar = ch;
393 }
Victor Stinnerda29cc32011-11-21 14:31:41 +0100394 if (maxchar > 0x10FFFF) {
395 printf("Invalid Unicode string! {");
396 for (i=0; i < ascii->length; i++)
397 {
398 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
399 if (i)
400 printf(", U+%04x", ch);
401 else
402 printf("U+%04x", ch);
403 }
Victor Stinner5bbe5e72011-11-21 22:54:05 +0100404 printf("} (len=%lu)\n", ascii->length);
Victor Stinnerda29cc32011-11-21 14:31:41 +0100405 abort();
406 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200407 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinner77faf692011-11-20 18:56:05 +0100408 if (ascii->state.ascii == 0) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200409 assert(maxchar >= 128);
Victor Stinner77faf692011-11-20 18:56:05 +0100410 assert(maxchar <= 255);
411 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200412 else
413 assert(maxchar < 128);
414 }
Victor Stinner77faf692011-11-20 18:56:05 +0100415 else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200416 assert(maxchar >= 0x100);
Victor Stinner77faf692011-11-20 18:56:05 +0100417 assert(maxchar <= 0xFFFF);
418 }
419 else {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200420 assert(maxchar >= 0x10000);
Victor Stinner77faf692011-11-20 18:56:05 +0100421 assert(maxchar <= 0x10FFFF);
422 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200423 }
Benjamin Petersonccc51c12011-10-03 19:34:12 -0400424 return 1;
425}
Victor Stinner910337b2011-10-03 03:20:16 +0200426#endif
427
Victor Stinner3a50e702011-10-18 21:21:00 +0200428#ifdef HAVE_MBCS
429static OSVERSIONINFOEX winver;
430#endif
431
Thomas Wouters477c8d52006-05-27 19:21:47 +0000432/* --- Bloom Filters ----------------------------------------------------- */
433
434/* stuff to implement simple "bloom filters" for Unicode characters.
435 to keep things simple, we use a single bitmask, using the least 5
436 bits from each unicode characters as the bit index. */
437
438/* the linebreak mask is set up by Unicode_Init below */
439
Antoine Pitrouf068f942010-01-13 14:19:12 +0000440#if LONG_BIT >= 128
441#define BLOOM_WIDTH 128
442#elif LONG_BIT >= 64
443#define BLOOM_WIDTH 64
444#elif LONG_BIT >= 32
445#define BLOOM_WIDTH 32
446#else
447#error "LONG_BIT is smaller than 32"
448#endif
449
Thomas Wouters477c8d52006-05-27 19:21:47 +0000450#define BLOOM_MASK unsigned long
451
452static BLOOM_MASK bloom_linebreak;
453
Antoine Pitrouf068f942010-01-13 14:19:12 +0000454#define BLOOM_ADD(mask, ch) ((mask |= (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
455#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000456
Benjamin Peterson29060642009-01-31 22:14:21 +0000457#define BLOOM_LINEBREAK(ch) \
458 ((ch) < 128U ? ascii_linebreak[(ch)] : \
459 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000460
Alexander Belopolsky40018472011-02-26 01:02:56 +0000461Py_LOCAL_INLINE(BLOOM_MASK)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200462make_bloom_mask(int kind, void* ptr, Py_ssize_t len)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000463{
464 /* calculate simple bloom-style bitmask for a given unicode string */
465
Antoine Pitrouf068f942010-01-13 14:19:12 +0000466 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000467 Py_ssize_t i;
468
469 mask = 0;
470 for (i = 0; i < len; i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200471 BLOOM_ADD(mask, PyUnicode_READ(kind, ptr, i));
Thomas Wouters477c8d52006-05-27 19:21:47 +0000472
473 return mask;
474}
475
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200476#define BLOOM_MEMBER(mask, chr, str) \
477 (BLOOM(mask, chr) \
478 && (PyUnicode_FindChar(str, chr, 0, PyUnicode_GET_LENGTH(str), 1) >= 0))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000479
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200480/* Compilation of templated routines */
481
482#include "stringlib/asciilib.h"
483#include "stringlib/fastsearch.h"
484#include "stringlib/partition.h"
485#include "stringlib/split.h"
486#include "stringlib/count.h"
487#include "stringlib/find.h"
488#include "stringlib/find_max_char.h"
489#include "stringlib/localeutil.h"
490#include "stringlib/undef.h"
491
492#include "stringlib/ucs1lib.h"
493#include "stringlib/fastsearch.h"
494#include "stringlib/partition.h"
495#include "stringlib/split.h"
496#include "stringlib/count.h"
497#include "stringlib/find.h"
498#include "stringlib/find_max_char.h"
499#include "stringlib/localeutil.h"
500#include "stringlib/undef.h"
501
502#include "stringlib/ucs2lib.h"
503#include "stringlib/fastsearch.h"
504#include "stringlib/partition.h"
505#include "stringlib/split.h"
506#include "stringlib/count.h"
507#include "stringlib/find.h"
508#include "stringlib/find_max_char.h"
509#include "stringlib/localeutil.h"
510#include "stringlib/undef.h"
511
512#include "stringlib/ucs4lib.h"
513#include "stringlib/fastsearch.h"
514#include "stringlib/partition.h"
515#include "stringlib/split.h"
516#include "stringlib/count.h"
517#include "stringlib/find.h"
518#include "stringlib/find_max_char.h"
519#include "stringlib/localeutil.h"
520#include "stringlib/undef.h"
521
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200522#include "stringlib/unicodedefs.h"
523#include "stringlib/fastsearch.h"
524#include "stringlib/count.h"
525#include "stringlib/find.h"
Antoine Pitrou0a3229d2011-11-21 20:39:13 +0100526#include "stringlib/undef.h"
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200527
Guido van Rossumd57fd912000-03-10 22:53:23 +0000528/* --- Unicode Object ----------------------------------------------------- */
529
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200530static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +0200531fixup(PyObject *self, Py_UCS4 (*fixfct)(PyObject *s));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200532
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200533Py_LOCAL_INLINE(Py_ssize_t) findchar(void *s, int kind,
534 Py_ssize_t size, Py_UCS4 ch,
535 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200536{
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200537 int mode = (direction == 1) ? FAST_SEARCH : FAST_RSEARCH;
538
539 switch (kind) {
540 case PyUnicode_1BYTE_KIND:
541 {
542 Py_UCS1 ch1 = (Py_UCS1) ch;
543 if (ch1 == ch)
544 return ucs1lib_fastsearch((Py_UCS1 *) s, size, &ch1, 1, 0, mode);
545 else
546 return -1;
547 }
548 case PyUnicode_2BYTE_KIND:
549 {
550 Py_UCS2 ch2 = (Py_UCS2) ch;
551 if (ch2 == ch)
552 return ucs2lib_fastsearch((Py_UCS2 *) s, size, &ch2, 1, 0, mode);
553 else
554 return -1;
555 }
556 case PyUnicode_4BYTE_KIND:
557 return ucs4lib_fastsearch((Py_UCS4 *) s, size, &ch, 1, 0, mode);
558 default:
559 assert(0);
560 return -1;
Victor Stinner9e7a1bc2011-10-13 00:18:12 +0200561 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200562}
563
Victor Stinnerfe226c02011-10-03 03:52:20 +0200564static PyObject*
565resize_compact(PyObject *unicode, Py_ssize_t length)
566{
567 Py_ssize_t char_size;
568 Py_ssize_t struct_size;
569 Py_ssize_t new_size;
570 int share_wstr;
571
572 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200573 char_size = PyUnicode_KIND(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200574 if (PyUnicode_IS_COMPACT_ASCII(unicode))
575 struct_size = sizeof(PyASCIIObject);
576 else
577 struct_size = sizeof(PyCompactUnicodeObject);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200578 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200579
580 _Py_DEC_REFTOTAL;
581 _Py_ForgetReference(unicode);
582
583 if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
584 PyErr_NoMemory();
585 return NULL;
586 }
587 new_size = (struct_size + (length + 1) * char_size);
588
589 unicode = (PyObject *)PyObject_REALLOC((char *)unicode, new_size);
590 if (unicode == NULL) {
591 PyObject_Del(unicode);
592 PyErr_NoMemory();
593 return NULL;
594 }
595 _Py_NewReference(unicode);
596 _PyUnicode_LENGTH(unicode) = length;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200597 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200598 _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200599 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
600 _PyUnicode_WSTR_LENGTH(unicode) = length;
601 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200602 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
603 length, 0);
604 return unicode;
605}
606
Alexander Belopolsky40018472011-02-26 01:02:56 +0000607static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200608resize_inplace(PyObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000609{
Victor Stinner95663112011-10-04 01:03:50 +0200610 wchar_t *wstr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200611 assert(!PyUnicode_IS_COMPACT(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200612 assert(Py_REFCNT(unicode) == 1);
Tim Petersced69f82003-09-16 20:30:58 +0000613
Victor Stinner95663112011-10-04 01:03:50 +0200614 _PyUnicode_DIRTY(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200615
616 if (PyUnicode_IS_READY(unicode)) {
617 Py_ssize_t char_size;
618 Py_ssize_t new_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200619 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200620 void *data;
621
622 data = _PyUnicode_DATA_ANY(unicode);
623 assert(data != NULL);
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200624 char_size = PyUnicode_KIND(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200625 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
626 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinner95663112011-10-04 01:03:50 +0200627 if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
628 {
629 PyObject_DEL(_PyUnicode_UTF8(unicode));
630 _PyUnicode_UTF8(unicode) = NULL;
631 _PyUnicode_UTF8_LENGTH(unicode) = 0;
632 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200633
634 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
635 PyErr_NoMemory();
636 return -1;
637 }
638 new_size = (length + 1) * char_size;
639
640 data = (PyObject *)PyObject_REALLOC(data, new_size);
641 if (data == NULL) {
642 PyErr_NoMemory();
643 return -1;
644 }
645 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200646 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200647 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200648 _PyUnicode_WSTR_LENGTH(unicode) = length;
649 }
650 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200651 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200652 _PyUnicode_UTF8_LENGTH(unicode) = length;
653 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200654 _PyUnicode_LENGTH(unicode) = length;
655 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
Victor Stinner95663112011-10-04 01:03:50 +0200656 if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200657 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200658 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200659 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200660 }
Victor Stinner95663112011-10-04 01:03:50 +0200661 assert(_PyUnicode_WSTR(unicode) != NULL);
662
663 /* check for integer overflow */
664 if (length > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
665 PyErr_NoMemory();
666 return -1;
667 }
668 wstr = _PyUnicode_WSTR(unicode);
669 wstr = PyObject_REALLOC(wstr, sizeof(wchar_t) * (length + 1));
670 if (!wstr) {
671 PyErr_NoMemory();
672 return -1;
673 }
674 _PyUnicode_WSTR(unicode) = wstr;
675 _PyUnicode_WSTR(unicode)[length] = 0;
676 _PyUnicode_WSTR_LENGTH(unicode) = length;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200677 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000678 return 0;
679}
680
Victor Stinnerfe226c02011-10-03 03:52:20 +0200681static PyObject*
682resize_copy(PyObject *unicode, Py_ssize_t length)
683{
684 Py_ssize_t copy_length;
685 if (PyUnicode_IS_COMPACT(unicode)) {
686 PyObject *copy;
687 assert(PyUnicode_IS_READY(unicode));
688
689 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
690 if (copy == NULL)
691 return NULL;
692
693 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200694 copy_characters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200695 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +0200696 }
697 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200698 PyObject *w;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200699 assert(_PyUnicode_WSTR(unicode) != NULL);
700 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200701 w = (PyObject*)_PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200702 if (w == NULL)
703 return NULL;
704 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
705 copy_length = Py_MIN(copy_length, length);
706 Py_UNICODE_COPY(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
707 copy_length);
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200708 return w;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200709 }
710}
711
Guido van Rossumd57fd912000-03-10 22:53:23 +0000712/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +0000713 Ux0000 terminated; some code (e.g. new_identifier)
714 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000715
716 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +0000717 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000718
719*/
720
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200721#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +0200722static int unicode_old_new_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200723#endif
724
Alexander Belopolsky40018472011-02-26 01:02:56 +0000725static PyUnicodeObject *
726_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000727{
728 register PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200729 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000730
Thomas Wouters477c8d52006-05-27 19:21:47 +0000731 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +0000732 if (length == 0 && unicode_empty != NULL) {
733 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200734 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000735 }
736
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000737 /* Ensure we won't overflow the size. */
738 if (length > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
739 return (PyUnicodeObject *)PyErr_NoMemory();
740 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200741 if (length < 0) {
742 PyErr_SetString(PyExc_SystemError,
743 "Negative size passed to _PyUnicode_New");
744 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000745 }
746
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200747#ifdef Py_DEBUG
748 ++unicode_old_new_calls;
749#endif
750
751 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
752 if (unicode == NULL)
753 return NULL;
754 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
755 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
756 if (!_PyUnicode_WSTR(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000757 PyErr_NoMemory();
758 goto onError;
Guido van Rossum3c1bb802000-04-27 20:13:50 +0000759 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200760
Jeremy Hyltond8082792003-09-16 19:41:39 +0000761 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +0000762 * the caller fails before initializing str -- unicode_resize()
763 * reads str[0], and the Keep-Alive optimization can keep memory
764 * allocated for str alive across a call to unicode_dealloc(unicode).
765 * We don't want unicode_resize to read uninitialized memory in
766 * that case.
767 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200768 _PyUnicode_WSTR(unicode)[0] = 0;
769 _PyUnicode_WSTR(unicode)[length] = 0;
770 _PyUnicode_WSTR_LENGTH(unicode) = length;
771 _PyUnicode_HASH(unicode) = -1;
772 _PyUnicode_STATE(unicode).interned = 0;
773 _PyUnicode_STATE(unicode).kind = 0;
774 _PyUnicode_STATE(unicode).compact = 0;
775 _PyUnicode_STATE(unicode).ready = 0;
776 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +0200777 _PyUnicode_DATA_ANY(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200778 _PyUnicode_LENGTH(unicode) = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200779 _PyUnicode_UTF8(unicode) = NULL;
780 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner7931d9a2011-11-04 00:22:48 +0100781 assert(_PyUnicode_CheckConsistency((PyObject *)unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000782 return unicode;
Barry Warsaw51ac5802000-03-20 16:36:48 +0000783
Benjamin Peterson29060642009-01-31 22:14:21 +0000784 onError:
Amaury Forgeot d'Arc7888d082008-08-01 01:06:32 +0000785 /* XXX UNREF/NEWREF interface should be more symmetrical */
786 _Py_DEC_REFTOTAL;
Barry Warsaw51ac5802000-03-20 16:36:48 +0000787 _Py_ForgetReference((PyObject *)unicode);
Neil Schemenauer58aa8612002-04-12 03:07:20 +0000788 PyObject_Del(unicode);
Barry Warsaw51ac5802000-03-20 16:36:48 +0000789 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000790}
791
Victor Stinnerf42dc442011-10-02 23:33:16 +0200792static const char*
793unicode_kind_name(PyObject *unicode)
794{
Victor Stinner42dfd712011-10-03 14:41:45 +0200795 /* don't check consistency: unicode_kind_name() is called from
796 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +0200797 if (!PyUnicode_IS_COMPACT(unicode))
798 {
799 if (!PyUnicode_IS_READY(unicode))
800 return "wstr";
801 switch(PyUnicode_KIND(unicode))
802 {
803 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200804 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200805 return "legacy ascii";
806 else
807 return "legacy latin1";
808 case PyUnicode_2BYTE_KIND:
809 return "legacy UCS2";
810 case PyUnicode_4BYTE_KIND:
811 return "legacy UCS4";
812 default:
813 return "<legacy invalid kind>";
814 }
815 }
816 assert(PyUnicode_IS_READY(unicode));
817 switch(PyUnicode_KIND(unicode))
818 {
819 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200820 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200821 return "ascii";
822 else
Victor Stinnera3b334d2011-10-03 13:53:37 +0200823 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200824 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200825 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200826 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200827 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200828 default:
829 return "<invalid compact kind>";
830 }
831}
832
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200833#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +0200834static int unicode_new_new_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200835
836/* Functions wrapping macros for use in debugger */
837char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200838 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200839}
840
841void *_PyUnicode_compact_data(void *unicode) {
842 return _PyUnicode_COMPACT_DATA(unicode);
843}
844void *_PyUnicode_data(void *unicode){
845 printf("obj %p\n", unicode);
846 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
847 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
848 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
849 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
850 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
851 return PyUnicode_DATA(unicode);
852}
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200853
854void
855_PyUnicode_Dump(PyObject *op)
856{
857 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +0200858 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
859 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
860 void *data;
Victor Stinner0d60e872011-10-23 19:47:19 +0200861
Victor Stinnera849a4b2011-10-03 12:12:11 +0200862 if (ascii->state.compact)
Victor Stinner0d60e872011-10-23 19:47:19 +0200863 {
864 if (ascii->state.ascii)
865 data = (ascii + 1);
866 else
867 data = (compact + 1);
868 }
Victor Stinnera849a4b2011-10-03 12:12:11 +0200869 else
870 data = unicode->data.any;
Victor Stinner0d60e872011-10-23 19:47:19 +0200871 printf("%s: len=%zu, ",unicode_kind_name(op), ascii->length);
872
Victor Stinnera849a4b2011-10-03 12:12:11 +0200873 if (ascii->wstr == data)
874 printf("shared ");
875 printf("wstr=%p", ascii->wstr);
Victor Stinner0d60e872011-10-23 19:47:19 +0200876
Victor Stinnera3b334d2011-10-03 13:53:37 +0200877 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinnera849a4b2011-10-03 12:12:11 +0200878 printf(" (%zu), ", compact->wstr_length);
879 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
880 printf("shared ");
881 printf("utf8=%p (%zu)", compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200882 }
Victor Stinnera849a4b2011-10-03 12:12:11 +0200883 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200884}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200885#endif
886
887PyObject *
888PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
889{
890 PyObject *obj;
891 PyCompactUnicodeObject *unicode;
892 void *data;
893 int kind_state;
Victor Stinner9e9d6892011-10-04 01:02:02 +0200894 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200895 Py_ssize_t char_size;
896 Py_ssize_t struct_size;
897
898 /* Optimization for empty strings */
899 if (size == 0 && unicode_empty != NULL) {
900 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200901 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200902 }
903
904#ifdef Py_DEBUG
905 ++unicode_new_new_calls;
906#endif
907
Victor Stinner9e9d6892011-10-04 01:02:02 +0200908 is_ascii = 0;
909 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200910 struct_size = sizeof(PyCompactUnicodeObject);
911 if (maxchar < 128) {
912 kind_state = PyUnicode_1BYTE_KIND;
913 char_size = 1;
914 is_ascii = 1;
915 struct_size = sizeof(PyASCIIObject);
916 }
917 else if (maxchar < 256) {
918 kind_state = PyUnicode_1BYTE_KIND;
919 char_size = 1;
920 }
921 else if (maxchar < 65536) {
922 kind_state = PyUnicode_2BYTE_KIND;
923 char_size = 2;
924 if (sizeof(wchar_t) == 2)
925 is_sharing = 1;
926 }
927 else {
928 kind_state = PyUnicode_4BYTE_KIND;
929 char_size = 4;
930 if (sizeof(wchar_t) == 4)
931 is_sharing = 1;
932 }
933
934 /* Ensure we won't overflow the size. */
935 if (size < 0) {
936 PyErr_SetString(PyExc_SystemError,
937 "Negative size passed to PyUnicode_New");
938 return NULL;
939 }
940 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
941 return PyErr_NoMemory();
942
943 /* Duplicated allocation code from _PyObject_New() instead of a call to
944 * PyObject_New() so we are able to allocate space for the object and
945 * it's data buffer.
946 */
947 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
948 if (obj == NULL)
949 return PyErr_NoMemory();
950 obj = PyObject_INIT(obj, &PyUnicode_Type);
951 if (obj == NULL)
952 return NULL;
953
954 unicode = (PyCompactUnicodeObject *)obj;
955 if (is_ascii)
956 data = ((PyASCIIObject*)obj) + 1;
957 else
958 data = unicode + 1;
959 _PyUnicode_LENGTH(unicode) = size;
960 _PyUnicode_HASH(unicode) = -1;
961 _PyUnicode_STATE(unicode).interned = 0;
962 _PyUnicode_STATE(unicode).kind = kind_state;
963 _PyUnicode_STATE(unicode).compact = 1;
964 _PyUnicode_STATE(unicode).ready = 1;
965 _PyUnicode_STATE(unicode).ascii = is_ascii;
966 if (is_ascii) {
967 ((char*)data)[size] = 0;
968 _PyUnicode_WSTR(unicode) = NULL;
969 }
970 else if (kind_state == PyUnicode_1BYTE_KIND) {
971 ((char*)data)[size] = 0;
972 _PyUnicode_WSTR(unicode) = NULL;
973 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200974 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +0200975 unicode->utf8_length = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200976 }
977 else {
978 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +0200979 unicode->utf8_length = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200980 if (kind_state == PyUnicode_2BYTE_KIND)
981 ((Py_UCS2*)data)[size] = 0;
982 else /* kind_state == PyUnicode_4BYTE_KIND */
983 ((Py_UCS4*)data)[size] = 0;
984 if (is_sharing) {
985 _PyUnicode_WSTR_LENGTH(unicode) = size;
986 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
987 }
988 else {
989 _PyUnicode_WSTR_LENGTH(unicode) = 0;
990 _PyUnicode_WSTR(unicode) = NULL;
991 }
992 }
Victor Stinner7931d9a2011-11-04 00:22:48 +0100993 assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200994 return obj;
995}
996
997#if SIZEOF_WCHAR_T == 2
998/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
999 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +02001000 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001001
1002 This function assumes that unicode can hold one more code point than wstr
1003 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001004static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001005unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001006 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001007{
1008 const wchar_t *iter;
1009 Py_UCS4 *ucs4_out;
1010
Victor Stinner910337b2011-10-03 03:20:16 +02001011 assert(unicode != NULL);
1012 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001013 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1014 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
1015
1016 for (iter = begin; iter < end; ) {
1017 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1018 _PyUnicode_GET_LENGTH(unicode)));
1019 if (*iter >= 0xD800 && *iter <= 0xDBFF
1020 && (iter+1) < end && iter[1] >= 0xDC00 && iter[1] <= 0xDFFF)
1021 {
1022 *ucs4_out++ = (((iter[0] & 0x3FF)<<10) | (iter[1] & 0x3FF)) + 0x10000;
1023 iter += 2;
1024 }
1025 else {
1026 *ucs4_out++ = *iter;
1027 iter++;
1028 }
1029 }
1030 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1031 _PyUnicode_GET_LENGTH(unicode)));
1032
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001033}
1034#endif
1035
Victor Stinnercd9950f2011-10-02 00:34:53 +02001036static int
1037_PyUnicode_Dirty(PyObject *unicode)
1038{
Victor Stinner910337b2011-10-03 03:20:16 +02001039 assert(_PyUnicode_CHECK(unicode));
Victor Stinnercd9950f2011-10-02 00:34:53 +02001040 if (Py_REFCNT(unicode) != 1) {
Victor Stinner01698042011-10-04 00:04:26 +02001041 PyErr_SetString(PyExc_SystemError,
Victor Stinnercd9950f2011-10-02 00:34:53 +02001042 "Cannot modify a string having more than 1 reference");
1043 return -1;
1044 }
1045 _PyUnicode_DIRTY(unicode);
1046 return 0;
1047}
1048
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001049static int
1050_copy_characters(PyObject *to, Py_ssize_t to_start,
1051 PyObject *from, Py_ssize_t from_start,
1052 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001053{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001054 unsigned int from_kind, to_kind;
1055 void *from_data, *to_data;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001056 int fast;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001057
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001058 assert(PyUnicode_Check(from));
1059 assert(PyUnicode_Check(to));
1060 assert(PyUnicode_IS_READY(from));
1061 assert(PyUnicode_IS_READY(to));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001062
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001063 assert(PyUnicode_GET_LENGTH(from) >= how_many);
1064 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1065 assert(0 <= how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001066
Victor Stinnerf5ca1a22011-09-28 23:54:59 +02001067 if (how_many == 0)
1068 return 0;
1069
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001070 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001071 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001072 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001073 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001074
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001075#ifdef Py_DEBUG
1076 if (!check_maxchar
1077 && (from_kind > to_kind
1078 || (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001079 {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001080 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1081 Py_UCS4 ch;
1082 Py_ssize_t i;
1083 for (i=0; i < how_many; i++) {
1084 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1085 assert(ch <= to_maxchar);
1086 }
1087 }
1088#endif
1089 fast = (from_kind == to_kind);
1090 if (check_maxchar
1091 && (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to)))
1092 {
1093 /* deny latin1 => ascii */
1094 fast = 0;
1095 }
1096
1097 if (fast) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001098 Py_MEMCPY((char*)to_data + to_kind * to_start,
1099 (char*)from_data + from_kind * from_start,
1100 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001101 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001102 else if (from_kind == PyUnicode_1BYTE_KIND
1103 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001104 {
1105 _PyUnicode_CONVERT_BYTES(
1106 Py_UCS1, Py_UCS2,
1107 PyUnicode_1BYTE_DATA(from) + from_start,
1108 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1109 PyUnicode_2BYTE_DATA(to) + to_start
1110 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001111 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001112 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001113 && to_kind == PyUnicode_4BYTE_KIND)
1114 {
1115 _PyUnicode_CONVERT_BYTES(
1116 Py_UCS1, Py_UCS4,
1117 PyUnicode_1BYTE_DATA(from) + from_start,
1118 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1119 PyUnicode_4BYTE_DATA(to) + to_start
1120 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001121 }
1122 else if (from_kind == PyUnicode_2BYTE_KIND
1123 && to_kind == PyUnicode_4BYTE_KIND)
1124 {
1125 _PyUnicode_CONVERT_BYTES(
1126 Py_UCS2, Py_UCS4,
1127 PyUnicode_2BYTE_DATA(from) + from_start,
1128 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1129 PyUnicode_4BYTE_DATA(to) + to_start
1130 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001131 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001132 else {
Victor Stinnerf42dc442011-10-02 23:33:16 +02001133 /* check if max_char(from substring) <= max_char(to) */
1134 if (from_kind > to_kind
1135 /* latin1 => ascii */
Victor Stinnerb9275c12011-10-05 14:01:42 +02001136 || (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to)))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001137 {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001138 /* slow path to check for character overflow */
1139 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001140 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001141 Py_ssize_t i;
1142
Victor Stinner56c161a2011-10-06 02:47:11 +02001143#ifdef Py_DEBUG
Victor Stinnera0702ab2011-09-29 14:14:38 +02001144 for (i=0; i < how_many; i++) {
1145 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinner56c161a2011-10-06 02:47:11 +02001146 assert(ch <= to_maxchar);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001147 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1148 }
Victor Stinner56c161a2011-10-06 02:47:11 +02001149#else
1150 if (!check_maxchar) {
1151 for (i=0; i < how_many; i++) {
1152 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1153 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1154 }
1155 }
1156 else {
1157 for (i=0; i < how_many; i++) {
1158 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1159 if (ch > to_maxchar)
1160 return 1;
1161 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1162 }
1163 }
1164#endif
Victor Stinnera0702ab2011-09-29 14:14:38 +02001165 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001166 else {
Victor Stinner56c161a2011-10-06 02:47:11 +02001167 assert(0 && "inconsistent state");
1168 return 1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001169 }
1170 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001171 return 0;
1172}
1173
1174static void
1175copy_characters(PyObject *to, Py_ssize_t to_start,
1176 PyObject *from, Py_ssize_t from_start,
1177 Py_ssize_t how_many)
1178{
1179 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1180}
1181
1182Py_ssize_t
1183PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1184 PyObject *from, Py_ssize_t from_start,
1185 Py_ssize_t how_many)
1186{
1187 int err;
1188
1189 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1190 PyErr_BadInternalCall();
1191 return -1;
1192 }
1193
1194 if (PyUnicode_READY(from))
1195 return -1;
1196 if (PyUnicode_READY(to))
1197 return -1;
1198
1199 how_many = Py_MIN(PyUnicode_GET_LENGTH(from), how_many);
1200 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1201 PyErr_Format(PyExc_SystemError,
1202 "Cannot write %zi characters at %zi "
1203 "in a string of %zi characters",
1204 how_many, to_start, PyUnicode_GET_LENGTH(to));
1205 return -1;
1206 }
1207
1208 if (how_many == 0)
1209 return 0;
1210
1211 if (_PyUnicode_Dirty(to))
1212 return -1;
1213
1214 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1215 if (err) {
1216 PyErr_Format(PyExc_SystemError,
1217 "Cannot copy %s characters "
1218 "into a string of %s characters",
1219 unicode_kind_name(from),
1220 unicode_kind_name(to));
1221 return -1;
1222 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001223 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001224}
1225
Victor Stinner17222162011-09-28 22:15:37 +02001226/* Find the maximum code point and count the number of surrogate pairs so a
1227 correct string length can be computed before converting a string to UCS4.
1228 This function counts single surrogates as a character and not as a pair.
1229
1230 Return 0 on success, or -1 on error. */
1231static int
1232find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1233 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001234{
1235 const wchar_t *iter;
1236
Victor Stinnerc53be962011-10-02 21:33:54 +02001237 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001238 *num_surrogates = 0;
1239 *maxchar = 0;
1240
1241 for (iter = begin; iter < end; ) {
Victor Stinnerae864852011-10-05 14:02:44 +02001242 if (*iter > *maxchar) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001243 *maxchar = *iter;
Victor Stinnerae864852011-10-05 14:02:44 +02001244#if SIZEOF_WCHAR_T != 2
1245 if (*maxchar >= 0x10000)
1246 return 0;
1247#endif
1248 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001249#if SIZEOF_WCHAR_T == 2
1250 if (*iter >= 0xD800 && *iter <= 0xDBFF
1251 && (iter+1) < end && iter[1] >= 0xDC00 && iter[1] <= 0xDFFF)
1252 {
1253 Py_UCS4 surrogate_val;
1254 surrogate_val = (((iter[0] & 0x3FF)<<10)
1255 | (iter[1] & 0x3FF)) + 0x10000;
1256 ++(*num_surrogates);
1257 if (surrogate_val > *maxchar)
1258 *maxchar = surrogate_val;
1259 iter += 2;
1260 }
1261 else
1262 iter++;
1263#else
1264 iter++;
1265#endif
1266 }
1267 return 0;
1268}
1269
1270#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +02001271static int unicode_ready_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001272#endif
1273
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001274static int
1275unicode_ready(PyObject **p_obj, int replace)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001276{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001277 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001278 wchar_t *end;
1279 Py_UCS4 maxchar = 0;
1280 Py_ssize_t num_surrogates;
1281#if SIZEOF_WCHAR_T == 2
1282 Py_ssize_t length_wo_surrogates;
1283#endif
1284
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001285 assert(p_obj != NULL);
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001286 unicode = *p_obj;
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001287
Georg Brandl7597add2011-10-05 16:36:47 +02001288 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001289 strings were created using _PyObject_New() and where no canonical
1290 representation (the str field) has been set yet aka strings
1291 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001292 assert(_PyUnicode_CHECK(unicode));
1293 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001294 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001295 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001296 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001297 /* Actually, it should neither be interned nor be anything else: */
1298 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001299
1300#ifdef Py_DEBUG
1301 ++unicode_ready_calls;
1302#endif
1303
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001304#ifdef Py_DEBUG
1305 assert(!replace || Py_REFCNT(unicode) == 1);
1306#else
1307 if (replace && Py_REFCNT(unicode) != 1)
1308 replace = 0;
1309#endif
1310 if (replace) {
1311 Py_ssize_t len = _PyUnicode_WSTR_LENGTH(unicode);
1312 wchar_t *wstr = _PyUnicode_WSTR(unicode);
1313 /* Optimization for empty strings */
1314 if (len == 0) {
1315 Py_INCREF(unicode_empty);
1316 Py_DECREF(*p_obj);
1317 *p_obj = unicode_empty;
1318 return 0;
1319 }
1320 if (len == 1 && wstr[0] < 256) {
1321 PyObject *latin1_char = get_latin1_char((unsigned char)wstr[0]);
1322 if (latin1_char == NULL)
1323 return -1;
1324 Py_DECREF(*p_obj);
1325 *p_obj = latin1_char;
1326 return 0;
1327 }
1328 }
1329
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001330 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001331 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001332 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001333 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001334
1335 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001336 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1337 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001338 PyErr_NoMemory();
1339 return -1;
1340 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001341 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001342 _PyUnicode_WSTR(unicode), end,
1343 PyUnicode_1BYTE_DATA(unicode));
1344 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1345 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1346 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1347 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001348 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001349 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001350 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001351 }
1352 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001353 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001354 _PyUnicode_UTF8(unicode) = NULL;
1355 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001356 }
1357 PyObject_FREE(_PyUnicode_WSTR(unicode));
1358 _PyUnicode_WSTR(unicode) = NULL;
1359 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1360 }
1361 /* In this case we might have to convert down from 4-byte native
1362 wchar_t to 2-byte unicode. */
1363 else if (maxchar < 65536) {
1364 assert(num_surrogates == 0 &&
1365 "FindMaxCharAndNumSurrogatePairs() messed up");
1366
Victor Stinner506f5922011-09-28 22:34:18 +02001367#if SIZEOF_WCHAR_T == 2
1368 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001369 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001370 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1371 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1372 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001373 _PyUnicode_UTF8(unicode) = NULL;
1374 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001375#else
1376 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001377 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001378 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001379 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001380 PyErr_NoMemory();
1381 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001382 }
Victor Stinner506f5922011-09-28 22:34:18 +02001383 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1384 _PyUnicode_WSTR(unicode), end,
1385 PyUnicode_2BYTE_DATA(unicode));
1386 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1387 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1388 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001389 _PyUnicode_UTF8(unicode) = NULL;
1390 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001391 PyObject_FREE(_PyUnicode_WSTR(unicode));
1392 _PyUnicode_WSTR(unicode) = NULL;
1393 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1394#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001395 }
1396 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1397 else {
1398#if SIZEOF_WCHAR_T == 2
1399 /* in case the native representation is 2-bytes, we need to allocate a
1400 new normalized 4-byte version. */
1401 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001402 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1403 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001404 PyErr_NoMemory();
1405 return -1;
1406 }
1407 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1408 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001409 _PyUnicode_UTF8(unicode) = NULL;
1410 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001411 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1412 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001413 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001414 PyObject_FREE(_PyUnicode_WSTR(unicode));
1415 _PyUnicode_WSTR(unicode) = NULL;
1416 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1417#else
1418 assert(num_surrogates == 0);
1419
Victor Stinnerc3c74152011-10-02 20:39:55 +02001420 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001421 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001422 _PyUnicode_UTF8(unicode) = NULL;
1423 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001424 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1425#endif
1426 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1427 }
1428 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001429 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001430 return 0;
1431}
1432
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001433int
1434_PyUnicode_ReadyReplace(PyObject **op)
1435{
1436 return unicode_ready(op, 1);
1437}
1438
1439int
1440_PyUnicode_Ready(PyObject *op)
1441{
1442 return unicode_ready(&op, 0);
1443}
1444
Alexander Belopolsky40018472011-02-26 01:02:56 +00001445static void
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001446unicode_dealloc(register PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001447{
Walter Dörwald16807132007-05-25 13:52:07 +00001448 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001449 case SSTATE_NOT_INTERNED:
1450 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001451
Benjamin Peterson29060642009-01-31 22:14:21 +00001452 case SSTATE_INTERNED_MORTAL:
1453 /* revive dead object temporarily for DelItem */
1454 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001455 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001456 Py_FatalError(
1457 "deletion of interned string failed");
1458 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001459
Benjamin Peterson29060642009-01-31 22:14:21 +00001460 case SSTATE_INTERNED_IMMORTAL:
1461 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001462
Benjamin Peterson29060642009-01-31 22:14:21 +00001463 default:
1464 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001465 }
1466
Victor Stinner03490912011-10-03 23:45:12 +02001467 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001468 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001469 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001470 PyObject_DEL(_PyUnicode_UTF8(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001471
1472 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinner7931d9a2011-11-04 00:22:48 +01001473 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001474 }
1475 else {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001476 if (_PyUnicode_DATA_ANY(unicode))
1477 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Victor Stinner7931d9a2011-11-04 00:22:48 +01001478 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001479 }
1480}
1481
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001482#ifdef Py_DEBUG
1483static int
1484unicode_is_singleton(PyObject *unicode)
1485{
1486 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1487 if (unicode == unicode_empty)
1488 return 1;
1489 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1490 {
1491 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1492 if (ch < 256 && unicode_latin1[ch] == unicode)
1493 return 1;
1494 }
1495 return 0;
1496}
1497#endif
1498
Alexander Belopolsky40018472011-02-26 01:02:56 +00001499static int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001500unicode_resizable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001501{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001502 if (Py_REFCNT(unicode) != 1)
1503 return 0;
1504 if (PyUnicode_CHECK_INTERNED(unicode))
1505 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001506#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001507 /* singleton refcount is greater than 1 */
1508 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001509#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001510 return 1;
1511}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001512
Victor Stinnerfe226c02011-10-03 03:52:20 +02001513static int
1514unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1515{
1516 PyObject *unicode;
1517 Py_ssize_t old_length;
1518
1519 assert(p_unicode != NULL);
1520 unicode = *p_unicode;
1521
1522 assert(unicode != NULL);
1523 assert(PyUnicode_Check(unicode));
1524 assert(0 <= length);
1525
Victor Stinner910337b2011-10-03 03:20:16 +02001526 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001527 old_length = PyUnicode_WSTR_LENGTH(unicode);
1528 else
1529 old_length = PyUnicode_GET_LENGTH(unicode);
1530 if (old_length == length)
1531 return 0;
1532
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001533 if (length == 0) {
1534 Py_DECREF(*p_unicode);
1535 *p_unicode = unicode_empty;
1536 Py_INCREF(*p_unicode);
1537 return 0;
1538 }
1539
Victor Stinnerfe226c02011-10-03 03:52:20 +02001540 if (!unicode_resizable(unicode)) {
1541 PyObject *copy = resize_copy(unicode, length);
1542 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001543 return -1;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001544 Py_DECREF(*p_unicode);
1545 *p_unicode = copy;
Benjamin Peterson29060642009-01-31 22:14:21 +00001546 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001547 }
1548
Victor Stinnerfe226c02011-10-03 03:52:20 +02001549 if (PyUnicode_IS_COMPACT(unicode)) {
1550 *p_unicode = resize_compact(unicode, length);
1551 if (*p_unicode == NULL)
1552 return -1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001553 assert(_PyUnicode_CheckConsistency(*p_unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001554 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001555 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001556 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001557}
1558
Alexander Belopolsky40018472011-02-26 01:02:56 +00001559int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001560PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001561{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001562 PyObject *unicode;
1563 if (p_unicode == NULL) {
1564 PyErr_BadInternalCall();
1565 return -1;
1566 }
1567 unicode = *p_unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001568 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001569 {
1570 PyErr_BadInternalCall();
1571 return -1;
1572 }
1573 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001574}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001575
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001576static int
Victor Stinner0a045ef2011-11-09 00:02:42 +01001577unicode_widen(PyObject **p_unicode, unsigned int maxchar)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001578{
1579 PyObject *result;
1580 assert(PyUnicode_IS_READY(*p_unicode));
1581 if (maxchar <= PyUnicode_MAX_CHAR_VALUE(*p_unicode))
1582 return 0;
1583 result = PyUnicode_New(PyUnicode_GET_LENGTH(*p_unicode),
1584 maxchar);
1585 if (result == NULL)
1586 return -1;
1587 PyUnicode_CopyCharacters(result, 0, *p_unicode, 0,
1588 PyUnicode_GET_LENGTH(*p_unicode));
1589 Py_DECREF(*p_unicode);
1590 *p_unicode = result;
1591 return 0;
1592}
1593
1594static int
1595unicode_putchar(PyObject **p_unicode, Py_ssize_t *pos,
1596 Py_UCS4 ch)
1597{
1598 if (unicode_widen(p_unicode, ch) < 0)
1599 return -1;
1600 PyUnicode_WRITE(PyUnicode_KIND(*p_unicode),
1601 PyUnicode_DATA(*p_unicode),
1602 (*pos)++, ch);
1603 return 0;
1604}
1605
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001606static PyObject*
1607get_latin1_char(unsigned char ch)
1608{
Victor Stinnera464fc12011-10-02 20:39:30 +02001609 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001610 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001611 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001612 if (!unicode)
1613 return NULL;
1614 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001615 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001616 unicode_latin1[ch] = unicode;
1617 }
1618 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001619 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001620}
1621
Alexander Belopolsky40018472011-02-26 01:02:56 +00001622PyObject *
1623PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001624{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001625 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001626 Py_UCS4 maxchar = 0;
1627 Py_ssize_t num_surrogates;
1628
1629 if (u == NULL)
1630 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001631
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001632 /* If the Unicode data is known at construction time, we can apply
1633 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001634
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001635 /* Optimization for empty strings */
1636 if (size == 0 && unicode_empty != NULL) {
1637 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001638 return unicode_empty;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001639 }
Tim Petersced69f82003-09-16 20:30:58 +00001640
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001641 /* Single character Unicode objects in the Latin-1 range are
1642 shared when using this constructor */
1643 if (size == 1 && *u < 256)
1644 return get_latin1_char((unsigned char)*u);
1645
1646 /* If not empty and not single character, copy the Unicode data
1647 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02001648 if (find_maxchar_surrogates(u, u + size,
1649 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001650 return NULL;
1651
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001652 unicode = PyUnicode_New(size - num_surrogates,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001653 maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001654 if (!unicode)
1655 return NULL;
1656
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001657 switch (PyUnicode_KIND(unicode)) {
1658 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001659 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001660 u, u + size, PyUnicode_1BYTE_DATA(unicode));
1661 break;
1662 case PyUnicode_2BYTE_KIND:
1663#if Py_UNICODE_SIZE == 2
1664 Py_MEMCPY(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
1665#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001666 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001667 u, u + size, PyUnicode_2BYTE_DATA(unicode));
1668#endif
1669 break;
1670 case PyUnicode_4BYTE_KIND:
1671#if SIZEOF_WCHAR_T == 2
1672 /* This is the only case which has to process surrogates, thus
1673 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001674 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001675#else
1676 assert(num_surrogates == 0);
1677 Py_MEMCPY(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
1678#endif
1679 break;
1680 default:
1681 assert(0 && "Impossible state");
1682 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001683
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001684 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001685 return unicode;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001686}
1687
Alexander Belopolsky40018472011-02-26 01:02:56 +00001688PyObject *
1689PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001690{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001691 if (size < 0) {
1692 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00001693 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00001694 return NULL;
1695 }
Christian Heimes33fe8092008-04-13 13:53:33 +00001696
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001697 /* If the Unicode data is known at construction time, we can apply
Martin v. Löwis9c121062007-08-05 20:26:11 +00001698 some optimizations which share commonly used objects.
1699 Also, this means the input must be UTF-8, so fall back to the
1700 UTF-8 decoder at the end. */
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001701 if (u != NULL) {
1702
Benjamin Peterson29060642009-01-31 22:14:21 +00001703 /* Optimization for empty strings */
1704 if (size == 0 && unicode_empty != NULL) {
1705 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001706 return unicode_empty;
Benjamin Peterson14339b62009-01-31 16:36:08 +00001707 }
Benjamin Peterson29060642009-01-31 22:14:21 +00001708
1709 /* Single characters are shared when using this constructor.
1710 Restrict to ASCII, since the input must be UTF-8. */
Victor Stinner9faa3842011-10-23 20:06:00 +02001711 if (size == 1 && (unsigned char)*u < 128)
1712 return get_latin1_char((unsigned char)*u);
Martin v. Löwis9c121062007-08-05 20:26:11 +00001713
1714 return PyUnicode_DecodeUTF8(u, size, NULL);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001715 }
1716
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001717 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001718}
1719
Alexander Belopolsky40018472011-02-26 01:02:56 +00001720PyObject *
1721PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00001722{
1723 size_t size = strlen(u);
1724 if (size > PY_SSIZE_T_MAX) {
1725 PyErr_SetString(PyExc_OverflowError, "input too long");
1726 return NULL;
1727 }
1728
1729 return PyUnicode_FromStringAndSize(u, size);
1730}
1731
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001732PyObject *
1733_PyUnicode_FromId(_Py_Identifier *id)
1734{
1735 if (!id->object) {
1736 id->object = PyUnicode_FromString(id->string);
1737 if (!id->object)
1738 return NULL;
1739 PyUnicode_InternInPlace(&id->object);
1740 assert(!id->next);
1741 id->next = static_strings;
1742 static_strings = id;
1743 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001744 return id->object;
1745}
1746
1747void
1748_PyUnicode_ClearStaticStrings()
1749{
1750 _Py_Identifier *i;
1751 for (i = static_strings; i; i = i->next) {
1752 Py_DECREF(i->object);
1753 i->object = NULL;
1754 i->next = NULL;
1755 }
1756}
1757
Victor Stinnere57b1c02011-09-28 22:20:48 +02001758static PyObject*
Victor Stinner0617b6e2011-10-05 23:26:01 +02001759unicode_fromascii(const unsigned char* s, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02001760{
Victor Stinner0617b6e2011-10-05 23:26:01 +02001761 PyObject *res;
1762#ifdef Py_DEBUG
1763 const unsigned char *p;
1764 const unsigned char *end = s + size;
1765 for (p=s; p < end; p++) {
1766 assert(*p < 128);
1767 }
1768#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001769 if (size == 1)
1770 return get_latin1_char(s[0]);
Victor Stinner0617b6e2011-10-05 23:26:01 +02001771 res = PyUnicode_New(size, 127);
Victor Stinner702c7342011-10-05 13:50:52 +02001772 if (!res)
1773 return NULL;
Victor Stinner0617b6e2011-10-05 23:26:01 +02001774 memcpy(PyUnicode_1BYTE_DATA(res), s, size);
Victor Stinner702c7342011-10-05 13:50:52 +02001775 return res;
1776}
1777
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001778static Py_UCS4
1779kind_maxchar_limit(unsigned int kind)
1780{
1781 switch(kind) {
1782 case PyUnicode_1BYTE_KIND:
1783 return 0x80;
1784 case PyUnicode_2BYTE_KIND:
1785 return 0x100;
1786 case PyUnicode_4BYTE_KIND:
1787 return 0x10000;
1788 default:
1789 assert(0 && "invalid kind");
1790 return 0x10ffff;
1791 }
1792}
1793
Victor Stinner702c7342011-10-05 13:50:52 +02001794static PyObject*
Victor Stinnere57b1c02011-09-28 22:20:48 +02001795_PyUnicode_FromUCS1(const unsigned char* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00001796{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001797 PyObject *res;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001798 unsigned char max_char = 127;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001799
1800 assert(size >= 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001801 if (size == 1)
1802 return get_latin1_char(u[0]);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001803 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001804 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001805 if (!res)
1806 return NULL;
1807 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001808 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001809 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001810}
1811
Victor Stinnere57b1c02011-09-28 22:20:48 +02001812static PyObject*
1813_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001814{
1815 PyObject *res;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001816 Py_UCS2 max_char = 0;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001817
1818 assert(size >= 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001819 if (size == 1 && u[0] < 256)
Victor Stinner4e101002011-10-11 23:27:52 +02001820 return get_latin1_char((unsigned char)u[0]);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001821 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001822 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001823 if (!res)
1824 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001825 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001826 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001827 else {
1828 _PyUnicode_CONVERT_BYTES(
1829 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
1830 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001831 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001832 return res;
1833}
1834
Victor Stinnere57b1c02011-09-28 22:20:48 +02001835static PyObject*
1836_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001837{
1838 PyObject *res;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001839 Py_UCS4 max_char = 0;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001840
1841 assert(size >= 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001842 if (size == 1 && u[0] < 256)
1843 return get_latin1_char(u[0]);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001844 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001845 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001846 if (!res)
1847 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02001848 if (max_char < 256)
1849 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
1850 PyUnicode_1BYTE_DATA(res));
1851 else if (max_char < 0x10000)
1852 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
1853 PyUnicode_2BYTE_DATA(res));
1854 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001855 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001856 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001857 return res;
1858}
1859
1860PyObject*
1861PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
1862{
1863 switch(kind) {
1864 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001865 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001866 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001867 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001868 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001869 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001870 default:
1871 assert(0 && "invalid kind");
1872 PyErr_SetString(PyExc_SystemError, "invalid kind");
1873 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001874 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001875}
1876
Victor Stinner25a4b292011-10-06 12:31:55 +02001877/* Ensure that a string uses the most efficient storage, if it is not the
1878 case: create a new string with of the right kind. Write NULL into *p_unicode
1879 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02001880static void
Victor Stinner25a4b292011-10-06 12:31:55 +02001881unicode_adjust_maxchar(PyObject **p_unicode)
1882{
1883 PyObject *unicode, *copy;
1884 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001885 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02001886 unsigned int kind;
1887
1888 assert(p_unicode != NULL);
1889 unicode = *p_unicode;
1890 assert(PyUnicode_IS_READY(unicode));
1891 if (PyUnicode_IS_ASCII(unicode))
1892 return;
1893
1894 len = PyUnicode_GET_LENGTH(unicode);
1895 kind = PyUnicode_KIND(unicode);
1896 if (kind == PyUnicode_1BYTE_KIND) {
1897 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001898 max_char = ucs1lib_find_max_char(u, u + len);
1899 if (max_char >= 128)
1900 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001901 }
1902 else if (kind == PyUnicode_2BYTE_KIND) {
1903 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001904 max_char = ucs2lib_find_max_char(u, u + len);
1905 if (max_char >= 256)
1906 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001907 }
1908 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001909 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02001910 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001911 max_char = ucs4lib_find_max_char(u, u + len);
1912 if (max_char >= 0x10000)
1913 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001914 }
Victor Stinner25a4b292011-10-06 12:31:55 +02001915 copy = PyUnicode_New(len, max_char);
1916 copy_characters(copy, 0, unicode, 0, len);
1917 Py_DECREF(unicode);
1918 *p_unicode = copy;
1919}
1920
Victor Stinner034f6cf2011-09-30 02:26:44 +02001921PyObject*
1922PyUnicode_Copy(PyObject *unicode)
1923{
Victor Stinner87af4f22011-11-21 23:03:47 +01001924 Py_ssize_t length;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001925 PyObject *copy;
1926 void *data;
1927
Victor Stinner034f6cf2011-09-30 02:26:44 +02001928 if (!PyUnicode_Check(unicode)) {
1929 PyErr_BadInternalCall();
1930 return NULL;
1931 }
1932 if (PyUnicode_READY(unicode))
1933 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001934
Victor Stinner87af4f22011-11-21 23:03:47 +01001935 length = PyUnicode_GET_LENGTH(unicode);
1936 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001937 if (!copy)
1938 return NULL;
1939 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
1940
1941 data = PyUnicode_DATA(unicode);
Victor Stinner87af4f22011-11-21 23:03:47 +01001942 Py_MEMCPY(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
1943 length * PyUnicode_KIND(unicode));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001944 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001945 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02001946}
1947
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001948
Victor Stinnerbc603d12011-10-02 01:00:40 +02001949/* Widen Unicode objects to larger buffers. Don't write terminating null
1950 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001951
1952void*
1953_PyUnicode_AsKind(PyObject *s, unsigned int kind)
1954{
Victor Stinnerbc603d12011-10-02 01:00:40 +02001955 Py_ssize_t len;
1956 void *result;
1957 unsigned int skind;
1958
1959 if (PyUnicode_READY(s))
1960 return NULL;
1961
1962 len = PyUnicode_GET_LENGTH(s);
1963 skind = PyUnicode_KIND(s);
1964 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02001965 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001966 return NULL;
1967 }
1968 switch(kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02001969 case PyUnicode_2BYTE_KIND:
1970 result = PyMem_Malloc(len * sizeof(Py_UCS2));
1971 if (!result)
1972 return PyErr_NoMemory();
1973 assert(skind == PyUnicode_1BYTE_KIND);
1974 _PyUnicode_CONVERT_BYTES(
1975 Py_UCS1, Py_UCS2,
1976 PyUnicode_1BYTE_DATA(s),
1977 PyUnicode_1BYTE_DATA(s) + len,
1978 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001979 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02001980 case PyUnicode_4BYTE_KIND:
1981 result = PyMem_Malloc(len * sizeof(Py_UCS4));
1982 if (!result)
1983 return PyErr_NoMemory();
1984 if (skind == PyUnicode_2BYTE_KIND) {
1985 _PyUnicode_CONVERT_BYTES(
1986 Py_UCS2, Py_UCS4,
1987 PyUnicode_2BYTE_DATA(s),
1988 PyUnicode_2BYTE_DATA(s) + len,
1989 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001990 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02001991 else {
1992 assert(skind == PyUnicode_1BYTE_KIND);
1993 _PyUnicode_CONVERT_BYTES(
1994 Py_UCS1, Py_UCS4,
1995 PyUnicode_1BYTE_DATA(s),
1996 PyUnicode_1BYTE_DATA(s) + len,
1997 result);
1998 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001999 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002000 default:
2001 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002002 }
Victor Stinner01698042011-10-04 00:04:26 +02002003 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002004 return NULL;
2005}
2006
2007static Py_UCS4*
2008as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2009 int copy_null)
2010{
2011 int kind;
2012 void *data;
2013 Py_ssize_t len, targetlen;
2014 if (PyUnicode_READY(string) == -1)
2015 return NULL;
2016 kind = PyUnicode_KIND(string);
2017 data = PyUnicode_DATA(string);
2018 len = PyUnicode_GET_LENGTH(string);
2019 targetlen = len;
2020 if (copy_null)
2021 targetlen++;
2022 if (!target) {
2023 if (PY_SSIZE_T_MAX / sizeof(Py_UCS4) < targetlen) {
2024 PyErr_NoMemory();
2025 return NULL;
2026 }
2027 target = PyMem_Malloc(targetlen * sizeof(Py_UCS4));
2028 if (!target) {
2029 PyErr_NoMemory();
2030 return NULL;
2031 }
2032 }
2033 else {
2034 if (targetsize < targetlen) {
2035 PyErr_Format(PyExc_SystemError,
2036 "string is longer than the buffer");
2037 if (copy_null && 0 < targetsize)
2038 target[0] = 0;
2039 return NULL;
2040 }
2041 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002042 if (kind == PyUnicode_1BYTE_KIND) {
2043 Py_UCS1 *start = (Py_UCS1 *) data;
2044 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002045 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002046 else if (kind == PyUnicode_2BYTE_KIND) {
2047 Py_UCS2 *start = (Py_UCS2 *) data;
2048 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2049 }
2050 else {
2051 assert(kind == PyUnicode_4BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002052 Py_MEMCPY(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002053 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002054 if (copy_null)
2055 target[len] = 0;
2056 return target;
2057}
2058
2059Py_UCS4*
2060PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2061 int copy_null)
2062{
Antoine Pitroude20b0b2011-11-10 21:47:38 +01002063 if (target == NULL || targetsize < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002064 PyErr_BadInternalCall();
2065 return NULL;
2066 }
2067 return as_ucs4(string, target, targetsize, copy_null);
2068}
2069
2070Py_UCS4*
2071PyUnicode_AsUCS4Copy(PyObject *string)
2072{
2073 return as_ucs4(string, NULL, 0, 1);
2074}
2075
2076#ifdef HAVE_WCHAR_H
Mark Dickinson081dfee2009-03-18 14:47:41 +00002077
Alexander Belopolsky40018472011-02-26 01:02:56 +00002078PyObject *
2079PyUnicode_FromWideChar(register const wchar_t *w, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002080{
Guido van Rossumd57fd912000-03-10 22:53:23 +00002081 if (w == NULL) {
Martin v. Löwis790465f2008-04-05 20:41:37 +00002082 if (size == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002083 return PyUnicode_New(0, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00002084 PyErr_BadInternalCall();
2085 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002086 }
2087
Martin v. Löwis790465f2008-04-05 20:41:37 +00002088 if (size == -1) {
2089 size = wcslen(w);
2090 }
2091
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002092 return PyUnicode_FromUnicode(w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002093}
2094
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002095#endif /* HAVE_WCHAR_H */
Mark Dickinson081dfee2009-03-18 14:47:41 +00002096
Walter Dörwald346737f2007-05-31 10:44:43 +00002097static void
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002098makefmt(char *fmt, int longflag, int longlongflag, int size_tflag,
2099 int zeropad, int width, int precision, char c)
Walter Dörwald346737f2007-05-31 10:44:43 +00002100{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002101 *fmt++ = '%';
2102 if (width) {
2103 if (zeropad)
2104 *fmt++ = '0';
2105 fmt += sprintf(fmt, "%d", width);
2106 }
2107 if (precision)
2108 fmt += sprintf(fmt, ".%d", precision);
2109 if (longflag)
2110 *fmt++ = 'l';
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002111 else if (longlongflag) {
2112 /* longlongflag should only ever be nonzero on machines with
2113 HAVE_LONG_LONG defined */
2114#ifdef HAVE_LONG_LONG
2115 char *f = PY_FORMAT_LONG_LONG;
2116 while (*f)
2117 *fmt++ = *f++;
2118#else
2119 /* we shouldn't ever get here */
2120 assert(0);
2121 *fmt++ = 'l';
2122#endif
2123 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002124 else if (size_tflag) {
2125 char *f = PY_FORMAT_SIZE_T;
2126 while (*f)
2127 *fmt++ = *f++;
2128 }
2129 *fmt++ = c;
2130 *fmt = '\0';
Walter Dörwald346737f2007-05-31 10:44:43 +00002131}
2132
Victor Stinner96865452011-03-01 23:44:09 +00002133/* helper for PyUnicode_FromFormatV() */
2134
2135static const char*
2136parse_format_flags(const char *f,
2137 int *p_width, int *p_precision,
2138 int *p_longflag, int *p_longlongflag, int *p_size_tflag)
2139{
2140 int width, precision, longflag, longlongflag, size_tflag;
2141
2142 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
2143 f++;
2144 width = 0;
2145 while (Py_ISDIGIT((unsigned)*f))
2146 width = (width*10) + *f++ - '0';
2147 precision = 0;
2148 if (*f == '.') {
2149 f++;
2150 while (Py_ISDIGIT((unsigned)*f))
2151 precision = (precision*10) + *f++ - '0';
2152 if (*f == '%') {
2153 /* "%.3%s" => f points to "3" */
2154 f--;
2155 }
2156 }
2157 if (*f == '\0') {
2158 /* bogus format "%.1" => go backward, f points to "1" */
2159 f--;
2160 }
2161 if (p_width != NULL)
2162 *p_width = width;
2163 if (p_precision != NULL)
2164 *p_precision = precision;
2165
2166 /* Handle %ld, %lu, %lld and %llu. */
2167 longflag = 0;
2168 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002169 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002170
2171 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002172 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002173 longflag = 1;
2174 ++f;
2175 }
2176#ifdef HAVE_LONG_LONG
2177 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002178 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002179 longlongflag = 1;
2180 f += 2;
2181 }
2182#endif
2183 }
2184 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002185 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002186 size_tflag = 1;
2187 ++f;
2188 }
2189 if (p_longflag != NULL)
2190 *p_longflag = longflag;
2191 if (p_longlongflag != NULL)
2192 *p_longlongflag = longlongflag;
2193 if (p_size_tflag != NULL)
2194 *p_size_tflag = size_tflag;
2195 return f;
2196}
2197
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002198/* maximum number of characters required for output of %ld. 21 characters
2199 allows for 64-bit integers (in decimal) and an optional sign. */
2200#define MAX_LONG_CHARS 21
2201/* maximum number of characters required for output of %lld.
2202 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2203 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2204#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
2205
Walter Dörwaldd2034312007-05-18 16:29:38 +00002206PyObject *
2207PyUnicode_FromFormatV(const char *format, va_list vargs)
2208{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002209 va_list count;
2210 Py_ssize_t callcount = 0;
2211 PyObject **callresults = NULL;
2212 PyObject **callresult = NULL;
2213 Py_ssize_t n = 0;
2214 int width = 0;
2215 int precision = 0;
2216 int zeropad;
2217 const char* f;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002218 PyObject *string;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002219 /* used by sprintf */
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002220 char fmt[61]; /* should be enough for %0width.precisionlld */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002221 Py_UCS4 maxchar = 127; /* result is ASCII by default */
2222 Py_UCS4 argmaxchar;
2223 Py_ssize_t numbersize = 0;
2224 char *numberresults = NULL;
2225 char *numberresult = NULL;
2226 Py_ssize_t i;
2227 int kind;
2228 void *data;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002229
Victor Stinner4a2b7a12010-08-13 14:03:48 +00002230 Py_VA_COPY(count, vargs);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002231 /* step 1: count the number of %S/%R/%A/%s format specifications
2232 * (we call PyObject_Str()/PyObject_Repr()/PyObject_ASCII()/
2233 * PyUnicode_DecodeUTF8() for these objects once during step 3 and put the
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002234 * result in an array)
Georg Brandl7597add2011-10-05 16:36:47 +02002235 * also estimate a upper bound for all the number formats in the string,
2236 * numbers will be formatted in step 3 and be kept in a '\0'-separated
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002237 * buffer before putting everything together. */
Benjamin Peterson14339b62009-01-31 16:36:08 +00002238 for (f = format; *f; f++) {
2239 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002240 int longlongflag;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002241 /* skip width or width.precision (eg. "1.2" of "%1.2f") */
2242 f = parse_format_flags(f, &width, NULL, NULL, &longlongflag, NULL);
2243 if (*f == 's' || *f=='S' || *f=='R' || *f=='A' || *f=='V')
2244 ++callcount;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002245
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002246 else if (*f == 'd' || *f=='u' || *f=='i' || *f=='x' || *f=='p') {
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002247#ifdef HAVE_LONG_LONG
2248 if (longlongflag) {
2249 if (width < MAX_LONG_LONG_CHARS)
2250 width = MAX_LONG_LONG_CHARS;
2251 }
2252 else
2253#endif
2254 /* MAX_LONG_CHARS is enough to hold a 64-bit integer,
2255 including sign. Decimal takes the most space. This
2256 isn't enough for octal. If a width is specified we
2257 need more (which we allocate later). */
2258 if (width < MAX_LONG_CHARS)
2259 width = MAX_LONG_CHARS;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002260
2261 /* account for the size + '\0' to separate numbers
2262 inside of the numberresults buffer */
2263 numbersize += (width + 1);
2264 }
2265 }
2266 else if ((unsigned char)*f > 127) {
2267 PyErr_Format(PyExc_ValueError,
2268 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2269 "string, got a non-ASCII byte: 0x%02x",
2270 (unsigned char)*f);
2271 return NULL;
2272 }
2273 }
2274 /* step 2: allocate memory for the results of
2275 * PyObject_Str()/PyObject_Repr()/PyUnicode_DecodeUTF8() calls */
2276 if (callcount) {
2277 callresults = PyObject_Malloc(sizeof(PyObject *) * callcount);
2278 if (!callresults) {
2279 PyErr_NoMemory();
2280 return NULL;
2281 }
2282 callresult = callresults;
2283 }
2284 /* step 2.5: allocate memory for the results of formating numbers */
2285 if (numbersize) {
2286 numberresults = PyObject_Malloc(numbersize);
2287 if (!numberresults) {
2288 PyErr_NoMemory();
2289 goto fail;
2290 }
2291 numberresult = numberresults;
2292 }
2293
2294 /* step 3: format numbers and figure out how large a buffer we need */
2295 for (f = format; *f; f++) {
2296 if (*f == '%') {
2297 const char* p;
2298 int longflag;
2299 int longlongflag;
2300 int size_tflag;
2301 int numprinted;
2302
2303 p = f;
2304 zeropad = (f[1] == '0');
2305 f = parse_format_flags(f, &width, &precision,
2306 &longflag, &longlongflag, &size_tflag);
2307 switch (*f) {
2308 case 'c':
2309 {
2310 Py_UCS4 ordinal = va_arg(count, int);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002311 maxchar = Py_MAX(maxchar, ordinal);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002312 n++;
2313 break;
2314 }
2315 case '%':
2316 n++;
2317 break;
2318 case 'i':
2319 case 'd':
2320 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2321 width, precision, *f);
2322 if (longflag)
2323 numprinted = sprintf(numberresult, fmt,
2324 va_arg(count, long));
2325#ifdef HAVE_LONG_LONG
2326 else if (longlongflag)
2327 numprinted = sprintf(numberresult, fmt,
2328 va_arg(count, PY_LONG_LONG));
2329#endif
2330 else if (size_tflag)
2331 numprinted = sprintf(numberresult, fmt,
2332 va_arg(count, Py_ssize_t));
2333 else
2334 numprinted = sprintf(numberresult, fmt,
2335 va_arg(count, int));
2336 n += numprinted;
2337 /* advance by +1 to skip over the '\0' */
2338 numberresult += (numprinted + 1);
2339 assert(*(numberresult - 1) == '\0');
2340 assert(*(numberresult - 2) != '\0');
2341 assert(numprinted >= 0);
2342 assert(numberresult <= numberresults + numbersize);
2343 break;
2344 case 'u':
2345 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2346 width, precision, 'u');
2347 if (longflag)
2348 numprinted = sprintf(numberresult, fmt,
2349 va_arg(count, unsigned long));
2350#ifdef HAVE_LONG_LONG
2351 else if (longlongflag)
2352 numprinted = sprintf(numberresult, fmt,
2353 va_arg(count, unsigned PY_LONG_LONG));
2354#endif
2355 else if (size_tflag)
2356 numprinted = sprintf(numberresult, fmt,
2357 va_arg(count, size_t));
2358 else
2359 numprinted = sprintf(numberresult, fmt,
2360 va_arg(count, unsigned int));
2361 n += numprinted;
2362 numberresult += (numprinted + 1);
2363 assert(*(numberresult - 1) == '\0');
2364 assert(*(numberresult - 2) != '\0');
2365 assert(numprinted >= 0);
2366 assert(numberresult <= numberresults + numbersize);
2367 break;
2368 case 'x':
2369 makefmt(fmt, 0, 0, 0, zeropad, width, precision, 'x');
2370 numprinted = sprintf(numberresult, fmt, va_arg(count, int));
2371 n += numprinted;
2372 numberresult += (numprinted + 1);
2373 assert(*(numberresult - 1) == '\0');
2374 assert(*(numberresult - 2) != '\0');
2375 assert(numprinted >= 0);
2376 assert(numberresult <= numberresults + numbersize);
2377 break;
2378 case 'p':
2379 numprinted = sprintf(numberresult, "%p", va_arg(count, void*));
2380 /* %p is ill-defined: ensure leading 0x. */
2381 if (numberresult[1] == 'X')
2382 numberresult[1] = 'x';
2383 else if (numberresult[1] != 'x') {
2384 memmove(numberresult + 2, numberresult,
2385 strlen(numberresult) + 1);
2386 numberresult[0] = '0';
2387 numberresult[1] = 'x';
2388 numprinted += 2;
2389 }
2390 n += numprinted;
2391 numberresult += (numprinted + 1);
2392 assert(*(numberresult - 1) == '\0');
2393 assert(*(numberresult - 2) != '\0');
2394 assert(numprinted >= 0);
2395 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002396 break;
2397 case 's':
2398 {
2399 /* UTF-8 */
Georg Brandl780b2a62009-05-05 09:19:59 +00002400 const char *s = va_arg(count, const char*);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002401 PyObject *str = PyUnicode_DecodeUTF8(s, strlen(s), "replace");
2402 if (!str)
2403 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002404 /* since PyUnicode_DecodeUTF8 returns already flexible
2405 unicode objects, there is no need to call ready on them */
2406 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002407 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002408 n += PyUnicode_GET_LENGTH(str);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002409 /* Remember the str and switch to the next slot */
2410 *callresult++ = str;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002411 break;
2412 }
2413 case 'U':
2414 {
2415 PyObject *obj = va_arg(count, PyObject *);
Victor Stinner910337b2011-10-03 03:20:16 +02002416 assert(obj && _PyUnicode_CHECK(obj));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002417 if (PyUnicode_READY(obj) == -1)
2418 goto fail;
2419 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002420 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002421 n += PyUnicode_GET_LENGTH(obj);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002422 break;
2423 }
2424 case 'V':
2425 {
2426 PyObject *obj = va_arg(count, PyObject *);
2427 const char *str = va_arg(count, const char *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002428 PyObject *str_obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002429 assert(obj || str);
Victor Stinner910337b2011-10-03 03:20:16 +02002430 assert(!obj || _PyUnicode_CHECK(obj));
Victor Stinner2512a8b2011-03-01 22:46:52 +00002431 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002432 if (PyUnicode_READY(obj) == -1)
2433 goto fail;
2434 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002435 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002436 n += PyUnicode_GET_LENGTH(obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002437 *callresult++ = NULL;
2438 }
2439 else {
2440 str_obj = PyUnicode_DecodeUTF8(str, strlen(str), "replace");
2441 if (!str_obj)
2442 goto fail;
Victor Stinnere1335c72011-10-04 20:53:03 +02002443 if (PyUnicode_READY(str_obj)) {
2444 Py_DECREF(str_obj);
2445 goto fail;
2446 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002447 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002448 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002449 n += PyUnicode_GET_LENGTH(str_obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002450 *callresult++ = str_obj;
2451 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002452 break;
2453 }
2454 case 'S':
2455 {
2456 PyObject *obj = va_arg(count, PyObject *);
2457 PyObject *str;
2458 assert(obj);
2459 str = PyObject_Str(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002460 if (!str || PyUnicode_READY(str) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002461 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002462 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002463 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002464 n += PyUnicode_GET_LENGTH(str);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002465 /* Remember the str and switch to the next slot */
2466 *callresult++ = str;
2467 break;
2468 }
2469 case 'R':
2470 {
2471 PyObject *obj = va_arg(count, PyObject *);
2472 PyObject *repr;
2473 assert(obj);
2474 repr = PyObject_Repr(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002475 if (!repr || PyUnicode_READY(repr) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002476 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002477 argmaxchar = PyUnicode_MAX_CHAR_VALUE(repr);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002478 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002479 n += PyUnicode_GET_LENGTH(repr);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002480 /* Remember the repr and switch to the next slot */
2481 *callresult++ = repr;
2482 break;
2483 }
2484 case 'A':
2485 {
2486 PyObject *obj = va_arg(count, PyObject *);
2487 PyObject *ascii;
2488 assert(obj);
2489 ascii = PyObject_ASCII(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002490 if (!ascii || PyUnicode_READY(ascii) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002491 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002492 argmaxchar = PyUnicode_MAX_CHAR_VALUE(ascii);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002493 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002494 n += PyUnicode_GET_LENGTH(ascii);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002495 /* Remember the repr and switch to the next slot */
2496 *callresult++ = ascii;
2497 break;
2498 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002499 default:
2500 /* if we stumble upon an unknown
2501 formatting code, copy the rest of
2502 the format string to the output
2503 string. (we cannot just skip the
2504 code, since there's no way to know
2505 what's in the argument list) */
2506 n += strlen(p);
2507 goto expand;
2508 }
2509 } else
2510 n++;
2511 }
Benjamin Peterson29060642009-01-31 22:14:21 +00002512 expand:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002513 /* step 4: fill the buffer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002514 /* Since we've analyzed how much space we need,
Benjamin Peterson14339b62009-01-31 16:36:08 +00002515 we don't have to resize the string.
2516 There can be no errors beyond this point. */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002517 string = PyUnicode_New(n, maxchar);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002518 if (!string)
2519 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002520 kind = PyUnicode_KIND(string);
2521 data = PyUnicode_DATA(string);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002522 callresult = callresults;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002523 numberresult = numberresults;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002524
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002525 for (i = 0, f = format; *f; f++) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002526 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002527 const char* p;
Victor Stinner96865452011-03-01 23:44:09 +00002528
2529 p = f;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002530 f = parse_format_flags(f, NULL, NULL, NULL, NULL, NULL);
2531 /* checking for == because the last argument could be a empty
2532 string, which causes i to point to end, the assert at the end of
2533 the loop */
2534 assert(i <= PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002535
Benjamin Peterson14339b62009-01-31 16:36:08 +00002536 switch (*f) {
2537 case 'c':
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002538 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002539 const int ordinal = va_arg(vargs, int);
2540 PyUnicode_WRITE(kind, data, i++, ordinal);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002541 break;
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002542 }
Victor Stinner6d970f42011-03-02 00:04:25 +00002543 case 'i':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002544 case 'd':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002545 case 'u':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002546 case 'x':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002547 case 'p':
2548 /* unused, since we already have the result */
2549 if (*f == 'p')
2550 (void) va_arg(vargs, void *);
2551 else
2552 (void) va_arg(vargs, int);
2553 /* extract the result from numberresults and append. */
2554 for (; *numberresult; ++i, ++numberresult)
2555 PyUnicode_WRITE(kind, data, i, *numberresult);
2556 /* skip over the separating '\0' */
2557 assert(*numberresult == '\0');
2558 numberresult++;
2559 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002560 break;
2561 case 's':
2562 {
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002563 /* unused, since we already have the result */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002564 Py_ssize_t size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002565 (void) va_arg(vargs, char *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002566 size = PyUnicode_GET_LENGTH(*callresult);
2567 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002568 copy_characters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002569 i += size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002570 /* We're done with the unicode()/repr() => forget it */
2571 Py_DECREF(*callresult);
2572 /* switch to next unicode()/repr() result */
2573 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002574 break;
2575 }
2576 case 'U':
2577 {
2578 PyObject *obj = va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002579 Py_ssize_t size;
2580 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
2581 size = PyUnicode_GET_LENGTH(obj);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002582 copy_characters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002583 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002584 break;
2585 }
2586 case 'V':
2587 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002588 Py_ssize_t size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002589 PyObject *obj = va_arg(vargs, PyObject *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002590 va_arg(vargs, const char *);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002591 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002592 size = PyUnicode_GET_LENGTH(obj);
2593 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002594 copy_characters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002595 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002596 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002597 size = PyUnicode_GET_LENGTH(*callresult);
2598 assert(PyUnicode_KIND(*callresult) <=
2599 PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002600 copy_characters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002601 i += size;
Victor Stinner2512a8b2011-03-01 22:46:52 +00002602 Py_DECREF(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002603 }
Victor Stinner2512a8b2011-03-01 22:46:52 +00002604 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002605 break;
2606 }
2607 case 'S':
2608 case 'R':
Victor Stinner9a909002010-10-18 20:59:24 +00002609 case 'A':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002610 {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002611 Py_ssize_t size = PyUnicode_GET_LENGTH(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002612 /* unused, since we already have the result */
2613 (void) va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002614 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002615 copy_characters(string, i, *callresult, 0, size);
2616 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002617 /* We're done with the unicode()/repr() => forget it */
2618 Py_DECREF(*callresult);
2619 /* switch to next unicode()/repr() result */
2620 ++callresult;
2621 break;
2622 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002623 case '%':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002624 PyUnicode_WRITE(kind, data, i++, '%');
Benjamin Peterson14339b62009-01-31 16:36:08 +00002625 break;
2626 default:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002627 for (; *p; ++p, ++i)
2628 PyUnicode_WRITE(kind, data, i, *p);
2629 assert(i == PyUnicode_GET_LENGTH(string));
Benjamin Peterson14339b62009-01-31 16:36:08 +00002630 goto end;
2631 }
Victor Stinner1205f272010-09-11 00:54:47 +00002632 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002633 else {
2634 assert(i < PyUnicode_GET_LENGTH(string));
2635 PyUnicode_WRITE(kind, data, i++, *f);
2636 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002637 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002638 assert(i == PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002639
Benjamin Peterson29060642009-01-31 22:14:21 +00002640 end:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002641 if (callresults)
2642 PyObject_Free(callresults);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002643 if (numberresults)
2644 PyObject_Free(numberresults);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002645 assert(_PyUnicode_CheckConsistency(string, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01002646 return string;
Benjamin Peterson29060642009-01-31 22:14:21 +00002647 fail:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002648 if (callresults) {
2649 PyObject **callresult2 = callresults;
2650 while (callresult2 < callresult) {
Victor Stinner2512a8b2011-03-01 22:46:52 +00002651 Py_XDECREF(*callresult2);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002652 ++callresult2;
2653 }
2654 PyObject_Free(callresults);
2655 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002656 if (numberresults)
2657 PyObject_Free(numberresults);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002658 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002659}
2660
Walter Dörwaldd2034312007-05-18 16:29:38 +00002661PyObject *
2662PyUnicode_FromFormat(const char *format, ...)
2663{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002664 PyObject* ret;
2665 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002666
2667#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002668 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002669#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002670 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002671#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002672 ret = PyUnicode_FromFormatV(format, vargs);
2673 va_end(vargs);
2674 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002675}
2676
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002677#ifdef HAVE_WCHAR_H
2678
Victor Stinner5593d8a2010-10-02 11:11:27 +00002679/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2680 convert a Unicode object to a wide character string.
2681
Victor Stinnerd88d9832011-09-06 02:00:05 +02002682 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002683 character) required to convert the unicode object. Ignore size argument.
2684
Victor Stinnerd88d9832011-09-06 02:00:05 +02002685 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002686 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002687 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002688static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002689unicode_aswidechar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002690 wchar_t *w,
2691 Py_ssize_t size)
2692{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002693 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002694 const wchar_t *wstr;
2695
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002696 wstr = PyUnicode_AsUnicodeAndSize(unicode, &res);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002697 if (wstr == NULL)
2698 return -1;
2699
Victor Stinner5593d8a2010-10-02 11:11:27 +00002700 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002701 if (size > res)
2702 size = res + 1;
2703 else
2704 res = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002705 Py_MEMCPY(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002706 return res;
2707 }
2708 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002709 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002710}
2711
2712Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002713PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002714 wchar_t *w,
2715 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002716{
2717 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002718 PyErr_BadInternalCall();
2719 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002720 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002721 return unicode_aswidechar(unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002722}
2723
Victor Stinner137c34c2010-09-29 10:25:54 +00002724wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002725PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002726 Py_ssize_t *size)
2727{
2728 wchar_t* buffer;
2729 Py_ssize_t buflen;
2730
2731 if (unicode == NULL) {
2732 PyErr_BadInternalCall();
2733 return NULL;
2734 }
2735
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002736 buflen = unicode_aswidechar(unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002737 if (buflen == -1)
2738 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002739 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < buflen) {
Victor Stinner137c34c2010-09-29 10:25:54 +00002740 PyErr_NoMemory();
2741 return NULL;
2742 }
2743
Victor Stinner137c34c2010-09-29 10:25:54 +00002744 buffer = PyMem_MALLOC(buflen * sizeof(wchar_t));
2745 if (buffer == NULL) {
2746 PyErr_NoMemory();
2747 return NULL;
2748 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002749 buflen = unicode_aswidechar(unicode, buffer, buflen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002750 if (buflen == -1)
2751 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002752 if (size != NULL)
2753 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00002754 return buffer;
2755}
2756
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002757#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002758
Alexander Belopolsky40018472011-02-26 01:02:56 +00002759PyObject *
2760PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002761{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002762 PyObject *v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002763 if (ordinal < 0 || ordinal > 0x10ffff) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002764 PyErr_SetString(PyExc_ValueError,
2765 "chr() arg not in range(0x110000)");
2766 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002767 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00002768
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002769 if (ordinal < 256)
2770 return get_latin1_char(ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002771
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002772 v = PyUnicode_New(1, ordinal);
2773 if (v == NULL)
2774 return NULL;
2775 PyUnicode_WRITE(PyUnicode_KIND(v), PyUnicode_DATA(v), 0, ordinal);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002776 assert(_PyUnicode_CheckConsistency(v, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002777 return v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002778}
2779
Alexander Belopolsky40018472011-02-26 01:02:56 +00002780PyObject *
2781PyUnicode_FromObject(register PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002782{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002783 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00002784 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002785 if (PyUnicode_CheckExact(obj)) {
Victor Stinnerd3a83d52011-10-01 03:09:33 +02002786 if (PyUnicode_READY(obj))
2787 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00002788 Py_INCREF(obj);
2789 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002790 }
2791 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002792 /* For a Unicode subtype that's not a Unicode object,
2793 return a true Unicode object with the same data. */
Victor Stinner2219e0a2011-10-01 01:16:59 +02002794 return PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002795 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00002796 PyErr_Format(PyExc_TypeError,
2797 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00002798 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002799 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002800}
2801
Alexander Belopolsky40018472011-02-26 01:02:56 +00002802PyObject *
2803PyUnicode_FromEncodedObject(register PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002804 const char *encoding,
2805 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002806{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002807 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002808 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00002809
Guido van Rossumd57fd912000-03-10 22:53:23 +00002810 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002811 PyErr_BadInternalCall();
2812 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002813 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002814
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002815 /* Decoding bytes objects is the most common case and should be fast */
2816 if (PyBytes_Check(obj)) {
2817 if (PyBytes_GET_SIZE(obj) == 0) {
2818 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002819 v = unicode_empty;
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002820 }
2821 else {
2822 v = PyUnicode_Decode(
2823 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
2824 encoding, errors);
2825 }
2826 return v;
2827 }
2828
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002829 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002830 PyErr_SetString(PyExc_TypeError,
2831 "decoding str is not supported");
2832 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002833 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002834
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002835 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
2836 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
2837 PyErr_Format(PyExc_TypeError,
2838 "coercing to str: need bytes, bytearray "
2839 "or buffer-like object, %.80s found",
2840 Py_TYPE(obj)->tp_name);
2841 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00002842 }
Tim Petersced69f82003-09-16 20:30:58 +00002843
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002844 if (buffer.len == 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002845 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002846 v = unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002847 }
Tim Petersced69f82003-09-16 20:30:58 +00002848 else
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002849 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00002850
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002851 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002852 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002853}
2854
Victor Stinner600d3be2010-06-10 12:00:55 +00002855/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00002856 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
2857 1 on success. */
2858static int
2859normalize_encoding(const char *encoding,
2860 char *lower,
2861 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002862{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002863 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00002864 char *l;
2865 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002866
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04002867 if (encoding == NULL) {
2868 strcpy(lower, "utf-8");
2869 return 1;
2870 }
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002871 e = encoding;
2872 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00002873 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00002874 while (*e) {
2875 if (l == l_end)
2876 return 0;
David Malcolm96960882010-11-05 17:23:41 +00002877 if (Py_ISUPPER(*e)) {
2878 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002879 }
2880 else if (*e == '_') {
2881 *l++ = '-';
2882 e++;
2883 }
2884 else {
2885 *l++ = *e++;
2886 }
2887 }
2888 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00002889 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00002890}
2891
Alexander Belopolsky40018472011-02-26 01:02:56 +00002892PyObject *
2893PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002894 Py_ssize_t size,
2895 const char *encoding,
2896 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00002897{
2898 PyObject *buffer = NULL, *unicode;
2899 Py_buffer info;
2900 char lower[11]; /* Enough for any encoding shortcut */
2901
Fred Drakee4315f52000-05-09 19:53:39 +00002902 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00002903 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002904 if ((strcmp(lower, "utf-8") == 0) ||
2905 (strcmp(lower, "utf8") == 0))
Victor Stinner37296e82010-06-10 13:36:23 +00002906 return PyUnicode_DecodeUTF8(s, size, errors);
2907 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002908 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00002909 (strcmp(lower, "iso-8859-1") == 0))
2910 return PyUnicode_DecodeLatin1(s, size, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02002911#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00002912 else if (strcmp(lower, "mbcs") == 0)
2913 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00002914#endif
Victor Stinner37296e82010-06-10 13:36:23 +00002915 else if (strcmp(lower, "ascii") == 0)
2916 return PyUnicode_DecodeASCII(s, size, errors);
2917 else if (strcmp(lower, "utf-16") == 0)
2918 return PyUnicode_DecodeUTF16(s, size, errors, 0);
2919 else if (strcmp(lower, "utf-32") == 0)
2920 return PyUnicode_DecodeUTF32(s, size, errors, 0);
2921 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002922
2923 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002924 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00002925 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002926 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00002927 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002928 if (buffer == NULL)
2929 goto onError;
2930 unicode = PyCodec_Decode(buffer, encoding, errors);
2931 if (unicode == NULL)
2932 goto onError;
2933 if (!PyUnicode_Check(unicode)) {
2934 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00002935 "decoder did not return a str object (type=%.400s)",
Christian Heimes90aa7642007-12-19 02:45:37 +00002936 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002937 Py_DECREF(unicode);
2938 goto onError;
2939 }
2940 Py_DECREF(buffer);
Victor Stinner17efeed2011-10-04 20:05:46 +02002941#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02002942 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002943 Py_DECREF(unicode);
2944 return NULL;
2945 }
Victor Stinner17efeed2011-10-04 20:05:46 +02002946#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002947 assert(_PyUnicode_CheckConsistency(unicode, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00002948 return unicode;
Tim Petersced69f82003-09-16 20:30:58 +00002949
Benjamin Peterson29060642009-01-31 22:14:21 +00002950 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00002951 Py_XDECREF(buffer);
2952 return NULL;
2953}
2954
Alexander Belopolsky40018472011-02-26 01:02:56 +00002955PyObject *
2956PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002957 const char *encoding,
2958 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002959{
2960 PyObject *v;
2961
2962 if (!PyUnicode_Check(unicode)) {
2963 PyErr_BadArgument();
2964 goto onError;
2965 }
2966
2967 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002968 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002969
2970 /* Decode via the codec registry */
2971 v = PyCodec_Decode(unicode, encoding, errors);
2972 if (v == NULL)
2973 goto onError;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002974 assert(_PyUnicode_CheckConsistency(v, 1));
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002975 return v;
2976
Benjamin Peterson29060642009-01-31 22:14:21 +00002977 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002978 return NULL;
2979}
2980
Alexander Belopolsky40018472011-02-26 01:02:56 +00002981PyObject *
2982PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002983 const char *encoding,
2984 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002985{
2986 PyObject *v;
2987
2988 if (!PyUnicode_Check(unicode)) {
2989 PyErr_BadArgument();
2990 goto onError;
2991 }
2992
2993 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002994 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002995
2996 /* Decode via the codec registry */
2997 v = PyCodec_Decode(unicode, encoding, errors);
2998 if (v == NULL)
2999 goto onError;
3000 if (!PyUnicode_Check(v)) {
3001 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003002 "decoder did not return a str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003003 Py_TYPE(v)->tp_name);
3004 Py_DECREF(v);
3005 goto onError;
3006 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02003007 assert(_PyUnicode_CheckConsistency(v, 1));
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003008 return v;
3009
Benjamin Peterson29060642009-01-31 22:14:21 +00003010 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003011 return NULL;
3012}
3013
Alexander Belopolsky40018472011-02-26 01:02:56 +00003014PyObject *
3015PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003016 Py_ssize_t size,
3017 const char *encoding,
3018 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003019{
3020 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003021
Guido van Rossumd57fd912000-03-10 22:53:23 +00003022 unicode = PyUnicode_FromUnicode(s, size);
3023 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003024 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003025 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3026 Py_DECREF(unicode);
3027 return v;
3028}
3029
Alexander Belopolsky40018472011-02-26 01:02:56 +00003030PyObject *
3031PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003032 const char *encoding,
3033 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003034{
3035 PyObject *v;
3036
3037 if (!PyUnicode_Check(unicode)) {
3038 PyErr_BadArgument();
3039 goto onError;
3040 }
3041
3042 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003043 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003044
3045 /* Encode via the codec registry */
3046 v = PyCodec_Encode(unicode, encoding, errors);
3047 if (v == NULL)
3048 goto onError;
3049 return v;
3050
Benjamin Peterson29060642009-01-31 22:14:21 +00003051 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003052 return NULL;
3053}
3054
Victor Stinnerad158722010-10-27 00:25:46 +00003055PyObject *
3056PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003057{
Victor Stinner99b95382011-07-04 14:23:54 +02003058#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003059 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003060#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003061 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00003062#else
Victor Stinner793b5312011-04-27 00:24:21 +02003063 PyInterpreterState *interp = PyThreadState_GET()->interp;
3064 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3065 cannot use it to encode and decode filenames before it is loaded. Load
3066 the Python codec requires to encode at least its own filename. Use the C
3067 version of the locale codec until the codec registry is initialized and
3068 the Python codec is loaded.
3069
3070 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3071 cannot only rely on it: check also interp->fscodec_initialized for
3072 subinterpreters. */
3073 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003074 return PyUnicode_AsEncodedString(unicode,
3075 Py_FileSystemDefaultEncoding,
3076 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003077 }
3078 else {
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003079 /* locale encoding with surrogateescape */
3080 wchar_t *wchar;
3081 char *bytes;
3082 PyObject *bytes_obj;
Victor Stinner2f02a512010-11-08 22:43:46 +00003083 size_t error_pos;
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003084
3085 wchar = PyUnicode_AsWideCharString(unicode, NULL);
3086 if (wchar == NULL)
3087 return NULL;
Victor Stinner2f02a512010-11-08 22:43:46 +00003088 bytes = _Py_wchar2char(wchar, &error_pos);
3089 if (bytes == NULL) {
3090 if (error_pos != (size_t)-1) {
3091 char *errmsg = strerror(errno);
3092 PyObject *exc = NULL;
3093 if (errmsg == NULL)
3094 errmsg = "Py_wchar2char() failed";
3095 raise_encode_exception(&exc,
Martin v. Löwis12be46c2011-11-04 19:04:15 +01003096 "filesystemencoding", unicode,
Victor Stinner2f02a512010-11-08 22:43:46 +00003097 error_pos, error_pos+1,
3098 errmsg);
3099 Py_XDECREF(exc);
3100 }
3101 else
3102 PyErr_NoMemory();
3103 PyMem_Free(wchar);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003104 return NULL;
Victor Stinner2f02a512010-11-08 22:43:46 +00003105 }
3106 PyMem_Free(wchar);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003107
3108 bytes_obj = PyBytes_FromString(bytes);
3109 PyMem_Free(bytes);
3110 return bytes_obj;
Victor Stinnerc39211f2010-09-29 16:35:47 +00003111 }
Victor Stinnerad158722010-10-27 00:25:46 +00003112#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003113}
3114
Alexander Belopolsky40018472011-02-26 01:02:56 +00003115PyObject *
3116PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003117 const char *encoding,
3118 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003119{
3120 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00003121 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003122
Guido van Rossumd57fd912000-03-10 22:53:23 +00003123 if (!PyUnicode_Check(unicode)) {
3124 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003125 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003126 }
Fred Drakee4315f52000-05-09 19:53:39 +00003127
Fred Drakee4315f52000-05-09 19:53:39 +00003128 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00003129 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003130 if ((strcmp(lower, "utf-8") == 0) ||
3131 (strcmp(lower, "utf8") == 0))
Victor Stinnera5c68c32011-03-02 01:03:14 +00003132 {
Victor Stinner2f283c22011-03-02 01:21:46 +00003133 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003134 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00003135 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003136 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinnera5c68c32011-03-02 01:03:14 +00003137 }
Victor Stinner37296e82010-06-10 13:36:23 +00003138 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003139 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00003140 (strcmp(lower, "iso-8859-1") == 0))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003141 return _PyUnicode_AsLatin1String(unicode, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003142#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003143 else if (strcmp(lower, "mbcs") == 0)
3144 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003145#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003146 else if (strcmp(lower, "ascii") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003147 return _PyUnicode_AsASCIIString(unicode, errors);
Victor Stinner37296e82010-06-10 13:36:23 +00003148 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003149
3150 /* Encode via the codec registry */
3151 v = PyCodec_Encode(unicode, encoding, errors);
3152 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003153 return NULL;
3154
3155 /* The normal path */
3156 if (PyBytes_Check(v))
3157 return v;
3158
3159 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003160 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003161 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003162 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003163
3164 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
3165 "encoder %s returned bytearray instead of bytes",
3166 encoding);
3167 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003168 Py_DECREF(v);
3169 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003170 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003171
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003172 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3173 Py_DECREF(v);
3174 return b;
3175 }
3176
3177 PyErr_Format(PyExc_TypeError,
3178 "encoder did not return a bytes object (type=%.400s)",
3179 Py_TYPE(v)->tp_name);
3180 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003181 return NULL;
3182}
3183
Alexander Belopolsky40018472011-02-26 01:02:56 +00003184PyObject *
3185PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003186 const char *encoding,
3187 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003188{
3189 PyObject *v;
3190
3191 if (!PyUnicode_Check(unicode)) {
3192 PyErr_BadArgument();
3193 goto onError;
3194 }
3195
3196 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003197 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003198
3199 /* Encode via the codec registry */
3200 v = PyCodec_Encode(unicode, encoding, errors);
3201 if (v == NULL)
3202 goto onError;
3203 if (!PyUnicode_Check(v)) {
3204 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003205 "encoder did not return an str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003206 Py_TYPE(v)->tp_name);
3207 Py_DECREF(v);
3208 goto onError;
3209 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003210 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003211
Benjamin Peterson29060642009-01-31 22:14:21 +00003212 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003213 return NULL;
3214}
3215
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003216PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003217PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003218 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003219 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3220}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003221
Christian Heimes5894ba72007-11-04 11:43:14 +00003222PyObject*
3223PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3224{
Victor Stinner99b95382011-07-04 14:23:54 +02003225#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003226 return PyUnicode_DecodeMBCS(s, size, NULL);
3227#elif defined(__APPLE__)
3228 return PyUnicode_DecodeUTF8(s, size, "surrogateescape");
3229#else
Victor Stinner793b5312011-04-27 00:24:21 +02003230 PyInterpreterState *interp = PyThreadState_GET()->interp;
3231 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3232 cannot use it to encode and decode filenames before it is loaded. Load
3233 the Python codec requires to encode at least its own filename. Use the C
3234 version of the locale codec until the codec registry is initialized and
3235 the Python codec is loaded.
3236
3237 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3238 cannot only rely on it: check also interp->fscodec_initialized for
3239 subinterpreters. */
3240 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003241 return PyUnicode_Decode(s, size,
3242 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00003243 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003244 }
3245 else {
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003246 /* locale encoding with surrogateescape */
3247 wchar_t *wchar;
3248 PyObject *unicode;
Victor Stinner168e1172010-10-16 23:16:16 +00003249 size_t len;
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003250
3251 if (s[size] != '\0' || size != strlen(s)) {
3252 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3253 return NULL;
3254 }
3255
Victor Stinner168e1172010-10-16 23:16:16 +00003256 wchar = _Py_char2wchar(s, &len);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003257 if (wchar == NULL)
Victor Stinnerd5af0a52010-11-08 23:34:29 +00003258 return PyErr_NoMemory();
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003259
Victor Stinner168e1172010-10-16 23:16:16 +00003260 unicode = PyUnicode_FromWideChar(wchar, len);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003261 PyMem_Free(wchar);
3262 return unicode;
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003263 }
Victor Stinnerad158722010-10-27 00:25:46 +00003264#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003265}
3266
Martin v. Löwis011e8422009-05-05 04:43:17 +00003267
3268int
3269PyUnicode_FSConverter(PyObject* arg, void* addr)
3270{
3271 PyObject *output = NULL;
3272 Py_ssize_t size;
3273 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003274 if (arg == NULL) {
3275 Py_DECREF(*(PyObject**)addr);
3276 return 1;
3277 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00003278 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00003279 output = arg;
3280 Py_INCREF(output);
3281 }
3282 else {
3283 arg = PyUnicode_FromObject(arg);
3284 if (!arg)
3285 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00003286 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003287 Py_DECREF(arg);
3288 if (!output)
3289 return 0;
3290 if (!PyBytes_Check(output)) {
3291 Py_DECREF(output);
3292 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
3293 return 0;
3294 }
3295 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00003296 size = PyBytes_GET_SIZE(output);
3297 data = PyBytes_AS_STRING(output);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003298 if (size != strlen(data)) {
Benjamin Peterson7a6b44a2011-08-18 13:51:47 -05003299 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003300 Py_DECREF(output);
3301 return 0;
3302 }
3303 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003304 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003305}
3306
3307
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003308int
3309PyUnicode_FSDecoder(PyObject* arg, void* addr)
3310{
3311 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003312 if (arg == NULL) {
3313 Py_DECREF(*(PyObject**)addr);
3314 return 1;
3315 }
3316 if (PyUnicode_Check(arg)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003317 if (PyUnicode_READY(arg))
3318 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003319 output = arg;
3320 Py_INCREF(output);
3321 }
3322 else {
3323 arg = PyBytes_FromObject(arg);
3324 if (!arg)
3325 return 0;
3326 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
3327 PyBytes_GET_SIZE(arg));
3328 Py_DECREF(arg);
3329 if (!output)
3330 return 0;
3331 if (!PyUnicode_Check(output)) {
3332 Py_DECREF(output);
3333 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
3334 return 0;
3335 }
3336 }
Victor Stinner065836e2011-10-27 01:56:33 +02003337 if (PyUnicode_READY(output) < 0) {
3338 Py_DECREF(output);
3339 return 0;
3340 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003341 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003342 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003343 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3344 Py_DECREF(output);
3345 return 0;
3346 }
3347 *(PyObject**)addr = output;
3348 return Py_CLEANUP_SUPPORTED;
3349}
3350
3351
Martin v. Löwis5b222132007-06-10 09:51:05 +00003352char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003353PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003354{
Christian Heimesf3863112007-11-22 07:46:41 +00003355 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003356
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003357 if (!PyUnicode_Check(unicode)) {
3358 PyErr_BadArgument();
3359 return NULL;
3360 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003361 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003362 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003363
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003364 if (PyUnicode_UTF8(unicode) == NULL) {
3365 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003366 bytes = _PyUnicode_AsUTF8String(unicode, "strict");
3367 if (bytes == NULL)
3368 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003369 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3370 if (_PyUnicode_UTF8(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003371 Py_DECREF(bytes);
3372 return NULL;
3373 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003374 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
3375 Py_MEMCPY(_PyUnicode_UTF8(unicode),
3376 PyBytes_AS_STRING(bytes),
3377 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003378 Py_DECREF(bytes);
3379 }
3380
3381 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003382 *psize = PyUnicode_UTF8_LENGTH(unicode);
3383 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003384}
3385
3386char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003387PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003388{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003389 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3390}
3391
3392#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +02003393static int unicode_as_unicode_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003394#endif
3395
3396
3397Py_UNICODE *
3398PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3399{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003400 const unsigned char *one_byte;
3401#if SIZEOF_WCHAR_T == 4
3402 const Py_UCS2 *two_bytes;
3403#else
3404 const Py_UCS4 *four_bytes;
3405 const Py_UCS4 *ucs4_end;
3406 Py_ssize_t num_surrogates;
3407#endif
3408 wchar_t *w;
3409 wchar_t *wchar_end;
3410
3411 if (!PyUnicode_Check(unicode)) {
3412 PyErr_BadArgument();
3413 return NULL;
3414 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003415 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003416 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003417 assert(_PyUnicode_KIND(unicode) != 0);
3418 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003419
3420#ifdef Py_DEBUG
3421 ++unicode_as_unicode_calls;
3422#endif
3423
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003424 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003425#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003426 four_bytes = PyUnicode_4BYTE_DATA(unicode);
3427 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003428 num_surrogates = 0;
3429
3430 for (; four_bytes < ucs4_end; ++four_bytes) {
3431 if (*four_bytes > 0xFFFF)
3432 ++num_surrogates;
3433 }
3434
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003435 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
3436 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
3437 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003438 PyErr_NoMemory();
3439 return NULL;
3440 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003441 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003442
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003443 w = _PyUnicode_WSTR(unicode);
3444 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
3445 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003446 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3447 if (*four_bytes > 0xFFFF) {
3448 /* encode surrogate pair in this case */
3449 *w++ = 0xD800 | ((*four_bytes - 0x10000) >> 10);
3450 *w = 0xDC00 | ((*four_bytes - 0x10000) & 0x3FF);
3451 }
3452 else
3453 *w = *four_bytes;
3454
3455 if (w > wchar_end) {
3456 assert(0 && "Miscalculated string end");
3457 }
3458 }
3459 *w = 0;
3460#else
3461 /* sizeof(wchar_t) == 4 */
3462 Py_FatalError("Impossible unicode object state, wstr and str "
3463 "should share memory already.");
3464 return NULL;
3465#endif
3466 }
3467 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003468 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3469 (_PyUnicode_LENGTH(unicode) + 1));
3470 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003471 PyErr_NoMemory();
3472 return NULL;
3473 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003474 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
3475 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
3476 w = _PyUnicode_WSTR(unicode);
3477 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003478
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003479 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3480 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003481 for (; w < wchar_end; ++one_byte, ++w)
3482 *w = *one_byte;
3483 /* null-terminate the wstr */
3484 *w = 0;
3485 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003486 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003487#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003488 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003489 for (; w < wchar_end; ++two_bytes, ++w)
3490 *w = *two_bytes;
3491 /* null-terminate the wstr */
3492 *w = 0;
3493#else
3494 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003495 PyObject_FREE(_PyUnicode_WSTR(unicode));
3496 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003497 Py_FatalError("Impossible unicode object state, wstr "
3498 "and str should share memory already.");
3499 return NULL;
3500#endif
3501 }
3502 else {
3503 assert(0 && "This should never happen.");
3504 }
3505 }
3506 }
3507 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003508 *size = PyUnicode_WSTR_LENGTH(unicode);
3509 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00003510}
3511
Alexander Belopolsky40018472011-02-26 01:02:56 +00003512Py_UNICODE *
3513PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003514{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003515 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003516}
3517
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003518
Alexander Belopolsky40018472011-02-26 01:02:56 +00003519Py_ssize_t
3520PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003521{
3522 if (!PyUnicode_Check(unicode)) {
3523 PyErr_BadArgument();
3524 goto onError;
3525 }
3526 return PyUnicode_GET_SIZE(unicode);
3527
Benjamin Peterson29060642009-01-31 22:14:21 +00003528 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003529 return -1;
3530}
3531
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003532Py_ssize_t
3533PyUnicode_GetLength(PyObject *unicode)
3534{
Victor Stinner5a706cf2011-10-02 00:36:53 +02003535 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003536 PyErr_BadArgument();
3537 return -1;
3538 }
3539
3540 return PyUnicode_GET_LENGTH(unicode);
3541}
3542
3543Py_UCS4
3544PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
3545{
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003546 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
3547 PyErr_BadArgument();
3548 return (Py_UCS4)-1;
3549 }
3550 if (index < 0 || index >= _PyUnicode_LENGTH(unicode)) {
3551 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003552 return (Py_UCS4)-1;
3553 }
3554 return PyUnicode_READ_CHAR(unicode, index);
3555}
3556
3557int
3558PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
3559{
3560 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003561 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003562 return -1;
3563 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02003564 if (index < 0 || index >= _PyUnicode_LENGTH(unicode)) {
3565 PyErr_SetString(PyExc_IndexError, "string index out of range");
3566 return -1;
3567 }
3568 if (_PyUnicode_Dirty(unicode))
3569 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003570 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
3571 index, ch);
3572 return 0;
3573}
3574
Alexander Belopolsky40018472011-02-26 01:02:56 +00003575const char *
3576PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00003577{
Victor Stinner42cb4622010-09-01 19:39:01 +00003578 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00003579}
3580
Victor Stinner554f3f02010-06-16 23:33:54 +00003581/* create or adjust a UnicodeDecodeError */
3582static void
3583make_decode_exception(PyObject **exceptionObject,
3584 const char *encoding,
3585 const char *input, Py_ssize_t length,
3586 Py_ssize_t startpos, Py_ssize_t endpos,
3587 const char *reason)
3588{
3589 if (*exceptionObject == NULL) {
3590 *exceptionObject = PyUnicodeDecodeError_Create(
3591 encoding, input, length, startpos, endpos, reason);
3592 }
3593 else {
3594 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
3595 goto onError;
3596 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
3597 goto onError;
3598 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
3599 goto onError;
3600 }
3601 return;
3602
3603onError:
3604 Py_DECREF(*exceptionObject);
3605 *exceptionObject = NULL;
3606}
3607
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003608/* error handling callback helper:
3609 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00003610 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003611 and adjust various state variables.
3612 return 0 on success, -1 on error
3613*/
3614
Alexander Belopolsky40018472011-02-26 01:02:56 +00003615static int
3616unicode_decode_call_errorhandler(const char *errors, PyObject **errorHandler,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003617 const char *encoding, const char *reason,
3618 const char **input, const char **inend, Py_ssize_t *startinpos,
3619 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003620 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003621{
Benjamin Peterson142957c2008-07-04 19:55:29 +00003622 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003623
3624 PyObject *restuple = NULL;
3625 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01003626 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003627 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003628 Py_ssize_t requiredsize;
3629 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003630 PyObject *inputobj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003631 int res = -1;
3632
Victor Stinner596a6c42011-11-09 00:02:18 +01003633 if (_PyUnicode_KIND(*output) != PyUnicode_WCHAR_KIND)
3634 outsize = PyUnicode_GET_LENGTH(*output);
3635 else
3636 outsize = _PyUnicode_WSTR_LENGTH(*output);
3637
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003638 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003639 *errorHandler = PyCodec_LookupError(errors);
3640 if (*errorHandler == NULL)
3641 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003642 }
3643
Victor Stinner554f3f02010-06-16 23:33:54 +00003644 make_decode_exception(exceptionObject,
3645 encoding,
3646 *input, *inend - *input,
3647 *startinpos, *endinpos,
3648 reason);
3649 if (*exceptionObject == NULL)
3650 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003651
3652 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
3653 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003654 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003655 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00003656 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00003657 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003658 }
3659 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00003660 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003661 if (PyUnicode_READY(repunicode) < 0)
3662 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003663
3664 /* Copy back the bytes variables, which might have been modified by the
3665 callback */
3666 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
3667 if (!inputobj)
3668 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00003669 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003670 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00003671 }
Christian Heimes72b710a2008-05-26 13:28:38 +00003672 *input = PyBytes_AS_STRING(inputobj);
3673 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003674 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00003675 /* we can DECREF safely, as the exception has another reference,
3676 so the object won't go away. */
3677 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003678
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003679 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003680 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00003681 if (newpos<0 || newpos>insize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003682 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
3683 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00003684 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003685
Victor Stinner596a6c42011-11-09 00:02:18 +01003686 if (_PyUnicode_KIND(*output) != PyUnicode_WCHAR_KIND) {
3687 /* need more space? (at least enough for what we
3688 have+the replacement+the rest of the string (starting
3689 at the new input position), so we won't have to check space
3690 when there are no errors in the rest of the string) */
3691 Py_ssize_t replen = PyUnicode_GET_LENGTH(repunicode);
3692 requiredsize = *outpos + replen + insize-newpos;
3693 if (requiredsize > outsize) {
3694 if (requiredsize<2*outsize)
3695 requiredsize = 2*outsize;
3696 if (unicode_resize(output, requiredsize) < 0)
3697 goto onError;
3698 }
3699 if (unicode_widen(output, PyUnicode_MAX_CHAR_VALUE(repunicode)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003700 goto onError;
Victor Stinner596a6c42011-11-09 00:02:18 +01003701 copy_characters(*output, *outpos, repunicode, 0, replen);
3702 *outpos += replen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003703 }
Victor Stinner596a6c42011-11-09 00:02:18 +01003704 else {
3705 wchar_t *repwstr;
3706 Py_ssize_t repwlen;
3707 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
3708 if (repwstr == NULL)
3709 goto onError;
3710 /* need more space? (at least enough for what we
3711 have+the replacement+the rest of the string (starting
3712 at the new input position), so we won't have to check space
3713 when there are no errors in the rest of the string) */
3714 requiredsize = *outpos + repwlen + insize-newpos;
3715 if (requiredsize > outsize) {
3716 if (requiredsize < 2*outsize)
3717 requiredsize = 2*outsize;
3718 if (unicode_resize(output, requiredsize) < 0)
3719 goto onError;
3720 }
3721 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
3722 *outpos += repwlen;
3723 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003724 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003725 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003726
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003727 /* we made it! */
3728 res = 0;
3729
Benjamin Peterson29060642009-01-31 22:14:21 +00003730 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003731 Py_XDECREF(restuple);
3732 return res;
3733}
3734
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003735/* --- UTF-7 Codec -------------------------------------------------------- */
3736
Antoine Pitrou244651a2009-05-04 18:56:13 +00003737/* See RFC2152 for details. We encode conservatively and decode liberally. */
3738
3739/* Three simple macros defining base-64. */
3740
3741/* Is c a base-64 character? */
3742
3743#define IS_BASE64(c) \
3744 (((c) >= 'A' && (c) <= 'Z') || \
3745 ((c) >= 'a' && (c) <= 'z') || \
3746 ((c) >= '0' && (c) <= '9') || \
3747 (c) == '+' || (c) == '/')
3748
3749/* given that c is a base-64 character, what is its base-64 value? */
3750
3751#define FROM_BASE64(c) \
3752 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
3753 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
3754 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
3755 (c) == '+' ? 62 : 63)
3756
3757/* What is the base-64 character of the bottom 6 bits of n? */
3758
3759#define TO_BASE64(n) \
3760 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
3761
3762/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
3763 * decoded as itself. We are permissive on decoding; the only ASCII
3764 * byte not decoding to itself is the + which begins a base64
3765 * string. */
3766
3767#define DECODE_DIRECT(c) \
3768 ((c) <= 127 && (c) != '+')
3769
3770/* The UTF-7 encoder treats ASCII characters differently according to
3771 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
3772 * the above). See RFC2152. This array identifies these different
3773 * sets:
3774 * 0 : "Set D"
3775 * alphanumeric and '(),-./:?
3776 * 1 : "Set O"
3777 * !"#$%&*;<=>@[]^_`{|}
3778 * 2 : "whitespace"
3779 * ht nl cr sp
3780 * 3 : special (must be base64 encoded)
3781 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
3782 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003783
Tim Petersced69f82003-09-16 20:30:58 +00003784static
Antoine Pitrou244651a2009-05-04 18:56:13 +00003785char utf7_category[128] = {
3786/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
3787 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
3788/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
3789 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3790/* sp ! " # $ % & ' ( ) * + , - . / */
3791 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
3792/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
3793 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
3794/* @ A B C D E F G H I J K L M N O */
3795 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3796/* P Q R S T U V W X Y Z [ \ ] ^ _ */
3797 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
3798/* ` a b c d e f g h i j k l m n o */
3799 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3800/* p q r s t u v w x y z { | } ~ del */
3801 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003802};
3803
Antoine Pitrou244651a2009-05-04 18:56:13 +00003804/* ENCODE_DIRECT: this character should be encoded as itself. The
3805 * answer depends on whether we are encoding set O as itself, and also
3806 * on whether we are encoding whitespace as itself. RFC2152 makes it
3807 * clear that the answers to these questions vary between
3808 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00003809
Antoine Pitrou244651a2009-05-04 18:56:13 +00003810#define ENCODE_DIRECT(c, directO, directWS) \
3811 ((c) < 128 && (c) > 0 && \
3812 ((utf7_category[(c)] == 0) || \
3813 (directWS && (utf7_category[(c)] == 2)) || \
3814 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003815
Alexander Belopolsky40018472011-02-26 01:02:56 +00003816PyObject *
3817PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003818 Py_ssize_t size,
3819 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003820{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003821 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
3822}
3823
Antoine Pitrou244651a2009-05-04 18:56:13 +00003824/* The decoder. The only state we preserve is our read position,
3825 * i.e. how many characters we have consumed. So if we end in the
3826 * middle of a shift sequence we have to back off the read position
3827 * and the output to the beginning of the sequence, otherwise we lose
3828 * all the shift state (seen bits, number of bits seen, high
3829 * surrogate). */
3830
Alexander Belopolsky40018472011-02-26 01:02:56 +00003831PyObject *
3832PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003833 Py_ssize_t size,
3834 const char *errors,
3835 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003836{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003837 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003838 Py_ssize_t startinpos;
3839 Py_ssize_t endinpos;
3840 Py_ssize_t outpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003841 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01003842 PyObject *unicode;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003843 const char *errmsg = "";
3844 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003845 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003846 unsigned int base64bits = 0;
3847 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01003848 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003849 PyObject *errorHandler = NULL;
3850 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003851
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003852 /* Start off assuming it's all ASCII. Widen later as necessary. */
3853 unicode = PyUnicode_New(size, 127);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003854 if (!unicode)
3855 return NULL;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003856 if (size == 0) {
3857 if (consumed)
3858 *consumed = 0;
Victor Stinner7931d9a2011-11-04 00:22:48 +01003859 return unicode;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003860 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003861
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003862 shiftOutStart = outpos = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003863 e = s + size;
3864
3865 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003866 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00003867 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00003868 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003869
Antoine Pitrou244651a2009-05-04 18:56:13 +00003870 if (inShift) { /* in a base-64 section */
3871 if (IS_BASE64(ch)) { /* consume a base-64 character */
3872 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
3873 base64bits += 6;
3874 s++;
3875 if (base64bits >= 16) {
3876 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01003877 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00003878 base64bits -= 16;
3879 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
3880 if (surrogate) {
3881 /* expecting a second surrogate */
3882 if (outCh >= 0xDC00 && outCh <= 0xDFFF) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003883 Py_UCS4 ch2 = (((surrogate & 0x3FF)<<10)
3884 | (outCh & 0x3FF)) + 0x10000;
3885 if (unicode_putchar(&unicode, &outpos, ch2) < 0)
3886 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003887 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01003888 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003889 }
3890 else {
Antoine Pitrou78edf752011-11-15 01:44:16 +01003891 if (unicode_putchar(&unicode, &outpos, surrogate) < 0)
3892 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003893 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003894 }
3895 }
Antoine Pitrou5418ee02011-11-15 01:42:21 +01003896 if (outCh >= 0xD800 && outCh <= 0xDBFF) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00003897 /* first surrogate */
3898 surrogate = outCh;
3899 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003900 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003901 if (unicode_putchar(&unicode, &outpos, outCh) < 0)
3902 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003903 }
3904 }
3905 }
3906 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003907 inShift = 0;
3908 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003909 if (surrogate) {
Antoine Pitrou78edf752011-11-15 01:44:16 +01003910 if (unicode_putchar(&unicode, &outpos, surrogate) < 0)
3911 goto onError;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01003912 surrogate = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003913 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003914 if (base64bits > 0) { /* left-over bits */
3915 if (base64bits >= 6) {
3916 /* We've seen at least one base-64 character */
3917 errmsg = "partial character in shift sequence";
3918 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003919 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003920 else {
3921 /* Some bits remain; they should be zero */
3922 if (base64buffer != 0) {
3923 errmsg = "non-zero padding bits in shift sequence";
3924 goto utf7Error;
3925 }
3926 }
3927 }
3928 if (ch != '-') {
3929 /* '-' is absorbed; other terminating
3930 characters are preserved */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003931 if (unicode_putchar(&unicode, &outpos, ch) < 0)
3932 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003933 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003934 }
3935 }
3936 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003937 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003938 s++; /* consume '+' */
3939 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003940 s++;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003941 if (unicode_putchar(&unicode, &outpos, '+') < 0)
3942 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003943 }
3944 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003945 inShift = 1;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003946 shiftOutStart = outpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003947 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003948 }
3949 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003950 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003951 if (unicode_putchar(&unicode, &outpos, ch) < 0)
3952 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003953 s++;
3954 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003955 else {
3956 startinpos = s-starts;
3957 s++;
3958 errmsg = "unexpected special character";
3959 goto utf7Error;
3960 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003961 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003962utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003963 endinpos = s-starts;
3964 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003965 errors, &errorHandler,
3966 "utf7", errmsg,
3967 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003968 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00003969 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003970 }
3971
Antoine Pitrou244651a2009-05-04 18:56:13 +00003972 /* end of string */
3973
3974 if (inShift && !consumed) { /* in shift sequence, no more to follow */
3975 /* if we're in an inconsistent state, that's an error */
3976 if (surrogate ||
3977 (base64bits >= 6) ||
3978 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00003979 endinpos = size;
3980 if (unicode_decode_call_errorhandler(
3981 errors, &errorHandler,
3982 "utf7", "unterminated shift sequence",
3983 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003984 &unicode, &outpos))
Antoine Pitrou244651a2009-05-04 18:56:13 +00003985 goto onError;
3986 if (s < e)
3987 goto restart;
3988 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003989 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003990
3991 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003992 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00003993 if (inShift) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003994 outpos = shiftOutStart; /* back off output */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003995 *consumed = startinpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003996 }
3997 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003998 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003999 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004000 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004001
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004002 if (unicode_resize(&unicode, outpos) < 0)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004003 goto onError;
4004
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004005 Py_XDECREF(errorHandler);
4006 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02004007#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02004008 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004009 Py_DECREF(unicode);
4010 return NULL;
4011 }
Victor Stinner17efeed2011-10-04 20:05:46 +02004012#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02004013 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01004014 return unicode;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004015
Benjamin Peterson29060642009-01-31 22:14:21 +00004016 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004017 Py_XDECREF(errorHandler);
4018 Py_XDECREF(exc);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004019 Py_DECREF(unicode);
4020 return NULL;
4021}
4022
4023
Alexander Belopolsky40018472011-02-26 01:02:56 +00004024PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004025_PyUnicode_EncodeUTF7(PyObject *str,
4026 int base64SetO,
4027 int base64WhiteSpace,
4028 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004029{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004030 int kind;
4031 void *data;
4032 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004033 PyObject *v;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004034 Py_ssize_t allocated;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004035 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004036 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004037 unsigned int base64bits = 0;
4038 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004039 char * out;
4040 char * start;
4041
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004042 if (PyUnicode_READY(str) < 0)
4043 return NULL;
4044 kind = PyUnicode_KIND(str);
4045 data = PyUnicode_DATA(str);
4046 len = PyUnicode_GET_LENGTH(str);
4047
4048 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004049 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004050
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004051 /* It might be possible to tighten this worst case */
4052 allocated = 8 * len;
4053 if (allocated / 8 != len)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004054 return PyErr_NoMemory();
4055
Antoine Pitrou244651a2009-05-04 18:56:13 +00004056 v = PyBytes_FromStringAndSize(NULL, allocated);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004057 if (v == NULL)
4058 return NULL;
4059
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004060 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004061 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004062 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004063
Antoine Pitrou244651a2009-05-04 18:56:13 +00004064 if (inShift) {
4065 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4066 /* shifting out */
4067 if (base64bits) { /* output remaining bits */
4068 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4069 base64buffer = 0;
4070 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004071 }
4072 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004073 /* Characters not in the BASE64 set implicitly unshift the sequence
4074 so no '-' is required, except if the character is itself a '-' */
4075 if (IS_BASE64(ch) || ch == '-') {
4076 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004077 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004078 *out++ = (char) ch;
4079 }
4080 else {
4081 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004082 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004083 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004084 else { /* not in a shift sequence */
4085 if (ch == '+') {
4086 *out++ = '+';
4087 *out++ = '-';
4088 }
4089 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4090 *out++ = (char) ch;
4091 }
4092 else {
4093 *out++ = '+';
4094 inShift = 1;
4095 goto encode_char;
4096 }
4097 }
4098 continue;
4099encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004100 if (ch >= 0x10000) {
4101 /* code first surrogate */
4102 base64bits += 16;
4103 base64buffer = (base64buffer << 16) | 0xd800 | ((ch-0x10000) >> 10);
4104 while (base64bits >= 6) {
4105 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4106 base64bits -= 6;
4107 }
4108 /* prepare second surrogate */
4109 ch = 0xDC00 | ((ch-0x10000) & 0x3FF);
4110 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004111 base64bits += 16;
4112 base64buffer = (base64buffer << 16) | ch;
4113 while (base64bits >= 6) {
4114 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4115 base64bits -= 6;
4116 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004117 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004118 if (base64bits)
4119 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4120 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004121 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004122 if (_PyBytes_Resize(&v, out - start) < 0)
4123 return NULL;
4124 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004125}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004126PyObject *
4127PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4128 Py_ssize_t size,
4129 int base64SetO,
4130 int base64WhiteSpace,
4131 const char *errors)
4132{
4133 PyObject *result;
4134 PyObject *tmp = PyUnicode_FromUnicode(s, size);
4135 if (tmp == NULL)
4136 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004137 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004138 base64WhiteSpace, errors);
4139 Py_DECREF(tmp);
4140 return result;
4141}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004142
Antoine Pitrou244651a2009-05-04 18:56:13 +00004143#undef IS_BASE64
4144#undef FROM_BASE64
4145#undef TO_BASE64
4146#undef DECODE_DIRECT
4147#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004148
Guido van Rossumd57fd912000-03-10 22:53:23 +00004149/* --- UTF-8 Codec -------------------------------------------------------- */
4150
Tim Petersced69f82003-09-16 20:30:58 +00004151static
Guido van Rossumd57fd912000-03-10 22:53:23 +00004152char utf8_code_length[256] = {
Ezio Melotti57221d02010-07-01 07:32:02 +00004153 /* Map UTF-8 encoded prefix byte to sequence length. Zero means
4154 illegal prefix. See RFC 3629 for details */
4155 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 00-0F */
4156 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Victor Stinner4a2b7a12010-08-13 14:03:48 +00004157 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Guido van Rossumd57fd912000-03-10 22:53:23 +00004158 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4159 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4160 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4161 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Ezio Melotti57221d02010-07-01 07:32:02 +00004162 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 70-7F */
4163 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 80-8F */
Guido van Rossumd57fd912000-03-10 22:53:23 +00004164 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4165 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
Ezio Melotti57221d02010-07-01 07:32:02 +00004166 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* B0-BF */
4167 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* C0-C1 + C2-CF */
4168 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* D0-DF */
4169 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* E0-EF */
4170 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 /* F0-F4 + F5-FF */
Guido van Rossumd57fd912000-03-10 22:53:23 +00004171};
4172
Alexander Belopolsky40018472011-02-26 01:02:56 +00004173PyObject *
4174PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004175 Py_ssize_t size,
4176 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004177{
Walter Dörwald69652032004-09-07 20:24:22 +00004178 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4179}
4180
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004181#include "stringlib/ucs1lib.h"
4182#include "stringlib/codecs.h"
4183#include "stringlib/undef.h"
4184
4185#include "stringlib/ucs2lib.h"
4186#include "stringlib/codecs.h"
4187#include "stringlib/undef.h"
4188
4189#include "stringlib/ucs4lib.h"
4190#include "stringlib/codecs.h"
4191#include "stringlib/undef.h"
4192
Antoine Pitrouab868312009-01-10 15:40:25 +00004193/* Mask to check or force alignment of a pointer to C 'long' boundaries */
4194#define LONG_PTR_MASK (size_t) (SIZEOF_LONG - 1)
4195
4196/* Mask to quickly check whether a C 'long' contains a
4197 non-ASCII, UTF8-encoded char. */
4198#if (SIZEOF_LONG == 8)
4199# define ASCII_CHAR_MASK 0x8080808080808080L
4200#elif (SIZEOF_LONG == 4)
4201# define ASCII_CHAR_MASK 0x80808080L
4202#else
4203# error C 'long' size should be either 4 or 8!
4204#endif
4205
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004206/* Scans a UTF-8 string and returns the maximum character to be expected
4207 and the size of the decoded unicode string.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004208
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004209 This function doesn't check for errors, these checks are performed in
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004210 PyUnicode_DecodeUTF8Stateful.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004211 */
4212static Py_UCS4
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004213utf8_max_char_size_and_char_count(const char *s, Py_ssize_t string_size,
4214 Py_ssize_t *unicode_size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004215{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004216 Py_ssize_t char_count = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004217 const unsigned char *p = (const unsigned char *)s;
4218 const unsigned char *end = p + string_size;
4219 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004220
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004221 assert(unicode_size != NULL);
4222
4223 /* By having a cascade of independent loops which fallback onto each
4224 other, we minimize the amount of work done in the average loop
4225 iteration, and we also maximize the CPU's ability to predict
4226 branches correctly (because a given condition will have always the
4227 same boolean outcome except perhaps in the last iteration of the
4228 corresponding loop).
4229 In the general case this brings us rather close to decoding
4230 performance pre-PEP 393, despite the two-pass decoding.
4231
4232 Note that the pure ASCII loop is not duplicated once a non-ASCII
4233 character has been encountered. It is actually a pessimization (by
4234 a significant factor) to use this loop on text with many non-ASCII
4235 characters, and it is important to avoid bad performance on valid
4236 utf-8 data (invalid utf-8 being a different can of worms).
4237 */
4238
4239 /* ASCII */
4240 for (; p < end; ++p) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004241 /* Only check value if it's not a ASCII char... */
4242 if (*p < 0x80) {
4243 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
4244 an explanation. */
4245 if (!((size_t) p & LONG_PTR_MASK)) {
4246 /* Help register allocation */
4247 register const unsigned char *_p = p;
4248 while (_p < aligned_end) {
4249 unsigned long value = *(unsigned long *) _p;
4250 if (value & ASCII_CHAR_MASK)
4251 break;
4252 _p += SIZEOF_LONG;
4253 char_count += SIZEOF_LONG;
4254 }
4255 p = _p;
4256 if (p == end)
4257 break;
4258 }
4259 }
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004260 if (*p < 0x80)
4261 ++char_count;
4262 else
4263 goto _ucs1loop;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004264 }
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004265 *unicode_size = char_count;
4266 return 127;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004267
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004268_ucs1loop:
4269 for (; p < end; ++p) {
4270 if (*p < 0xc4)
4271 char_count += ((*p & 0xc0) != 0x80);
4272 else
4273 goto _ucs2loop;
4274 }
4275 *unicode_size = char_count;
4276 return 255;
4277
4278_ucs2loop:
4279 for (; p < end; ++p) {
4280 if (*p < 0xf0)
4281 char_count += ((*p & 0xc0) != 0x80);
4282 else
4283 goto _ucs4loop;
4284 }
4285 *unicode_size = char_count;
4286 return 65535;
4287
4288_ucs4loop:
4289 for (; p < end; ++p) {
4290 char_count += ((*p & 0xc0) != 0x80);
4291 }
4292 *unicode_size = char_count;
4293 return 65537;
4294}
4295
4296/* Called when we encountered some error that wasn't detected in the original
4297 scan, e.g. an encoded surrogate character. The original maxchar computation
4298 may have been incorrect, so redo it. */
4299static int
4300refit_partial_string(PyObject **unicode, int kind, void *data, Py_ssize_t n)
4301{
4302 PyObject *tmp;
4303 Py_ssize_t k, maxchar;
4304 for (k = 0, maxchar = 0; k < n; k++)
4305 maxchar = Py_MAX(maxchar, PyUnicode_READ(kind, data, k));
4306 tmp = PyUnicode_New(PyUnicode_GET_LENGTH(*unicode), maxchar);
4307 if (tmp == NULL)
4308 return -1;
4309 PyUnicode_CopyCharacters(tmp, 0, *unicode, 0, n);
4310 Py_DECREF(*unicode);
4311 *unicode = tmp;
4312 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004313}
4314
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004315/* Similar to PyUnicode_WRITE but may attempt to widen and resize the string
4316 in case of errors. Implicit parameters: unicode, kind, data, has_errors,
4317 onError. Potential resizing overallocates, so the result needs to shrink
4318 at the end.
4319*/
4320#define WRITE_MAYBE_FAIL(index, value) \
4321 do { \
4322 if (has_errors) { \
4323 Py_ssize_t pos = index; \
4324 if (pos > PyUnicode_GET_LENGTH(unicode) && \
4325 unicode_resize(&unicode, pos + pos/8) < 0) \
4326 goto onError; \
4327 if (unicode_putchar(&unicode, &pos, value) < 0) \
4328 goto onError; \
4329 } \
4330 else \
4331 PyUnicode_WRITE(kind, data, index, value); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004332 } while (0)
4333
Alexander Belopolsky40018472011-02-26 01:02:56 +00004334PyObject *
4335PyUnicode_DecodeUTF8Stateful(const char *s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004336 Py_ssize_t size,
4337 const char *errors,
4338 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00004339{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004340 const char *starts = s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004341 int n;
Ezio Melotti57221d02010-07-01 07:32:02 +00004342 int k;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004343 Py_ssize_t startinpos;
4344 Py_ssize_t endinpos;
Antoine Pitrouab868312009-01-10 15:40:25 +00004345 const char *e, *aligned_end;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004346 PyObject *unicode;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004347 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004348 PyObject *errorHandler = NULL;
4349 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004350 Py_UCS4 maxchar = 0;
4351 Py_ssize_t unicode_size;
4352 Py_ssize_t i;
4353 int kind;
4354 void *data;
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004355 int has_errors = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004356
Walter Dörwald69652032004-09-07 20:24:22 +00004357 if (size == 0) {
4358 if (consumed)
4359 *consumed = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004360 return (PyObject *)PyUnicode_New(0, 0);
Walter Dörwald69652032004-09-07 20:24:22 +00004361 }
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004362 maxchar = utf8_max_char_size_and_char_count(s, size, &unicode_size);
4363 /* In case of errors, maxchar and size computation might be incorrect;
4364 code below refits and resizes as necessary. */
4365 unicode = PyUnicode_New(unicode_size, maxchar);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004366 if (!unicode)
4367 return NULL;
4368 /* When the string is ASCII only, just use memcpy and return.
4369 unicode_size may be != size if there is an incomplete UTF-8
4370 sequence at the end of the ASCII block. */
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004371 if (maxchar < 128 && size == unicode_size) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004372 Py_MEMCPY(PyUnicode_1BYTE_DATA(unicode), s, unicode_size);
4373 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004374 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004375 kind = PyUnicode_KIND(unicode);
4376 data = PyUnicode_DATA(unicode);
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004377
Guido van Rossumd57fd912000-03-10 22:53:23 +00004378 /* Unpack UTF-8 encoded data */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004379 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004380 e = s + size;
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004381 switch (kind) {
4382 case PyUnicode_1BYTE_KIND:
4383 has_errors = ucs1lib_utf8_try_decode(s, e, (Py_UCS1 *) data, &s, &i);
4384 break;
4385 case PyUnicode_2BYTE_KIND:
4386 has_errors = ucs2lib_utf8_try_decode(s, e, (Py_UCS2 *) data, &s, &i);
4387 break;
4388 case PyUnicode_4BYTE_KIND:
4389 has_errors = ucs4lib_utf8_try_decode(s, e, (Py_UCS4 *) data, &s, &i);
4390 break;
4391 }
4392 if (!has_errors) {
4393 /* Ensure the unicode size calculation was correct */
4394 assert(i == unicode_size);
4395 assert(s == e);
4396 if (consumed)
4397 *consumed = s-starts;
4398 return unicode;
4399 }
4400 /* Fall through to the generic decoding loop for the rest of
4401 the string */
4402 if (refit_partial_string(&unicode, kind, data, i) < 0)
4403 goto onError;
4404
Antoine Pitrouab868312009-01-10 15:40:25 +00004405 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004406
4407 while (s < e) {
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004408 Py_UCS4 ch = (unsigned char)*s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004409
4410 if (ch < 0x80) {
Antoine Pitrouab868312009-01-10 15:40:25 +00004411 /* Fast path for runs of ASCII characters. Given that common UTF-8
4412 input will consist of an overwhelming majority of ASCII
4413 characters, we try to optimize for this case by checking
4414 as many characters as a C 'long' can contain.
4415 First, check if we can do an aligned read, as most CPUs have
4416 a penalty for unaligned reads.
4417 */
4418 if (!((size_t) s & LONG_PTR_MASK)) {
4419 /* Help register allocation */
4420 register const char *_s = s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004421 register Py_ssize_t _i = i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004422 while (_s < aligned_end) {
4423 /* Read a whole long at a time (either 4 or 8 bytes),
4424 and do a fast unrolled copy if it only contains ASCII
4425 characters. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004426 unsigned long value = *(unsigned long *) _s;
4427 if (value & ASCII_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00004428 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004429 WRITE_MAYBE_FAIL(_i+0, _s[0]);
4430 WRITE_MAYBE_FAIL(_i+1, _s[1]);
4431 WRITE_MAYBE_FAIL(_i+2, _s[2]);
4432 WRITE_MAYBE_FAIL(_i+3, _s[3]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004433#if (SIZEOF_LONG == 8)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004434 WRITE_MAYBE_FAIL(_i+4, _s[4]);
4435 WRITE_MAYBE_FAIL(_i+5, _s[5]);
4436 WRITE_MAYBE_FAIL(_i+6, _s[6]);
4437 WRITE_MAYBE_FAIL(_i+7, _s[7]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004438#endif
4439 _s += SIZEOF_LONG;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004440 _i += SIZEOF_LONG;
Antoine Pitrouab868312009-01-10 15:40:25 +00004441 }
4442 s = _s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004443 i = _i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004444 if (s == e)
4445 break;
4446 ch = (unsigned char)*s;
4447 }
4448 }
4449
4450 if (ch < 0x80) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004451 WRITE_MAYBE_FAIL(i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004452 s++;
4453 continue;
4454 }
4455
4456 n = utf8_code_length[ch];
4457
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004458 if (s + n > e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004459 if (consumed)
4460 break;
4461 else {
4462 errmsg = "unexpected end of data";
4463 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004464 endinpos = startinpos+1;
4465 for (k=1; (k < size-startinpos) && ((s[k]&0xC0) == 0x80); k++)
4466 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004467 goto utf8Error;
4468 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00004469 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004470
4471 switch (n) {
4472
4473 case 0:
Ezio Melotti57221d02010-07-01 07:32:02 +00004474 errmsg = "invalid start byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004475 startinpos = s-starts;
4476 endinpos = startinpos+1;
4477 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004478
4479 case 1:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004480 errmsg = "internal error";
Benjamin Peterson29060642009-01-31 22:14:21 +00004481 startinpos = s-starts;
4482 endinpos = startinpos+1;
4483 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004484
4485 case 2:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004486 if ((s[1] & 0xc0) != 0x80) {
Ezio Melotti57221d02010-07-01 07:32:02 +00004487 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004488 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004489 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00004490 goto utf8Error;
4491 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004492 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004493 assert ((ch > 0x007F) && (ch <= 0x07FF));
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004494 WRITE_MAYBE_FAIL(i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004495 break;
4496
4497 case 3:
Ezio Melotti9bf2b3a2010-07-03 04:52:19 +00004498 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
4499 will result in surrogates in range d800-dfff. Surrogates are
4500 not valid UTF-8 so they are rejected.
4501 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
4502 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
Tim Petersced69f82003-09-16 20:30:58 +00004503 if ((s[1] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004504 (s[2] & 0xc0) != 0x80 ||
4505 ((unsigned char)s[0] == 0xE0 &&
4506 (unsigned char)s[1] < 0xA0) ||
4507 ((unsigned char)s[0] == 0xED &&
4508 (unsigned char)s[1] > 0x9F)) {
4509 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004510 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004511 endinpos = startinpos + 1;
4512
4513 /* if s[1] first two bits are 1 and 0, then the invalid
4514 continuation byte is s[2], so increment endinpos by 1,
4515 if not, s[1] is invalid and endinpos doesn't need to
4516 be incremented. */
4517 if ((s[1] & 0xC0) == 0x80)
4518 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004519 goto utf8Error;
4520 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004521 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004522 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004523 WRITE_MAYBE_FAIL(i++, ch);
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004524 break;
4525
4526 case 4:
4527 if ((s[1] & 0xc0) != 0x80 ||
4528 (s[2] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004529 (s[3] & 0xc0) != 0x80 ||
4530 ((unsigned char)s[0] == 0xF0 &&
4531 (unsigned char)s[1] < 0x90) ||
4532 ((unsigned char)s[0] == 0xF4 &&
4533 (unsigned char)s[1] > 0x8F)) {
4534 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004535 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004536 endinpos = startinpos + 1;
4537 if ((s[1] & 0xC0) == 0x80) {
4538 endinpos++;
4539 if ((s[2] & 0xC0) == 0x80)
4540 endinpos++;
4541 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004542 goto utf8Error;
4543 }
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004544 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
Ezio Melotti57221d02010-07-01 07:32:02 +00004545 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
4546 assert ((ch > 0xFFFF) && (ch <= 0x10ffff));
4547
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004548 WRITE_MAYBE_FAIL(i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004549 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004550 }
4551 s += n;
Benjamin Peterson29060642009-01-31 22:14:21 +00004552 continue;
Tim Petersced69f82003-09-16 20:30:58 +00004553
Benjamin Peterson29060642009-01-31 22:14:21 +00004554 utf8Error:
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004555 if (!has_errors) {
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004556 if (refit_partial_string(&unicode, kind, data, i) < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004557 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004558 has_errors = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004559 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004560 if (unicode_decode_call_errorhandler(
4561 errors, &errorHandler,
4562 "utf8", errmsg,
4563 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004564 &unicode, &i))
Benjamin Peterson29060642009-01-31 22:14:21 +00004565 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004566 /* Update data because unicode_decode_call_errorhandler might have
4567 re-created or resized the unicode object. */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004568 data = PyUnicode_DATA(unicode);
4569 kind = PyUnicode_KIND(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00004570 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004571 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004572 /* Ensure the unicode_size calculation above was correct: */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004573 assert(has_errors || i == unicode_size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004574
Walter Dörwald69652032004-09-07 20:24:22 +00004575 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00004576 *consumed = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004577
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004578 /* Adjust length and ready string when it contained errors and
4579 is of the old resizable kind. */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004580 if (has_errors) {
Victor Stinner7931d9a2011-11-04 00:22:48 +01004581 if (PyUnicode_Resize(&unicode, i) < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004582 goto onError;
4583 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004584
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004585 Py_XDECREF(errorHandler);
4586 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02004587 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01004588 return unicode;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004589
Benjamin Peterson29060642009-01-31 22:14:21 +00004590 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004591 Py_XDECREF(errorHandler);
4592 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004593 Py_DECREF(unicode);
4594 return NULL;
4595}
4596
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004597#undef WRITE_MAYBE_FAIL
Antoine Pitrouab868312009-01-10 15:40:25 +00004598
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004599#ifdef __APPLE__
4600
4601/* Simplified UTF-8 decoder using surrogateescape error handler,
4602 used to decode the command line arguments on Mac OS X. */
4603
4604wchar_t*
4605_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4606{
4607 int n;
4608 const char *e;
4609 wchar_t *unicode, *p;
4610
4611 /* Note: size will always be longer than the resulting Unicode
4612 character count */
4613 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1)) {
4614 PyErr_NoMemory();
4615 return NULL;
4616 }
4617 unicode = PyMem_Malloc((size + 1) * sizeof(wchar_t));
4618 if (!unicode)
4619 return NULL;
4620
4621 /* Unpack UTF-8 encoded data */
4622 p = unicode;
4623 e = s + size;
4624 while (s < e) {
4625 Py_UCS4 ch = (unsigned char)*s;
4626
4627 if (ch < 0x80) {
4628 *p++ = (wchar_t)ch;
4629 s++;
4630 continue;
4631 }
4632
4633 n = utf8_code_length[ch];
4634 if (s + n > e) {
4635 goto surrogateescape;
4636 }
4637
4638 switch (n) {
4639 case 0:
4640 case 1:
4641 goto surrogateescape;
4642
4643 case 2:
4644 if ((s[1] & 0xc0) != 0x80)
4645 goto surrogateescape;
4646 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
4647 assert ((ch > 0x007F) && (ch <= 0x07FF));
4648 *p++ = (wchar_t)ch;
4649 break;
4650
4651 case 3:
4652 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
4653 will result in surrogates in range d800-dfff. Surrogates are
4654 not valid UTF-8 so they are rejected.
4655 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
4656 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
4657 if ((s[1] & 0xc0) != 0x80 ||
4658 (s[2] & 0xc0) != 0x80 ||
4659 ((unsigned char)s[0] == 0xE0 &&
4660 (unsigned char)s[1] < 0xA0) ||
4661 ((unsigned char)s[0] == 0xED &&
4662 (unsigned char)s[1] > 0x9F)) {
4663
4664 goto surrogateescape;
4665 }
4666 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
4667 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004668 *p++ = (wchar_t)ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004669 break;
4670
4671 case 4:
4672 if ((s[1] & 0xc0) != 0x80 ||
4673 (s[2] & 0xc0) != 0x80 ||
4674 (s[3] & 0xc0) != 0x80 ||
4675 ((unsigned char)s[0] == 0xF0 &&
4676 (unsigned char)s[1] < 0x90) ||
4677 ((unsigned char)s[0] == 0xF4 &&
4678 (unsigned char)s[1] > 0x8F)) {
4679 goto surrogateescape;
4680 }
4681 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
4682 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
4683 assert ((ch > 0xFFFF) && (ch <= 0x10ffff));
4684
4685#if SIZEOF_WCHAR_T == 4
4686 *p++ = (wchar_t)ch;
4687#else
4688 /* compute and append the two surrogates: */
4689
4690 /* translate from 10000..10FFFF to 0..FFFF */
4691 ch -= 0x10000;
4692
4693 /* high surrogate = top 10 bits added to D800 */
4694 *p++ = (wchar_t)(0xD800 + (ch >> 10));
4695
4696 /* low surrogate = bottom 10 bits added to DC00 */
4697 *p++ = (wchar_t)(0xDC00 + (ch & 0x03FF));
4698#endif
4699 break;
4700 }
4701 s += n;
4702 continue;
4703
4704 surrogateescape:
4705 *p++ = 0xDC00 + ch;
4706 s++;
4707 }
4708 *p = L'\0';
4709 return unicode;
4710}
4711
4712#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00004713
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004714/* Primary internal function which creates utf8 encoded bytes objects.
4715
4716 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00004717 and allocate exactly as much space needed at the end. Else allocate the
4718 maximum possible needed (4 result bytes per Unicode character), and return
4719 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004720*/
Tim Peters7e3d9612002-04-21 03:26:37 +00004721PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01004722_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004723{
Tim Peters602f7402002-04-27 18:03:26 +00004724#define MAX_SHORT_UNICHARS 300 /* largest size we'll do on the stack */
Tim Peters0eca65c2002-04-21 17:28:06 +00004725
Guido van Rossum98297ee2007-11-06 21:34:58 +00004726 Py_ssize_t i; /* index into s of next input byte */
4727 PyObject *result; /* result string object */
4728 char *p; /* next free byte in output buffer */
4729 Py_ssize_t nallocated; /* number of result bytes allocated */
4730 Py_ssize_t nneeded; /* number of result bytes needed */
Tim Peters602f7402002-04-27 18:03:26 +00004731 char stackbuf[MAX_SHORT_UNICHARS * 4];
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004732 PyObject *errorHandler = NULL;
4733 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004734 int kind;
4735 void *data;
4736 Py_ssize_t size;
Antoine Pitrou31b92a52011-11-12 18:35:19 +01004737 PyObject *rep = NULL;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00004738
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004739 if (!PyUnicode_Check(unicode)) {
4740 PyErr_BadArgument();
4741 return NULL;
4742 }
4743
4744 if (PyUnicode_READY(unicode) == -1)
4745 return NULL;
4746
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004747 if (PyUnicode_UTF8(unicode))
4748 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
4749 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004750
4751 kind = PyUnicode_KIND(unicode);
4752 data = PyUnicode_DATA(unicode);
4753 size = PyUnicode_GET_LENGTH(unicode);
4754
Tim Peters602f7402002-04-27 18:03:26 +00004755 assert(size >= 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004756
Tim Peters602f7402002-04-27 18:03:26 +00004757 if (size <= MAX_SHORT_UNICHARS) {
4758 /* Write into the stack buffer; nallocated can't overflow.
4759 * At the end, we'll allocate exactly as much heap space as it
4760 * turns out we need.
4761 */
4762 nallocated = Py_SAFE_DOWNCAST(sizeof(stackbuf), size_t, int);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004763 result = NULL; /* will allocate after we're done */
Tim Peters602f7402002-04-27 18:03:26 +00004764 p = stackbuf;
4765 }
4766 else {
4767 /* Overallocate on the heap, and give the excess back at the end. */
4768 nallocated = size * 4;
4769 if (nallocated / 4 != size) /* overflow! */
4770 return PyErr_NoMemory();
Christian Heimes72b710a2008-05-26 13:28:38 +00004771 result = PyBytes_FromStringAndSize(NULL, nallocated);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004772 if (result == NULL)
Tim Peters602f7402002-04-27 18:03:26 +00004773 return NULL;
Christian Heimes72b710a2008-05-26 13:28:38 +00004774 p = PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00004775 }
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004776
Tim Peters602f7402002-04-27 18:03:26 +00004777 for (i = 0; i < size;) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004778 Py_UCS4 ch = PyUnicode_READ(kind, data, i++);
Marc-André Lemburg3688a882002-02-06 18:09:02 +00004779
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004780 if (ch < 0x80)
Tim Peters602f7402002-04-27 18:03:26 +00004781 /* Encode ASCII */
Guido van Rossumd57fd912000-03-10 22:53:23 +00004782 *p++ = (char) ch;
Marc-André Lemburg3688a882002-02-06 18:09:02 +00004783
Guido van Rossumd57fd912000-03-10 22:53:23 +00004784 else if (ch < 0x0800) {
Tim Peters602f7402002-04-27 18:03:26 +00004785 /* Encode Latin-1 */
Marc-André Lemburgdc724d62002-02-06 18:20:19 +00004786 *p++ = (char)(0xc0 | (ch >> 6));
4787 *p++ = (char)(0x80 | (ch & 0x3f));
Victor Stinner31be90b2010-04-22 19:38:16 +00004788 } else if (0xD800 <= ch && ch <= 0xDFFF) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004789 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004790 Py_ssize_t repsize, k, startpos;
4791 startpos = i-1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004792 rep = unicode_encode_call_errorhandler(
4793 errors, &errorHandler, "utf-8", "surrogates not allowed",
Victor Stinner7931d9a2011-11-04 00:22:48 +01004794 unicode, &exc, startpos, startpos+1, &newpos);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004795 if (!rep)
4796 goto error;
Victor Stinner31be90b2010-04-22 19:38:16 +00004797
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004798 if (PyBytes_Check(rep))
4799 repsize = PyBytes_GET_SIZE(rep);
4800 else
Victor Stinner9e30aa52011-11-21 02:49:52 +01004801 repsize = PyUnicode_GET_LENGTH(rep);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004802
4803 if (repsize > 4) {
4804 Py_ssize_t offset;
4805
4806 if (result == NULL)
4807 offset = p - stackbuf;
Victor Stinner31be90b2010-04-22 19:38:16 +00004808 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004809 offset = p - PyBytes_AS_STRING(result);
Victor Stinner31be90b2010-04-22 19:38:16 +00004810
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004811 if (nallocated > PY_SSIZE_T_MAX - repsize + 4) {
4812 /* integer overflow */
4813 PyErr_NoMemory();
4814 goto error;
4815 }
4816 nallocated += repsize - 4;
4817 if (result != NULL) {
4818 if (_PyBytes_Resize(&result, nallocated) < 0)
4819 goto error;
4820 } else {
4821 result = PyBytes_FromStringAndSize(NULL, nallocated);
Victor Stinner31be90b2010-04-22 19:38:16 +00004822 if (result == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004823 goto error;
4824 Py_MEMCPY(PyBytes_AS_STRING(result), stackbuf, offset);
4825 }
4826 p = PyBytes_AS_STRING(result) + offset;
4827 }
Victor Stinner31be90b2010-04-22 19:38:16 +00004828
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004829 if (PyBytes_Check(rep)) {
4830 char *prep = PyBytes_AS_STRING(rep);
4831 for(k = repsize; k > 0; k--)
4832 *p++ = *prep++;
4833 } else /* rep is unicode */ {
Victor Stinnera98b28c2011-11-10 20:21:49 +01004834 enum PyUnicode_Kind repkind;
4835 void *repdata;
4836
Antoine Pitrou31b92a52011-11-12 18:35:19 +01004837 if (PyUnicode_READY(rep) < 0)
Victor Stinnera98b28c2011-11-10 20:21:49 +01004838 goto error;
Victor Stinnera98b28c2011-11-10 20:21:49 +01004839 repkind = PyUnicode_KIND(rep);
4840 repdata = PyUnicode_DATA(rep);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004841
4842 for(k=0; k<repsize; k++) {
Victor Stinnera98b28c2011-11-10 20:21:49 +01004843 Py_UCS4 c = PyUnicode_READ(repkind, repdata, k);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004844 if (0x80 <= c) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01004845 raise_encode_exception(&exc, "utf-8",
Victor Stinner7931d9a2011-11-04 00:22:48 +01004846 unicode,
Martin v. Löwis9e816682011-11-02 12:45:42 +01004847 i-1, i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004848 "surrogates not allowed");
Victor Stinner31be90b2010-04-22 19:38:16 +00004849 goto error;
4850 }
Victor Stinnera98b28c2011-11-10 20:21:49 +01004851 *p++ = (char)c;
Victor Stinner31be90b2010-04-22 19:38:16 +00004852 }
Victor Stinner31be90b2010-04-22 19:38:16 +00004853 }
Antoine Pitrou31b92a52011-11-12 18:35:19 +01004854 Py_CLEAR(rep);
Victor Stinner31be90b2010-04-22 19:38:16 +00004855 } else if (ch < 0x10000) {
4856 *p++ = (char)(0xe0 | (ch >> 12));
4857 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
4858 *p++ = (char)(0x80 | (ch & 0x3f));
4859 } else /* ch >= 0x10000 */ {
Tim Peters602f7402002-04-27 18:03:26 +00004860 /* Encode UCS4 Unicode ordinals */
4861 *p++ = (char)(0xf0 | (ch >> 18));
4862 *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
4863 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
4864 *p++ = (char)(0x80 | (ch & 0x3f));
4865 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004866 }
Tim Peters0eca65c2002-04-21 17:28:06 +00004867
Guido van Rossum98297ee2007-11-06 21:34:58 +00004868 if (result == NULL) {
Tim Peters602f7402002-04-27 18:03:26 +00004869 /* This was stack allocated. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004870 nneeded = p - stackbuf;
Tim Peters602f7402002-04-27 18:03:26 +00004871 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00004872 result = PyBytes_FromStringAndSize(stackbuf, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00004873 }
4874 else {
Christian Heimesf3863112007-11-22 07:46:41 +00004875 /* Cut back to size actually needed. */
Christian Heimes72b710a2008-05-26 13:28:38 +00004876 nneeded = p - PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00004877 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00004878 _PyBytes_Resize(&result, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00004879 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004880
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004881 Py_XDECREF(errorHandler);
4882 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004883 return result;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004884 error:
Antoine Pitrou31b92a52011-11-12 18:35:19 +01004885 Py_XDECREF(rep);
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004886 Py_XDECREF(errorHandler);
4887 Py_XDECREF(exc);
4888 Py_XDECREF(result);
4889 return NULL;
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004890
Tim Peters602f7402002-04-27 18:03:26 +00004891#undef MAX_SHORT_UNICHARS
Guido van Rossumd57fd912000-03-10 22:53:23 +00004892}
4893
Alexander Belopolsky40018472011-02-26 01:02:56 +00004894PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004895PyUnicode_EncodeUTF8(const Py_UNICODE *s,
4896 Py_ssize_t size,
4897 const char *errors)
4898{
4899 PyObject *v, *unicode;
4900
4901 unicode = PyUnicode_FromUnicode(s, size);
4902 if (unicode == NULL)
4903 return NULL;
4904 v = _PyUnicode_AsUTF8String(unicode, errors);
4905 Py_DECREF(unicode);
4906 return v;
4907}
4908
4909PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00004910PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004911{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004912 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004913}
4914
Walter Dörwald41980ca2007-08-16 21:55:45 +00004915/* --- UTF-32 Codec ------------------------------------------------------- */
4916
4917PyObject *
4918PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004919 Py_ssize_t size,
4920 const char *errors,
4921 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004922{
4923 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
4924}
4925
4926PyObject *
4927PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004928 Py_ssize_t size,
4929 const char *errors,
4930 int *byteorder,
4931 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004932{
4933 const char *starts = s;
4934 Py_ssize_t startinpos;
4935 Py_ssize_t endinpos;
4936 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004937 PyObject *unicode;
Mark Dickinson7db923c2010-06-12 09:10:14 +00004938 const unsigned char *q, *e;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004939 int bo = 0; /* assume native ordering by default */
4940 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00004941 /* Offsets from q for retrieving bytes in the right order. */
4942#ifdef BYTEORDER_IS_LITTLE_ENDIAN
4943 int iorder[] = {0, 1, 2, 3};
4944#else
4945 int iorder[] = {3, 2, 1, 0};
4946#endif
4947 PyObject *errorHandler = NULL;
4948 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00004949
Walter Dörwald41980ca2007-08-16 21:55:45 +00004950 q = (unsigned char *)s;
4951 e = q + size;
4952
4953 if (byteorder)
4954 bo = *byteorder;
4955
4956 /* Check for BOM marks (U+FEFF) in the input and adjust current
4957 byte order setting accordingly. In native mode, the leading BOM
4958 mark is skipped, in all other modes, it is copied to the output
4959 stream as-is (giving a ZWNBSP character). */
4960 if (bo == 0) {
4961 if (size >= 4) {
4962 const Py_UCS4 bom = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
Benjamin Peterson29060642009-01-31 22:14:21 +00004963 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00004964#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00004965 if (bom == 0x0000FEFF) {
4966 q += 4;
4967 bo = -1;
4968 }
4969 else if (bom == 0xFFFE0000) {
4970 q += 4;
4971 bo = 1;
4972 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004973#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004974 if (bom == 0x0000FEFF) {
4975 q += 4;
4976 bo = 1;
4977 }
4978 else if (bom == 0xFFFE0000) {
4979 q += 4;
4980 bo = -1;
4981 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004982#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00004983 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004984 }
4985
4986 if (bo == -1) {
4987 /* force LE */
4988 iorder[0] = 0;
4989 iorder[1] = 1;
4990 iorder[2] = 2;
4991 iorder[3] = 3;
4992 }
4993 else if (bo == 1) {
4994 /* force BE */
4995 iorder[0] = 3;
4996 iorder[1] = 2;
4997 iorder[2] = 1;
4998 iorder[3] = 0;
4999 }
5000
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005001 /* This might be one to much, because of a BOM */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005002 unicode = PyUnicode_New((size+3)/4, 127);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005003 if (!unicode)
5004 return NULL;
5005 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005006 return unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005007 outpos = 0;
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005008
Walter Dörwald41980ca2007-08-16 21:55:45 +00005009 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005010 Py_UCS4 ch;
5011 /* remaining bytes at the end? (size should be divisible by 4) */
5012 if (e-q<4) {
5013 if (consumed)
5014 break;
5015 errmsg = "truncated data";
5016 startinpos = ((const char *)q)-starts;
5017 endinpos = ((const char *)e)-starts;
5018 goto utf32Error;
5019 /* The remaining input chars are ignored if the callback
5020 chooses to skip the input */
5021 }
5022 ch = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
5023 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00005024
Benjamin Peterson29060642009-01-31 22:14:21 +00005025 if (ch >= 0x110000)
5026 {
5027 errmsg = "codepoint not in range(0x110000)";
5028 startinpos = ((const char *)q)-starts;
5029 endinpos = startinpos+4;
5030 goto utf32Error;
5031 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005032 if (unicode_putchar(&unicode, &outpos, ch) < 0)
5033 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005034 q += 4;
5035 continue;
5036 utf32Error:
Benjamin Peterson29060642009-01-31 22:14:21 +00005037 if (unicode_decode_call_errorhandler(
5038 errors, &errorHandler,
5039 "utf32", errmsg,
5040 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005041 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005042 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005043 }
5044
5045 if (byteorder)
5046 *byteorder = bo;
5047
5048 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005049 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005050
5051 /* Adjust length */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005052 if (PyUnicode_Resize(&unicode, outpos) < 0)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005053 goto onError;
5054
5055 Py_XDECREF(errorHandler);
5056 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02005057#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02005058 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005059 Py_DECREF(unicode);
5060 return NULL;
5061 }
Victor Stinner17efeed2011-10-04 20:05:46 +02005062#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02005063 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01005064 return unicode;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005065
Benjamin Peterson29060642009-01-31 22:14:21 +00005066 onError:
Walter Dörwald41980ca2007-08-16 21:55:45 +00005067 Py_DECREF(unicode);
5068 Py_XDECREF(errorHandler);
5069 Py_XDECREF(exc);
5070 return NULL;
5071}
5072
5073PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005074_PyUnicode_EncodeUTF32(PyObject *str,
5075 const char *errors,
5076 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005077{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005078 int kind;
5079 void *data;
5080 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005081 PyObject *v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005082 unsigned char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005083 Py_ssize_t nsize, bytesize, i;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005084 /* Offsets from p for storing byte pairs in the right order. */
5085#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5086 int iorder[] = {0, 1, 2, 3};
5087#else
5088 int iorder[] = {3, 2, 1, 0};
5089#endif
5090
Benjamin Peterson29060642009-01-31 22:14:21 +00005091#define STORECHAR(CH) \
5092 do { \
5093 p[iorder[3]] = ((CH) >> 24) & 0xff; \
5094 p[iorder[2]] = ((CH) >> 16) & 0xff; \
5095 p[iorder[1]] = ((CH) >> 8) & 0xff; \
5096 p[iorder[0]] = (CH) & 0xff; \
5097 p += 4; \
Walter Dörwald41980ca2007-08-16 21:55:45 +00005098 } while(0)
5099
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005100 if (!PyUnicode_Check(str)) {
5101 PyErr_BadArgument();
5102 return NULL;
5103 }
5104 if (PyUnicode_READY(str) < 0)
5105 return NULL;
5106 kind = PyUnicode_KIND(str);
5107 data = PyUnicode_DATA(str);
5108 len = PyUnicode_GET_LENGTH(str);
5109
5110 nsize = len + (byteorder == 0);
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005111 bytesize = nsize * 4;
5112 if (bytesize / 4 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005113 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005114 v = PyBytes_FromStringAndSize(NULL, bytesize);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005115 if (v == NULL)
5116 return NULL;
5117
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005118 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005119 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005120 STORECHAR(0xFEFF);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005121 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005122 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005123
5124 if (byteorder == -1) {
5125 /* force LE */
5126 iorder[0] = 0;
5127 iorder[1] = 1;
5128 iorder[2] = 2;
5129 iorder[3] = 3;
5130 }
5131 else if (byteorder == 1) {
5132 /* force BE */
5133 iorder[0] = 3;
5134 iorder[1] = 2;
5135 iorder[2] = 1;
5136 iorder[3] = 0;
5137 }
5138
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005139 for (i = 0; i < len; i++)
5140 STORECHAR(PyUnicode_READ(kind, data, i));
Guido van Rossum98297ee2007-11-06 21:34:58 +00005141
5142 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005143 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005144#undef STORECHAR
5145}
5146
Alexander Belopolsky40018472011-02-26 01:02:56 +00005147PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005148PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5149 Py_ssize_t size,
5150 const char *errors,
5151 int byteorder)
5152{
5153 PyObject *result;
5154 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5155 if (tmp == NULL)
5156 return NULL;
5157 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5158 Py_DECREF(tmp);
5159 return result;
5160}
5161
5162PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005163PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005164{
Victor Stinnerb960b342011-11-20 19:12:52 +01005165 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005166}
5167
Guido van Rossumd57fd912000-03-10 22:53:23 +00005168/* --- UTF-16 Codec ------------------------------------------------------- */
5169
Tim Peters772747b2001-08-09 22:21:55 +00005170PyObject *
5171PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005172 Py_ssize_t size,
5173 const char *errors,
5174 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005175{
Walter Dörwald69652032004-09-07 20:24:22 +00005176 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5177}
5178
Antoine Pitrouab868312009-01-10 15:40:25 +00005179/* Two masks for fast checking of whether a C 'long' may contain
5180 UTF16-encoded surrogate characters. This is an efficient heuristic,
5181 assuming that non-surrogate characters with a code point >= 0x8000 are
5182 rare in most input.
5183 FAST_CHAR_MASK is used when the input is in native byte ordering,
5184 SWAPPED_FAST_CHAR_MASK when the input is in byteswapped ordering.
Benjamin Peterson29060642009-01-31 22:14:21 +00005185*/
Antoine Pitrouab868312009-01-10 15:40:25 +00005186#if (SIZEOF_LONG == 8)
5187# define FAST_CHAR_MASK 0x8000800080008000L
5188# define SWAPPED_FAST_CHAR_MASK 0x0080008000800080L
5189#elif (SIZEOF_LONG == 4)
5190# define FAST_CHAR_MASK 0x80008000L
5191# define SWAPPED_FAST_CHAR_MASK 0x00800080L
5192#else
5193# error C 'long' size should be either 4 or 8!
5194#endif
5195
Walter Dörwald69652032004-09-07 20:24:22 +00005196PyObject *
5197PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005198 Py_ssize_t size,
5199 const char *errors,
5200 int *byteorder,
5201 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005202{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005203 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005204 Py_ssize_t startinpos;
5205 Py_ssize_t endinpos;
5206 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005207 PyObject *unicode;
Antoine Pitrouab868312009-01-10 15:40:25 +00005208 const unsigned char *q, *e, *aligned_end;
Tim Peters772747b2001-08-09 22:21:55 +00005209 int bo = 0; /* assume native ordering by default */
Antoine Pitrouab868312009-01-10 15:40:25 +00005210 int native_ordering = 0;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005211 const char *errmsg = "";
Tim Peters772747b2001-08-09 22:21:55 +00005212 /* Offsets from q for retrieving byte pairs in the right order. */
5213#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5214 int ihi = 1, ilo = 0;
5215#else
5216 int ihi = 0, ilo = 1;
5217#endif
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005218 PyObject *errorHandler = NULL;
5219 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005220
5221 /* Note: size will always be longer than the resulting Unicode
5222 character count */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005223 unicode = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005224 if (!unicode)
5225 return NULL;
5226 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005227 return unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005228 outpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005229
Tim Peters772747b2001-08-09 22:21:55 +00005230 q = (unsigned char *)s;
Antoine Pitrouab868312009-01-10 15:40:25 +00005231 e = q + size - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005232
5233 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005234 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005235
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005236 /* Check for BOM marks (U+FEFF) in the input and adjust current
5237 byte order setting accordingly. In native mode, the leading BOM
5238 mark is skipped, in all other modes, it is copied to the output
5239 stream as-is (giving a ZWNBSP character). */
5240 if (bo == 0) {
Walter Dörwald69652032004-09-07 20:24:22 +00005241 if (size >= 2) {
Victor Stinner24729f32011-11-10 20:31:37 +01005242 const Py_UCS4 bom = (q[ihi] << 8) | q[ilo];
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005243#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00005244 if (bom == 0xFEFF) {
5245 q += 2;
5246 bo = -1;
5247 }
5248 else if (bom == 0xFFFE) {
5249 q += 2;
5250 bo = 1;
5251 }
Tim Petersced69f82003-09-16 20:30:58 +00005252#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005253 if (bom == 0xFEFF) {
5254 q += 2;
5255 bo = 1;
5256 }
5257 else if (bom == 0xFFFE) {
5258 q += 2;
5259 bo = -1;
5260 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005261#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005262 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005263 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005264
Tim Peters772747b2001-08-09 22:21:55 +00005265 if (bo == -1) {
5266 /* force LE */
5267 ihi = 1;
5268 ilo = 0;
5269 }
5270 else if (bo == 1) {
5271 /* force BE */
5272 ihi = 0;
5273 ilo = 1;
5274 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005275#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5276 native_ordering = ilo < ihi;
5277#else
5278 native_ordering = ilo > ihi;
5279#endif
Tim Peters772747b2001-08-09 22:21:55 +00005280
Antoine Pitrouab868312009-01-10 15:40:25 +00005281 aligned_end = (const unsigned char *) ((size_t) e & ~LONG_PTR_MASK);
Tim Peters772747b2001-08-09 22:21:55 +00005282 while (q < e) {
Victor Stinner24729f32011-11-10 20:31:37 +01005283 Py_UCS4 ch;
Antoine Pitrouab868312009-01-10 15:40:25 +00005284 /* First check for possible aligned read of a C 'long'. Unaligned
5285 reads are more expensive, better to defer to another iteration. */
5286 if (!((size_t) q & LONG_PTR_MASK)) {
5287 /* Fast path for runs of non-surrogate chars. */
5288 register const unsigned char *_q = q;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005289 int kind = PyUnicode_KIND(unicode);
5290 void *data = PyUnicode_DATA(unicode);
5291 while (_q < aligned_end) {
5292 unsigned long block = * (unsigned long *) _q;
5293 unsigned short *pblock = (unsigned short*)&block;
5294 Py_UCS4 maxch;
5295 if (native_ordering) {
5296 /* Can use buffer directly */
5297 if (block & FAST_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00005298 break;
Antoine Pitrouab868312009-01-10 15:40:25 +00005299 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005300 else {
5301 /* Need to byte-swap */
5302 unsigned char *_p = (unsigned char*)pblock;
5303 if (block & SWAPPED_FAST_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00005304 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005305 _p[0] = _q[1];
5306 _p[1] = _q[0];
5307 _p[2] = _q[3];
5308 _p[3] = _q[2];
Antoine Pitrouab868312009-01-10 15:40:25 +00005309#if (SIZEOF_LONG == 8)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005310 _p[4] = _q[5];
5311 _p[5] = _q[4];
5312 _p[6] = _q[7];
5313 _p[7] = _q[6];
Antoine Pitrouab868312009-01-10 15:40:25 +00005314#endif
Antoine Pitrouab868312009-01-10 15:40:25 +00005315 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005316 maxch = Py_MAX(pblock[0], pblock[1]);
5317#if SIZEOF_LONG == 8
5318 maxch = Py_MAX(maxch, Py_MAX(pblock[2], pblock[3]));
5319#endif
5320 if (maxch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
5321 if (unicode_widen(&unicode, maxch) < 0)
5322 goto onError;
5323 kind = PyUnicode_KIND(unicode);
5324 data = PyUnicode_DATA(unicode);
5325 }
5326 PyUnicode_WRITE(kind, data, outpos++, pblock[0]);
5327 PyUnicode_WRITE(kind, data, outpos++, pblock[1]);
5328#if SIZEOF_LONG == 8
5329 PyUnicode_WRITE(kind, data, outpos++, pblock[2]);
5330 PyUnicode_WRITE(kind, data, outpos++, pblock[3]);
5331#endif
5332 _q += SIZEOF_LONG;
Antoine Pitrouab868312009-01-10 15:40:25 +00005333 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005334 q = _q;
5335 if (q >= e)
5336 break;
5337 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005338 ch = (q[ihi] << 8) | q[ilo];
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005339
Benjamin Peterson14339b62009-01-31 16:36:08 +00005340 q += 2;
Benjamin Peterson29060642009-01-31 22:14:21 +00005341
5342 if (ch < 0xD800 || ch > 0xDFFF) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005343 if (unicode_putchar(&unicode, &outpos, ch) < 0)
5344 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005345 continue;
5346 }
5347
5348 /* UTF-16 code pair: */
5349 if (q > e) {
5350 errmsg = "unexpected end of data";
5351 startinpos = (((const char *)q) - 2) - starts;
5352 endinpos = ((const char *)e) + 1 - starts;
5353 goto utf16Error;
5354 }
Victor Stinner2e9cfad2011-11-20 18:40:27 +01005355 if (Py_UNICODE_IS_HIGH_SURROGATE(ch)) {
5356 Py_UCS4 ch2 = (q[ihi] << 8) | q[ilo];
Benjamin Peterson29060642009-01-31 22:14:21 +00005357 q += 2;
Victor Stinner2e9cfad2011-11-20 18:40:27 +01005358 if (Py_UNICODE_IS_LOW_SURROGATE(ch2)) {
Victor Stinner62aa4d02011-11-09 00:03:45 +01005359 if (unicode_putchar(&unicode, &outpos,
Victor Stinner2e9cfad2011-11-20 18:40:27 +01005360 Py_UNICODE_JOIN_SURROGATES(ch, ch2)) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005361 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005362 continue;
5363 }
5364 else {
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005365 errmsg = "illegal UTF-16 surrogate";
Benjamin Peterson29060642009-01-31 22:14:21 +00005366 startinpos = (((const char *)q)-4)-starts;
5367 endinpos = startinpos+2;
5368 goto utf16Error;
5369 }
5370
Benjamin Peterson14339b62009-01-31 16:36:08 +00005371 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005372 errmsg = "illegal encoding";
5373 startinpos = (((const char *)q)-2)-starts;
5374 endinpos = startinpos+2;
5375 /* Fall through to report the error */
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005376
Benjamin Peterson29060642009-01-31 22:14:21 +00005377 utf16Error:
Benjamin Peterson29060642009-01-31 22:14:21 +00005378 if (unicode_decode_call_errorhandler(
Antoine Pitrouab868312009-01-10 15:40:25 +00005379 errors,
5380 &errorHandler,
5381 "utf16", errmsg,
5382 &starts,
5383 (const char **)&e,
5384 &startinpos,
5385 &endinpos,
5386 &exc,
5387 (const char **)&q,
5388 &unicode,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005389 &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005390 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005391 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005392 /* remaining byte at the end? (size should be even) */
5393 if (e == q) {
5394 if (!consumed) {
5395 errmsg = "truncated data";
5396 startinpos = ((const char *)q) - starts;
5397 endinpos = ((const char *)e) + 1 - starts;
Antoine Pitrouab868312009-01-10 15:40:25 +00005398 if (unicode_decode_call_errorhandler(
5399 errors,
5400 &errorHandler,
5401 "utf16", errmsg,
5402 &starts,
5403 (const char **)&e,
5404 &startinpos,
5405 &endinpos,
5406 &exc,
5407 (const char **)&q,
5408 &unicode,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005409 &outpos))
Antoine Pitrouab868312009-01-10 15:40:25 +00005410 goto onError;
5411 /* The remaining input chars are ignored if the callback
5412 chooses to skip the input */
5413 }
5414 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005415
5416 if (byteorder)
5417 *byteorder = bo;
5418
Walter Dörwald69652032004-09-07 20:24:22 +00005419 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005420 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005421
Guido van Rossumd57fd912000-03-10 22:53:23 +00005422 /* Adjust length */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005423 if (PyUnicode_Resize(&unicode, outpos) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005424 goto onError;
5425
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005426 Py_XDECREF(errorHandler);
5427 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02005428 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01005429 return unicode;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005430
Benjamin Peterson29060642009-01-31 22:14:21 +00005431 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005432 Py_DECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005433 Py_XDECREF(errorHandler);
5434 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005435 return NULL;
5436}
5437
Antoine Pitrouab868312009-01-10 15:40:25 +00005438#undef FAST_CHAR_MASK
5439#undef SWAPPED_FAST_CHAR_MASK
5440
Tim Peters772747b2001-08-09 22:21:55 +00005441PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005442_PyUnicode_EncodeUTF16(PyObject *str,
5443 const char *errors,
5444 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005445{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005446 int kind;
5447 void *data;
5448 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005449 PyObject *v;
Tim Peters772747b2001-08-09 22:21:55 +00005450 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005451 Py_ssize_t nsize, bytesize;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005452 Py_ssize_t i, pairs;
Tim Peters772747b2001-08-09 22:21:55 +00005453 /* Offsets from p for storing byte pairs in the right order. */
5454#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5455 int ihi = 1, ilo = 0;
5456#else
5457 int ihi = 0, ilo = 1;
5458#endif
5459
Benjamin Peterson29060642009-01-31 22:14:21 +00005460#define STORECHAR(CH) \
5461 do { \
5462 p[ihi] = ((CH) >> 8) & 0xff; \
5463 p[ilo] = (CH) & 0xff; \
5464 p += 2; \
Tim Peters772747b2001-08-09 22:21:55 +00005465 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005466
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005467 if (!PyUnicode_Check(str)) {
5468 PyErr_BadArgument();
5469 return NULL;
5470 }
5471 if (PyUnicode_READY(str) < 0)
5472 return NULL;
5473 kind = PyUnicode_KIND(str);
5474 data = PyUnicode_DATA(str);
5475 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005476
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005477 pairs = 0;
5478 if (kind == PyUnicode_4BYTE_KIND)
5479 for (i = 0; i < len; i++)
5480 if (PyUnicode_READ(kind, data, i) >= 0x10000)
5481 pairs++;
5482 /* 2 * (len + pairs + (byteorder == 0)) */
5483 if (len > PY_SSIZE_T_MAX - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005484 return PyErr_NoMemory();
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005485 nsize = len + pairs + (byteorder == 0);
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005486 bytesize = nsize * 2;
5487 if (bytesize / 2 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005488 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005489 v = PyBytes_FromStringAndSize(NULL, bytesize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005490 if (v == NULL)
5491 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005492
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005493 p = (unsigned char *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005494 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005495 STORECHAR(0xFEFF);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005496 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005497 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005498
5499 if (byteorder == -1) {
5500 /* force LE */
5501 ihi = 1;
5502 ilo = 0;
5503 }
5504 else if (byteorder == 1) {
5505 /* force BE */
5506 ihi = 0;
5507 ilo = 1;
5508 }
5509
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005510 for (i = 0; i < len; i++) {
5511 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
5512 Py_UCS4 ch2 = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +00005513 if (ch >= 0x10000) {
5514 ch2 = 0xDC00 | ((ch-0x10000) & 0x3FF);
5515 ch = 0xD800 | ((ch-0x10000) >> 10);
5516 }
Tim Peters772747b2001-08-09 22:21:55 +00005517 STORECHAR(ch);
5518 if (ch2)
5519 STORECHAR(ch2);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005520 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005521
5522 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005523 return v;
Tim Peters772747b2001-08-09 22:21:55 +00005524#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005525}
5526
Alexander Belopolsky40018472011-02-26 01:02:56 +00005527PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005528PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5529 Py_ssize_t size,
5530 const char *errors,
5531 int byteorder)
5532{
5533 PyObject *result;
5534 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5535 if (tmp == NULL)
5536 return NULL;
5537 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5538 Py_DECREF(tmp);
5539 return result;
5540}
5541
5542PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005543PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005544{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005545 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005546}
5547
5548/* --- Unicode Escape Codec ----------------------------------------------- */
5549
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005550/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5551 if all the escapes in the string make it still a valid ASCII string.
5552 Returns -1 if any escapes were found which cause the string to
5553 pop out of ASCII range. Otherwise returns the length of the
5554 required buffer to hold the string.
5555 */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02005556static Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005557length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5558{
5559 const unsigned char *p = (const unsigned char *)s;
5560 const unsigned char *end = p + size;
5561 Py_ssize_t length = 0;
5562
5563 if (size < 0)
5564 return -1;
5565
5566 for (; p < end; ++p) {
5567 if (*p > 127) {
5568 /* Non-ASCII */
5569 return -1;
5570 }
5571 else if (*p != '\\') {
5572 /* Normal character */
5573 ++length;
5574 }
5575 else {
5576 /* Backslash-escape, check next char */
5577 ++p;
5578 /* Escape sequence reaches till end of string or
5579 non-ASCII follow-up. */
5580 if (p >= end || *p > 127)
5581 return -1;
5582 switch (*p) {
5583 case '\n':
5584 /* backslash + \n result in zero characters */
5585 break;
5586 case '\\': case '\'': case '\"':
5587 case 'b': case 'f': case 't':
5588 case 'n': case 'r': case 'v': case 'a':
5589 ++length;
5590 break;
5591 case '0': case '1': case '2': case '3':
5592 case '4': case '5': case '6': case '7':
5593 case 'x': case 'u': case 'U': case 'N':
5594 /* these do not guarantee ASCII characters */
5595 return -1;
5596 default:
5597 /* count the backslash + the other character */
5598 length += 2;
5599 }
5600 }
5601 }
5602 return length;
5603}
5604
Fredrik Lundh06d12682001-01-24 07:59:11 +00005605static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005606
Alexander Belopolsky40018472011-02-26 01:02:56 +00005607PyObject *
5608PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005609 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005610 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005611{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005612 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005613 Py_ssize_t startinpos;
5614 Py_ssize_t endinpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005615 int j;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005616 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005617 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005618 char* message;
5619 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005620 PyObject *errorHandler = NULL;
5621 PyObject *exc = NULL;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005622 Py_ssize_t len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005623 Py_ssize_t i;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005624
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005625 len = length_of_escaped_ascii_string(s, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005626
5627 /* After length_of_escaped_ascii_string() there are two alternatives,
5628 either the string is pure ASCII with named escapes like \n, etc.
5629 and we determined it's exact size (common case)
5630 or it contains \x, \u, ... escape sequences. then we create a
5631 legacy wchar string and resize it at the end of this function. */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005632 if (len >= 0) {
5633 v = PyUnicode_New(len, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005634 if (!v)
5635 goto onError;
5636 assert(PyUnicode_KIND(v) == PyUnicode_1BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005637 }
5638 else {
5639 /* Escaped strings will always be longer than the resulting
5640 Unicode string, so we start with size here and then reduce the
5641 length after conversion to the true value.
5642 (but if the error callback returns a long replacement string
5643 we'll have to allocate more space) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005644 v = PyUnicode_New(size, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005645 if (!v)
5646 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005647 len = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005648 }
5649
Guido van Rossumd57fd912000-03-10 22:53:23 +00005650 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005651 return v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005652 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005653 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005654
Guido van Rossumd57fd912000-03-10 22:53:23 +00005655 while (s < end) {
5656 unsigned char c;
Victor Stinner24729f32011-11-10 20:31:37 +01005657 Py_UCS4 x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005658 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005659
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005660 /* The only case in which i == ascii_length is a backslash
5661 followed by a newline. */
5662 assert(i <= len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005663
Guido van Rossumd57fd912000-03-10 22:53:23 +00005664 /* Non-escape characters are interpreted as Unicode ordinals */
5665 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005666 if (unicode_putchar(&v, &i, (unsigned char) *s++) < 0)
5667 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005668 continue;
5669 }
5670
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005671 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005672 /* \ - Escapes */
5673 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005674 c = *s++;
5675 if (s > end)
5676 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005677
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005678 /* The only case in which i == ascii_length is a backslash
5679 followed by a newline. */
5680 assert(i < len || (i == len && c == '\n'));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005681
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005682 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005683
Benjamin Peterson29060642009-01-31 22:14:21 +00005684 /* \x escapes */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005685#define WRITECHAR(ch) \
5686 do { \
5687 if (unicode_putchar(&v, &i, ch) < 0) \
5688 goto onError; \
5689 }while(0)
5690
Guido van Rossumd57fd912000-03-10 22:53:23 +00005691 case '\n': break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005692 case '\\': WRITECHAR('\\'); break;
5693 case '\'': WRITECHAR('\''); break;
5694 case '\"': WRITECHAR('\"'); break;
5695 case 'b': WRITECHAR('\b'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005696 /* FF */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005697 case 'f': WRITECHAR('\014'); break;
5698 case 't': WRITECHAR('\t'); break;
5699 case 'n': WRITECHAR('\n'); break;
5700 case 'r': WRITECHAR('\r'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005701 /* VT */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005702 case 'v': WRITECHAR('\013'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005703 /* BEL, not classic C */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005704 case 'a': WRITECHAR('\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005705
Benjamin Peterson29060642009-01-31 22:14:21 +00005706 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005707 case '0': case '1': case '2': case '3':
5708 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005709 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005710 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005711 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005712 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005713 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00005714 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005715 WRITECHAR(x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005716 break;
5717
Benjamin Peterson29060642009-01-31 22:14:21 +00005718 /* hex escapes */
5719 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005720 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005721 digits = 2;
5722 message = "truncated \\xXX escape";
5723 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005724
Benjamin Peterson29060642009-01-31 22:14:21 +00005725 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005726 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005727 digits = 4;
5728 message = "truncated \\uXXXX escape";
5729 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005730
Benjamin Peterson29060642009-01-31 22:14:21 +00005731 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005732 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005733 digits = 8;
5734 message = "truncated \\UXXXXXXXX escape";
5735 hexescape:
5736 chr = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005737 if (s+digits>end) {
5738 endinpos = size;
5739 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005740 errors, &errorHandler,
5741 "unicodeescape", "end of string in escape sequence",
5742 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005743 &v, &i))
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005744 goto onError;
5745 goto nextByte;
5746 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005747 for (j = 0; j < digits; ++j) {
5748 c = (unsigned char) s[j];
David Malcolm96960882010-11-05 17:23:41 +00005749 if (!Py_ISXDIGIT(c)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005750 endinpos = (s+j+1)-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005751 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005752 errors, &errorHandler,
5753 "unicodeescape", message,
5754 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005755 &v, &i))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005756 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005757 len = PyUnicode_GET_LENGTH(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005758 goto nextByte;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005759 }
5760 chr = (chr<<4) & ~0xF;
5761 if (c >= '0' && c <= '9')
5762 chr += c - '0';
5763 else if (c >= 'a' && c <= 'f')
5764 chr += 10 + c - 'a';
5765 else
5766 chr += 10 + c - 'A';
5767 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005768 s += j;
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005769 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005770 /* _decoding_error will have already written into the
5771 target buffer. */
5772 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005773 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005774 /* when we get here, chr is a 32-bit unicode character */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005775 if (chr <= 0x10ffff) {
5776 WRITECHAR(chr);
Fredrik Lundhdf846752000-09-03 11:29:49 +00005777 } else {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005778 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005779 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005780 errors, &errorHandler,
5781 "unicodeescape", "illegal Unicode character",
5782 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005783 &v, &i))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005784 goto onError;
5785 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005786 break;
5787
Benjamin Peterson29060642009-01-31 22:14:21 +00005788 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005789 case 'N':
5790 message = "malformed \\N character escape";
5791 if (ucnhash_CAPI == NULL) {
5792 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005793 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
5794 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005795 if (ucnhash_CAPI == NULL)
5796 goto ucnhashError;
5797 }
5798 if (*s == '{') {
5799 const char *start = s+1;
5800 /* look for the closing brace */
5801 while (*s != '}' && s < end)
5802 s++;
5803 if (s > start && s < end && *s == '}') {
5804 /* found a name. look it up in the unicode database */
5805 message = "unknown Unicode character name";
5806 s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005807 if (ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
Ezio Melotti931b8aa2011-10-21 21:57:36 +03005808 &chr, 0))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005809 goto store;
5810 }
5811 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005812 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005813 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005814 errors, &errorHandler,
5815 "unicodeescape", message,
5816 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005817 &v, &i))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005818 goto onError;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005819 break;
5820
5821 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00005822 if (s > end) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005823 message = "\\ at end of string";
5824 s--;
5825 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005826 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005827 errors, &errorHandler,
5828 "unicodeescape", message,
5829 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005830 &v, &i))
Walter Dörwald8c077222002-03-25 11:16:18 +00005831 goto onError;
5832 }
5833 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005834 WRITECHAR('\\');
5835 WRITECHAR(s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00005836 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005837 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005838 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005839 nextByte:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005840 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005841 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005842#undef WRITECHAR
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005843
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005844 if (PyUnicode_Resize(&v, i) < 0)
5845 goto onError;
Walter Dörwaldd4ade082003-08-15 15:00:26 +00005846 Py_XDECREF(errorHandler);
5847 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02005848#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02005849 if (_PyUnicode_READY_REPLACE(&v)) {
5850 Py_DECREF(v);
5851 return NULL;
5852 }
Victor Stinner17efeed2011-10-04 20:05:46 +02005853#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02005854 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01005855 return v;
Walter Dörwald8c077222002-03-25 11:16:18 +00005856
Benjamin Peterson29060642009-01-31 22:14:21 +00005857 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00005858 PyErr_SetString(
5859 PyExc_UnicodeError,
5860 "\\N escapes not supported (can't load unicodedata module)"
5861 );
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00005862 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005863 Py_XDECREF(errorHandler);
5864 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00005865 return NULL;
5866
Benjamin Peterson29060642009-01-31 22:14:21 +00005867 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005868 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005869 Py_XDECREF(errorHandler);
5870 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005871 return NULL;
5872}
5873
5874/* Return a Unicode-Escape string version of the Unicode object.
5875
5876 If quotes is true, the string is enclosed in u"" or u'' quotes as
5877 appropriate.
5878
5879*/
5880
Alexander Belopolsky40018472011-02-26 01:02:56 +00005881PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005882PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005883{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005884 Py_ssize_t i, len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005885 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005886 char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005887 int kind;
5888 void *data;
5889 Py_ssize_t expandsize = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005890
Thomas Wouters89f507f2006-12-13 04:49:30 +00005891 /* Initial allocation is based on the longest-possible unichr
5892 escape.
5893
5894 In wide (UTF-32) builds '\U00xxxxxx' is 10 chars per source
5895 unichr, so in this case it's the longest unichr escape. In
5896 narrow (UTF-16) builds this is five chars per source unichr
5897 since there are two unichrs in the surrogate pair, so in narrow
5898 (UTF-16) builds it's not the longest unichr escape.
5899
5900 In wide or narrow builds '\uxxxx' is 6 chars per source unichr,
5901 so in the narrow (UTF-16) build case it's the longest unichr
5902 escape.
5903 */
5904
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005905 if (!PyUnicode_Check(unicode)) {
5906 PyErr_BadArgument();
5907 return NULL;
5908 }
5909 if (PyUnicode_READY(unicode) < 0)
5910 return NULL;
5911 len = PyUnicode_GET_LENGTH(unicode);
5912 kind = PyUnicode_KIND(unicode);
5913 data = PyUnicode_DATA(unicode);
5914 switch(kind) {
5915 case PyUnicode_1BYTE_KIND: expandsize = 4; break;
5916 case PyUnicode_2BYTE_KIND: expandsize = 6; break;
5917 case PyUnicode_4BYTE_KIND: expandsize = 10; break;
5918 }
5919
5920 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005921 return PyBytes_FromStringAndSize(NULL, 0);
5922
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005923 if (len > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005924 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005925
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005926 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00005927 2
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005928 + expandsize*len
Benjamin Peterson29060642009-01-31 22:14:21 +00005929 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005930 if (repr == NULL)
5931 return NULL;
5932
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005933 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005934
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005935 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01005936 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005937
Walter Dörwald79e913e2007-05-12 11:08:06 +00005938 /* Escape backslashes */
5939 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005940 *p++ = '\\';
5941 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00005942 continue;
Tim Petersced69f82003-09-16 20:30:58 +00005943 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005944
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005945 /* Map 21-bit characters to '\U00xxxxxx' */
5946 else if (ch >= 0x10000) {
5947 *p++ = '\\';
5948 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005949 *p++ = Py_hexdigits[(ch >> 28) & 0x0000000F];
5950 *p++ = Py_hexdigits[(ch >> 24) & 0x0000000F];
5951 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
5952 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
5953 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
5954 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
5955 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
5956 *p++ = Py_hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00005957 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005958 }
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005959
Guido van Rossumd57fd912000-03-10 22:53:23 +00005960 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005961 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005962 *p++ = '\\';
5963 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005964 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
5965 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
5966 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
5967 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00005968 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005969
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005970 /* Map special whitespace to '\t', \n', '\r' */
5971 else if (ch == '\t') {
5972 *p++ = '\\';
5973 *p++ = 't';
5974 }
5975 else if (ch == '\n') {
5976 *p++ = '\\';
5977 *p++ = 'n';
5978 }
5979 else if (ch == '\r') {
5980 *p++ = '\\';
5981 *p++ = 'r';
5982 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005983
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005984 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00005985 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005986 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005987 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005988 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
5989 *p++ = Py_hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00005990 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005991
Guido van Rossumd57fd912000-03-10 22:53:23 +00005992 /* Copy everything else as-is */
5993 else
5994 *p++ = (char) ch;
5995 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005996
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005997 assert(p - PyBytes_AS_STRING(repr) > 0);
5998 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
5999 return NULL;
6000 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006001}
6002
Alexander Belopolsky40018472011-02-26 01:02:56 +00006003PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006004PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
6005 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006006{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006007 PyObject *result;
6008 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6009 if (tmp == NULL)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006010 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006011 result = PyUnicode_AsUnicodeEscapeString(tmp);
6012 Py_DECREF(tmp);
6013 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006014}
6015
6016/* --- Raw Unicode Escape Codec ------------------------------------------- */
6017
Alexander Belopolsky40018472011-02-26 01:02:56 +00006018PyObject *
6019PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006020 Py_ssize_t size,
6021 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006022{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006023 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006024 Py_ssize_t startinpos;
6025 Py_ssize_t endinpos;
6026 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006027 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006028 const char *end;
6029 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006030 PyObject *errorHandler = NULL;
6031 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006032
Guido van Rossumd57fd912000-03-10 22:53:23 +00006033 /* Escaped strings will always be longer than the resulting
6034 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006035 length after conversion to the true value. (But decoding error
6036 handler might have to resize the string) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006037 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006038 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006039 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006040 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006041 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006042 outpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006043 end = s + size;
6044 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006045 unsigned char c;
6046 Py_UCS4 x;
6047 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006048 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006049
Benjamin Peterson29060642009-01-31 22:14:21 +00006050 /* Non-escape characters are interpreted as Unicode ordinals */
6051 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006052 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
6053 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006054 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006055 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006056 startinpos = s-starts;
6057
6058 /* \u-escapes are only interpreted iff the number of leading
6059 backslashes if odd */
6060 bs = s;
6061 for (;s < end;) {
6062 if (*s != '\\')
6063 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006064 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
6065 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006066 }
6067 if (((s - bs) & 1) == 0 ||
6068 s >= end ||
6069 (*s != 'u' && *s != 'U')) {
6070 continue;
6071 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006072 outpos--;
Benjamin Peterson29060642009-01-31 22:14:21 +00006073 count = *s=='u' ? 4 : 8;
6074 s++;
6075
6076 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
Benjamin Peterson29060642009-01-31 22:14:21 +00006077 for (x = 0, i = 0; i < count; ++i, ++s) {
6078 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00006079 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006080 endinpos = s-starts;
6081 if (unicode_decode_call_errorhandler(
6082 errors, &errorHandler,
6083 "rawunicodeescape", "truncated \\uXXXX",
6084 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006085 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006086 goto onError;
6087 goto nextByte;
6088 }
6089 x = (x<<4) & ~0xF;
6090 if (c >= '0' && c <= '9')
6091 x += c - '0';
6092 else if (c >= 'a' && c <= 'f')
6093 x += 10 + c - 'a';
6094 else
6095 x += 10 + c - 'A';
6096 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006097 if (x <= 0x10ffff) {
6098 if (unicode_putchar(&v, &outpos, x) < 0)
6099 goto onError;
Christian Heimesfe337bf2008-03-23 21:54:12 +00006100 } else {
6101 endinpos = s-starts;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006102 if (unicode_decode_call_errorhandler(
6103 errors, &errorHandler,
6104 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00006105 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006106 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006107 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006108 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006109 nextByte:
6110 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006111 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006112 if (PyUnicode_Resize(&v, outpos) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006113 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006114 Py_XDECREF(errorHandler);
6115 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006116 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01006117 return v;
Tim Petersced69f82003-09-16 20:30:58 +00006118
Benjamin Peterson29060642009-01-31 22:14:21 +00006119 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006120 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006121 Py_XDECREF(errorHandler);
6122 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006123 return NULL;
6124}
6125
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006126
Alexander Belopolsky40018472011-02-26 01:02:56 +00006127PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006128PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006129{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006130 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006131 char *p;
6132 char *q;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006133 Py_ssize_t expandsize, pos;
6134 int kind;
6135 void *data;
6136 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006137
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006138 if (!PyUnicode_Check(unicode)) {
6139 PyErr_BadArgument();
6140 return NULL;
6141 }
6142 if (PyUnicode_READY(unicode) < 0)
6143 return NULL;
6144 kind = PyUnicode_KIND(unicode);
6145 data = PyUnicode_DATA(unicode);
6146 len = PyUnicode_GET_LENGTH(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006147
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006148 switch(kind) {
6149 case PyUnicode_1BYTE_KIND: expandsize = 4; break;
6150 case PyUnicode_2BYTE_KIND: expandsize = 6; break;
6151 case PyUnicode_4BYTE_KIND: expandsize = 10; break;
6152 }
Victor Stinner0e368262011-11-10 20:12:49 +01006153
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006154 if (len > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006155 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00006156
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006157 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006158 if (repr == NULL)
6159 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006160 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006161 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006162
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006163 p = q = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006164 for (pos = 0; pos < len; pos++) {
6165 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006166 /* Map 32-bit characters to '\Uxxxxxxxx' */
6167 if (ch >= 0x10000) {
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006168 *p++ = '\\';
6169 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006170 *p++ = Py_hexdigits[(ch >> 28) & 0xf];
6171 *p++ = Py_hexdigits[(ch >> 24) & 0xf];
6172 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6173 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6174 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6175 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6176 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6177 *p++ = Py_hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00006178 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006179 /* Map 16-bit characters to '\uxxxx' */
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006180 else if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006181 *p++ = '\\';
6182 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006183 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6184 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6185 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6186 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006187 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006188 /* Copy everything else as-is */
6189 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00006190 *p++ = (char) ch;
6191 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006192
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006193 assert(p > q);
6194 if (_PyBytes_Resize(&repr, p - q) < 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006195 return NULL;
6196 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006197}
6198
Alexander Belopolsky40018472011-02-26 01:02:56 +00006199PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006200PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6201 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006202{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006203 PyObject *result;
6204 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6205 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006206 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006207 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6208 Py_DECREF(tmp);
6209 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006210}
6211
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006212/* --- Unicode Internal Codec ------------------------------------------- */
6213
Alexander Belopolsky40018472011-02-26 01:02:56 +00006214PyObject *
6215_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006216 Py_ssize_t size,
6217 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006218{
6219 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006220 Py_ssize_t startinpos;
6221 Py_ssize_t endinpos;
6222 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006223 PyObject *v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006224 const char *end;
6225 const char *reason;
6226 PyObject *errorHandler = NULL;
6227 PyObject *exc = NULL;
6228
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006229 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006230 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006231 1))
6232 return NULL;
6233
Thomas Wouters89f507f2006-12-13 04:49:30 +00006234 /* XXX overflow detection missing */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006235 v = PyUnicode_New((size+Py_UNICODE_SIZE-1)/ Py_UNICODE_SIZE, 127);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006236 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006237 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006238 if (PyUnicode_GET_LENGTH(v) == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006239 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006240 outpos = 0;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006241 end = s + size;
6242
6243 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006244 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006245 Py_UCS4 ch;
6246 /* We copy the raw representation one byte at a time because the
6247 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006248 ((char *) &uch)[0] = s[0];
6249 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006250#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006251 ((char *) &uch)[2] = s[2];
6252 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006253#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006254 ch = uch;
6255
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006256 /* We have to sanity check the raw data, otherwise doom looms for
6257 some malformed UCS-4 data. */
6258 if (
Benjamin Peterson29060642009-01-31 22:14:21 +00006259#ifdef Py_UNICODE_WIDE
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006260 ch > 0x10ffff ||
Benjamin Peterson29060642009-01-31 22:14:21 +00006261#endif
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006262 end-s < Py_UNICODE_SIZE
6263 )
Benjamin Peterson29060642009-01-31 22:14:21 +00006264 {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006265 startinpos = s - starts;
6266 if (end-s < Py_UNICODE_SIZE) {
6267 endinpos = end-starts;
6268 reason = "truncated input";
6269 }
6270 else {
6271 endinpos = s - starts + Py_UNICODE_SIZE;
6272 reason = "illegal code point (> 0x10FFFF)";
6273 }
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006274 if (unicode_decode_call_errorhandler(
6275 errors, &errorHandler,
6276 "unicode_internal", reason,
Walter Dörwalde78178e2007-07-30 13:31:40 +00006277 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006278 &v, &outpos))
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006279 goto onError;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006280 continue;
6281 }
6282
6283 s += Py_UNICODE_SIZE;
6284#ifndef Py_UNICODE_WIDE
6285 if (ch >= 0xD800 && ch <= 0xDBFF && s < end)
6286 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006287 Py_UNICODE uch2;
6288 ((char *) &uch2)[0] = s[0];
6289 ((char *) &uch2)[1] = s[1];
6290 if (uch2 >= 0xDC00 && uch2 <= 0xDFFF)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006291 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006292 ch = (((uch & 0x3FF)<<10) | (uch2 & 0x3FF)) + 0x10000;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006293 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006294 }
6295 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006296#endif
6297
6298 if (unicode_putchar(&v, &outpos, ch) < 0)
6299 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006300 }
6301
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006302 if (PyUnicode_Resize(&v, outpos) < 0)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006303 goto onError;
6304 Py_XDECREF(errorHandler);
6305 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006306 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01006307 return v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006308
Benjamin Peterson29060642009-01-31 22:14:21 +00006309 onError:
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006310 Py_XDECREF(v);
6311 Py_XDECREF(errorHandler);
6312 Py_XDECREF(exc);
6313 return NULL;
6314}
6315
Guido van Rossumd57fd912000-03-10 22:53:23 +00006316/* --- Latin-1 Codec ------------------------------------------------------ */
6317
Alexander Belopolsky40018472011-02-26 01:02:56 +00006318PyObject *
6319PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006320 Py_ssize_t size,
6321 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006322{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006323 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006324 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006325}
6326
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006327/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006328static void
6329make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006330 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006331 PyObject *unicode,
6332 Py_ssize_t startpos, Py_ssize_t endpos,
6333 const char *reason)
6334{
6335 if (*exceptionObject == NULL) {
6336 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006337 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006338 encoding, unicode, startpos, endpos, reason);
6339 }
6340 else {
6341 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6342 goto onError;
6343 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6344 goto onError;
6345 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6346 goto onError;
6347 return;
6348 onError:
6349 Py_DECREF(*exceptionObject);
6350 *exceptionObject = NULL;
6351 }
6352}
6353
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006354/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006355static void
6356raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006357 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006358 PyObject *unicode,
6359 Py_ssize_t startpos, Py_ssize_t endpos,
6360 const char *reason)
6361{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006362 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006363 encoding, unicode, startpos, endpos, reason);
6364 if (*exceptionObject != NULL)
6365 PyCodec_StrictErrors(*exceptionObject);
6366}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006367
6368/* error handling callback helper:
6369 build arguments, call the callback and check the arguments,
6370 put the result into newpos and return the replacement string, which
6371 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006372static PyObject *
6373unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006374 PyObject **errorHandler,
6375 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006376 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006377 Py_ssize_t startpos, Py_ssize_t endpos,
6378 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006379{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006380 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006381 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006382 PyObject *restuple;
6383 PyObject *resunicode;
6384
6385 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006386 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006387 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006388 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006389 }
6390
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006391 if (PyUnicode_READY(unicode) < 0)
6392 return NULL;
6393 len = PyUnicode_GET_LENGTH(unicode);
6394
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006395 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006396 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006397 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006398 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006399
6400 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006401 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006402 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006403 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006404 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006405 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006406 Py_DECREF(restuple);
6407 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006408 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006409 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006410 &resunicode, newpos)) {
6411 Py_DECREF(restuple);
6412 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006413 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006414 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6415 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6416 Py_DECREF(restuple);
6417 return NULL;
6418 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006419 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006420 *newpos = len + *newpos;
6421 if (*newpos<0 || *newpos>len) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006422 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
6423 Py_DECREF(restuple);
6424 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006425 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006426 Py_INCREF(resunicode);
6427 Py_DECREF(restuple);
6428 return resunicode;
6429}
6430
Alexander Belopolsky40018472011-02-26 01:02:56 +00006431static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006432unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006433 const char *errors,
Victor Stinnerfcd96532011-11-04 00:28:50 +01006434 unsigned int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006435{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006436 /* input state */
6437 Py_ssize_t pos=0, size;
6438 int kind;
6439 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006440 /* output object */
6441 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006442 /* pointer into the output */
6443 char *str;
6444 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006445 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006446 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6447 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006448 PyObject *errorHandler = NULL;
6449 PyObject *exc = NULL;
6450 /* the following variable is used for caching string comparisons
6451 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6452 int known_errorHandler = -1;
6453
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006454 if (PyUnicode_READY(unicode) < 0)
6455 return NULL;
6456 size = PyUnicode_GET_LENGTH(unicode);
6457 kind = PyUnicode_KIND(unicode);
6458 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006459 /* allocate enough for a simple encoding without
6460 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006461 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006462 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006463 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006464 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006465 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006466 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006467 ressize = size;
6468
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006469 while (pos < size) {
6470 Py_UCS4 c = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006471
Benjamin Peterson29060642009-01-31 22:14:21 +00006472 /* can we encode this? */
6473 if (c<limit) {
6474 /* no overflow check, because we know that the space is enough */
6475 *str++ = (char)c;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006476 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006477 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006478 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006479 Py_ssize_t requiredsize;
6480 PyObject *repunicode;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006481 Py_ssize_t repsize, newpos, respos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006482 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006483 Py_ssize_t collstart = pos;
6484 Py_ssize_t collend = pos;
Benjamin Peterson29060642009-01-31 22:14:21 +00006485 /* find all unecodable characters */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006486 while ((collend < size) && (PyUnicode_READ(kind, data, collend)>=limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006487 ++collend;
6488 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
6489 if (known_errorHandler==-1) {
6490 if ((errors==NULL) || (!strcmp(errors, "strict")))
6491 known_errorHandler = 1;
6492 else if (!strcmp(errors, "replace"))
6493 known_errorHandler = 2;
6494 else if (!strcmp(errors, "ignore"))
6495 known_errorHandler = 3;
6496 else if (!strcmp(errors, "xmlcharrefreplace"))
6497 known_errorHandler = 4;
6498 else
6499 known_errorHandler = 0;
6500 }
6501 switch (known_errorHandler) {
6502 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006503 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006504 goto onError;
6505 case 2: /* replace */
6506 while (collstart++<collend)
6507 *str++ = '?'; /* fall through */
6508 case 3: /* ignore */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006509 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006510 break;
6511 case 4: /* xmlcharrefreplace */
6512 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006513 /* determine replacement size */
6514 for (i = collstart, repsize = 0; i < collend; ++i) {
6515 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
6516 if (ch < 10)
Benjamin Peterson29060642009-01-31 22:14:21 +00006517 repsize += 2+1+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006518 else if (ch < 100)
Benjamin Peterson29060642009-01-31 22:14:21 +00006519 repsize += 2+2+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006520 else if (ch < 1000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006521 repsize += 2+3+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006522 else if (ch < 10000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006523 repsize += 2+4+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00006524#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00006525 else
6526 repsize += 2+5+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00006527#else
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006528 else if (ch < 100000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006529 repsize += 2+5+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006530 else if (ch < 1000000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006531 repsize += 2+6+1;
6532 else
6533 repsize += 2+7+1;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00006534#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00006535 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006536 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006537 if (requiredsize > ressize) {
6538 if (requiredsize<2*ressize)
6539 requiredsize = 2*ressize;
6540 if (_PyBytes_Resize(&res, requiredsize))
6541 goto onError;
6542 str = PyBytes_AS_STRING(res) + respos;
6543 ressize = requiredsize;
6544 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006545 /* generate replacement */
6546 for (i = collstart; i < collend; ++i) {
6547 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
Benjamin Peterson29060642009-01-31 22:14:21 +00006548 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006549 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006550 break;
6551 default:
6552 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006553 encoding, reason, unicode, &exc,
6554 collstart, collend, &newpos);
6555 if (repunicode == NULL || (PyUnicode_Check(repunicode) &&
6556 PyUnicode_READY(repunicode) < 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00006557 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006558 if (PyBytes_Check(repunicode)) {
6559 /* Directly copy bytes result to output. */
6560 repsize = PyBytes_Size(repunicode);
6561 if (repsize > 1) {
6562 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006563 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006564 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
6565 Py_DECREF(repunicode);
6566 goto onError;
6567 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006568 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006569 ressize += repsize-1;
6570 }
6571 memcpy(str, PyBytes_AsString(repunicode), repsize);
6572 str += repsize;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006573 pos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006574 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006575 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006576 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006577 /* need more space? (at least enough for what we
6578 have+the replacement+the rest of the string, so
6579 we won't have to check space for encodable characters) */
6580 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006581 repsize = PyUnicode_GET_LENGTH(repunicode);
6582 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006583 if (requiredsize > ressize) {
6584 if (requiredsize<2*ressize)
6585 requiredsize = 2*ressize;
6586 if (_PyBytes_Resize(&res, requiredsize)) {
6587 Py_DECREF(repunicode);
6588 goto onError;
6589 }
6590 str = PyBytes_AS_STRING(res) + respos;
6591 ressize = requiredsize;
6592 }
6593 /* check if there is anything unencodable in the replacement
6594 and copy it to the output */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006595 for (i = 0; repsize-->0; ++i, ++str) {
6596 c = PyUnicode_READ_CHAR(repunicode, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00006597 if (c >= limit) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006598 raise_encode_exception(&exc, encoding, unicode,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006599 pos, pos+1, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006600 Py_DECREF(repunicode);
6601 goto onError;
6602 }
6603 *str = (char)c;
6604 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006605 pos = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006606 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006607 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006608 }
6609 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006610 /* Resize if we allocated to much */
6611 size = str - PyBytes_AS_STRING(res);
6612 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00006613 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006614 if (_PyBytes_Resize(&res, size) < 0)
6615 goto onError;
6616 }
6617
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006618 Py_XDECREF(errorHandler);
6619 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006620 return res;
6621
6622 onError:
6623 Py_XDECREF(res);
6624 Py_XDECREF(errorHandler);
6625 Py_XDECREF(exc);
6626 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006627}
6628
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006629/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006630PyObject *
6631PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006632 Py_ssize_t size,
6633 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006634{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006635 PyObject *result;
6636 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6637 if (unicode == NULL)
6638 return NULL;
6639 result = unicode_encode_ucs1(unicode, errors, 256);
6640 Py_DECREF(unicode);
6641 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006642}
6643
Alexander Belopolsky40018472011-02-26 01:02:56 +00006644PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006645_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006646{
6647 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006648 PyErr_BadArgument();
6649 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006650 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006651 if (PyUnicode_READY(unicode) == -1)
6652 return NULL;
6653 /* Fast path: if it is a one-byte string, construct
6654 bytes object directly. */
6655 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6656 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6657 PyUnicode_GET_LENGTH(unicode));
6658 /* Non-Latin-1 characters present. Defer to above function to
6659 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006660 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006661}
6662
6663PyObject*
6664PyUnicode_AsLatin1String(PyObject *unicode)
6665{
6666 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006667}
6668
6669/* --- 7-bit ASCII Codec -------------------------------------------------- */
6670
Alexander Belopolsky40018472011-02-26 01:02:56 +00006671PyObject *
6672PyUnicode_DecodeASCII(const char *s,
6673 Py_ssize_t size,
6674 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006675{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006676 const char *starts = s;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006677 PyObject *v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006678 int kind;
6679 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006680 Py_ssize_t startinpos;
6681 Py_ssize_t endinpos;
6682 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006683 const char *e;
Victor Stinner702c7342011-10-05 13:50:52 +02006684 int has_error;
6685 const unsigned char *p = (const unsigned char *)s;
6686 const unsigned char *end = p + size;
6687 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006688 PyObject *errorHandler = NULL;
6689 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006690
Guido van Rossumd57fd912000-03-10 22:53:23 +00006691 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006692 if (size == 1 && (unsigned char)s[0] < 128)
6693 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006694
Victor Stinner702c7342011-10-05 13:50:52 +02006695 has_error = 0;
6696 while (p < end && !has_error) {
6697 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
6698 an explanation. */
6699 if (!((size_t) p & LONG_PTR_MASK)) {
6700 /* Help register allocation */
6701 register const unsigned char *_p = p;
6702 while (_p < aligned_end) {
6703 unsigned long value = *(unsigned long *) _p;
6704 if (value & ASCII_CHAR_MASK) {
6705 has_error = 1;
6706 break;
6707 }
6708 _p += SIZEOF_LONG;
6709 }
6710 if (_p == end)
6711 break;
6712 if (has_error)
6713 break;
6714 p = _p;
6715 }
6716 if (*p & 0x80) {
6717 has_error = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006718 break;
Victor Stinner702c7342011-10-05 13:50:52 +02006719 }
6720 else {
6721 ++p;
6722 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00006723 }
Victor Stinner702c7342011-10-05 13:50:52 +02006724 if (!has_error)
6725 return unicode_fromascii((const unsigned char *)s, size);
Tim Petersced69f82003-09-16 20:30:58 +00006726
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006727 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006728 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006729 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006730 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006731 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006732 kind = PyUnicode_KIND(v);
6733 data = PyUnicode_DATA(v);
6734 outpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006735 e = s + size;
6736 while (s < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006737 register unsigned char c = (unsigned char)*s;
6738 if (c < 128) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006739 PyUnicode_WRITE(kind, data, outpos++, c);
Benjamin Peterson29060642009-01-31 22:14:21 +00006740 ++s;
6741 }
6742 else {
6743 startinpos = s-starts;
6744 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006745 if (unicode_decode_call_errorhandler(
6746 errors, &errorHandler,
6747 "ascii", "ordinal not in range(128)",
6748 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006749 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006750 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006751 kind = PyUnicode_KIND(v);
6752 data = PyUnicode_DATA(v);
Benjamin Peterson29060642009-01-31 22:14:21 +00006753 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006754 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006755 if (PyUnicode_Resize(&v, outpos) < 0)
6756 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006757 Py_XDECREF(errorHandler);
6758 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006759 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01006760 return v;
Tim Petersced69f82003-09-16 20:30:58 +00006761
Benjamin Peterson29060642009-01-31 22:14:21 +00006762 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006763 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006764 Py_XDECREF(errorHandler);
6765 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006766 return NULL;
6767}
6768
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006769/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006770PyObject *
6771PyUnicode_EncodeASCII(const Py_UNICODE *p,
6772 Py_ssize_t size,
6773 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006774{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006775 PyObject *result;
6776 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6777 if (unicode == NULL)
6778 return NULL;
6779 result = unicode_encode_ucs1(unicode, errors, 128);
6780 Py_DECREF(unicode);
6781 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006782}
6783
Alexander Belopolsky40018472011-02-26 01:02:56 +00006784PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006785_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006786{
6787 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006788 PyErr_BadArgument();
6789 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006790 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006791 if (PyUnicode_READY(unicode) == -1)
6792 return NULL;
6793 /* Fast path: if it is an ASCII-only string, construct bytes object
6794 directly. Else defer to above function to raise the exception. */
6795 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
6796 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6797 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006798 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006799}
6800
6801PyObject *
6802PyUnicode_AsASCIIString(PyObject *unicode)
6803{
6804 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006805}
6806
Victor Stinner99b95382011-07-04 14:23:54 +02006807#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006808
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006809/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006810
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00006811#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006812#define NEED_RETRY
6813#endif
6814
Victor Stinner3a50e702011-10-18 21:21:00 +02006815#ifndef WC_ERR_INVALID_CHARS
6816# define WC_ERR_INVALID_CHARS 0x0080
6817#endif
6818
6819static char*
6820code_page_name(UINT code_page, PyObject **obj)
6821{
6822 *obj = NULL;
6823 if (code_page == CP_ACP)
6824 return "mbcs";
6825 if (code_page == CP_UTF7)
6826 return "CP_UTF7";
6827 if (code_page == CP_UTF8)
6828 return "CP_UTF8";
6829
6830 *obj = PyBytes_FromFormat("cp%u", code_page);
6831 if (*obj == NULL)
6832 return NULL;
6833 return PyBytes_AS_STRING(*obj);
6834}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006835
Alexander Belopolsky40018472011-02-26 01:02:56 +00006836static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006837is_dbcs_lead_byte(UINT code_page, const char *s, int offset)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006838{
6839 const char *curr = s + offset;
Victor Stinner3a50e702011-10-18 21:21:00 +02006840 const char *prev;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006841
Victor Stinner3a50e702011-10-18 21:21:00 +02006842 if (!IsDBCSLeadByteEx(code_page, *curr))
6843 return 0;
6844
6845 prev = CharPrevExA(code_page, s, curr, 0);
6846 if (prev == curr)
6847 return 1;
6848 /* FIXME: This code is limited to "true" double-byte encodings,
6849 as it assumes an incomplete character consists of a single
6850 byte. */
6851 if (curr - prev == 2)
6852 return 1;
6853 if (!IsDBCSLeadByteEx(code_page, *prev))
6854 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006855 return 0;
6856}
6857
Victor Stinner3a50e702011-10-18 21:21:00 +02006858static DWORD
6859decode_code_page_flags(UINT code_page)
6860{
6861 if (code_page == CP_UTF7) {
6862 /* The CP_UTF7 decoder only supports flags=0 */
6863 return 0;
6864 }
6865 else
6866 return MB_ERR_INVALID_CHARS;
6867}
6868
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006869/*
Victor Stinner3a50e702011-10-18 21:21:00 +02006870 * Decode a byte string from a Windows code page into unicode object in strict
6871 * mode.
6872 *
6873 * Returns consumed size if succeed, returns -2 on decode error, or raise a
6874 * WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006875 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006876static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006877decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006878 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02006879 const char *in,
6880 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006881{
Victor Stinner3a50e702011-10-18 21:21:00 +02006882 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01006883 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02006884 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006885
6886 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02006887 assert(insize > 0);
6888 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
6889 if (outsize <= 0)
6890 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006891
6892 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006893 /* Create unicode object */
Victor Stinner76a31a62011-11-04 00:05:13 +01006894 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00006895 if (*v == NULL)
6896 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006897 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006898 }
6899 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006900 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02006901 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner76a31a62011-11-04 00:05:13 +01006902 if (PyUnicode_Resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006903 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006904 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006905 }
6906
6907 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02006908 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
6909 if (outsize <= 0)
6910 goto error;
6911 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00006912
Victor Stinner3a50e702011-10-18 21:21:00 +02006913error:
6914 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
6915 return -2;
6916 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00006917 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006918}
6919
Victor Stinner3a50e702011-10-18 21:21:00 +02006920/*
6921 * Decode a byte string from a code page into unicode object with an error
6922 * handler.
6923 *
6924 * Returns consumed size if succeed, or raise a WindowsError or
6925 * UnicodeDecodeError exception and returns -1 on error.
6926 */
6927static int
6928decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006929 PyObject **v,
6930 const char *in, const int size,
Victor Stinner3a50e702011-10-18 21:21:00 +02006931 const char *errors)
6932{
6933 const char *startin = in;
6934 const char *endin = in + size;
6935 const DWORD flags = decode_code_page_flags(code_page);
6936 /* Ideally, we should get reason from FormatMessage. This is the Windows
6937 2000 English version of the message. */
6938 const char *reason = "No mapping for the Unicode character exists "
6939 "in the target code page.";
6940 /* each step cannot decode more than 1 character, but a character can be
6941 represented as a surrogate pair */
6942 wchar_t buffer[2], *startout, *out;
6943 int insize, outsize;
6944 PyObject *errorHandler = NULL;
6945 PyObject *exc = NULL;
6946 PyObject *encoding_obj = NULL;
6947 char *encoding;
6948 DWORD err;
6949 int ret = -1;
6950
6951 assert(size > 0);
6952
6953 encoding = code_page_name(code_page, &encoding_obj);
6954 if (encoding == NULL)
6955 return -1;
6956
6957 if (errors == NULL || strcmp(errors, "strict") == 0) {
6958 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
6959 UnicodeDecodeError. */
6960 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
6961 if (exc != NULL) {
6962 PyCodec_StrictErrors(exc);
6963 Py_CLEAR(exc);
6964 }
6965 goto error;
6966 }
6967
6968 if (*v == NULL) {
6969 /* Create unicode object */
6970 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6971 PyErr_NoMemory();
6972 goto error;
6973 }
Victor Stinner76a31a62011-11-04 00:05:13 +01006974 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02006975 if (*v == NULL)
6976 goto error;
6977 startout = PyUnicode_AS_UNICODE(*v);
6978 }
6979 else {
6980 /* Extend unicode object */
6981 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
6982 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6983 PyErr_NoMemory();
6984 goto error;
6985 }
Victor Stinner76a31a62011-11-04 00:05:13 +01006986 if (PyUnicode_Resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02006987 goto error;
6988 startout = PyUnicode_AS_UNICODE(*v) + n;
6989 }
6990
6991 /* Decode the byte string character per character */
6992 out = startout;
6993 while (in < endin)
6994 {
6995 /* Decode a character */
6996 insize = 1;
6997 do
6998 {
6999 outsize = MultiByteToWideChar(code_page, flags,
7000 in, insize,
7001 buffer, Py_ARRAY_LENGTH(buffer));
7002 if (outsize > 0)
7003 break;
7004 err = GetLastError();
7005 if (err != ERROR_NO_UNICODE_TRANSLATION
7006 && err != ERROR_INSUFFICIENT_BUFFER)
7007 {
7008 PyErr_SetFromWindowsErr(0);
7009 goto error;
7010 }
7011 insize++;
7012 }
7013 /* 4=maximum length of a UTF-8 sequence */
7014 while (insize <= 4 && (in + insize) <= endin);
7015
7016 if (outsize <= 0) {
7017 Py_ssize_t startinpos, endinpos, outpos;
7018
7019 startinpos = in - startin;
7020 endinpos = startinpos + 1;
7021 outpos = out - PyUnicode_AS_UNICODE(*v);
7022 if (unicode_decode_call_errorhandler(
7023 errors, &errorHandler,
7024 encoding, reason,
7025 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01007026 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02007027 {
7028 goto error;
7029 }
Victor Stinner596a6c42011-11-09 00:02:18 +01007030 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007031 }
7032 else {
7033 in += insize;
7034 memcpy(out, buffer, outsize * sizeof(wchar_t));
7035 out += outsize;
7036 }
7037 }
7038
7039 /* write a NUL character at the end */
7040 *out = 0;
7041
7042 /* Extend unicode object */
7043 outsize = out - startout;
7044 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner76a31a62011-11-04 00:05:13 +01007045 if (PyUnicode_Resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007046 goto error;
Victor Stinner76a31a62011-11-04 00:05:13 +01007047 ret = size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007048
7049error:
7050 Py_XDECREF(encoding_obj);
7051 Py_XDECREF(errorHandler);
7052 Py_XDECREF(exc);
7053 return ret;
7054}
7055
Victor Stinner3a50e702011-10-18 21:21:00 +02007056static PyObject *
7057decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007058 const char *s, Py_ssize_t size,
7059 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007060{
Victor Stinner76a31a62011-11-04 00:05:13 +01007061 PyObject *v = NULL;
7062 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007063
Victor Stinner3a50e702011-10-18 21:21:00 +02007064 if (code_page < 0) {
7065 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7066 return NULL;
7067 }
7068
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007069 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007070 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007071
Victor Stinner76a31a62011-11-04 00:05:13 +01007072 do
7073 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007074#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007075 if (size > INT_MAX) {
7076 chunk_size = INT_MAX;
7077 final = 0;
7078 done = 0;
7079 }
7080 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007081#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007082 {
7083 chunk_size = (int)size;
7084 final = (consumed == NULL);
7085 done = 1;
7086 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007087
Victor Stinner76a31a62011-11-04 00:05:13 +01007088 /* Skip trailing lead-byte unless 'final' is set */
7089 if (!final && is_dbcs_lead_byte(code_page, s, chunk_size - 1))
7090 --chunk_size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007091
Victor Stinner76a31a62011-11-04 00:05:13 +01007092 if (chunk_size == 0 && done) {
7093 if (v != NULL)
7094 break;
7095 Py_INCREF(unicode_empty);
7096 return unicode_empty;
7097 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007098
Victor Stinner76a31a62011-11-04 00:05:13 +01007099
7100 converted = decode_code_page_strict(code_page, &v,
7101 s, chunk_size);
7102 if (converted == -2)
7103 converted = decode_code_page_errors(code_page, &v,
7104 s, chunk_size,
7105 errors);
7106 assert(converted != 0);
7107
7108 if (converted < 0) {
7109 Py_XDECREF(v);
7110 return NULL;
7111 }
7112
7113 if (consumed)
7114 *consumed += converted;
7115
7116 s += converted;
7117 size -= converted;
7118 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007119
Victor Stinner17efeed2011-10-04 20:05:46 +02007120#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02007121 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007122 Py_DECREF(v);
7123 return NULL;
7124 }
Victor Stinner17efeed2011-10-04 20:05:46 +02007125#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02007126 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner76a31a62011-11-04 00:05:13 +01007127 return v;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007128}
7129
Alexander Belopolsky40018472011-02-26 01:02:56 +00007130PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007131PyUnicode_DecodeCodePageStateful(int code_page,
7132 const char *s,
7133 Py_ssize_t size,
7134 const char *errors,
7135 Py_ssize_t *consumed)
7136{
7137 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7138}
7139
7140PyObject *
7141PyUnicode_DecodeMBCSStateful(const char *s,
7142 Py_ssize_t size,
7143 const char *errors,
7144 Py_ssize_t *consumed)
7145{
7146 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7147}
7148
7149PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007150PyUnicode_DecodeMBCS(const char *s,
7151 Py_ssize_t size,
7152 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007153{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007154 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7155}
7156
Victor Stinner3a50e702011-10-18 21:21:00 +02007157static DWORD
7158encode_code_page_flags(UINT code_page, const char *errors)
7159{
7160 if (code_page == CP_UTF8) {
7161 if (winver.dwMajorVersion >= 6)
7162 /* CP_UTF8 supports WC_ERR_INVALID_CHARS on Windows Vista
7163 and later */
7164 return WC_ERR_INVALID_CHARS;
7165 else
7166 /* CP_UTF8 only supports flags=0 on Windows older than Vista */
7167 return 0;
7168 }
7169 else if (code_page == CP_UTF7) {
7170 /* CP_UTF7 only supports flags=0 */
7171 return 0;
7172 }
7173 else {
7174 if (errors != NULL && strcmp(errors, "replace") == 0)
7175 return 0;
7176 else
7177 return WC_NO_BEST_FIT_CHARS;
7178 }
7179}
7180
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007181/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007182 * Encode a Unicode string to a Windows code page into a byte string in strict
7183 * mode.
7184 *
7185 * Returns consumed characters if succeed, returns -2 on encode error, or raise
7186 * a WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007187 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007188static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007189encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007190 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007191 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007192{
Victor Stinner554f3f02010-06-16 23:33:54 +00007193 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007194 BOOL *pusedDefaultChar = &usedDefaultChar;
7195 int outsize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007196 PyObject *exc = NULL;
Victor Stinner24729f32011-11-10 20:31:37 +01007197 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007198 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007199 const DWORD flags = encode_code_page_flags(code_page, NULL);
7200 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007201 /* Create a substring so that we can get the UTF-16 representation
7202 of just the slice under consideration. */
7203 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007204
Martin v. Löwis3d325192011-11-04 18:23:06 +01007205 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007206
Victor Stinner3a50e702011-10-18 21:21:00 +02007207 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007208 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007209 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007210 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007211
Victor Stinner2fc507f2011-11-04 20:06:39 +01007212 substring = PyUnicode_Substring(unicode, offset, offset+len);
7213 if (substring == NULL)
7214 return -1;
7215 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7216 if (p == NULL) {
7217 Py_DECREF(substring);
7218 return -1;
7219 }
Martin v. Löwis3d325192011-11-04 18:23:06 +01007220
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007221 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007222 outsize = WideCharToMultiByte(code_page, flags,
7223 p, size,
7224 NULL, 0,
7225 NULL, pusedDefaultChar);
7226 if (outsize <= 0)
7227 goto error;
7228 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007229 if (pusedDefaultChar && *pusedDefaultChar) {
7230 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007231 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007232 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007233
Victor Stinner3a50e702011-10-18 21:21:00 +02007234 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007235 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007236 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007237 if (*outbytes == NULL) {
7238 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007239 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007240 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007241 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007242 }
7243 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007244 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007245 const Py_ssize_t n = PyBytes_Size(*outbytes);
7246 if (outsize > PY_SSIZE_T_MAX - n) {
7247 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007248 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007249 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007250 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007251 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7252 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007253 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007254 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007255 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007256 }
7257
7258 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007259 outsize = WideCharToMultiByte(code_page, flags,
7260 p, size,
7261 out, outsize,
7262 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007263 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007264 if (outsize <= 0)
7265 goto error;
7266 if (pusedDefaultChar && *pusedDefaultChar)
7267 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007268 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007269
Victor Stinner3a50e702011-10-18 21:21:00 +02007270error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007271 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007272 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7273 return -2;
7274 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007275 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007276}
7277
Victor Stinner3a50e702011-10-18 21:21:00 +02007278/*
7279 * Encode a Unicode string to a Windows code page into a byte string using a
7280 * error handler.
7281 *
7282 * Returns consumed characters if succeed, or raise a WindowsError and returns
7283 * -1 on other error.
7284 */
7285static int
7286encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007287 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007288 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007289{
Victor Stinner3a50e702011-10-18 21:21:00 +02007290 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007291 Py_ssize_t pos = unicode_offset;
7292 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007293 /* Ideally, we should get reason from FormatMessage. This is the Windows
7294 2000 English version of the message. */
7295 const char *reason = "invalid character";
7296 /* 4=maximum length of a UTF-8 sequence */
7297 char buffer[4];
7298 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7299 Py_ssize_t outsize;
7300 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007301 PyObject *errorHandler = NULL;
7302 PyObject *exc = NULL;
7303 PyObject *encoding_obj = NULL;
7304 char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007305 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007306 PyObject *rep;
7307 int ret = -1;
7308
7309 assert(insize > 0);
7310
7311 encoding = code_page_name(code_page, &encoding_obj);
7312 if (encoding == NULL)
7313 return -1;
7314
7315 if (errors == NULL || strcmp(errors, "strict") == 0) {
7316 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7317 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007318 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007319 if (exc != NULL) {
7320 PyCodec_StrictErrors(exc);
7321 Py_DECREF(exc);
7322 }
7323 Py_XDECREF(encoding_obj);
7324 return -1;
7325 }
7326
7327 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7328 pusedDefaultChar = &usedDefaultChar;
7329 else
7330 pusedDefaultChar = NULL;
7331
7332 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7333 PyErr_NoMemory();
7334 goto error;
7335 }
7336 outsize = insize * Py_ARRAY_LENGTH(buffer);
7337
7338 if (*outbytes == NULL) {
7339 /* Create string object */
7340 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7341 if (*outbytes == NULL)
7342 goto error;
7343 out = PyBytes_AS_STRING(*outbytes);
7344 }
7345 else {
7346 /* Extend string object */
7347 Py_ssize_t n = PyBytes_Size(*outbytes);
7348 if (n > PY_SSIZE_T_MAX - outsize) {
7349 PyErr_NoMemory();
7350 goto error;
7351 }
7352 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7353 goto error;
7354 out = PyBytes_AS_STRING(*outbytes) + n;
7355 }
7356
7357 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007358 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007359 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007360 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7361 wchar_t chars[2];
7362 int charsize;
7363 if (ch < 0x10000) {
7364 chars[0] = (wchar_t)ch;
7365 charsize = 1;
7366 }
7367 else {
7368 ch -= 0x10000;
7369 chars[0] = 0xd800 + (ch >> 10);
7370 chars[1] = 0xdc00 + (ch & 0x3ff);
7371 charsize = 2;
7372 }
7373
Victor Stinner3a50e702011-10-18 21:21:00 +02007374 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007375 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007376 buffer, Py_ARRAY_LENGTH(buffer),
7377 NULL, pusedDefaultChar);
7378 if (outsize > 0) {
7379 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7380 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007381 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007382 memcpy(out, buffer, outsize);
7383 out += outsize;
7384 continue;
7385 }
7386 }
7387 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7388 PyErr_SetFromWindowsErr(0);
7389 goto error;
7390 }
7391
Victor Stinner3a50e702011-10-18 21:21:00 +02007392 rep = unicode_encode_call_errorhandler(
7393 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007394 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007395 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007396 if (rep == NULL)
7397 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007398 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007399
7400 if (PyBytes_Check(rep)) {
7401 outsize = PyBytes_GET_SIZE(rep);
7402 if (outsize != 1) {
7403 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7404 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7405 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7406 Py_DECREF(rep);
7407 goto error;
7408 }
7409 out = PyBytes_AS_STRING(*outbytes) + offset;
7410 }
7411 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7412 out += outsize;
7413 }
7414 else {
7415 Py_ssize_t i;
7416 enum PyUnicode_Kind kind;
7417 void *data;
7418
7419 if (PyUnicode_READY(rep) < 0) {
7420 Py_DECREF(rep);
7421 goto error;
7422 }
7423
7424 outsize = PyUnicode_GET_LENGTH(rep);
7425 if (outsize != 1) {
7426 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7427 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7428 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7429 Py_DECREF(rep);
7430 goto error;
7431 }
7432 out = PyBytes_AS_STRING(*outbytes) + offset;
7433 }
7434 kind = PyUnicode_KIND(rep);
7435 data = PyUnicode_DATA(rep);
7436 for (i=0; i < outsize; i++) {
7437 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7438 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007439 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007440 encoding, unicode,
7441 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007442 "unable to encode error handler result to ASCII");
7443 Py_DECREF(rep);
7444 goto error;
7445 }
7446 *out = (unsigned char)ch;
7447 out++;
7448 }
7449 }
7450 Py_DECREF(rep);
7451 }
7452 /* write a NUL byte */
7453 *out = 0;
7454 outsize = out - PyBytes_AS_STRING(*outbytes);
7455 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7456 if (_PyBytes_Resize(outbytes, outsize) < 0)
7457 goto error;
7458 ret = 0;
7459
7460error:
7461 Py_XDECREF(encoding_obj);
7462 Py_XDECREF(errorHandler);
7463 Py_XDECREF(exc);
7464 return ret;
7465}
7466
Victor Stinner3a50e702011-10-18 21:21:00 +02007467static PyObject *
7468encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007469 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007470 const char *errors)
7471{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007472 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007473 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007474 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007475 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007476
Victor Stinner2fc507f2011-11-04 20:06:39 +01007477 if (PyUnicode_READY(unicode) < 0)
7478 return NULL;
7479 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007480
Victor Stinner3a50e702011-10-18 21:21:00 +02007481 if (code_page < 0) {
7482 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7483 return NULL;
7484 }
7485
Martin v. Löwis3d325192011-11-04 18:23:06 +01007486 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007487 return PyBytes_FromStringAndSize(NULL, 0);
7488
Victor Stinner7581cef2011-11-03 22:32:33 +01007489 offset = 0;
7490 do
7491 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007492#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007493 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007494 chunks. */
7495 if (len > INT_MAX/2) {
7496 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007497 done = 0;
7498 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007499 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007500#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007501 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007502 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007503 done = 1;
7504 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007505
Victor Stinner76a31a62011-11-04 00:05:13 +01007506 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007507 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007508 errors);
7509 if (ret == -2)
7510 ret = encode_code_page_errors(code_page, &outbytes,
7511 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007512 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007513 if (ret < 0) {
7514 Py_XDECREF(outbytes);
7515 return NULL;
7516 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007517
Victor Stinner7581cef2011-11-03 22:32:33 +01007518 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007519 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007520 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007521
Victor Stinner3a50e702011-10-18 21:21:00 +02007522 return outbytes;
7523}
7524
7525PyObject *
7526PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7527 Py_ssize_t size,
7528 const char *errors)
7529{
Victor Stinner7581cef2011-11-03 22:32:33 +01007530 PyObject *unicode, *res;
7531 unicode = PyUnicode_FromUnicode(p, size);
7532 if (unicode == NULL)
7533 return NULL;
7534 res = encode_code_page(CP_ACP, unicode, errors);
7535 Py_DECREF(unicode);
7536 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007537}
7538
7539PyObject *
7540PyUnicode_EncodeCodePage(int code_page,
7541 PyObject *unicode,
7542 const char *errors)
7543{
Victor Stinner7581cef2011-11-03 22:32:33 +01007544 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007545}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007546
Alexander Belopolsky40018472011-02-26 01:02:56 +00007547PyObject *
7548PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007549{
7550 if (!PyUnicode_Check(unicode)) {
7551 PyErr_BadArgument();
7552 return NULL;
7553 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007554 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007555}
7556
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007557#undef NEED_RETRY
7558
Victor Stinner99b95382011-07-04 14:23:54 +02007559#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007560
Guido van Rossumd57fd912000-03-10 22:53:23 +00007561/* --- Character Mapping Codec -------------------------------------------- */
7562
Alexander Belopolsky40018472011-02-26 01:02:56 +00007563PyObject *
7564PyUnicode_DecodeCharmap(const char *s,
7565 Py_ssize_t size,
7566 PyObject *mapping,
7567 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007568{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007569 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007570 Py_ssize_t startinpos;
7571 Py_ssize_t endinpos;
7572 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007573 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01007574 PyObject *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007575 Py_ssize_t extrachars = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007576 PyObject *errorHandler = NULL;
7577 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00007578
Guido van Rossumd57fd912000-03-10 22:53:23 +00007579 /* Default to Latin-1 */
7580 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007581 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007582
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007583 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007584 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007585 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007586 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01007587 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007588 outpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007589 e = s + size;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007590 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007591 Py_ssize_t maplen;
7592 enum PyUnicode_Kind kind;
7593 void *data;
7594 Py_UCS4 x;
7595
7596 if (PyUnicode_READY(mapping) < 0)
7597 return NULL;
7598
7599 maplen = PyUnicode_GET_LENGTH(mapping);
7600 data = PyUnicode_DATA(mapping);
7601 kind = PyUnicode_KIND(mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007602 while (s < e) {
7603 unsigned char ch = *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007604
Benjamin Peterson29060642009-01-31 22:14:21 +00007605 if (ch < maplen)
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007606 x = PyUnicode_READ(kind, data, ch);
7607 else
7608 x = 0xfffe; /* invalid value */
Guido van Rossumd57fd912000-03-10 22:53:23 +00007609
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007610 if (x == 0xfffe)
7611 {
Benjamin Peterson29060642009-01-31 22:14:21 +00007612 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007613 startinpos = s-starts;
7614 endinpos = startinpos+1;
7615 if (unicode_decode_call_errorhandler(
7616 errors, &errorHandler,
7617 "charmap", "character maps to <undefined>",
7618 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007619 &v, &outpos)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007620 goto onError;
7621 }
7622 continue;
7623 }
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007624
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007625 if (unicode_putchar(&v, &outpos, x) < 0)
7626 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007627 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007628 }
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007629 }
7630 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007631 while (s < e) {
7632 unsigned char ch = *s;
7633 PyObject *w, *x;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007634
Benjamin Peterson29060642009-01-31 22:14:21 +00007635 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7636 w = PyLong_FromLong((long)ch);
7637 if (w == NULL)
7638 goto onError;
7639 x = PyObject_GetItem(mapping, w);
7640 Py_DECREF(w);
7641 if (x == NULL) {
7642 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7643 /* No mapping found means: mapping is undefined. */
7644 PyErr_Clear();
7645 x = Py_None;
7646 Py_INCREF(x);
7647 } else
7648 goto onError;
7649 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007650
Benjamin Peterson29060642009-01-31 22:14:21 +00007651 /* Apply mapping */
7652 if (PyLong_Check(x)) {
7653 long value = PyLong_AS_LONG(x);
7654 if (value < 0 || value > 65535) {
7655 PyErr_SetString(PyExc_TypeError,
7656 "character mapping must be in range(65536)");
7657 Py_DECREF(x);
7658 goto onError;
7659 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007660 if (unicode_putchar(&v, &outpos, value) < 0)
7661 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007662 }
7663 else if (x == Py_None) {
7664 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007665 startinpos = s-starts;
7666 endinpos = startinpos+1;
7667 if (unicode_decode_call_errorhandler(
7668 errors, &errorHandler,
7669 "charmap", "character maps to <undefined>",
7670 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007671 &v, &outpos)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007672 Py_DECREF(x);
7673 goto onError;
7674 }
7675 Py_DECREF(x);
7676 continue;
7677 }
7678 else if (PyUnicode_Check(x)) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007679 Py_ssize_t targetsize;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007680
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007681 if (PyUnicode_READY(x) < 0)
7682 goto onError;
7683 targetsize = PyUnicode_GET_LENGTH(x);
7684
7685 if (targetsize == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007686 /* 1-1 mapping */
Victor Stinner62aa4d02011-11-09 00:03:45 +01007687 if (unicode_putchar(&v, &outpos,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007688 PyUnicode_READ_CHAR(x, 0)) < 0)
7689 goto onError;
7690 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007691 else if (targetsize > 1) {
7692 /* 1-n mapping */
7693 if (targetsize > extrachars) {
7694 /* resize first */
Benjamin Peterson29060642009-01-31 22:14:21 +00007695 Py_ssize_t needed = (targetsize - extrachars) + \
7696 (targetsize << 2);
7697 extrachars += needed;
7698 /* XXX overflow detection missing */
Victor Stinner7931d9a2011-11-04 00:22:48 +01007699 if (PyUnicode_Resize(&v,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007700 PyUnicode_GET_LENGTH(v) + needed) < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007701 Py_DECREF(x);
7702 goto onError;
7703 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007704 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007705 if (unicode_widen(&v, PyUnicode_MAX_CHAR_VALUE(x)) < 0)
7706 goto onError;
7707 PyUnicode_CopyCharacters(v, outpos, x, 0, targetsize);
7708 outpos += targetsize;
Benjamin Peterson29060642009-01-31 22:14:21 +00007709 extrachars -= targetsize;
7710 }
7711 /* 1-0 mapping: skip the character */
7712 }
7713 else {
7714 /* wrong return value */
7715 PyErr_SetString(PyExc_TypeError,
7716 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00007717 Py_DECREF(x);
7718 goto onError;
7719 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007720 Py_DECREF(x);
7721 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007722 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007723 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007724 if (PyUnicode_Resize(&v, outpos) < 0)
Antoine Pitroua8f63c02011-11-08 18:37:16 +01007725 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007726 Py_XDECREF(errorHandler);
7727 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02007728 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01007729 return v;
Tim Petersced69f82003-09-16 20:30:58 +00007730
Benjamin Peterson29060642009-01-31 22:14:21 +00007731 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007732 Py_XDECREF(errorHandler);
7733 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007734 Py_XDECREF(v);
7735 return NULL;
7736}
7737
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007738/* Charmap encoding: the lookup table */
7739
Alexander Belopolsky40018472011-02-26 01:02:56 +00007740struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007741 PyObject_HEAD
7742 unsigned char level1[32];
7743 int count2, count3;
7744 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007745};
7746
7747static PyObject*
7748encoding_map_size(PyObject *obj, PyObject* args)
7749{
7750 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007751 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007752 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007753}
7754
7755static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007756 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007757 PyDoc_STR("Return the size (in bytes) of this object") },
7758 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007759};
7760
7761static void
7762encoding_map_dealloc(PyObject* o)
7763{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007764 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007765}
7766
7767static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007768 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007769 "EncodingMap", /*tp_name*/
7770 sizeof(struct encoding_map), /*tp_basicsize*/
7771 0, /*tp_itemsize*/
7772 /* methods */
7773 encoding_map_dealloc, /*tp_dealloc*/
7774 0, /*tp_print*/
7775 0, /*tp_getattr*/
7776 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007777 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007778 0, /*tp_repr*/
7779 0, /*tp_as_number*/
7780 0, /*tp_as_sequence*/
7781 0, /*tp_as_mapping*/
7782 0, /*tp_hash*/
7783 0, /*tp_call*/
7784 0, /*tp_str*/
7785 0, /*tp_getattro*/
7786 0, /*tp_setattro*/
7787 0, /*tp_as_buffer*/
7788 Py_TPFLAGS_DEFAULT, /*tp_flags*/
7789 0, /*tp_doc*/
7790 0, /*tp_traverse*/
7791 0, /*tp_clear*/
7792 0, /*tp_richcompare*/
7793 0, /*tp_weaklistoffset*/
7794 0, /*tp_iter*/
7795 0, /*tp_iternext*/
7796 encoding_map_methods, /*tp_methods*/
7797 0, /*tp_members*/
7798 0, /*tp_getset*/
7799 0, /*tp_base*/
7800 0, /*tp_dict*/
7801 0, /*tp_descr_get*/
7802 0, /*tp_descr_set*/
7803 0, /*tp_dictoffset*/
7804 0, /*tp_init*/
7805 0, /*tp_alloc*/
7806 0, /*tp_new*/
7807 0, /*tp_free*/
7808 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007809};
7810
7811PyObject*
7812PyUnicode_BuildEncodingMap(PyObject* string)
7813{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007814 PyObject *result;
7815 struct encoding_map *mresult;
7816 int i;
7817 int need_dict = 0;
7818 unsigned char level1[32];
7819 unsigned char level2[512];
7820 unsigned char *mlevel1, *mlevel2, *mlevel3;
7821 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007822 int kind;
7823 void *data;
7824 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007825
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007826 if (!PyUnicode_Check(string) || PyUnicode_GET_LENGTH(string) != 256) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007827 PyErr_BadArgument();
7828 return NULL;
7829 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007830 kind = PyUnicode_KIND(string);
7831 data = PyUnicode_DATA(string);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007832 memset(level1, 0xFF, sizeof level1);
7833 memset(level2, 0xFF, sizeof level2);
7834
7835 /* If there isn't a one-to-one mapping of NULL to \0,
7836 or if there are non-BMP characters, we need to use
7837 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007838 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007839 need_dict = 1;
7840 for (i = 1; i < 256; i++) {
7841 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007842 ch = PyUnicode_READ(kind, data, i);
7843 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007844 need_dict = 1;
7845 break;
7846 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007847 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007848 /* unmapped character */
7849 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007850 l1 = ch >> 11;
7851 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007852 if (level1[l1] == 0xFF)
7853 level1[l1] = count2++;
7854 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00007855 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007856 }
7857
7858 if (count2 >= 0xFF || count3 >= 0xFF)
7859 need_dict = 1;
7860
7861 if (need_dict) {
7862 PyObject *result = PyDict_New();
7863 PyObject *key, *value;
7864 if (!result)
7865 return NULL;
7866 for (i = 0; i < 256; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007867 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00007868 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007869 if (!key || !value)
7870 goto failed1;
7871 if (PyDict_SetItem(result, key, value) == -1)
7872 goto failed1;
7873 Py_DECREF(key);
7874 Py_DECREF(value);
7875 }
7876 return result;
7877 failed1:
7878 Py_XDECREF(key);
7879 Py_XDECREF(value);
7880 Py_DECREF(result);
7881 return NULL;
7882 }
7883
7884 /* Create a three-level trie */
7885 result = PyObject_MALLOC(sizeof(struct encoding_map) +
7886 16*count2 + 128*count3 - 1);
7887 if (!result)
7888 return PyErr_NoMemory();
7889 PyObject_Init(result, &EncodingMapType);
7890 mresult = (struct encoding_map*)result;
7891 mresult->count2 = count2;
7892 mresult->count3 = count3;
7893 mlevel1 = mresult->level1;
7894 mlevel2 = mresult->level23;
7895 mlevel3 = mresult->level23 + 16*count2;
7896 memcpy(mlevel1, level1, 32);
7897 memset(mlevel2, 0xFF, 16*count2);
7898 memset(mlevel3, 0, 128*count3);
7899 count3 = 0;
7900 for (i = 1; i < 256; i++) {
7901 int o1, o2, o3, i2, i3;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007902 if (PyUnicode_READ(kind, data, i) == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007903 /* unmapped character */
7904 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007905 o1 = PyUnicode_READ(kind, data, i)>>11;
7906 o2 = (PyUnicode_READ(kind, data, i)>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007907 i2 = 16*mlevel1[o1] + o2;
7908 if (mlevel2[i2] == 0xFF)
7909 mlevel2[i2] = count3++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007910 o3 = PyUnicode_READ(kind, data, i) & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007911 i3 = 128*mlevel2[i2] + o3;
7912 mlevel3[i3] = i;
7913 }
7914 return result;
7915}
7916
7917static int
Victor Stinner22168992011-11-20 17:09:18 +01007918encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007919{
7920 struct encoding_map *map = (struct encoding_map*)mapping;
7921 int l1 = c>>11;
7922 int l2 = (c>>7) & 0xF;
7923 int l3 = c & 0x7F;
7924 int i;
7925
Victor Stinner22168992011-11-20 17:09:18 +01007926 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00007927 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007928 if (c == 0)
7929 return 0;
7930 /* level 1*/
7931 i = map->level1[l1];
7932 if (i == 0xFF) {
7933 return -1;
7934 }
7935 /* level 2*/
7936 i = map->level23[16*i+l2];
7937 if (i == 0xFF) {
7938 return -1;
7939 }
7940 /* level 3 */
7941 i = map->level23[16*map->count2 + 128*i + l3];
7942 if (i == 0) {
7943 return -1;
7944 }
7945 return i;
7946}
7947
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007948/* Lookup the character ch in the mapping. If the character
7949 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00007950 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007951static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01007952charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007953{
Christian Heimes217cfd12007-12-02 14:31:20 +00007954 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007955 PyObject *x;
7956
7957 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007958 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007959 x = PyObject_GetItem(mapping, w);
7960 Py_DECREF(w);
7961 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007962 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7963 /* No mapping found means: mapping is undefined. */
7964 PyErr_Clear();
7965 x = Py_None;
7966 Py_INCREF(x);
7967 return x;
7968 } else
7969 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007970 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00007971 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00007972 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00007973 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007974 long value = PyLong_AS_LONG(x);
7975 if (value < 0 || value > 255) {
7976 PyErr_SetString(PyExc_TypeError,
7977 "character mapping must be in range(256)");
7978 Py_DECREF(x);
7979 return NULL;
7980 }
7981 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007982 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007983 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00007984 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007985 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007986 /* wrong return value */
7987 PyErr_Format(PyExc_TypeError,
7988 "character mapping must return integer, bytes or None, not %.400s",
7989 x->ob_type->tp_name);
7990 Py_DECREF(x);
7991 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007992 }
7993}
7994
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007995static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00007996charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007997{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007998 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
7999 /* exponentially overallocate to minimize reallocations */
8000 if (requiredsize < 2*outsize)
8001 requiredsize = 2*outsize;
8002 if (_PyBytes_Resize(outobj, requiredsize))
8003 return -1;
8004 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008005}
8006
Benjamin Peterson14339b62009-01-31 16:36:08 +00008007typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008008 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008009} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008010/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008011 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008012 space is available. Return a new reference to the object that
8013 was put in the output buffer, or Py_None, if the mapping was undefined
8014 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008015 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008016static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01008017charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008018 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008019{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008020 PyObject *rep;
8021 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008022 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008023
Christian Heimes90aa7642007-12-19 02:45:37 +00008024 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008025 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008026 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008027 if (res == -1)
8028 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008029 if (outsize<requiredsize)
8030 if (charmapencode_resize(outobj, outpos, requiredsize))
8031 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008032 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008033 outstart[(*outpos)++] = (char)res;
8034 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008035 }
8036
8037 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008038 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008039 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008040 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008041 Py_DECREF(rep);
8042 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008043 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008044 if (PyLong_Check(rep)) {
8045 Py_ssize_t requiredsize = *outpos+1;
8046 if (outsize<requiredsize)
8047 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8048 Py_DECREF(rep);
8049 return enc_EXCEPTION;
8050 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008051 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008052 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008053 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008054 else {
8055 const char *repchars = PyBytes_AS_STRING(rep);
8056 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8057 Py_ssize_t requiredsize = *outpos+repsize;
8058 if (outsize<requiredsize)
8059 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8060 Py_DECREF(rep);
8061 return enc_EXCEPTION;
8062 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008063 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008064 memcpy(outstart + *outpos, repchars, repsize);
8065 *outpos += repsize;
8066 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008067 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008068 Py_DECREF(rep);
8069 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008070}
8071
8072/* handle an error in PyUnicode_EncodeCharmap
8073 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008074static int
8075charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008076 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008077 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00008078 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008079 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008080{
8081 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008082 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008083 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008084 enum PyUnicode_Kind kind;
8085 void *data;
8086 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008087 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008088 Py_ssize_t collstartpos = *inpos;
8089 Py_ssize_t collendpos = *inpos+1;
8090 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008091 char *encoding = "charmap";
8092 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008093 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008094 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008095 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008096
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008097 if (PyUnicode_READY(unicode) < 0)
8098 return -1;
8099 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008100 /* find all unencodable characters */
8101 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008102 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008103 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008104 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008105 val = encoding_map_lookup(ch, mapping);
8106 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008107 break;
8108 ++collendpos;
8109 continue;
8110 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008111
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008112 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8113 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008114 if (rep==NULL)
8115 return -1;
8116 else if (rep!=Py_None) {
8117 Py_DECREF(rep);
8118 break;
8119 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008120 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008121 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008122 }
8123 /* cache callback name lookup
8124 * (if not done yet, i.e. it's the first error) */
8125 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008126 if ((errors==NULL) || (!strcmp(errors, "strict")))
8127 *known_errorHandler = 1;
8128 else if (!strcmp(errors, "replace"))
8129 *known_errorHandler = 2;
8130 else if (!strcmp(errors, "ignore"))
8131 *known_errorHandler = 3;
8132 else if (!strcmp(errors, "xmlcharrefreplace"))
8133 *known_errorHandler = 4;
8134 else
8135 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008136 }
8137 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008138 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008139 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008140 return -1;
8141 case 2: /* replace */
8142 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008143 x = charmapencode_output('?', mapping, res, respos);
8144 if (x==enc_EXCEPTION) {
8145 return -1;
8146 }
8147 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008148 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008149 return -1;
8150 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008151 }
8152 /* fall through */
8153 case 3: /* ignore */
8154 *inpos = collendpos;
8155 break;
8156 case 4: /* xmlcharrefreplace */
8157 /* generate replacement (temporarily (mis)uses p) */
8158 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008159 char buffer[2+29+1+1];
8160 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008161 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008162 for (cp = buffer; *cp; ++cp) {
8163 x = charmapencode_output(*cp, mapping, res, respos);
8164 if (x==enc_EXCEPTION)
8165 return -1;
8166 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008167 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008168 return -1;
8169 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008170 }
8171 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008172 *inpos = collendpos;
8173 break;
8174 default:
8175 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008176 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008177 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008178 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008179 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008180 if (PyBytes_Check(repunicode)) {
8181 /* Directly copy bytes result to output. */
8182 Py_ssize_t outsize = PyBytes_Size(*res);
8183 Py_ssize_t requiredsize;
8184 repsize = PyBytes_Size(repunicode);
8185 requiredsize = *respos + repsize;
8186 if (requiredsize > outsize)
8187 /* Make room for all additional bytes. */
8188 if (charmapencode_resize(res, respos, requiredsize)) {
8189 Py_DECREF(repunicode);
8190 return -1;
8191 }
8192 memcpy(PyBytes_AsString(*res) + *respos,
8193 PyBytes_AsString(repunicode), repsize);
8194 *respos += repsize;
8195 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008196 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008197 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008198 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008199 /* generate replacement */
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008200 if (PyUnicode_READY(repunicode) < 0) {
8201 Py_DECREF(repunicode);
8202 return -1;
8203 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008204 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008205 data = PyUnicode_DATA(repunicode);
8206 kind = PyUnicode_KIND(repunicode);
8207 for (index = 0; index < repsize; index++) {
8208 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8209 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008210 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008211 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008212 return -1;
8213 }
8214 else if (x==enc_FAILED) {
8215 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008216 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008217 return -1;
8218 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008219 }
8220 *inpos = newpos;
8221 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008222 }
8223 return 0;
8224}
8225
Alexander Belopolsky40018472011-02-26 01:02:56 +00008226PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008227_PyUnicode_EncodeCharmap(PyObject *unicode,
8228 PyObject *mapping,
8229 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008230{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008231 /* output object */
8232 PyObject *res = NULL;
8233 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008234 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008235 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008236 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008237 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008238 PyObject *errorHandler = NULL;
8239 PyObject *exc = NULL;
8240 /* the following variable is used for caching string comparisons
8241 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8242 * 3=ignore, 4=xmlcharrefreplace */
8243 int known_errorHandler = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008244
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008245 if (PyUnicode_READY(unicode) < 0)
8246 return NULL;
8247 size = PyUnicode_GET_LENGTH(unicode);
8248
Guido van Rossumd57fd912000-03-10 22:53:23 +00008249 /* Default to Latin-1 */
8250 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008251 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008252
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008253 /* allocate enough for a simple encoding without
8254 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008255 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008256 if (res == NULL)
8257 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008258 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008259 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008260
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008261 while (inpos<size) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008262 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008263 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008264 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008265 if (x==enc_EXCEPTION) /* error */
8266 goto onError;
8267 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008268 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008269 &exc,
8270 &known_errorHandler, &errorHandler, errors,
8271 &res, &respos)) {
8272 goto onError;
8273 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008274 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008275 else
8276 /* done with this character => adjust input position */
8277 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008278 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008279
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008280 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008281 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008282 if (_PyBytes_Resize(&res, respos) < 0)
8283 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008284
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008285 Py_XDECREF(exc);
8286 Py_XDECREF(errorHandler);
8287 return res;
8288
Benjamin Peterson29060642009-01-31 22:14:21 +00008289 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008290 Py_XDECREF(res);
8291 Py_XDECREF(exc);
8292 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008293 return NULL;
8294}
8295
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008296/* Deprecated */
8297PyObject *
8298PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8299 Py_ssize_t size,
8300 PyObject *mapping,
8301 const char *errors)
8302{
8303 PyObject *result;
8304 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8305 if (unicode == NULL)
8306 return NULL;
8307 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8308 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008309 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008310}
8311
Alexander Belopolsky40018472011-02-26 01:02:56 +00008312PyObject *
8313PyUnicode_AsCharmapString(PyObject *unicode,
8314 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008315{
8316 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008317 PyErr_BadArgument();
8318 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008319 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008320 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008321}
8322
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008323/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008324static void
8325make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008326 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008327 Py_ssize_t startpos, Py_ssize_t endpos,
8328 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008329{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008330 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008331 *exceptionObject = _PyUnicodeTranslateError_Create(
8332 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008333 }
8334 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008335 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8336 goto onError;
8337 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8338 goto onError;
8339 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8340 goto onError;
8341 return;
8342 onError:
8343 Py_DECREF(*exceptionObject);
8344 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008345 }
8346}
8347
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008348/* raises a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008349static void
8350raise_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008351 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008352 Py_ssize_t startpos, Py_ssize_t endpos,
8353 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008354{
8355 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008356 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008357 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008358 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008359}
8360
8361/* error handling callback helper:
8362 build arguments, call the callback and check the arguments,
8363 put the result into newpos and return the replacement string, which
8364 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008365static PyObject *
8366unicode_translate_call_errorhandler(const char *errors,
8367 PyObject **errorHandler,
8368 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008369 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008370 Py_ssize_t startpos, Py_ssize_t endpos,
8371 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008372{
Benjamin Peterson142957c2008-07-04 19:55:29 +00008373 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008374
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008375 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008376 PyObject *restuple;
8377 PyObject *resunicode;
8378
8379 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008380 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008381 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008382 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008383 }
8384
8385 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008386 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008387 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008388 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008389
8390 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008391 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008392 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008393 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008394 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008395 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008396 Py_DECREF(restuple);
8397 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008398 }
8399 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008400 &resunicode, &i_newpos)) {
8401 Py_DECREF(restuple);
8402 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008403 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008404 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008405 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008406 else
8407 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008408 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008409 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
8410 Py_DECREF(restuple);
8411 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008412 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008413 Py_INCREF(resunicode);
8414 Py_DECREF(restuple);
8415 return resunicode;
8416}
8417
8418/* Lookup the character ch in the mapping and put the result in result,
8419 which must be decrefed by the caller.
8420 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008421static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008422charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008423{
Christian Heimes217cfd12007-12-02 14:31:20 +00008424 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008425 PyObject *x;
8426
8427 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008428 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008429 x = PyObject_GetItem(mapping, w);
8430 Py_DECREF(w);
8431 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008432 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8433 /* No mapping found means: use 1:1 mapping. */
8434 PyErr_Clear();
8435 *result = NULL;
8436 return 0;
8437 } else
8438 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008439 }
8440 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008441 *result = x;
8442 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008443 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008444 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008445 long value = PyLong_AS_LONG(x);
8446 long max = PyUnicode_GetMax();
8447 if (value < 0 || value > max) {
8448 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00008449 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008450 Py_DECREF(x);
8451 return -1;
8452 }
8453 *result = x;
8454 return 0;
8455 }
8456 else if (PyUnicode_Check(x)) {
8457 *result = x;
8458 return 0;
8459 }
8460 else {
8461 /* wrong return value */
8462 PyErr_SetString(PyExc_TypeError,
8463 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008464 Py_DECREF(x);
8465 return -1;
8466 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008467}
8468/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00008469 if not reallocate and adjust various state variables.
8470 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008471static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008472charmaptranslate_makespace(Py_UCS4 **outobj, Py_ssize_t *psize,
Benjamin Peterson29060642009-01-31 22:14:21 +00008473 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008474{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008475 Py_ssize_t oldsize = *psize;
Walter Dörwald4894c302003-10-24 14:25:28 +00008476 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008477 /* exponentially overallocate to minimize reallocations */
8478 if (requiredsize < 2 * oldsize)
8479 requiredsize = 2 * oldsize;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008480 *outobj = PyMem_Realloc(*outobj, requiredsize * sizeof(Py_UCS4));
8481 if (*outobj == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008482 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008483 *psize = requiredsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008484 }
8485 return 0;
8486}
8487/* lookup the character, put the result in the output string and adjust
8488 various state variables. Return a new reference to the object that
8489 was put in the output buffer in *result, or Py_None, if the mapping was
8490 undefined (in which case no character was written).
8491 The called must decref result.
8492 Return 0 on success, -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008493static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008494charmaptranslate_output(PyObject *input, Py_ssize_t ipos,
8495 PyObject *mapping, Py_UCS4 **output,
8496 Py_ssize_t *osize, Py_ssize_t *opos,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008497 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008498{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008499 Py_UCS4 curinp = PyUnicode_READ_CHAR(input, ipos);
8500 if (charmaptranslate_lookup(curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00008501 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008502 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008503 /* not found => default to 1:1 mapping */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008504 (*output)[(*opos)++] = curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008505 }
8506 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008507 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00008508 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008509 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008510 (*output)[(*opos)++] = (Py_UCS4)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008511 }
8512 else if (PyUnicode_Check(*res)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008513 Py_ssize_t repsize;
8514 if (PyUnicode_READY(*res) == -1)
8515 return -1;
8516 repsize = PyUnicode_GET_LENGTH(*res);
Benjamin Peterson29060642009-01-31 22:14:21 +00008517 if (repsize==1) {
8518 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008519 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00008520 }
8521 else if (repsize!=0) {
8522 /* more than one character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008523 Py_ssize_t requiredsize = *opos +
8524 (PyUnicode_GET_LENGTH(input) - ipos) +
Benjamin Peterson29060642009-01-31 22:14:21 +00008525 repsize - 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008526 Py_ssize_t i;
8527 if (charmaptranslate_makespace(output, osize, requiredsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00008528 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008529 for(i = 0; i < repsize; i++)
8530 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00008531 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008532 }
8533 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008534 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008535 return 0;
8536}
8537
Alexander Belopolsky40018472011-02-26 01:02:56 +00008538PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008539_PyUnicode_TranslateCharmap(PyObject *input,
8540 PyObject *mapping,
8541 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008542{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008543 /* input object */
8544 char *idata;
8545 Py_ssize_t size, i;
8546 int kind;
8547 /* output buffer */
8548 Py_UCS4 *output = NULL;
8549 Py_ssize_t osize;
8550 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008551 /* current output position */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008552 Py_ssize_t opos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008553 char *reason = "character maps to <undefined>";
8554 PyObject *errorHandler = NULL;
8555 PyObject *exc = NULL;
8556 /* the following variable is used for caching string comparisons
8557 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8558 * 3=ignore, 4=xmlcharrefreplace */
8559 int known_errorHandler = -1;
8560
Guido van Rossumd57fd912000-03-10 22:53:23 +00008561 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008562 PyErr_BadArgument();
8563 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008564 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008565
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008566 if (PyUnicode_READY(input) == -1)
8567 return NULL;
8568 idata = (char*)PyUnicode_DATA(input);
8569 kind = PyUnicode_KIND(input);
8570 size = PyUnicode_GET_LENGTH(input);
8571 i = 0;
8572
8573 if (size == 0) {
8574 Py_INCREF(input);
8575 return input;
8576 }
8577
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008578 /* allocate enough for a simple 1:1 translation without
8579 replacements, if we need more, we'll resize */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008580 osize = size;
8581 output = PyMem_Malloc(osize * sizeof(Py_UCS4));
8582 opos = 0;
8583 if (output == NULL) {
8584 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00008585 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008586 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008587
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008588 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008589 /* try to encode it */
8590 PyObject *x = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008591 if (charmaptranslate_output(input, i, mapping,
8592 &output, &osize, &opos, &x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008593 Py_XDECREF(x);
8594 goto onError;
8595 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008596 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00008597 if (x!=Py_None) /* it worked => adjust input pointer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008598 ++i;
Benjamin Peterson29060642009-01-31 22:14:21 +00008599 else { /* untranslatable character */
8600 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8601 Py_ssize_t repsize;
8602 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008603 Py_ssize_t uni2;
Benjamin Peterson29060642009-01-31 22:14:21 +00008604 /* startpos for collecting untranslatable chars */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008605 Py_ssize_t collstart = i;
8606 Py_ssize_t collend = i+1;
8607 Py_ssize_t coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008608
Benjamin Peterson29060642009-01-31 22:14:21 +00008609 /* find all untranslatable characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008610 while (collend < size) {
8611 if (charmaptranslate_lookup(PyUnicode_READ(kind,idata, collend), mapping, &x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008612 goto onError;
8613 Py_XDECREF(x);
8614 if (x!=Py_None)
8615 break;
8616 ++collend;
8617 }
8618 /* cache callback name lookup
8619 * (if not done yet, i.e. it's the first error) */
8620 if (known_errorHandler==-1) {
8621 if ((errors==NULL) || (!strcmp(errors, "strict")))
8622 known_errorHandler = 1;
8623 else if (!strcmp(errors, "replace"))
8624 known_errorHandler = 2;
8625 else if (!strcmp(errors, "ignore"))
8626 known_errorHandler = 3;
8627 else if (!strcmp(errors, "xmlcharrefreplace"))
8628 known_errorHandler = 4;
8629 else
8630 known_errorHandler = 0;
8631 }
8632 switch (known_errorHandler) {
8633 case 1: /* strict */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008634 raise_translate_exception(&exc, input, collstart,
8635 collend, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008636 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008637 case 2: /* replace */
8638 /* No need to check for space, this is a 1:1 replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008639 for (coll = collstart; coll<collend; coll++)
8640 output[opos++] = '?';
Benjamin Peterson29060642009-01-31 22:14:21 +00008641 /* fall through */
8642 case 3: /* ignore */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008643 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008644 break;
8645 case 4: /* xmlcharrefreplace */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008646 /* generate replacement (temporarily (mis)uses i) */
8647 for (i = collstart; i < collend; ++i) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008648 char buffer[2+29+1+1];
8649 char *cp;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008650 sprintf(buffer, "&#%d;", PyUnicode_READ(kind, idata, i));
8651 if (charmaptranslate_makespace(&output, &osize,
8652 opos+strlen(buffer)+(size-collend)))
Benjamin Peterson29060642009-01-31 22:14:21 +00008653 goto onError;
8654 for (cp = buffer; *cp; ++cp)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008655 output[opos++] = *cp;
Benjamin Peterson29060642009-01-31 22:14:21 +00008656 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008657 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008658 break;
8659 default:
8660 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008661 reason, input, &exc,
8662 collstart, collend, &newpos);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02008663 if (repunicode == NULL || _PyUnicode_READY_REPLACE(&repunicode))
Benjamin Peterson29060642009-01-31 22:14:21 +00008664 goto onError;
8665 /* generate replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008666 repsize = PyUnicode_GET_LENGTH(repunicode);
8667 if (charmaptranslate_makespace(&output, &osize,
8668 opos+repsize+(size-collend))) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008669 Py_DECREF(repunicode);
8670 goto onError;
8671 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008672 for (uni2 = 0; repsize-->0; ++uni2)
8673 output[opos++] = PyUnicode_READ_CHAR(repunicode, uni2);
8674 i = newpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00008675 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008676 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008677 }
8678 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008679 res = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, output, opos);
8680 if (!res)
8681 goto onError;
8682 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008683 Py_XDECREF(exc);
8684 Py_XDECREF(errorHandler);
8685 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008686
Benjamin Peterson29060642009-01-31 22:14:21 +00008687 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008688 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008689 Py_XDECREF(exc);
8690 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008691 return NULL;
8692}
8693
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008694/* Deprecated. Use PyUnicode_Translate instead. */
8695PyObject *
8696PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8697 Py_ssize_t size,
8698 PyObject *mapping,
8699 const char *errors)
8700{
8701 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8702 if (!unicode)
8703 return NULL;
8704 return _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8705}
8706
Alexander Belopolsky40018472011-02-26 01:02:56 +00008707PyObject *
8708PyUnicode_Translate(PyObject *str,
8709 PyObject *mapping,
8710 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008711{
8712 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008713
Guido van Rossumd57fd912000-03-10 22:53:23 +00008714 str = PyUnicode_FromObject(str);
8715 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008716 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008717 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008718 Py_DECREF(str);
8719 return result;
Tim Petersced69f82003-09-16 20:30:58 +00008720
Benjamin Peterson29060642009-01-31 22:14:21 +00008721 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00008722 Py_XDECREF(str);
8723 return NULL;
8724}
Tim Petersced69f82003-09-16 20:30:58 +00008725
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008726static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008727fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008728{
8729 /* No need to call PyUnicode_READY(self) because this function is only
8730 called as a callback from fixup() which does it already. */
8731 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8732 const int kind = PyUnicode_KIND(self);
8733 void *data = PyUnicode_DATA(self);
8734 Py_UCS4 maxchar = 0, ch, fixed;
8735 Py_ssize_t i;
8736
8737 for (i = 0; i < len; ++i) {
8738 ch = PyUnicode_READ(kind, data, i);
8739 fixed = 0;
8740 if (ch > 127) {
8741 if (Py_UNICODE_ISSPACE(ch))
8742 fixed = ' ';
8743 else {
8744 const int decimal = Py_UNICODE_TODECIMAL(ch);
8745 if (decimal >= 0)
8746 fixed = '0' + decimal;
8747 }
8748 if (fixed != 0) {
8749 if (fixed > maxchar)
8750 maxchar = fixed;
8751 PyUnicode_WRITE(kind, data, i, fixed);
8752 }
8753 else if (ch > maxchar)
8754 maxchar = ch;
8755 }
8756 else if (ch > maxchar)
8757 maxchar = ch;
8758 }
8759
8760 return maxchar;
8761}
8762
8763PyObject *
8764_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
8765{
8766 if (!PyUnicode_Check(unicode)) {
8767 PyErr_BadInternalCall();
8768 return NULL;
8769 }
8770 if (PyUnicode_READY(unicode) == -1)
8771 return NULL;
8772 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
8773 /* If the string is already ASCII, just return the same string */
8774 Py_INCREF(unicode);
8775 return unicode;
8776 }
Victor Stinner9310abb2011-10-05 00:59:23 +02008777 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008778}
8779
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008780PyObject *
8781PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
8782 Py_ssize_t length)
8783{
8784 PyObject *result;
8785 Py_UNICODE *p; /* write pointer into result */
8786 Py_ssize_t i;
8787 /* Copy to a new string */
8788 result = (PyObject *)_PyUnicode_New(length);
8789 Py_UNICODE_COPY(PyUnicode_AS_UNICODE(result), s, length);
8790 if (result == NULL)
8791 return result;
8792 p = PyUnicode_AS_UNICODE(result);
8793 /* Iterate over code points */
8794 for (i = 0; i < length; i++) {
8795 Py_UNICODE ch =s[i];
8796 if (ch > 127) {
8797 int decimal = Py_UNICODE_TODECIMAL(ch);
8798 if (decimal >= 0)
8799 p[i] = '0' + decimal;
8800 }
8801 }
Victor Stinner17efeed2011-10-04 20:05:46 +02008802#ifndef DONT_MAKE_RESULT_READY
8803 if (_PyUnicode_READY_REPLACE(&result)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008804 Py_DECREF(result);
8805 return NULL;
8806 }
Victor Stinner17efeed2011-10-04 20:05:46 +02008807#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02008808 assert(_PyUnicode_CheckConsistency(result, 1));
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008809 return result;
8810}
Guido van Rossum9e896b32000-04-05 20:11:21 +00008811/* --- Decimal Encoder ---------------------------------------------------- */
8812
Alexander Belopolsky40018472011-02-26 01:02:56 +00008813int
8814PyUnicode_EncodeDecimal(Py_UNICODE *s,
8815 Py_ssize_t length,
8816 char *output,
8817 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00008818{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008819 PyObject *errorHandler = NULL;
8820 PyObject *exc = NULL;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008821 PyObject *unicode;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008822 const char *encoding = "decimal";
8823 const char *reason = "invalid decimal Unicode string";
8824 /* the following variable is used for caching string comparisons
8825 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
8826 int known_errorHandler = -1;
Victor Stinner42bf7752011-11-21 22:52:58 +01008827 Py_ssize_t i, j;
8828 enum PyUnicode_Kind kind;
8829 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008830
8831 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008832 PyErr_BadArgument();
8833 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008834 }
8835
Victor Stinner42bf7752011-11-21 22:52:58 +01008836 unicode = PyUnicode_FromUnicode(s, length);
8837 if (unicode == NULL)
8838 return -1;
8839
8840 if (PyUnicode_READY(unicode) < 0)
8841 goto onError;
8842 kind = PyUnicode_KIND(unicode);
8843 data = PyUnicode_DATA(unicode);
8844
8845 for (i=0; i < length; i++) {
8846 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00008847 int decimal;
Victor Stinner42bf7752011-11-21 22:52:58 +01008848 Py_ssize_t startpos, endpos;
Tim Petersced69f82003-09-16 20:30:58 +00008849
Benjamin Peterson29060642009-01-31 22:14:21 +00008850 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008851 *output++ = ' ';
Benjamin Peterson29060642009-01-31 22:14:21 +00008852 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008853 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008854 decimal = Py_UNICODE_TODECIMAL(ch);
8855 if (decimal >= 0) {
8856 *output++ = '0' + decimal;
Benjamin Peterson29060642009-01-31 22:14:21 +00008857 continue;
8858 }
8859 if (0 < ch && ch < 256) {
8860 *output++ = (char)ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00008861 continue;
8862 }
8863 /* All other characters are considered unencodable */
Victor Stinner42bf7752011-11-21 22:52:58 +01008864 startpos = i;
8865 endpos = i+1;
8866 for (; endpos < length; endpos++) {
8867 ch = PyUnicode_READ(kind, data, endpos);
8868 if ((0 < ch && ch < 256) ||
8869 !Py_UNICODE_ISSPACE(ch) ||
8870 Py_UNICODE_TODECIMAL(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +00008871 break;
8872 }
8873 /* cache callback name lookup
8874 * (if not done yet, i.e. it's the first error) */
8875 if (known_errorHandler==-1) {
8876 if ((errors==NULL) || (!strcmp(errors, "strict")))
8877 known_errorHandler = 1;
8878 else if (!strcmp(errors, "replace"))
8879 known_errorHandler = 2;
8880 else if (!strcmp(errors, "ignore"))
8881 known_errorHandler = 3;
8882 else if (!strcmp(errors, "xmlcharrefreplace"))
8883 known_errorHandler = 4;
8884 else
8885 known_errorHandler = 0;
8886 }
8887 switch (known_errorHandler) {
8888 case 1: /* strict */
Victor Stinner42bf7752011-11-21 22:52:58 +01008889 raise_encode_exception(&exc, encoding, unicode, startpos, endpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008890 goto onError;
8891 case 2: /* replace */
Victor Stinner42bf7752011-11-21 22:52:58 +01008892 for (j=startpos; j < endpos; j++)
Benjamin Peterson29060642009-01-31 22:14:21 +00008893 *output++ = '?';
8894 /* fall through */
8895 case 3: /* ignore */
Victor Stinner42bf7752011-11-21 22:52:58 +01008896 i = endpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00008897 break;
8898 case 4: /* xmlcharrefreplace */
Victor Stinner42bf7752011-11-21 22:52:58 +01008899 /* generate replacement */
8900 for (j=startpos; j < endpos; j++) {
8901 ch = PyUnicode_READ(kind, data, i);
8902 output += sprintf(output, "&#%d;", (int)ch);
8903 i++;
8904 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008905 break;
8906 default:
Victor Stinner42bf7752011-11-21 22:52:58 +01008907 {
8908 PyObject *repunicode;
8909 Py_ssize_t repsize, newpos, k;
8910 enum PyUnicode_Kind repkind;
8911 void *repdata;
8912
Benjamin Peterson29060642009-01-31 22:14:21 +00008913 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008914 encoding, reason, unicode, &exc,
Victor Stinner42bf7752011-11-21 22:52:58 +01008915 startpos, endpos, &newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008916 if (repunicode == NULL)
8917 goto onError;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008918 if (!PyUnicode_Check(repunicode)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00008919 /* Byte results not supported, since they have no decimal property. */
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008920 PyErr_SetString(PyExc_TypeError, "error handler should return unicode");
8921 Py_DECREF(repunicode);
8922 goto onError;
8923 }
Victor Stinner42bf7752011-11-21 22:52:58 +01008924 if (PyUnicode_READY(repunicode) < 0) {
8925 Py_DECREF(repunicode);
8926 goto onError;
8927 }
8928 repkind = PyUnicode_KIND(repunicode);
8929 repdata = PyUnicode_DATA(repunicode);
8930
Benjamin Peterson29060642009-01-31 22:14:21 +00008931 /* generate replacement */
8932 repsize = PyUnicode_GET_SIZE(repunicode);
Victor Stinner42bf7752011-11-21 22:52:58 +01008933 for (k=0; k<repsize; k++) {
8934 ch = PyUnicode_READ(repkind, repdata, k);
Benjamin Peterson29060642009-01-31 22:14:21 +00008935 if (Py_UNICODE_ISSPACE(ch))
8936 *output++ = ' ';
8937 else {
8938 decimal = Py_UNICODE_TODECIMAL(ch);
8939 if (decimal >= 0)
8940 *output++ = '0' + decimal;
8941 else if (0 < ch && ch < 256)
8942 *output++ = (char)ch;
8943 else {
8944 Py_DECREF(repunicode);
8945 raise_encode_exception(&exc, encoding,
Victor Stinner42bf7752011-11-21 22:52:58 +01008946 unicode, startpos, endpos,
8947 reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008948 goto onError;
8949 }
8950 }
8951 }
Victor Stinner42bf7752011-11-21 22:52:58 +01008952 i = newpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00008953 Py_DECREF(repunicode);
8954 }
Victor Stinner42bf7752011-11-21 22:52:58 +01008955 }
Guido van Rossum9e896b32000-04-05 20:11:21 +00008956 }
8957 /* 0-terminate the output string */
8958 *output++ = '\0';
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008959 Py_XDECREF(exc);
8960 Py_XDECREF(errorHandler);
Victor Stinner42bf7752011-11-21 22:52:58 +01008961 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008962 return 0;
8963
Benjamin Peterson29060642009-01-31 22:14:21 +00008964 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008965 Py_XDECREF(exc);
8966 Py_XDECREF(errorHandler);
Victor Stinner42bf7752011-11-21 22:52:58 +01008967 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008968 return -1;
8969}
8970
Guido van Rossumd57fd912000-03-10 22:53:23 +00008971/* --- Helpers ------------------------------------------------------------ */
8972
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008973static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02008974any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008975 Py_ssize_t start,
8976 Py_ssize_t end)
8977{
8978 int kind1, kind2, kind;
8979 void *buf1, *buf2;
8980 Py_ssize_t len1, len2, result;
8981
8982 kind1 = PyUnicode_KIND(s1);
8983 kind2 = PyUnicode_KIND(s2);
8984 kind = kind1 > kind2 ? kind1 : kind2;
8985 buf1 = PyUnicode_DATA(s1);
8986 buf2 = PyUnicode_DATA(s2);
8987 if (kind1 != kind)
8988 buf1 = _PyUnicode_AsKind(s1, kind);
8989 if (!buf1)
8990 return -2;
8991 if (kind2 != kind)
8992 buf2 = _PyUnicode_AsKind(s2, kind);
8993 if (!buf2) {
8994 if (kind1 != kind) PyMem_Free(buf1);
8995 return -2;
8996 }
8997 len1 = PyUnicode_GET_LENGTH(s1);
8998 len2 = PyUnicode_GET_LENGTH(s2);
8999
Victor Stinner794d5672011-10-10 03:21:36 +02009000 if (direction > 0) {
9001 switch(kind) {
9002 case PyUnicode_1BYTE_KIND:
9003 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9004 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9005 else
9006 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9007 break;
9008 case PyUnicode_2BYTE_KIND:
9009 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9010 break;
9011 case PyUnicode_4BYTE_KIND:
9012 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9013 break;
9014 default:
9015 assert(0); result = -2;
9016 }
9017 }
9018 else {
9019 switch(kind) {
9020 case PyUnicode_1BYTE_KIND:
9021 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9022 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9023 else
9024 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9025 break;
9026 case PyUnicode_2BYTE_KIND:
9027 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9028 break;
9029 case PyUnicode_4BYTE_KIND:
9030 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9031 break;
9032 default:
9033 assert(0); result = -2;
9034 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009035 }
9036
9037 if (kind1 != kind)
9038 PyMem_Free(buf1);
9039 if (kind2 != kind)
9040 PyMem_Free(buf2);
9041
9042 return result;
9043}
9044
9045Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02009046_PyUnicode_InsertThousandsGrouping(PyObject *unicode, int kind, void *data,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009047 Py_ssize_t n_buffer,
9048 void *digits, Py_ssize_t n_digits,
9049 Py_ssize_t min_width,
9050 const char *grouping,
9051 const char *thousands_sep)
9052{
9053 switch(kind) {
9054 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009055 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
9056 return _PyUnicode_ascii_InsertThousandsGrouping(
9057 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
9058 min_width, grouping, thousands_sep);
9059 else
9060 return _PyUnicode_ucs1_InsertThousandsGrouping(
9061 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
9062 min_width, grouping, thousands_sep);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009063 case PyUnicode_2BYTE_KIND:
9064 return _PyUnicode_ucs2_InsertThousandsGrouping(
9065 (Py_UCS2*)data, n_buffer, (Py_UCS2*)digits, n_digits,
9066 min_width, grouping, thousands_sep);
9067 case PyUnicode_4BYTE_KIND:
9068 return _PyUnicode_ucs4_InsertThousandsGrouping(
9069 (Py_UCS4*)data, n_buffer, (Py_UCS4*)digits, n_digits,
9070 min_width, grouping, thousands_sep);
9071 }
9072 assert(0);
9073 return -1;
9074}
9075
9076
Thomas Wouters477c8d52006-05-27 19:21:47 +00009077/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009078#define ADJUST_INDICES(start, end, len) \
9079 if (end > len) \
9080 end = len; \
9081 else if (end < 0) { \
9082 end += len; \
9083 if (end < 0) \
9084 end = 0; \
9085 } \
9086 if (start < 0) { \
9087 start += len; \
9088 if (start < 0) \
9089 start = 0; \
9090 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009091
Alexander Belopolsky40018472011-02-26 01:02:56 +00009092Py_ssize_t
9093PyUnicode_Count(PyObject *str,
9094 PyObject *substr,
9095 Py_ssize_t start,
9096 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009097{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009098 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009099 PyObject* str_obj;
9100 PyObject* sub_obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009101 int kind1, kind2, kind;
9102 void *buf1 = NULL, *buf2 = NULL;
9103 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009104
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009105 str_obj = PyUnicode_FromObject(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009106 if (!str_obj || PyUnicode_READY(str_obj) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009107 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009108 sub_obj = PyUnicode_FromObject(substr);
Victor Stinnere9a29352011-10-01 02:14:59 +02009109 if (!sub_obj || PyUnicode_READY(sub_obj) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009110 Py_DECREF(str_obj);
9111 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009112 }
Tim Petersced69f82003-09-16 20:30:58 +00009113
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009114 kind1 = PyUnicode_KIND(str_obj);
9115 kind2 = PyUnicode_KIND(sub_obj);
9116 kind = kind1 > kind2 ? kind1 : kind2;
9117 buf1 = PyUnicode_DATA(str_obj);
9118 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009119 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009120 if (!buf1)
9121 goto onError;
9122 buf2 = PyUnicode_DATA(sub_obj);
9123 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009124 buf2 = _PyUnicode_AsKind(sub_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009125 if (!buf2)
9126 goto onError;
9127 len1 = PyUnicode_GET_LENGTH(str_obj);
9128 len2 = PyUnicode_GET_LENGTH(sub_obj);
9129
9130 ADJUST_INDICES(start, end, len1);
9131 switch(kind) {
9132 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009133 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
9134 result = asciilib_count(
9135 ((Py_UCS1*)buf1) + start, end - start,
9136 buf2, len2, PY_SSIZE_T_MAX
9137 );
9138 else
9139 result = ucs1lib_count(
9140 ((Py_UCS1*)buf1) + start, end - start,
9141 buf2, len2, PY_SSIZE_T_MAX
9142 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009143 break;
9144 case PyUnicode_2BYTE_KIND:
9145 result = ucs2lib_count(
9146 ((Py_UCS2*)buf1) + start, end - start,
9147 buf2, len2, PY_SSIZE_T_MAX
9148 );
9149 break;
9150 case PyUnicode_4BYTE_KIND:
9151 result = ucs4lib_count(
9152 ((Py_UCS4*)buf1) + start, end - start,
9153 buf2, len2, PY_SSIZE_T_MAX
9154 );
9155 break;
9156 default:
9157 assert(0); result = 0;
9158 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009159
9160 Py_DECREF(sub_obj);
9161 Py_DECREF(str_obj);
9162
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009163 if (kind1 != kind)
9164 PyMem_Free(buf1);
9165 if (kind2 != kind)
9166 PyMem_Free(buf2);
9167
Guido van Rossumd57fd912000-03-10 22:53:23 +00009168 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009169 onError:
9170 Py_DECREF(sub_obj);
9171 Py_DECREF(str_obj);
9172 if (kind1 != kind && buf1)
9173 PyMem_Free(buf1);
9174 if (kind2 != kind && buf2)
9175 PyMem_Free(buf2);
9176 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009177}
9178
Alexander Belopolsky40018472011-02-26 01:02:56 +00009179Py_ssize_t
9180PyUnicode_Find(PyObject *str,
9181 PyObject *sub,
9182 Py_ssize_t start,
9183 Py_ssize_t end,
9184 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009185{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009186 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009187
Guido van Rossumd57fd912000-03-10 22:53:23 +00009188 str = PyUnicode_FromObject(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009189 if (!str || PyUnicode_READY(str) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009190 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009191 sub = PyUnicode_FromObject(sub);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009192 if (!sub || PyUnicode_READY(sub) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009193 Py_DECREF(str);
9194 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009195 }
Tim Petersced69f82003-09-16 20:30:58 +00009196
Victor Stinner794d5672011-10-10 03:21:36 +02009197 result = any_find_slice(direction,
9198 str, sub, start, end
9199 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00009200
Guido van Rossumd57fd912000-03-10 22:53:23 +00009201 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009202 Py_DECREF(sub);
9203
Guido van Rossumd57fd912000-03-10 22:53:23 +00009204 return result;
9205}
9206
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009207Py_ssize_t
9208PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9209 Py_ssize_t start, Py_ssize_t end,
9210 int direction)
9211{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009212 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009213 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009214 if (PyUnicode_READY(str) == -1)
9215 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009216 if (start < 0 || end < 0) {
9217 PyErr_SetString(PyExc_IndexError, "string index out of range");
9218 return -2;
9219 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009220 if (end > PyUnicode_GET_LENGTH(str))
9221 end = PyUnicode_GET_LENGTH(str);
9222 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009223 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9224 kind, end-start, ch, direction);
9225 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009226 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009227 else
9228 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009229}
9230
Alexander Belopolsky40018472011-02-26 01:02:56 +00009231static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009232tailmatch(PyObject *self,
9233 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009234 Py_ssize_t start,
9235 Py_ssize_t end,
9236 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009237{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009238 int kind_self;
9239 int kind_sub;
9240 void *data_self;
9241 void *data_sub;
9242 Py_ssize_t offset;
9243 Py_ssize_t i;
9244 Py_ssize_t end_sub;
9245
9246 if (PyUnicode_READY(self) == -1 ||
9247 PyUnicode_READY(substring) == -1)
9248 return 0;
9249
9250 if (PyUnicode_GET_LENGTH(substring) == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009251 return 1;
9252
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009253 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9254 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009255 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009256 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009257
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009258 kind_self = PyUnicode_KIND(self);
9259 data_self = PyUnicode_DATA(self);
9260 kind_sub = PyUnicode_KIND(substring);
9261 data_sub = PyUnicode_DATA(substring);
9262 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9263
9264 if (direction > 0)
9265 offset = end;
9266 else
9267 offset = start;
9268
9269 if (PyUnicode_READ(kind_self, data_self, offset) ==
9270 PyUnicode_READ(kind_sub, data_sub, 0) &&
9271 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9272 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9273 /* If both are of the same kind, memcmp is sufficient */
9274 if (kind_self == kind_sub) {
9275 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009276 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009277 data_sub,
9278 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009279 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009280 }
9281 /* otherwise we have to compare each character by first accesing it */
9282 else {
9283 /* We do not need to compare 0 and len(substring)-1 because
9284 the if statement above ensured already that they are equal
9285 when we end up here. */
9286 // TODO: honor direction and do a forward or backwards search
9287 for (i = 1; i < end_sub; ++i) {
9288 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9289 PyUnicode_READ(kind_sub, data_sub, i))
9290 return 0;
9291 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009292 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009293 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009294 }
9295
9296 return 0;
9297}
9298
Alexander Belopolsky40018472011-02-26 01:02:56 +00009299Py_ssize_t
9300PyUnicode_Tailmatch(PyObject *str,
9301 PyObject *substr,
9302 Py_ssize_t start,
9303 Py_ssize_t end,
9304 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009305{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009306 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009307
Guido van Rossumd57fd912000-03-10 22:53:23 +00009308 str = PyUnicode_FromObject(str);
9309 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009310 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009311 substr = PyUnicode_FromObject(substr);
9312 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009313 Py_DECREF(str);
9314 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009315 }
Tim Petersced69f82003-09-16 20:30:58 +00009316
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009317 result = tailmatch(str, substr,
Benjamin Peterson29060642009-01-31 22:14:21 +00009318 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009319 Py_DECREF(str);
9320 Py_DECREF(substr);
9321 return result;
9322}
9323
Guido van Rossumd57fd912000-03-10 22:53:23 +00009324/* Apply fixfct filter to the Unicode object self and return a
9325 reference to the modified object */
9326
Alexander Belopolsky40018472011-02-26 01:02:56 +00009327static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009328fixup(PyObject *self,
9329 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009330{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009331 PyObject *u;
9332 Py_UCS4 maxchar_old, maxchar_new = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009333
Victor Stinner87af4f22011-11-21 23:03:47 +01009334 u = PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009335 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009336 return NULL;
Victor Stinner87af4f22011-11-21 23:03:47 +01009337 maxchar_old = PyUnicode_MAX_CHAR_VALUE(u);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009338
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009339 /* fix functions return the new maximum character in a string,
9340 if the kind of the resulting unicode object does not change,
9341 everything is fine. Otherwise we need to change the string kind
9342 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009343 maxchar_new = fixfct(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009344 if (maxchar_new == 0)
9345 /* do nothing, keep maxchar_new at 0 which means no changes. */;
9346 else if (maxchar_new <= 127)
9347 maxchar_new = 127;
9348 else if (maxchar_new <= 255)
9349 maxchar_new = 255;
9350 else if (maxchar_new <= 65535)
9351 maxchar_new = 65535;
9352 else
9353 maxchar_new = 1114111; /* 0x10ffff */
9354
9355 if (!maxchar_new && PyUnicode_CheckExact(self)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009356 /* fixfct should return TRUE if it modified the buffer. If
9357 FALSE, return a reference to the original buffer instead
9358 (to save space, not time) */
9359 Py_INCREF(self);
9360 Py_DECREF(u);
Victor Stinner7931d9a2011-11-04 00:22:48 +01009361 return self;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009362 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009363 else if (maxchar_new == maxchar_old) {
9364 return u;
9365 }
9366 else {
9367 /* In case the maximum character changed, we need to
9368 convert the string to the new category. */
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009369 PyObject *v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009370 if (v == NULL) {
9371 Py_DECREF(u);
9372 return NULL;
9373 }
9374 if (maxchar_new > maxchar_old) {
9375 /* If the maxchar increased so that the kind changed, not all
9376 characters are representable anymore and we need to fix the
9377 string again. This only happens in very few cases. */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009378 copy_characters(v, 0, self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinner9310abb2011-10-05 00:59:23 +02009379 maxchar_old = fixfct(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009380 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
9381 }
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009382 else {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009383 copy_characters(v, 0, u, 0, PyUnicode_GET_LENGTH(self));
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009384 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009385
9386 Py_DECREF(u);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009387 assert(_PyUnicode_CheckConsistency(v, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009388 return v;
9389 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009390}
9391
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009392static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009393fixupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009394{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009395 /* No need to call PyUnicode_READY(self) because this function is only
9396 called as a callback from fixup() which does it already. */
9397 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9398 const int kind = PyUnicode_KIND(self);
9399 void *data = PyUnicode_DATA(self);
9400 int touched = 0;
9401 Py_UCS4 maxchar = 0;
9402 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009403
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009404 for (i = 0; i < len; ++i) {
9405 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9406 const Py_UCS4 up = Py_UNICODE_TOUPPER(ch);
9407 if (up != ch) {
9408 if (up > maxchar)
9409 maxchar = up;
9410 PyUnicode_WRITE(kind, data, i, up);
9411 touched = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00009412 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009413 else if (ch > maxchar)
9414 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009415 }
9416
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009417 if (touched)
9418 return maxchar;
9419 else
9420 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009421}
9422
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009423static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009424fixlower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009425{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009426 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9427 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9428 const int kind = PyUnicode_KIND(self);
9429 void *data = PyUnicode_DATA(self);
9430 int touched = 0;
9431 Py_UCS4 maxchar = 0;
9432 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009433
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009434 for(i = 0; i < len; ++i) {
9435 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9436 const Py_UCS4 lo = Py_UNICODE_TOLOWER(ch);
9437 if (lo != ch) {
9438 if (lo > maxchar)
9439 maxchar = lo;
9440 PyUnicode_WRITE(kind, data, i, lo);
9441 touched = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00009442 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009443 else if (ch > maxchar)
9444 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009445 }
9446
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009447 if (touched)
9448 return maxchar;
9449 else
9450 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009451}
9452
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009453static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009454fixswapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009455{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009456 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9457 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9458 const int kind = PyUnicode_KIND(self);
9459 void *data = PyUnicode_DATA(self);
9460 int touched = 0;
9461 Py_UCS4 maxchar = 0;
9462 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009463
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009464 for(i = 0; i < len; ++i) {
9465 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9466 Py_UCS4 nu = 0;
9467
9468 if (Py_UNICODE_ISUPPER(ch))
9469 nu = Py_UNICODE_TOLOWER(ch);
9470 else if (Py_UNICODE_ISLOWER(ch))
9471 nu = Py_UNICODE_TOUPPER(ch);
9472
9473 if (nu != 0) {
9474 if (nu > maxchar)
9475 maxchar = nu;
9476 PyUnicode_WRITE(kind, data, i, nu);
9477 touched = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009478 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009479 else if (ch > maxchar)
9480 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009481 }
9482
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009483 if (touched)
9484 return maxchar;
9485 else
9486 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009487}
9488
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009489static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009490fixcapitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009491{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009492 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9493 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9494 const int kind = PyUnicode_KIND(self);
9495 void *data = PyUnicode_DATA(self);
9496 int touched = 0;
9497 Py_UCS4 maxchar = 0;
9498 Py_ssize_t i = 0;
9499 Py_UCS4 ch;
Tim Petersced69f82003-09-16 20:30:58 +00009500
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009501 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009502 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009503
9504 ch = PyUnicode_READ(kind, data, i);
9505 if (!Py_UNICODE_ISUPPER(ch)) {
9506 maxchar = Py_UNICODE_TOUPPER(ch);
9507 PyUnicode_WRITE(kind, data, i, maxchar);
9508 touched = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009509 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009510 ++i;
9511 for(; i < len; ++i) {
9512 ch = PyUnicode_READ(kind, data, i);
9513 if (!Py_UNICODE_ISLOWER(ch)) {
9514 const Py_UCS4 lo = Py_UNICODE_TOLOWER(ch);
9515 if (lo > maxchar)
9516 maxchar = lo;
9517 PyUnicode_WRITE(kind, data, i, lo);
9518 touched = 1;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009519 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009520 else if (ch > maxchar)
9521 maxchar = ch;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009522 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009523
9524 if (touched)
9525 return maxchar;
9526 else
9527 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009528}
9529
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009530static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009531fixtitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009532{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009533 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9534 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9535 const int kind = PyUnicode_KIND(self);
9536 void *data = PyUnicode_DATA(self);
9537 Py_UCS4 maxchar = 0;
9538 Py_ssize_t i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009539 int previous_is_cased;
9540
9541 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009542 if (len == 1) {
9543 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9544 const Py_UCS4 ti = Py_UNICODE_TOTITLE(ch);
9545 if (ti != ch) {
9546 PyUnicode_WRITE(kind, data, i, ti);
9547 return ti;
Benjamin Peterson29060642009-01-31 22:14:21 +00009548 }
9549 else
9550 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009551 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009552 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009553 for(; i < len; ++i) {
9554 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9555 Py_UCS4 nu;
Tim Petersced69f82003-09-16 20:30:58 +00009556
Benjamin Peterson29060642009-01-31 22:14:21 +00009557 if (previous_is_cased)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009558 nu = Py_UNICODE_TOLOWER(ch);
Benjamin Peterson29060642009-01-31 22:14:21 +00009559 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009560 nu = Py_UNICODE_TOTITLE(ch);
9561
9562 if (nu > maxchar)
9563 maxchar = nu;
9564 PyUnicode_WRITE(kind, data, i, nu);
Tim Petersced69f82003-09-16 20:30:58 +00009565
Benjamin Peterson29060642009-01-31 22:14:21 +00009566 if (Py_UNICODE_ISLOWER(ch) ||
9567 Py_UNICODE_ISUPPER(ch) ||
9568 Py_UNICODE_ISTITLE(ch))
9569 previous_is_cased = 1;
9570 else
9571 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009572 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009573 return maxchar;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009574}
9575
Tim Peters8ce9f162004-08-27 01:49:32 +00009576PyObject *
9577PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009578{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009579 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009580 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009581 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009582 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009583 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9584 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009585 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009586 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009587 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009588 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009589 int use_memcpy;
9590 unsigned char *res_data = NULL, *sep_data = NULL;
9591 PyObject *last_obj;
9592 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009593
Tim Peters05eba1f2004-08-27 21:32:02 +00009594 fseq = PySequence_Fast(seq, "");
9595 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009596 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009597 }
9598
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009599 /* NOTE: the following code can't call back into Python code,
9600 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009601 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009602
Tim Peters05eba1f2004-08-27 21:32:02 +00009603 seqlen = PySequence_Fast_GET_SIZE(fseq);
9604 /* If empty sequence, return u"". */
9605 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009606 Py_DECREF(fseq);
9607 Py_INCREF(unicode_empty);
9608 res = unicode_empty;
9609 return res;
Tim Peters05eba1f2004-08-27 21:32:02 +00009610 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009611
Tim Peters05eba1f2004-08-27 21:32:02 +00009612 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009613 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009614 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009615 if (seqlen == 1) {
9616 if (PyUnicode_CheckExact(items[0])) {
9617 res = items[0];
9618 Py_INCREF(res);
9619 Py_DECREF(fseq);
9620 return res;
9621 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009622 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009623 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009624 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009625 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009626 /* Set up sep and seplen */
9627 if (separator == NULL) {
9628 /* fall back to a blank space separator */
9629 sep = PyUnicode_FromOrdinal(' ');
9630 if (!sep)
9631 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009632 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009633 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009634 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009635 else {
9636 if (!PyUnicode_Check(separator)) {
9637 PyErr_Format(PyExc_TypeError,
9638 "separator: expected str instance,"
9639 " %.80s found",
9640 Py_TYPE(separator)->tp_name);
9641 goto onError;
9642 }
9643 if (PyUnicode_READY(separator))
9644 goto onError;
9645 sep = separator;
9646 seplen = PyUnicode_GET_LENGTH(separator);
9647 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9648 /* inc refcount to keep this code path symmetric with the
9649 above case of a blank separator */
9650 Py_INCREF(sep);
9651 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009652 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009653 }
9654
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009655 /* There are at least two things to join, or else we have a subclass
9656 * of str in the sequence.
9657 * Do a pre-pass to figure out the total amount of space we'll
9658 * need (sz), and see whether all argument are strings.
9659 */
9660 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009661#ifdef Py_DEBUG
9662 use_memcpy = 0;
9663#else
9664 use_memcpy = 1;
9665#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009666 for (i = 0; i < seqlen; i++) {
9667 const Py_ssize_t old_sz = sz;
9668 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009669 if (!PyUnicode_Check(item)) {
9670 PyErr_Format(PyExc_TypeError,
9671 "sequence item %zd: expected str instance,"
9672 " %.80s found",
9673 i, Py_TYPE(item)->tp_name);
9674 goto onError;
9675 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009676 if (PyUnicode_READY(item) == -1)
9677 goto onError;
9678 sz += PyUnicode_GET_LENGTH(item);
9679 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009680 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009681 if (i != 0)
9682 sz += seplen;
9683 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9684 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009685 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009686 goto onError;
9687 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009688 if (use_memcpy && last_obj != NULL) {
9689 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9690 use_memcpy = 0;
9691 }
9692 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009693 }
Tim Petersced69f82003-09-16 20:30:58 +00009694
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009695 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009696 if (res == NULL)
9697 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009698
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009699 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009700#ifdef Py_DEBUG
9701 use_memcpy = 0;
9702#else
9703 if (use_memcpy) {
9704 res_data = PyUnicode_1BYTE_DATA(res);
9705 kind = PyUnicode_KIND(res);
9706 if (seplen != 0)
9707 sep_data = PyUnicode_1BYTE_DATA(sep);
9708 }
9709#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009710 for (i = 0, res_offset = 0; i < seqlen; ++i) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009711 Py_ssize_t itemlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009712 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009713 /* Copy item, and maybe the separator. */
Victor Stinner9ce5a832011-10-03 23:36:02 +02009714 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009715 if (use_memcpy) {
9716 Py_MEMCPY(res_data,
9717 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009718 kind * seplen);
9719 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009720 }
9721 else {
9722 copy_characters(res, res_offset, sep, 0, seplen);
9723 res_offset += seplen;
9724 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009725 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009726 itemlen = PyUnicode_GET_LENGTH(item);
9727 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009728 if (use_memcpy) {
9729 Py_MEMCPY(res_data,
9730 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009731 kind * itemlen);
9732 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009733 }
9734 else {
9735 copy_characters(res, res_offset, item, 0, itemlen);
9736 res_offset += itemlen;
9737 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009738 }
Tim Peters05eba1f2004-08-27 21:32:02 +00009739 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009740 if (use_memcpy)
9741 assert(res_data == PyUnicode_1BYTE_DATA(res)
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009742 + kind * PyUnicode_GET_LENGTH(res));
Victor Stinnerdd077322011-10-07 17:02:31 +02009743 else
9744 assert(res_offset == PyUnicode_GET_LENGTH(res));
Tim Peters8ce9f162004-08-27 01:49:32 +00009745
Tim Peters05eba1f2004-08-27 21:32:02 +00009746 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009747 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009748 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009749 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009750
Benjamin Peterson29060642009-01-31 22:14:21 +00009751 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00009752 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009753 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009754 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009755 return NULL;
9756}
9757
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009758#define FILL(kind, data, value, start, length) \
9759 do { \
9760 Py_ssize_t i_ = 0; \
9761 assert(kind != PyUnicode_WCHAR_KIND); \
9762 switch ((kind)) { \
9763 case PyUnicode_1BYTE_KIND: { \
9764 unsigned char * to_ = (unsigned char *)((data)) + (start); \
9765 memset(to_, (unsigned char)value, length); \
9766 break; \
9767 } \
9768 case PyUnicode_2BYTE_KIND: { \
9769 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
9770 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9771 break; \
9772 } \
9773 default: { \
9774 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
9775 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9776 break; \
9777 } \
9778 } \
9779 } while (0)
9780
Victor Stinner9310abb2011-10-05 00:59:23 +02009781static PyObject *
9782pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009783 Py_ssize_t left,
9784 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009785 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009786{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009787 PyObject *u;
9788 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009789 int kind;
9790 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009791
9792 if (left < 0)
9793 left = 0;
9794 if (right < 0)
9795 right = 0;
9796
Tim Peters7a29bd52001-09-12 03:03:31 +00009797 if (left == 0 && right == 0 && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00009798 Py_INCREF(self);
9799 return self;
9800 }
9801
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009802 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
9803 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00009804 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
9805 return NULL;
9806 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009807 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
9808 if (fill > maxchar)
9809 maxchar = fill;
9810 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009811 if (!u)
9812 return NULL;
9813
9814 kind = PyUnicode_KIND(u);
9815 data = PyUnicode_DATA(u);
9816 if (left)
9817 FILL(kind, data, fill, 0, left);
9818 if (right)
9819 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009820 copy_characters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009821 assert(_PyUnicode_CheckConsistency(u, 1));
9822 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009823}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009824#undef FILL
Guido van Rossumd57fd912000-03-10 22:53:23 +00009825
Alexander Belopolsky40018472011-02-26 01:02:56 +00009826PyObject *
9827PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009828{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009829 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009830
9831 string = PyUnicode_FromObject(string);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009832 if (string == NULL || PyUnicode_READY(string) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009833 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009834
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009835 switch(PyUnicode_KIND(string)) {
9836 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009837 if (PyUnicode_IS_ASCII(string))
9838 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009839 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009840 PyUnicode_GET_LENGTH(string), keepends);
9841 else
9842 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009843 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009844 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009845 break;
9846 case PyUnicode_2BYTE_KIND:
9847 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009848 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009849 PyUnicode_GET_LENGTH(string), keepends);
9850 break;
9851 case PyUnicode_4BYTE_KIND:
9852 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009853 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009854 PyUnicode_GET_LENGTH(string), keepends);
9855 break;
9856 default:
9857 assert(0);
9858 list = 0;
9859 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009860 Py_DECREF(string);
9861 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009862}
9863
Alexander Belopolsky40018472011-02-26 01:02:56 +00009864static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009865split(PyObject *self,
9866 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009867 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009868{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009869 int kind1, kind2, kind;
9870 void *buf1, *buf2;
9871 Py_ssize_t len1, len2;
9872 PyObject* out;
9873
Guido van Rossumd57fd912000-03-10 22:53:23 +00009874 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009875 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009876
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009877 if (PyUnicode_READY(self) == -1)
9878 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009879
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009880 if (substring == NULL)
9881 switch(PyUnicode_KIND(self)) {
9882 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009883 if (PyUnicode_IS_ASCII(self))
9884 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009885 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009886 PyUnicode_GET_LENGTH(self), maxcount
9887 );
9888 else
9889 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009890 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009891 PyUnicode_GET_LENGTH(self), maxcount
9892 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009893 case PyUnicode_2BYTE_KIND:
9894 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009895 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009896 PyUnicode_GET_LENGTH(self), maxcount
9897 );
9898 case PyUnicode_4BYTE_KIND:
9899 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009900 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009901 PyUnicode_GET_LENGTH(self), maxcount
9902 );
9903 default:
9904 assert(0);
9905 return NULL;
9906 }
9907
9908 if (PyUnicode_READY(substring) == -1)
9909 return NULL;
9910
9911 kind1 = PyUnicode_KIND(self);
9912 kind2 = PyUnicode_KIND(substring);
9913 kind = kind1 > kind2 ? kind1 : kind2;
9914 buf1 = PyUnicode_DATA(self);
9915 buf2 = PyUnicode_DATA(substring);
9916 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009917 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009918 if (!buf1)
9919 return NULL;
9920 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009921 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009922 if (!buf2) {
9923 if (kind1 != kind) PyMem_Free(buf1);
9924 return NULL;
9925 }
9926 len1 = PyUnicode_GET_LENGTH(self);
9927 len2 = PyUnicode_GET_LENGTH(substring);
9928
9929 switch(kind) {
9930 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009931 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
9932 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009933 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009934 else
9935 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009936 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009937 break;
9938 case PyUnicode_2BYTE_KIND:
9939 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009940 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009941 break;
9942 case PyUnicode_4BYTE_KIND:
9943 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009944 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009945 break;
9946 default:
9947 out = NULL;
9948 }
9949 if (kind1 != kind)
9950 PyMem_Free(buf1);
9951 if (kind2 != kind)
9952 PyMem_Free(buf2);
9953 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009954}
9955
Alexander Belopolsky40018472011-02-26 01:02:56 +00009956static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009957rsplit(PyObject *self,
9958 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009959 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009960{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009961 int kind1, kind2, kind;
9962 void *buf1, *buf2;
9963 Py_ssize_t len1, len2;
9964 PyObject* out;
9965
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009966 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009967 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009968
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009969 if (PyUnicode_READY(self) == -1)
9970 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009971
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009972 if (substring == NULL)
9973 switch(PyUnicode_KIND(self)) {
9974 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009975 if (PyUnicode_IS_ASCII(self))
9976 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009977 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009978 PyUnicode_GET_LENGTH(self), maxcount
9979 );
9980 else
9981 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009982 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009983 PyUnicode_GET_LENGTH(self), maxcount
9984 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009985 case PyUnicode_2BYTE_KIND:
9986 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009987 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009988 PyUnicode_GET_LENGTH(self), maxcount
9989 );
9990 case PyUnicode_4BYTE_KIND:
9991 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009992 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009993 PyUnicode_GET_LENGTH(self), maxcount
9994 );
9995 default:
9996 assert(0);
9997 return NULL;
9998 }
9999
10000 if (PyUnicode_READY(substring) == -1)
10001 return NULL;
10002
10003 kind1 = PyUnicode_KIND(self);
10004 kind2 = PyUnicode_KIND(substring);
10005 kind = kind1 > kind2 ? kind1 : kind2;
10006 buf1 = PyUnicode_DATA(self);
10007 buf2 = PyUnicode_DATA(substring);
10008 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010009 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010010 if (!buf1)
10011 return NULL;
10012 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010013 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010014 if (!buf2) {
10015 if (kind1 != kind) PyMem_Free(buf1);
10016 return NULL;
10017 }
10018 len1 = PyUnicode_GET_LENGTH(self);
10019 len2 = PyUnicode_GET_LENGTH(substring);
10020
10021 switch(kind) {
10022 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010023 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10024 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010025 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010026 else
10027 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010028 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010029 break;
10030 case PyUnicode_2BYTE_KIND:
10031 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010032 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010033 break;
10034 case PyUnicode_4BYTE_KIND:
10035 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010036 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010037 break;
10038 default:
10039 out = NULL;
10040 }
10041 if (kind1 != kind)
10042 PyMem_Free(buf1);
10043 if (kind2 != kind)
10044 PyMem_Free(buf2);
10045 return out;
10046}
10047
10048static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010049anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10050 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010051{
10052 switch(kind) {
10053 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010054 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10055 return asciilib_find(buf1, len1, buf2, len2, offset);
10056 else
10057 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010058 case PyUnicode_2BYTE_KIND:
10059 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10060 case PyUnicode_4BYTE_KIND:
10061 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10062 }
10063 assert(0);
10064 return -1;
10065}
10066
10067static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010068anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10069 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010070{
10071 switch(kind) {
10072 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010073 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10074 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10075 else
10076 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010077 case PyUnicode_2BYTE_KIND:
10078 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10079 case PyUnicode_4BYTE_KIND:
10080 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10081 }
10082 assert(0);
10083 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010084}
10085
Alexander Belopolsky40018472011-02-26 01:02:56 +000010086static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010087replace(PyObject *self, PyObject *str1,
10088 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010089{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010090 PyObject *u;
10091 char *sbuf = PyUnicode_DATA(self);
10092 char *buf1 = PyUnicode_DATA(str1);
10093 char *buf2 = PyUnicode_DATA(str2);
10094 int srelease = 0, release1 = 0, release2 = 0;
10095 int skind = PyUnicode_KIND(self);
10096 int kind1 = PyUnicode_KIND(str1);
10097 int kind2 = PyUnicode_KIND(str2);
10098 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10099 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10100 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010101 int mayshrink;
10102 Py_UCS4 maxchar, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010103
10104 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010105 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010106 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010107 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010108
Victor Stinner59de0ee2011-10-07 10:01:28 +020010109 if (str1 == str2)
10110 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010111 if (skind < kind1)
10112 /* substring too wide to be present */
10113 goto nothing;
10114
Victor Stinner49a0a212011-10-12 23:46:10 +020010115 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
10116 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10117 /* Replacing str1 with str2 may cause a maxchar reduction in the
10118 result string. */
10119 mayshrink = (maxchar_str2 < maxchar);
10120 maxchar = Py_MAX(maxchar, maxchar_str2);
10121
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010122 if (len1 == len2) {
Antoine Pitroucbfdee32010-01-13 08:58:08 +000010123 Py_ssize_t i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010124 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010125 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010126 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010127 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010128 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010129 Py_UCS4 u1, u2;
10130 int rkind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010131 u1 = PyUnicode_READ_CHAR(str1, 0);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +020010132 if (findchar(sbuf, PyUnicode_KIND(self),
10133 slen, u1, 1) < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010134 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010135 u2 = PyUnicode_READ_CHAR(str2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010136 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010137 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010138 goto error;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010139 copy_characters(u, 0, self, 0, slen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010140 rkind = PyUnicode_KIND(u);
10141 for (i = 0; i < PyUnicode_GET_LENGTH(u); i++)
10142 if (PyUnicode_READ(rkind, PyUnicode_DATA(u), i) == u1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010143 if (--maxcount < 0)
10144 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010145 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), i, u2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010146 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010147 }
10148 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010149 int rkind = skind;
10150 char *res;
Victor Stinner25a4b292011-10-06 12:31:55 +020010151
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010152 if (kind1 < rkind) {
10153 /* widen substring */
10154 buf1 = _PyUnicode_AsKind(str1, rkind);
10155 if (!buf1) goto error;
10156 release1 = 1;
10157 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010158 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010159 if (i < 0)
10160 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010161 if (rkind > kind2) {
10162 /* widen replacement */
10163 buf2 = _PyUnicode_AsKind(str2, rkind);
10164 if (!buf2) goto error;
10165 release2 = 1;
10166 }
10167 else if (rkind < kind2) {
10168 /* widen self and buf1 */
10169 rkind = kind2;
10170 if (release1) PyMem_Free(buf1);
10171 sbuf = _PyUnicode_AsKind(self, rkind);
10172 if (!sbuf) goto error;
10173 srelease = 1;
10174 buf1 = _PyUnicode_AsKind(str1, rkind);
10175 if (!buf1) goto error;
10176 release1 = 1;
10177 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010178 u = PyUnicode_New(slen, maxchar);
10179 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010180 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010181 assert(PyUnicode_KIND(u) == rkind);
10182 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010183
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010184 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010185 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010186 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010187 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010188 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010189 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010190
10191 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010192 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010193 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010194 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010195 if (i == -1)
10196 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010197 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010198 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010199 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010200 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010201 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010202 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010203 }
10204 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010205 Py_ssize_t n, i, j, ires;
10206 Py_ssize_t product, new_size;
10207 int rkind = skind;
10208 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010209
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010210 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010211 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010212 buf1 = _PyUnicode_AsKind(str1, rkind);
10213 if (!buf1) goto error;
10214 release1 = 1;
10215 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010216 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010217 if (n == 0)
10218 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010219 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010220 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010221 buf2 = _PyUnicode_AsKind(str2, rkind);
10222 if (!buf2) goto error;
10223 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010224 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010225 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010226 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010227 rkind = kind2;
10228 sbuf = _PyUnicode_AsKind(self, rkind);
10229 if (!sbuf) goto error;
10230 srelease = 1;
10231 if (release1) PyMem_Free(buf1);
10232 buf1 = _PyUnicode_AsKind(str1, rkind);
10233 if (!buf1) goto error;
10234 release1 = 1;
10235 }
10236 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10237 PyUnicode_GET_LENGTH(str1))); */
10238 product = n * (len2-len1);
10239 if ((product / (len2-len1)) != n) {
10240 PyErr_SetString(PyExc_OverflowError,
10241 "replace string is too long");
10242 goto error;
10243 }
10244 new_size = slen + product;
Victor Stinner49a0a212011-10-12 23:46:10 +020010245 if (new_size == 0) {
10246 Py_INCREF(unicode_empty);
10247 u = unicode_empty;
10248 goto done;
10249 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010250 if (new_size < 0 || new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
10251 PyErr_SetString(PyExc_OverflowError,
10252 "replace string is too long");
10253 goto error;
10254 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010255 u = PyUnicode_New(new_size, maxchar);
10256 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010257 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010258 assert(PyUnicode_KIND(u) == rkind);
10259 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010260 ires = i = 0;
10261 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010262 while (n-- > 0) {
10263 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010264 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010265 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010266 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010267 if (j == -1)
10268 break;
10269 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010270 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010271 memcpy(res + rkind * ires,
10272 sbuf + rkind * i,
10273 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010274 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010275 }
10276 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010277 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010278 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010279 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010280 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010281 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010282 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010283 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010284 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010285 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010286 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010287 memcpy(res + rkind * ires,
10288 sbuf + rkind * i,
10289 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010290 }
10291 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010292 /* interleave */
10293 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010294 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010295 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010296 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010297 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010298 if (--n <= 0)
10299 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010300 memcpy(res + rkind * ires,
10301 sbuf + rkind * i,
10302 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010303 ires++;
10304 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010305 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010306 memcpy(res + rkind * ires,
10307 sbuf + rkind * i,
10308 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010309 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010310 }
10311
10312 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010313 unicode_adjust_maxchar(&u);
10314 if (u == NULL)
10315 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010316 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010317
10318 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010319 if (srelease)
10320 PyMem_FREE(sbuf);
10321 if (release1)
10322 PyMem_FREE(buf1);
10323 if (release2)
10324 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010325 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010326 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010327
Benjamin Peterson29060642009-01-31 22:14:21 +000010328 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010329 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010330 if (srelease)
10331 PyMem_FREE(sbuf);
10332 if (release1)
10333 PyMem_FREE(buf1);
10334 if (release2)
10335 PyMem_FREE(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010336 if (PyUnicode_CheckExact(self)) {
10337 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010010338 return self;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010339 }
Victor Stinner034f6cf2011-09-30 02:26:44 +020010340 return PyUnicode_Copy(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010341 error:
10342 if (srelease && sbuf)
10343 PyMem_FREE(sbuf);
10344 if (release1 && buf1)
10345 PyMem_FREE(buf1);
10346 if (release2 && buf2)
10347 PyMem_FREE(buf2);
10348 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010349}
10350
10351/* --- Unicode Object Methods --------------------------------------------- */
10352
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010353PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010354 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010355\n\
10356Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010357characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010358
10359static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010360unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010361{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010362 return fixup(self, fixtitle);
10363}
10364
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010365PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010366 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010367\n\
10368Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010369have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010370
10371static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010372unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010373{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010374 return fixup(self, fixcapitalize);
10375}
10376
10377#if 0
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010378PyDoc_STRVAR(capwords__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010379 "S.capwords() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010380\n\
10381Apply .capitalize() to all words in S and return the result with\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010382normalized whitespace (all whitespace strings are replaced by ' ').");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010383
10384static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010385unicode_capwords(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010386{
10387 PyObject *list;
10388 PyObject *item;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010389 Py_ssize_t i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010390
Guido van Rossumd57fd912000-03-10 22:53:23 +000010391 /* Split into words */
10392 list = split(self, NULL, -1);
10393 if (!list)
10394 return NULL;
10395
10396 /* Capitalize each word */
10397 for (i = 0; i < PyList_GET_SIZE(list); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010398 item = fixup(PyList_GET_ITEM(list, i),
Benjamin Peterson29060642009-01-31 22:14:21 +000010399 fixcapitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010400 if (item == NULL)
10401 goto onError;
10402 Py_DECREF(PyList_GET_ITEM(list, i));
10403 PyList_SET_ITEM(list, i, item);
10404 }
10405
10406 /* Join the words to form a new string */
10407 item = PyUnicode_Join(NULL, list);
10408
Benjamin Peterson29060642009-01-31 22:14:21 +000010409 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010410 Py_DECREF(list);
Victor Stinner7931d9a2011-11-04 00:22:48 +010010411 return item;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010412}
10413#endif
10414
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010415/* Argument converter. Coerces to a single unicode character */
10416
10417static int
10418convert_uc(PyObject *obj, void *addr)
10419{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010420 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010421 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010422
Benjamin Peterson14339b62009-01-31 16:36:08 +000010423 uniobj = PyUnicode_FromObject(obj);
10424 if (uniobj == NULL) {
10425 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010426 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010427 return 0;
10428 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010429 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010430 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010431 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010432 Py_DECREF(uniobj);
10433 return 0;
10434 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010435 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010436 Py_DECREF(uniobj);
10437 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010438}
10439
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010440PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010441 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010442\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010443Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010444done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010445
10446static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010447unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010448{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010449 Py_ssize_t marg, left;
10450 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010451 Py_UCS4 fillchar = ' ';
10452
Victor Stinnere9a29352011-10-01 02:14:59 +020010453 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010454 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010455
Victor Stinnere9a29352011-10-01 02:14:59 +020010456 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010457 return NULL;
10458
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010459 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000010460 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010010461 return self;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010462 }
10463
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010464 marg = width - _PyUnicode_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010465 left = marg / 2 + (marg & width & 1);
10466
Victor Stinner9310abb2011-10-05 00:59:23 +020010467 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010468}
10469
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010470/* This function assumes that str1 and str2 are readied by the caller. */
10471
Marc-André Lemburge5034372000-08-08 08:04:29 +000010472static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010473unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010474{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010475 int kind1, kind2;
10476 void *data1, *data2;
10477 Py_ssize_t len1, len2, i;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010478
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010479 kind1 = PyUnicode_KIND(str1);
10480 kind2 = PyUnicode_KIND(str2);
10481 data1 = PyUnicode_DATA(str1);
10482 data2 = PyUnicode_DATA(str2);
10483 len1 = PyUnicode_GET_LENGTH(str1);
10484 len2 = PyUnicode_GET_LENGTH(str2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010485
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010486 for (i = 0; i < len1 && i < len2; ++i) {
10487 Py_UCS4 c1, c2;
10488 c1 = PyUnicode_READ(kind1, data1, i);
10489 c2 = PyUnicode_READ(kind2, data2, i);
Fredrik Lundh45714e92001-06-26 16:39:36 +000010490
10491 if (c1 != c2)
10492 return (c1 < c2) ? -1 : 1;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010493 }
10494
10495 return (len1 < len2) ? -1 : (len1 != len2);
10496}
10497
Alexander Belopolsky40018472011-02-26 01:02:56 +000010498int
10499PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010500{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010501 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10502 if (PyUnicode_READY(left) == -1 ||
10503 PyUnicode_READY(right) == -1)
10504 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010505 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010506 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010507 PyErr_Format(PyExc_TypeError,
10508 "Can't compare %.100s and %.100s",
10509 left->ob_type->tp_name,
10510 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010511 return -1;
10512}
10513
Martin v. Löwis5b222132007-06-10 09:51:05 +000010514int
10515PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10516{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010517 Py_ssize_t i;
10518 int kind;
10519 void *data;
10520 Py_UCS4 chr;
10521
Victor Stinner910337b2011-10-03 03:20:16 +020010522 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010523 if (PyUnicode_READY(uni) == -1)
10524 return -1;
10525 kind = PyUnicode_KIND(uni);
10526 data = PyUnicode_DATA(uni);
Martin v. Löwis5b222132007-06-10 09:51:05 +000010527 /* Compare Unicode string and source character set string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010528 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
10529 if (chr != str[i])
10530 return (chr < (unsigned char)(str[i])) ? -1 : 1;
Benjamin Peterson8667a9b2010-01-09 21:45:28 +000010531 /* This check keeps Python strings that end in '\0' from comparing equal
10532 to C strings identical up to that point. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010533 if (PyUnicode_GET_LENGTH(uni) != i || chr)
Benjamin Peterson29060642009-01-31 22:14:21 +000010534 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010535 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +000010536 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010537 return 0;
10538}
10539
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010540
Benjamin Peterson29060642009-01-31 22:14:21 +000010541#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010542 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010543
Alexander Belopolsky40018472011-02-26 01:02:56 +000010544PyObject *
10545PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010546{
10547 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010548
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010549 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10550 PyObject *v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010551 if (PyUnicode_READY(left) == -1 ||
10552 PyUnicode_READY(right) == -1)
10553 return NULL;
10554 if (PyUnicode_GET_LENGTH(left) != PyUnicode_GET_LENGTH(right) ||
10555 PyUnicode_KIND(left) != PyUnicode_KIND(right)) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010556 if (op == Py_EQ) {
10557 Py_INCREF(Py_False);
10558 return Py_False;
10559 }
10560 if (op == Py_NE) {
10561 Py_INCREF(Py_True);
10562 return Py_True;
10563 }
10564 }
10565 if (left == right)
10566 result = 0;
10567 else
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010568 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010569
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010570 /* Convert the return value to a Boolean */
10571 switch (op) {
10572 case Py_EQ:
10573 v = TEST_COND(result == 0);
10574 break;
10575 case Py_NE:
10576 v = TEST_COND(result != 0);
10577 break;
10578 case Py_LE:
10579 v = TEST_COND(result <= 0);
10580 break;
10581 case Py_GE:
10582 v = TEST_COND(result >= 0);
10583 break;
10584 case Py_LT:
10585 v = TEST_COND(result == -1);
10586 break;
10587 case Py_GT:
10588 v = TEST_COND(result == 1);
10589 break;
10590 default:
10591 PyErr_BadArgument();
10592 return NULL;
10593 }
10594 Py_INCREF(v);
10595 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010596 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010597
Brian Curtindfc80e32011-08-10 20:28:54 -050010598 Py_RETURN_NOTIMPLEMENTED;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010599}
10600
Alexander Belopolsky40018472011-02-26 01:02:56 +000010601int
10602PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010603{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010604 PyObject *str, *sub;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010605 int kind1, kind2, kind;
10606 void *buf1, *buf2;
10607 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010608 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010609
10610 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010611 sub = PyUnicode_FromObject(element);
10612 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010613 PyErr_Format(PyExc_TypeError,
10614 "'in <string>' requires string as left operand, not %s",
10615 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010616 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010617 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010618 if (PyUnicode_READY(sub) == -1)
10619 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010620
Thomas Wouters477c8d52006-05-27 19:21:47 +000010621 str = PyUnicode_FromObject(container);
Victor Stinnere9a29352011-10-01 02:14:59 +020010622 if (!str || PyUnicode_READY(str) == -1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010623 Py_DECREF(sub);
10624 return -1;
10625 }
10626
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010627 kind1 = PyUnicode_KIND(str);
10628 kind2 = PyUnicode_KIND(sub);
10629 kind = kind1 > kind2 ? kind1 : kind2;
10630 buf1 = PyUnicode_DATA(str);
10631 buf2 = PyUnicode_DATA(sub);
10632 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010633 buf1 = _PyUnicode_AsKind(str, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010634 if (!buf1) {
10635 Py_DECREF(sub);
10636 return -1;
10637 }
10638 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010639 buf2 = _PyUnicode_AsKind(sub, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010640 if (!buf2) {
10641 Py_DECREF(sub);
10642 if (kind1 != kind) PyMem_Free(buf1);
10643 return -1;
10644 }
10645 len1 = PyUnicode_GET_LENGTH(str);
10646 len2 = PyUnicode_GET_LENGTH(sub);
10647
10648 switch(kind) {
10649 case PyUnicode_1BYTE_KIND:
10650 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10651 break;
10652 case PyUnicode_2BYTE_KIND:
10653 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
10654 break;
10655 case PyUnicode_4BYTE_KIND:
10656 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
10657 break;
10658 default:
10659 result = -1;
10660 assert(0);
10661 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010662
10663 Py_DECREF(str);
10664 Py_DECREF(sub);
10665
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010666 if (kind1 != kind)
10667 PyMem_Free(buf1);
10668 if (kind2 != kind)
10669 PyMem_Free(buf2);
10670
Guido van Rossum403d68b2000-03-13 15:55:09 +000010671 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010672}
10673
Guido van Rossumd57fd912000-03-10 22:53:23 +000010674/* Concat to string or Unicode object giving a new Unicode object. */
10675
Alexander Belopolsky40018472011-02-26 01:02:56 +000010676PyObject *
10677PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010678{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010679 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020010680 Py_UCS4 maxchar, maxchar2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010681
10682 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010683 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010684 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010685 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010686 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010687 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010688 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010689
10690 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020010691 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010692 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010693 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010694 }
Victor Stinnera464fc12011-10-02 20:39:30 +020010695 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010696 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010697 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010698 }
10699
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010700 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020010701 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
10702 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010703
Guido van Rossumd57fd912000-03-10 22:53:23 +000010704 /* Concat the two Unicode strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010705 w = PyUnicode_New(
10706 PyUnicode_GET_LENGTH(u) + PyUnicode_GET_LENGTH(v),
10707 maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010708 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010709 goto onError;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010710 copy_characters(w, 0, u, 0, PyUnicode_GET_LENGTH(u));
10711 copy_characters(w, PyUnicode_GET_LENGTH(u), v, 0, PyUnicode_GET_LENGTH(v));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010712 Py_DECREF(u);
10713 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010714 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010715 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010716
Benjamin Peterson29060642009-01-31 22:14:21 +000010717 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010718 Py_XDECREF(u);
10719 Py_XDECREF(v);
10720 return NULL;
10721}
10722
Victor Stinnerb0923652011-10-04 01:17:31 +020010723static void
10724unicode_append_inplace(PyObject **p_left, PyObject *right)
10725{
10726 Py_ssize_t left_len, right_len, new_len;
Victor Stinnerb0923652011-10-04 01:17:31 +020010727
10728 assert(PyUnicode_IS_READY(*p_left));
10729 assert(PyUnicode_IS_READY(right));
10730
10731 left_len = PyUnicode_GET_LENGTH(*p_left);
10732 right_len = PyUnicode_GET_LENGTH(right);
10733 if (left_len > PY_SSIZE_T_MAX - right_len) {
10734 PyErr_SetString(PyExc_OverflowError,
10735 "strings are too large to concat");
10736 goto error;
10737 }
10738 new_len = left_len + right_len;
10739
10740 /* Now we own the last reference to 'left', so we can resize it
10741 * in-place.
10742 */
10743 if (unicode_resize(p_left, new_len) != 0) {
10744 /* XXX if _PyUnicode_Resize() fails, 'left' has been
10745 * deallocated so it cannot be put back into
10746 * 'variable'. The MemoryError is raised when there
10747 * is no value in 'variable', which might (very
10748 * remotely) be a cause of incompatibilities.
10749 */
10750 goto error;
10751 }
10752 /* copy 'right' into the newly allocated area of 'left' */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010753 copy_characters(*p_left, left_len, right, 0, right_len);
10754 _PyUnicode_DIRTY(*p_left);
Victor Stinnerb0923652011-10-04 01:17:31 +020010755 return;
10756
10757error:
10758 Py_DECREF(*p_left);
10759 *p_left = NULL;
10760}
10761
Walter Dörwald1ab83302007-05-18 17:15:44 +000010762void
Victor Stinner23e56682011-10-03 03:54:37 +020010763PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000010764{
Victor Stinner23e56682011-10-03 03:54:37 +020010765 PyObject *left, *res;
10766
10767 if (p_left == NULL) {
10768 if (!PyErr_Occurred())
10769 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000010770 return;
10771 }
Victor Stinner23e56682011-10-03 03:54:37 +020010772 left = *p_left;
10773 if (right == NULL || !PyUnicode_Check(left)) {
10774 if (!PyErr_Occurred())
10775 PyErr_BadInternalCall();
10776 goto error;
10777 }
10778
Victor Stinnere1335c72011-10-04 20:53:03 +020010779 if (PyUnicode_READY(left))
10780 goto error;
10781 if (PyUnicode_READY(right))
10782 goto error;
10783
Victor Stinner23e56682011-10-03 03:54:37 +020010784 if (PyUnicode_CheckExact(left) && left != unicode_empty
10785 && PyUnicode_CheckExact(right) && right != unicode_empty
10786 && unicode_resizable(left)
10787 && (_PyUnicode_KIND(right) <= _PyUnicode_KIND(left)
10788 || _PyUnicode_WSTR(left) != NULL))
10789 {
Victor Stinnerb0923652011-10-04 01:17:31 +020010790 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
10791 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020010792 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020010793 not so different than duplicating the string. */
10794 if (!(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
Victor Stinner23e56682011-10-03 03:54:37 +020010795 {
Victor Stinnerb0923652011-10-04 01:17:31 +020010796 unicode_append_inplace(p_left, right);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010797 if (p_left != NULL)
10798 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020010799 return;
10800 }
10801 }
10802
10803 res = PyUnicode_Concat(left, right);
10804 if (res == NULL)
10805 goto error;
10806 Py_DECREF(left);
10807 *p_left = res;
10808 return;
10809
10810error:
10811 Py_DECREF(*p_left);
10812 *p_left = NULL;
Walter Dörwald1ab83302007-05-18 17:15:44 +000010813}
10814
10815void
10816PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
10817{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010818 PyUnicode_Append(pleft, right);
10819 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010820}
10821
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010822PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010823 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010824\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000010825Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010826string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010827interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010828
10829static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010830unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010831{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010832 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010833 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010834 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010835 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010836 int kind1, kind2, kind;
10837 void *buf1, *buf2;
10838 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010839
Jesus Ceaac451502011-04-20 17:09:23 +020010840 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
10841 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000010842 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000010843
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010844 kind1 = PyUnicode_KIND(self);
10845 kind2 = PyUnicode_KIND(substring);
10846 kind = kind1 > kind2 ? kind1 : kind2;
10847 buf1 = PyUnicode_DATA(self);
10848 buf2 = PyUnicode_DATA(substring);
10849 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010850 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010851 if (!buf1) {
10852 Py_DECREF(substring);
10853 return NULL;
10854 }
10855 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010856 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010857 if (!buf2) {
10858 Py_DECREF(substring);
10859 if (kind1 != kind) PyMem_Free(buf1);
10860 return NULL;
10861 }
10862 len1 = PyUnicode_GET_LENGTH(self);
10863 len2 = PyUnicode_GET_LENGTH(substring);
10864
10865 ADJUST_INDICES(start, end, len1);
10866 switch(kind) {
10867 case PyUnicode_1BYTE_KIND:
10868 iresult = ucs1lib_count(
10869 ((Py_UCS1*)buf1) + start, end - start,
10870 buf2, len2, PY_SSIZE_T_MAX
10871 );
10872 break;
10873 case PyUnicode_2BYTE_KIND:
10874 iresult = ucs2lib_count(
10875 ((Py_UCS2*)buf1) + start, end - start,
10876 buf2, len2, PY_SSIZE_T_MAX
10877 );
10878 break;
10879 case PyUnicode_4BYTE_KIND:
10880 iresult = ucs4lib_count(
10881 ((Py_UCS4*)buf1) + start, end - start,
10882 buf2, len2, PY_SSIZE_T_MAX
10883 );
10884 break;
10885 default:
10886 assert(0); iresult = 0;
10887 }
10888
10889 result = PyLong_FromSsize_t(iresult);
10890
10891 if (kind1 != kind)
10892 PyMem_Free(buf1);
10893 if (kind2 != kind)
10894 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010895
10896 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010897
Guido van Rossumd57fd912000-03-10 22:53:23 +000010898 return result;
10899}
10900
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010901PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000010902 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010903\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000010904Encode S using the codec registered for encoding. Default encoding\n\
10905is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000010906handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000010907a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
10908'xmlcharrefreplace' as well as any other name registered with\n\
10909codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010910
10911static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010912unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010913{
Benjamin Peterson308d6372009-09-18 21:42:35 +000010914 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000010915 char *encoding = NULL;
10916 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000010917
Benjamin Peterson308d6372009-09-18 21:42:35 +000010918 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
10919 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010920 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010921 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000010922}
10923
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010924PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010925 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010926\n\
10927Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010928If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010929
10930static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010931unicode_expandtabs(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010932{
Antoine Pitroue71d5742011-10-04 15:55:09 +020010933 Py_ssize_t i, j, line_pos, src_len, incr;
10934 Py_UCS4 ch;
10935 PyObject *u;
10936 void *src_data, *dest_data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010937 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010938 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020010939 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010940
10941 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000010942 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010943
Antoine Pitrou22425222011-10-04 19:10:51 +020010944 if (PyUnicode_READY(self) == -1)
10945 return NULL;
10946
Thomas Wouters7e474022000-07-16 12:04:32 +000010947 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010948 src_len = PyUnicode_GET_LENGTH(self);
10949 i = j = line_pos = 0;
10950 kind = PyUnicode_KIND(self);
10951 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020010952 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010953 for (; i < src_len; i++) {
10954 ch = PyUnicode_READ(kind, src_data, i);
10955 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020010956 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000010957 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010958 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000010959 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010960 goto overflow;
10961 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000010962 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010963 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010964 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010965 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000010966 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010967 goto overflow;
10968 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010969 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010970 if (ch == '\n' || ch == '\r')
10971 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010972 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020010973 }
Antoine Pitroue19aa382011-10-04 16:04:01 +020010974 if (!found && PyUnicode_CheckExact(self)) {
Victor Stinner7931d9a2011-11-04 00:22:48 +010010975 Py_INCREF(self);
10976 return self;
Antoine Pitroue19aa382011-10-04 16:04:01 +020010977 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +000010978
Guido van Rossumd57fd912000-03-10 22:53:23 +000010979 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010980 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010981 if (!u)
10982 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010983 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010984
Antoine Pitroue71d5742011-10-04 15:55:09 +020010985 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010986
Antoine Pitroue71d5742011-10-04 15:55:09 +020010987 for (; i < src_len; i++) {
10988 ch = PyUnicode_READ(kind, src_data, i);
10989 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000010990 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010991 incr = tabsize - (line_pos % tabsize);
10992 line_pos += incr;
10993 while (incr--) {
10994 PyUnicode_WRITE(kind, dest_data, j, ' ');
10995 j++;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010996 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010997 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010998 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010999 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011000 line_pos++;
11001 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011002 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011003 if (ch == '\n' || ch == '\r')
11004 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011005 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011006 }
11007 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinner17efeed2011-10-04 20:05:46 +020011008#ifndef DONT_MAKE_RESULT_READY
11009 if (_PyUnicode_READY_REPLACE(&u)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011010 Py_DECREF(u);
11011 return NULL;
11012 }
Victor Stinner17efeed2011-10-04 20:05:46 +020011013#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011014 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010011015 return u;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011016
Antoine Pitroue71d5742011-10-04 15:55:09 +020011017 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011018 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11019 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011020}
11021
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011022PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011023 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011024\n\
11025Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011026such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011027arguments start and end are interpreted as in slice notation.\n\
11028\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011029Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011030
11031static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011032unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011033{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011034 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011035 Py_ssize_t start;
11036 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011037 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011038
Jesus Ceaac451502011-04-20 17:09:23 +020011039 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
11040 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011041 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011042
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011043 if (PyUnicode_READY(self) == -1)
11044 return NULL;
11045 if (PyUnicode_READY(substring) == -1)
11046 return NULL;
11047
Victor Stinner7931d9a2011-11-04 00:22:48 +010011048 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011049
11050 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011051
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011052 if (result == -2)
11053 return NULL;
11054
Christian Heimes217cfd12007-12-02 14:31:20 +000011055 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011056}
11057
11058static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011059unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011060{
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011061 Py_UCS4 ch = PyUnicode_ReadChar(self, index);
11062 if (ch == (Py_UCS4)-1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011063 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011064 return PyUnicode_FromOrdinal(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011065}
11066
Guido van Rossumc2504932007-09-18 19:42:40 +000011067/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011068 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011069static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011070unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011071{
Guido van Rossumc2504932007-09-18 19:42:40 +000011072 Py_ssize_t len;
Mark Dickinson57e683e2011-09-24 18:18:40 +010011073 Py_uhash_t x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011074
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011075 if (_PyUnicode_HASH(self) != -1)
11076 return _PyUnicode_HASH(self);
11077 if (PyUnicode_READY(self) == -1)
11078 return -1;
11079 len = PyUnicode_GET_LENGTH(self);
11080
11081 /* The hash function as a macro, gets expanded three times below. */
11082#define HASH(P) \
11083 x = (Py_uhash_t)*P << 7; \
11084 while (--len >= 0) \
11085 x = (1000003*x) ^ (Py_uhash_t)*P++;
11086
11087 switch (PyUnicode_KIND(self)) {
11088 case PyUnicode_1BYTE_KIND: {
11089 const unsigned char *c = PyUnicode_1BYTE_DATA(self);
11090 HASH(c);
11091 break;
11092 }
11093 case PyUnicode_2BYTE_KIND: {
11094 const Py_UCS2 *s = PyUnicode_2BYTE_DATA(self);
11095 HASH(s);
11096 break;
11097 }
11098 default: {
11099 Py_UCS4 *l;
11100 assert(PyUnicode_KIND(self) == PyUnicode_4BYTE_KIND &&
11101 "Impossible switch case in unicode_hash");
11102 l = PyUnicode_4BYTE_DATA(self);
11103 HASH(l);
11104 break;
11105 }
11106 }
11107 x ^= (Py_uhash_t)PyUnicode_GET_LENGTH(self);
11108
Guido van Rossumc2504932007-09-18 19:42:40 +000011109 if (x == -1)
11110 x = -2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011111 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011112 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011113}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011114#undef HASH
Guido van Rossumd57fd912000-03-10 22:53:23 +000011115
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011116PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011117 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011118\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011119Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011120
11121static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011122unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011123{
Martin v. Löwis18e16552006-02-15 17:27:45 +000011124 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011125 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011126 Py_ssize_t start;
11127 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011128
Jesus Ceaac451502011-04-20 17:09:23 +020011129 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
11130 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011131 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011132
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011133 if (PyUnicode_READY(self) == -1)
11134 return NULL;
11135 if (PyUnicode_READY(substring) == -1)
11136 return NULL;
11137
Victor Stinner7931d9a2011-11-04 00:22:48 +010011138 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011139
11140 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011141
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011142 if (result == -2)
11143 return NULL;
11144
Guido van Rossumd57fd912000-03-10 22:53:23 +000011145 if (result < 0) {
11146 PyErr_SetString(PyExc_ValueError, "substring not found");
11147 return NULL;
11148 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011149
Christian Heimes217cfd12007-12-02 14:31:20 +000011150 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011151}
11152
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011153PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011154 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011155\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011156Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011157at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011158
11159static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011160unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011161{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011162 Py_ssize_t i, length;
11163 int kind;
11164 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011165 int cased;
11166
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011167 if (PyUnicode_READY(self) == -1)
11168 return NULL;
11169 length = PyUnicode_GET_LENGTH(self);
11170 kind = PyUnicode_KIND(self);
11171 data = PyUnicode_DATA(self);
11172
Guido van Rossumd57fd912000-03-10 22:53:23 +000011173 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011174 if (length == 1)
11175 return PyBool_FromLong(
11176 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011177
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011178 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011179 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011180 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011181
Guido van Rossumd57fd912000-03-10 22:53:23 +000011182 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011183 for (i = 0; i < length; i++) {
11184 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011185
Benjamin Peterson29060642009-01-31 22:14:21 +000011186 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11187 return PyBool_FromLong(0);
11188 else if (!cased && Py_UNICODE_ISLOWER(ch))
11189 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011190 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011191 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011192}
11193
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011194PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011195 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011196\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011197Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011198at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011199
11200static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011201unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011202{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011203 Py_ssize_t i, length;
11204 int kind;
11205 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011206 int cased;
11207
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011208 if (PyUnicode_READY(self) == -1)
11209 return NULL;
11210 length = PyUnicode_GET_LENGTH(self);
11211 kind = PyUnicode_KIND(self);
11212 data = PyUnicode_DATA(self);
11213
Guido van Rossumd57fd912000-03-10 22:53:23 +000011214 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011215 if (length == 1)
11216 return PyBool_FromLong(
11217 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011218
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011219 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011220 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011221 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011222
Guido van Rossumd57fd912000-03-10 22:53:23 +000011223 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011224 for (i = 0; i < length; i++) {
11225 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011226
Benjamin Peterson29060642009-01-31 22:14:21 +000011227 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11228 return PyBool_FromLong(0);
11229 else if (!cased && Py_UNICODE_ISUPPER(ch))
11230 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011231 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011232 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011233}
11234
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011235PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011236 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011237\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011238Return True if S is a titlecased string and there is at least one\n\
11239character in S, i.e. upper- and titlecase characters may only\n\
11240follow uncased characters and lowercase characters only cased ones.\n\
11241Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011242
11243static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011244unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011245{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011246 Py_ssize_t i, length;
11247 int kind;
11248 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011249 int cased, previous_is_cased;
11250
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011251 if (PyUnicode_READY(self) == -1)
11252 return NULL;
11253 length = PyUnicode_GET_LENGTH(self);
11254 kind = PyUnicode_KIND(self);
11255 data = PyUnicode_DATA(self);
11256
Guido van Rossumd57fd912000-03-10 22:53:23 +000011257 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011258 if (length == 1) {
11259 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11260 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11261 (Py_UNICODE_ISUPPER(ch) != 0));
11262 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011263
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011264 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011265 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011266 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011267
Guido van Rossumd57fd912000-03-10 22:53:23 +000011268 cased = 0;
11269 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011270 for (i = 0; i < length; i++) {
11271 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011272
Benjamin Peterson29060642009-01-31 22:14:21 +000011273 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11274 if (previous_is_cased)
11275 return PyBool_FromLong(0);
11276 previous_is_cased = 1;
11277 cased = 1;
11278 }
11279 else if (Py_UNICODE_ISLOWER(ch)) {
11280 if (!previous_is_cased)
11281 return PyBool_FromLong(0);
11282 previous_is_cased = 1;
11283 cased = 1;
11284 }
11285 else
11286 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011287 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011288 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011289}
11290
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011291PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011292 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011293\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011294Return True if all characters in S are whitespace\n\
11295and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011296
11297static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011298unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011299{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011300 Py_ssize_t i, length;
11301 int kind;
11302 void *data;
11303
11304 if (PyUnicode_READY(self) == -1)
11305 return NULL;
11306 length = PyUnicode_GET_LENGTH(self);
11307 kind = PyUnicode_KIND(self);
11308 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011309
Guido van Rossumd57fd912000-03-10 22:53:23 +000011310 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011311 if (length == 1)
11312 return PyBool_FromLong(
11313 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011314
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011315 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011316 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011317 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011318
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011319 for (i = 0; i < length; i++) {
11320 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011321 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011322 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011323 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011324 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011325}
11326
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011327PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011328 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011329\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011330Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011331and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011332
11333static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011334unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011335{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011336 Py_ssize_t i, length;
11337 int kind;
11338 void *data;
11339
11340 if (PyUnicode_READY(self) == -1)
11341 return NULL;
11342 length = PyUnicode_GET_LENGTH(self);
11343 kind = PyUnicode_KIND(self);
11344 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011345
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011346 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011347 if (length == 1)
11348 return PyBool_FromLong(
11349 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011350
11351 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011352 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011353 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011354
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011355 for (i = 0; i < length; i++) {
11356 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011357 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011358 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011359 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011360}
11361
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011362PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011363 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011364\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011365Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011366and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011367
11368static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011369unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011370{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011371 int kind;
11372 void *data;
11373 Py_ssize_t len, i;
11374
11375 if (PyUnicode_READY(self) == -1)
11376 return NULL;
11377
11378 kind = PyUnicode_KIND(self);
11379 data = PyUnicode_DATA(self);
11380 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011381
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011382 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011383 if (len == 1) {
11384 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11385 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11386 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011387
11388 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011389 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011390 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011391
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011392 for (i = 0; i < len; i++) {
11393 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011394 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011395 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011396 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011397 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011398}
11399
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011400PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011401 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011402\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011403Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011404False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011405
11406static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011407unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011408{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011409 Py_ssize_t i, length;
11410 int kind;
11411 void *data;
11412
11413 if (PyUnicode_READY(self) == -1)
11414 return NULL;
11415 length = PyUnicode_GET_LENGTH(self);
11416 kind = PyUnicode_KIND(self);
11417 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011418
Guido van Rossumd57fd912000-03-10 22:53:23 +000011419 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011420 if (length == 1)
11421 return PyBool_FromLong(
11422 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011423
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011424 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011425 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011426 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011427
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011428 for (i = 0; i < length; i++) {
11429 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011430 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011431 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011432 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011433}
11434
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011435PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011436 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011437\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011438Return True if all characters in S are digits\n\
11439and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011440
11441static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011442unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011443{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011444 Py_ssize_t i, length;
11445 int kind;
11446 void *data;
11447
11448 if (PyUnicode_READY(self) == -1)
11449 return NULL;
11450 length = PyUnicode_GET_LENGTH(self);
11451 kind = PyUnicode_KIND(self);
11452 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011453
Guido van Rossumd57fd912000-03-10 22:53:23 +000011454 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011455 if (length == 1) {
11456 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11457 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11458 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011459
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011460 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011461 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011462 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011463
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011464 for (i = 0; i < length; i++) {
11465 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011466 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011467 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011468 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011469}
11470
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011471PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011472 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011473\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011474Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011475False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011476
11477static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011478unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011479{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011480 Py_ssize_t i, length;
11481 int kind;
11482 void *data;
11483
11484 if (PyUnicode_READY(self) == -1)
11485 return NULL;
11486 length = PyUnicode_GET_LENGTH(self);
11487 kind = PyUnicode_KIND(self);
11488 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011489
Guido van Rossumd57fd912000-03-10 22:53:23 +000011490 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011491 if (length == 1)
11492 return PyBool_FromLong(
11493 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011494
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011495 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011496 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011497 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011498
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011499 for (i = 0; i < length; i++) {
11500 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011501 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011502 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011503 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011504}
11505
Martin v. Löwis47383402007-08-15 07:32:56 +000011506int
11507PyUnicode_IsIdentifier(PyObject *self)
11508{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011509 int kind;
11510 void *data;
11511 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011512 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011513
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011514 if (PyUnicode_READY(self) == -1) {
11515 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011516 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011517 }
11518
11519 /* Special case for empty strings */
11520 if (PyUnicode_GET_LENGTH(self) == 0)
11521 return 0;
11522 kind = PyUnicode_KIND(self);
11523 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011524
11525 /* PEP 3131 says that the first character must be in
11526 XID_Start and subsequent characters in XID_Continue,
11527 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011528 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011529 letters, digits, underscore). However, given the current
11530 definition of XID_Start and XID_Continue, it is sufficient
11531 to check just for these, except that _ must be allowed
11532 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011533 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011534 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011535 return 0;
11536
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011537 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011538 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011539 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011540 return 1;
11541}
11542
11543PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011544 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011545\n\
11546Return True if S is a valid identifier according\n\
11547to the language definition.");
11548
11549static PyObject*
11550unicode_isidentifier(PyObject *self)
11551{
11552 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11553}
11554
Georg Brandl559e5d72008-06-11 18:37:52 +000011555PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011556 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011557\n\
11558Return True if all characters in S are considered\n\
11559printable in repr() or S is empty, False otherwise.");
11560
11561static PyObject*
11562unicode_isprintable(PyObject *self)
11563{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011564 Py_ssize_t i, length;
11565 int kind;
11566 void *data;
11567
11568 if (PyUnicode_READY(self) == -1)
11569 return NULL;
11570 length = PyUnicode_GET_LENGTH(self);
11571 kind = PyUnicode_KIND(self);
11572 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011573
11574 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011575 if (length == 1)
11576 return PyBool_FromLong(
11577 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011578
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011579 for (i = 0; i < length; i++) {
11580 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011581 Py_RETURN_FALSE;
11582 }
11583 }
11584 Py_RETURN_TRUE;
11585}
11586
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011587PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011588 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011589\n\
11590Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011591iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011592
11593static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011594unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011595{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011596 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011597}
11598
Martin v. Löwis18e16552006-02-15 17:27:45 +000011599static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011600unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011601{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011602 if (PyUnicode_READY(self) == -1)
11603 return -1;
11604 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011605}
11606
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011607PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011608 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011609\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011610Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011611done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011612
11613static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011614unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011615{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011616 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011617 Py_UCS4 fillchar = ' ';
11618
11619 if (PyUnicode_READY(self) == -1)
11620 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011621
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011622 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011623 return NULL;
11624
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011625 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000011626 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010011627 return self;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011628 }
11629
Victor Stinner7931d9a2011-11-04 00:22:48 +010011630 return pad(self, 0, width - _PyUnicode_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011631}
11632
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011633PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011634 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011635\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011636Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011637
11638static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011639unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011640{
Guido van Rossumd57fd912000-03-10 22:53:23 +000011641 return fixup(self, fixlower);
11642}
11643
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011644#define LEFTSTRIP 0
11645#define RIGHTSTRIP 1
11646#define BOTHSTRIP 2
11647
11648/* Arrays indexed by above */
11649static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11650
11651#define STRIPNAME(i) (stripformat[i]+3)
11652
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011653/* externally visible for str.strip(unicode) */
11654PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011655_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011656{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011657 void *data;
11658 int kind;
11659 Py_ssize_t i, j, len;
11660 BLOOM_MASK sepmask;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011661
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011662 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
11663 return NULL;
11664
11665 kind = PyUnicode_KIND(self);
11666 data = PyUnicode_DATA(self);
11667 len = PyUnicode_GET_LENGTH(self);
11668 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
11669 PyUnicode_DATA(sepobj),
11670 PyUnicode_GET_LENGTH(sepobj));
Thomas Wouters477c8d52006-05-27 19:21:47 +000011671
Benjamin Peterson14339b62009-01-31 16:36:08 +000011672 i = 0;
11673 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011674 while (i < len &&
11675 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, i), sepobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011676 i++;
11677 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011678 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011679
Benjamin Peterson14339b62009-01-31 16:36:08 +000011680 j = len;
11681 if (striptype != LEFTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011682 do {
11683 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011684 } while (j >= i &&
11685 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, j), sepobj));
Benjamin Peterson29060642009-01-31 22:14:21 +000011686 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011687 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011688
Victor Stinner7931d9a2011-11-04 00:22:48 +010011689 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011690}
11691
11692PyObject*
11693PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
11694{
11695 unsigned char *data;
11696 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020011697 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011698
Victor Stinnerde636f32011-10-01 03:55:54 +020011699 if (PyUnicode_READY(self) == -1)
11700 return NULL;
11701
11702 end = Py_MIN(end, PyUnicode_GET_LENGTH(self));
11703
Victor Stinner12bab6d2011-10-01 01:53:49 +020011704 if (start == 0 && end == PyUnicode_GET_LENGTH(self))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011705 {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011706 if (PyUnicode_CheckExact(self)) {
11707 Py_INCREF(self);
11708 return self;
11709 }
11710 else
11711 return PyUnicode_Copy(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011712 }
11713
Victor Stinner12bab6d2011-10-01 01:53:49 +020011714 length = end - start;
11715 if (length == 1)
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011716 return unicode_getitem(self, start);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011717
Victor Stinnerde636f32011-10-01 03:55:54 +020011718 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011719 PyErr_SetString(PyExc_IndexError, "string index out of range");
11720 return NULL;
11721 }
11722
Victor Stinnerb9275c12011-10-05 14:01:42 +020011723 if (PyUnicode_IS_ASCII(self)) {
11724 kind = PyUnicode_KIND(self);
11725 data = PyUnicode_1BYTE_DATA(self);
11726 return unicode_fromascii(data + start, length);
11727 }
11728 else {
11729 kind = PyUnicode_KIND(self);
11730 data = PyUnicode_1BYTE_DATA(self);
11731 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011732 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020011733 length);
11734 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011735}
Guido van Rossumd57fd912000-03-10 22:53:23 +000011736
11737static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011738do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011739{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011740 int kind;
11741 void *data;
11742 Py_ssize_t len, i, j;
11743
11744 if (PyUnicode_READY(self) == -1)
11745 return NULL;
11746
11747 kind = PyUnicode_KIND(self);
11748 data = PyUnicode_DATA(self);
11749 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011750
Benjamin Peterson14339b62009-01-31 16:36:08 +000011751 i = 0;
11752 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011753 while (i < len && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, i))) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000011754 i++;
11755 }
11756 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011757
Benjamin Peterson14339b62009-01-31 16:36:08 +000011758 j = len;
11759 if (striptype != LEFTSTRIP) {
11760 do {
11761 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011762 } while (j >= i && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, j)));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011763 j++;
11764 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011765
Victor Stinner7931d9a2011-11-04 00:22:48 +010011766 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011767}
11768
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011769
11770static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011771do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011772{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011773 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011774
Benjamin Peterson14339b62009-01-31 16:36:08 +000011775 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
11776 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011777
Benjamin Peterson14339b62009-01-31 16:36:08 +000011778 if (sep != NULL && sep != Py_None) {
11779 if (PyUnicode_Check(sep))
11780 return _PyUnicode_XStrip(self, striptype, sep);
11781 else {
11782 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000011783 "%s arg must be None or str",
11784 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011785 return NULL;
11786 }
11787 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011788
Benjamin Peterson14339b62009-01-31 16:36:08 +000011789 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011790}
11791
11792
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011793PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011794 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011795\n\
11796Return a copy of the string S with leading and trailing\n\
11797whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011798If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011799
11800static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011801unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011802{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011803 if (PyTuple_GET_SIZE(args) == 0)
11804 return do_strip(self, BOTHSTRIP); /* Common case */
11805 else
11806 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011807}
11808
11809
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011810PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011811 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011812\n\
11813Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011814If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011815
11816static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011817unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011818{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011819 if (PyTuple_GET_SIZE(args) == 0)
11820 return do_strip(self, LEFTSTRIP); /* Common case */
11821 else
11822 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011823}
11824
11825
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011826PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011827 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011828\n\
11829Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011830If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011831
11832static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011833unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011834{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011835 if (PyTuple_GET_SIZE(args) == 0)
11836 return do_strip(self, RIGHTSTRIP); /* Common case */
11837 else
11838 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011839}
11840
11841
Guido van Rossumd57fd912000-03-10 22:53:23 +000011842static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011843unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011844{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011845 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011846 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011847
Georg Brandl222de0f2009-04-12 12:01:50 +000011848 if (len < 1) {
11849 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +020011850 return unicode_empty;
Georg Brandl222de0f2009-04-12 12:01:50 +000011851 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011852
Tim Peters7a29bd52001-09-12 03:03:31 +000011853 if (len == 1 && PyUnicode_CheckExact(str)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000011854 /* no repeat, return original string */
11855 Py_INCREF(str);
Victor Stinner7931d9a2011-11-04 00:22:48 +010011856 return str;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011857 }
Tim Peters8f422462000-09-09 06:13:41 +000011858
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011859 if (PyUnicode_READY(str) == -1)
11860 return NULL;
11861
Victor Stinnerc759f3e2011-10-01 03:09:58 +020011862 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020011863 PyErr_SetString(PyExc_OverflowError,
11864 "repeated string is too long");
11865 return NULL;
11866 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011867 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011868
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011869 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011870 if (!u)
11871 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011872 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011873
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011874 if (PyUnicode_GET_LENGTH(str) == 1) {
11875 const int kind = PyUnicode_KIND(str);
11876 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
11877 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011878 if (kind == PyUnicode_1BYTE_KIND)
11879 memset(to, (unsigned char)fill_char, len);
11880 else {
11881 for (n = 0; n < len; ++n)
11882 PyUnicode_WRITE(kind, to, n, fill_char);
11883 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011884 }
11885 else {
11886 /* number of characters copied this far */
11887 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011888 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011889 char *to = (char *) PyUnicode_DATA(u);
11890 Py_MEMCPY(to, PyUnicode_DATA(str),
11891 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000011892 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011893 n = (done <= nchars-done) ? done : nchars-done;
11894 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011895 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000011896 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011897 }
11898
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011899 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011900 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011901}
11902
Alexander Belopolsky40018472011-02-26 01:02:56 +000011903PyObject *
11904PyUnicode_Replace(PyObject *obj,
11905 PyObject *subobj,
11906 PyObject *replobj,
11907 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011908{
11909 PyObject *self;
11910 PyObject *str1;
11911 PyObject *str2;
11912 PyObject *result;
11913
11914 self = PyUnicode_FromObject(obj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011915 if (self == NULL || PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011916 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011917 str1 = PyUnicode_FromObject(subobj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011918 if (str1 == NULL || PyUnicode_READY(str1) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011919 Py_DECREF(self);
11920 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011921 }
11922 str2 = PyUnicode_FromObject(replobj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011923 if (str2 == NULL || PyUnicode_READY(str2)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011924 Py_DECREF(self);
11925 Py_DECREF(str1);
11926 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011927 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011928 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011929 Py_DECREF(self);
11930 Py_DECREF(str1);
11931 Py_DECREF(str2);
11932 return result;
11933}
11934
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011935PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000011936 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011937\n\
11938Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000011939old replaced by new. If the optional argument count is\n\
11940given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011941
11942static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011943unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011944{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011945 PyObject *str1;
11946 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011947 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011948 PyObject *result;
11949
Martin v. Löwis18e16552006-02-15 17:27:45 +000011950 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011951 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011952 if (!PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011953 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011954 str1 = PyUnicode_FromObject(str1);
11955 if (str1 == NULL || PyUnicode_READY(str1) == -1)
11956 return NULL;
11957 str2 = PyUnicode_FromObject(str2);
Victor Stinnere9a29352011-10-01 02:14:59 +020011958 if (str2 == NULL || PyUnicode_READY(str2) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011959 Py_DECREF(str1);
11960 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000011961 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011962
11963 result = replace(self, str1, str2, maxcount);
11964
11965 Py_DECREF(str1);
11966 Py_DECREF(str2);
11967 return result;
11968}
11969
Alexander Belopolsky40018472011-02-26 01:02:56 +000011970static PyObject *
11971unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011972{
Walter Dörwald79e913e2007-05-12 11:08:06 +000011973 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011974 Py_ssize_t isize;
11975 Py_ssize_t osize, squote, dquote, i, o;
11976 Py_UCS4 max, quote;
11977 int ikind, okind;
11978 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000011979
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011980 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000011981 return NULL;
11982
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011983 isize = PyUnicode_GET_LENGTH(unicode);
11984 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011985
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011986 /* Compute length of output, quote characters, and
11987 maximum character */
11988 osize = 2; /* quotes */
11989 max = 127;
11990 squote = dquote = 0;
11991 ikind = PyUnicode_KIND(unicode);
11992 for (i = 0; i < isize; i++) {
11993 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
11994 switch (ch) {
11995 case '\'': squote++; osize++; break;
11996 case '"': dquote++; osize++; break;
11997 case '\\': case '\t': case '\r': case '\n':
11998 osize += 2; break;
11999 default:
12000 /* Fast-path ASCII */
12001 if (ch < ' ' || ch == 0x7f)
12002 osize += 4; /* \xHH */
12003 else if (ch < 0x7f)
12004 osize++;
12005 else if (Py_UNICODE_ISPRINTABLE(ch)) {
12006 osize++;
12007 max = ch > max ? ch : max;
12008 }
12009 else if (ch < 0x100)
12010 osize += 4; /* \xHH */
12011 else if (ch < 0x10000)
12012 osize += 6; /* \uHHHH */
12013 else
12014 osize += 10; /* \uHHHHHHHH */
12015 }
12016 }
12017
12018 quote = '\'';
12019 if (squote) {
12020 if (dquote)
12021 /* Both squote and dquote present. Use squote,
12022 and escape them */
12023 osize += squote;
12024 else
12025 quote = '"';
12026 }
12027
12028 repr = PyUnicode_New(osize, max);
12029 if (repr == NULL)
12030 return NULL;
12031 okind = PyUnicode_KIND(repr);
12032 odata = PyUnicode_DATA(repr);
12033
12034 PyUnicode_WRITE(okind, odata, 0, quote);
12035 PyUnicode_WRITE(okind, odata, osize-1, quote);
12036
12037 for (i = 0, o = 1; i < isize; i++) {
12038 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012039
12040 /* Escape quotes and backslashes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012041 if ((ch == quote) || (ch == '\\')) {
12042 PyUnicode_WRITE(okind, odata, o++, '\\');
12043 PyUnicode_WRITE(okind, odata, o++, ch);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012044 continue;
12045 }
12046
Benjamin Peterson29060642009-01-31 22:14:21 +000012047 /* Map special whitespace to '\t', \n', '\r' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012048 if (ch == '\t') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012049 PyUnicode_WRITE(okind, odata, o++, '\\');
12050 PyUnicode_WRITE(okind, odata, o++, 't');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012051 }
12052 else if (ch == '\n') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012053 PyUnicode_WRITE(okind, odata, o++, '\\');
12054 PyUnicode_WRITE(okind, odata, o++, 'n');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012055 }
12056 else if (ch == '\r') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012057 PyUnicode_WRITE(okind, odata, o++, '\\');
12058 PyUnicode_WRITE(okind, odata, o++, 'r');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012059 }
12060
12061 /* Map non-printable US ASCII to '\xhh' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012062 else if (ch < ' ' || ch == 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012063 PyUnicode_WRITE(okind, odata, o++, '\\');
12064 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012065 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12066 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012067 }
12068
Georg Brandl559e5d72008-06-11 18:37:52 +000012069 /* Copy ASCII characters as-is */
12070 else if (ch < 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012071 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012072 }
12073
Benjamin Peterson29060642009-01-31 22:14:21 +000012074 /* Non-ASCII characters */
Georg Brandl559e5d72008-06-11 18:37:52 +000012075 else {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012076 /* Map Unicode whitespace and control characters
Georg Brandl559e5d72008-06-11 18:37:52 +000012077 (categories Z* and C* except ASCII space)
12078 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012079 if (!Py_UNICODE_ISPRINTABLE(ch)) {
Georg Brandl559e5d72008-06-11 18:37:52 +000012080 /* Map 8-bit characters to '\xhh' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012081 if (ch <= 0xff) {
12082 PyUnicode_WRITE(okind, odata, o++, '\\');
12083 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012084 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12085 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012086 }
12087 /* Map 21-bit characters to '\U00xxxxxx' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012088 else if (ch >= 0x10000) {
12089 PyUnicode_WRITE(okind, odata, o++, '\\');
12090 PyUnicode_WRITE(okind, odata, o++, 'U');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012091 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12092 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12093 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12094 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12095 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12096 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12097 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12098 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012099 }
12100 /* Map 16-bit characters to '\uxxxx' */
12101 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012102 PyUnicode_WRITE(okind, odata, o++, '\\');
12103 PyUnicode_WRITE(okind, odata, o++, 'u');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012104 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12105 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12106 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12107 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012108 }
12109 }
12110 /* Copy characters as-is */
12111 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012112 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012113 }
12114 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012115 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012116 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012117 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012118 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012119}
12120
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012121PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012122 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012123\n\
12124Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012125such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012126arguments start and end are interpreted as in slice notation.\n\
12127\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012128Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012129
12130static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012131unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012132{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012133 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012134 Py_ssize_t start;
12135 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012136 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012137
Jesus Ceaac451502011-04-20 17:09:23 +020012138 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
12139 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012140 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012141
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012142 if (PyUnicode_READY(self) == -1)
12143 return NULL;
12144 if (PyUnicode_READY(substring) == -1)
12145 return NULL;
12146
Victor Stinner7931d9a2011-11-04 00:22:48 +010012147 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012148
12149 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012150
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012151 if (result == -2)
12152 return NULL;
12153
Christian Heimes217cfd12007-12-02 14:31:20 +000012154 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012155}
12156
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012157PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012158 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012159\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012160Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012161
12162static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012163unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012164{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012165 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012166 Py_ssize_t start;
12167 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012168 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012169
Jesus Ceaac451502011-04-20 17:09:23 +020012170 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12171 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012172 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012173
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012174 if (PyUnicode_READY(self) == -1)
12175 return NULL;
12176 if (PyUnicode_READY(substring) == -1)
12177 return NULL;
12178
Victor Stinner7931d9a2011-11-04 00:22:48 +010012179 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012180
12181 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012182
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012183 if (result == -2)
12184 return NULL;
12185
Guido van Rossumd57fd912000-03-10 22:53:23 +000012186 if (result < 0) {
12187 PyErr_SetString(PyExc_ValueError, "substring not found");
12188 return NULL;
12189 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012190
Christian Heimes217cfd12007-12-02 14:31:20 +000012191 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012192}
12193
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012194PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012195 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012196\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012197Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012198done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012199
12200static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012201unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012202{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012203 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012204 Py_UCS4 fillchar = ' ';
12205
Victor Stinnere9a29352011-10-01 02:14:59 +020012206 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012207 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012208
Victor Stinnere9a29352011-10-01 02:14:59 +020012209 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012210 return NULL;
12211
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012212 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012213 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010012214 return self;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012215 }
12216
Victor Stinner7931d9a2011-11-04 00:22:48 +010012217 return pad(self, width - _PyUnicode_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012218}
12219
Alexander Belopolsky40018472011-02-26 01:02:56 +000012220PyObject *
12221PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012222{
12223 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012224
Guido van Rossumd57fd912000-03-10 22:53:23 +000012225 s = PyUnicode_FromObject(s);
12226 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012227 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012228 if (sep != NULL) {
12229 sep = PyUnicode_FromObject(sep);
12230 if (sep == NULL) {
12231 Py_DECREF(s);
12232 return NULL;
12233 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012234 }
12235
Victor Stinner9310abb2011-10-05 00:59:23 +020012236 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012237
12238 Py_DECREF(s);
12239 Py_XDECREF(sep);
12240 return result;
12241}
12242
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012243PyDoc_STRVAR(split__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012244 "S.split([sep[, maxsplit]]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012245\n\
12246Return a list of the words in S, using sep as the\n\
12247delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012248splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012249whitespace string is a separator and empty strings are\n\
12250removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012251
12252static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012253unicode_split(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012254{
12255 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012256 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012257
Martin v. Löwis18e16552006-02-15 17:27:45 +000012258 if (!PyArg_ParseTuple(args, "|On:split", &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012259 return NULL;
12260
12261 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012262 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012263 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012264 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012265 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012266 return PyUnicode_Split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012267}
12268
Thomas Wouters477c8d52006-05-27 19:21:47 +000012269PyObject *
12270PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12271{
12272 PyObject* str_obj;
12273 PyObject* sep_obj;
12274 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012275 int kind1, kind2, kind;
12276 void *buf1 = NULL, *buf2 = NULL;
12277 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012278
12279 str_obj = PyUnicode_FromObject(str_in);
Victor Stinnere9a29352011-10-01 02:14:59 +020012280 if (!str_obj || PyUnicode_READY(str_obj) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012281 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012282 sep_obj = PyUnicode_FromObject(sep_in);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012283 if (!sep_obj || PyUnicode_READY(sep_obj) == -1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000012284 Py_DECREF(str_obj);
12285 return NULL;
12286 }
12287
Victor Stinner14f8f022011-10-05 20:58:25 +020012288 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012289 kind2 = PyUnicode_KIND(sep_obj);
Victor Stinner14f8f022011-10-05 20:58:25 +020012290 kind = Py_MAX(kind1, kind2);
12291 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012292 if (kind1 != kind)
Victor Stinner14f8f022011-10-05 20:58:25 +020012293 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012294 if (!buf1)
12295 goto onError;
12296 buf2 = PyUnicode_DATA(sep_obj);
12297 if (kind2 != kind)
12298 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12299 if (!buf2)
12300 goto onError;
12301 len1 = PyUnicode_GET_LENGTH(str_obj);
12302 len2 = PyUnicode_GET_LENGTH(sep_obj);
12303
Victor Stinner14f8f022011-10-05 20:58:25 +020012304 switch(PyUnicode_KIND(str_obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012305 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012306 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12307 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12308 else
12309 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012310 break;
12311 case PyUnicode_2BYTE_KIND:
12312 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12313 break;
12314 case PyUnicode_4BYTE_KIND:
12315 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12316 break;
12317 default:
12318 assert(0);
12319 out = 0;
12320 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012321
12322 Py_DECREF(sep_obj);
12323 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012324 if (kind1 != kind)
12325 PyMem_Free(buf1);
12326 if (kind2 != kind)
12327 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012328
12329 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012330 onError:
12331 Py_DECREF(sep_obj);
12332 Py_DECREF(str_obj);
12333 if (kind1 != kind && buf1)
12334 PyMem_Free(buf1);
12335 if (kind2 != kind && buf2)
12336 PyMem_Free(buf2);
12337 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012338}
12339
12340
12341PyObject *
12342PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12343{
12344 PyObject* str_obj;
12345 PyObject* sep_obj;
12346 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012347 int kind1, kind2, kind;
12348 void *buf1 = NULL, *buf2 = NULL;
12349 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012350
12351 str_obj = PyUnicode_FromObject(str_in);
12352 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012353 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012354 sep_obj = PyUnicode_FromObject(sep_in);
12355 if (!sep_obj) {
12356 Py_DECREF(str_obj);
12357 return NULL;
12358 }
12359
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012360 kind1 = PyUnicode_KIND(str_in);
12361 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020012362 kind = Py_MAX(kind1, kind2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012363 buf1 = PyUnicode_DATA(str_in);
12364 if (kind1 != kind)
12365 buf1 = _PyUnicode_AsKind(str_in, kind);
12366 if (!buf1)
12367 goto onError;
12368 buf2 = PyUnicode_DATA(sep_obj);
12369 if (kind2 != kind)
12370 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12371 if (!buf2)
12372 goto onError;
12373 len1 = PyUnicode_GET_LENGTH(str_obj);
12374 len2 = PyUnicode_GET_LENGTH(sep_obj);
12375
12376 switch(PyUnicode_KIND(str_in)) {
12377 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012378 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12379 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12380 else
12381 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012382 break;
12383 case PyUnicode_2BYTE_KIND:
12384 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12385 break;
12386 case PyUnicode_4BYTE_KIND:
12387 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12388 break;
12389 default:
12390 assert(0);
12391 out = 0;
12392 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012393
12394 Py_DECREF(sep_obj);
12395 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012396 if (kind1 != kind)
12397 PyMem_Free(buf1);
12398 if (kind2 != kind)
12399 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012400
12401 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012402 onError:
12403 Py_DECREF(sep_obj);
12404 Py_DECREF(str_obj);
12405 if (kind1 != kind && buf1)
12406 PyMem_Free(buf1);
12407 if (kind2 != kind && buf2)
12408 PyMem_Free(buf2);
12409 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012410}
12411
12412PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012413 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012414\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012415Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012416the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012417found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012418
12419static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012420unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012421{
Victor Stinner9310abb2011-10-05 00:59:23 +020012422 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012423}
12424
12425PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012426 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012427\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012428Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012429the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012430separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012431
12432static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012433unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012434{
Victor Stinner9310abb2011-10-05 00:59:23 +020012435 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012436}
12437
Alexander Belopolsky40018472011-02-26 01:02:56 +000012438PyObject *
12439PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012440{
12441 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012442
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012443 s = PyUnicode_FromObject(s);
12444 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012445 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012446 if (sep != NULL) {
12447 sep = PyUnicode_FromObject(sep);
12448 if (sep == NULL) {
12449 Py_DECREF(s);
12450 return NULL;
12451 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012452 }
12453
Victor Stinner9310abb2011-10-05 00:59:23 +020012454 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012455
12456 Py_DECREF(s);
12457 Py_XDECREF(sep);
12458 return result;
12459}
12460
12461PyDoc_STRVAR(rsplit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012462 "S.rsplit([sep[, maxsplit]]) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012463\n\
12464Return a list of the words in S, using sep as the\n\
12465delimiter string, starting at the end of the string and\n\
12466working to the front. If maxsplit is given, at most maxsplit\n\
12467splits are done. If sep is not specified, any whitespace string\n\
12468is a separator.");
12469
12470static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012471unicode_rsplit(PyObject *self, PyObject *args)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012472{
12473 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012474 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012475
Martin v. Löwis18e16552006-02-15 17:27:45 +000012476 if (!PyArg_ParseTuple(args, "|On:rsplit", &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012477 return NULL;
12478
12479 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012480 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012481 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012482 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012483 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012484 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012485}
12486
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012487PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012488 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012489\n\
12490Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012491Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012492is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012493
12494static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012495unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012496{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012497 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012498 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012499
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012500 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12501 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012502 return NULL;
12503
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012504 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012505}
12506
12507static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012508PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012509{
Walter Dörwald346737f2007-05-31 10:44:43 +000012510 if (PyUnicode_CheckExact(self)) {
12511 Py_INCREF(self);
12512 return self;
12513 } else
12514 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinner034f6cf2011-09-30 02:26:44 +020012515 return PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012516}
12517
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012518PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012519 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012520\n\
12521Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012522and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012523
12524static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012525unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012526{
Guido van Rossumd57fd912000-03-10 22:53:23 +000012527 return fixup(self, fixswapcase);
12528}
12529
Georg Brandlceee0772007-11-27 23:48:05 +000012530PyDoc_STRVAR(maketrans__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012531 "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012532\n\
12533Return a translation table usable for str.translate().\n\
12534If there is only one argument, it must be a dictionary mapping Unicode\n\
12535ordinals (integers) or characters to Unicode ordinals, strings or None.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012536Character keys will be then converted to ordinals.\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012537If there are two arguments, they must be strings of equal length, and\n\
12538in the resulting dictionary, each character in x will be mapped to the\n\
12539character at the same position in y. If there is a third argument, it\n\
12540must be a string, whose characters will be mapped to None in the result.");
12541
12542static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012543unicode_maketrans(PyObject *null, PyObject *args)
Georg Brandlceee0772007-11-27 23:48:05 +000012544{
12545 PyObject *x, *y = NULL, *z = NULL;
12546 PyObject *new = NULL, *key, *value;
12547 Py_ssize_t i = 0;
12548 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012549
Georg Brandlceee0772007-11-27 23:48:05 +000012550 if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
12551 return NULL;
12552 new = PyDict_New();
12553 if (!new)
12554 return NULL;
12555 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012556 int x_kind, y_kind, z_kind;
12557 void *x_data, *y_data, *z_data;
12558
Georg Brandlceee0772007-11-27 23:48:05 +000012559 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012560 if (!PyUnicode_Check(x)) {
12561 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12562 "be a string if there is a second argument");
12563 goto err;
12564 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012565 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012566 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12567 "arguments must have equal length");
12568 goto err;
12569 }
12570 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012571 x_kind = PyUnicode_KIND(x);
12572 y_kind = PyUnicode_KIND(y);
12573 x_data = PyUnicode_DATA(x);
12574 y_data = PyUnicode_DATA(y);
12575 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
12576 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
12577 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012578 if (!key || !value)
12579 goto err;
12580 res = PyDict_SetItem(new, key, value);
12581 Py_DECREF(key);
12582 Py_DECREF(value);
12583 if (res < 0)
12584 goto err;
12585 }
12586 /* create entries for deleting chars in z */
12587 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012588 z_kind = PyUnicode_KIND(z);
12589 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012590 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012591 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012592 if (!key)
12593 goto err;
12594 res = PyDict_SetItem(new, key, Py_None);
12595 Py_DECREF(key);
12596 if (res < 0)
12597 goto err;
12598 }
12599 }
12600 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012601 int kind;
12602 void *data;
12603
Georg Brandlceee0772007-11-27 23:48:05 +000012604 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000012605 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012606 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
12607 "to maketrans it must be a dict");
12608 goto err;
12609 }
12610 /* copy entries into the new dict, converting string keys to int keys */
12611 while (PyDict_Next(x, &i, &key, &value)) {
12612 if (PyUnicode_Check(key)) {
12613 /* convert string keys to integer keys */
12614 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012615 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000012616 PyErr_SetString(PyExc_ValueError, "string keys in translate "
12617 "table must be of length 1");
12618 goto err;
12619 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012620 kind = PyUnicode_KIND(key);
12621 data = PyUnicode_DATA(key);
12622 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000012623 if (!newkey)
12624 goto err;
12625 res = PyDict_SetItem(new, newkey, value);
12626 Py_DECREF(newkey);
12627 if (res < 0)
12628 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000012629 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012630 /* just keep integer keys */
12631 if (PyDict_SetItem(new, key, value) < 0)
12632 goto err;
12633 } else {
12634 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
12635 "be strings or integers");
12636 goto err;
12637 }
12638 }
12639 }
12640 return new;
12641 err:
12642 Py_DECREF(new);
12643 return NULL;
12644}
12645
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012646PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012647 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012648\n\
12649Return a copy of the string S, where all characters have been mapped\n\
12650through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012651Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000012652Unmapped characters are left untouched. Characters mapped to None\n\
12653are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012654
12655static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012656unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012657{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012658 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012659}
12660
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012661PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012662 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012663\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012664Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012665
12666static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012667unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012668{
Guido van Rossumd57fd912000-03-10 22:53:23 +000012669 return fixup(self, fixupper);
12670}
12671
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012672PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012673 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012674\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000012675Pad a numeric string S with zeros on the left, to fill a field\n\
12676of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012677
12678static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012679unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012680{
Martin v. Löwis18e16552006-02-15 17:27:45 +000012681 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020012682 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012683 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012684 int kind;
12685 void *data;
12686 Py_UCS4 chr;
12687
12688 if (PyUnicode_READY(self) == -1)
12689 return NULL;
12690
Martin v. Löwis18e16552006-02-15 17:27:45 +000012691 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012692 return NULL;
12693
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012694 if (PyUnicode_GET_LENGTH(self) >= width) {
Walter Dörwald0fe940c2002-04-15 18:42:15 +000012695 if (PyUnicode_CheckExact(self)) {
12696 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010012697 return self;
Walter Dörwald0fe940c2002-04-15 18:42:15 +000012698 }
12699 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012700 return PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012701 }
12702
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012703 fill = width - _PyUnicode_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012704
12705 u = pad(self, fill, 0, '0');
12706
Walter Dörwald068325e2002-04-15 13:36:47 +000012707 if (u == NULL)
12708 return NULL;
12709
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012710 kind = PyUnicode_KIND(u);
12711 data = PyUnicode_DATA(u);
12712 chr = PyUnicode_READ(kind, data, fill);
12713
12714 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012715 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012716 PyUnicode_WRITE(kind, data, 0, chr);
12717 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000012718 }
12719
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012720 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010012721 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012722}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012723
12724#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012725static PyObject *
12726unicode__decimal2ascii(PyObject *self)
12727{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012728 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012729}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012730#endif
12731
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012732PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012733 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012734\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012735Return True if S starts with the specified prefix, False otherwise.\n\
12736With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012737With optional end, stop comparing S at that position.\n\
12738prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012739
12740static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012741unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012742 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012743{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012744 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012745 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012746 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012747 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012748 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012749
Jesus Ceaac451502011-04-20 17:09:23 +020012750 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012751 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012752 if (PyTuple_Check(subobj)) {
12753 Py_ssize_t i;
12754 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012755 substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012756 if (substring == NULL)
12757 return NULL;
12758 result = tailmatch(self, substring, start, end, -1);
12759 Py_DECREF(substring);
12760 if (result) {
12761 Py_RETURN_TRUE;
12762 }
12763 }
12764 /* nothing matched */
12765 Py_RETURN_FALSE;
12766 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012767 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012768 if (substring == NULL) {
12769 if (PyErr_ExceptionMatches(PyExc_TypeError))
12770 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
12771 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012772 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012773 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012774 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012775 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012776 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012777}
12778
12779
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012780PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012781 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012782\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012783Return True if S ends with the specified suffix, False otherwise.\n\
12784With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012785With optional end, stop comparing S at that position.\n\
12786suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012787
12788static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012789unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012790 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012791{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012792 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012793 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012794 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012795 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012796 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012797
Jesus Ceaac451502011-04-20 17:09:23 +020012798 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012799 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012800 if (PyTuple_Check(subobj)) {
12801 Py_ssize_t i;
12802 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012803 substring = PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000012804 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012805 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012806 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012807 result = tailmatch(self, substring, start, end, +1);
12808 Py_DECREF(substring);
12809 if (result) {
12810 Py_RETURN_TRUE;
12811 }
12812 }
12813 Py_RETURN_FALSE;
12814 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012815 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012816 if (substring == NULL) {
12817 if (PyErr_ExceptionMatches(PyExc_TypeError))
12818 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
12819 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012820 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012821 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012822 result = tailmatch(self, substring, start, end, +1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012823 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012824 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012825}
12826
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012827#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000012828
12829PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012830 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012831\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012832Return a formatted version of S, using substitutions from args and kwargs.\n\
12833The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000012834
Eric Smith27bbca62010-11-04 17:06:58 +000012835PyDoc_STRVAR(format_map__doc__,
12836 "S.format_map(mapping) -> str\n\
12837\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012838Return a formatted version of S, using substitutions from mapping.\n\
12839The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000012840
Eric Smith4a7d76d2008-05-30 18:10:19 +000012841static PyObject *
12842unicode__format__(PyObject* self, PyObject* args)
12843{
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012844 PyObject *format_spec, *out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012845
12846 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
12847 return NULL;
12848
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012849 out = _PyUnicode_FormatAdvanced(self, format_spec, 0,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012850 PyUnicode_GET_LENGTH(format_spec));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012851 return out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012852}
12853
Eric Smith8c663262007-08-25 02:26:07 +000012854PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012855 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012856\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012857Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000012858
12859static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012860unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012861{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012862 Py_ssize_t size;
12863
12864 /* If it's a compact object, account for base structure +
12865 character data. */
12866 if (PyUnicode_IS_COMPACT_ASCII(v))
12867 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
12868 else if (PyUnicode_IS_COMPACT(v))
12869 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012870 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012871 else {
12872 /* If it is a two-block object, account for base object, and
12873 for character block if present. */
12874 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020012875 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012876 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012877 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012878 }
12879 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020012880 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020012881 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012882 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020012883 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020012884 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012885
12886 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012887}
12888
12889PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012890 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012891
12892static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020012893unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000012894{
Victor Stinner034f6cf2011-09-30 02:26:44 +020012895 PyObject *copy = PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012896 if (!copy)
12897 return NULL;
12898 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000012899}
12900
Guido van Rossumd57fd912000-03-10 22:53:23 +000012901static PyMethodDef unicode_methods[] = {
12902
12903 /* Order is according to common usage: often used methods should
12904 appear first, since lookup is done sequentially. */
12905
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000012906 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012907 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
12908 {"split", (PyCFunction) unicode_split, METH_VARARGS, split__doc__},
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012909 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012910 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
12911 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
12912 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
12913 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
12914 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
12915 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
12916 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000012917 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012918 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
12919 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
12920 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012921 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012922 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
12923 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
12924 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012925 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000012926 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012927 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012928 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012929 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
12930 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
12931 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
12932 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
12933 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
12934 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
12935 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
12936 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
12937 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
12938 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
12939 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
12940 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
12941 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
12942 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000012943 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000012944 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012945 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000012946 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000012947 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000012948 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Georg Brandlceee0772007-11-27 23:48:05 +000012949 {"maketrans", (PyCFunction) unicode_maketrans,
12950 METH_VARARGS | METH_STATIC, maketrans__doc__},
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012951 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000012952#if 0
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012953 {"capwords", (PyCFunction) unicode_capwords, METH_NOARGS, capwords__doc__},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012954#endif
12955
12956#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012957 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012958 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012959#endif
12960
Benjamin Peterson14339b62009-01-31 16:36:08 +000012961 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012962 {NULL, NULL}
12963};
12964
Neil Schemenauerce30bc92002-11-18 16:10:18 +000012965static PyObject *
12966unicode_mod(PyObject *v, PyObject *w)
12967{
Brian Curtindfc80e32011-08-10 20:28:54 -050012968 if (!PyUnicode_Check(v))
12969 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000012970 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000012971}
12972
12973static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012974 0, /*nb_add*/
12975 0, /*nb_subtract*/
12976 0, /*nb_multiply*/
12977 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000012978};
12979
Guido van Rossumd57fd912000-03-10 22:53:23 +000012980static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012981 (lenfunc) unicode_length, /* sq_length */
12982 PyUnicode_Concat, /* sq_concat */
12983 (ssizeargfunc) unicode_repeat, /* sq_repeat */
12984 (ssizeargfunc) unicode_getitem, /* sq_item */
12985 0, /* sq_slice */
12986 0, /* sq_ass_item */
12987 0, /* sq_ass_slice */
12988 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000012989};
12990
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012991static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012992unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012993{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012994 if (PyUnicode_READY(self) == -1)
12995 return NULL;
12996
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000012997 if (PyIndex_Check(item)) {
12998 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012999 if (i == -1 && PyErr_Occurred())
13000 return NULL;
13001 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013002 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013003 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013004 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013005 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013006 PyObject *result;
13007 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013008 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013009 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013010
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013011 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013012 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013013 return NULL;
13014 }
13015
13016 if (slicelength <= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013017 return PyUnicode_New(0, 0);
13018 } else if (start == 0 && step == 1 &&
13019 slicelength == PyUnicode_GET_LENGTH(self) &&
Thomas Woutersed03b412007-08-28 21:37:11 +000013020 PyUnicode_CheckExact(self)) {
13021 Py_INCREF(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013022 return self;
Thomas Woutersed03b412007-08-28 21:37:11 +000013023 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013024 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013025 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013026 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013027 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013028 src_kind = PyUnicode_KIND(self);
13029 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013030 if (!PyUnicode_IS_ASCII(self)) {
13031 kind_limit = kind_maxchar_limit(src_kind);
13032 max_char = 0;
13033 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13034 ch = PyUnicode_READ(src_kind, src_data, cur);
13035 if (ch > max_char) {
13036 max_char = ch;
13037 if (max_char >= kind_limit)
13038 break;
13039 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013040 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013041 }
Victor Stinner55c99112011-10-13 01:17:06 +020013042 else
13043 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013044 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013045 if (result == NULL)
13046 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013047 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013048 dest_data = PyUnicode_DATA(result);
13049
13050 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013051 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13052 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013053 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013054 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013055 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013056 } else {
13057 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13058 return NULL;
13059 }
13060}
13061
13062static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013063 (lenfunc)unicode_length, /* mp_length */
13064 (binaryfunc)unicode_subscript, /* mp_subscript */
13065 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013066};
13067
Guido van Rossumd57fd912000-03-10 22:53:23 +000013068
Guido van Rossumd57fd912000-03-10 22:53:23 +000013069/* Helpers for PyUnicode_Format() */
13070
13071static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +000013072getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013073{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013074 Py_ssize_t argidx = *p_argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013075 if (argidx < arglen) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013076 (*p_argidx)++;
13077 if (arglen < 0)
13078 return args;
13079 else
13080 return PyTuple_GetItem(args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013081 }
13082 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013083 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013084 return NULL;
13085}
13086
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013087/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013088
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013089static PyObject *
13090formatfloat(PyObject *v, int flags, int prec, int type)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013091{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013092 char *p;
13093 PyObject *result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013094 double x;
Tim Petersced69f82003-09-16 20:30:58 +000013095
Guido van Rossumd57fd912000-03-10 22:53:23 +000013096 x = PyFloat_AsDouble(v);
13097 if (x == -1.0 && PyErr_Occurred())
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013098 return NULL;
13099
Guido van Rossumd57fd912000-03-10 22:53:23 +000013100 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013101 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013102
Eric Smith0923d1d2009-04-16 20:16:10 +000013103 p = PyOS_double_to_string(x, type, prec,
13104 (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013105 if (p == NULL)
13106 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013107 result = PyUnicode_DecodeASCII(p, strlen(p), NULL);
Eric Smith0923d1d2009-04-16 20:16:10 +000013108 PyMem_Free(p);
13109 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013110}
13111
Tim Peters38fd5b62000-09-21 05:43:11 +000013112static PyObject*
13113formatlong(PyObject *val, int flags, int prec, int type)
13114{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013115 char *buf;
13116 int len;
13117 PyObject *str; /* temporary string object. */
13118 PyObject *result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013119
Benjamin Peterson14339b62009-01-31 16:36:08 +000013120 str = _PyBytes_FormatLong(val, flags, prec, type, &buf, &len);
13121 if (!str)
13122 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013123 result = PyUnicode_DecodeASCII(buf, len, NULL);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013124 Py_DECREF(str);
13125 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013126}
13127
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013128static Py_UCS4
13129formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013130{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013131 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013132 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013133 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013134 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000013135 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013136 goto onError;
13137 }
13138 else {
13139 /* Integer input truncated to a character */
13140 long x;
13141 x = PyLong_AsLong(v);
13142 if (x == -1 && PyErr_Occurred())
13143 goto onError;
13144
13145 if (x < 0 || x > 0x10ffff) {
13146 PyErr_SetString(PyExc_OverflowError,
13147 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013148 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013149 }
13150
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013151 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013152 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013153
Benjamin Peterson29060642009-01-31 22:14:21 +000013154 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013155 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013156 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013157 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013158}
13159
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013160static int
13161repeat_accumulate(_PyAccu *acc, PyObject *obj, Py_ssize_t count)
13162{
13163 int r;
13164 assert(count > 0);
13165 assert(PyUnicode_Check(obj));
13166 if (count > 5) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013167 PyObject *repeated = unicode_repeat(obj, count);
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013168 if (repeated == NULL)
13169 return -1;
13170 r = _PyAccu_Accumulate(acc, repeated);
13171 Py_DECREF(repeated);
13172 return r;
13173 }
13174 else {
13175 do {
13176 if (_PyAccu_Accumulate(acc, obj))
13177 return -1;
13178 } while (--count);
13179 return 0;
13180 }
13181}
13182
Alexander Belopolsky40018472011-02-26 01:02:56 +000013183PyObject *
13184PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013185{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013186 void *fmt;
13187 int fmtkind;
13188 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013189 int kind;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013190 int r;
13191 Py_ssize_t fmtcnt, fmtpos, arglen, argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013192 int args_owned = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013193 PyObject *dict = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013194 PyObject *temp = NULL;
13195 PyObject *second = NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013196 PyObject *uformat;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013197 _PyAccu acc;
13198 static PyObject *plus, *minus, *blank, *zero, *percent;
13199
13200 if (!plus && !(plus = get_latin1_char('+')))
13201 return NULL;
13202 if (!minus && !(minus = get_latin1_char('-')))
13203 return NULL;
13204 if (!blank && !(blank = get_latin1_char(' ')))
13205 return NULL;
13206 if (!zero && !(zero = get_latin1_char('0')))
13207 return NULL;
13208 if (!percent && !(percent = get_latin1_char('%')))
13209 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000013210
Guido van Rossumd57fd912000-03-10 22:53:23 +000013211 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013212 PyErr_BadInternalCall();
13213 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013214 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013215 uformat = PyUnicode_FromObject(format);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013216 if (uformat == NULL || PyUnicode_READY(uformat) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013217 return NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013218 if (_PyAccu_Init(&acc))
13219 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013220 fmt = PyUnicode_DATA(uformat);
13221 fmtkind = PyUnicode_KIND(uformat);
13222 fmtcnt = PyUnicode_GET_LENGTH(uformat);
13223 fmtpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013224
Guido van Rossumd57fd912000-03-10 22:53:23 +000013225 if (PyTuple_Check(args)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013226 arglen = PyTuple_Size(args);
13227 argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013228 }
13229 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013230 arglen = -1;
13231 argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013232 }
Christian Heimes90aa7642007-12-19 02:45:37 +000013233 if (Py_TYPE(args)->tp_as_mapping && !PyTuple_Check(args) &&
Christian Heimesf3863112007-11-22 07:46:41 +000013234 !PyUnicode_Check(args))
Benjamin Peterson29060642009-01-31 22:14:21 +000013235 dict = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013236
13237 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013238 if (PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013239 PyObject *nonfmt;
13240 Py_ssize_t nonfmtpos;
13241 nonfmtpos = fmtpos++;
13242 while (fmtcnt >= 0 &&
13243 PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
13244 fmtpos++;
13245 fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013246 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010013247 nonfmt = PyUnicode_Substring(uformat, nonfmtpos, fmtpos);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013248 if (nonfmt == NULL)
13249 goto onError;
13250 r = _PyAccu_Accumulate(&acc, nonfmt);
13251 Py_DECREF(nonfmt);
13252 if (r)
13253 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013254 }
13255 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013256 /* Got a format specifier */
13257 int flags = 0;
13258 Py_ssize_t width = -1;
13259 int prec = -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013260 Py_UCS4 c = '\0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013261 Py_UCS4 fill, sign;
Benjamin Peterson29060642009-01-31 22:14:21 +000013262 int isnumok;
13263 PyObject *v = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013264 void *pbuf = NULL;
13265 Py_ssize_t pindex, len;
13266 PyObject *signobj = NULL, *fillobj = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013267
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013268 fmtpos++;
13269 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(') {
13270 Py_ssize_t keystart;
Benjamin Peterson29060642009-01-31 22:14:21 +000013271 Py_ssize_t keylen;
13272 PyObject *key;
13273 int pcount = 1;
Christian Heimesa612dc02008-02-24 13:08:18 +000013274
Benjamin Peterson29060642009-01-31 22:14:21 +000013275 if (dict == NULL) {
13276 PyErr_SetString(PyExc_TypeError,
13277 "format requires a mapping");
13278 goto onError;
13279 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013280 ++fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013281 --fmtcnt;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013282 keystart = fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013283 /* Skip over balanced parentheses */
13284 while (pcount > 0 && --fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013285 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == ')')
Benjamin Peterson29060642009-01-31 22:14:21 +000013286 --pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013287 else if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(')
Benjamin Peterson29060642009-01-31 22:14:21 +000013288 ++pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013289 fmtpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013290 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013291 keylen = fmtpos - keystart - 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013292 if (fmtcnt < 0 || pcount > 0) {
13293 PyErr_SetString(PyExc_ValueError,
13294 "incomplete format key");
13295 goto onError;
13296 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010013297 key = PyUnicode_Substring(uformat,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013298 keystart, keystart + keylen);
Benjamin Peterson29060642009-01-31 22:14:21 +000013299 if (key == NULL)
13300 goto onError;
13301 if (args_owned) {
13302 Py_DECREF(args);
13303 args_owned = 0;
13304 }
13305 args = PyObject_GetItem(dict, key);
13306 Py_DECREF(key);
13307 if (args == NULL) {
13308 goto onError;
13309 }
13310 args_owned = 1;
13311 arglen = -1;
13312 argidx = -2;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013313 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013314 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013315 switch (c = PyUnicode_READ(fmtkind, fmt, fmtpos++)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013316 case '-': flags |= F_LJUST; continue;
13317 case '+': flags |= F_SIGN; continue;
13318 case ' ': flags |= F_BLANK; continue;
13319 case '#': flags |= F_ALT; continue;
13320 case '0': flags |= F_ZERO; continue;
13321 }
13322 break;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013323 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013324 if (c == '*') {
13325 v = getnextarg(args, arglen, &argidx);
13326 if (v == NULL)
13327 goto onError;
13328 if (!PyLong_Check(v)) {
13329 PyErr_SetString(PyExc_TypeError,
13330 "* wants int");
13331 goto onError;
13332 }
13333 width = PyLong_AsLong(v);
13334 if (width == -1 && PyErr_Occurred())
13335 goto onError;
13336 if (width < 0) {
13337 flags |= F_LJUST;
13338 width = -width;
13339 }
13340 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013341 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013342 }
13343 else if (c >= '0' && c <= '9') {
13344 width = c - '0';
13345 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013346 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013347 if (c < '0' || c > '9')
13348 break;
13349 if ((width*10) / 10 != width) {
13350 PyErr_SetString(PyExc_ValueError,
13351 "width too big");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013352 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013353 }
13354 width = width*10 + (c - '0');
13355 }
13356 }
13357 if (c == '.') {
13358 prec = 0;
13359 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013360 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013361 if (c == '*') {
13362 v = getnextarg(args, arglen, &argidx);
13363 if (v == NULL)
13364 goto onError;
13365 if (!PyLong_Check(v)) {
13366 PyErr_SetString(PyExc_TypeError,
13367 "* wants int");
13368 goto onError;
13369 }
13370 prec = PyLong_AsLong(v);
13371 if (prec == -1 && PyErr_Occurred())
13372 goto onError;
13373 if (prec < 0)
13374 prec = 0;
13375 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013376 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013377 }
13378 else if (c >= '0' && c <= '9') {
13379 prec = c - '0';
13380 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013381 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013382 if (c < '0' || c > '9')
13383 break;
13384 if ((prec*10) / 10 != prec) {
13385 PyErr_SetString(PyExc_ValueError,
13386 "prec too big");
13387 goto onError;
13388 }
13389 prec = prec*10 + (c - '0');
13390 }
13391 }
13392 } /* prec */
13393 if (fmtcnt >= 0) {
13394 if (c == 'h' || c == 'l' || c == 'L') {
13395 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013396 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013397 }
13398 }
13399 if (fmtcnt < 0) {
13400 PyErr_SetString(PyExc_ValueError,
13401 "incomplete format");
13402 goto onError;
13403 }
13404 if (c != '%') {
13405 v = getnextarg(args, arglen, &argidx);
13406 if (v == NULL)
13407 goto onError;
13408 }
13409 sign = 0;
13410 fill = ' ';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013411 fillobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013412 switch (c) {
13413
13414 case '%':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013415 _PyAccu_Accumulate(&acc, percent);
13416 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +000013417
13418 case 's':
13419 case 'r':
13420 case 'a':
Victor Stinner808fc0a2010-03-22 12:50:40 +000013421 if (PyUnicode_CheckExact(v) && c == 's') {
Benjamin Peterson29060642009-01-31 22:14:21 +000013422 temp = v;
13423 Py_INCREF(temp);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013424 }
13425 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013426 if (c == 's')
13427 temp = PyObject_Str(v);
13428 else if (c == 'r')
13429 temp = PyObject_Repr(v);
13430 else
13431 temp = PyObject_ASCII(v);
13432 if (temp == NULL)
13433 goto onError;
13434 if (PyUnicode_Check(temp))
13435 /* nothing to do */;
13436 else {
13437 Py_DECREF(temp);
13438 PyErr_SetString(PyExc_TypeError,
13439 "%s argument has non-string str()");
13440 goto onError;
13441 }
13442 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013443 if (PyUnicode_READY(temp) == -1) {
13444 Py_CLEAR(temp);
13445 goto onError;
13446 }
13447 pbuf = PyUnicode_DATA(temp);
13448 kind = PyUnicode_KIND(temp);
13449 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013450 if (prec >= 0 && len > prec)
13451 len = prec;
13452 break;
13453
13454 case 'i':
13455 case 'd':
13456 case 'u':
13457 case 'o':
13458 case 'x':
13459 case 'X':
Benjamin Peterson29060642009-01-31 22:14:21 +000013460 isnumok = 0;
13461 if (PyNumber_Check(v)) {
13462 PyObject *iobj=NULL;
13463
13464 if (PyLong_Check(v)) {
13465 iobj = v;
13466 Py_INCREF(iobj);
13467 }
13468 else {
13469 iobj = PyNumber_Long(v);
13470 }
13471 if (iobj!=NULL) {
13472 if (PyLong_Check(iobj)) {
13473 isnumok = 1;
Senthil Kumaran9ebe08d2011-07-03 21:03:16 -070013474 temp = formatlong(iobj, flags, prec, (c == 'i'? 'd': c));
Benjamin Peterson29060642009-01-31 22:14:21 +000013475 Py_DECREF(iobj);
13476 if (!temp)
13477 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013478 if (PyUnicode_READY(temp) == -1) {
13479 Py_CLEAR(temp);
13480 goto onError;
13481 }
13482 pbuf = PyUnicode_DATA(temp);
13483 kind = PyUnicode_KIND(temp);
13484 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013485 sign = 1;
13486 }
13487 else {
13488 Py_DECREF(iobj);
13489 }
13490 }
13491 }
13492 if (!isnumok) {
13493 PyErr_Format(PyExc_TypeError,
13494 "%%%c format: a number is required, "
13495 "not %.200s", (char)c, Py_TYPE(v)->tp_name);
13496 goto onError;
13497 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013498 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013499 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013500 fillobj = zero;
13501 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013502 break;
13503
13504 case 'e':
13505 case 'E':
13506 case 'f':
13507 case 'F':
13508 case 'g':
13509 case 'G':
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013510 temp = formatfloat(v, flags, prec, c);
13511 if (!temp)
Benjamin Peterson29060642009-01-31 22:14:21 +000013512 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013513 if (PyUnicode_READY(temp) == -1) {
13514 Py_CLEAR(temp);
13515 goto onError;
13516 }
13517 pbuf = PyUnicode_DATA(temp);
13518 kind = PyUnicode_KIND(temp);
13519 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013520 sign = 1;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013521 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013522 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013523 fillobj = zero;
13524 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013525 break;
13526
13527 case 'c':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013528 {
13529 Py_UCS4 ch = formatchar(v);
13530 if (ch == (Py_UCS4) -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013531 goto onError;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013532 temp = _PyUnicode_FromUCS4(&ch, 1);
13533 if (temp == NULL)
13534 goto onError;
13535 pbuf = PyUnicode_DATA(temp);
13536 kind = PyUnicode_KIND(temp);
13537 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013538 break;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013539 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013540
13541 default:
13542 PyErr_Format(PyExc_ValueError,
13543 "unsupported format character '%c' (0x%x) "
13544 "at index %zd",
13545 (31<=c && c<=126) ? (char)c : '?',
13546 (int)c,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013547 fmtpos - 1);
Benjamin Peterson29060642009-01-31 22:14:21 +000013548 goto onError;
13549 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013550 /* pbuf is initialized here. */
13551 pindex = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +000013552 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013553 if (PyUnicode_READ(kind, pbuf, pindex) == '-') {
13554 signobj = minus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013555 len--;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013556 pindex++;
13557 }
13558 else if (PyUnicode_READ(kind, pbuf, pindex) == '+') {
13559 signobj = plus;
13560 len--;
13561 pindex++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013562 }
13563 else if (flags & F_SIGN)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013564 signobj = plus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013565 else if (flags & F_BLANK)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013566 signobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013567 else
13568 sign = 0;
13569 }
13570 if (width < len)
13571 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013572 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013573 if (fill != ' ') {
13574 assert(signobj != NULL);
13575 if (_PyAccu_Accumulate(&acc, signobj))
13576 goto onError;
13577 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013578 if (width > len)
13579 width--;
13580 }
13581 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013582 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013583 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == c);
Benjamin Peterson29060642009-01-31 22:14:21 +000013584 if (fill != ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013585 second = get_latin1_char(
13586 PyUnicode_READ(kind, pbuf, pindex + 1));
13587 pindex += 2;
13588 if (second == NULL ||
13589 _PyAccu_Accumulate(&acc, zero) ||
13590 _PyAccu_Accumulate(&acc, second))
13591 goto onError;
13592 Py_CLEAR(second);
Benjamin Peterson29060642009-01-31 22:14:21 +000013593 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013594 width -= 2;
13595 if (width < 0)
13596 width = 0;
13597 len -= 2;
13598 }
13599 if (width > len && !(flags & F_LJUST)) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013600 assert(fillobj != NULL);
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013601 if (repeat_accumulate(&acc, fillobj, width - len))
13602 goto onError;
13603 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013604 }
13605 if (fill == ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013606 if (sign) {
13607 assert(signobj != NULL);
13608 if (_PyAccu_Accumulate(&acc, signobj))
13609 goto onError;
13610 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013611 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013612 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
13613 assert(PyUnicode_READ(kind, pbuf, pindex+1) == c);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013614 second = get_latin1_char(
13615 PyUnicode_READ(kind, pbuf, pindex + 1));
13616 pindex += 2;
13617 if (second == NULL ||
13618 _PyAccu_Accumulate(&acc, zero) ||
13619 _PyAccu_Accumulate(&acc, second))
13620 goto onError;
13621 Py_CLEAR(second);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013622 }
13623 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013624 /* Copy all characters, preserving len */
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013625 if (temp != NULL) {
13626 assert(pbuf == PyUnicode_DATA(temp));
13627 v = PyUnicode_Substring(temp, pindex, pindex + len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013628 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013629 else {
13630 const char *p = (const char *) pbuf;
13631 assert(pbuf != NULL);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013632 p += kind * pindex;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013633 v = PyUnicode_FromKindAndData(kind, p, len);
13634 }
13635 if (v == NULL)
13636 goto onError;
13637 r = _PyAccu_Accumulate(&acc, v);
13638 Py_DECREF(v);
13639 if (r)
13640 goto onError;
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013641 if (width > len && repeat_accumulate(&acc, blank, width - len))
13642 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013643 if (dict && (argidx < arglen) && c != '%') {
13644 PyErr_SetString(PyExc_TypeError,
13645 "not all arguments converted during string formatting");
Benjamin Peterson29060642009-01-31 22:14:21 +000013646 goto onError;
13647 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013648 Py_CLEAR(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013649 } /* '%' */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013650 } /* until end */
13651 if (argidx < arglen && !dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013652 PyErr_SetString(PyExc_TypeError,
13653 "not all arguments converted during string formatting");
13654 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013655 }
13656
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013657 result = _PyAccu_Finish(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013658 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013659 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013660 }
13661 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013662 Py_XDECREF(temp);
13663 Py_XDECREF(second);
Victor Stinner7931d9a2011-11-04 00:22:48 +010013664 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013665
Benjamin Peterson29060642009-01-31 22:14:21 +000013666 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013667 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013668 Py_XDECREF(temp);
13669 Py_XDECREF(second);
13670 _PyAccu_Destroy(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013671 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013672 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013673 }
13674 return NULL;
13675}
13676
Jeremy Hylton938ace62002-07-17 16:30:39 +000013677static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000013678unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
13679
Tim Peters6d6c1a32001-08-02 04:15:00 +000013680static PyObject *
13681unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13682{
Benjamin Peterson29060642009-01-31 22:14:21 +000013683 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013684 static char *kwlist[] = {"object", "encoding", "errors", 0};
13685 char *encoding = NULL;
13686 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000013687
Benjamin Peterson14339b62009-01-31 16:36:08 +000013688 if (type != &PyUnicode_Type)
13689 return unicode_subtype_new(type, args, kwds);
13690 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000013691 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000013692 return NULL;
13693 if (x == NULL)
Victor Stinner7931d9a2011-11-04 00:22:48 +010013694 return PyUnicode_New(0, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013695 if (encoding == NULL && errors == NULL)
13696 return PyObject_Str(x);
13697 else
Benjamin Peterson29060642009-01-31 22:14:21 +000013698 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000013699}
13700
Guido van Rossume023fe02001-08-30 03:12:59 +000013701static PyObject *
13702unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13703{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013704 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013705 Py_ssize_t length, char_size;
13706 int share_wstr, share_utf8;
13707 unsigned int kind;
13708 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000013709
Benjamin Peterson14339b62009-01-31 16:36:08 +000013710 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013711
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013712 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013713 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013714 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020013715 assert(_PyUnicode_CHECK(unicode));
Victor Stinnere06e1452011-10-04 20:52:31 +020013716 if (PyUnicode_READY(unicode))
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013717 return NULL;
13718
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013719 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013720 if (self == NULL) {
13721 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013722 return NULL;
13723 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013724 kind = PyUnicode_KIND(unicode);
13725 length = PyUnicode_GET_LENGTH(unicode);
13726
13727 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013728#ifdef Py_DEBUG
13729 _PyUnicode_HASH(self) = -1;
13730#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013731 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013732#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013733 _PyUnicode_STATE(self).interned = 0;
13734 _PyUnicode_STATE(self).kind = kind;
13735 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020013736 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013737 _PyUnicode_STATE(self).ready = 1;
13738 _PyUnicode_WSTR(self) = NULL;
13739 _PyUnicode_UTF8_LENGTH(self) = 0;
13740 _PyUnicode_UTF8(self) = NULL;
13741 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020013742 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013743
13744 share_utf8 = 0;
13745 share_wstr = 0;
13746 if (kind == PyUnicode_1BYTE_KIND) {
13747 char_size = 1;
13748 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
13749 share_utf8 = 1;
13750 }
13751 else if (kind == PyUnicode_2BYTE_KIND) {
13752 char_size = 2;
13753 if (sizeof(wchar_t) == 2)
13754 share_wstr = 1;
13755 }
13756 else {
13757 assert(kind == PyUnicode_4BYTE_KIND);
13758 char_size = 4;
13759 if (sizeof(wchar_t) == 4)
13760 share_wstr = 1;
13761 }
13762
13763 /* Ensure we won't overflow the length. */
13764 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
13765 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013766 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013767 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013768 data = PyObject_MALLOC((length + 1) * char_size);
13769 if (data == NULL) {
13770 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013771 goto onError;
13772 }
13773
Victor Stinnerc3c74152011-10-02 20:39:55 +020013774 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013775 if (share_utf8) {
13776 _PyUnicode_UTF8_LENGTH(self) = length;
13777 _PyUnicode_UTF8(self) = data;
13778 }
13779 if (share_wstr) {
13780 _PyUnicode_WSTR_LENGTH(self) = length;
13781 _PyUnicode_WSTR(self) = (wchar_t *)data;
13782 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013783
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013784 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013785 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013786 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013787#ifdef Py_DEBUG
13788 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
13789#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020013790 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010013791 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013792
13793onError:
13794 Py_DECREF(unicode);
13795 Py_DECREF(self);
13796 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000013797}
13798
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013799PyDoc_STRVAR(unicode_doc,
Benjamin Peterson29060642009-01-31 22:14:21 +000013800 "str(string[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000013801\n\
Collin Winterd474ce82007-08-07 19:42:11 +000013802Create a new string object from the given encoded string.\n\
Skip Montanaro35b37a52002-07-26 16:22:46 +000013803encoding defaults to the current default string encoding.\n\
13804errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000013805
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013806static PyObject *unicode_iter(PyObject *seq);
13807
Guido van Rossumd57fd912000-03-10 22:53:23 +000013808PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000013809 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013810 "str", /* tp_name */
13811 sizeof(PyUnicodeObject), /* tp_size */
13812 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013813 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013814 (destructor)unicode_dealloc, /* tp_dealloc */
13815 0, /* tp_print */
13816 0, /* tp_getattr */
13817 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000013818 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013819 unicode_repr, /* tp_repr */
13820 &unicode_as_number, /* tp_as_number */
13821 &unicode_as_sequence, /* tp_as_sequence */
13822 &unicode_as_mapping, /* tp_as_mapping */
13823 (hashfunc) unicode_hash, /* tp_hash*/
13824 0, /* tp_call*/
13825 (reprfunc) unicode_str, /* tp_str */
13826 PyObject_GenericGetAttr, /* tp_getattro */
13827 0, /* tp_setattro */
13828 0, /* tp_as_buffer */
13829 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000013830 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013831 unicode_doc, /* tp_doc */
13832 0, /* tp_traverse */
13833 0, /* tp_clear */
13834 PyUnicode_RichCompare, /* tp_richcompare */
13835 0, /* tp_weaklistoffset */
13836 unicode_iter, /* tp_iter */
13837 0, /* tp_iternext */
13838 unicode_methods, /* tp_methods */
13839 0, /* tp_members */
13840 0, /* tp_getset */
13841 &PyBaseObject_Type, /* tp_base */
13842 0, /* tp_dict */
13843 0, /* tp_descr_get */
13844 0, /* tp_descr_set */
13845 0, /* tp_dictoffset */
13846 0, /* tp_init */
13847 0, /* tp_alloc */
13848 unicode_new, /* tp_new */
13849 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013850};
13851
13852/* Initialize the Unicode implementation */
13853
Victor Stinner3a50e702011-10-18 21:21:00 +020013854int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013855{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013856 int i;
13857
Thomas Wouters477c8d52006-05-27 19:21:47 +000013858 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013859 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000013860 0x000A, /* LINE FEED */
13861 0x000D, /* CARRIAGE RETURN */
13862 0x001C, /* FILE SEPARATOR */
13863 0x001D, /* GROUP SEPARATOR */
13864 0x001E, /* RECORD SEPARATOR */
13865 0x0085, /* NEXT LINE */
13866 0x2028, /* LINE SEPARATOR */
13867 0x2029, /* PARAGRAPH SEPARATOR */
13868 };
13869
Fred Drakee4315f52000-05-09 19:53:39 +000013870 /* Init the implementation */
Victor Stinnera464fc12011-10-02 20:39:30 +020013871 unicode_empty = PyUnicode_New(0, 0);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013872 assert(_PyUnicode_CheckConsistency(unicode_empty, 1));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013873 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013874 Py_FatalError("Can't create empty string");
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013875
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013876 for (i = 0; i < 256; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +000013877 unicode_latin1[i] = NULL;
Guido van Rossumcacfc072002-05-24 19:01:59 +000013878 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013879 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000013880
13881 /* initialize the linebreak bloom filter */
13882 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013883 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020013884 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013885
13886 PyType_Ready(&EncodingMapType);
Victor Stinner3a50e702011-10-18 21:21:00 +020013887
13888#ifdef HAVE_MBCS
13889 winver.dwOSVersionInfoSize = sizeof(winver);
13890 if (!GetVersionEx((OSVERSIONINFO*)&winver)) {
13891 PyErr_SetFromWindowsErr(0);
13892 return -1;
13893 }
13894#endif
13895 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013896}
13897
13898/* Finalize the Unicode implementation */
13899
Christian Heimesa156e092008-02-16 07:38:31 +000013900int
13901PyUnicode_ClearFreeList(void)
13902{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013903 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000013904}
13905
Guido van Rossumd57fd912000-03-10 22:53:23 +000013906void
Thomas Wouters78890102000-07-22 19:25:51 +000013907_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013908{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013909 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013910
Guido van Rossum4ae8ef82000-10-03 18:09:04 +000013911 Py_XDECREF(unicode_empty);
13912 unicode_empty = NULL;
Barry Warsaw5b4c2282000-10-03 20:45:26 +000013913
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013914 for (i = 0; i < 256; i++) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013915 if (unicode_latin1[i]) {
13916 Py_DECREF(unicode_latin1[i]);
13917 unicode_latin1[i] = NULL;
13918 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013919 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020013920 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000013921 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000013922}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000013923
Walter Dörwald16807132007-05-25 13:52:07 +000013924void
13925PyUnicode_InternInPlace(PyObject **p)
13926{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013927 register PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013928 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020013929#ifdef Py_DEBUG
13930 assert(s != NULL);
13931 assert(_PyUnicode_CHECK(s));
13932#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000013933 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020013934 return;
13935#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000013936 /* If it's a subclass, we don't really know what putting
13937 it in the interned dict might do. */
13938 if (!PyUnicode_CheckExact(s))
13939 return;
13940 if (PyUnicode_CHECK_INTERNED(s))
13941 return;
Victor Stinner1b4f9ce2011-10-03 13:28:14 +020013942 if (_PyUnicode_READY_REPLACE(p)) {
Victor Stinner6b56a7f2011-10-04 20:04:52 +020013943 assert(0 && "_PyUnicode_READY_REPLACE fail in PyUnicode_InternInPlace");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013944 return;
13945 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013946 s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013947 if (interned == NULL) {
13948 interned = PyDict_New();
13949 if (interned == NULL) {
13950 PyErr_Clear(); /* Don't leave an exception */
13951 return;
13952 }
13953 }
13954 /* It might be that the GetItem call fails even
13955 though the key is present in the dictionary,
13956 namely when this happens during a stack overflow. */
13957 Py_ALLOW_RECURSION
Victor Stinner7931d9a2011-11-04 00:22:48 +010013958 t = PyDict_GetItem(interned, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013959 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000013960
Benjamin Peterson29060642009-01-31 22:14:21 +000013961 if (t) {
13962 Py_INCREF(t);
13963 Py_DECREF(*p);
13964 *p = t;
13965 return;
13966 }
Walter Dörwald16807132007-05-25 13:52:07 +000013967
Benjamin Peterson14339b62009-01-31 16:36:08 +000013968 PyThreadState_GET()->recursion_critical = 1;
Victor Stinner7931d9a2011-11-04 00:22:48 +010013969 if (PyDict_SetItem(interned, s, s) < 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013970 PyErr_Clear();
13971 PyThreadState_GET()->recursion_critical = 0;
13972 return;
13973 }
13974 PyThreadState_GET()->recursion_critical = 0;
13975 /* The two references in interned are not counted by refcnt.
13976 The deallocator will take care of this */
13977 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013978 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000013979}
13980
13981void
13982PyUnicode_InternImmortal(PyObject **p)
13983{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013984 PyUnicode_InternInPlace(p);
13985 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020013986 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013987 Py_INCREF(*p);
13988 }
Walter Dörwald16807132007-05-25 13:52:07 +000013989}
13990
13991PyObject *
13992PyUnicode_InternFromString(const char *cp)
13993{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013994 PyObject *s = PyUnicode_FromString(cp);
13995 if (s == NULL)
13996 return NULL;
13997 PyUnicode_InternInPlace(&s);
13998 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000013999}
14000
Alexander Belopolsky40018472011-02-26 01:02:56 +000014001void
14002_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000014003{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014004 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014005 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014006 Py_ssize_t i, n;
14007 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000014008
Benjamin Peterson14339b62009-01-31 16:36:08 +000014009 if (interned == NULL || !PyDict_Check(interned))
14010 return;
14011 keys = PyDict_Keys(interned);
14012 if (keys == NULL || !PyList_Check(keys)) {
14013 PyErr_Clear();
14014 return;
14015 }
Walter Dörwald16807132007-05-25 13:52:07 +000014016
Benjamin Peterson14339b62009-01-31 16:36:08 +000014017 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
14018 detector, interned unicode strings are not forcibly deallocated;
14019 rather, we give them their stolen references back, and then clear
14020 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000014021
Benjamin Peterson14339b62009-01-31 16:36:08 +000014022 n = PyList_GET_SIZE(keys);
14023 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000014024 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014025 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014026 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014027 if (PyUnicode_READY(s) == -1) {
14028 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014029 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014030 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014031 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014032 case SSTATE_NOT_INTERNED:
14033 /* XXX Shouldn't happen */
14034 break;
14035 case SSTATE_INTERNED_IMMORTAL:
14036 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014037 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014038 break;
14039 case SSTATE_INTERNED_MORTAL:
14040 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014041 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014042 break;
14043 default:
14044 Py_FatalError("Inconsistent interned string state.");
14045 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014046 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014047 }
14048 fprintf(stderr, "total size of all interned strings: "
14049 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
14050 "mortal/immortal\n", mortal_size, immortal_size);
14051 Py_DECREF(keys);
14052 PyDict_Clear(interned);
14053 Py_DECREF(interned);
14054 interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +000014055}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014056
14057
14058/********************* Unicode Iterator **************************/
14059
14060typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014061 PyObject_HEAD
14062 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014063 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014064} unicodeiterobject;
14065
14066static void
14067unicodeiter_dealloc(unicodeiterobject *it)
14068{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014069 _PyObject_GC_UNTRACK(it);
14070 Py_XDECREF(it->it_seq);
14071 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014072}
14073
14074static int
14075unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
14076{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014077 Py_VISIT(it->it_seq);
14078 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014079}
14080
14081static PyObject *
14082unicodeiter_next(unicodeiterobject *it)
14083{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014084 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014085
Benjamin Peterson14339b62009-01-31 16:36:08 +000014086 assert(it != NULL);
14087 seq = it->it_seq;
14088 if (seq == NULL)
14089 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014090 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014091
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014092 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
14093 int kind = PyUnicode_KIND(seq);
14094 void *data = PyUnicode_DATA(seq);
14095 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
14096 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014097 if (item != NULL)
14098 ++it->it_index;
14099 return item;
14100 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014101
Benjamin Peterson14339b62009-01-31 16:36:08 +000014102 Py_DECREF(seq);
14103 it->it_seq = NULL;
14104 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014105}
14106
14107static PyObject *
14108unicodeiter_len(unicodeiterobject *it)
14109{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014110 Py_ssize_t len = 0;
14111 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020014112 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014113 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014114}
14115
14116PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
14117
14118static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014119 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000014120 length_hint_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000014121 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014122};
14123
14124PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014125 PyVarObject_HEAD_INIT(&PyType_Type, 0)
14126 "str_iterator", /* tp_name */
14127 sizeof(unicodeiterobject), /* tp_basicsize */
14128 0, /* tp_itemsize */
14129 /* methods */
14130 (destructor)unicodeiter_dealloc, /* tp_dealloc */
14131 0, /* tp_print */
14132 0, /* tp_getattr */
14133 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014134 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014135 0, /* tp_repr */
14136 0, /* tp_as_number */
14137 0, /* tp_as_sequence */
14138 0, /* tp_as_mapping */
14139 0, /* tp_hash */
14140 0, /* tp_call */
14141 0, /* tp_str */
14142 PyObject_GenericGetAttr, /* tp_getattro */
14143 0, /* tp_setattro */
14144 0, /* tp_as_buffer */
14145 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
14146 0, /* tp_doc */
14147 (traverseproc)unicodeiter_traverse, /* tp_traverse */
14148 0, /* tp_clear */
14149 0, /* tp_richcompare */
14150 0, /* tp_weaklistoffset */
14151 PyObject_SelfIter, /* tp_iter */
14152 (iternextfunc)unicodeiter_next, /* tp_iternext */
14153 unicodeiter_methods, /* tp_methods */
14154 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014155};
14156
14157static PyObject *
14158unicode_iter(PyObject *seq)
14159{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014160 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014161
Benjamin Peterson14339b62009-01-31 16:36:08 +000014162 if (!PyUnicode_Check(seq)) {
14163 PyErr_BadInternalCall();
14164 return NULL;
14165 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014166 if (PyUnicode_READY(seq) == -1)
14167 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014168 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
14169 if (it == NULL)
14170 return NULL;
14171 it->it_index = 0;
14172 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014173 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014174 _PyObject_GC_TRACK(it);
14175 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014176}
14177
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010014178
14179size_t
14180Py_UNICODE_strlen(const Py_UNICODE *u)
14181{
14182 int res = 0;
14183 while(*u++)
14184 res++;
14185 return res;
14186}
14187
14188Py_UNICODE*
14189Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
14190{
14191 Py_UNICODE *u = s1;
14192 while ((*u++ = *s2++));
14193 return s1;
14194}
14195
14196Py_UNICODE*
14197Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14198{
14199 Py_UNICODE *u = s1;
14200 while ((*u++ = *s2++))
14201 if (n-- == 0)
14202 break;
14203 return s1;
14204}
14205
14206Py_UNICODE*
14207Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
14208{
14209 Py_UNICODE *u1 = s1;
14210 u1 += Py_UNICODE_strlen(u1);
14211 Py_UNICODE_strcpy(u1, s2);
14212 return s1;
14213}
14214
14215int
14216Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
14217{
14218 while (*s1 && *s2 && *s1 == *s2)
14219 s1++, s2++;
14220 if (*s1 && *s2)
14221 return (*s1 < *s2) ? -1 : +1;
14222 if (*s1)
14223 return 1;
14224 if (*s2)
14225 return -1;
14226 return 0;
14227}
14228
14229int
14230Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14231{
14232 register Py_UNICODE u1, u2;
14233 for (; n != 0; n--) {
14234 u1 = *s1;
14235 u2 = *s2;
14236 if (u1 != u2)
14237 return (u1 < u2) ? -1 : +1;
14238 if (u1 == '\0')
14239 return 0;
14240 s1++;
14241 s2++;
14242 }
14243 return 0;
14244}
14245
14246Py_UNICODE*
14247Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
14248{
14249 const Py_UNICODE *p;
14250 for (p = s; *p; p++)
14251 if (*p == c)
14252 return (Py_UNICODE*)p;
14253 return NULL;
14254}
14255
14256Py_UNICODE*
14257Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
14258{
14259 const Py_UNICODE *p;
14260 p = s + Py_UNICODE_strlen(s);
14261 while (p != s) {
14262 p--;
14263 if (*p == c)
14264 return (Py_UNICODE*)p;
14265 }
14266 return NULL;
14267}
Victor Stinner331ea922010-08-10 16:37:20 +000014268
Victor Stinner71133ff2010-09-01 23:43:53 +000014269Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014270PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000014271{
Victor Stinner577db2c2011-10-11 22:12:48 +020014272 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014273 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000014274
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014275 if (!PyUnicode_Check(unicode)) {
14276 PyErr_BadArgument();
14277 return NULL;
14278 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014279 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020014280 if (u == NULL)
14281 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000014282 /* Ensure we won't overflow the size. */
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014283 if (len > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000014284 PyErr_NoMemory();
14285 return NULL;
14286 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014287 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000014288 size *= sizeof(Py_UNICODE);
14289 copy = PyMem_Malloc(size);
14290 if (copy == NULL) {
14291 PyErr_NoMemory();
14292 return NULL;
14293 }
Victor Stinner577db2c2011-10-11 22:12:48 +020014294 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000014295 return copy;
14296}
Martin v. Löwis5b222132007-06-10 09:51:05 +000014297
Georg Brandl66c221e2010-10-14 07:04:07 +000014298/* A _string module, to export formatter_parser and formatter_field_name_split
14299 to the string.Formatter class implemented in Python. */
14300
14301static PyMethodDef _string_methods[] = {
14302 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
14303 METH_O, PyDoc_STR("split the argument as a field name")},
14304 {"formatter_parser", (PyCFunction) formatter_parser,
14305 METH_O, PyDoc_STR("parse the argument as a format string")},
14306 {NULL, NULL}
14307};
14308
14309static struct PyModuleDef _string_module = {
14310 PyModuleDef_HEAD_INIT,
14311 "_string",
14312 PyDoc_STR("string helper module"),
14313 0,
14314 _string_methods,
14315 NULL,
14316 NULL,
14317 NULL,
14318 NULL
14319};
14320
14321PyMODINIT_FUNC
14322PyInit__string(void)
14323{
14324 return PyModule_Create(&_string_module);
14325}
14326
14327
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014328#ifdef __cplusplus
14329}
14330#endif