blob: 541ded8bacddb4835b696ac0c4202e166b3a093d [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,
257 const Py_UNICODE *unicode, Py_ssize_t size,
258 Py_ssize_t startpos, Py_ssize_t endpos,
259 const char *reason);
Martin v. Löwis9e816682011-11-02 12:45:42 +0100260static void
261raise_encode_exception_obj(PyObject **exceptionObject,
262 const char *encoding,
263 PyObject *unicode,
264 Py_ssize_t startpos, Py_ssize_t endpos,
265 const char *reason);
Victor Stinner31be90b2010-04-22 19:38:16 +0000266
Christian Heimes190d79e2008-01-30 11:58:22 +0000267/* Same for linebreaks */
268static unsigned char ascii_linebreak[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000269 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000270/* 0x000A, * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000271/* 0x000B, * LINE TABULATION */
272/* 0x000C, * FORM FEED */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000273/* 0x000D, * CARRIAGE RETURN */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000274 0, 0, 1, 1, 1, 1, 0, 0,
Benjamin Peterson14339b62009-01-31 16:36:08 +0000275 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000276/* 0x001C, * FILE SEPARATOR */
277/* 0x001D, * GROUP SEPARATOR */
278/* 0x001E, * RECORD SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000279 0, 0, 0, 0, 1, 1, 1, 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,
Christian Heimes190d79e2008-01-30 11:58:22 +0000284
Benjamin Peterson14339b62009-01-31 16:36:08 +0000285 0, 0, 0, 0, 0, 0, 0, 0,
286 0, 0, 0, 0, 0, 0, 0, 0,
287 0, 0, 0, 0, 0, 0, 0, 0,
288 0, 0, 0, 0, 0, 0, 0, 0,
289 0, 0, 0, 0, 0, 0, 0, 0,
290 0, 0, 0, 0, 0, 0, 0, 0,
291 0, 0, 0, 0, 0, 0, 0, 0,
292 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000293};
294
Ezio Melotti48a2f8f2011-09-29 00:18:19 +0300295/* The max unicode value is always 0x10FFFF while using the PEP-393 API.
296 This function is kept for backward compatibility with the old API. */
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000297Py_UNICODE
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +0000298PyUnicode_GetMax(void)
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000299{
Fredrik Lundh8f455852001-06-27 18:59:43 +0000300#ifdef Py_UNICODE_WIDE
Benjamin Peterson14339b62009-01-31 16:36:08 +0000301 return 0x10FFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000302#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000303 /* This is actually an illegal character, so it should
304 not be passed to unichr. */
305 return 0xFFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000306#endif
307}
308
Victor Stinner910337b2011-10-03 03:20:16 +0200309#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200310int
Victor Stinner7931d9a2011-11-04 00:22:48 +0100311_PyUnicode_CheckConsistency(PyObject *op, int check_content)
Victor Stinner910337b2011-10-03 03:20:16 +0200312{
313 PyASCIIObject *ascii;
314 unsigned int kind;
315
316 assert(PyUnicode_Check(op));
317
318 ascii = (PyASCIIObject *)op;
319 kind = ascii->state.kind;
320
Victor Stinnera3b334d2011-10-03 13:53:37 +0200321 if (ascii->state.ascii == 1 && ascii->state.compact == 1) {
Victor Stinner910337b2011-10-03 03:20:16 +0200322 assert(kind == PyUnicode_1BYTE_KIND);
Victor Stinner910337b2011-10-03 03:20:16 +0200323 assert(ascii->state.ready == 1);
324 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200325 else {
Victor Stinner85041a52011-10-03 14:42:39 +0200326 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
Victor Stinner7f11ad42011-10-04 00:00:20 +0200327 void *data;
Victor Stinner910337b2011-10-03 03:20:16 +0200328
Victor Stinnera41463c2011-10-04 01:05:08 +0200329 if (ascii->state.compact == 1) {
330 data = compact + 1;
Victor Stinner910337b2011-10-03 03:20:16 +0200331 assert(kind == PyUnicode_1BYTE_KIND
332 || kind == PyUnicode_2BYTE_KIND
333 || kind == PyUnicode_4BYTE_KIND);
Victor Stinnera41463c2011-10-04 01:05:08 +0200334 assert(ascii->state.ascii == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200335 assert(ascii->state.ready == 1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200336 assert (compact->utf8 != data);
337 } else {
338 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
339
340 data = unicode->data.any;
341 if (kind == PyUnicode_WCHAR_KIND) {
342 assert(ascii->state.compact == 0);
343 assert(ascii->state.ascii == 0);
344 assert(ascii->state.ready == 0);
345 assert(ascii->wstr != NULL);
346 assert(data == NULL);
347 assert(compact->utf8 == NULL);
348 assert(ascii->state.interned == SSTATE_NOT_INTERNED);
349 }
350 else {
351 assert(kind == PyUnicode_1BYTE_KIND
352 || kind == PyUnicode_2BYTE_KIND
353 || kind == PyUnicode_4BYTE_KIND);
354 assert(ascii->state.compact == 0);
355 assert(ascii->state.ready == 1);
356 assert(data != NULL);
357 if (ascii->state.ascii) {
358 assert (compact->utf8 == data);
359 assert (compact->utf8_length == ascii->length);
360 }
361 else
362 assert (compact->utf8 != data);
363 }
364 }
365 if (kind != PyUnicode_WCHAR_KIND) {
Victor Stinner7f11ad42011-10-04 00:00:20 +0200366 if (
367#if SIZEOF_WCHAR_T == 2
368 kind == PyUnicode_2BYTE_KIND
369#else
370 kind == PyUnicode_4BYTE_KIND
371#endif
372 )
Victor Stinnera41463c2011-10-04 01:05:08 +0200373 {
374 assert(ascii->wstr == data);
375 assert(compact->wstr_length == ascii->length);
376 } else
377 assert(ascii->wstr != data);
Victor Stinner910337b2011-10-03 03:20:16 +0200378 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200379
380 if (compact->utf8 == NULL)
381 assert(compact->utf8_length == 0);
382 if (ascii->wstr == NULL)
383 assert(compact->wstr_length == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200384 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200385 /* check that the best kind is used */
386 if (check_content && kind != PyUnicode_WCHAR_KIND)
387 {
388 Py_ssize_t i;
389 Py_UCS4 maxchar = 0;
390 void *data = PyUnicode_DATA(ascii);
391 for (i=0; i < ascii->length; i++)
392 {
393 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
394 if (ch > maxchar)
395 maxchar = ch;
396 }
397 if (kind == PyUnicode_1BYTE_KIND) {
398 if (ascii->state.ascii == 0)
399 assert(maxchar >= 128);
400 else
401 assert(maxchar < 128);
402 }
403 else if (kind == PyUnicode_2BYTE_KIND)
404 assert(maxchar >= 0x100);
405 else
406 assert(maxchar >= 0x10000);
407 }
Victor Stinner7931d9a2011-11-04 00:22:48 +0100408 if (check_content && !unicode_is_singleton(op))
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200409 assert(ascii->hash == -1);
Benjamin Petersonccc51c12011-10-03 19:34:12 -0400410 return 1;
411}
Victor Stinner910337b2011-10-03 03:20:16 +0200412#endif
413
Victor Stinner3a50e702011-10-18 21:21:00 +0200414#ifdef HAVE_MBCS
415static OSVERSIONINFOEX winver;
416#endif
417
Thomas Wouters477c8d52006-05-27 19:21:47 +0000418/* --- Bloom Filters ----------------------------------------------------- */
419
420/* stuff to implement simple "bloom filters" for Unicode characters.
421 to keep things simple, we use a single bitmask, using the least 5
422 bits from each unicode characters as the bit index. */
423
424/* the linebreak mask is set up by Unicode_Init below */
425
Antoine Pitrouf068f942010-01-13 14:19:12 +0000426#if LONG_BIT >= 128
427#define BLOOM_WIDTH 128
428#elif LONG_BIT >= 64
429#define BLOOM_WIDTH 64
430#elif LONG_BIT >= 32
431#define BLOOM_WIDTH 32
432#else
433#error "LONG_BIT is smaller than 32"
434#endif
435
Thomas Wouters477c8d52006-05-27 19:21:47 +0000436#define BLOOM_MASK unsigned long
437
438static BLOOM_MASK bloom_linebreak;
439
Antoine Pitrouf068f942010-01-13 14:19:12 +0000440#define BLOOM_ADD(mask, ch) ((mask |= (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
441#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000442
Benjamin Peterson29060642009-01-31 22:14:21 +0000443#define BLOOM_LINEBREAK(ch) \
444 ((ch) < 128U ? ascii_linebreak[(ch)] : \
445 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000446
Alexander Belopolsky40018472011-02-26 01:02:56 +0000447Py_LOCAL_INLINE(BLOOM_MASK)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200448make_bloom_mask(int kind, void* ptr, Py_ssize_t len)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000449{
450 /* calculate simple bloom-style bitmask for a given unicode string */
451
Antoine Pitrouf068f942010-01-13 14:19:12 +0000452 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000453 Py_ssize_t i;
454
455 mask = 0;
456 for (i = 0; i < len; i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200457 BLOOM_ADD(mask, PyUnicode_READ(kind, ptr, i));
Thomas Wouters477c8d52006-05-27 19:21:47 +0000458
459 return mask;
460}
461
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200462#define BLOOM_MEMBER(mask, chr, str) \
463 (BLOOM(mask, chr) \
464 && (PyUnicode_FindChar(str, chr, 0, PyUnicode_GET_LENGTH(str), 1) >= 0))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000465
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200466/* Compilation of templated routines */
467
468#include "stringlib/asciilib.h"
469#include "stringlib/fastsearch.h"
470#include "stringlib/partition.h"
471#include "stringlib/split.h"
472#include "stringlib/count.h"
473#include "stringlib/find.h"
474#include "stringlib/find_max_char.h"
475#include "stringlib/localeutil.h"
476#include "stringlib/undef.h"
477
478#include "stringlib/ucs1lib.h"
479#include "stringlib/fastsearch.h"
480#include "stringlib/partition.h"
481#include "stringlib/split.h"
482#include "stringlib/count.h"
483#include "stringlib/find.h"
484#include "stringlib/find_max_char.h"
485#include "stringlib/localeutil.h"
486#include "stringlib/undef.h"
487
488#include "stringlib/ucs2lib.h"
489#include "stringlib/fastsearch.h"
490#include "stringlib/partition.h"
491#include "stringlib/split.h"
492#include "stringlib/count.h"
493#include "stringlib/find.h"
494#include "stringlib/find_max_char.h"
495#include "stringlib/localeutil.h"
496#include "stringlib/undef.h"
497
498#include "stringlib/ucs4lib.h"
499#include "stringlib/fastsearch.h"
500#include "stringlib/partition.h"
501#include "stringlib/split.h"
502#include "stringlib/count.h"
503#include "stringlib/find.h"
504#include "stringlib/find_max_char.h"
505#include "stringlib/localeutil.h"
506#include "stringlib/undef.h"
507
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200508#include "stringlib/unicodedefs.h"
509#include "stringlib/fastsearch.h"
510#include "stringlib/count.h"
511#include "stringlib/find.h"
512
Guido van Rossumd57fd912000-03-10 22:53:23 +0000513/* --- Unicode Object ----------------------------------------------------- */
514
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200515static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +0200516fixup(PyObject *self, Py_UCS4 (*fixfct)(PyObject *s));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200517
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200518Py_LOCAL_INLINE(Py_ssize_t) findchar(void *s, int kind,
519 Py_ssize_t size, Py_UCS4 ch,
520 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200521{
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200522 int mode = (direction == 1) ? FAST_SEARCH : FAST_RSEARCH;
523
524 switch (kind) {
525 case PyUnicode_1BYTE_KIND:
526 {
527 Py_UCS1 ch1 = (Py_UCS1) ch;
528 if (ch1 == ch)
529 return ucs1lib_fastsearch((Py_UCS1 *) s, size, &ch1, 1, 0, mode);
530 else
531 return -1;
532 }
533 case PyUnicode_2BYTE_KIND:
534 {
535 Py_UCS2 ch2 = (Py_UCS2) ch;
536 if (ch2 == ch)
537 return ucs2lib_fastsearch((Py_UCS2 *) s, size, &ch2, 1, 0, mode);
538 else
539 return -1;
540 }
541 case PyUnicode_4BYTE_KIND:
542 return ucs4lib_fastsearch((Py_UCS4 *) s, size, &ch, 1, 0, mode);
543 default:
544 assert(0);
545 return -1;
Victor Stinner9e7a1bc2011-10-13 00:18:12 +0200546 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200547}
548
Victor Stinnerfe226c02011-10-03 03:52:20 +0200549static PyObject*
550resize_compact(PyObject *unicode, Py_ssize_t length)
551{
552 Py_ssize_t char_size;
553 Py_ssize_t struct_size;
554 Py_ssize_t new_size;
555 int share_wstr;
556
557 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200558 char_size = PyUnicode_KIND(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200559 if (PyUnicode_IS_COMPACT_ASCII(unicode))
560 struct_size = sizeof(PyASCIIObject);
561 else
562 struct_size = sizeof(PyCompactUnicodeObject);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200563 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200564
565 _Py_DEC_REFTOTAL;
566 _Py_ForgetReference(unicode);
567
568 if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
569 PyErr_NoMemory();
570 return NULL;
571 }
572 new_size = (struct_size + (length + 1) * char_size);
573
574 unicode = (PyObject *)PyObject_REALLOC((char *)unicode, new_size);
575 if (unicode == NULL) {
576 PyObject_Del(unicode);
577 PyErr_NoMemory();
578 return NULL;
579 }
580 _Py_NewReference(unicode);
581 _PyUnicode_LENGTH(unicode) = length;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200582 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200583 _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200584 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
585 _PyUnicode_WSTR_LENGTH(unicode) = length;
586 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200587 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
588 length, 0);
589 return unicode;
590}
591
Alexander Belopolsky40018472011-02-26 01:02:56 +0000592static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200593resize_inplace(PyObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000594{
Victor Stinner95663112011-10-04 01:03:50 +0200595 wchar_t *wstr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200596 assert(!PyUnicode_IS_COMPACT(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200597 assert(Py_REFCNT(unicode) == 1);
Tim Petersced69f82003-09-16 20:30:58 +0000598
Victor Stinner95663112011-10-04 01:03:50 +0200599 _PyUnicode_DIRTY(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200600
601 if (PyUnicode_IS_READY(unicode)) {
602 Py_ssize_t char_size;
603 Py_ssize_t new_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200604 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200605 void *data;
606
607 data = _PyUnicode_DATA_ANY(unicode);
608 assert(data != NULL);
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200609 char_size = PyUnicode_KIND(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200610 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
611 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinner95663112011-10-04 01:03:50 +0200612 if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
613 {
614 PyObject_DEL(_PyUnicode_UTF8(unicode));
615 _PyUnicode_UTF8(unicode) = NULL;
616 _PyUnicode_UTF8_LENGTH(unicode) = 0;
617 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200618
619 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
620 PyErr_NoMemory();
621 return -1;
622 }
623 new_size = (length + 1) * char_size;
624
625 data = (PyObject *)PyObject_REALLOC(data, new_size);
626 if (data == NULL) {
627 PyErr_NoMemory();
628 return -1;
629 }
630 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200631 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200632 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200633 _PyUnicode_WSTR_LENGTH(unicode) = length;
634 }
635 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200636 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200637 _PyUnicode_UTF8_LENGTH(unicode) = length;
638 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200639 _PyUnicode_LENGTH(unicode) = length;
640 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
Victor Stinner95663112011-10-04 01:03:50 +0200641 if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200642 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200643 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200644 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200645 }
Victor Stinner95663112011-10-04 01:03:50 +0200646 assert(_PyUnicode_WSTR(unicode) != NULL);
647
648 /* check for integer overflow */
649 if (length > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
650 PyErr_NoMemory();
651 return -1;
652 }
653 wstr = _PyUnicode_WSTR(unicode);
654 wstr = PyObject_REALLOC(wstr, sizeof(wchar_t) * (length + 1));
655 if (!wstr) {
656 PyErr_NoMemory();
657 return -1;
658 }
659 _PyUnicode_WSTR(unicode) = wstr;
660 _PyUnicode_WSTR(unicode)[length] = 0;
661 _PyUnicode_WSTR_LENGTH(unicode) = length;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200662 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000663 return 0;
664}
665
Victor Stinnerfe226c02011-10-03 03:52:20 +0200666static PyObject*
667resize_copy(PyObject *unicode, Py_ssize_t length)
668{
669 Py_ssize_t copy_length;
670 if (PyUnicode_IS_COMPACT(unicode)) {
671 PyObject *copy;
672 assert(PyUnicode_IS_READY(unicode));
673
674 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
675 if (copy == NULL)
676 return NULL;
677
678 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200679 copy_characters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200680 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +0200681 }
682 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200683 PyObject *w;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200684 assert(_PyUnicode_WSTR(unicode) != NULL);
685 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200686 w = (PyObject*)_PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200687 if (w == NULL)
688 return NULL;
689 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
690 copy_length = Py_MIN(copy_length, length);
691 Py_UNICODE_COPY(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
692 copy_length);
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200693 return w;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200694 }
695}
696
Guido van Rossumd57fd912000-03-10 22:53:23 +0000697/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +0000698 Ux0000 terminated; some code (e.g. new_identifier)
699 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000700
701 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +0000702 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000703
704*/
705
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200706#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +0200707static int unicode_old_new_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200708#endif
709
Alexander Belopolsky40018472011-02-26 01:02:56 +0000710static PyUnicodeObject *
711_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000712{
713 register PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200714 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000715
Thomas Wouters477c8d52006-05-27 19:21:47 +0000716 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +0000717 if (length == 0 && unicode_empty != NULL) {
718 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200719 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000720 }
721
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000722 /* Ensure we won't overflow the size. */
723 if (length > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
724 return (PyUnicodeObject *)PyErr_NoMemory();
725 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200726 if (length < 0) {
727 PyErr_SetString(PyExc_SystemError,
728 "Negative size passed to _PyUnicode_New");
729 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000730 }
731
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200732#ifdef Py_DEBUG
733 ++unicode_old_new_calls;
734#endif
735
736 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
737 if (unicode == NULL)
738 return NULL;
739 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
740 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
741 if (!_PyUnicode_WSTR(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000742 PyErr_NoMemory();
743 goto onError;
Guido van Rossum3c1bb802000-04-27 20:13:50 +0000744 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200745
Jeremy Hyltond8082792003-09-16 19:41:39 +0000746 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +0000747 * the caller fails before initializing str -- unicode_resize()
748 * reads str[0], and the Keep-Alive optimization can keep memory
749 * allocated for str alive across a call to unicode_dealloc(unicode).
750 * We don't want unicode_resize to read uninitialized memory in
751 * that case.
752 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200753 _PyUnicode_WSTR(unicode)[0] = 0;
754 _PyUnicode_WSTR(unicode)[length] = 0;
755 _PyUnicode_WSTR_LENGTH(unicode) = length;
756 _PyUnicode_HASH(unicode) = -1;
757 _PyUnicode_STATE(unicode).interned = 0;
758 _PyUnicode_STATE(unicode).kind = 0;
759 _PyUnicode_STATE(unicode).compact = 0;
760 _PyUnicode_STATE(unicode).ready = 0;
761 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +0200762 _PyUnicode_DATA_ANY(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200763 _PyUnicode_LENGTH(unicode) = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200764 _PyUnicode_UTF8(unicode) = NULL;
765 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner7931d9a2011-11-04 00:22:48 +0100766 assert(_PyUnicode_CheckConsistency((PyObject *)unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000767 return unicode;
Barry Warsaw51ac5802000-03-20 16:36:48 +0000768
Benjamin Peterson29060642009-01-31 22:14:21 +0000769 onError:
Amaury Forgeot d'Arc7888d082008-08-01 01:06:32 +0000770 /* XXX UNREF/NEWREF interface should be more symmetrical */
771 _Py_DEC_REFTOTAL;
Barry Warsaw51ac5802000-03-20 16:36:48 +0000772 _Py_ForgetReference((PyObject *)unicode);
Neil Schemenauer58aa8612002-04-12 03:07:20 +0000773 PyObject_Del(unicode);
Barry Warsaw51ac5802000-03-20 16:36:48 +0000774 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000775}
776
Victor Stinnerf42dc442011-10-02 23:33:16 +0200777static const char*
778unicode_kind_name(PyObject *unicode)
779{
Victor Stinner42dfd712011-10-03 14:41:45 +0200780 /* don't check consistency: unicode_kind_name() is called from
781 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +0200782 if (!PyUnicode_IS_COMPACT(unicode))
783 {
784 if (!PyUnicode_IS_READY(unicode))
785 return "wstr";
786 switch(PyUnicode_KIND(unicode))
787 {
788 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200789 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200790 return "legacy ascii";
791 else
792 return "legacy latin1";
793 case PyUnicode_2BYTE_KIND:
794 return "legacy UCS2";
795 case PyUnicode_4BYTE_KIND:
796 return "legacy UCS4";
797 default:
798 return "<legacy invalid kind>";
799 }
800 }
801 assert(PyUnicode_IS_READY(unicode));
802 switch(PyUnicode_KIND(unicode))
803 {
804 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200805 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200806 return "ascii";
807 else
Victor Stinnera3b334d2011-10-03 13:53:37 +0200808 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200809 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200810 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200811 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200812 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200813 default:
814 return "<invalid compact kind>";
815 }
816}
817
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200818#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +0200819static int unicode_new_new_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200820
821/* Functions wrapping macros for use in debugger */
822char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200823 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200824}
825
826void *_PyUnicode_compact_data(void *unicode) {
827 return _PyUnicode_COMPACT_DATA(unicode);
828}
829void *_PyUnicode_data(void *unicode){
830 printf("obj %p\n", unicode);
831 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
832 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
833 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
834 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
835 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
836 return PyUnicode_DATA(unicode);
837}
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200838
839void
840_PyUnicode_Dump(PyObject *op)
841{
842 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +0200843 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
844 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
845 void *data;
Victor Stinner0d60e872011-10-23 19:47:19 +0200846
Victor Stinnera849a4b2011-10-03 12:12:11 +0200847 if (ascii->state.compact)
Victor Stinner0d60e872011-10-23 19:47:19 +0200848 {
849 if (ascii->state.ascii)
850 data = (ascii + 1);
851 else
852 data = (compact + 1);
853 }
Victor Stinnera849a4b2011-10-03 12:12:11 +0200854 else
855 data = unicode->data.any;
Victor Stinner0d60e872011-10-23 19:47:19 +0200856 printf("%s: len=%zu, ",unicode_kind_name(op), ascii->length);
857
Victor Stinnera849a4b2011-10-03 12:12:11 +0200858 if (ascii->wstr == data)
859 printf("shared ");
860 printf("wstr=%p", ascii->wstr);
Victor Stinner0d60e872011-10-23 19:47:19 +0200861
Victor Stinnera3b334d2011-10-03 13:53:37 +0200862 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinnera849a4b2011-10-03 12:12:11 +0200863 printf(" (%zu), ", compact->wstr_length);
864 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
865 printf("shared ");
866 printf("utf8=%p (%zu)", compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200867 }
Victor Stinnera849a4b2011-10-03 12:12:11 +0200868 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200869}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200870#endif
871
872PyObject *
873PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
874{
875 PyObject *obj;
876 PyCompactUnicodeObject *unicode;
877 void *data;
878 int kind_state;
Victor Stinner9e9d6892011-10-04 01:02:02 +0200879 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200880 Py_ssize_t char_size;
881 Py_ssize_t struct_size;
882
883 /* Optimization for empty strings */
884 if (size == 0 && unicode_empty != NULL) {
885 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200886 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200887 }
888
889#ifdef Py_DEBUG
890 ++unicode_new_new_calls;
891#endif
892
Victor Stinner9e9d6892011-10-04 01:02:02 +0200893 is_ascii = 0;
894 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200895 struct_size = sizeof(PyCompactUnicodeObject);
896 if (maxchar < 128) {
897 kind_state = PyUnicode_1BYTE_KIND;
898 char_size = 1;
899 is_ascii = 1;
900 struct_size = sizeof(PyASCIIObject);
901 }
902 else if (maxchar < 256) {
903 kind_state = PyUnicode_1BYTE_KIND;
904 char_size = 1;
905 }
906 else if (maxchar < 65536) {
907 kind_state = PyUnicode_2BYTE_KIND;
908 char_size = 2;
909 if (sizeof(wchar_t) == 2)
910 is_sharing = 1;
911 }
912 else {
913 kind_state = PyUnicode_4BYTE_KIND;
914 char_size = 4;
915 if (sizeof(wchar_t) == 4)
916 is_sharing = 1;
917 }
918
919 /* Ensure we won't overflow the size. */
920 if (size < 0) {
921 PyErr_SetString(PyExc_SystemError,
922 "Negative size passed to PyUnicode_New");
923 return NULL;
924 }
925 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
926 return PyErr_NoMemory();
927
928 /* Duplicated allocation code from _PyObject_New() instead of a call to
929 * PyObject_New() so we are able to allocate space for the object and
930 * it's data buffer.
931 */
932 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
933 if (obj == NULL)
934 return PyErr_NoMemory();
935 obj = PyObject_INIT(obj, &PyUnicode_Type);
936 if (obj == NULL)
937 return NULL;
938
939 unicode = (PyCompactUnicodeObject *)obj;
940 if (is_ascii)
941 data = ((PyASCIIObject*)obj) + 1;
942 else
943 data = unicode + 1;
944 _PyUnicode_LENGTH(unicode) = size;
945 _PyUnicode_HASH(unicode) = -1;
946 _PyUnicode_STATE(unicode).interned = 0;
947 _PyUnicode_STATE(unicode).kind = kind_state;
948 _PyUnicode_STATE(unicode).compact = 1;
949 _PyUnicode_STATE(unicode).ready = 1;
950 _PyUnicode_STATE(unicode).ascii = is_ascii;
951 if (is_ascii) {
952 ((char*)data)[size] = 0;
953 _PyUnicode_WSTR(unicode) = NULL;
954 }
955 else if (kind_state == PyUnicode_1BYTE_KIND) {
956 ((char*)data)[size] = 0;
957 _PyUnicode_WSTR(unicode) = NULL;
958 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200959 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +0200960 unicode->utf8_length = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200961 }
962 else {
963 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +0200964 unicode->utf8_length = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200965 if (kind_state == PyUnicode_2BYTE_KIND)
966 ((Py_UCS2*)data)[size] = 0;
967 else /* kind_state == PyUnicode_4BYTE_KIND */
968 ((Py_UCS4*)data)[size] = 0;
969 if (is_sharing) {
970 _PyUnicode_WSTR_LENGTH(unicode) = size;
971 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
972 }
973 else {
974 _PyUnicode_WSTR_LENGTH(unicode) = 0;
975 _PyUnicode_WSTR(unicode) = NULL;
976 }
977 }
Victor Stinner7931d9a2011-11-04 00:22:48 +0100978 assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200979 return obj;
980}
981
982#if SIZEOF_WCHAR_T == 2
983/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
984 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +0200985 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200986
987 This function assumes that unicode can hold one more code point than wstr
988 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +0200989static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200990unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200991 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200992{
993 const wchar_t *iter;
994 Py_UCS4 *ucs4_out;
995
Victor Stinner910337b2011-10-03 03:20:16 +0200996 assert(unicode != NULL);
997 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200998 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
999 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
1000
1001 for (iter = begin; iter < end; ) {
1002 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1003 _PyUnicode_GET_LENGTH(unicode)));
1004 if (*iter >= 0xD800 && *iter <= 0xDBFF
1005 && (iter+1) < end && iter[1] >= 0xDC00 && iter[1] <= 0xDFFF)
1006 {
1007 *ucs4_out++ = (((iter[0] & 0x3FF)<<10) | (iter[1] & 0x3FF)) + 0x10000;
1008 iter += 2;
1009 }
1010 else {
1011 *ucs4_out++ = *iter;
1012 iter++;
1013 }
1014 }
1015 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1016 _PyUnicode_GET_LENGTH(unicode)));
1017
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001018}
1019#endif
1020
Victor Stinnercd9950f2011-10-02 00:34:53 +02001021static int
1022_PyUnicode_Dirty(PyObject *unicode)
1023{
Victor Stinner910337b2011-10-03 03:20:16 +02001024 assert(_PyUnicode_CHECK(unicode));
Victor Stinnercd9950f2011-10-02 00:34:53 +02001025 if (Py_REFCNT(unicode) != 1) {
Victor Stinner01698042011-10-04 00:04:26 +02001026 PyErr_SetString(PyExc_SystemError,
Victor Stinnercd9950f2011-10-02 00:34:53 +02001027 "Cannot modify a string having more than 1 reference");
1028 return -1;
1029 }
1030 _PyUnicode_DIRTY(unicode);
1031 return 0;
1032}
1033
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001034static int
1035_copy_characters(PyObject *to, Py_ssize_t to_start,
1036 PyObject *from, Py_ssize_t from_start,
1037 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001038{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001039 unsigned int from_kind, to_kind;
1040 void *from_data, *to_data;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001041 int fast;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001042
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001043 assert(PyUnicode_Check(from));
1044 assert(PyUnicode_Check(to));
1045 assert(PyUnicode_IS_READY(from));
1046 assert(PyUnicode_IS_READY(to));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001047
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001048 assert(PyUnicode_GET_LENGTH(from) >= how_many);
1049 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1050 assert(0 <= how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001051
Victor Stinnerf5ca1a22011-09-28 23:54:59 +02001052 if (how_many == 0)
1053 return 0;
1054
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001055 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001056 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001057 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001058 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001059
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001060#ifdef Py_DEBUG
1061 if (!check_maxchar
1062 && (from_kind > to_kind
1063 || (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001064 {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001065 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1066 Py_UCS4 ch;
1067 Py_ssize_t i;
1068 for (i=0; i < how_many; i++) {
1069 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1070 assert(ch <= to_maxchar);
1071 }
1072 }
1073#endif
1074 fast = (from_kind == to_kind);
1075 if (check_maxchar
1076 && (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to)))
1077 {
1078 /* deny latin1 => ascii */
1079 fast = 0;
1080 }
1081
1082 if (fast) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001083 Py_MEMCPY((char*)to_data + to_kind * to_start,
1084 (char*)from_data + from_kind * from_start,
1085 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001086 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001087 else if (from_kind == PyUnicode_1BYTE_KIND
1088 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001089 {
1090 _PyUnicode_CONVERT_BYTES(
1091 Py_UCS1, Py_UCS2,
1092 PyUnicode_1BYTE_DATA(from) + from_start,
1093 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1094 PyUnicode_2BYTE_DATA(to) + to_start
1095 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001096 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001097 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001098 && to_kind == PyUnicode_4BYTE_KIND)
1099 {
1100 _PyUnicode_CONVERT_BYTES(
1101 Py_UCS1, Py_UCS4,
1102 PyUnicode_1BYTE_DATA(from) + from_start,
1103 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1104 PyUnicode_4BYTE_DATA(to) + to_start
1105 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001106 }
1107 else if (from_kind == PyUnicode_2BYTE_KIND
1108 && to_kind == PyUnicode_4BYTE_KIND)
1109 {
1110 _PyUnicode_CONVERT_BYTES(
1111 Py_UCS2, Py_UCS4,
1112 PyUnicode_2BYTE_DATA(from) + from_start,
1113 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1114 PyUnicode_4BYTE_DATA(to) + to_start
1115 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001116 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001117 else {
Victor Stinnerf42dc442011-10-02 23:33:16 +02001118 /* check if max_char(from substring) <= max_char(to) */
1119 if (from_kind > to_kind
1120 /* latin1 => ascii */
Victor Stinnerb9275c12011-10-05 14:01:42 +02001121 || (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to)))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001122 {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001123 /* slow path to check for character overflow */
1124 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001125 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001126 Py_ssize_t i;
1127
Victor Stinner56c161a2011-10-06 02:47:11 +02001128#ifdef Py_DEBUG
Victor Stinnera0702ab2011-09-29 14:14:38 +02001129 for (i=0; i < how_many; i++) {
1130 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinner56c161a2011-10-06 02:47:11 +02001131 assert(ch <= to_maxchar);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001132 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1133 }
Victor Stinner56c161a2011-10-06 02:47:11 +02001134#else
1135 if (!check_maxchar) {
1136 for (i=0; i < how_many; i++) {
1137 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1138 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1139 }
1140 }
1141 else {
1142 for (i=0; i < how_many; i++) {
1143 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1144 if (ch > to_maxchar)
1145 return 1;
1146 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1147 }
1148 }
1149#endif
Victor Stinnera0702ab2011-09-29 14:14:38 +02001150 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001151 else {
Victor Stinner56c161a2011-10-06 02:47:11 +02001152 assert(0 && "inconsistent state");
1153 return 1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001154 }
1155 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001156 return 0;
1157}
1158
1159static void
1160copy_characters(PyObject *to, Py_ssize_t to_start,
1161 PyObject *from, Py_ssize_t from_start,
1162 Py_ssize_t how_many)
1163{
1164 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1165}
1166
1167Py_ssize_t
1168PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1169 PyObject *from, Py_ssize_t from_start,
1170 Py_ssize_t how_many)
1171{
1172 int err;
1173
1174 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1175 PyErr_BadInternalCall();
1176 return -1;
1177 }
1178
1179 if (PyUnicode_READY(from))
1180 return -1;
1181 if (PyUnicode_READY(to))
1182 return -1;
1183
1184 how_many = Py_MIN(PyUnicode_GET_LENGTH(from), how_many);
1185 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1186 PyErr_Format(PyExc_SystemError,
1187 "Cannot write %zi characters at %zi "
1188 "in a string of %zi characters",
1189 how_many, to_start, PyUnicode_GET_LENGTH(to));
1190 return -1;
1191 }
1192
1193 if (how_many == 0)
1194 return 0;
1195
1196 if (_PyUnicode_Dirty(to))
1197 return -1;
1198
1199 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1200 if (err) {
1201 PyErr_Format(PyExc_SystemError,
1202 "Cannot copy %s characters "
1203 "into a string of %s characters",
1204 unicode_kind_name(from),
1205 unicode_kind_name(to));
1206 return -1;
1207 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001208 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001209}
1210
Victor Stinner17222162011-09-28 22:15:37 +02001211/* Find the maximum code point and count the number of surrogate pairs so a
1212 correct string length can be computed before converting a string to UCS4.
1213 This function counts single surrogates as a character and not as a pair.
1214
1215 Return 0 on success, or -1 on error. */
1216static int
1217find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1218 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001219{
1220 const wchar_t *iter;
1221
Victor Stinnerc53be962011-10-02 21:33:54 +02001222 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001223 *num_surrogates = 0;
1224 *maxchar = 0;
1225
1226 for (iter = begin; iter < end; ) {
Victor Stinnerae864852011-10-05 14:02:44 +02001227 if (*iter > *maxchar) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001228 *maxchar = *iter;
Victor Stinnerae864852011-10-05 14:02:44 +02001229#if SIZEOF_WCHAR_T != 2
1230 if (*maxchar >= 0x10000)
1231 return 0;
1232#endif
1233 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001234#if SIZEOF_WCHAR_T == 2
1235 if (*iter >= 0xD800 && *iter <= 0xDBFF
1236 && (iter+1) < end && iter[1] >= 0xDC00 && iter[1] <= 0xDFFF)
1237 {
1238 Py_UCS4 surrogate_val;
1239 surrogate_val = (((iter[0] & 0x3FF)<<10)
1240 | (iter[1] & 0x3FF)) + 0x10000;
1241 ++(*num_surrogates);
1242 if (surrogate_val > *maxchar)
1243 *maxchar = surrogate_val;
1244 iter += 2;
1245 }
1246 else
1247 iter++;
1248#else
1249 iter++;
1250#endif
1251 }
1252 return 0;
1253}
1254
1255#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +02001256static int unicode_ready_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001257#endif
1258
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001259static int
1260unicode_ready(PyObject **p_obj, int replace)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001261{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001262 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001263 wchar_t *end;
1264 Py_UCS4 maxchar = 0;
1265 Py_ssize_t num_surrogates;
1266#if SIZEOF_WCHAR_T == 2
1267 Py_ssize_t length_wo_surrogates;
1268#endif
1269
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001270 assert(p_obj != NULL);
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001271 unicode = *p_obj;
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001272
Georg Brandl7597add2011-10-05 16:36:47 +02001273 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001274 strings were created using _PyObject_New() and where no canonical
1275 representation (the str field) has been set yet aka strings
1276 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001277 assert(_PyUnicode_CHECK(unicode));
1278 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001279 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001280 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001281 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001282 /* Actually, it should neither be interned nor be anything else: */
1283 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001284
1285#ifdef Py_DEBUG
1286 ++unicode_ready_calls;
1287#endif
1288
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001289#ifdef Py_DEBUG
1290 assert(!replace || Py_REFCNT(unicode) == 1);
1291#else
1292 if (replace && Py_REFCNT(unicode) != 1)
1293 replace = 0;
1294#endif
1295 if (replace) {
1296 Py_ssize_t len = _PyUnicode_WSTR_LENGTH(unicode);
1297 wchar_t *wstr = _PyUnicode_WSTR(unicode);
1298 /* Optimization for empty strings */
1299 if (len == 0) {
1300 Py_INCREF(unicode_empty);
1301 Py_DECREF(*p_obj);
1302 *p_obj = unicode_empty;
1303 return 0;
1304 }
1305 if (len == 1 && wstr[0] < 256) {
1306 PyObject *latin1_char = get_latin1_char((unsigned char)wstr[0]);
1307 if (latin1_char == NULL)
1308 return -1;
1309 Py_DECREF(*p_obj);
1310 *p_obj = latin1_char;
1311 return 0;
1312 }
1313 }
1314
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001315 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001316 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001317 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001318 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001319
1320 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001321 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1322 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001323 PyErr_NoMemory();
1324 return -1;
1325 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001326 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001327 _PyUnicode_WSTR(unicode), end,
1328 PyUnicode_1BYTE_DATA(unicode));
1329 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1330 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1331 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1332 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001333 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001334 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001335 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001336 }
1337 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001338 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001339 _PyUnicode_UTF8(unicode) = NULL;
1340 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001341 }
1342 PyObject_FREE(_PyUnicode_WSTR(unicode));
1343 _PyUnicode_WSTR(unicode) = NULL;
1344 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1345 }
1346 /* In this case we might have to convert down from 4-byte native
1347 wchar_t to 2-byte unicode. */
1348 else if (maxchar < 65536) {
1349 assert(num_surrogates == 0 &&
1350 "FindMaxCharAndNumSurrogatePairs() messed up");
1351
Victor Stinner506f5922011-09-28 22:34:18 +02001352#if SIZEOF_WCHAR_T == 2
1353 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001354 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001355 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1356 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1357 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001358 _PyUnicode_UTF8(unicode) = NULL;
1359 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001360#else
1361 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001362 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001363 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001364 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001365 PyErr_NoMemory();
1366 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001367 }
Victor Stinner506f5922011-09-28 22:34:18 +02001368 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1369 _PyUnicode_WSTR(unicode), end,
1370 PyUnicode_2BYTE_DATA(unicode));
1371 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1372 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1373 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001374 _PyUnicode_UTF8(unicode) = NULL;
1375 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001376 PyObject_FREE(_PyUnicode_WSTR(unicode));
1377 _PyUnicode_WSTR(unicode) = NULL;
1378 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1379#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001380 }
1381 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1382 else {
1383#if SIZEOF_WCHAR_T == 2
1384 /* in case the native representation is 2-bytes, we need to allocate a
1385 new normalized 4-byte version. */
1386 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001387 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1388 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001389 PyErr_NoMemory();
1390 return -1;
1391 }
1392 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1393 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001394 _PyUnicode_UTF8(unicode) = NULL;
1395 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001396 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1397 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001398 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001399 PyObject_FREE(_PyUnicode_WSTR(unicode));
1400 _PyUnicode_WSTR(unicode) = NULL;
1401 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1402#else
1403 assert(num_surrogates == 0);
1404
Victor Stinnerc3c74152011-10-02 20:39:55 +02001405 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001406 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001407 _PyUnicode_UTF8(unicode) = NULL;
1408 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001409 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1410#endif
1411 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1412 }
1413 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001414 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001415 return 0;
1416}
1417
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001418int
1419_PyUnicode_ReadyReplace(PyObject **op)
1420{
1421 return unicode_ready(op, 1);
1422}
1423
1424int
1425_PyUnicode_Ready(PyObject *op)
1426{
1427 return unicode_ready(&op, 0);
1428}
1429
Alexander Belopolsky40018472011-02-26 01:02:56 +00001430static void
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001431unicode_dealloc(register PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001432{
Walter Dörwald16807132007-05-25 13:52:07 +00001433 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001434 case SSTATE_NOT_INTERNED:
1435 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001436
Benjamin Peterson29060642009-01-31 22:14:21 +00001437 case SSTATE_INTERNED_MORTAL:
1438 /* revive dead object temporarily for DelItem */
1439 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001440 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001441 Py_FatalError(
1442 "deletion of interned string failed");
1443 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001444
Benjamin Peterson29060642009-01-31 22:14:21 +00001445 case SSTATE_INTERNED_IMMORTAL:
1446 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001447
Benjamin Peterson29060642009-01-31 22:14:21 +00001448 default:
1449 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001450 }
1451
Victor Stinner03490912011-10-03 23:45:12 +02001452 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001453 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001454 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001455 PyObject_DEL(_PyUnicode_UTF8(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001456
1457 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinner7931d9a2011-11-04 00:22:48 +01001458 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001459 }
1460 else {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001461 if (_PyUnicode_DATA_ANY(unicode))
1462 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Victor Stinner7931d9a2011-11-04 00:22:48 +01001463 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001464 }
1465}
1466
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001467#ifdef Py_DEBUG
1468static int
1469unicode_is_singleton(PyObject *unicode)
1470{
1471 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1472 if (unicode == unicode_empty)
1473 return 1;
1474 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1475 {
1476 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1477 if (ch < 256 && unicode_latin1[ch] == unicode)
1478 return 1;
1479 }
1480 return 0;
1481}
1482#endif
1483
Alexander Belopolsky40018472011-02-26 01:02:56 +00001484static int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001485unicode_resizable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001486{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001487 if (Py_REFCNT(unicode) != 1)
1488 return 0;
1489 if (PyUnicode_CHECK_INTERNED(unicode))
1490 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001491#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001492 /* singleton refcount is greater than 1 */
1493 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001494#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001495 return 1;
1496}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001497
Victor Stinnerfe226c02011-10-03 03:52:20 +02001498static int
1499unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1500{
1501 PyObject *unicode;
1502 Py_ssize_t old_length;
1503
1504 assert(p_unicode != NULL);
1505 unicode = *p_unicode;
1506
1507 assert(unicode != NULL);
1508 assert(PyUnicode_Check(unicode));
1509 assert(0 <= length);
1510
Victor Stinner910337b2011-10-03 03:20:16 +02001511 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001512 old_length = PyUnicode_WSTR_LENGTH(unicode);
1513 else
1514 old_length = PyUnicode_GET_LENGTH(unicode);
1515 if (old_length == length)
1516 return 0;
1517
Victor Stinnerfe226c02011-10-03 03:52:20 +02001518 if (!unicode_resizable(unicode)) {
1519 PyObject *copy = resize_copy(unicode, length);
1520 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001521 return -1;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001522 Py_DECREF(*p_unicode);
1523 *p_unicode = copy;
Benjamin Peterson29060642009-01-31 22:14:21 +00001524 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001525 }
1526
Victor Stinnerfe226c02011-10-03 03:52:20 +02001527 if (PyUnicode_IS_COMPACT(unicode)) {
1528 *p_unicode = resize_compact(unicode, length);
1529 if (*p_unicode == NULL)
1530 return -1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001531 assert(_PyUnicode_CheckConsistency(*p_unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001532 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001533 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001534 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001535}
1536
Alexander Belopolsky40018472011-02-26 01:02:56 +00001537int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001538PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001539{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001540 PyObject *unicode;
1541 if (p_unicode == NULL) {
1542 PyErr_BadInternalCall();
1543 return -1;
1544 }
1545 unicode = *p_unicode;
1546 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0
1547 || _PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND)
1548 {
1549 PyErr_BadInternalCall();
1550 return -1;
1551 }
1552 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001553}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001554
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001555static PyObject*
1556get_latin1_char(unsigned char ch)
1557{
Victor Stinnera464fc12011-10-02 20:39:30 +02001558 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001559 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001560 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001561 if (!unicode)
1562 return NULL;
1563 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001564 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001565 unicode_latin1[ch] = unicode;
1566 }
1567 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001568 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001569}
1570
Alexander Belopolsky40018472011-02-26 01:02:56 +00001571PyObject *
1572PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001573{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001574 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001575 Py_UCS4 maxchar = 0;
1576 Py_ssize_t num_surrogates;
1577
1578 if (u == NULL)
1579 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001580
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001581 /* If the Unicode data is known at construction time, we can apply
1582 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001583
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001584 /* Optimization for empty strings */
1585 if (size == 0 && unicode_empty != NULL) {
1586 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001587 return unicode_empty;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001588 }
Tim Petersced69f82003-09-16 20:30:58 +00001589
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001590 /* Single character Unicode objects in the Latin-1 range are
1591 shared when using this constructor */
1592 if (size == 1 && *u < 256)
1593 return get_latin1_char((unsigned char)*u);
1594
1595 /* If not empty and not single character, copy the Unicode data
1596 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02001597 if (find_maxchar_surrogates(u, u + size,
1598 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001599 return NULL;
1600
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001601 unicode = PyUnicode_New(size - num_surrogates,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001602 maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001603 if (!unicode)
1604 return NULL;
1605
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001606 switch (PyUnicode_KIND(unicode)) {
1607 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001608 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001609 u, u + size, PyUnicode_1BYTE_DATA(unicode));
1610 break;
1611 case PyUnicode_2BYTE_KIND:
1612#if Py_UNICODE_SIZE == 2
1613 Py_MEMCPY(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
1614#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001615 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001616 u, u + size, PyUnicode_2BYTE_DATA(unicode));
1617#endif
1618 break;
1619 case PyUnicode_4BYTE_KIND:
1620#if SIZEOF_WCHAR_T == 2
1621 /* This is the only case which has to process surrogates, thus
1622 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001623 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001624#else
1625 assert(num_surrogates == 0);
1626 Py_MEMCPY(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
1627#endif
1628 break;
1629 default:
1630 assert(0 && "Impossible state");
1631 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001632
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001633 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001634 return unicode;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001635}
1636
Alexander Belopolsky40018472011-02-26 01:02:56 +00001637PyObject *
1638PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001639{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001640 if (size < 0) {
1641 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00001642 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00001643 return NULL;
1644 }
Christian Heimes33fe8092008-04-13 13:53:33 +00001645
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001646 /* If the Unicode data is known at construction time, we can apply
Martin v. Löwis9c121062007-08-05 20:26:11 +00001647 some optimizations which share commonly used objects.
1648 Also, this means the input must be UTF-8, so fall back to the
1649 UTF-8 decoder at the end. */
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001650 if (u != NULL) {
1651
Benjamin Peterson29060642009-01-31 22:14:21 +00001652 /* Optimization for empty strings */
1653 if (size == 0 && unicode_empty != NULL) {
1654 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001655 return unicode_empty;
Benjamin Peterson14339b62009-01-31 16:36:08 +00001656 }
Benjamin Peterson29060642009-01-31 22:14:21 +00001657
1658 /* Single characters are shared when using this constructor.
1659 Restrict to ASCII, since the input must be UTF-8. */
Victor Stinner9faa3842011-10-23 20:06:00 +02001660 if (size == 1 && (unsigned char)*u < 128)
1661 return get_latin1_char((unsigned char)*u);
Martin v. Löwis9c121062007-08-05 20:26:11 +00001662
1663 return PyUnicode_DecodeUTF8(u, size, NULL);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001664 }
1665
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001666 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001667}
1668
Alexander Belopolsky40018472011-02-26 01:02:56 +00001669PyObject *
1670PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00001671{
1672 size_t size = strlen(u);
1673 if (size > PY_SSIZE_T_MAX) {
1674 PyErr_SetString(PyExc_OverflowError, "input too long");
1675 return NULL;
1676 }
1677
1678 return PyUnicode_FromStringAndSize(u, size);
1679}
1680
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001681PyObject *
1682_PyUnicode_FromId(_Py_Identifier *id)
1683{
1684 if (!id->object) {
1685 id->object = PyUnicode_FromString(id->string);
1686 if (!id->object)
1687 return NULL;
1688 PyUnicode_InternInPlace(&id->object);
1689 assert(!id->next);
1690 id->next = static_strings;
1691 static_strings = id;
1692 }
1693 Py_INCREF(id->object);
1694 return id->object;
1695}
1696
1697void
1698_PyUnicode_ClearStaticStrings()
1699{
1700 _Py_Identifier *i;
1701 for (i = static_strings; i; i = i->next) {
1702 Py_DECREF(i->object);
1703 i->object = NULL;
1704 i->next = NULL;
1705 }
1706}
1707
Victor Stinnere57b1c02011-09-28 22:20:48 +02001708static PyObject*
Victor Stinner0617b6e2011-10-05 23:26:01 +02001709unicode_fromascii(const unsigned char* s, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02001710{
Victor Stinner0617b6e2011-10-05 23:26:01 +02001711 PyObject *res;
1712#ifdef Py_DEBUG
1713 const unsigned char *p;
1714 const unsigned char *end = s + size;
1715 for (p=s; p < end; p++) {
1716 assert(*p < 128);
1717 }
1718#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001719 if (size == 1)
1720 return get_latin1_char(s[0]);
Victor Stinner0617b6e2011-10-05 23:26:01 +02001721 res = PyUnicode_New(size, 127);
Victor Stinner702c7342011-10-05 13:50:52 +02001722 if (!res)
1723 return NULL;
Victor Stinner0617b6e2011-10-05 23:26:01 +02001724 memcpy(PyUnicode_1BYTE_DATA(res), s, size);
Victor Stinner702c7342011-10-05 13:50:52 +02001725 return res;
1726}
1727
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001728static Py_UCS4
1729kind_maxchar_limit(unsigned int kind)
1730{
1731 switch(kind) {
1732 case PyUnicode_1BYTE_KIND:
1733 return 0x80;
1734 case PyUnicode_2BYTE_KIND:
1735 return 0x100;
1736 case PyUnicode_4BYTE_KIND:
1737 return 0x10000;
1738 default:
1739 assert(0 && "invalid kind");
1740 return 0x10ffff;
1741 }
1742}
1743
Victor Stinner702c7342011-10-05 13:50:52 +02001744static PyObject*
Victor Stinnere57b1c02011-09-28 22:20:48 +02001745_PyUnicode_FromUCS1(const unsigned char* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00001746{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001747 PyObject *res;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001748 unsigned char max_char = 127;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001749
1750 assert(size >= 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001751 if (size == 1)
1752 return get_latin1_char(u[0]);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001753 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001754 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001755 if (!res)
1756 return NULL;
1757 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001758 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001759 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001760}
1761
Victor Stinnere57b1c02011-09-28 22:20:48 +02001762static PyObject*
1763_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001764{
1765 PyObject *res;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001766 Py_UCS2 max_char = 0;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001767
1768 assert(size >= 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001769 if (size == 1 && u[0] < 256)
Victor Stinner4e101002011-10-11 23:27:52 +02001770 return get_latin1_char((unsigned char)u[0]);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001771 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001772 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001773 if (!res)
1774 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001775 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001776 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001777 else {
1778 _PyUnicode_CONVERT_BYTES(
1779 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
1780 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001781 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001782 return res;
1783}
1784
Victor Stinnere57b1c02011-09-28 22:20:48 +02001785static PyObject*
1786_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001787{
1788 PyObject *res;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001789 Py_UCS4 max_char = 0;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001790
1791 assert(size >= 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001792 if (size == 1 && u[0] < 256)
1793 return get_latin1_char(u[0]);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001794 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001795 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001796 if (!res)
1797 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02001798 if (max_char < 256)
1799 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
1800 PyUnicode_1BYTE_DATA(res));
1801 else if (max_char < 0x10000)
1802 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
1803 PyUnicode_2BYTE_DATA(res));
1804 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001805 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001806 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001807 return res;
1808}
1809
1810PyObject*
1811PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
1812{
1813 switch(kind) {
1814 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001815 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001816 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001817 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001818 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001819 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001820 default:
1821 assert(0 && "invalid kind");
1822 PyErr_SetString(PyExc_SystemError, "invalid kind");
1823 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001824 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001825}
1826
Victor Stinner25a4b292011-10-06 12:31:55 +02001827/* Ensure that a string uses the most efficient storage, if it is not the
1828 case: create a new string with of the right kind. Write NULL into *p_unicode
1829 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02001830static void
Victor Stinner25a4b292011-10-06 12:31:55 +02001831unicode_adjust_maxchar(PyObject **p_unicode)
1832{
1833 PyObject *unicode, *copy;
1834 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001835 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02001836 unsigned int kind;
1837
1838 assert(p_unicode != NULL);
1839 unicode = *p_unicode;
1840 assert(PyUnicode_IS_READY(unicode));
1841 if (PyUnicode_IS_ASCII(unicode))
1842 return;
1843
1844 len = PyUnicode_GET_LENGTH(unicode);
1845 kind = PyUnicode_KIND(unicode);
1846 if (kind == PyUnicode_1BYTE_KIND) {
1847 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001848 max_char = ucs1lib_find_max_char(u, u + len);
1849 if (max_char >= 128)
1850 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001851 }
1852 else if (kind == PyUnicode_2BYTE_KIND) {
1853 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001854 max_char = ucs2lib_find_max_char(u, u + len);
1855 if (max_char >= 256)
1856 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001857 }
1858 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001859 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02001860 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001861 max_char = ucs4lib_find_max_char(u, u + len);
1862 if (max_char >= 0x10000)
1863 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001864 }
Victor Stinner25a4b292011-10-06 12:31:55 +02001865 copy = PyUnicode_New(len, max_char);
1866 copy_characters(copy, 0, unicode, 0, len);
1867 Py_DECREF(unicode);
1868 *p_unicode = copy;
1869}
1870
Victor Stinner034f6cf2011-09-30 02:26:44 +02001871PyObject*
1872PyUnicode_Copy(PyObject *unicode)
1873{
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001874 Py_ssize_t size;
1875 PyObject *copy;
1876 void *data;
1877
Victor Stinner034f6cf2011-09-30 02:26:44 +02001878 if (!PyUnicode_Check(unicode)) {
1879 PyErr_BadInternalCall();
1880 return NULL;
1881 }
1882 if (PyUnicode_READY(unicode))
1883 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001884
1885 size = PyUnicode_GET_LENGTH(unicode);
1886 copy = PyUnicode_New(size, PyUnicode_MAX_CHAR_VALUE(unicode));
1887 if (!copy)
1888 return NULL;
1889 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
1890
1891 data = PyUnicode_DATA(unicode);
1892 switch (PyUnicode_KIND(unicode))
1893 {
1894 case PyUnicode_1BYTE_KIND:
1895 memcpy(PyUnicode_1BYTE_DATA(copy), data, size);
1896 break;
1897 case PyUnicode_2BYTE_KIND:
1898 memcpy(PyUnicode_2BYTE_DATA(copy), data, sizeof(Py_UCS2) * size);
1899 break;
1900 case PyUnicode_4BYTE_KIND:
1901 memcpy(PyUnicode_4BYTE_DATA(copy), data, sizeof(Py_UCS4) * size);
1902 break;
1903 default:
1904 assert(0);
1905 break;
1906 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001907 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001908 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02001909}
1910
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001911
Victor Stinnerbc603d12011-10-02 01:00:40 +02001912/* Widen Unicode objects to larger buffers. Don't write terminating null
1913 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001914
1915void*
1916_PyUnicode_AsKind(PyObject *s, unsigned int kind)
1917{
Victor Stinnerbc603d12011-10-02 01:00:40 +02001918 Py_ssize_t len;
1919 void *result;
1920 unsigned int skind;
1921
1922 if (PyUnicode_READY(s))
1923 return NULL;
1924
1925 len = PyUnicode_GET_LENGTH(s);
1926 skind = PyUnicode_KIND(s);
1927 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02001928 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001929 return NULL;
1930 }
1931 switch(kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02001932 case PyUnicode_2BYTE_KIND:
1933 result = PyMem_Malloc(len * sizeof(Py_UCS2));
1934 if (!result)
1935 return PyErr_NoMemory();
1936 assert(skind == PyUnicode_1BYTE_KIND);
1937 _PyUnicode_CONVERT_BYTES(
1938 Py_UCS1, Py_UCS2,
1939 PyUnicode_1BYTE_DATA(s),
1940 PyUnicode_1BYTE_DATA(s) + len,
1941 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001942 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02001943 case PyUnicode_4BYTE_KIND:
1944 result = PyMem_Malloc(len * sizeof(Py_UCS4));
1945 if (!result)
1946 return PyErr_NoMemory();
1947 if (skind == PyUnicode_2BYTE_KIND) {
1948 _PyUnicode_CONVERT_BYTES(
1949 Py_UCS2, Py_UCS4,
1950 PyUnicode_2BYTE_DATA(s),
1951 PyUnicode_2BYTE_DATA(s) + len,
1952 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001953 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02001954 else {
1955 assert(skind == PyUnicode_1BYTE_KIND);
1956 _PyUnicode_CONVERT_BYTES(
1957 Py_UCS1, Py_UCS4,
1958 PyUnicode_1BYTE_DATA(s),
1959 PyUnicode_1BYTE_DATA(s) + len,
1960 result);
1961 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001962 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02001963 default:
1964 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001965 }
Victor Stinner01698042011-10-04 00:04:26 +02001966 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001967 return NULL;
1968}
1969
1970static Py_UCS4*
1971as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
1972 int copy_null)
1973{
1974 int kind;
1975 void *data;
1976 Py_ssize_t len, targetlen;
1977 if (PyUnicode_READY(string) == -1)
1978 return NULL;
1979 kind = PyUnicode_KIND(string);
1980 data = PyUnicode_DATA(string);
1981 len = PyUnicode_GET_LENGTH(string);
1982 targetlen = len;
1983 if (copy_null)
1984 targetlen++;
1985 if (!target) {
1986 if (PY_SSIZE_T_MAX / sizeof(Py_UCS4) < targetlen) {
1987 PyErr_NoMemory();
1988 return NULL;
1989 }
1990 target = PyMem_Malloc(targetlen * sizeof(Py_UCS4));
1991 if (!target) {
1992 PyErr_NoMemory();
1993 return NULL;
1994 }
1995 }
1996 else {
1997 if (targetsize < targetlen) {
1998 PyErr_Format(PyExc_SystemError,
1999 "string is longer than the buffer");
2000 if (copy_null && 0 < targetsize)
2001 target[0] = 0;
2002 return NULL;
2003 }
2004 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002005 if (kind == PyUnicode_1BYTE_KIND) {
2006 Py_UCS1 *start = (Py_UCS1 *) data;
2007 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002008 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002009 else if (kind == PyUnicode_2BYTE_KIND) {
2010 Py_UCS2 *start = (Py_UCS2 *) data;
2011 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2012 }
2013 else {
2014 assert(kind == PyUnicode_4BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002015 Py_MEMCPY(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002016 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002017 if (copy_null)
2018 target[len] = 0;
2019 return target;
2020}
2021
2022Py_UCS4*
2023PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2024 int copy_null)
2025{
2026 if (target == NULL || targetsize < 1) {
2027 PyErr_BadInternalCall();
2028 return NULL;
2029 }
2030 return as_ucs4(string, target, targetsize, copy_null);
2031}
2032
2033Py_UCS4*
2034PyUnicode_AsUCS4Copy(PyObject *string)
2035{
2036 return as_ucs4(string, NULL, 0, 1);
2037}
2038
2039#ifdef HAVE_WCHAR_H
Mark Dickinson081dfee2009-03-18 14:47:41 +00002040
Alexander Belopolsky40018472011-02-26 01:02:56 +00002041PyObject *
2042PyUnicode_FromWideChar(register const wchar_t *w, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002043{
Guido van Rossumd57fd912000-03-10 22:53:23 +00002044 if (w == NULL) {
Martin v. Löwis790465f2008-04-05 20:41:37 +00002045 if (size == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002046 return PyUnicode_New(0, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00002047 PyErr_BadInternalCall();
2048 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002049 }
2050
Martin v. Löwis790465f2008-04-05 20:41:37 +00002051 if (size == -1) {
2052 size = wcslen(w);
2053 }
2054
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002055 return PyUnicode_FromUnicode(w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002056}
2057
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002058#endif /* HAVE_WCHAR_H */
Mark Dickinson081dfee2009-03-18 14:47:41 +00002059
Walter Dörwald346737f2007-05-31 10:44:43 +00002060static void
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002061makefmt(char *fmt, int longflag, int longlongflag, int size_tflag,
2062 int zeropad, int width, int precision, char c)
Walter Dörwald346737f2007-05-31 10:44:43 +00002063{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002064 *fmt++ = '%';
2065 if (width) {
2066 if (zeropad)
2067 *fmt++ = '0';
2068 fmt += sprintf(fmt, "%d", width);
2069 }
2070 if (precision)
2071 fmt += sprintf(fmt, ".%d", precision);
2072 if (longflag)
2073 *fmt++ = 'l';
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002074 else if (longlongflag) {
2075 /* longlongflag should only ever be nonzero on machines with
2076 HAVE_LONG_LONG defined */
2077#ifdef HAVE_LONG_LONG
2078 char *f = PY_FORMAT_LONG_LONG;
2079 while (*f)
2080 *fmt++ = *f++;
2081#else
2082 /* we shouldn't ever get here */
2083 assert(0);
2084 *fmt++ = 'l';
2085#endif
2086 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002087 else if (size_tflag) {
2088 char *f = PY_FORMAT_SIZE_T;
2089 while (*f)
2090 *fmt++ = *f++;
2091 }
2092 *fmt++ = c;
2093 *fmt = '\0';
Walter Dörwald346737f2007-05-31 10:44:43 +00002094}
2095
Victor Stinner96865452011-03-01 23:44:09 +00002096/* helper for PyUnicode_FromFormatV() */
2097
2098static const char*
2099parse_format_flags(const char *f,
2100 int *p_width, int *p_precision,
2101 int *p_longflag, int *p_longlongflag, int *p_size_tflag)
2102{
2103 int width, precision, longflag, longlongflag, size_tflag;
2104
2105 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
2106 f++;
2107 width = 0;
2108 while (Py_ISDIGIT((unsigned)*f))
2109 width = (width*10) + *f++ - '0';
2110 precision = 0;
2111 if (*f == '.') {
2112 f++;
2113 while (Py_ISDIGIT((unsigned)*f))
2114 precision = (precision*10) + *f++ - '0';
2115 if (*f == '%') {
2116 /* "%.3%s" => f points to "3" */
2117 f--;
2118 }
2119 }
2120 if (*f == '\0') {
2121 /* bogus format "%.1" => go backward, f points to "1" */
2122 f--;
2123 }
2124 if (p_width != NULL)
2125 *p_width = width;
2126 if (p_precision != NULL)
2127 *p_precision = precision;
2128
2129 /* Handle %ld, %lu, %lld and %llu. */
2130 longflag = 0;
2131 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002132 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002133
2134 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002135 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002136 longflag = 1;
2137 ++f;
2138 }
2139#ifdef HAVE_LONG_LONG
2140 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002141 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002142 longlongflag = 1;
2143 f += 2;
2144 }
2145#endif
2146 }
2147 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002148 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002149 size_tflag = 1;
2150 ++f;
2151 }
2152 if (p_longflag != NULL)
2153 *p_longflag = longflag;
2154 if (p_longlongflag != NULL)
2155 *p_longlongflag = longlongflag;
2156 if (p_size_tflag != NULL)
2157 *p_size_tflag = size_tflag;
2158 return f;
2159}
2160
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002161/* maximum number of characters required for output of %ld. 21 characters
2162 allows for 64-bit integers (in decimal) and an optional sign. */
2163#define MAX_LONG_CHARS 21
2164/* maximum number of characters required for output of %lld.
2165 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2166 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2167#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
2168
Walter Dörwaldd2034312007-05-18 16:29:38 +00002169PyObject *
2170PyUnicode_FromFormatV(const char *format, va_list vargs)
2171{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002172 va_list count;
2173 Py_ssize_t callcount = 0;
2174 PyObject **callresults = NULL;
2175 PyObject **callresult = NULL;
2176 Py_ssize_t n = 0;
2177 int width = 0;
2178 int precision = 0;
2179 int zeropad;
2180 const char* f;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002181 PyObject *string;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002182 /* used by sprintf */
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002183 char fmt[61]; /* should be enough for %0width.precisionlld */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002184 Py_UCS4 maxchar = 127; /* result is ASCII by default */
2185 Py_UCS4 argmaxchar;
2186 Py_ssize_t numbersize = 0;
2187 char *numberresults = NULL;
2188 char *numberresult = NULL;
2189 Py_ssize_t i;
2190 int kind;
2191 void *data;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002192
Victor Stinner4a2b7a12010-08-13 14:03:48 +00002193 Py_VA_COPY(count, vargs);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002194 /* step 1: count the number of %S/%R/%A/%s format specifications
2195 * (we call PyObject_Str()/PyObject_Repr()/PyObject_ASCII()/
2196 * PyUnicode_DecodeUTF8() for these objects once during step 3 and put the
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002197 * result in an array)
Georg Brandl7597add2011-10-05 16:36:47 +02002198 * also estimate a upper bound for all the number formats in the string,
2199 * numbers will be formatted in step 3 and be kept in a '\0'-separated
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002200 * buffer before putting everything together. */
Benjamin Peterson14339b62009-01-31 16:36:08 +00002201 for (f = format; *f; f++) {
2202 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002203 int longlongflag;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002204 /* skip width or width.precision (eg. "1.2" of "%1.2f") */
2205 f = parse_format_flags(f, &width, NULL, NULL, &longlongflag, NULL);
2206 if (*f == 's' || *f=='S' || *f=='R' || *f=='A' || *f=='V')
2207 ++callcount;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002208
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002209 else if (*f == 'd' || *f=='u' || *f=='i' || *f=='x' || *f=='p') {
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002210#ifdef HAVE_LONG_LONG
2211 if (longlongflag) {
2212 if (width < MAX_LONG_LONG_CHARS)
2213 width = MAX_LONG_LONG_CHARS;
2214 }
2215 else
2216#endif
2217 /* MAX_LONG_CHARS is enough to hold a 64-bit integer,
2218 including sign. Decimal takes the most space. This
2219 isn't enough for octal. If a width is specified we
2220 need more (which we allocate later). */
2221 if (width < MAX_LONG_CHARS)
2222 width = MAX_LONG_CHARS;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002223
2224 /* account for the size + '\0' to separate numbers
2225 inside of the numberresults buffer */
2226 numbersize += (width + 1);
2227 }
2228 }
2229 else if ((unsigned char)*f > 127) {
2230 PyErr_Format(PyExc_ValueError,
2231 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2232 "string, got a non-ASCII byte: 0x%02x",
2233 (unsigned char)*f);
2234 return NULL;
2235 }
2236 }
2237 /* step 2: allocate memory for the results of
2238 * PyObject_Str()/PyObject_Repr()/PyUnicode_DecodeUTF8() calls */
2239 if (callcount) {
2240 callresults = PyObject_Malloc(sizeof(PyObject *) * callcount);
2241 if (!callresults) {
2242 PyErr_NoMemory();
2243 return NULL;
2244 }
2245 callresult = callresults;
2246 }
2247 /* step 2.5: allocate memory for the results of formating numbers */
2248 if (numbersize) {
2249 numberresults = PyObject_Malloc(numbersize);
2250 if (!numberresults) {
2251 PyErr_NoMemory();
2252 goto fail;
2253 }
2254 numberresult = numberresults;
2255 }
2256
2257 /* step 3: format numbers and figure out how large a buffer we need */
2258 for (f = format; *f; f++) {
2259 if (*f == '%') {
2260 const char* p;
2261 int longflag;
2262 int longlongflag;
2263 int size_tflag;
2264 int numprinted;
2265
2266 p = f;
2267 zeropad = (f[1] == '0');
2268 f = parse_format_flags(f, &width, &precision,
2269 &longflag, &longlongflag, &size_tflag);
2270 switch (*f) {
2271 case 'c':
2272 {
2273 Py_UCS4 ordinal = va_arg(count, int);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002274 maxchar = Py_MAX(maxchar, ordinal);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002275 n++;
2276 break;
2277 }
2278 case '%':
2279 n++;
2280 break;
2281 case 'i':
2282 case 'd':
2283 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2284 width, precision, *f);
2285 if (longflag)
2286 numprinted = sprintf(numberresult, fmt,
2287 va_arg(count, long));
2288#ifdef HAVE_LONG_LONG
2289 else if (longlongflag)
2290 numprinted = sprintf(numberresult, fmt,
2291 va_arg(count, PY_LONG_LONG));
2292#endif
2293 else if (size_tflag)
2294 numprinted = sprintf(numberresult, fmt,
2295 va_arg(count, Py_ssize_t));
2296 else
2297 numprinted = sprintf(numberresult, fmt,
2298 va_arg(count, int));
2299 n += numprinted;
2300 /* advance by +1 to skip over the '\0' */
2301 numberresult += (numprinted + 1);
2302 assert(*(numberresult - 1) == '\0');
2303 assert(*(numberresult - 2) != '\0');
2304 assert(numprinted >= 0);
2305 assert(numberresult <= numberresults + numbersize);
2306 break;
2307 case 'u':
2308 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2309 width, precision, 'u');
2310 if (longflag)
2311 numprinted = sprintf(numberresult, fmt,
2312 va_arg(count, unsigned long));
2313#ifdef HAVE_LONG_LONG
2314 else if (longlongflag)
2315 numprinted = sprintf(numberresult, fmt,
2316 va_arg(count, unsigned PY_LONG_LONG));
2317#endif
2318 else if (size_tflag)
2319 numprinted = sprintf(numberresult, fmt,
2320 va_arg(count, size_t));
2321 else
2322 numprinted = sprintf(numberresult, fmt,
2323 va_arg(count, unsigned int));
2324 n += numprinted;
2325 numberresult += (numprinted + 1);
2326 assert(*(numberresult - 1) == '\0');
2327 assert(*(numberresult - 2) != '\0');
2328 assert(numprinted >= 0);
2329 assert(numberresult <= numberresults + numbersize);
2330 break;
2331 case 'x':
2332 makefmt(fmt, 0, 0, 0, zeropad, width, precision, 'x');
2333 numprinted = sprintf(numberresult, fmt, va_arg(count, int));
2334 n += numprinted;
2335 numberresult += (numprinted + 1);
2336 assert(*(numberresult - 1) == '\0');
2337 assert(*(numberresult - 2) != '\0');
2338 assert(numprinted >= 0);
2339 assert(numberresult <= numberresults + numbersize);
2340 break;
2341 case 'p':
2342 numprinted = sprintf(numberresult, "%p", va_arg(count, void*));
2343 /* %p is ill-defined: ensure leading 0x. */
2344 if (numberresult[1] == 'X')
2345 numberresult[1] = 'x';
2346 else if (numberresult[1] != 'x') {
2347 memmove(numberresult + 2, numberresult,
2348 strlen(numberresult) + 1);
2349 numberresult[0] = '0';
2350 numberresult[1] = 'x';
2351 numprinted += 2;
2352 }
2353 n += numprinted;
2354 numberresult += (numprinted + 1);
2355 assert(*(numberresult - 1) == '\0');
2356 assert(*(numberresult - 2) != '\0');
2357 assert(numprinted >= 0);
2358 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002359 break;
2360 case 's':
2361 {
2362 /* UTF-8 */
Georg Brandl780b2a62009-05-05 09:19:59 +00002363 const char *s = va_arg(count, const char*);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002364 PyObject *str = PyUnicode_DecodeUTF8(s, strlen(s), "replace");
2365 if (!str)
2366 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002367 /* since PyUnicode_DecodeUTF8 returns already flexible
2368 unicode objects, there is no need to call ready on them */
2369 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002370 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002371 n += PyUnicode_GET_LENGTH(str);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002372 /* Remember the str and switch to the next slot */
2373 *callresult++ = str;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002374 break;
2375 }
2376 case 'U':
2377 {
2378 PyObject *obj = va_arg(count, PyObject *);
Victor Stinner910337b2011-10-03 03:20:16 +02002379 assert(obj && _PyUnicode_CHECK(obj));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002380 if (PyUnicode_READY(obj) == -1)
2381 goto fail;
2382 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002383 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002384 n += PyUnicode_GET_LENGTH(obj);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002385 break;
2386 }
2387 case 'V':
2388 {
2389 PyObject *obj = va_arg(count, PyObject *);
2390 const char *str = va_arg(count, const char *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002391 PyObject *str_obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002392 assert(obj || str);
Victor Stinner910337b2011-10-03 03:20:16 +02002393 assert(!obj || _PyUnicode_CHECK(obj));
Victor Stinner2512a8b2011-03-01 22:46:52 +00002394 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002395 if (PyUnicode_READY(obj) == -1)
2396 goto fail;
2397 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002398 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002399 n += PyUnicode_GET_LENGTH(obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002400 *callresult++ = NULL;
2401 }
2402 else {
2403 str_obj = PyUnicode_DecodeUTF8(str, strlen(str), "replace");
2404 if (!str_obj)
2405 goto fail;
Victor Stinnere1335c72011-10-04 20:53:03 +02002406 if (PyUnicode_READY(str_obj)) {
2407 Py_DECREF(str_obj);
2408 goto fail;
2409 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002410 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002411 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002412 n += PyUnicode_GET_LENGTH(str_obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002413 *callresult++ = str_obj;
2414 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002415 break;
2416 }
2417 case 'S':
2418 {
2419 PyObject *obj = va_arg(count, PyObject *);
2420 PyObject *str;
2421 assert(obj);
2422 str = PyObject_Str(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002423 if (!str || PyUnicode_READY(str) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002424 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002425 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002426 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002427 n += PyUnicode_GET_LENGTH(str);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002428 /* Remember the str and switch to the next slot */
2429 *callresult++ = str;
2430 break;
2431 }
2432 case 'R':
2433 {
2434 PyObject *obj = va_arg(count, PyObject *);
2435 PyObject *repr;
2436 assert(obj);
2437 repr = PyObject_Repr(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002438 if (!repr || PyUnicode_READY(repr) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002439 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002440 argmaxchar = PyUnicode_MAX_CHAR_VALUE(repr);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002441 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002442 n += PyUnicode_GET_LENGTH(repr);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002443 /* Remember the repr and switch to the next slot */
2444 *callresult++ = repr;
2445 break;
2446 }
2447 case 'A':
2448 {
2449 PyObject *obj = va_arg(count, PyObject *);
2450 PyObject *ascii;
2451 assert(obj);
2452 ascii = PyObject_ASCII(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002453 if (!ascii || PyUnicode_READY(ascii) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002454 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002455 argmaxchar = PyUnicode_MAX_CHAR_VALUE(ascii);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002456 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002457 n += PyUnicode_GET_LENGTH(ascii);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002458 /* Remember the repr and switch to the next slot */
2459 *callresult++ = ascii;
2460 break;
2461 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002462 default:
2463 /* if we stumble upon an unknown
2464 formatting code, copy the rest of
2465 the format string to the output
2466 string. (we cannot just skip the
2467 code, since there's no way to know
2468 what's in the argument list) */
2469 n += strlen(p);
2470 goto expand;
2471 }
2472 } else
2473 n++;
2474 }
Benjamin Peterson29060642009-01-31 22:14:21 +00002475 expand:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002476 /* step 4: fill the buffer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002477 /* Since we've analyzed how much space we need,
Benjamin Peterson14339b62009-01-31 16:36:08 +00002478 we don't have to resize the string.
2479 There can be no errors beyond this point. */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002480 string = PyUnicode_New(n, maxchar);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002481 if (!string)
2482 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002483 kind = PyUnicode_KIND(string);
2484 data = PyUnicode_DATA(string);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002485 callresult = callresults;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002486 numberresult = numberresults;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002487
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002488 for (i = 0, f = format; *f; f++) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002489 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002490 const char* p;
Victor Stinner96865452011-03-01 23:44:09 +00002491
2492 p = f;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002493 f = parse_format_flags(f, NULL, NULL, NULL, NULL, NULL);
2494 /* checking for == because the last argument could be a empty
2495 string, which causes i to point to end, the assert at the end of
2496 the loop */
2497 assert(i <= PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002498
Benjamin Peterson14339b62009-01-31 16:36:08 +00002499 switch (*f) {
2500 case 'c':
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002501 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002502 const int ordinal = va_arg(vargs, int);
2503 PyUnicode_WRITE(kind, data, i++, ordinal);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002504 break;
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002505 }
Victor Stinner6d970f42011-03-02 00:04:25 +00002506 case 'i':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002507 case 'd':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002508 case 'u':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002509 case 'x':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002510 case 'p':
2511 /* unused, since we already have the result */
2512 if (*f == 'p')
2513 (void) va_arg(vargs, void *);
2514 else
2515 (void) va_arg(vargs, int);
2516 /* extract the result from numberresults and append. */
2517 for (; *numberresult; ++i, ++numberresult)
2518 PyUnicode_WRITE(kind, data, i, *numberresult);
2519 /* skip over the separating '\0' */
2520 assert(*numberresult == '\0');
2521 numberresult++;
2522 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002523 break;
2524 case 's':
2525 {
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002526 /* unused, since we already have the result */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002527 Py_ssize_t size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002528 (void) va_arg(vargs, char *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002529 size = PyUnicode_GET_LENGTH(*callresult);
2530 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002531 copy_characters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002532 i += size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002533 /* We're done with the unicode()/repr() => forget it */
2534 Py_DECREF(*callresult);
2535 /* switch to next unicode()/repr() result */
2536 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002537 break;
2538 }
2539 case 'U':
2540 {
2541 PyObject *obj = va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002542 Py_ssize_t size;
2543 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
2544 size = PyUnicode_GET_LENGTH(obj);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002545 copy_characters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002546 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002547 break;
2548 }
2549 case 'V':
2550 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002551 Py_ssize_t size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002552 PyObject *obj = va_arg(vargs, PyObject *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002553 va_arg(vargs, const char *);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002554 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002555 size = PyUnicode_GET_LENGTH(obj);
2556 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002557 copy_characters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002558 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002559 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002560 size = PyUnicode_GET_LENGTH(*callresult);
2561 assert(PyUnicode_KIND(*callresult) <=
2562 PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002563 copy_characters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002564 i += size;
Victor Stinner2512a8b2011-03-01 22:46:52 +00002565 Py_DECREF(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002566 }
Victor Stinner2512a8b2011-03-01 22:46:52 +00002567 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002568 break;
2569 }
2570 case 'S':
2571 case 'R':
Victor Stinner9a909002010-10-18 20:59:24 +00002572 case 'A':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002573 {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002574 Py_ssize_t size = PyUnicode_GET_LENGTH(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002575 /* unused, since we already have the result */
2576 (void) va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002577 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002578 copy_characters(string, i, *callresult, 0, size);
2579 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002580 /* We're done with the unicode()/repr() => forget it */
2581 Py_DECREF(*callresult);
2582 /* switch to next unicode()/repr() result */
2583 ++callresult;
2584 break;
2585 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002586 case '%':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002587 PyUnicode_WRITE(kind, data, i++, '%');
Benjamin Peterson14339b62009-01-31 16:36:08 +00002588 break;
2589 default:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002590 for (; *p; ++p, ++i)
2591 PyUnicode_WRITE(kind, data, i, *p);
2592 assert(i == PyUnicode_GET_LENGTH(string));
Benjamin Peterson14339b62009-01-31 16:36:08 +00002593 goto end;
2594 }
Victor Stinner1205f272010-09-11 00:54:47 +00002595 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002596 else {
2597 assert(i < PyUnicode_GET_LENGTH(string));
2598 PyUnicode_WRITE(kind, data, i++, *f);
2599 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002600 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002601 assert(i == PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002602
Benjamin Peterson29060642009-01-31 22:14:21 +00002603 end:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002604 if (callresults)
2605 PyObject_Free(callresults);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002606 if (numberresults)
2607 PyObject_Free(numberresults);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002608 assert(_PyUnicode_CheckConsistency(string, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01002609 return string;
Benjamin Peterson29060642009-01-31 22:14:21 +00002610 fail:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002611 if (callresults) {
2612 PyObject **callresult2 = callresults;
2613 while (callresult2 < callresult) {
Victor Stinner2512a8b2011-03-01 22:46:52 +00002614 Py_XDECREF(*callresult2);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002615 ++callresult2;
2616 }
2617 PyObject_Free(callresults);
2618 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002619 if (numberresults)
2620 PyObject_Free(numberresults);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002621 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002622}
2623
Walter Dörwaldd2034312007-05-18 16:29:38 +00002624PyObject *
2625PyUnicode_FromFormat(const char *format, ...)
2626{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002627 PyObject* ret;
2628 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002629
2630#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002631 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002632#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002633 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002634#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002635 ret = PyUnicode_FromFormatV(format, vargs);
2636 va_end(vargs);
2637 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002638}
2639
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002640#ifdef HAVE_WCHAR_H
2641
Victor Stinner5593d8a2010-10-02 11:11:27 +00002642/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2643 convert a Unicode object to a wide character string.
2644
Victor Stinnerd88d9832011-09-06 02:00:05 +02002645 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002646 character) required to convert the unicode object. Ignore size argument.
2647
Victor Stinnerd88d9832011-09-06 02:00:05 +02002648 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002649 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002650 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002651static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002652unicode_aswidechar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002653 wchar_t *w,
2654 Py_ssize_t size)
2655{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002656 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002657 const wchar_t *wstr;
2658
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002659 wstr = PyUnicode_AsUnicodeAndSize(unicode, &res);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002660 if (wstr == NULL)
2661 return -1;
2662
Victor Stinner5593d8a2010-10-02 11:11:27 +00002663 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002664 if (size > res)
2665 size = res + 1;
2666 else
2667 res = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002668 Py_MEMCPY(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002669 return res;
2670 }
2671 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002672 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002673}
2674
2675Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002676PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002677 wchar_t *w,
2678 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002679{
2680 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002681 PyErr_BadInternalCall();
2682 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002683 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002684 return unicode_aswidechar(unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002685}
2686
Victor Stinner137c34c2010-09-29 10:25:54 +00002687wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002688PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002689 Py_ssize_t *size)
2690{
2691 wchar_t* buffer;
2692 Py_ssize_t buflen;
2693
2694 if (unicode == NULL) {
2695 PyErr_BadInternalCall();
2696 return NULL;
2697 }
2698
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002699 buflen = unicode_aswidechar(unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002700 if (buflen == -1)
2701 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002702 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < buflen) {
Victor Stinner137c34c2010-09-29 10:25:54 +00002703 PyErr_NoMemory();
2704 return NULL;
2705 }
2706
Victor Stinner137c34c2010-09-29 10:25:54 +00002707 buffer = PyMem_MALLOC(buflen * sizeof(wchar_t));
2708 if (buffer == NULL) {
2709 PyErr_NoMemory();
2710 return NULL;
2711 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002712 buflen = unicode_aswidechar(unicode, buffer, buflen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002713 if (buflen == -1)
2714 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002715 if (size != NULL)
2716 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00002717 return buffer;
2718}
2719
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002720#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002721
Alexander Belopolsky40018472011-02-26 01:02:56 +00002722PyObject *
2723PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002724{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002725 PyObject *v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002726 if (ordinal < 0 || ordinal > 0x10ffff) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002727 PyErr_SetString(PyExc_ValueError,
2728 "chr() arg not in range(0x110000)");
2729 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002730 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00002731
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002732 if (ordinal < 256)
2733 return get_latin1_char(ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002734
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002735 v = PyUnicode_New(1, ordinal);
2736 if (v == NULL)
2737 return NULL;
2738 PyUnicode_WRITE(PyUnicode_KIND(v), PyUnicode_DATA(v), 0, ordinal);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002739 assert(_PyUnicode_CheckConsistency(v, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002740 return v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002741}
2742
Alexander Belopolsky40018472011-02-26 01:02:56 +00002743PyObject *
2744PyUnicode_FromObject(register PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002745{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002746 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00002747 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002748 if (PyUnicode_CheckExact(obj)) {
Victor Stinnerd3a83d52011-10-01 03:09:33 +02002749 if (PyUnicode_READY(obj))
2750 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00002751 Py_INCREF(obj);
2752 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002753 }
2754 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002755 /* For a Unicode subtype that's not a Unicode object,
2756 return a true Unicode object with the same data. */
Victor Stinner2219e0a2011-10-01 01:16:59 +02002757 return PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002758 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00002759 PyErr_Format(PyExc_TypeError,
2760 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00002761 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002762 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002763}
2764
Alexander Belopolsky40018472011-02-26 01:02:56 +00002765PyObject *
2766PyUnicode_FromEncodedObject(register PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002767 const char *encoding,
2768 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002769{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002770 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002771 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00002772
Guido van Rossumd57fd912000-03-10 22:53:23 +00002773 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002774 PyErr_BadInternalCall();
2775 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002776 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002777
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002778 /* Decoding bytes objects is the most common case and should be fast */
2779 if (PyBytes_Check(obj)) {
2780 if (PyBytes_GET_SIZE(obj) == 0) {
2781 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002782 v = unicode_empty;
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002783 }
2784 else {
2785 v = PyUnicode_Decode(
2786 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
2787 encoding, errors);
2788 }
2789 return v;
2790 }
2791
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002792 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002793 PyErr_SetString(PyExc_TypeError,
2794 "decoding str is not supported");
2795 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002796 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002797
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002798 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
2799 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
2800 PyErr_Format(PyExc_TypeError,
2801 "coercing to str: need bytes, bytearray "
2802 "or buffer-like object, %.80s found",
2803 Py_TYPE(obj)->tp_name);
2804 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00002805 }
Tim Petersced69f82003-09-16 20:30:58 +00002806
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002807 if (buffer.len == 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002808 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002809 v = unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002810 }
Tim Petersced69f82003-09-16 20:30:58 +00002811 else
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002812 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00002813
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002814 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002815 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002816}
2817
Victor Stinner600d3be2010-06-10 12:00:55 +00002818/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00002819 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
2820 1 on success. */
2821static int
2822normalize_encoding(const char *encoding,
2823 char *lower,
2824 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002825{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002826 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00002827 char *l;
2828 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002829
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04002830 if (encoding == NULL) {
2831 strcpy(lower, "utf-8");
2832 return 1;
2833 }
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002834 e = encoding;
2835 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00002836 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00002837 while (*e) {
2838 if (l == l_end)
2839 return 0;
David Malcolm96960882010-11-05 17:23:41 +00002840 if (Py_ISUPPER(*e)) {
2841 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002842 }
2843 else if (*e == '_') {
2844 *l++ = '-';
2845 e++;
2846 }
2847 else {
2848 *l++ = *e++;
2849 }
2850 }
2851 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00002852 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00002853}
2854
Alexander Belopolsky40018472011-02-26 01:02:56 +00002855PyObject *
2856PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002857 Py_ssize_t size,
2858 const char *encoding,
2859 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00002860{
2861 PyObject *buffer = NULL, *unicode;
2862 Py_buffer info;
2863 char lower[11]; /* Enough for any encoding shortcut */
2864
Fred Drakee4315f52000-05-09 19:53:39 +00002865 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00002866 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002867 if ((strcmp(lower, "utf-8") == 0) ||
2868 (strcmp(lower, "utf8") == 0))
Victor Stinner37296e82010-06-10 13:36:23 +00002869 return PyUnicode_DecodeUTF8(s, size, errors);
2870 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002871 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00002872 (strcmp(lower, "iso-8859-1") == 0))
2873 return PyUnicode_DecodeLatin1(s, size, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02002874#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00002875 else if (strcmp(lower, "mbcs") == 0)
2876 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00002877#endif
Victor Stinner37296e82010-06-10 13:36:23 +00002878 else if (strcmp(lower, "ascii") == 0)
2879 return PyUnicode_DecodeASCII(s, size, errors);
2880 else if (strcmp(lower, "utf-16") == 0)
2881 return PyUnicode_DecodeUTF16(s, size, errors, 0);
2882 else if (strcmp(lower, "utf-32") == 0)
2883 return PyUnicode_DecodeUTF32(s, size, errors, 0);
2884 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002885
2886 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002887 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00002888 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002889 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00002890 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002891 if (buffer == NULL)
2892 goto onError;
2893 unicode = PyCodec_Decode(buffer, encoding, errors);
2894 if (unicode == NULL)
2895 goto onError;
2896 if (!PyUnicode_Check(unicode)) {
2897 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00002898 "decoder did not return a str object (type=%.400s)",
Christian Heimes90aa7642007-12-19 02:45:37 +00002899 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002900 Py_DECREF(unicode);
2901 goto onError;
2902 }
2903 Py_DECREF(buffer);
Victor Stinner17efeed2011-10-04 20:05:46 +02002904#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02002905 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002906 Py_DECREF(unicode);
2907 return NULL;
2908 }
Victor Stinner17efeed2011-10-04 20:05:46 +02002909#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002910 assert(_PyUnicode_CheckConsistency(unicode, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00002911 return unicode;
Tim Petersced69f82003-09-16 20:30:58 +00002912
Benjamin Peterson29060642009-01-31 22:14:21 +00002913 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00002914 Py_XDECREF(buffer);
2915 return NULL;
2916}
2917
Alexander Belopolsky40018472011-02-26 01:02:56 +00002918PyObject *
2919PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002920 const char *encoding,
2921 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002922{
2923 PyObject *v;
2924
2925 if (!PyUnicode_Check(unicode)) {
2926 PyErr_BadArgument();
2927 goto onError;
2928 }
2929
2930 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002931 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002932
2933 /* Decode via the codec registry */
2934 v = PyCodec_Decode(unicode, encoding, errors);
2935 if (v == NULL)
2936 goto onError;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002937 assert(_PyUnicode_CheckConsistency(v, 1));
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002938 return v;
2939
Benjamin Peterson29060642009-01-31 22:14:21 +00002940 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002941 return NULL;
2942}
2943
Alexander Belopolsky40018472011-02-26 01:02:56 +00002944PyObject *
2945PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002946 const char *encoding,
2947 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002948{
2949 PyObject *v;
2950
2951 if (!PyUnicode_Check(unicode)) {
2952 PyErr_BadArgument();
2953 goto onError;
2954 }
2955
2956 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002957 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002958
2959 /* Decode via the codec registry */
2960 v = PyCodec_Decode(unicode, encoding, errors);
2961 if (v == NULL)
2962 goto onError;
2963 if (!PyUnicode_Check(v)) {
2964 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00002965 "decoder did not return a str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002966 Py_TYPE(v)->tp_name);
2967 Py_DECREF(v);
2968 goto onError;
2969 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002970 assert(_PyUnicode_CheckConsistency(v, 1));
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002971 return v;
2972
Benjamin Peterson29060642009-01-31 22:14:21 +00002973 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002974 return NULL;
2975}
2976
Alexander Belopolsky40018472011-02-26 01:02:56 +00002977PyObject *
2978PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002979 Py_ssize_t size,
2980 const char *encoding,
2981 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002982{
2983 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00002984
Guido van Rossumd57fd912000-03-10 22:53:23 +00002985 unicode = PyUnicode_FromUnicode(s, size);
2986 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002987 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002988 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
2989 Py_DECREF(unicode);
2990 return v;
2991}
2992
Alexander Belopolsky40018472011-02-26 01:02:56 +00002993PyObject *
2994PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002995 const char *encoding,
2996 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002997{
2998 PyObject *v;
2999
3000 if (!PyUnicode_Check(unicode)) {
3001 PyErr_BadArgument();
3002 goto onError;
3003 }
3004
3005 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003006 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003007
3008 /* Encode via the codec registry */
3009 v = PyCodec_Encode(unicode, encoding, errors);
3010 if (v == NULL)
3011 goto onError;
3012 return v;
3013
Benjamin Peterson29060642009-01-31 22:14:21 +00003014 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003015 return NULL;
3016}
3017
Victor Stinnerad158722010-10-27 00:25:46 +00003018PyObject *
3019PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003020{
Victor Stinner99b95382011-07-04 14:23:54 +02003021#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003022 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
3023 PyUnicode_GET_SIZE(unicode),
3024 NULL);
3025#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003026 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00003027#else
Victor Stinner793b5312011-04-27 00:24:21 +02003028 PyInterpreterState *interp = PyThreadState_GET()->interp;
3029 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3030 cannot use it to encode and decode filenames before it is loaded. Load
3031 the Python codec requires to encode at least its own filename. Use the C
3032 version of the locale codec until the codec registry is initialized and
3033 the Python codec is loaded.
3034
3035 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3036 cannot only rely on it: check also interp->fscodec_initialized for
3037 subinterpreters. */
3038 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003039 return PyUnicode_AsEncodedString(unicode,
3040 Py_FileSystemDefaultEncoding,
3041 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003042 }
3043 else {
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003044 /* locale encoding with surrogateescape */
3045 wchar_t *wchar;
3046 char *bytes;
3047 PyObject *bytes_obj;
Victor Stinner2f02a512010-11-08 22:43:46 +00003048 size_t error_pos;
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003049
3050 wchar = PyUnicode_AsWideCharString(unicode, NULL);
3051 if (wchar == NULL)
3052 return NULL;
Victor Stinner2f02a512010-11-08 22:43:46 +00003053 bytes = _Py_wchar2char(wchar, &error_pos);
3054 if (bytes == NULL) {
3055 if (error_pos != (size_t)-1) {
3056 char *errmsg = strerror(errno);
3057 PyObject *exc = NULL;
3058 if (errmsg == NULL)
3059 errmsg = "Py_wchar2char() failed";
3060 raise_encode_exception(&exc,
3061 "filesystemencoding",
3062 PyUnicode_AS_UNICODE(unicode), PyUnicode_GET_SIZE(unicode),
3063 error_pos, error_pos+1,
3064 errmsg);
3065 Py_XDECREF(exc);
3066 }
3067 else
3068 PyErr_NoMemory();
3069 PyMem_Free(wchar);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003070 return NULL;
Victor Stinner2f02a512010-11-08 22:43:46 +00003071 }
3072 PyMem_Free(wchar);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003073
3074 bytes_obj = PyBytes_FromString(bytes);
3075 PyMem_Free(bytes);
3076 return bytes_obj;
Victor Stinnerc39211f2010-09-29 16:35:47 +00003077 }
Victor Stinnerad158722010-10-27 00:25:46 +00003078#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003079}
3080
Alexander Belopolsky40018472011-02-26 01:02:56 +00003081PyObject *
3082PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003083 const char *encoding,
3084 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003085{
3086 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00003087 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003088
Guido van Rossumd57fd912000-03-10 22:53:23 +00003089 if (!PyUnicode_Check(unicode)) {
3090 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003091 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003092 }
Fred Drakee4315f52000-05-09 19:53:39 +00003093
Fred Drakee4315f52000-05-09 19:53:39 +00003094 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00003095 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003096 if ((strcmp(lower, "utf-8") == 0) ||
3097 (strcmp(lower, "utf8") == 0))
Victor Stinnera5c68c32011-03-02 01:03:14 +00003098 {
Victor Stinner2f283c22011-03-02 01:21:46 +00003099 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003100 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00003101 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003102 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinnera5c68c32011-03-02 01:03:14 +00003103 }
Victor Stinner37296e82010-06-10 13:36:23 +00003104 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003105 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00003106 (strcmp(lower, "iso-8859-1") == 0))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003107 return _PyUnicode_AsLatin1String(unicode, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003108#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00003109 else if (strcmp(lower, "mbcs") == 0)
3110 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
3111 PyUnicode_GET_SIZE(unicode),
3112 errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003113#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003114 else if (strcmp(lower, "ascii") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003115 return _PyUnicode_AsASCIIString(unicode, errors);
Victor Stinner37296e82010-06-10 13:36:23 +00003116 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003117
3118 /* Encode via the codec registry */
3119 v = PyCodec_Encode(unicode, encoding, errors);
3120 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003121 return NULL;
3122
3123 /* The normal path */
3124 if (PyBytes_Check(v))
3125 return v;
3126
3127 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003128 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003129 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003130 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003131
3132 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
3133 "encoder %s returned bytearray instead of bytes",
3134 encoding);
3135 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003136 Py_DECREF(v);
3137 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003138 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003139
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003140 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3141 Py_DECREF(v);
3142 return b;
3143 }
3144
3145 PyErr_Format(PyExc_TypeError,
3146 "encoder did not return a bytes object (type=%.400s)",
3147 Py_TYPE(v)->tp_name);
3148 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003149 return NULL;
3150}
3151
Alexander Belopolsky40018472011-02-26 01:02:56 +00003152PyObject *
3153PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003154 const char *encoding,
3155 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003156{
3157 PyObject *v;
3158
3159 if (!PyUnicode_Check(unicode)) {
3160 PyErr_BadArgument();
3161 goto onError;
3162 }
3163
3164 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003165 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003166
3167 /* Encode via the codec registry */
3168 v = PyCodec_Encode(unicode, encoding, errors);
3169 if (v == NULL)
3170 goto onError;
3171 if (!PyUnicode_Check(v)) {
3172 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003173 "encoder did not return an str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003174 Py_TYPE(v)->tp_name);
3175 Py_DECREF(v);
3176 goto onError;
3177 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003178 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003179
Benjamin Peterson29060642009-01-31 22:14:21 +00003180 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003181 return NULL;
3182}
3183
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003184PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003185PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003186 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003187 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3188}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003189
Christian Heimes5894ba72007-11-04 11:43:14 +00003190PyObject*
3191PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3192{
Victor Stinner99b95382011-07-04 14:23:54 +02003193#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003194 return PyUnicode_DecodeMBCS(s, size, NULL);
3195#elif defined(__APPLE__)
3196 return PyUnicode_DecodeUTF8(s, size, "surrogateescape");
3197#else
Victor Stinner793b5312011-04-27 00:24:21 +02003198 PyInterpreterState *interp = PyThreadState_GET()->interp;
3199 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3200 cannot use it to encode and decode filenames before it is loaded. Load
3201 the Python codec requires to encode at least its own filename. Use the C
3202 version of the locale codec until the codec registry is initialized and
3203 the Python codec is loaded.
3204
3205 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3206 cannot only rely on it: check also interp->fscodec_initialized for
3207 subinterpreters. */
3208 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003209 return PyUnicode_Decode(s, size,
3210 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00003211 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003212 }
3213 else {
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003214 /* locale encoding with surrogateescape */
3215 wchar_t *wchar;
3216 PyObject *unicode;
Victor Stinner168e1172010-10-16 23:16:16 +00003217 size_t len;
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003218
3219 if (s[size] != '\0' || size != strlen(s)) {
3220 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3221 return NULL;
3222 }
3223
Victor Stinner168e1172010-10-16 23:16:16 +00003224 wchar = _Py_char2wchar(s, &len);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003225 if (wchar == NULL)
Victor Stinnerd5af0a52010-11-08 23:34:29 +00003226 return PyErr_NoMemory();
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003227
Victor Stinner168e1172010-10-16 23:16:16 +00003228 unicode = PyUnicode_FromWideChar(wchar, len);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003229 PyMem_Free(wchar);
3230 return unicode;
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003231 }
Victor Stinnerad158722010-10-27 00:25:46 +00003232#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003233}
3234
Martin v. Löwis011e8422009-05-05 04:43:17 +00003235
3236int
3237PyUnicode_FSConverter(PyObject* arg, void* addr)
3238{
3239 PyObject *output = NULL;
3240 Py_ssize_t size;
3241 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003242 if (arg == NULL) {
3243 Py_DECREF(*(PyObject**)addr);
3244 return 1;
3245 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00003246 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00003247 output = arg;
3248 Py_INCREF(output);
3249 }
3250 else {
3251 arg = PyUnicode_FromObject(arg);
3252 if (!arg)
3253 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00003254 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003255 Py_DECREF(arg);
3256 if (!output)
3257 return 0;
3258 if (!PyBytes_Check(output)) {
3259 Py_DECREF(output);
3260 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
3261 return 0;
3262 }
3263 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00003264 size = PyBytes_GET_SIZE(output);
3265 data = PyBytes_AS_STRING(output);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003266 if (size != strlen(data)) {
Benjamin Peterson7a6b44a2011-08-18 13:51:47 -05003267 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003268 Py_DECREF(output);
3269 return 0;
3270 }
3271 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003272 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003273}
3274
3275
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003276int
3277PyUnicode_FSDecoder(PyObject* arg, void* addr)
3278{
3279 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003280 if (arg == NULL) {
3281 Py_DECREF(*(PyObject**)addr);
3282 return 1;
3283 }
3284 if (PyUnicode_Check(arg)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003285 if (PyUnicode_READY(arg))
3286 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003287 output = arg;
3288 Py_INCREF(output);
3289 }
3290 else {
3291 arg = PyBytes_FromObject(arg);
3292 if (!arg)
3293 return 0;
3294 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
3295 PyBytes_GET_SIZE(arg));
3296 Py_DECREF(arg);
3297 if (!output)
3298 return 0;
3299 if (!PyUnicode_Check(output)) {
3300 Py_DECREF(output);
3301 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
3302 return 0;
3303 }
3304 }
Victor Stinner065836e2011-10-27 01:56:33 +02003305 if (PyUnicode_READY(output) < 0) {
3306 Py_DECREF(output);
3307 return 0;
3308 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003309 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003310 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003311 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3312 Py_DECREF(output);
3313 return 0;
3314 }
3315 *(PyObject**)addr = output;
3316 return Py_CLEANUP_SUPPORTED;
3317}
3318
3319
Martin v. Löwis5b222132007-06-10 09:51:05 +00003320char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003321PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003322{
Christian Heimesf3863112007-11-22 07:46:41 +00003323 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003324
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003325 if (!PyUnicode_Check(unicode)) {
3326 PyErr_BadArgument();
3327 return NULL;
3328 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003329 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003330 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003331
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003332 if (PyUnicode_UTF8(unicode) == NULL) {
3333 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003334 bytes = _PyUnicode_AsUTF8String(unicode, "strict");
3335 if (bytes == NULL)
3336 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003337 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3338 if (_PyUnicode_UTF8(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003339 Py_DECREF(bytes);
3340 return NULL;
3341 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003342 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
3343 Py_MEMCPY(_PyUnicode_UTF8(unicode),
3344 PyBytes_AS_STRING(bytes),
3345 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003346 Py_DECREF(bytes);
3347 }
3348
3349 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003350 *psize = PyUnicode_UTF8_LENGTH(unicode);
3351 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003352}
3353
3354char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003355PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003356{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003357 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3358}
3359
3360#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +02003361static int unicode_as_unicode_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003362#endif
3363
3364
3365Py_UNICODE *
3366PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3367{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003368 const unsigned char *one_byte;
3369#if SIZEOF_WCHAR_T == 4
3370 const Py_UCS2 *two_bytes;
3371#else
3372 const Py_UCS4 *four_bytes;
3373 const Py_UCS4 *ucs4_end;
3374 Py_ssize_t num_surrogates;
3375#endif
3376 wchar_t *w;
3377 wchar_t *wchar_end;
3378
3379 if (!PyUnicode_Check(unicode)) {
3380 PyErr_BadArgument();
3381 return NULL;
3382 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003383 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003384 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003385 assert(_PyUnicode_KIND(unicode) != 0);
3386 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003387
3388#ifdef Py_DEBUG
3389 ++unicode_as_unicode_calls;
3390#endif
3391
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003392 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003393#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003394 four_bytes = PyUnicode_4BYTE_DATA(unicode);
3395 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003396 num_surrogates = 0;
3397
3398 for (; four_bytes < ucs4_end; ++four_bytes) {
3399 if (*four_bytes > 0xFFFF)
3400 ++num_surrogates;
3401 }
3402
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003403 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
3404 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
3405 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003406 PyErr_NoMemory();
3407 return NULL;
3408 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003409 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003410
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003411 w = _PyUnicode_WSTR(unicode);
3412 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
3413 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003414 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3415 if (*four_bytes > 0xFFFF) {
3416 /* encode surrogate pair in this case */
3417 *w++ = 0xD800 | ((*four_bytes - 0x10000) >> 10);
3418 *w = 0xDC00 | ((*four_bytes - 0x10000) & 0x3FF);
3419 }
3420 else
3421 *w = *four_bytes;
3422
3423 if (w > wchar_end) {
3424 assert(0 && "Miscalculated string end");
3425 }
3426 }
3427 *w = 0;
3428#else
3429 /* sizeof(wchar_t) == 4 */
3430 Py_FatalError("Impossible unicode object state, wstr and str "
3431 "should share memory already.");
3432 return NULL;
3433#endif
3434 }
3435 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003436 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3437 (_PyUnicode_LENGTH(unicode) + 1));
3438 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003439 PyErr_NoMemory();
3440 return NULL;
3441 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003442 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
3443 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
3444 w = _PyUnicode_WSTR(unicode);
3445 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003446
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003447 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3448 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003449 for (; w < wchar_end; ++one_byte, ++w)
3450 *w = *one_byte;
3451 /* null-terminate the wstr */
3452 *w = 0;
3453 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003454 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003455#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003456 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003457 for (; w < wchar_end; ++two_bytes, ++w)
3458 *w = *two_bytes;
3459 /* null-terminate the wstr */
3460 *w = 0;
3461#else
3462 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003463 PyObject_FREE(_PyUnicode_WSTR(unicode));
3464 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003465 Py_FatalError("Impossible unicode object state, wstr "
3466 "and str should share memory already.");
3467 return NULL;
3468#endif
3469 }
3470 else {
3471 assert(0 && "This should never happen.");
3472 }
3473 }
3474 }
3475 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003476 *size = PyUnicode_WSTR_LENGTH(unicode);
3477 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00003478}
3479
Alexander Belopolsky40018472011-02-26 01:02:56 +00003480Py_UNICODE *
3481PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003482{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003483 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003484}
3485
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003486
Alexander Belopolsky40018472011-02-26 01:02:56 +00003487Py_ssize_t
3488PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003489{
3490 if (!PyUnicode_Check(unicode)) {
3491 PyErr_BadArgument();
3492 goto onError;
3493 }
3494 return PyUnicode_GET_SIZE(unicode);
3495
Benjamin Peterson29060642009-01-31 22:14:21 +00003496 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003497 return -1;
3498}
3499
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003500Py_ssize_t
3501PyUnicode_GetLength(PyObject *unicode)
3502{
Victor Stinner5a706cf2011-10-02 00:36:53 +02003503 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003504 PyErr_BadArgument();
3505 return -1;
3506 }
3507
3508 return PyUnicode_GET_LENGTH(unicode);
3509}
3510
3511Py_UCS4
3512PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
3513{
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003514 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
3515 PyErr_BadArgument();
3516 return (Py_UCS4)-1;
3517 }
3518 if (index < 0 || index >= _PyUnicode_LENGTH(unicode)) {
3519 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003520 return (Py_UCS4)-1;
3521 }
3522 return PyUnicode_READ_CHAR(unicode, index);
3523}
3524
3525int
3526PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
3527{
3528 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003529 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003530 return -1;
3531 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02003532 if (index < 0 || index >= _PyUnicode_LENGTH(unicode)) {
3533 PyErr_SetString(PyExc_IndexError, "string index out of range");
3534 return -1;
3535 }
3536 if (_PyUnicode_Dirty(unicode))
3537 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003538 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
3539 index, ch);
3540 return 0;
3541}
3542
Alexander Belopolsky40018472011-02-26 01:02:56 +00003543const char *
3544PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00003545{
Victor Stinner42cb4622010-09-01 19:39:01 +00003546 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00003547}
3548
Victor Stinner554f3f02010-06-16 23:33:54 +00003549/* create or adjust a UnicodeDecodeError */
3550static void
3551make_decode_exception(PyObject **exceptionObject,
3552 const char *encoding,
3553 const char *input, Py_ssize_t length,
3554 Py_ssize_t startpos, Py_ssize_t endpos,
3555 const char *reason)
3556{
3557 if (*exceptionObject == NULL) {
3558 *exceptionObject = PyUnicodeDecodeError_Create(
3559 encoding, input, length, startpos, endpos, reason);
3560 }
3561 else {
3562 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
3563 goto onError;
3564 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
3565 goto onError;
3566 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
3567 goto onError;
3568 }
3569 return;
3570
3571onError:
3572 Py_DECREF(*exceptionObject);
3573 *exceptionObject = NULL;
3574}
3575
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003576/* error handling callback helper:
3577 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00003578 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003579 and adjust various state variables.
3580 return 0 on success, -1 on error
3581*/
3582
Alexander Belopolsky40018472011-02-26 01:02:56 +00003583static int
3584unicode_decode_call_errorhandler(const char *errors, PyObject **errorHandler,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003585 const char *encoding, const char *reason,
3586 const char **input, const char **inend, Py_ssize_t *startinpos,
3587 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
Victor Stinner7931d9a2011-11-04 00:22:48 +01003588 PyObject **output, Py_ssize_t *outpos, Py_UNICODE **outptr)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003589{
Benjamin Peterson142957c2008-07-04 19:55:29 +00003590 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003591
3592 PyObject *restuple = NULL;
3593 PyObject *repunicode = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003594 Py_ssize_t outsize = PyUnicode_GET_SIZE(*output);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003595 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003596 Py_ssize_t requiredsize;
3597 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003598 const Py_UNICODE *repptr;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003599 PyObject *inputobj = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003600 Py_ssize_t repsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003601 int res = -1;
3602
3603 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003604 *errorHandler = PyCodec_LookupError(errors);
3605 if (*errorHandler == NULL)
3606 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003607 }
3608
Victor Stinner554f3f02010-06-16 23:33:54 +00003609 make_decode_exception(exceptionObject,
3610 encoding,
3611 *input, *inend - *input,
3612 *startinpos, *endinpos,
3613 reason);
3614 if (*exceptionObject == NULL)
3615 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003616
3617 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
3618 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003619 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003620 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00003621 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00003622 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003623 }
3624 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00003625 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003626
3627 /* Copy back the bytes variables, which might have been modified by the
3628 callback */
3629 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
3630 if (!inputobj)
3631 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00003632 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003633 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00003634 }
Christian Heimes72b710a2008-05-26 13:28:38 +00003635 *input = PyBytes_AS_STRING(inputobj);
3636 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003637 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00003638 /* we can DECREF safely, as the exception has another reference,
3639 so the object won't go away. */
3640 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003641
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003642 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003643 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00003644 if (newpos<0 || newpos>insize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003645 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
3646 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00003647 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003648
3649 /* need more space? (at least enough for what we
3650 have+the replacement+the rest of the string (starting
3651 at the new input position), so we won't have to check space
3652 when there are no errors in the rest of the string) */
3653 repptr = PyUnicode_AS_UNICODE(repunicode);
3654 repsize = PyUnicode_GET_SIZE(repunicode);
3655 requiredsize = *outpos + repsize + insize-newpos;
3656 if (requiredsize > outsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003657 if (requiredsize<2*outsize)
3658 requiredsize = 2*outsize;
Victor Stinner7931d9a2011-11-04 00:22:48 +01003659 if (PyUnicode_Resize(output, requiredsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003660 goto onError;
3661 *outptr = PyUnicode_AS_UNICODE(*output) + *outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003662 }
3663 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003664 *inptr = *input + newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003665 Py_UNICODE_COPY(*outptr, repptr, repsize);
3666 *outptr += repsize;
3667 *outpos += repsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003668
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003669 /* we made it! */
3670 res = 0;
3671
Benjamin Peterson29060642009-01-31 22:14:21 +00003672 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003673 Py_XDECREF(restuple);
3674 return res;
3675}
3676
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003677/* --- UTF-7 Codec -------------------------------------------------------- */
3678
Antoine Pitrou244651a2009-05-04 18:56:13 +00003679/* See RFC2152 for details. We encode conservatively and decode liberally. */
3680
3681/* Three simple macros defining base-64. */
3682
3683/* Is c a base-64 character? */
3684
3685#define IS_BASE64(c) \
3686 (((c) >= 'A' && (c) <= 'Z') || \
3687 ((c) >= 'a' && (c) <= 'z') || \
3688 ((c) >= '0' && (c) <= '9') || \
3689 (c) == '+' || (c) == '/')
3690
3691/* given that c is a base-64 character, what is its base-64 value? */
3692
3693#define FROM_BASE64(c) \
3694 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
3695 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
3696 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
3697 (c) == '+' ? 62 : 63)
3698
3699/* What is the base-64 character of the bottom 6 bits of n? */
3700
3701#define TO_BASE64(n) \
3702 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
3703
3704/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
3705 * decoded as itself. We are permissive on decoding; the only ASCII
3706 * byte not decoding to itself is the + which begins a base64
3707 * string. */
3708
3709#define DECODE_DIRECT(c) \
3710 ((c) <= 127 && (c) != '+')
3711
3712/* The UTF-7 encoder treats ASCII characters differently according to
3713 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
3714 * the above). See RFC2152. This array identifies these different
3715 * sets:
3716 * 0 : "Set D"
3717 * alphanumeric and '(),-./:?
3718 * 1 : "Set O"
3719 * !"#$%&*;<=>@[]^_`{|}
3720 * 2 : "whitespace"
3721 * ht nl cr sp
3722 * 3 : special (must be base64 encoded)
3723 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
3724 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003725
Tim Petersced69f82003-09-16 20:30:58 +00003726static
Antoine Pitrou244651a2009-05-04 18:56:13 +00003727char utf7_category[128] = {
3728/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
3729 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
3730/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
3731 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3732/* sp ! " # $ % & ' ( ) * + , - . / */
3733 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
3734/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
3735 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
3736/* @ A B C D E F G H I J K L M N O */
3737 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3738/* P Q R S T U V W X Y Z [ \ ] ^ _ */
3739 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
3740/* ` a b c d e f g h i j k l m n o */
3741 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3742/* p q r s t u v w x y z { | } ~ del */
3743 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003744};
3745
Antoine Pitrou244651a2009-05-04 18:56:13 +00003746/* ENCODE_DIRECT: this character should be encoded as itself. The
3747 * answer depends on whether we are encoding set O as itself, and also
3748 * on whether we are encoding whitespace as itself. RFC2152 makes it
3749 * clear that the answers to these questions vary between
3750 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00003751
Antoine Pitrou244651a2009-05-04 18:56:13 +00003752#define ENCODE_DIRECT(c, directO, directWS) \
3753 ((c) < 128 && (c) > 0 && \
3754 ((utf7_category[(c)] == 0) || \
3755 (directWS && (utf7_category[(c)] == 2)) || \
3756 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003757
Alexander Belopolsky40018472011-02-26 01:02:56 +00003758PyObject *
3759PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003760 Py_ssize_t size,
3761 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003762{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003763 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
3764}
3765
Antoine Pitrou244651a2009-05-04 18:56:13 +00003766/* The decoder. The only state we preserve is our read position,
3767 * i.e. how many characters we have consumed. So if we end in the
3768 * middle of a shift sequence we have to back off the read position
3769 * and the output to the beginning of the sequence, otherwise we lose
3770 * all the shift state (seen bits, number of bits seen, high
3771 * surrogate). */
3772
Alexander Belopolsky40018472011-02-26 01:02:56 +00003773PyObject *
3774PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003775 Py_ssize_t size,
3776 const char *errors,
3777 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003778{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003779 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003780 Py_ssize_t startinpos;
3781 Py_ssize_t endinpos;
3782 Py_ssize_t outpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003783 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01003784 PyObject *unicode;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003785 Py_UNICODE *p;
3786 const char *errmsg = "";
3787 int inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003788 Py_UNICODE *shiftOutStart;
3789 unsigned int base64bits = 0;
3790 unsigned long base64buffer = 0;
3791 Py_UNICODE surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003792 PyObject *errorHandler = NULL;
3793 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003794
Victor Stinner7931d9a2011-11-04 00:22:48 +01003795 unicode = (PyObject*)_PyUnicode_New(size);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003796 if (!unicode)
3797 return NULL;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003798 if (size == 0) {
3799 if (consumed)
3800 *consumed = 0;
Victor Stinner7931d9a2011-11-04 00:22:48 +01003801 return unicode;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003802 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003803
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003804 p = PyUnicode_AS_UNICODE(unicode);
Antoine Pitrou244651a2009-05-04 18:56:13 +00003805 shiftOutStart = p;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003806 e = s + size;
3807
3808 while (s < e) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003809 Py_UNICODE ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00003810 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00003811 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003812
Antoine Pitrou244651a2009-05-04 18:56:13 +00003813 if (inShift) { /* in a base-64 section */
3814 if (IS_BASE64(ch)) { /* consume a base-64 character */
3815 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
3816 base64bits += 6;
3817 s++;
3818 if (base64bits >= 16) {
3819 /* we have enough bits for a UTF-16 value */
3820 Py_UNICODE outCh = (Py_UNICODE)
3821 (base64buffer >> (base64bits-16));
3822 base64bits -= 16;
3823 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
3824 if (surrogate) {
3825 /* expecting a second surrogate */
3826 if (outCh >= 0xDC00 && outCh <= 0xDFFF) {
3827#ifdef Py_UNICODE_WIDE
3828 *p++ = (((surrogate & 0x3FF)<<10)
3829 | (outCh & 0x3FF)) + 0x10000;
3830#else
3831 *p++ = surrogate;
3832 *p++ = outCh;
3833#endif
3834 surrogate = 0;
3835 }
3836 else {
3837 surrogate = 0;
3838 errmsg = "second surrogate missing";
3839 goto utf7Error;
3840 }
3841 }
3842 else if (outCh >= 0xD800 && outCh <= 0xDBFF) {
3843 /* first surrogate */
3844 surrogate = outCh;
3845 }
3846 else if (outCh >= 0xDC00 && outCh <= 0xDFFF) {
3847 errmsg = "unexpected second surrogate";
3848 goto utf7Error;
3849 }
3850 else {
3851 *p++ = outCh;
3852 }
3853 }
3854 }
3855 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003856 inShift = 0;
3857 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003858 if (surrogate) {
3859 errmsg = "second surrogate missing at end of shift sequence";
Tim Petersced69f82003-09-16 20:30:58 +00003860 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003861 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003862 if (base64bits > 0) { /* left-over bits */
3863 if (base64bits >= 6) {
3864 /* We've seen at least one base-64 character */
3865 errmsg = "partial character in shift sequence";
3866 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003867 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003868 else {
3869 /* Some bits remain; they should be zero */
3870 if (base64buffer != 0) {
3871 errmsg = "non-zero padding bits in shift sequence";
3872 goto utf7Error;
3873 }
3874 }
3875 }
3876 if (ch != '-') {
3877 /* '-' is absorbed; other terminating
3878 characters are preserved */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003879 *p++ = ch;
3880 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003881 }
3882 }
3883 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003884 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003885 s++; /* consume '+' */
3886 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003887 s++;
3888 *p++ = '+';
Antoine Pitrou244651a2009-05-04 18:56:13 +00003889 }
3890 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003891 inShift = 1;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003892 shiftOutStart = p;
3893 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003894 }
3895 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003896 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003897 *p++ = ch;
3898 s++;
3899 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003900 else {
3901 startinpos = s-starts;
3902 s++;
3903 errmsg = "unexpected special character";
3904 goto utf7Error;
3905 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003906 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003907utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003908 outpos = p-PyUnicode_AS_UNICODE(unicode);
3909 endinpos = s-starts;
3910 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003911 errors, &errorHandler,
3912 "utf7", errmsg,
3913 &starts, &e, &startinpos, &endinpos, &exc, &s,
3914 &unicode, &outpos, &p))
3915 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003916 }
3917
Antoine Pitrou244651a2009-05-04 18:56:13 +00003918 /* end of string */
3919
3920 if (inShift && !consumed) { /* in shift sequence, no more to follow */
3921 /* if we're in an inconsistent state, that's an error */
3922 if (surrogate ||
3923 (base64bits >= 6) ||
3924 (base64bits > 0 && base64buffer != 0)) {
3925 outpos = p-PyUnicode_AS_UNICODE(unicode);
3926 endinpos = size;
3927 if (unicode_decode_call_errorhandler(
3928 errors, &errorHandler,
3929 "utf7", "unterminated shift sequence",
3930 &starts, &e, &startinpos, &endinpos, &exc, &s,
3931 &unicode, &outpos, &p))
3932 goto onError;
3933 if (s < e)
3934 goto restart;
3935 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003936 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003937
3938 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003939 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00003940 if (inShift) {
3941 p = shiftOutStart; /* back off output */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003942 *consumed = startinpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003943 }
3944 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003945 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003946 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003947 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003948
Victor Stinner7931d9a2011-11-04 00:22:48 +01003949 if (PyUnicode_Resize(&unicode, p - PyUnicode_AS_UNICODE(unicode)) < 0)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003950 goto onError;
3951
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003952 Py_XDECREF(errorHandler);
3953 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02003954#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02003955 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003956 Py_DECREF(unicode);
3957 return NULL;
3958 }
Victor Stinner17efeed2011-10-04 20:05:46 +02003959#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02003960 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01003961 return unicode;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003962
Benjamin Peterson29060642009-01-31 22:14:21 +00003963 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003964 Py_XDECREF(errorHandler);
3965 Py_XDECREF(exc);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003966 Py_DECREF(unicode);
3967 return NULL;
3968}
3969
3970
Alexander Belopolsky40018472011-02-26 01:02:56 +00003971PyObject *
3972PyUnicode_EncodeUTF7(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003973 Py_ssize_t size,
3974 int base64SetO,
3975 int base64WhiteSpace,
3976 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003977{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003978 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003979 /* It might be possible to tighten this worst case */
Alexandre Vassalottie85bd982009-07-21 00:39:03 +00003980 Py_ssize_t allocated = 8 * size;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003981 int inShift = 0;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003982 Py_ssize_t i = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003983 unsigned int base64bits = 0;
3984 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003985 char * out;
3986 char * start;
3987
3988 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003989 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003990
Alexandre Vassalottie85bd982009-07-21 00:39:03 +00003991 if (allocated / 8 != size)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003992 return PyErr_NoMemory();
3993
Antoine Pitrou244651a2009-05-04 18:56:13 +00003994 v = PyBytes_FromStringAndSize(NULL, allocated);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003995 if (v == NULL)
3996 return NULL;
3997
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003998 start = out = PyBytes_AS_STRING(v);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003999 for (;i < size; ++i) {
4000 Py_UNICODE ch = s[i];
4001
Antoine Pitrou244651a2009-05-04 18:56:13 +00004002 if (inShift) {
4003 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4004 /* shifting out */
4005 if (base64bits) { /* output remaining bits */
4006 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4007 base64buffer = 0;
4008 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004009 }
4010 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004011 /* Characters not in the BASE64 set implicitly unshift the sequence
4012 so no '-' is required, except if the character is itself a '-' */
4013 if (IS_BASE64(ch) || ch == '-') {
4014 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004015 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004016 *out++ = (char) ch;
4017 }
4018 else {
4019 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004020 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004021 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004022 else { /* not in a shift sequence */
4023 if (ch == '+') {
4024 *out++ = '+';
4025 *out++ = '-';
4026 }
4027 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4028 *out++ = (char) ch;
4029 }
4030 else {
4031 *out++ = '+';
4032 inShift = 1;
4033 goto encode_char;
4034 }
4035 }
4036 continue;
4037encode_char:
4038#ifdef Py_UNICODE_WIDE
4039 if (ch >= 0x10000) {
4040 /* code first surrogate */
4041 base64bits += 16;
4042 base64buffer = (base64buffer << 16) | 0xd800 | ((ch-0x10000) >> 10);
4043 while (base64bits >= 6) {
4044 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4045 base64bits -= 6;
4046 }
4047 /* prepare second surrogate */
4048 ch = 0xDC00 | ((ch-0x10000) & 0x3FF);
4049 }
4050#endif
4051 base64bits += 16;
4052 base64buffer = (base64buffer << 16) | ch;
4053 while (base64bits >= 6) {
4054 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4055 base64bits -= 6;
4056 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004057 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004058 if (base64bits)
4059 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4060 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004061 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004062 if (_PyBytes_Resize(&v, out - start) < 0)
4063 return NULL;
4064 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004065}
4066
Antoine Pitrou244651a2009-05-04 18:56:13 +00004067#undef IS_BASE64
4068#undef FROM_BASE64
4069#undef TO_BASE64
4070#undef DECODE_DIRECT
4071#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004072
Guido van Rossumd57fd912000-03-10 22:53:23 +00004073/* --- UTF-8 Codec -------------------------------------------------------- */
4074
Tim Petersced69f82003-09-16 20:30:58 +00004075static
Guido van Rossumd57fd912000-03-10 22:53:23 +00004076char utf8_code_length[256] = {
Ezio Melotti57221d02010-07-01 07:32:02 +00004077 /* Map UTF-8 encoded prefix byte to sequence length. Zero means
4078 illegal prefix. See RFC 3629 for details */
4079 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 00-0F */
4080 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Victor Stinner4a2b7a12010-08-13 14:03:48 +00004081 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Guido van Rossumd57fd912000-03-10 22:53:23 +00004082 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4083 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4084 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4085 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Ezio Melotti57221d02010-07-01 07:32:02 +00004086 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 70-7F */
4087 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 +00004088 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4089 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
Ezio Melotti57221d02010-07-01 07:32:02 +00004090 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* B0-BF */
4091 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* C0-C1 + C2-CF */
4092 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* D0-DF */
4093 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* E0-EF */
4094 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 +00004095};
4096
Alexander Belopolsky40018472011-02-26 01:02:56 +00004097PyObject *
4098PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004099 Py_ssize_t size,
4100 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004101{
Walter Dörwald69652032004-09-07 20:24:22 +00004102 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4103}
4104
Antoine Pitrouab868312009-01-10 15:40:25 +00004105/* Mask to check or force alignment of a pointer to C 'long' boundaries */
4106#define LONG_PTR_MASK (size_t) (SIZEOF_LONG - 1)
4107
4108/* Mask to quickly check whether a C 'long' contains a
4109 non-ASCII, UTF8-encoded char. */
4110#if (SIZEOF_LONG == 8)
4111# define ASCII_CHAR_MASK 0x8080808080808080L
4112#elif (SIZEOF_LONG == 4)
4113# define ASCII_CHAR_MASK 0x80808080L
4114#else
4115# error C 'long' size should be either 4 or 8!
4116#endif
4117
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004118/* Scans a UTF-8 string and returns the maximum character to be expected,
4119 the size of the decoded unicode string and if any major errors were
4120 encountered.
4121
4122 This function does check basic UTF-8 sanity, it does however NOT CHECK
4123 if the string contains surrogates, and if all continuation bytes are
4124 within the correct ranges, these checks are performed in
4125 PyUnicode_DecodeUTF8Stateful.
4126
4127 If it sets has_errors to 1, it means the value of unicode_size and max_char
4128 will be bogus and you should not rely on useful information in them.
4129 */
4130static Py_UCS4
4131utf8_max_char_size_and_has_errors(const char *s, Py_ssize_t string_size,
4132 Py_ssize_t *unicode_size, Py_ssize_t* consumed,
4133 int *has_errors)
4134{
4135 Py_ssize_t n;
4136 Py_ssize_t char_count = 0;
4137 Py_UCS4 max_char = 127, new_max;
4138 Py_UCS4 upper_bound;
4139 const unsigned char *p = (const unsigned char *)s;
4140 const unsigned char *end = p + string_size;
4141 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
4142 int err = 0;
4143
4144 for (; p < end && !err; ++p, ++char_count) {
4145 /* Only check value if it's not a ASCII char... */
4146 if (*p < 0x80) {
4147 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
4148 an explanation. */
4149 if (!((size_t) p & LONG_PTR_MASK)) {
4150 /* Help register allocation */
4151 register const unsigned char *_p = p;
4152 while (_p < aligned_end) {
4153 unsigned long value = *(unsigned long *) _p;
4154 if (value & ASCII_CHAR_MASK)
4155 break;
4156 _p += SIZEOF_LONG;
4157 char_count += SIZEOF_LONG;
4158 }
4159 p = _p;
4160 if (p == end)
4161 break;
4162 }
4163 }
4164 if (*p >= 0x80) {
4165 n = utf8_code_length[*p];
4166 new_max = max_char;
4167 switch (n) {
4168 /* invalid start byte */
4169 case 0:
4170 err = 1;
4171 break;
4172 case 2:
4173 /* Code points between 0x00FF and 0x07FF inclusive.
4174 Approximate the upper bound of the code point,
4175 if this flips over 255 we can be sure it will be more
4176 than 255 and the string will need 2 bytes per code coint,
4177 if it stays under or equal to 255, we can be sure 1 byte
4178 is enough.
4179 ((*p & 0b00011111) << 6) | 0b00111111 */
4180 upper_bound = ((*p & 0x1F) << 6) | 0x3F;
4181 if (max_char < upper_bound)
4182 new_max = upper_bound;
4183 /* Ensure we track at least that we left ASCII space. */
4184 if (new_max < 128)
4185 new_max = 128;
4186 break;
4187 case 3:
4188 /* Between 0x0FFF and 0xFFFF inclusive, so values are
4189 always > 255 and <= 65535 and will always need 2 bytes. */
4190 if (max_char < 65535)
4191 new_max = 65535;
4192 break;
4193 case 4:
4194 /* Code point will be above 0xFFFF for sure in this case. */
4195 new_max = 65537;
4196 break;
4197 /* Internal error, this should be caught by the first if */
4198 case 1:
4199 default:
4200 assert(0 && "Impossible case in utf8_max_char_and_size");
4201 err = 1;
4202 }
4203 /* Instead of number of overall bytes for this code point,
Georg Brandl7597add2011-10-05 16:36:47 +02004204 n contains the number of following bytes: */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004205 --n;
4206 /* Check if the follow up chars are all valid continuation bytes */
4207 if (n >= 1) {
4208 const unsigned char *cont;
4209 if ((p + n) >= end) {
4210 if (consumed == 0)
4211 /* incomplete data, non-incremental decoding */
4212 err = 1;
4213 break;
4214 }
4215 for (cont = p + 1; cont < (p + n); ++cont) {
4216 if ((*cont & 0xc0) != 0x80) {
4217 err = 1;
4218 break;
4219 }
4220 }
4221 p += n;
4222 }
4223 else
4224 err = 1;
4225 max_char = new_max;
4226 }
4227 }
4228
4229 if (unicode_size)
4230 *unicode_size = char_count;
4231 if (has_errors)
4232 *has_errors = err;
4233 return max_char;
4234}
4235
4236/* Similar to PyUnicode_WRITE but can also write into wstr field
4237 of the legacy unicode representation */
4238#define WRITE_FLEXIBLE_OR_WSTR(kind, buf, index, value) \
4239 do { \
4240 const int k_ = (kind); \
4241 if (k_ == PyUnicode_WCHAR_KIND) \
4242 ((Py_UNICODE *)(buf))[(index)] = (Py_UNICODE)(value); \
4243 else if (k_ == PyUnicode_1BYTE_KIND) \
4244 ((unsigned char *)(buf))[(index)] = (unsigned char)(value); \
4245 else if (k_ == PyUnicode_2BYTE_KIND) \
4246 ((Py_UCS2 *)(buf))[(index)] = (Py_UCS2)(value); \
4247 else \
4248 ((Py_UCS4 *)(buf))[(index)] = (Py_UCS4)(value); \
4249 } while (0)
4250
Alexander Belopolsky40018472011-02-26 01:02:56 +00004251PyObject *
4252PyUnicode_DecodeUTF8Stateful(const char *s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004253 Py_ssize_t size,
4254 const char *errors,
4255 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00004256{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004257 const char *starts = s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004258 int n;
Ezio Melotti57221d02010-07-01 07:32:02 +00004259 int k;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004260 Py_ssize_t startinpos;
4261 Py_ssize_t endinpos;
Antoine Pitrouab868312009-01-10 15:40:25 +00004262 const char *e, *aligned_end;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004263 PyObject *unicode;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004264 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004265 PyObject *errorHandler = NULL;
4266 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004267 Py_UCS4 maxchar = 0;
4268 Py_ssize_t unicode_size;
4269 Py_ssize_t i;
4270 int kind;
4271 void *data;
4272 int has_errors;
4273 Py_UNICODE *error_outptr;
4274#if SIZEOF_WCHAR_T == 2
4275 Py_ssize_t wchar_offset = 0;
4276#endif
Guido van Rossumd57fd912000-03-10 22:53:23 +00004277
Walter Dörwald69652032004-09-07 20:24:22 +00004278 if (size == 0) {
4279 if (consumed)
4280 *consumed = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004281 return (PyObject *)PyUnicode_New(0, 0);
Walter Dörwald69652032004-09-07 20:24:22 +00004282 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004283 maxchar = utf8_max_char_size_and_has_errors(s, size, &unicode_size,
4284 consumed, &has_errors);
4285 if (has_errors) {
Victor Stinner7931d9a2011-11-04 00:22:48 +01004286 unicode = (PyObject*)_PyUnicode_New(size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004287 if (!unicode)
4288 return NULL;
4289 kind = PyUnicode_WCHAR_KIND;
4290 data = PyUnicode_AS_UNICODE(unicode);
4291 assert(data != NULL);
4292 }
4293 else {
Victor Stinner7931d9a2011-11-04 00:22:48 +01004294 unicode = PyUnicode_New(unicode_size, maxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004295 if (!unicode)
4296 return NULL;
4297 /* When the string is ASCII only, just use memcpy and return.
4298 unicode_size may be != size if there is an incomplete UTF-8
4299 sequence at the end of the ASCII block. */
4300 if (maxchar < 128 && size == unicode_size) {
4301 Py_MEMCPY(PyUnicode_1BYTE_DATA(unicode), s, unicode_size);
Victor Stinner7931d9a2011-11-04 00:22:48 +01004302 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004303 }
4304 kind = PyUnicode_KIND(unicode);
4305 data = PyUnicode_DATA(unicode);
4306 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004307 /* Unpack UTF-8 encoded data */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004308 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004309 e = s + size;
Antoine Pitrouab868312009-01-10 15:40:25 +00004310 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004311
4312 while (s < e) {
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004313 Py_UCS4 ch = (unsigned char)*s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004314
4315 if (ch < 0x80) {
Antoine Pitrouab868312009-01-10 15:40:25 +00004316 /* Fast path for runs of ASCII characters. Given that common UTF-8
4317 input will consist of an overwhelming majority of ASCII
4318 characters, we try to optimize for this case by checking
4319 as many characters as a C 'long' can contain.
4320 First, check if we can do an aligned read, as most CPUs have
4321 a penalty for unaligned reads.
4322 */
4323 if (!((size_t) s & LONG_PTR_MASK)) {
4324 /* Help register allocation */
4325 register const char *_s = s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004326 register Py_ssize_t _i = i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004327 while (_s < aligned_end) {
4328 /* Read a whole long at a time (either 4 or 8 bytes),
4329 and do a fast unrolled copy if it only contains ASCII
4330 characters. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004331 unsigned long value = *(unsigned long *) _s;
4332 if (value & ASCII_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00004333 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004334 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+0, _s[0]);
4335 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+1, _s[1]);
4336 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+2, _s[2]);
4337 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+3, _s[3]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004338#if (SIZEOF_LONG == 8)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004339 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+4, _s[4]);
4340 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+5, _s[5]);
4341 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+6, _s[6]);
4342 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+7, _s[7]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004343#endif
4344 _s += SIZEOF_LONG;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004345 _i += SIZEOF_LONG;
Antoine Pitrouab868312009-01-10 15:40:25 +00004346 }
4347 s = _s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004348 i = _i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004349 if (s == e)
4350 break;
4351 ch = (unsigned char)*s;
4352 }
4353 }
4354
4355 if (ch < 0x80) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004356 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004357 s++;
4358 continue;
4359 }
4360
4361 n = utf8_code_length[ch];
4362
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004363 if (s + n > e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004364 if (consumed)
4365 break;
4366 else {
4367 errmsg = "unexpected end of data";
4368 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004369 endinpos = startinpos+1;
4370 for (k=1; (k < size-startinpos) && ((s[k]&0xC0) == 0x80); k++)
4371 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004372 goto utf8Error;
4373 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00004374 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004375
4376 switch (n) {
4377
4378 case 0:
Ezio Melotti57221d02010-07-01 07:32:02 +00004379 errmsg = "invalid start byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004380 startinpos = s-starts;
4381 endinpos = startinpos+1;
4382 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004383
4384 case 1:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004385 errmsg = "internal error";
Benjamin Peterson29060642009-01-31 22:14:21 +00004386 startinpos = s-starts;
4387 endinpos = startinpos+1;
4388 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004389
4390 case 2:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004391 if ((s[1] & 0xc0) != 0x80) {
Ezio Melotti57221d02010-07-01 07:32:02 +00004392 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004393 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004394 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00004395 goto utf8Error;
4396 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004397 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004398 assert ((ch > 0x007F) && (ch <= 0x07FF));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004399 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004400 break;
4401
4402 case 3:
Ezio Melotti9bf2b3a2010-07-03 04:52:19 +00004403 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
4404 will result in surrogates in range d800-dfff. Surrogates are
4405 not valid UTF-8 so they are rejected.
4406 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
4407 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
Tim Petersced69f82003-09-16 20:30:58 +00004408 if ((s[1] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004409 (s[2] & 0xc0) != 0x80 ||
4410 ((unsigned char)s[0] == 0xE0 &&
4411 (unsigned char)s[1] < 0xA0) ||
4412 ((unsigned char)s[0] == 0xED &&
4413 (unsigned char)s[1] > 0x9F)) {
4414 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004415 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004416 endinpos = startinpos + 1;
4417
4418 /* if s[1] first two bits are 1 and 0, then the invalid
4419 continuation byte is s[2], so increment endinpos by 1,
4420 if not, s[1] is invalid and endinpos doesn't need to
4421 be incremented. */
4422 if ((s[1] & 0xC0) == 0x80)
4423 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004424 goto utf8Error;
4425 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004426 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004427 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004428 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++, ch);
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004429 break;
4430
4431 case 4:
4432 if ((s[1] & 0xc0) != 0x80 ||
4433 (s[2] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004434 (s[3] & 0xc0) != 0x80 ||
4435 ((unsigned char)s[0] == 0xF0 &&
4436 (unsigned char)s[1] < 0x90) ||
4437 ((unsigned char)s[0] == 0xF4 &&
4438 (unsigned char)s[1] > 0x8F)) {
4439 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004440 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004441 endinpos = startinpos + 1;
4442 if ((s[1] & 0xC0) == 0x80) {
4443 endinpos++;
4444 if ((s[2] & 0xC0) == 0x80)
4445 endinpos++;
4446 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004447 goto utf8Error;
4448 }
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004449 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
Ezio Melotti57221d02010-07-01 07:32:02 +00004450 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
4451 assert ((ch > 0xFFFF) && (ch <= 0x10ffff));
4452
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004453 /* If the string is flexible or we have native UCS-4, write
4454 directly.. */
4455 if (sizeof(Py_UNICODE) > 2 || kind != PyUnicode_WCHAR_KIND)
4456 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++, ch);
Tim Petersced69f82003-09-16 20:30:58 +00004457
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004458 else {
4459 /* compute and append the two surrogates: */
Tim Petersced69f82003-09-16 20:30:58 +00004460
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004461 /* translate from 10000..10FFFF to 0..FFFF */
4462 ch -= 0x10000;
Tim Petersced69f82003-09-16 20:30:58 +00004463
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004464 /* high surrogate = top 10 bits added to D800 */
4465 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++,
4466 (Py_UNICODE)(0xD800 + (ch >> 10)));
4467
4468 /* low surrogate = bottom 10 bits added to DC00 */
4469 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++,
4470 (Py_UNICODE)(0xDC00 + (ch & 0x03FF)));
4471 }
4472#if SIZEOF_WCHAR_T == 2
4473 wchar_offset++;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00004474#endif
Guido van Rossumd57fd912000-03-10 22:53:23 +00004475 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004476 }
4477 s += n;
Benjamin Peterson29060642009-01-31 22:14:21 +00004478 continue;
Tim Petersced69f82003-09-16 20:30:58 +00004479
Benjamin Peterson29060642009-01-31 22:14:21 +00004480 utf8Error:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004481 /* If this is not yet a resizable string, make it one.. */
4482 if (kind != PyUnicode_WCHAR_KIND) {
4483 const Py_UNICODE *u;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004484 PyObject *new_unicode = (PyObject*)_PyUnicode_New(size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004485 if (!new_unicode)
4486 goto onError;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004487 u = PyUnicode_AsUnicode(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004488 if (!u)
4489 goto onError;
4490#if SIZEOF_WCHAR_T == 2
4491 i += wchar_offset;
4492#endif
4493 Py_UNICODE_COPY(PyUnicode_AS_UNICODE(new_unicode), u, i);
4494 Py_DECREF(unicode);
4495 unicode = new_unicode;
4496 kind = 0;
4497 data = PyUnicode_AS_UNICODE(new_unicode);
4498 assert(data != NULL);
4499 }
4500 error_outptr = PyUnicode_AS_UNICODE(unicode) + i;
Benjamin Peterson29060642009-01-31 22:14:21 +00004501 if (unicode_decode_call_errorhandler(
4502 errors, &errorHandler,
4503 "utf8", errmsg,
4504 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004505 &unicode, &i, &error_outptr))
Benjamin Peterson29060642009-01-31 22:14:21 +00004506 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004507 /* Update data because unicode_decode_call_errorhandler might have
4508 re-created or resized the unicode object. */
4509 data = PyUnicode_AS_UNICODE(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00004510 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004511 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004512 /* Ensure the unicode_size calculation above was correct: */
4513 assert(kind == PyUnicode_WCHAR_KIND || i == unicode_size);
4514
Walter Dörwald69652032004-09-07 20:24:22 +00004515 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00004516 *consumed = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004517
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004518 /* Adjust length and ready string when it contained errors and
4519 is of the old resizable kind. */
4520 if (kind == PyUnicode_WCHAR_KIND) {
Victor Stinner7931d9a2011-11-04 00:22:48 +01004521 if (PyUnicode_Resize(&unicode, i) < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004522 goto onError;
4523 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004524
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004525 Py_XDECREF(errorHandler);
4526 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02004527#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02004528 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004529 Py_DECREF(unicode);
4530 return NULL;
4531 }
Victor Stinner17efeed2011-10-04 20:05:46 +02004532#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02004533 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01004534 return unicode;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004535
Benjamin Peterson29060642009-01-31 22:14:21 +00004536 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004537 Py_XDECREF(errorHandler);
4538 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004539 Py_DECREF(unicode);
4540 return NULL;
4541}
4542
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004543#undef WRITE_FLEXIBLE_OR_WSTR
Antoine Pitrouab868312009-01-10 15:40:25 +00004544
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004545#ifdef __APPLE__
4546
4547/* Simplified UTF-8 decoder using surrogateescape error handler,
4548 used to decode the command line arguments on Mac OS X. */
4549
4550wchar_t*
4551_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4552{
4553 int n;
4554 const char *e;
4555 wchar_t *unicode, *p;
4556
4557 /* Note: size will always be longer than the resulting Unicode
4558 character count */
4559 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1)) {
4560 PyErr_NoMemory();
4561 return NULL;
4562 }
4563 unicode = PyMem_Malloc((size + 1) * sizeof(wchar_t));
4564 if (!unicode)
4565 return NULL;
4566
4567 /* Unpack UTF-8 encoded data */
4568 p = unicode;
4569 e = s + size;
4570 while (s < e) {
4571 Py_UCS4 ch = (unsigned char)*s;
4572
4573 if (ch < 0x80) {
4574 *p++ = (wchar_t)ch;
4575 s++;
4576 continue;
4577 }
4578
4579 n = utf8_code_length[ch];
4580 if (s + n > e) {
4581 goto surrogateescape;
4582 }
4583
4584 switch (n) {
4585 case 0:
4586 case 1:
4587 goto surrogateescape;
4588
4589 case 2:
4590 if ((s[1] & 0xc0) != 0x80)
4591 goto surrogateescape;
4592 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
4593 assert ((ch > 0x007F) && (ch <= 0x07FF));
4594 *p++ = (wchar_t)ch;
4595 break;
4596
4597 case 3:
4598 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
4599 will result in surrogates in range d800-dfff. Surrogates are
4600 not valid UTF-8 so they are rejected.
4601 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
4602 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
4603 if ((s[1] & 0xc0) != 0x80 ||
4604 (s[2] & 0xc0) != 0x80 ||
4605 ((unsigned char)s[0] == 0xE0 &&
4606 (unsigned char)s[1] < 0xA0) ||
4607 ((unsigned char)s[0] == 0xED &&
4608 (unsigned char)s[1] > 0x9F)) {
4609
4610 goto surrogateescape;
4611 }
4612 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
4613 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004614 *p++ = (wchar_t)ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004615 break;
4616
4617 case 4:
4618 if ((s[1] & 0xc0) != 0x80 ||
4619 (s[2] & 0xc0) != 0x80 ||
4620 (s[3] & 0xc0) != 0x80 ||
4621 ((unsigned char)s[0] == 0xF0 &&
4622 (unsigned char)s[1] < 0x90) ||
4623 ((unsigned char)s[0] == 0xF4 &&
4624 (unsigned char)s[1] > 0x8F)) {
4625 goto surrogateescape;
4626 }
4627 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
4628 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
4629 assert ((ch > 0xFFFF) && (ch <= 0x10ffff));
4630
4631#if SIZEOF_WCHAR_T == 4
4632 *p++ = (wchar_t)ch;
4633#else
4634 /* compute and append the two surrogates: */
4635
4636 /* translate from 10000..10FFFF to 0..FFFF */
4637 ch -= 0x10000;
4638
4639 /* high surrogate = top 10 bits added to D800 */
4640 *p++ = (wchar_t)(0xD800 + (ch >> 10));
4641
4642 /* low surrogate = bottom 10 bits added to DC00 */
4643 *p++ = (wchar_t)(0xDC00 + (ch & 0x03FF));
4644#endif
4645 break;
4646 }
4647 s += n;
4648 continue;
4649
4650 surrogateescape:
4651 *p++ = 0xDC00 + ch;
4652 s++;
4653 }
4654 *p = L'\0';
4655 return unicode;
4656}
4657
4658#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00004659
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004660/* Primary internal function which creates utf8 encoded bytes objects.
4661
4662 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00004663 and allocate exactly as much space needed at the end. Else allocate the
4664 maximum possible needed (4 result bytes per Unicode character), and return
4665 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004666*/
Tim Peters7e3d9612002-04-21 03:26:37 +00004667PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01004668_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004669{
Tim Peters602f7402002-04-27 18:03:26 +00004670#define MAX_SHORT_UNICHARS 300 /* largest size we'll do on the stack */
Tim Peters0eca65c2002-04-21 17:28:06 +00004671
Guido van Rossum98297ee2007-11-06 21:34:58 +00004672 Py_ssize_t i; /* index into s of next input byte */
4673 PyObject *result; /* result string object */
4674 char *p; /* next free byte in output buffer */
4675 Py_ssize_t nallocated; /* number of result bytes allocated */
4676 Py_ssize_t nneeded; /* number of result bytes needed */
Tim Peters602f7402002-04-27 18:03:26 +00004677 char stackbuf[MAX_SHORT_UNICHARS * 4];
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004678 PyObject *errorHandler = NULL;
4679 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004680 int kind;
4681 void *data;
4682 Py_ssize_t size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004683#if SIZEOF_WCHAR_T == 2
4684 Py_ssize_t wchar_offset = 0;
4685#endif
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00004686
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004687 if (!PyUnicode_Check(unicode)) {
4688 PyErr_BadArgument();
4689 return NULL;
4690 }
4691
4692 if (PyUnicode_READY(unicode) == -1)
4693 return NULL;
4694
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004695 if (PyUnicode_UTF8(unicode))
4696 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
4697 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004698
4699 kind = PyUnicode_KIND(unicode);
4700 data = PyUnicode_DATA(unicode);
4701 size = PyUnicode_GET_LENGTH(unicode);
4702
Tim Peters602f7402002-04-27 18:03:26 +00004703 assert(size >= 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004704
Tim Peters602f7402002-04-27 18:03:26 +00004705 if (size <= MAX_SHORT_UNICHARS) {
4706 /* Write into the stack buffer; nallocated can't overflow.
4707 * At the end, we'll allocate exactly as much heap space as it
4708 * turns out we need.
4709 */
4710 nallocated = Py_SAFE_DOWNCAST(sizeof(stackbuf), size_t, int);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004711 result = NULL; /* will allocate after we're done */
Tim Peters602f7402002-04-27 18:03:26 +00004712 p = stackbuf;
4713 }
4714 else {
4715 /* Overallocate on the heap, and give the excess back at the end. */
4716 nallocated = size * 4;
4717 if (nallocated / 4 != size) /* overflow! */
4718 return PyErr_NoMemory();
Christian Heimes72b710a2008-05-26 13:28:38 +00004719 result = PyBytes_FromStringAndSize(NULL, nallocated);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004720 if (result == NULL)
Tim Peters602f7402002-04-27 18:03:26 +00004721 return NULL;
Christian Heimes72b710a2008-05-26 13:28:38 +00004722 p = PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00004723 }
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004724
Tim Peters602f7402002-04-27 18:03:26 +00004725 for (i = 0; i < size;) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004726 Py_UCS4 ch = PyUnicode_READ(kind, data, i++);
Marc-André Lemburg3688a882002-02-06 18:09:02 +00004727
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004728 if (ch < 0x80)
Tim Peters602f7402002-04-27 18:03:26 +00004729 /* Encode ASCII */
Guido van Rossumd57fd912000-03-10 22:53:23 +00004730 *p++ = (char) ch;
Marc-André Lemburg3688a882002-02-06 18:09:02 +00004731
Guido van Rossumd57fd912000-03-10 22:53:23 +00004732 else if (ch < 0x0800) {
Tim Peters602f7402002-04-27 18:03:26 +00004733 /* Encode Latin-1 */
Marc-André Lemburgdc724d62002-02-06 18:20:19 +00004734 *p++ = (char)(0xc0 | (ch >> 6));
4735 *p++ = (char)(0x80 | (ch & 0x3f));
Victor Stinner31be90b2010-04-22 19:38:16 +00004736 } else if (0xD800 <= ch && ch <= 0xDFFF) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004737 Py_ssize_t newpos;
4738 PyObject *rep;
4739 Py_ssize_t repsize, k, startpos;
4740 startpos = i-1;
4741#if SIZEOF_WCHAR_T == 2
4742 startpos += wchar_offset;
Victor Stinner445a6232010-04-22 20:01:57 +00004743#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004744 rep = unicode_encode_call_errorhandler(
4745 errors, &errorHandler, "utf-8", "surrogates not allowed",
Victor Stinner7931d9a2011-11-04 00:22:48 +01004746 unicode, &exc, startpos, startpos+1, &newpos);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004747 if (!rep)
4748 goto error;
Victor Stinner31be90b2010-04-22 19:38:16 +00004749
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004750 if (PyBytes_Check(rep))
4751 repsize = PyBytes_GET_SIZE(rep);
4752 else
4753 repsize = PyUnicode_GET_SIZE(rep);
4754
4755 if (repsize > 4) {
4756 Py_ssize_t offset;
4757
4758 if (result == NULL)
4759 offset = p - stackbuf;
Victor Stinner31be90b2010-04-22 19:38:16 +00004760 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004761 offset = p - PyBytes_AS_STRING(result);
Victor Stinner31be90b2010-04-22 19:38:16 +00004762
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004763 if (nallocated > PY_SSIZE_T_MAX - repsize + 4) {
4764 /* integer overflow */
4765 PyErr_NoMemory();
4766 goto error;
4767 }
4768 nallocated += repsize - 4;
4769 if (result != NULL) {
4770 if (_PyBytes_Resize(&result, nallocated) < 0)
4771 goto error;
4772 } else {
4773 result = PyBytes_FromStringAndSize(NULL, nallocated);
Victor Stinner31be90b2010-04-22 19:38:16 +00004774 if (result == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004775 goto error;
4776 Py_MEMCPY(PyBytes_AS_STRING(result), stackbuf, offset);
4777 }
4778 p = PyBytes_AS_STRING(result) + offset;
4779 }
Victor Stinner31be90b2010-04-22 19:38:16 +00004780
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004781 if (PyBytes_Check(rep)) {
4782 char *prep = PyBytes_AS_STRING(rep);
4783 for(k = repsize; k > 0; k--)
4784 *p++ = *prep++;
4785 } else /* rep is unicode */ {
4786 const Py_UNICODE *prep = PyUnicode_AS_UNICODE(rep);
4787 Py_UNICODE c;
4788
4789 for(k=0; k<repsize; k++) {
4790 c = prep[k];
4791 if (0x80 <= c) {
Martin v. Löwis9e816682011-11-02 12:45:42 +01004792 raise_encode_exception_obj(&exc, "utf-8",
Victor Stinner7931d9a2011-11-04 00:22:48 +01004793 unicode,
Martin v. Löwis9e816682011-11-02 12:45:42 +01004794 i-1, i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004795 "surrogates not allowed");
Victor Stinner31be90b2010-04-22 19:38:16 +00004796 goto error;
4797 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004798 *p++ = (char)prep[k];
Victor Stinner31be90b2010-04-22 19:38:16 +00004799 }
Victor Stinner31be90b2010-04-22 19:38:16 +00004800 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004801 Py_DECREF(rep);
Victor Stinner31be90b2010-04-22 19:38:16 +00004802 } else if (ch < 0x10000) {
4803 *p++ = (char)(0xe0 | (ch >> 12));
4804 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
4805 *p++ = (char)(0x80 | (ch & 0x3f));
4806 } else /* ch >= 0x10000 */ {
Tim Peters602f7402002-04-27 18:03:26 +00004807 /* Encode UCS4 Unicode ordinals */
4808 *p++ = (char)(0xf0 | (ch >> 18));
4809 *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
4810 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
4811 *p++ = (char)(0x80 | (ch & 0x3f));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004812#if SIZEOF_WCHAR_T == 2
4813 wchar_offset++;
4814#endif
Tim Peters602f7402002-04-27 18:03:26 +00004815 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004816 }
Tim Peters0eca65c2002-04-21 17:28:06 +00004817
Guido van Rossum98297ee2007-11-06 21:34:58 +00004818 if (result == NULL) {
Tim Peters602f7402002-04-27 18:03:26 +00004819 /* This was stack allocated. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004820 nneeded = p - stackbuf;
Tim Peters602f7402002-04-27 18:03:26 +00004821 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00004822 result = PyBytes_FromStringAndSize(stackbuf, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00004823 }
4824 else {
Christian Heimesf3863112007-11-22 07:46:41 +00004825 /* Cut back to size actually needed. */
Christian Heimes72b710a2008-05-26 13:28:38 +00004826 nneeded = p - PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00004827 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00004828 _PyBytes_Resize(&result, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00004829 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004830
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004831 Py_XDECREF(errorHandler);
4832 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004833 return result;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004834 error:
4835 Py_XDECREF(errorHandler);
4836 Py_XDECREF(exc);
4837 Py_XDECREF(result);
4838 return NULL;
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004839
Tim Peters602f7402002-04-27 18:03:26 +00004840#undef MAX_SHORT_UNICHARS
Guido van Rossumd57fd912000-03-10 22:53:23 +00004841}
4842
Alexander Belopolsky40018472011-02-26 01:02:56 +00004843PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004844PyUnicode_EncodeUTF8(const Py_UNICODE *s,
4845 Py_ssize_t size,
4846 const char *errors)
4847{
4848 PyObject *v, *unicode;
4849
4850 unicode = PyUnicode_FromUnicode(s, size);
4851 if (unicode == NULL)
4852 return NULL;
4853 v = _PyUnicode_AsUTF8String(unicode, errors);
4854 Py_DECREF(unicode);
4855 return v;
4856}
4857
4858PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00004859PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004860{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004861 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004862}
4863
Walter Dörwald41980ca2007-08-16 21:55:45 +00004864/* --- UTF-32 Codec ------------------------------------------------------- */
4865
4866PyObject *
4867PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004868 Py_ssize_t size,
4869 const char *errors,
4870 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004871{
4872 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
4873}
4874
4875PyObject *
4876PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004877 Py_ssize_t size,
4878 const char *errors,
4879 int *byteorder,
4880 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004881{
4882 const char *starts = s;
4883 Py_ssize_t startinpos;
4884 Py_ssize_t endinpos;
4885 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004886 PyObject *unicode;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004887 Py_UNICODE *p;
4888#ifndef Py_UNICODE_WIDE
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004889 int pairs = 0;
Mark Dickinson7db923c2010-06-12 09:10:14 +00004890 const unsigned char *qq;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004891#else
4892 const int pairs = 0;
4893#endif
Mark Dickinson7db923c2010-06-12 09:10:14 +00004894 const unsigned char *q, *e;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004895 int bo = 0; /* assume native ordering by default */
4896 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00004897 /* Offsets from q for retrieving bytes in the right order. */
4898#ifdef BYTEORDER_IS_LITTLE_ENDIAN
4899 int iorder[] = {0, 1, 2, 3};
4900#else
4901 int iorder[] = {3, 2, 1, 0};
4902#endif
4903 PyObject *errorHandler = NULL;
4904 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00004905
Walter Dörwald41980ca2007-08-16 21:55:45 +00004906 q = (unsigned char *)s;
4907 e = q + size;
4908
4909 if (byteorder)
4910 bo = *byteorder;
4911
4912 /* Check for BOM marks (U+FEFF) in the input and adjust current
4913 byte order setting accordingly. In native mode, the leading BOM
4914 mark is skipped, in all other modes, it is copied to the output
4915 stream as-is (giving a ZWNBSP character). */
4916 if (bo == 0) {
4917 if (size >= 4) {
4918 const Py_UCS4 bom = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
Benjamin Peterson29060642009-01-31 22:14:21 +00004919 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00004920#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00004921 if (bom == 0x0000FEFF) {
4922 q += 4;
4923 bo = -1;
4924 }
4925 else if (bom == 0xFFFE0000) {
4926 q += 4;
4927 bo = 1;
4928 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004929#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004930 if (bom == 0x0000FEFF) {
4931 q += 4;
4932 bo = 1;
4933 }
4934 else if (bom == 0xFFFE0000) {
4935 q += 4;
4936 bo = -1;
4937 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004938#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00004939 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004940 }
4941
4942 if (bo == -1) {
4943 /* force LE */
4944 iorder[0] = 0;
4945 iorder[1] = 1;
4946 iorder[2] = 2;
4947 iorder[3] = 3;
4948 }
4949 else if (bo == 1) {
4950 /* force BE */
4951 iorder[0] = 3;
4952 iorder[1] = 2;
4953 iorder[2] = 1;
4954 iorder[3] = 0;
4955 }
4956
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004957 /* On narrow builds we split characters outside the BMP into two
4958 codepoints => count how much extra space we need. */
4959#ifndef Py_UNICODE_WIDE
4960 for (qq = q; qq < e; qq += 4)
4961 if (qq[iorder[2]] != 0 || qq[iorder[3]] != 0)
4962 pairs++;
4963#endif
4964
4965 /* This might be one to much, because of a BOM */
Victor Stinner7931d9a2011-11-04 00:22:48 +01004966 unicode = (PyObject*)_PyUnicode_New((size+3)/4+pairs);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004967 if (!unicode)
4968 return NULL;
4969 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01004970 return unicode;
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004971
4972 /* Unpack UTF-32 encoded data */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004973 p = PyUnicode_AS_UNICODE(unicode);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004974
Walter Dörwald41980ca2007-08-16 21:55:45 +00004975 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004976 Py_UCS4 ch;
4977 /* remaining bytes at the end? (size should be divisible by 4) */
4978 if (e-q<4) {
4979 if (consumed)
4980 break;
4981 errmsg = "truncated data";
4982 startinpos = ((const char *)q)-starts;
4983 endinpos = ((const char *)e)-starts;
4984 goto utf32Error;
4985 /* The remaining input chars are ignored if the callback
4986 chooses to skip the input */
4987 }
4988 ch = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
4989 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00004990
Benjamin Peterson29060642009-01-31 22:14:21 +00004991 if (ch >= 0x110000)
4992 {
4993 errmsg = "codepoint not in range(0x110000)";
4994 startinpos = ((const char *)q)-starts;
4995 endinpos = startinpos+4;
4996 goto utf32Error;
4997 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004998#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00004999 if (ch >= 0x10000)
5000 {
5001 *p++ = 0xD800 | ((ch-0x10000) >> 10);
5002 *p++ = 0xDC00 | ((ch-0x10000) & 0x3FF);
5003 }
5004 else
Walter Dörwald41980ca2007-08-16 21:55:45 +00005005#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005006 *p++ = ch;
5007 q += 4;
5008 continue;
5009 utf32Error:
5010 outpos = p-PyUnicode_AS_UNICODE(unicode);
5011 if (unicode_decode_call_errorhandler(
5012 errors, &errorHandler,
5013 "utf32", errmsg,
5014 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
5015 &unicode, &outpos, &p))
5016 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005017 }
5018
5019 if (byteorder)
5020 *byteorder = bo;
5021
5022 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005023 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005024
5025 /* Adjust length */
Victor Stinner7931d9a2011-11-04 00:22:48 +01005026 if (PyUnicode_Resize(&unicode, p - PyUnicode_AS_UNICODE(unicode)) < 0)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005027 goto onError;
5028
5029 Py_XDECREF(errorHandler);
5030 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02005031#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02005032 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005033 Py_DECREF(unicode);
5034 return NULL;
5035 }
Victor Stinner17efeed2011-10-04 20:05:46 +02005036#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02005037 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01005038 return unicode;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005039
Benjamin Peterson29060642009-01-31 22:14:21 +00005040 onError:
Walter Dörwald41980ca2007-08-16 21:55:45 +00005041 Py_DECREF(unicode);
5042 Py_XDECREF(errorHandler);
5043 Py_XDECREF(exc);
5044 return NULL;
5045}
5046
5047PyObject *
5048PyUnicode_EncodeUTF32(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005049 Py_ssize_t size,
5050 const char *errors,
5051 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005052{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005053 PyObject *v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005054 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005055 Py_ssize_t nsize, bytesize;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005056#ifndef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005057 Py_ssize_t i, pairs;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005058#else
5059 const int pairs = 0;
5060#endif
5061 /* Offsets from p for storing byte pairs in the right order. */
5062#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5063 int iorder[] = {0, 1, 2, 3};
5064#else
5065 int iorder[] = {3, 2, 1, 0};
5066#endif
5067
Benjamin Peterson29060642009-01-31 22:14:21 +00005068#define STORECHAR(CH) \
5069 do { \
5070 p[iorder[3]] = ((CH) >> 24) & 0xff; \
5071 p[iorder[2]] = ((CH) >> 16) & 0xff; \
5072 p[iorder[1]] = ((CH) >> 8) & 0xff; \
5073 p[iorder[0]] = (CH) & 0xff; \
5074 p += 4; \
Walter Dörwald41980ca2007-08-16 21:55:45 +00005075 } while(0)
5076
5077 /* In narrow builds we can output surrogate pairs as one codepoint,
5078 so we need less space. */
5079#ifndef Py_UNICODE_WIDE
5080 for (i = pairs = 0; i < size-1; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00005081 if (0xD800 <= s[i] && s[i] <= 0xDBFF &&
5082 0xDC00 <= s[i+1] && s[i+1] <= 0xDFFF)
5083 pairs++;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005084#endif
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005085 nsize = (size - pairs + (byteorder == 0));
5086 bytesize = nsize * 4;
5087 if (bytesize / 4 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005088 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005089 v = PyBytes_FromStringAndSize(NULL, bytesize);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005090 if (v == NULL)
5091 return NULL;
5092
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005093 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005094 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005095 STORECHAR(0xFEFF);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005096 if (size == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005097 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005098
5099 if (byteorder == -1) {
5100 /* force LE */
5101 iorder[0] = 0;
5102 iorder[1] = 1;
5103 iorder[2] = 2;
5104 iorder[3] = 3;
5105 }
5106 else if (byteorder == 1) {
5107 /* force BE */
5108 iorder[0] = 3;
5109 iorder[1] = 2;
5110 iorder[2] = 1;
5111 iorder[3] = 0;
5112 }
5113
5114 while (size-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005115 Py_UCS4 ch = *s++;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005116#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00005117 if (0xD800 <= ch && ch <= 0xDBFF && size > 0) {
5118 Py_UCS4 ch2 = *s;
5119 if (0xDC00 <= ch2 && ch2 <= 0xDFFF) {
5120 ch = (((ch & 0x3FF)<<10) | (ch2 & 0x3FF)) + 0x10000;
5121 s++;
5122 size--;
5123 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005124 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005125#endif
5126 STORECHAR(ch);
5127 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005128
5129 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005130 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005131#undef STORECHAR
5132}
5133
Alexander Belopolsky40018472011-02-26 01:02:56 +00005134PyObject *
5135PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005136{
5137 if (!PyUnicode_Check(unicode)) {
5138 PyErr_BadArgument();
5139 return NULL;
5140 }
5141 return PyUnicode_EncodeUTF32(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00005142 PyUnicode_GET_SIZE(unicode),
5143 NULL,
5144 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005145}
5146
Guido van Rossumd57fd912000-03-10 22:53:23 +00005147/* --- UTF-16 Codec ------------------------------------------------------- */
5148
Tim Peters772747b2001-08-09 22:21:55 +00005149PyObject *
5150PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005151 Py_ssize_t size,
5152 const char *errors,
5153 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005154{
Walter Dörwald69652032004-09-07 20:24:22 +00005155 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5156}
5157
Antoine Pitrouab868312009-01-10 15:40:25 +00005158/* Two masks for fast checking of whether a C 'long' may contain
5159 UTF16-encoded surrogate characters. This is an efficient heuristic,
5160 assuming that non-surrogate characters with a code point >= 0x8000 are
5161 rare in most input.
5162 FAST_CHAR_MASK is used when the input is in native byte ordering,
5163 SWAPPED_FAST_CHAR_MASK when the input is in byteswapped ordering.
Benjamin Peterson29060642009-01-31 22:14:21 +00005164*/
Antoine Pitrouab868312009-01-10 15:40:25 +00005165#if (SIZEOF_LONG == 8)
5166# define FAST_CHAR_MASK 0x8000800080008000L
5167# define SWAPPED_FAST_CHAR_MASK 0x0080008000800080L
5168#elif (SIZEOF_LONG == 4)
5169# define FAST_CHAR_MASK 0x80008000L
5170# define SWAPPED_FAST_CHAR_MASK 0x00800080L
5171#else
5172# error C 'long' size should be either 4 or 8!
5173#endif
5174
Walter Dörwald69652032004-09-07 20:24:22 +00005175PyObject *
5176PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005177 Py_ssize_t size,
5178 const char *errors,
5179 int *byteorder,
5180 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005181{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005182 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005183 Py_ssize_t startinpos;
5184 Py_ssize_t endinpos;
5185 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005186 PyObject *unicode;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005187 Py_UNICODE *p;
Antoine Pitrouab868312009-01-10 15:40:25 +00005188 const unsigned char *q, *e, *aligned_end;
Tim Peters772747b2001-08-09 22:21:55 +00005189 int bo = 0; /* assume native ordering by default */
Antoine Pitrouab868312009-01-10 15:40:25 +00005190 int native_ordering = 0;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005191 const char *errmsg = "";
Tim Peters772747b2001-08-09 22:21:55 +00005192 /* Offsets from q for retrieving byte pairs in the right order. */
5193#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5194 int ihi = 1, ilo = 0;
5195#else
5196 int ihi = 0, ilo = 1;
5197#endif
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005198 PyObject *errorHandler = NULL;
5199 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005200
5201 /* Note: size will always be longer than the resulting Unicode
5202 character count */
Victor Stinner7931d9a2011-11-04 00:22:48 +01005203 unicode = (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005204 if (!unicode)
5205 return NULL;
5206 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005207 return unicode;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005208
5209 /* Unpack UTF-16 encoded data */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005210 p = PyUnicode_AS_UNICODE(unicode);
Tim Peters772747b2001-08-09 22:21:55 +00005211 q = (unsigned char *)s;
Antoine Pitrouab868312009-01-10 15:40:25 +00005212 e = q + size - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005213
5214 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005215 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005216
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005217 /* Check for BOM marks (U+FEFF) in the input and adjust current
5218 byte order setting accordingly. In native mode, the leading BOM
5219 mark is skipped, in all other modes, it is copied to the output
5220 stream as-is (giving a ZWNBSP character). */
5221 if (bo == 0) {
Walter Dörwald69652032004-09-07 20:24:22 +00005222 if (size >= 2) {
5223 const Py_UNICODE bom = (q[ihi] << 8) | q[ilo];
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005224#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00005225 if (bom == 0xFEFF) {
5226 q += 2;
5227 bo = -1;
5228 }
5229 else if (bom == 0xFFFE) {
5230 q += 2;
5231 bo = 1;
5232 }
Tim Petersced69f82003-09-16 20:30:58 +00005233#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005234 if (bom == 0xFEFF) {
5235 q += 2;
5236 bo = 1;
5237 }
5238 else if (bom == 0xFFFE) {
5239 q += 2;
5240 bo = -1;
5241 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005242#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005243 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005244 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005245
Tim Peters772747b2001-08-09 22:21:55 +00005246 if (bo == -1) {
5247 /* force LE */
5248 ihi = 1;
5249 ilo = 0;
5250 }
5251 else if (bo == 1) {
5252 /* force BE */
5253 ihi = 0;
5254 ilo = 1;
5255 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005256#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5257 native_ordering = ilo < ihi;
5258#else
5259 native_ordering = ilo > ihi;
5260#endif
Tim Peters772747b2001-08-09 22:21:55 +00005261
Antoine Pitrouab868312009-01-10 15:40:25 +00005262 aligned_end = (const unsigned char *) ((size_t) e & ~LONG_PTR_MASK);
Tim Peters772747b2001-08-09 22:21:55 +00005263 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005264 Py_UNICODE ch;
Antoine Pitrouab868312009-01-10 15:40:25 +00005265 /* First check for possible aligned read of a C 'long'. Unaligned
5266 reads are more expensive, better to defer to another iteration. */
5267 if (!((size_t) q & LONG_PTR_MASK)) {
5268 /* Fast path for runs of non-surrogate chars. */
5269 register const unsigned char *_q = q;
5270 Py_UNICODE *_p = p;
5271 if (native_ordering) {
5272 /* Native ordering is simple: as long as the input cannot
5273 possibly contain a surrogate char, do an unrolled copy
5274 of several 16-bit code points to the target object.
5275 The non-surrogate check is done on several input bytes
5276 at a time (as many as a C 'long' can contain). */
5277 while (_q < aligned_end) {
5278 unsigned long data = * (unsigned long *) _q;
5279 if (data & FAST_CHAR_MASK)
5280 break;
5281 _p[0] = ((unsigned short *) _q)[0];
5282 _p[1] = ((unsigned short *) _q)[1];
5283#if (SIZEOF_LONG == 8)
5284 _p[2] = ((unsigned short *) _q)[2];
5285 _p[3] = ((unsigned short *) _q)[3];
5286#endif
5287 _q += SIZEOF_LONG;
5288 _p += SIZEOF_LONG / 2;
5289 }
5290 }
5291 else {
5292 /* Byteswapped ordering is similar, but we must decompose
5293 the copy bytewise, and take care of zero'ing out the
5294 upper bytes if the target object is in 32-bit units
5295 (that is, in UCS-4 builds). */
5296 while (_q < aligned_end) {
5297 unsigned long data = * (unsigned long *) _q;
5298 if (data & SWAPPED_FAST_CHAR_MASK)
5299 break;
5300 /* Zero upper bytes in UCS-4 builds */
5301#if (Py_UNICODE_SIZE > 2)
5302 _p[0] = 0;
5303 _p[1] = 0;
5304#if (SIZEOF_LONG == 8)
5305 _p[2] = 0;
5306 _p[3] = 0;
5307#endif
5308#endif
Antoine Pitroud6e8de12009-01-11 23:56:55 +00005309 /* Issue #4916; UCS-4 builds on big endian machines must
5310 fill the two last bytes of each 4-byte unit. */
5311#if (!defined(BYTEORDER_IS_LITTLE_ENDIAN) && Py_UNICODE_SIZE > 2)
5312# define OFF 2
5313#else
5314# define OFF 0
Antoine Pitrouab868312009-01-10 15:40:25 +00005315#endif
Antoine Pitroud6e8de12009-01-11 23:56:55 +00005316 ((unsigned char *) _p)[OFF + 1] = _q[0];
5317 ((unsigned char *) _p)[OFF + 0] = _q[1];
5318 ((unsigned char *) _p)[OFF + 1 + Py_UNICODE_SIZE] = _q[2];
5319 ((unsigned char *) _p)[OFF + 0 + Py_UNICODE_SIZE] = _q[3];
5320#if (SIZEOF_LONG == 8)
5321 ((unsigned char *) _p)[OFF + 1 + 2 * Py_UNICODE_SIZE] = _q[4];
5322 ((unsigned char *) _p)[OFF + 0 + 2 * Py_UNICODE_SIZE] = _q[5];
5323 ((unsigned char *) _p)[OFF + 1 + 3 * Py_UNICODE_SIZE] = _q[6];
5324 ((unsigned char *) _p)[OFF + 0 + 3 * Py_UNICODE_SIZE] = _q[7];
5325#endif
5326#undef OFF
Antoine Pitrouab868312009-01-10 15:40:25 +00005327 _q += SIZEOF_LONG;
5328 _p += SIZEOF_LONG / 2;
5329 }
5330 }
5331 p = _p;
5332 q = _q;
5333 if (q >= e)
5334 break;
5335 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005336 ch = (q[ihi] << 8) | q[ilo];
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005337
Benjamin Peterson14339b62009-01-31 16:36:08 +00005338 q += 2;
Benjamin Peterson29060642009-01-31 22:14:21 +00005339
5340 if (ch < 0xD800 || ch > 0xDFFF) {
5341 *p++ = ch;
5342 continue;
5343 }
5344
5345 /* UTF-16 code pair: */
5346 if (q > e) {
5347 errmsg = "unexpected end of data";
5348 startinpos = (((const char *)q) - 2) - starts;
5349 endinpos = ((const char *)e) + 1 - starts;
5350 goto utf16Error;
5351 }
5352 if (0xD800 <= ch && ch <= 0xDBFF) {
5353 Py_UNICODE ch2 = (q[ihi] << 8) | q[ilo];
5354 q += 2;
5355 if (0xDC00 <= ch2 && ch2 <= 0xDFFF) {
Fredrik Lundh8f455852001-06-27 18:59:43 +00005356#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00005357 *p++ = ch;
5358 *p++ = ch2;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005359#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005360 *p++ = (((ch & 0x3FF)<<10) | (ch2 & 0x3FF)) + 0x10000;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005361#endif
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:
5378 outpos = p - PyUnicode_AS_UNICODE(unicode);
5379 if (unicode_decode_call_errorhandler(
Antoine Pitrouab868312009-01-10 15:40:25 +00005380 errors,
5381 &errorHandler,
5382 "utf16", errmsg,
5383 &starts,
5384 (const char **)&e,
5385 &startinpos,
5386 &endinpos,
5387 &exc,
5388 (const char **)&q,
5389 &unicode,
5390 &outpos,
5391 &p))
Benjamin Peterson29060642009-01-31 22:14:21 +00005392 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005393 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005394 /* remaining byte at the end? (size should be even) */
5395 if (e == q) {
5396 if (!consumed) {
5397 errmsg = "truncated data";
5398 startinpos = ((const char *)q) - starts;
5399 endinpos = ((const char *)e) + 1 - starts;
5400 outpos = p - PyUnicode_AS_UNICODE(unicode);
5401 if (unicode_decode_call_errorhandler(
5402 errors,
5403 &errorHandler,
5404 "utf16", errmsg,
5405 &starts,
5406 (const char **)&e,
5407 &startinpos,
5408 &endinpos,
5409 &exc,
5410 (const char **)&q,
5411 &unicode,
5412 &outpos,
5413 &p))
5414 goto onError;
5415 /* The remaining input chars are ignored if the callback
5416 chooses to skip the input */
5417 }
5418 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005419
5420 if (byteorder)
5421 *byteorder = bo;
5422
Walter Dörwald69652032004-09-07 20:24:22 +00005423 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005424 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005425
Guido van Rossumd57fd912000-03-10 22:53:23 +00005426 /* Adjust length */
Victor Stinner7931d9a2011-11-04 00:22:48 +01005427 if (PyUnicode_Resize(&unicode, p - PyUnicode_AS_UNICODE(unicode)) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005428 goto onError;
5429
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005430 Py_XDECREF(errorHandler);
5431 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02005432#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02005433 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005434 Py_DECREF(unicode);
5435 return NULL;
5436 }
Victor Stinner17efeed2011-10-04 20:05:46 +02005437#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02005438 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01005439 return unicode;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005440
Benjamin Peterson29060642009-01-31 22:14:21 +00005441 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005442 Py_DECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005443 Py_XDECREF(errorHandler);
5444 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005445 return NULL;
5446}
5447
Antoine Pitrouab868312009-01-10 15:40:25 +00005448#undef FAST_CHAR_MASK
5449#undef SWAPPED_FAST_CHAR_MASK
5450
Tim Peters772747b2001-08-09 22:21:55 +00005451PyObject *
5452PyUnicode_EncodeUTF16(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005453 Py_ssize_t size,
5454 const char *errors,
5455 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005456{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005457 PyObject *v;
Tim Peters772747b2001-08-09 22:21:55 +00005458 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005459 Py_ssize_t nsize, bytesize;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005460#ifdef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005461 Py_ssize_t i, pairs;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005462#else
5463 const int pairs = 0;
5464#endif
Tim Peters772747b2001-08-09 22:21:55 +00005465 /* Offsets from p for storing byte pairs in the right order. */
5466#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5467 int ihi = 1, ilo = 0;
5468#else
5469 int ihi = 0, ilo = 1;
5470#endif
5471
Benjamin Peterson29060642009-01-31 22:14:21 +00005472#define STORECHAR(CH) \
5473 do { \
5474 p[ihi] = ((CH) >> 8) & 0xff; \
5475 p[ilo] = (CH) & 0xff; \
5476 p += 2; \
Tim Peters772747b2001-08-09 22:21:55 +00005477 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005478
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005479#ifdef Py_UNICODE_WIDE
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005480 for (i = pairs = 0; i < size; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00005481 if (s[i] >= 0x10000)
5482 pairs++;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005483#endif
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005484 /* 2 * (size + pairs + (byteorder == 0)) */
5485 if (size > PY_SSIZE_T_MAX ||
5486 size > PY_SSIZE_T_MAX - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005487 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005488 nsize = size + pairs + (byteorder == 0);
5489 bytesize = nsize * 2;
5490 if (bytesize / 2 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005491 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005492 v = PyBytes_FromStringAndSize(NULL, bytesize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005493 if (v == NULL)
5494 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005495
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005496 p = (unsigned char *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005497 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005498 STORECHAR(0xFEFF);
Marc-André Lemburg063e0cb2000-07-07 11:27:45 +00005499 if (size == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005500 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005501
5502 if (byteorder == -1) {
5503 /* force LE */
5504 ihi = 1;
5505 ilo = 0;
5506 }
5507 else if (byteorder == 1) {
5508 /* force BE */
5509 ihi = 0;
5510 ilo = 1;
5511 }
5512
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005513 while (size-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005514 Py_UNICODE ch = *s++;
5515 Py_UNICODE ch2 = 0;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005516#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00005517 if (ch >= 0x10000) {
5518 ch2 = 0xDC00 | ((ch-0x10000) & 0x3FF);
5519 ch = 0xD800 | ((ch-0x10000) >> 10);
5520 }
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005521#endif
Tim Peters772747b2001-08-09 22:21:55 +00005522 STORECHAR(ch);
5523 if (ch2)
5524 STORECHAR(ch2);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005525 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005526
5527 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005528 return v;
Tim Peters772747b2001-08-09 22:21:55 +00005529#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005530}
5531
Alexander Belopolsky40018472011-02-26 01:02:56 +00005532PyObject *
5533PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005534{
5535 if (!PyUnicode_Check(unicode)) {
5536 PyErr_BadArgument();
5537 return NULL;
5538 }
5539 return PyUnicode_EncodeUTF16(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00005540 PyUnicode_GET_SIZE(unicode),
5541 NULL,
5542 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005543}
5544
5545/* --- Unicode Escape Codec ----------------------------------------------- */
5546
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005547/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5548 if all the escapes in the string make it still a valid ASCII string.
5549 Returns -1 if any escapes were found which cause the string to
5550 pop out of ASCII range. Otherwise returns the length of the
5551 required buffer to hold the string.
5552 */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02005553static Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005554length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5555{
5556 const unsigned char *p = (const unsigned char *)s;
5557 const unsigned char *end = p + size;
5558 Py_ssize_t length = 0;
5559
5560 if (size < 0)
5561 return -1;
5562
5563 for (; p < end; ++p) {
5564 if (*p > 127) {
5565 /* Non-ASCII */
5566 return -1;
5567 }
5568 else if (*p != '\\') {
5569 /* Normal character */
5570 ++length;
5571 }
5572 else {
5573 /* Backslash-escape, check next char */
5574 ++p;
5575 /* Escape sequence reaches till end of string or
5576 non-ASCII follow-up. */
5577 if (p >= end || *p > 127)
5578 return -1;
5579 switch (*p) {
5580 case '\n':
5581 /* backslash + \n result in zero characters */
5582 break;
5583 case '\\': case '\'': case '\"':
5584 case 'b': case 'f': case 't':
5585 case 'n': case 'r': case 'v': case 'a':
5586 ++length;
5587 break;
5588 case '0': case '1': case '2': case '3':
5589 case '4': case '5': case '6': case '7':
5590 case 'x': case 'u': case 'U': case 'N':
5591 /* these do not guarantee ASCII characters */
5592 return -1;
5593 default:
5594 /* count the backslash + the other character */
5595 length += 2;
5596 }
5597 }
5598 }
5599 return length;
5600}
5601
5602/* Similar to PyUnicode_WRITE but either write into wstr field
5603 or treat string as ASCII. */
5604#define WRITE_ASCII_OR_WSTR(kind, buf, index, value) \
5605 do { \
5606 if ((kind) != PyUnicode_WCHAR_KIND) \
5607 ((unsigned char *)(buf))[(index)] = (unsigned char)(value); \
5608 else \
5609 ((Py_UNICODE *)(buf))[(index)] = (Py_UNICODE)(value); \
5610 } while (0)
5611
5612#define WRITE_WSTR(buf, index, value) \
5613 assert(kind == PyUnicode_WCHAR_KIND), \
5614 ((Py_UNICODE *)(buf))[(index)] = (Py_UNICODE)(value)
5615
5616
Fredrik Lundh06d12682001-01-24 07:59:11 +00005617static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005618
Alexander Belopolsky40018472011-02-26 01:02:56 +00005619PyObject *
5620PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005621 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005622 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005623{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005624 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005625 Py_ssize_t startinpos;
5626 Py_ssize_t endinpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005627 int j;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005628 PyObject *v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005629 Py_UNICODE *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005630 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005631 char* message;
5632 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005633 PyObject *errorHandler = NULL;
5634 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005635 Py_ssize_t ascii_length;
5636 Py_ssize_t i;
5637 int kind;
5638 void *data;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005639
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005640 ascii_length = length_of_escaped_ascii_string(s, size);
5641
5642 /* After length_of_escaped_ascii_string() there are two alternatives,
5643 either the string is pure ASCII with named escapes like \n, etc.
5644 and we determined it's exact size (common case)
5645 or it contains \x, \u, ... escape sequences. then we create a
5646 legacy wchar string and resize it at the end of this function. */
5647 if (ascii_length >= 0) {
Victor Stinner7931d9a2011-11-04 00:22:48 +01005648 v = PyUnicode_New(ascii_length, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005649 if (!v)
5650 goto onError;
5651 assert(PyUnicode_KIND(v) == PyUnicode_1BYTE_KIND);
5652 kind = PyUnicode_1BYTE_KIND;
5653 data = PyUnicode_DATA(v);
5654 }
5655 else {
5656 /* Escaped strings will always be longer than the resulting
5657 Unicode string, so we start with size here and then reduce the
5658 length after conversion to the true value.
5659 (but if the error callback returns a long replacement string
5660 we'll have to allocate more space) */
Victor Stinner7931d9a2011-11-04 00:22:48 +01005661 v = (PyObject*)_PyUnicode_New(size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005662 if (!v)
5663 goto onError;
5664 kind = PyUnicode_WCHAR_KIND;
5665 data = PyUnicode_AS_UNICODE(v);
5666 }
5667
Guido van Rossumd57fd912000-03-10 22:53:23 +00005668 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005669 return v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005670 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005671 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005672
Guido van Rossumd57fd912000-03-10 22:53:23 +00005673 while (s < end) {
5674 unsigned char c;
Marc-André Lemburg063e0cb2000-07-07 11:27:45 +00005675 Py_UNICODE x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005676 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005677
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005678 if (kind == PyUnicode_WCHAR_KIND) {
5679 assert(i < _PyUnicode_WSTR_LENGTH(v));
5680 }
5681 else {
5682 /* The only case in which i == ascii_length is a backslash
5683 followed by a newline. */
5684 assert(i <= ascii_length);
5685 }
5686
Guido van Rossumd57fd912000-03-10 22:53:23 +00005687 /* Non-escape characters are interpreted as Unicode ordinals */
5688 if (*s != '\\') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005689 WRITE_ASCII_OR_WSTR(kind, data, i++, (unsigned char) *s++);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005690 continue;
5691 }
5692
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005693 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005694 /* \ - Escapes */
5695 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005696 c = *s++;
5697 if (s > end)
5698 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005699
5700 if (kind == PyUnicode_WCHAR_KIND) {
5701 assert(i < _PyUnicode_WSTR_LENGTH(v));
5702 }
5703 else {
5704 /* The only case in which i == ascii_length is a backslash
5705 followed by a newline. */
5706 assert(i < ascii_length || (i == ascii_length && c == '\n'));
5707 }
5708
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005709 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005710
Benjamin Peterson29060642009-01-31 22:14:21 +00005711 /* \x escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005712 case '\n': break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005713 case '\\': WRITE_ASCII_OR_WSTR(kind, data, i++, '\\'); break;
5714 case '\'': WRITE_ASCII_OR_WSTR(kind, data, i++, '\''); break;
5715 case '\"': WRITE_ASCII_OR_WSTR(kind, data, i++, '\"'); break;
5716 case 'b': WRITE_ASCII_OR_WSTR(kind, data, i++, '\b'); break;
5717 /* FF */
5718 case 'f': WRITE_ASCII_OR_WSTR(kind, data, i++, '\014'); break;
5719 case 't': WRITE_ASCII_OR_WSTR(kind, data, i++, '\t'); break;
5720 case 'n': WRITE_ASCII_OR_WSTR(kind, data, i++, '\n'); break;
5721 case 'r': WRITE_ASCII_OR_WSTR(kind, data, i++, '\r'); break;
5722 /* VT */
5723 case 'v': WRITE_ASCII_OR_WSTR(kind, data, i++, '\013'); break;
5724 /* BEL, not classic C */
5725 case 'a': WRITE_ASCII_OR_WSTR(kind, data, i++, '\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005726
Benjamin Peterson29060642009-01-31 22:14:21 +00005727 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005728 case '0': case '1': case '2': case '3':
5729 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005730 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005731 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005732 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005733 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005734 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00005735 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005736 WRITE_WSTR(data, i++, x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005737 break;
5738
Benjamin Peterson29060642009-01-31 22:14:21 +00005739 /* hex escapes */
5740 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005741 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005742 digits = 2;
5743 message = "truncated \\xXX escape";
5744 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005745
Benjamin Peterson29060642009-01-31 22:14:21 +00005746 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005747 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005748 digits = 4;
5749 message = "truncated \\uXXXX escape";
5750 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005751
Benjamin Peterson29060642009-01-31 22:14:21 +00005752 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005753 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005754 digits = 8;
5755 message = "truncated \\UXXXXXXXX escape";
5756 hexescape:
5757 chr = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005758 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005759 if (s+digits>end) {
5760 endinpos = size;
5761 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005762 errors, &errorHandler,
5763 "unicodeescape", "end of string in escape sequence",
5764 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005765 &v, &i, &p))
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005766 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005767 data = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005768 goto nextByte;
5769 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005770 for (j = 0; j < digits; ++j) {
5771 c = (unsigned char) s[j];
David Malcolm96960882010-11-05 17:23:41 +00005772 if (!Py_ISXDIGIT(c)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005773 endinpos = (s+j+1)-starts;
5774 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005775 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005776 errors, &errorHandler,
5777 "unicodeescape", message,
5778 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005779 &v, &i, &p))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005780 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005781 data = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005782 goto nextByte;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005783 }
5784 chr = (chr<<4) & ~0xF;
5785 if (c >= '0' && c <= '9')
5786 chr += c - '0';
5787 else if (c >= 'a' && c <= 'f')
5788 chr += 10 + c - 'a';
5789 else
5790 chr += 10 + c - 'A';
5791 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005792 s += j;
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005793 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005794 /* _decoding_error will have already written into the
5795 target buffer. */
5796 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005797 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005798 /* when we get here, chr is a 32-bit unicode character */
5799 if (chr <= 0xffff)
5800 /* UCS-2 character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005801 WRITE_WSTR(data, i++, chr);
Fredrik Lundhdf846752000-09-03 11:29:49 +00005802 else if (chr <= 0x10ffff) {
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005803 /* UCS-4 character. Either store directly, or as
Walter Dörwald8c077222002-03-25 11:16:18 +00005804 surrogate pair. */
Fredrik Lundh8f455852001-06-27 18:59:43 +00005805#ifdef Py_UNICODE_WIDE
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005806 WRITE_WSTR(data, i++, chr);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005807#else
Fredrik Lundhdf846752000-09-03 11:29:49 +00005808 chr -= 0x10000L;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005809 WRITE_WSTR(data, i++, 0xD800 + (Py_UNICODE) (chr >> 10));
5810 WRITE_WSTR(data, i++, 0xDC00 + (Py_UNICODE) (chr & 0x03FF));
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005811#endif
Fredrik Lundhdf846752000-09-03 11:29:49 +00005812 } else {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005813 endinpos = s-starts;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005814 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005815 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005816 errors, &errorHandler,
5817 "unicodeescape", "illegal Unicode character",
5818 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005819 &v, &i, &p))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005820 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005821 data = PyUnicode_AS_UNICODE(v);
Fredrik Lundhdf846752000-09-03 11:29:49 +00005822 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005823 break;
5824
Benjamin Peterson29060642009-01-31 22:14:21 +00005825 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005826 case 'N':
5827 message = "malformed \\N character escape";
5828 if (ucnhash_CAPI == NULL) {
5829 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005830 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
5831 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005832 if (ucnhash_CAPI == NULL)
5833 goto ucnhashError;
5834 }
5835 if (*s == '{') {
5836 const char *start = s+1;
5837 /* look for the closing brace */
5838 while (*s != '}' && s < end)
5839 s++;
5840 if (s > start && s < end && *s == '}') {
5841 /* found a name. look it up in the unicode database */
5842 message = "unknown Unicode character name";
5843 s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005844 if (ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
Ezio Melotti931b8aa2011-10-21 21:57:36 +03005845 &chr, 0))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005846 goto store;
5847 }
5848 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005849 endinpos = s-starts;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005850 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005851 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005852 errors, &errorHandler,
5853 "unicodeescape", message,
5854 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005855 &v, &i, &p))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005856 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005857 data = PyUnicode_AS_UNICODE(v);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005858 break;
5859
5860 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00005861 if (s > end) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005862 assert(kind == PyUnicode_WCHAR_KIND);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005863 message = "\\ at end of string";
5864 s--;
5865 endinpos = s-starts;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005866 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005867 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005868 errors, &errorHandler,
5869 "unicodeescape", message,
5870 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005871 &v, &i, &p))
Walter Dörwald8c077222002-03-25 11:16:18 +00005872 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005873 data = PyUnicode_AS_UNICODE(v);
Walter Dörwald8c077222002-03-25 11:16:18 +00005874 }
5875 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005876 WRITE_ASCII_OR_WSTR(kind, data, i++, '\\');
5877 WRITE_ASCII_OR_WSTR(kind, data, i++, (unsigned char)s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00005878 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005879 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005880 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005881 nextByte:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005882 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005883 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005884 /* Ensure the length prediction worked in case of ASCII strings */
5885 assert(kind == PyUnicode_WCHAR_KIND || i == ascii_length);
5886
Victor Stinnerfe226c02011-10-03 03:52:20 +02005887 if (kind == PyUnicode_WCHAR_KIND)
5888 {
Victor Stinner7931d9a2011-11-04 00:22:48 +01005889 if (PyUnicode_Resize(&v, i) < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02005890 goto onError;
Victor Stinnerfe226c02011-10-03 03:52:20 +02005891 }
Walter Dörwaldd4ade082003-08-15 15:00:26 +00005892 Py_XDECREF(errorHandler);
5893 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02005894#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02005895 if (_PyUnicode_READY_REPLACE(&v)) {
5896 Py_DECREF(v);
5897 return NULL;
5898 }
Victor Stinner17efeed2011-10-04 20:05:46 +02005899#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02005900 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01005901 return v;
Walter Dörwald8c077222002-03-25 11:16:18 +00005902
Benjamin Peterson29060642009-01-31 22:14:21 +00005903 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00005904 PyErr_SetString(
5905 PyExc_UnicodeError,
5906 "\\N escapes not supported (can't load unicodedata module)"
5907 );
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00005908 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005909 Py_XDECREF(errorHandler);
5910 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00005911 return NULL;
5912
Benjamin Peterson29060642009-01-31 22:14:21 +00005913 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005914 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005915 Py_XDECREF(errorHandler);
5916 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005917 return NULL;
5918}
5919
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005920#undef WRITE_ASCII_OR_WSTR
5921#undef WRITE_WSTR
5922
Guido van Rossumd57fd912000-03-10 22:53:23 +00005923/* Return a Unicode-Escape string version of the Unicode object.
5924
5925 If quotes is true, the string is enclosed in u"" or u'' quotes as
5926 appropriate.
5927
5928*/
5929
Alexander Belopolsky40018472011-02-26 01:02:56 +00005930PyObject *
5931PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005932 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005933{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005934 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005935 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005936
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005937#ifdef Py_UNICODE_WIDE
5938 const Py_ssize_t expandsize = 10;
5939#else
5940 const Py_ssize_t expandsize = 6;
5941#endif
5942
Thomas Wouters89f507f2006-12-13 04:49:30 +00005943 /* XXX(nnorwitz): rather than over-allocating, it would be
5944 better to choose a different scheme. Perhaps scan the
5945 first N-chars of the string and allocate based on that size.
5946 */
5947 /* Initial allocation is based on the longest-possible unichr
5948 escape.
5949
5950 In wide (UTF-32) builds '\U00xxxxxx' is 10 chars per source
5951 unichr, so in this case it's the longest unichr escape. In
5952 narrow (UTF-16) builds this is five chars per source unichr
5953 since there are two unichrs in the surrogate pair, so in narrow
5954 (UTF-16) builds it's not the longest unichr escape.
5955
5956 In wide or narrow builds '\uxxxx' is 6 chars per source unichr,
5957 so in the narrow (UTF-16) build case it's the longest unichr
5958 escape.
5959 */
5960
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005961 if (size == 0)
5962 return PyBytes_FromStringAndSize(NULL, 0);
5963
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005964 if (size > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005965 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005966
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005967 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00005968 2
5969 + expandsize*size
5970 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005971 if (repr == NULL)
5972 return NULL;
5973
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005974 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005975
Guido van Rossumd57fd912000-03-10 22:53:23 +00005976 while (size-- > 0) {
5977 Py_UNICODE ch = *s++;
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005978
Walter Dörwald79e913e2007-05-12 11:08:06 +00005979 /* Escape backslashes */
5980 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005981 *p++ = '\\';
5982 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00005983 continue;
Tim Petersced69f82003-09-16 20:30:58 +00005984 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005985
Guido van Rossum0d42e0c2001-07-20 16:36:21 +00005986#ifdef Py_UNICODE_WIDE
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005987 /* Map 21-bit characters to '\U00xxxxxx' */
5988 else if (ch >= 0x10000) {
5989 *p++ = '\\';
5990 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005991 *p++ = Py_hexdigits[(ch >> 28) & 0x0000000F];
5992 *p++ = Py_hexdigits[(ch >> 24) & 0x0000000F];
5993 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
5994 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
5995 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
5996 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
5997 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
5998 *p++ = Py_hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00005999 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00006000 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00006001#else
Benjamin Peterson29060642009-01-31 22:14:21 +00006002 /* Map UTF-16 surrogate pairs to '\U00xxxxxx' */
6003 else if (ch >= 0xD800 && ch < 0xDC00) {
6004 Py_UNICODE ch2;
6005 Py_UCS4 ucs;
Tim Petersced69f82003-09-16 20:30:58 +00006006
Benjamin Peterson29060642009-01-31 22:14:21 +00006007 ch2 = *s++;
6008 size--;
Georg Brandl78eef3de2010-08-01 20:51:02 +00006009 if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006010 ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
6011 *p++ = '\\';
6012 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006013 *p++ = Py_hexdigits[(ucs >> 28) & 0x0000000F];
6014 *p++ = Py_hexdigits[(ucs >> 24) & 0x0000000F];
6015 *p++ = Py_hexdigits[(ucs >> 20) & 0x0000000F];
6016 *p++ = Py_hexdigits[(ucs >> 16) & 0x0000000F];
6017 *p++ = Py_hexdigits[(ucs >> 12) & 0x0000000F];
6018 *p++ = Py_hexdigits[(ucs >> 8) & 0x0000000F];
6019 *p++ = Py_hexdigits[(ucs >> 4) & 0x0000000F];
6020 *p++ = Py_hexdigits[ucs & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00006021 continue;
6022 }
6023 /* Fall through: isolated surrogates are copied as-is */
6024 s--;
6025 size++;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006026 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00006027#endif
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00006028
Guido van Rossumd57fd912000-03-10 22:53:23 +00006029 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00006030 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006031 *p++ = '\\';
6032 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006033 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
6034 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
6035 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6036 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006037 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006038
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006039 /* Map special whitespace to '\t', \n', '\r' */
6040 else if (ch == '\t') {
6041 *p++ = '\\';
6042 *p++ = 't';
6043 }
6044 else if (ch == '\n') {
6045 *p++ = '\\';
6046 *p++ = 'n';
6047 }
6048 else if (ch == '\r') {
6049 *p++ = '\\';
6050 *p++ = 'r';
6051 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006052
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006053 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00006054 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006055 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006056 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006057 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6058 *p++ = Py_hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00006059 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006060
Guido van Rossumd57fd912000-03-10 22:53:23 +00006061 /* Copy everything else as-is */
6062 else
6063 *p++ = (char) ch;
6064 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006065
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006066 assert(p - PyBytes_AS_STRING(repr) > 0);
6067 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
6068 return NULL;
6069 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006070}
6071
Alexander Belopolsky40018472011-02-26 01:02:56 +00006072PyObject *
6073PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006074{
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00006075 PyObject *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006076 if (!PyUnicode_Check(unicode)) {
6077 PyErr_BadArgument();
6078 return NULL;
6079 }
Walter Dörwald79e913e2007-05-12 11:08:06 +00006080 s = PyUnicode_EncodeUnicodeEscape(PyUnicode_AS_UNICODE(unicode),
6081 PyUnicode_GET_SIZE(unicode));
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00006082 return s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006083}
6084
6085/* --- Raw Unicode Escape Codec ------------------------------------------- */
6086
Alexander Belopolsky40018472011-02-26 01:02:56 +00006087PyObject *
6088PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006089 Py_ssize_t size,
6090 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006091{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006092 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006093 Py_ssize_t startinpos;
6094 Py_ssize_t endinpos;
6095 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006096 PyObject *v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006097 Py_UNICODE *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006098 const char *end;
6099 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006100 PyObject *errorHandler = NULL;
6101 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006102
Guido van Rossumd57fd912000-03-10 22:53:23 +00006103 /* Escaped strings will always be longer than the resulting
6104 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006105 length after conversion to the true value. (But decoding error
6106 handler might have to resize the string) */
Victor Stinner7931d9a2011-11-04 00:22:48 +01006107 v = (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006108 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006109 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006110 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006111 return v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006112 p = PyUnicode_AS_UNICODE(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006113 end = s + size;
6114 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006115 unsigned char c;
6116 Py_UCS4 x;
6117 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006118 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006119
Benjamin Peterson29060642009-01-31 22:14:21 +00006120 /* Non-escape characters are interpreted as Unicode ordinals */
6121 if (*s != '\\') {
6122 *p++ = (unsigned char)*s++;
6123 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006124 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006125 startinpos = s-starts;
6126
6127 /* \u-escapes are only interpreted iff the number of leading
6128 backslashes if odd */
6129 bs = s;
6130 for (;s < end;) {
6131 if (*s != '\\')
6132 break;
6133 *p++ = (unsigned char)*s++;
6134 }
6135 if (((s - bs) & 1) == 0 ||
6136 s >= end ||
6137 (*s != 'u' && *s != 'U')) {
6138 continue;
6139 }
6140 p--;
6141 count = *s=='u' ? 4 : 8;
6142 s++;
6143
6144 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
6145 outpos = p-PyUnicode_AS_UNICODE(v);
6146 for (x = 0, i = 0; i < count; ++i, ++s) {
6147 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00006148 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006149 endinpos = s-starts;
6150 if (unicode_decode_call_errorhandler(
6151 errors, &errorHandler,
6152 "rawunicodeescape", "truncated \\uXXXX",
6153 &starts, &end, &startinpos, &endinpos, &exc, &s,
6154 &v, &outpos, &p))
6155 goto onError;
6156 goto nextByte;
6157 }
6158 x = (x<<4) & ~0xF;
6159 if (c >= '0' && c <= '9')
6160 x += c - '0';
6161 else if (c >= 'a' && c <= 'f')
6162 x += 10 + c - 'a';
6163 else
6164 x += 10 + c - 'A';
6165 }
Christian Heimesfe337bf2008-03-23 21:54:12 +00006166 if (x <= 0xffff)
Benjamin Peterson29060642009-01-31 22:14:21 +00006167 /* UCS-2 character */
6168 *p++ = (Py_UNICODE) x;
Christian Heimesfe337bf2008-03-23 21:54:12 +00006169 else if (x <= 0x10ffff) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006170 /* UCS-4 character. Either store directly, or as
6171 surrogate pair. */
Christian Heimesfe337bf2008-03-23 21:54:12 +00006172#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00006173 *p++ = (Py_UNICODE) x;
Christian Heimesfe337bf2008-03-23 21:54:12 +00006174#else
Benjamin Peterson29060642009-01-31 22:14:21 +00006175 x -= 0x10000L;
6176 *p++ = 0xD800 + (Py_UNICODE) (x >> 10);
6177 *p++ = 0xDC00 + (Py_UNICODE) (x & 0x03FF);
Christian Heimesfe337bf2008-03-23 21:54:12 +00006178#endif
6179 } else {
6180 endinpos = s-starts;
6181 outpos = p-PyUnicode_AS_UNICODE(v);
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006182 if (unicode_decode_call_errorhandler(
6183 errors, &errorHandler,
6184 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00006185 &starts, &end, &startinpos, &endinpos, &exc, &s,
6186 &v, &outpos, &p))
6187 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006188 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006189 nextByte:
6190 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006191 }
Victor Stinner7931d9a2011-11-04 00:22:48 +01006192 if (PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006193 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006194 Py_XDECREF(errorHandler);
6195 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02006196#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02006197 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006198 Py_DECREF(v);
6199 return NULL;
6200 }
Victor Stinner17efeed2011-10-04 20:05:46 +02006201#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006202 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01006203 return v;
Tim Petersced69f82003-09-16 20:30:58 +00006204
Benjamin Peterson29060642009-01-31 22:14:21 +00006205 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006206 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006207 Py_XDECREF(errorHandler);
6208 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006209 return NULL;
6210}
6211
Alexander Belopolsky40018472011-02-26 01:02:56 +00006212PyObject *
6213PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006214 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006215{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006216 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006217 char *p;
6218 char *q;
6219
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006220#ifdef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00006221 const Py_ssize_t expandsize = 10;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006222#else
Neal Norwitz3ce5d922008-08-24 07:08:55 +00006223 const Py_ssize_t expandsize = 6;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006224#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00006225
Neal Norwitz3ce5d922008-08-24 07:08:55 +00006226 if (size > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006227 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00006228
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006229 repr = PyBytes_FromStringAndSize(NULL, expandsize * size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006230 if (repr == NULL)
6231 return NULL;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00006232 if (size == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006233 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006234
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006235 p = q = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006236 while (size-- > 0) {
6237 Py_UNICODE ch = *s++;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006238#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00006239 /* Map 32-bit characters to '\Uxxxxxxxx' */
6240 if (ch >= 0x10000) {
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006241 *p++ = '\\';
6242 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006243 *p++ = Py_hexdigits[(ch >> 28) & 0xf];
6244 *p++ = Py_hexdigits[(ch >> 24) & 0xf];
6245 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6246 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6247 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6248 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6249 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6250 *p++ = Py_hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00006251 }
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006252 else
Christian Heimesfe337bf2008-03-23 21:54:12 +00006253#else
Benjamin Peterson29060642009-01-31 22:14:21 +00006254 /* Map UTF-16 surrogate pairs to '\U00xxxxxx' */
6255 if (ch >= 0xD800 && ch < 0xDC00) {
6256 Py_UNICODE ch2;
6257 Py_UCS4 ucs;
Christian Heimesfe337bf2008-03-23 21:54:12 +00006258
Benjamin Peterson29060642009-01-31 22:14:21 +00006259 ch2 = *s++;
6260 size--;
Georg Brandl78eef3de2010-08-01 20:51:02 +00006261 if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006262 ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
6263 *p++ = '\\';
6264 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006265 *p++ = Py_hexdigits[(ucs >> 28) & 0xf];
6266 *p++ = Py_hexdigits[(ucs >> 24) & 0xf];
6267 *p++ = Py_hexdigits[(ucs >> 20) & 0xf];
6268 *p++ = Py_hexdigits[(ucs >> 16) & 0xf];
6269 *p++ = Py_hexdigits[(ucs >> 12) & 0xf];
6270 *p++ = Py_hexdigits[(ucs >> 8) & 0xf];
6271 *p++ = Py_hexdigits[(ucs >> 4) & 0xf];
6272 *p++ = Py_hexdigits[ucs & 0xf];
Benjamin Peterson29060642009-01-31 22:14:21 +00006273 continue;
6274 }
6275 /* Fall through: isolated surrogates are copied as-is */
6276 s--;
6277 size++;
6278 }
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006279#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00006280 /* Map 16-bit characters to '\uxxxx' */
6281 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006282 *p++ = '\\';
6283 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006284 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6285 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6286 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6287 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006288 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006289 /* Copy everything else as-is */
6290 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00006291 *p++ = (char) ch;
6292 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006293 size = p - q;
6294
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006295 assert(size > 0);
6296 if (_PyBytes_Resize(&repr, size) < 0)
6297 return NULL;
6298 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006299}
6300
Alexander Belopolsky40018472011-02-26 01:02:56 +00006301PyObject *
6302PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006303{
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00006304 PyObject *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006305 if (!PyUnicode_Check(unicode)) {
Walter Dörwald711005d2007-05-12 12:03:26 +00006306 PyErr_BadArgument();
6307 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006308 }
Walter Dörwald711005d2007-05-12 12:03:26 +00006309 s = PyUnicode_EncodeRawUnicodeEscape(PyUnicode_AS_UNICODE(unicode),
6310 PyUnicode_GET_SIZE(unicode));
6311
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00006312 return s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006313}
6314
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006315/* --- Unicode Internal Codec ------------------------------------------- */
6316
Alexander Belopolsky40018472011-02-26 01:02:56 +00006317PyObject *
6318_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006319 Py_ssize_t size,
6320 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006321{
6322 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006323 Py_ssize_t startinpos;
6324 Py_ssize_t endinpos;
6325 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006326 PyObject *v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006327 Py_UNICODE *p;
6328 const char *end;
6329 const char *reason;
6330 PyObject *errorHandler = NULL;
6331 PyObject *exc = NULL;
6332
Neal Norwitzd43069c2006-01-08 01:12:10 +00006333#ifdef Py_UNICODE_WIDE
6334 Py_UNICODE unimax = PyUnicode_GetMax();
6335#endif
6336
Thomas Wouters89f507f2006-12-13 04:49:30 +00006337 /* XXX overflow detection missing */
Victor Stinner7931d9a2011-11-04 00:22:48 +01006338 v = (PyObject*)_PyUnicode_New((size+Py_UNICODE_SIZE-1)/ Py_UNICODE_SIZE);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006339 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006340 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006341 /* Intentionally PyUnicode_GET_SIZE instead of PyUnicode_GET_LENGTH
6342 as string was created with the old API. */
6343 if (PyUnicode_GET_SIZE(v) == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006344 return v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006345 p = PyUnicode_AS_UNICODE(v);
6346 end = s + size;
6347
6348 while (s < end) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00006349 memcpy(p, s, sizeof(Py_UNICODE));
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006350 /* We have to sanity check the raw data, otherwise doom looms for
6351 some malformed UCS-4 data. */
6352 if (
Benjamin Peterson29060642009-01-31 22:14:21 +00006353#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006354 *p > unimax || *p < 0 ||
Benjamin Peterson29060642009-01-31 22:14:21 +00006355#endif
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006356 end-s < Py_UNICODE_SIZE
6357 )
Benjamin Peterson29060642009-01-31 22:14:21 +00006358 {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006359 startinpos = s - starts;
6360 if (end-s < Py_UNICODE_SIZE) {
6361 endinpos = end-starts;
6362 reason = "truncated input";
6363 }
6364 else {
6365 endinpos = s - starts + Py_UNICODE_SIZE;
6366 reason = "illegal code point (> 0x10FFFF)";
6367 }
6368 outpos = p - PyUnicode_AS_UNICODE(v);
6369 if (unicode_decode_call_errorhandler(
6370 errors, &errorHandler,
6371 "unicode_internal", reason,
Walter Dörwalde78178e2007-07-30 13:31:40 +00006372 &starts, &end, &startinpos, &endinpos, &exc, &s,
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00006373 &v, &outpos, &p)) {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006374 goto onError;
6375 }
6376 }
6377 else {
6378 p++;
6379 s += Py_UNICODE_SIZE;
6380 }
6381 }
6382
Victor Stinner7931d9a2011-11-04 00:22:48 +01006383 if (PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006384 goto onError;
6385 Py_XDECREF(errorHandler);
6386 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02006387#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02006388 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006389 Py_DECREF(v);
6390 return NULL;
6391 }
Victor Stinner17efeed2011-10-04 20:05:46 +02006392#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006393 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01006394 return v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006395
Benjamin Peterson29060642009-01-31 22:14:21 +00006396 onError:
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006397 Py_XDECREF(v);
6398 Py_XDECREF(errorHandler);
6399 Py_XDECREF(exc);
6400 return NULL;
6401}
6402
Guido van Rossumd57fd912000-03-10 22:53:23 +00006403/* --- Latin-1 Codec ------------------------------------------------------ */
6404
Alexander Belopolsky40018472011-02-26 01:02:56 +00006405PyObject *
6406PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006407 Py_ssize_t size,
6408 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006409{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006410 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006411 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006412}
6413
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006414/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006415static void
6416make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006417 const char *encoding,
6418 const Py_UNICODE *unicode, Py_ssize_t size,
6419 Py_ssize_t startpos, Py_ssize_t endpos,
6420 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006421{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006422 if (*exceptionObject == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006423 *exceptionObject = PyUnicodeEncodeError_Create(
6424 encoding, unicode, size, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006425 }
6426 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006427 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6428 goto onError;
6429 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6430 goto onError;
6431 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6432 goto onError;
6433 return;
6434 onError:
6435 Py_DECREF(*exceptionObject);
6436 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006437 }
6438}
6439
Martin v. Löwis9e816682011-11-02 12:45:42 +01006440/* This is ultimately going t replace above function. */
6441static void
6442make_encode_exception_obj(PyObject **exceptionObject,
6443 const char *encoding,
6444 PyObject *unicode,
6445 Py_ssize_t startpos, Py_ssize_t endpos,
6446 const char *reason)
6447{
6448 if (*exceptionObject == NULL) {
6449 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006450 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006451 encoding, unicode, startpos, endpos, reason);
6452 }
6453 else {
6454 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6455 goto onError;
6456 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6457 goto onError;
6458 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6459 goto onError;
6460 return;
6461 onError:
6462 Py_DECREF(*exceptionObject);
6463 *exceptionObject = NULL;
6464 }
6465}
6466
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006467/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006468static void
6469raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006470 const char *encoding,
6471 const Py_UNICODE *unicode, Py_ssize_t size,
6472 Py_ssize_t startpos, Py_ssize_t endpos,
6473 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006474{
6475 make_encode_exception(exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00006476 encoding, unicode, size, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006477 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006478 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006479}
Martin v. Löwis9e816682011-11-02 12:45:42 +01006480/* This is ultimately going to replace above function. */
6481static void
6482raise_encode_exception_obj(PyObject **exceptionObject,
6483 const char *encoding,
6484 PyObject *unicode,
6485 Py_ssize_t startpos, Py_ssize_t endpos,
6486 const char *reason)
6487{
6488 make_encode_exception_obj(exceptionObject,
6489 encoding, unicode, startpos, endpos, reason);
6490 if (*exceptionObject != NULL)
6491 PyCodec_StrictErrors(*exceptionObject);
6492}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006493
6494/* error handling callback helper:
6495 build arguments, call the callback and check the arguments,
6496 put the result into newpos and return the replacement string, which
6497 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006498static PyObject *
6499unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006500 PyObject **errorHandler,
6501 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006502 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006503 Py_ssize_t startpos, Py_ssize_t endpos,
6504 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006505{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006506 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006507 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006508 PyObject *restuple;
6509 PyObject *resunicode;
6510
6511 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006512 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006513 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006514 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006515 }
6516
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006517 if (PyUnicode_READY(unicode) < 0)
6518 return NULL;
6519 len = PyUnicode_GET_LENGTH(unicode);
6520
6521 make_encode_exception_obj(exceptionObject,
6522 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006523 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006524 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006525
6526 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006527 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006528 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006529 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006530 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006531 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006532 Py_DECREF(restuple);
6533 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006534 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006535 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006536 &resunicode, newpos)) {
6537 Py_DECREF(restuple);
6538 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006539 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006540 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6541 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6542 Py_DECREF(restuple);
6543 return NULL;
6544 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006545 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006546 *newpos = len + *newpos;
6547 if (*newpos<0 || *newpos>len) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006548 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
6549 Py_DECREF(restuple);
6550 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006551 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006552 Py_INCREF(resunicode);
6553 Py_DECREF(restuple);
6554 return resunicode;
6555}
6556
Alexander Belopolsky40018472011-02-26 01:02:56 +00006557static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006558unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006559 const char *errors,
6560 int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006561{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006562 /* input state */
6563 Py_ssize_t pos=0, size;
6564 int kind;
6565 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006566 /* output object */
6567 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006568 /* pointer into the output */
6569 char *str;
6570 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006571 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006572 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6573 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006574 PyObject *errorHandler = NULL;
6575 PyObject *exc = NULL;
6576 /* the following variable is used for caching string comparisons
6577 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6578 int known_errorHandler = -1;
6579
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006580 if (PyUnicode_READY(unicode) < 0)
6581 return NULL;
6582 size = PyUnicode_GET_LENGTH(unicode);
6583 kind = PyUnicode_KIND(unicode);
6584 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006585 /* allocate enough for a simple encoding without
6586 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006587 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006588 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006589 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006590 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006591 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006592 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006593 ressize = size;
6594
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006595 while (pos < size) {
6596 Py_UCS4 c = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006597
Benjamin Peterson29060642009-01-31 22:14:21 +00006598 /* can we encode this? */
6599 if (c<limit) {
6600 /* no overflow check, because we know that the space is enough */
6601 *str++ = (char)c;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006602 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006603 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006604 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006605 Py_ssize_t requiredsize;
6606 PyObject *repunicode;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006607 Py_ssize_t repsize, newpos, respos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006608 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006609 Py_ssize_t collstart = pos;
6610 Py_ssize_t collend = pos;
Benjamin Peterson29060642009-01-31 22:14:21 +00006611 /* find all unecodable characters */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006612 while ((collend < size) && (PyUnicode_READ(kind, data, collend)>=limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006613 ++collend;
6614 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
6615 if (known_errorHandler==-1) {
6616 if ((errors==NULL) || (!strcmp(errors, "strict")))
6617 known_errorHandler = 1;
6618 else if (!strcmp(errors, "replace"))
6619 known_errorHandler = 2;
6620 else if (!strcmp(errors, "ignore"))
6621 known_errorHandler = 3;
6622 else if (!strcmp(errors, "xmlcharrefreplace"))
6623 known_errorHandler = 4;
6624 else
6625 known_errorHandler = 0;
6626 }
6627 switch (known_errorHandler) {
6628 case 1: /* strict */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006629 raise_encode_exception_obj(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006630 goto onError;
6631 case 2: /* replace */
6632 while (collstart++<collend)
6633 *str++ = '?'; /* fall through */
6634 case 3: /* ignore */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006635 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006636 break;
6637 case 4: /* xmlcharrefreplace */
6638 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006639 /* determine replacement size */
6640 for (i = collstart, repsize = 0; i < collend; ++i) {
6641 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
6642 if (ch < 10)
Benjamin Peterson29060642009-01-31 22:14:21 +00006643 repsize += 2+1+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006644 else if (ch < 100)
Benjamin Peterson29060642009-01-31 22:14:21 +00006645 repsize += 2+2+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006646 else if (ch < 1000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006647 repsize += 2+3+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006648 else if (ch < 10000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006649 repsize += 2+4+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00006650#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00006651 else
6652 repsize += 2+5+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00006653#else
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006654 else if (ch < 100000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006655 repsize += 2+5+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006656 else if (ch < 1000000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006657 repsize += 2+6+1;
6658 else
6659 repsize += 2+7+1;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00006660#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00006661 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006662 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006663 if (requiredsize > ressize) {
6664 if (requiredsize<2*ressize)
6665 requiredsize = 2*ressize;
6666 if (_PyBytes_Resize(&res, requiredsize))
6667 goto onError;
6668 str = PyBytes_AS_STRING(res) + respos;
6669 ressize = requiredsize;
6670 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006671 /* generate replacement */
6672 for (i = collstart; i < collend; ++i) {
6673 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
Benjamin Peterson29060642009-01-31 22:14:21 +00006674 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006675 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006676 break;
6677 default:
6678 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006679 encoding, reason, unicode, &exc,
6680 collstart, collend, &newpos);
6681 if (repunicode == NULL || (PyUnicode_Check(repunicode) &&
6682 PyUnicode_READY(repunicode) < 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00006683 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006684 if (PyBytes_Check(repunicode)) {
6685 /* Directly copy bytes result to output. */
6686 repsize = PyBytes_Size(repunicode);
6687 if (repsize > 1) {
6688 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006689 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006690 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
6691 Py_DECREF(repunicode);
6692 goto onError;
6693 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006694 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006695 ressize += repsize-1;
6696 }
6697 memcpy(str, PyBytes_AsString(repunicode), repsize);
6698 str += repsize;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006699 pos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006700 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006701 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006702 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006703 /* need more space? (at least enough for what we
6704 have+the replacement+the rest of the string, so
6705 we won't have to check space for encodable characters) */
6706 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006707 repsize = PyUnicode_GET_LENGTH(repunicode);
6708 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006709 if (requiredsize > ressize) {
6710 if (requiredsize<2*ressize)
6711 requiredsize = 2*ressize;
6712 if (_PyBytes_Resize(&res, requiredsize)) {
6713 Py_DECREF(repunicode);
6714 goto onError;
6715 }
6716 str = PyBytes_AS_STRING(res) + respos;
6717 ressize = requiredsize;
6718 }
6719 /* check if there is anything unencodable in the replacement
6720 and copy it to the output */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006721 for (i = 0; repsize-->0; ++i, ++str) {
6722 c = PyUnicode_READ_CHAR(repunicode, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00006723 if (c >= limit) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006724 raise_encode_exception_obj(&exc, encoding, unicode,
6725 pos, pos+1, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006726 Py_DECREF(repunicode);
6727 goto onError;
6728 }
6729 *str = (char)c;
6730 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006731 pos = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006732 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006733 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006734 }
6735 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006736 /* Resize if we allocated to much */
6737 size = str - PyBytes_AS_STRING(res);
6738 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00006739 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006740 if (_PyBytes_Resize(&res, size) < 0)
6741 goto onError;
6742 }
6743
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006744 Py_XDECREF(errorHandler);
6745 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006746 return res;
6747
6748 onError:
6749 Py_XDECREF(res);
6750 Py_XDECREF(errorHandler);
6751 Py_XDECREF(exc);
6752 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006753}
6754
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006755/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006756PyObject *
6757PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006758 Py_ssize_t size,
6759 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006760{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006761 PyObject *result;
6762 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6763 if (unicode == NULL)
6764 return NULL;
6765 result = unicode_encode_ucs1(unicode, errors, 256);
6766 Py_DECREF(unicode);
6767 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006768}
6769
Alexander Belopolsky40018472011-02-26 01:02:56 +00006770PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006771_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006772{
6773 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006774 PyErr_BadArgument();
6775 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006776 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006777 if (PyUnicode_READY(unicode) == -1)
6778 return NULL;
6779 /* Fast path: if it is a one-byte string, construct
6780 bytes object directly. */
6781 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6782 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6783 PyUnicode_GET_LENGTH(unicode));
6784 /* Non-Latin-1 characters present. Defer to above function to
6785 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006786 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006787}
6788
6789PyObject*
6790PyUnicode_AsLatin1String(PyObject *unicode)
6791{
6792 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006793}
6794
6795/* --- 7-bit ASCII Codec -------------------------------------------------- */
6796
Alexander Belopolsky40018472011-02-26 01:02:56 +00006797PyObject *
6798PyUnicode_DecodeASCII(const char *s,
6799 Py_ssize_t size,
6800 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006801{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006802 const char *starts = s;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006803 PyObject *v;
Victor Stinner702c7342011-10-05 13:50:52 +02006804 Py_UNICODE *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006805 Py_ssize_t startinpos;
6806 Py_ssize_t endinpos;
6807 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006808 const char *e;
Victor Stinner702c7342011-10-05 13:50:52 +02006809 int has_error;
6810 const unsigned char *p = (const unsigned char *)s;
6811 const unsigned char *end = p + size;
6812 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006813 PyObject *errorHandler = NULL;
6814 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006815
Guido van Rossumd57fd912000-03-10 22:53:23 +00006816 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006817 if (size == 1 && (unsigned char)s[0] < 128)
6818 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006819
Victor Stinner702c7342011-10-05 13:50:52 +02006820 has_error = 0;
6821 while (p < end && !has_error) {
6822 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
6823 an explanation. */
6824 if (!((size_t) p & LONG_PTR_MASK)) {
6825 /* Help register allocation */
6826 register const unsigned char *_p = p;
6827 while (_p < aligned_end) {
6828 unsigned long value = *(unsigned long *) _p;
6829 if (value & ASCII_CHAR_MASK) {
6830 has_error = 1;
6831 break;
6832 }
6833 _p += SIZEOF_LONG;
6834 }
6835 if (_p == end)
6836 break;
6837 if (has_error)
6838 break;
6839 p = _p;
6840 }
6841 if (*p & 0x80) {
6842 has_error = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006843 break;
Victor Stinner702c7342011-10-05 13:50:52 +02006844 }
6845 else {
6846 ++p;
6847 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00006848 }
Victor Stinner702c7342011-10-05 13:50:52 +02006849 if (!has_error)
6850 return unicode_fromascii((const unsigned char *)s, size);
Tim Petersced69f82003-09-16 20:30:58 +00006851
Victor Stinner7931d9a2011-11-04 00:22:48 +01006852 v = (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006853 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006854 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006855 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006856 return v;
Victor Stinner702c7342011-10-05 13:50:52 +02006857 u = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006858 e = s + size;
6859 while (s < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006860 register unsigned char c = (unsigned char)*s;
6861 if (c < 128) {
Victor Stinner702c7342011-10-05 13:50:52 +02006862 *u++ = c;
Benjamin Peterson29060642009-01-31 22:14:21 +00006863 ++s;
6864 }
6865 else {
6866 startinpos = s-starts;
6867 endinpos = startinpos + 1;
Victor Stinner702c7342011-10-05 13:50:52 +02006868 outpos = u - (Py_UNICODE *)PyUnicode_AS_UNICODE(v);
Benjamin Peterson29060642009-01-31 22:14:21 +00006869 if (unicode_decode_call_errorhandler(
6870 errors, &errorHandler,
6871 "ascii", "ordinal not in range(128)",
6872 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinner702c7342011-10-05 13:50:52 +02006873 &v, &outpos, &u))
Benjamin Peterson29060642009-01-31 22:14:21 +00006874 goto onError;
6875 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006876 }
Victor Stinner702c7342011-10-05 13:50:52 +02006877 if (u - PyUnicode_AS_UNICODE(v) < PyUnicode_GET_SIZE(v))
Victor Stinner7931d9a2011-11-04 00:22:48 +01006878 if (PyUnicode_Resize(&v, u - PyUnicode_AS_UNICODE(v)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006879 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006880 Py_XDECREF(errorHandler);
6881 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02006882#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02006883 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006884 Py_DECREF(v);
6885 return NULL;
6886 }
Victor Stinner17efeed2011-10-04 20:05:46 +02006887#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006888 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01006889 return v;
Tim Petersced69f82003-09-16 20:30:58 +00006890
Benjamin Peterson29060642009-01-31 22:14:21 +00006891 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006892 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006893 Py_XDECREF(errorHandler);
6894 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006895 return NULL;
6896}
6897
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006898/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006899PyObject *
6900PyUnicode_EncodeASCII(const Py_UNICODE *p,
6901 Py_ssize_t size,
6902 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006903{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006904 PyObject *result;
6905 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6906 if (unicode == NULL)
6907 return NULL;
6908 result = unicode_encode_ucs1(unicode, errors, 128);
6909 Py_DECREF(unicode);
6910 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006911}
6912
Alexander Belopolsky40018472011-02-26 01:02:56 +00006913PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006914_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006915{
6916 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006917 PyErr_BadArgument();
6918 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006919 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006920 if (PyUnicode_READY(unicode) == -1)
6921 return NULL;
6922 /* Fast path: if it is an ASCII-only string, construct bytes object
6923 directly. Else defer to above function to raise the exception. */
6924 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
6925 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6926 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006927 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006928}
6929
6930PyObject *
6931PyUnicode_AsASCIIString(PyObject *unicode)
6932{
6933 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006934}
6935
Victor Stinner99b95382011-07-04 14:23:54 +02006936#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006937
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006938/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006939
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00006940#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006941#define NEED_RETRY
6942#endif
6943
Victor Stinner3a50e702011-10-18 21:21:00 +02006944#ifndef WC_ERR_INVALID_CHARS
6945# define WC_ERR_INVALID_CHARS 0x0080
6946#endif
6947
6948static char*
6949code_page_name(UINT code_page, PyObject **obj)
6950{
6951 *obj = NULL;
6952 if (code_page == CP_ACP)
6953 return "mbcs";
6954 if (code_page == CP_UTF7)
6955 return "CP_UTF7";
6956 if (code_page == CP_UTF8)
6957 return "CP_UTF8";
6958
6959 *obj = PyBytes_FromFormat("cp%u", code_page);
6960 if (*obj == NULL)
6961 return NULL;
6962 return PyBytes_AS_STRING(*obj);
6963}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006964
Alexander Belopolsky40018472011-02-26 01:02:56 +00006965static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006966is_dbcs_lead_byte(UINT code_page, const char *s, int offset)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006967{
6968 const char *curr = s + offset;
Victor Stinner3a50e702011-10-18 21:21:00 +02006969 const char *prev;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006970
Victor Stinner3a50e702011-10-18 21:21:00 +02006971 if (!IsDBCSLeadByteEx(code_page, *curr))
6972 return 0;
6973
6974 prev = CharPrevExA(code_page, s, curr, 0);
6975 if (prev == curr)
6976 return 1;
6977 /* FIXME: This code is limited to "true" double-byte encodings,
6978 as it assumes an incomplete character consists of a single
6979 byte. */
6980 if (curr - prev == 2)
6981 return 1;
6982 if (!IsDBCSLeadByteEx(code_page, *prev))
6983 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006984 return 0;
6985}
6986
Victor Stinner3a50e702011-10-18 21:21:00 +02006987static DWORD
6988decode_code_page_flags(UINT code_page)
6989{
6990 if (code_page == CP_UTF7) {
6991 /* The CP_UTF7 decoder only supports flags=0 */
6992 return 0;
6993 }
6994 else
6995 return MB_ERR_INVALID_CHARS;
6996}
6997
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006998/*
Victor Stinner3a50e702011-10-18 21:21:00 +02006999 * Decode a byte string from a Windows code page into unicode object in strict
7000 * mode.
7001 *
7002 * Returns consumed size if succeed, returns -2 on decode error, or raise a
7003 * WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007004 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007005static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007006decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007007 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02007008 const char *in,
7009 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007010{
Victor Stinner3a50e702011-10-18 21:21:00 +02007011 const DWORD flags = decode_code_page_flags(code_page);
7012 Py_UNICODE *out;
7013 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007014
7015 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007016 assert(insize > 0);
7017 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
7018 if (outsize <= 0)
7019 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007020
7021 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007022 /* Create unicode object */
Victor Stinner76a31a62011-11-04 00:05:13 +01007023 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00007024 if (*v == NULL)
7025 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007026 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007027 }
7028 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007029 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007030 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner76a31a62011-11-04 00:05:13 +01007031 if (PyUnicode_Resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007032 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007033 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007034 }
7035
7036 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007037 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
7038 if (outsize <= 0)
7039 goto error;
7040 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007041
Victor Stinner3a50e702011-10-18 21:21:00 +02007042error:
7043 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7044 return -2;
7045 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007046 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007047}
7048
Victor Stinner3a50e702011-10-18 21:21:00 +02007049/*
7050 * Decode a byte string from a code page into unicode object with an error
7051 * handler.
7052 *
7053 * Returns consumed size if succeed, or raise a WindowsError or
7054 * UnicodeDecodeError exception and returns -1 on error.
7055 */
7056static int
7057decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007058 PyObject **v,
7059 const char *in, const int size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007060 const char *errors)
7061{
7062 const char *startin = in;
7063 const char *endin = in + size;
7064 const DWORD flags = decode_code_page_flags(code_page);
7065 /* Ideally, we should get reason from FormatMessage. This is the Windows
7066 2000 English version of the message. */
7067 const char *reason = "No mapping for the Unicode character exists "
7068 "in the target code page.";
7069 /* each step cannot decode more than 1 character, but a character can be
7070 represented as a surrogate pair */
7071 wchar_t buffer[2], *startout, *out;
7072 int insize, outsize;
7073 PyObject *errorHandler = NULL;
7074 PyObject *exc = NULL;
7075 PyObject *encoding_obj = NULL;
7076 char *encoding;
7077 DWORD err;
7078 int ret = -1;
7079
7080 assert(size > 0);
7081
7082 encoding = code_page_name(code_page, &encoding_obj);
7083 if (encoding == NULL)
7084 return -1;
7085
7086 if (errors == NULL || strcmp(errors, "strict") == 0) {
7087 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
7088 UnicodeDecodeError. */
7089 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
7090 if (exc != NULL) {
7091 PyCodec_StrictErrors(exc);
7092 Py_CLEAR(exc);
7093 }
7094 goto error;
7095 }
7096
7097 if (*v == NULL) {
7098 /* Create unicode object */
7099 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7100 PyErr_NoMemory();
7101 goto error;
7102 }
Victor Stinner76a31a62011-11-04 00:05:13 +01007103 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02007104 if (*v == NULL)
7105 goto error;
7106 startout = PyUnicode_AS_UNICODE(*v);
7107 }
7108 else {
7109 /* Extend unicode object */
7110 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
7111 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7112 PyErr_NoMemory();
7113 goto error;
7114 }
Victor Stinner76a31a62011-11-04 00:05:13 +01007115 if (PyUnicode_Resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007116 goto error;
7117 startout = PyUnicode_AS_UNICODE(*v) + n;
7118 }
7119
7120 /* Decode the byte string character per character */
7121 out = startout;
7122 while (in < endin)
7123 {
7124 /* Decode a character */
7125 insize = 1;
7126 do
7127 {
7128 outsize = MultiByteToWideChar(code_page, flags,
7129 in, insize,
7130 buffer, Py_ARRAY_LENGTH(buffer));
7131 if (outsize > 0)
7132 break;
7133 err = GetLastError();
7134 if (err != ERROR_NO_UNICODE_TRANSLATION
7135 && err != ERROR_INSUFFICIENT_BUFFER)
7136 {
7137 PyErr_SetFromWindowsErr(0);
7138 goto error;
7139 }
7140 insize++;
7141 }
7142 /* 4=maximum length of a UTF-8 sequence */
7143 while (insize <= 4 && (in + insize) <= endin);
7144
7145 if (outsize <= 0) {
7146 Py_ssize_t startinpos, endinpos, outpos;
7147
7148 startinpos = in - startin;
7149 endinpos = startinpos + 1;
7150 outpos = out - PyUnicode_AS_UNICODE(*v);
7151 if (unicode_decode_call_errorhandler(
7152 errors, &errorHandler,
7153 encoding, reason,
7154 &startin, &endin, &startinpos, &endinpos, &exc, &in,
7155 v, &outpos, &out))
7156 {
7157 goto error;
7158 }
7159 }
7160 else {
7161 in += insize;
7162 memcpy(out, buffer, outsize * sizeof(wchar_t));
7163 out += outsize;
7164 }
7165 }
7166
7167 /* write a NUL character at the end */
7168 *out = 0;
7169
7170 /* Extend unicode object */
7171 outsize = out - startout;
7172 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner76a31a62011-11-04 00:05:13 +01007173 if (PyUnicode_Resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007174 goto error;
Victor Stinner76a31a62011-11-04 00:05:13 +01007175 ret = size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007176
7177error:
7178 Py_XDECREF(encoding_obj);
7179 Py_XDECREF(errorHandler);
7180 Py_XDECREF(exc);
7181 return ret;
7182}
7183
Victor Stinner3a50e702011-10-18 21:21:00 +02007184static PyObject *
7185decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007186 const char *s, Py_ssize_t size,
7187 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007188{
Victor Stinner76a31a62011-11-04 00:05:13 +01007189 PyObject *v = NULL;
7190 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007191
Victor Stinner3a50e702011-10-18 21:21:00 +02007192 if (code_page < 0) {
7193 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7194 return NULL;
7195 }
7196
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007197 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007198 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007199
Victor Stinner76a31a62011-11-04 00:05:13 +01007200 do
7201 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007202#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007203 if (size > INT_MAX) {
7204 chunk_size = INT_MAX;
7205 final = 0;
7206 done = 0;
7207 }
7208 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007209#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007210 {
7211 chunk_size = (int)size;
7212 final = (consumed == NULL);
7213 done = 1;
7214 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007215
Victor Stinner76a31a62011-11-04 00:05:13 +01007216 /* Skip trailing lead-byte unless 'final' is set */
7217 if (!final && is_dbcs_lead_byte(code_page, s, chunk_size - 1))
7218 --chunk_size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007219
Victor Stinner76a31a62011-11-04 00:05:13 +01007220 if (chunk_size == 0 && done) {
7221 if (v != NULL)
7222 break;
7223 Py_INCREF(unicode_empty);
7224 return unicode_empty;
7225 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007226
Victor Stinner76a31a62011-11-04 00:05:13 +01007227
7228 converted = decode_code_page_strict(code_page, &v,
7229 s, chunk_size);
7230 if (converted == -2)
7231 converted = decode_code_page_errors(code_page, &v,
7232 s, chunk_size,
7233 errors);
7234 assert(converted != 0);
7235
7236 if (converted < 0) {
7237 Py_XDECREF(v);
7238 return NULL;
7239 }
7240
7241 if (consumed)
7242 *consumed += converted;
7243
7244 s += converted;
7245 size -= converted;
7246 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007247
Victor Stinner17efeed2011-10-04 20:05:46 +02007248#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02007249 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007250 Py_DECREF(v);
7251 return NULL;
7252 }
Victor Stinner17efeed2011-10-04 20:05:46 +02007253#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02007254 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner76a31a62011-11-04 00:05:13 +01007255 return v;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007256}
7257
Alexander Belopolsky40018472011-02-26 01:02:56 +00007258PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007259PyUnicode_DecodeCodePageStateful(int code_page,
7260 const char *s,
7261 Py_ssize_t size,
7262 const char *errors,
7263 Py_ssize_t *consumed)
7264{
7265 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7266}
7267
7268PyObject *
7269PyUnicode_DecodeMBCSStateful(const char *s,
7270 Py_ssize_t size,
7271 const char *errors,
7272 Py_ssize_t *consumed)
7273{
7274 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7275}
7276
7277PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007278PyUnicode_DecodeMBCS(const char *s,
7279 Py_ssize_t size,
7280 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007281{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007282 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7283}
7284
Victor Stinner3a50e702011-10-18 21:21:00 +02007285static DWORD
7286encode_code_page_flags(UINT code_page, const char *errors)
7287{
7288 if (code_page == CP_UTF8) {
7289 if (winver.dwMajorVersion >= 6)
7290 /* CP_UTF8 supports WC_ERR_INVALID_CHARS on Windows Vista
7291 and later */
7292 return WC_ERR_INVALID_CHARS;
7293 else
7294 /* CP_UTF8 only supports flags=0 on Windows older than Vista */
7295 return 0;
7296 }
7297 else if (code_page == CP_UTF7) {
7298 /* CP_UTF7 only supports flags=0 */
7299 return 0;
7300 }
7301 else {
7302 if (errors != NULL && strcmp(errors, "replace") == 0)
7303 return 0;
7304 else
7305 return WC_NO_BEST_FIT_CHARS;
7306 }
7307}
7308
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007309/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007310 * Encode a Unicode string to a Windows code page into a byte string in strict
7311 * mode.
7312 *
7313 * Returns consumed characters if succeed, returns -2 on encode error, or raise
7314 * a WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007315 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007316static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007317encode_code_page_strict(UINT code_page, PyObject **outbytes,
7318 const Py_UNICODE *p, const int size,
7319 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007320{
Victor Stinner554f3f02010-06-16 23:33:54 +00007321 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007322 BOOL *pusedDefaultChar = &usedDefaultChar;
7323 int outsize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007324 PyObject *exc = NULL;
Victor Stinner3a50e702011-10-18 21:21:00 +02007325 const DWORD flags = encode_code_page_flags(code_page, NULL);
7326 char *out;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007327
Victor Stinner3a50e702011-10-18 21:21:00 +02007328 assert(size > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007329
Victor Stinner3a50e702011-10-18 21:21:00 +02007330 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007331 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007332 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007333 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007334
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007335 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007336 outsize = WideCharToMultiByte(code_page, flags,
7337 p, size,
7338 NULL, 0,
7339 NULL, pusedDefaultChar);
7340 if (outsize <= 0)
7341 goto error;
7342 /* If we used a default char, then we failed! */
7343 if (pusedDefaultChar && *pusedDefaultChar)
7344 return -2;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007345
Victor Stinner3a50e702011-10-18 21:21:00 +02007346 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007347 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007348 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7349 if (*outbytes == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007350 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007351 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007352 }
7353 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007354 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007355 const Py_ssize_t n = PyBytes_Size(*outbytes);
7356 if (outsize > PY_SSIZE_T_MAX - n) {
7357 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00007358 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007359 }
7360 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7361 return -1;
7362 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007363 }
7364
7365 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007366 outsize = WideCharToMultiByte(code_page, flags,
7367 p, size,
7368 out, outsize,
7369 NULL, pusedDefaultChar);
7370 if (outsize <= 0)
7371 goto error;
7372 if (pusedDefaultChar && *pusedDefaultChar)
7373 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007374 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007375
Victor Stinner3a50e702011-10-18 21:21:00 +02007376error:
7377 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7378 return -2;
7379 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007380 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007381}
7382
Victor Stinner3a50e702011-10-18 21:21:00 +02007383/*
7384 * Encode a Unicode string to a Windows code page into a byte string using a
7385 * error handler.
7386 *
7387 * Returns consumed characters if succeed, or raise a WindowsError and returns
7388 * -1 on other error.
7389 */
7390static int
7391encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007392 PyObject *unicode, Py_ssize_t unicode_offset,
Victor Stinner3a50e702011-10-18 21:21:00 +02007393 const Py_UNICODE *in, const int insize,
7394 const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007395{
Victor Stinner3a50e702011-10-18 21:21:00 +02007396 const DWORD flags = encode_code_page_flags(code_page, errors);
7397 const Py_UNICODE *startin = in;
7398 const Py_UNICODE *endin = in + insize;
7399 /* Ideally, we should get reason from FormatMessage. This is the Windows
7400 2000 English version of the message. */
7401 const char *reason = "invalid character";
7402 /* 4=maximum length of a UTF-8 sequence */
7403 char buffer[4];
7404 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7405 Py_ssize_t outsize;
7406 char *out;
7407 int charsize;
7408 PyObject *errorHandler = NULL;
7409 PyObject *exc = NULL;
7410 PyObject *encoding_obj = NULL;
7411 char *encoding;
Victor Stinner3a50e702011-10-18 21:21:00 +02007412 Py_ssize_t startpos, newpos, newoutsize;
7413 PyObject *rep;
7414 int ret = -1;
7415
7416 assert(insize > 0);
7417
7418 encoding = code_page_name(code_page, &encoding_obj);
7419 if (encoding == NULL)
7420 return -1;
7421
7422 if (errors == NULL || strcmp(errors, "strict") == 0) {
7423 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7424 then we raise a UnicodeEncodeError. */
7425 make_encode_exception(&exc, encoding, in, insize, 0, 0, reason);
7426 if (exc != NULL) {
7427 PyCodec_StrictErrors(exc);
7428 Py_DECREF(exc);
7429 }
7430 Py_XDECREF(encoding_obj);
7431 return -1;
7432 }
7433
7434 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7435 pusedDefaultChar = &usedDefaultChar;
7436 else
7437 pusedDefaultChar = NULL;
7438
7439 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7440 PyErr_NoMemory();
7441 goto error;
7442 }
7443 outsize = insize * Py_ARRAY_LENGTH(buffer);
7444
7445 if (*outbytes == NULL) {
7446 /* Create string object */
7447 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7448 if (*outbytes == NULL)
7449 goto error;
7450 out = PyBytes_AS_STRING(*outbytes);
7451 }
7452 else {
7453 /* Extend string object */
7454 Py_ssize_t n = PyBytes_Size(*outbytes);
7455 if (n > PY_SSIZE_T_MAX - outsize) {
7456 PyErr_NoMemory();
7457 goto error;
7458 }
7459 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7460 goto error;
7461 out = PyBytes_AS_STRING(*outbytes) + n;
7462 }
7463
7464 /* Encode the string character per character */
7465 while (in < endin)
7466 {
7467 if ((in + 2) <= endin
7468 && 0xD800 <= in[0] && in[0] <= 0xDBFF
7469 && 0xDC00 <= in[1] && in[1] <= 0xDFFF)
7470 charsize = 2;
7471 else
7472 charsize = 1;
7473
7474 outsize = WideCharToMultiByte(code_page, flags,
7475 in, charsize,
7476 buffer, Py_ARRAY_LENGTH(buffer),
7477 NULL, pusedDefaultChar);
7478 if (outsize > 0) {
7479 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7480 {
7481 in += charsize;
7482 memcpy(out, buffer, outsize);
7483 out += outsize;
7484 continue;
7485 }
7486 }
7487 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7488 PyErr_SetFromWindowsErr(0);
7489 goto error;
7490 }
7491
7492 charsize = Py_MAX(charsize - 1, 1);
Victor Stinner7581cef2011-11-03 22:32:33 +01007493 startpos = unicode_offset + in - startin;
Victor Stinner3a50e702011-10-18 21:21:00 +02007494 rep = unicode_encode_call_errorhandler(
7495 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007496 unicode, &exc,
Victor Stinner3a50e702011-10-18 21:21:00 +02007497 startpos, startpos + charsize, &newpos);
7498 if (rep == NULL)
7499 goto error;
Victor Stinner7581cef2011-11-03 22:32:33 +01007500 in += (newpos - startpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007501
7502 if (PyBytes_Check(rep)) {
7503 outsize = PyBytes_GET_SIZE(rep);
7504 if (outsize != 1) {
7505 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7506 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7507 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7508 Py_DECREF(rep);
7509 goto error;
7510 }
7511 out = PyBytes_AS_STRING(*outbytes) + offset;
7512 }
7513 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7514 out += outsize;
7515 }
7516 else {
7517 Py_ssize_t i;
7518 enum PyUnicode_Kind kind;
7519 void *data;
7520
7521 if (PyUnicode_READY(rep) < 0) {
7522 Py_DECREF(rep);
7523 goto error;
7524 }
7525
7526 outsize = PyUnicode_GET_LENGTH(rep);
7527 if (outsize != 1) {
7528 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7529 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7530 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7531 Py_DECREF(rep);
7532 goto error;
7533 }
7534 out = PyBytes_AS_STRING(*outbytes) + offset;
7535 }
7536 kind = PyUnicode_KIND(rep);
7537 data = PyUnicode_DATA(rep);
7538 for (i=0; i < outsize; i++) {
7539 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7540 if (ch > 127) {
7541 raise_encode_exception(&exc,
7542 encoding,
7543 startin, insize,
7544 startpos, startpos + charsize,
7545 "unable to encode error handler result to ASCII");
7546 Py_DECREF(rep);
7547 goto error;
7548 }
7549 *out = (unsigned char)ch;
7550 out++;
7551 }
7552 }
7553 Py_DECREF(rep);
7554 }
7555 /* write a NUL byte */
7556 *out = 0;
7557 outsize = out - PyBytes_AS_STRING(*outbytes);
7558 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7559 if (_PyBytes_Resize(outbytes, outsize) < 0)
7560 goto error;
7561 ret = 0;
7562
7563error:
7564 Py_XDECREF(encoding_obj);
7565 Py_XDECREF(errorHandler);
7566 Py_XDECREF(exc);
7567 return ret;
7568}
7569
Victor Stinner3a50e702011-10-18 21:21:00 +02007570static PyObject *
7571encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007572 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007573 const char *errors)
7574{
Victor Stinner7581cef2011-11-03 22:32:33 +01007575 const Py_UNICODE *p;
7576 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007577 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007578 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007579 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007580
7581 p = PyUnicode_AsUnicodeAndSize(unicode, &size);
7582 if (p == NULL)
7583 return NULL;
Guido van Rossum03e29f12000-05-04 15:52:20 +00007584
Victor Stinner3a50e702011-10-18 21:21:00 +02007585 if (code_page < 0) {
7586 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7587 return NULL;
7588 }
7589
Victor Stinner76a31a62011-11-04 00:05:13 +01007590 if (size == 0)
7591 return PyBytes_FromStringAndSize(NULL, 0);
7592
Victor Stinner7581cef2011-11-03 22:32:33 +01007593 offset = 0;
7594 do
7595 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007596#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007597 if (size > INT_MAX) {
Victor Stinner7581cef2011-11-03 22:32:33 +01007598 chunk_len = INT_MAX;
Victor Stinner76a31a62011-11-04 00:05:13 +01007599 done = 0;
7600 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007601 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007602#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007603 {
Victor Stinner7581cef2011-11-03 22:32:33 +01007604 chunk_len = (int)size;
Victor Stinner76a31a62011-11-04 00:05:13 +01007605 done = 1;
7606 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007607
Victor Stinner76a31a62011-11-04 00:05:13 +01007608 ret = encode_code_page_strict(code_page, &outbytes,
7609 p, chunk_len,
7610 errors);
7611 if (ret == -2)
7612 ret = encode_code_page_errors(code_page, &outbytes,
7613 unicode, offset,
7614 p, chunk_len,
7615 errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007616 if (ret < 0) {
7617 Py_XDECREF(outbytes);
7618 return NULL;
7619 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007620
Victor Stinner7581cef2011-11-03 22:32:33 +01007621 p += chunk_len;
7622 offset += chunk_len;
7623 size -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007624 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007625
Victor Stinner3a50e702011-10-18 21:21:00 +02007626 return outbytes;
7627}
7628
7629PyObject *
7630PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7631 Py_ssize_t size,
7632 const char *errors)
7633{
Victor Stinner7581cef2011-11-03 22:32:33 +01007634 PyObject *unicode, *res;
7635 unicode = PyUnicode_FromUnicode(p, size);
7636 if (unicode == NULL)
7637 return NULL;
7638 res = encode_code_page(CP_ACP, unicode, errors);
7639 Py_DECREF(unicode);
7640 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007641}
7642
7643PyObject *
7644PyUnicode_EncodeCodePage(int code_page,
7645 PyObject *unicode,
7646 const char *errors)
7647{
Victor Stinner7581cef2011-11-03 22:32:33 +01007648 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007649}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007650
Alexander Belopolsky40018472011-02-26 01:02:56 +00007651PyObject *
7652PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007653{
7654 if (!PyUnicode_Check(unicode)) {
7655 PyErr_BadArgument();
7656 return NULL;
7657 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007658 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007659}
7660
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007661#undef NEED_RETRY
7662
Victor Stinner99b95382011-07-04 14:23:54 +02007663#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007664
Guido van Rossumd57fd912000-03-10 22:53:23 +00007665/* --- Character Mapping Codec -------------------------------------------- */
7666
Alexander Belopolsky40018472011-02-26 01:02:56 +00007667PyObject *
7668PyUnicode_DecodeCharmap(const char *s,
7669 Py_ssize_t size,
7670 PyObject *mapping,
7671 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007672{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007673 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007674 Py_ssize_t startinpos;
7675 Py_ssize_t endinpos;
7676 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007677 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01007678 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007679 Py_UNICODE *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007680 Py_ssize_t extrachars = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007681 PyObject *errorHandler = NULL;
7682 PyObject *exc = NULL;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007683 Py_UNICODE *mapstring = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007684 Py_ssize_t maplen = 0;
Tim Petersced69f82003-09-16 20:30:58 +00007685
Guido van Rossumd57fd912000-03-10 22:53:23 +00007686 /* Default to Latin-1 */
7687 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007688 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007689
Victor Stinner7931d9a2011-11-04 00:22:48 +01007690 v = (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007691 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007692 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007693 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01007694 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007695 p = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007696 e = s + size;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007697 if (PyUnicode_CheckExact(mapping)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007698 mapstring = PyUnicode_AS_UNICODE(mapping);
7699 maplen = PyUnicode_GET_SIZE(mapping);
7700 while (s < e) {
7701 unsigned char ch = *s;
7702 Py_UNICODE x = 0xfffe; /* illegal value */
Guido van Rossumd57fd912000-03-10 22:53:23 +00007703
Benjamin Peterson29060642009-01-31 22:14:21 +00007704 if (ch < maplen)
7705 x = mapstring[ch];
Guido van Rossumd57fd912000-03-10 22:53:23 +00007706
Benjamin Peterson29060642009-01-31 22:14:21 +00007707 if (x == 0xfffe) {
7708 /* undefined mapping */
7709 outpos = p-PyUnicode_AS_UNICODE(v);
7710 startinpos = s-starts;
7711 endinpos = startinpos+1;
7712 if (unicode_decode_call_errorhandler(
7713 errors, &errorHandler,
7714 "charmap", "character maps to <undefined>",
7715 &starts, &e, &startinpos, &endinpos, &exc, &s,
7716 &v, &outpos, &p)) {
7717 goto onError;
7718 }
7719 continue;
7720 }
7721 *p++ = x;
7722 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007723 }
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007724 }
7725 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007726 while (s < e) {
7727 unsigned char ch = *s;
7728 PyObject *w, *x;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007729
Benjamin Peterson29060642009-01-31 22:14:21 +00007730 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7731 w = PyLong_FromLong((long)ch);
7732 if (w == NULL)
7733 goto onError;
7734 x = PyObject_GetItem(mapping, w);
7735 Py_DECREF(w);
7736 if (x == NULL) {
7737 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7738 /* No mapping found means: mapping is undefined. */
7739 PyErr_Clear();
7740 x = Py_None;
7741 Py_INCREF(x);
7742 } else
7743 goto onError;
7744 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007745
Benjamin Peterson29060642009-01-31 22:14:21 +00007746 /* Apply mapping */
7747 if (PyLong_Check(x)) {
7748 long value = PyLong_AS_LONG(x);
7749 if (value < 0 || value > 65535) {
7750 PyErr_SetString(PyExc_TypeError,
7751 "character mapping must be in range(65536)");
7752 Py_DECREF(x);
7753 goto onError;
7754 }
7755 *p++ = (Py_UNICODE)value;
7756 }
7757 else if (x == Py_None) {
7758 /* undefined mapping */
7759 outpos = p-PyUnicode_AS_UNICODE(v);
7760 startinpos = s-starts;
7761 endinpos = startinpos+1;
7762 if (unicode_decode_call_errorhandler(
7763 errors, &errorHandler,
7764 "charmap", "character maps to <undefined>",
7765 &starts, &e, &startinpos, &endinpos, &exc, &s,
7766 &v, &outpos, &p)) {
7767 Py_DECREF(x);
7768 goto onError;
7769 }
7770 Py_DECREF(x);
7771 continue;
7772 }
7773 else if (PyUnicode_Check(x)) {
7774 Py_ssize_t targetsize = PyUnicode_GET_SIZE(x);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007775
Benjamin Peterson29060642009-01-31 22:14:21 +00007776 if (targetsize == 1)
7777 /* 1-1 mapping */
7778 *p++ = *PyUnicode_AS_UNICODE(x);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007779
Benjamin Peterson29060642009-01-31 22:14:21 +00007780 else if (targetsize > 1) {
7781 /* 1-n mapping */
7782 if (targetsize > extrachars) {
7783 /* resize first */
7784 Py_ssize_t oldpos = p - PyUnicode_AS_UNICODE(v);
7785 Py_ssize_t needed = (targetsize - extrachars) + \
7786 (targetsize << 2);
7787 extrachars += needed;
7788 /* XXX overflow detection missing */
Victor Stinner7931d9a2011-11-04 00:22:48 +01007789 if (PyUnicode_Resize(&v,
7790 PyUnicode_GET_SIZE(v) + needed) < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007791 Py_DECREF(x);
7792 goto onError;
7793 }
7794 p = PyUnicode_AS_UNICODE(v) + oldpos;
7795 }
7796 Py_UNICODE_COPY(p,
7797 PyUnicode_AS_UNICODE(x),
7798 targetsize);
7799 p += targetsize;
7800 extrachars -= targetsize;
7801 }
7802 /* 1-0 mapping: skip the character */
7803 }
7804 else {
7805 /* wrong return value */
7806 PyErr_SetString(PyExc_TypeError,
7807 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00007808 Py_DECREF(x);
7809 goto onError;
7810 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007811 Py_DECREF(x);
7812 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007813 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007814 }
7815 if (p - PyUnicode_AS_UNICODE(v) < PyUnicode_GET_SIZE(v))
Victor Stinner7931d9a2011-11-04 00:22:48 +01007816 if (PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007817 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007818 Py_XDECREF(errorHandler);
7819 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02007820#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02007821 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007822 Py_DECREF(v);
7823 return NULL;
7824 }
Victor Stinner17efeed2011-10-04 20:05:46 +02007825#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02007826 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01007827 return v;
Tim Petersced69f82003-09-16 20:30:58 +00007828
Benjamin Peterson29060642009-01-31 22:14:21 +00007829 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007830 Py_XDECREF(errorHandler);
7831 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007832 Py_XDECREF(v);
7833 return NULL;
7834}
7835
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007836/* Charmap encoding: the lookup table */
7837
Alexander Belopolsky40018472011-02-26 01:02:56 +00007838struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007839 PyObject_HEAD
7840 unsigned char level1[32];
7841 int count2, count3;
7842 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007843};
7844
7845static PyObject*
7846encoding_map_size(PyObject *obj, PyObject* args)
7847{
7848 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007849 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007850 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007851}
7852
7853static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007854 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007855 PyDoc_STR("Return the size (in bytes) of this object") },
7856 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007857};
7858
7859static void
7860encoding_map_dealloc(PyObject* o)
7861{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007862 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007863}
7864
7865static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007866 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007867 "EncodingMap", /*tp_name*/
7868 sizeof(struct encoding_map), /*tp_basicsize*/
7869 0, /*tp_itemsize*/
7870 /* methods */
7871 encoding_map_dealloc, /*tp_dealloc*/
7872 0, /*tp_print*/
7873 0, /*tp_getattr*/
7874 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007875 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007876 0, /*tp_repr*/
7877 0, /*tp_as_number*/
7878 0, /*tp_as_sequence*/
7879 0, /*tp_as_mapping*/
7880 0, /*tp_hash*/
7881 0, /*tp_call*/
7882 0, /*tp_str*/
7883 0, /*tp_getattro*/
7884 0, /*tp_setattro*/
7885 0, /*tp_as_buffer*/
7886 Py_TPFLAGS_DEFAULT, /*tp_flags*/
7887 0, /*tp_doc*/
7888 0, /*tp_traverse*/
7889 0, /*tp_clear*/
7890 0, /*tp_richcompare*/
7891 0, /*tp_weaklistoffset*/
7892 0, /*tp_iter*/
7893 0, /*tp_iternext*/
7894 encoding_map_methods, /*tp_methods*/
7895 0, /*tp_members*/
7896 0, /*tp_getset*/
7897 0, /*tp_base*/
7898 0, /*tp_dict*/
7899 0, /*tp_descr_get*/
7900 0, /*tp_descr_set*/
7901 0, /*tp_dictoffset*/
7902 0, /*tp_init*/
7903 0, /*tp_alloc*/
7904 0, /*tp_new*/
7905 0, /*tp_free*/
7906 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007907};
7908
7909PyObject*
7910PyUnicode_BuildEncodingMap(PyObject* string)
7911{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007912 PyObject *result;
7913 struct encoding_map *mresult;
7914 int i;
7915 int need_dict = 0;
7916 unsigned char level1[32];
7917 unsigned char level2[512];
7918 unsigned char *mlevel1, *mlevel2, *mlevel3;
7919 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007920 int kind;
7921 void *data;
7922 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007923
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007924 if (!PyUnicode_Check(string) || PyUnicode_GET_LENGTH(string) != 256) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007925 PyErr_BadArgument();
7926 return NULL;
7927 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007928 kind = PyUnicode_KIND(string);
7929 data = PyUnicode_DATA(string);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007930 memset(level1, 0xFF, sizeof level1);
7931 memset(level2, 0xFF, sizeof level2);
7932
7933 /* If there isn't a one-to-one mapping of NULL to \0,
7934 or if there are non-BMP characters, we need to use
7935 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007936 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007937 need_dict = 1;
7938 for (i = 1; i < 256; i++) {
7939 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007940 ch = PyUnicode_READ(kind, data, i);
7941 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007942 need_dict = 1;
7943 break;
7944 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007945 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007946 /* unmapped character */
7947 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007948 l1 = ch >> 11;
7949 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007950 if (level1[l1] == 0xFF)
7951 level1[l1] = count2++;
7952 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00007953 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007954 }
7955
7956 if (count2 >= 0xFF || count3 >= 0xFF)
7957 need_dict = 1;
7958
7959 if (need_dict) {
7960 PyObject *result = PyDict_New();
7961 PyObject *key, *value;
7962 if (!result)
7963 return NULL;
7964 for (i = 0; i < 256; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007965 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00007966 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007967 if (!key || !value)
7968 goto failed1;
7969 if (PyDict_SetItem(result, key, value) == -1)
7970 goto failed1;
7971 Py_DECREF(key);
7972 Py_DECREF(value);
7973 }
7974 return result;
7975 failed1:
7976 Py_XDECREF(key);
7977 Py_XDECREF(value);
7978 Py_DECREF(result);
7979 return NULL;
7980 }
7981
7982 /* Create a three-level trie */
7983 result = PyObject_MALLOC(sizeof(struct encoding_map) +
7984 16*count2 + 128*count3 - 1);
7985 if (!result)
7986 return PyErr_NoMemory();
7987 PyObject_Init(result, &EncodingMapType);
7988 mresult = (struct encoding_map*)result;
7989 mresult->count2 = count2;
7990 mresult->count3 = count3;
7991 mlevel1 = mresult->level1;
7992 mlevel2 = mresult->level23;
7993 mlevel3 = mresult->level23 + 16*count2;
7994 memcpy(mlevel1, level1, 32);
7995 memset(mlevel2, 0xFF, 16*count2);
7996 memset(mlevel3, 0, 128*count3);
7997 count3 = 0;
7998 for (i = 1; i < 256; i++) {
7999 int o1, o2, o3, i2, i3;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008000 if (PyUnicode_READ(kind, data, i) == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008001 /* unmapped character */
8002 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008003 o1 = PyUnicode_READ(kind, data, i)>>11;
8004 o2 = (PyUnicode_READ(kind, data, i)>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008005 i2 = 16*mlevel1[o1] + o2;
8006 if (mlevel2[i2] == 0xFF)
8007 mlevel2[i2] = count3++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008008 o3 = PyUnicode_READ(kind, data, i) & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008009 i3 = 128*mlevel2[i2] + o3;
8010 mlevel3[i3] = i;
8011 }
8012 return result;
8013}
8014
8015static int
8016encoding_map_lookup(Py_UNICODE c, PyObject *mapping)
8017{
8018 struct encoding_map *map = (struct encoding_map*)mapping;
8019 int l1 = c>>11;
8020 int l2 = (c>>7) & 0xF;
8021 int l3 = c & 0x7F;
8022 int i;
8023
8024#ifdef Py_UNICODE_WIDE
8025 if (c > 0xFFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008026 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008027 }
8028#endif
8029 if (c == 0)
8030 return 0;
8031 /* level 1*/
8032 i = map->level1[l1];
8033 if (i == 0xFF) {
8034 return -1;
8035 }
8036 /* level 2*/
8037 i = map->level23[16*i+l2];
8038 if (i == 0xFF) {
8039 return -1;
8040 }
8041 /* level 3 */
8042 i = map->level23[16*map->count2 + 128*i + l3];
8043 if (i == 0) {
8044 return -1;
8045 }
8046 return i;
8047}
8048
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008049/* Lookup the character ch in the mapping. If the character
8050 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00008051 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008052static PyObject *
8053charmapencode_lookup(Py_UNICODE c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008054{
Christian Heimes217cfd12007-12-02 14:31:20 +00008055 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008056 PyObject *x;
8057
8058 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008059 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008060 x = PyObject_GetItem(mapping, w);
8061 Py_DECREF(w);
8062 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008063 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8064 /* No mapping found means: mapping is undefined. */
8065 PyErr_Clear();
8066 x = Py_None;
8067 Py_INCREF(x);
8068 return x;
8069 } else
8070 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008071 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00008072 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008073 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00008074 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008075 long value = PyLong_AS_LONG(x);
8076 if (value < 0 || value > 255) {
8077 PyErr_SetString(PyExc_TypeError,
8078 "character mapping must be in range(256)");
8079 Py_DECREF(x);
8080 return NULL;
8081 }
8082 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008083 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008084 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008085 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008086 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008087 /* wrong return value */
8088 PyErr_Format(PyExc_TypeError,
8089 "character mapping must return integer, bytes or None, not %.400s",
8090 x->ob_type->tp_name);
8091 Py_DECREF(x);
8092 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008093 }
8094}
8095
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008096static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008097charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008098{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008099 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8100 /* exponentially overallocate to minimize reallocations */
8101 if (requiredsize < 2*outsize)
8102 requiredsize = 2*outsize;
8103 if (_PyBytes_Resize(outobj, requiredsize))
8104 return -1;
8105 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008106}
8107
Benjamin Peterson14339b62009-01-31 16:36:08 +00008108typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008109 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008110} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008111/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008112 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008113 space is available. Return a new reference to the object that
8114 was put in the output buffer, or Py_None, if the mapping was undefined
8115 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008116 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008117static charmapencode_result
8118charmapencode_output(Py_UNICODE c, PyObject *mapping,
8119 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008120{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008121 PyObject *rep;
8122 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008123 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008124
Christian Heimes90aa7642007-12-19 02:45:37 +00008125 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008126 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008127 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008128 if (res == -1)
8129 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008130 if (outsize<requiredsize)
8131 if (charmapencode_resize(outobj, outpos, requiredsize))
8132 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008133 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008134 outstart[(*outpos)++] = (char)res;
8135 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008136 }
8137
8138 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008139 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008140 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008141 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008142 Py_DECREF(rep);
8143 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008144 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008145 if (PyLong_Check(rep)) {
8146 Py_ssize_t requiredsize = *outpos+1;
8147 if (outsize<requiredsize)
8148 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8149 Py_DECREF(rep);
8150 return enc_EXCEPTION;
8151 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008152 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008153 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008154 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008155 else {
8156 const char *repchars = PyBytes_AS_STRING(rep);
8157 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8158 Py_ssize_t requiredsize = *outpos+repsize;
8159 if (outsize<requiredsize)
8160 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8161 Py_DECREF(rep);
8162 return enc_EXCEPTION;
8163 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008164 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008165 memcpy(outstart + *outpos, repchars, repsize);
8166 *outpos += repsize;
8167 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008168 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008169 Py_DECREF(rep);
8170 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008171}
8172
8173/* handle an error in PyUnicode_EncodeCharmap
8174 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008175static int
8176charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008177 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008178 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00008179 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008180 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008181{
8182 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008183 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008184 Py_ssize_t newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008185 Py_UNICODE *uni2;
8186 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008187 Py_ssize_t collstartpos = *inpos;
8188 Py_ssize_t collendpos = *inpos+1;
8189 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008190 char *encoding = "charmap";
8191 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008192 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008193 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008194 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008195
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008196 if (PyUnicode_READY(unicode) < 0)
8197 return -1;
8198 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008199 /* find all unencodable characters */
8200 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008201 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008202 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008203 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008204 val = encoding_map_lookup(ch, mapping);
8205 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008206 break;
8207 ++collendpos;
8208 continue;
8209 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008210
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008211 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8212 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008213 if (rep==NULL)
8214 return -1;
8215 else if (rep!=Py_None) {
8216 Py_DECREF(rep);
8217 break;
8218 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008219 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008220 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008221 }
8222 /* cache callback name lookup
8223 * (if not done yet, i.e. it's the first error) */
8224 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008225 if ((errors==NULL) || (!strcmp(errors, "strict")))
8226 *known_errorHandler = 1;
8227 else if (!strcmp(errors, "replace"))
8228 *known_errorHandler = 2;
8229 else if (!strcmp(errors, "ignore"))
8230 *known_errorHandler = 3;
8231 else if (!strcmp(errors, "xmlcharrefreplace"))
8232 *known_errorHandler = 4;
8233 else
8234 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008235 }
8236 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008237 case 1: /* strict */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008238 raise_encode_exception_obj(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008239 return -1;
8240 case 2: /* replace */
8241 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008242 x = charmapencode_output('?', mapping, res, respos);
8243 if (x==enc_EXCEPTION) {
8244 return -1;
8245 }
8246 else if (x==enc_FAILED) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008247 raise_encode_exception_obj(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008248 return -1;
8249 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008250 }
8251 /* fall through */
8252 case 3: /* ignore */
8253 *inpos = collendpos;
8254 break;
8255 case 4: /* xmlcharrefreplace */
8256 /* generate replacement (temporarily (mis)uses p) */
8257 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008258 char buffer[2+29+1+1];
8259 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008260 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008261 for (cp = buffer; *cp; ++cp) {
8262 x = charmapencode_output(*cp, mapping, res, respos);
8263 if (x==enc_EXCEPTION)
8264 return -1;
8265 else if (x==enc_FAILED) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008266 raise_encode_exception_obj(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008267 return -1;
8268 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008269 }
8270 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008271 *inpos = collendpos;
8272 break;
8273 default:
8274 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008275 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008276 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008277 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008278 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008279 if (PyBytes_Check(repunicode)) {
8280 /* Directly copy bytes result to output. */
8281 Py_ssize_t outsize = PyBytes_Size(*res);
8282 Py_ssize_t requiredsize;
8283 repsize = PyBytes_Size(repunicode);
8284 requiredsize = *respos + repsize;
8285 if (requiredsize > outsize)
8286 /* Make room for all additional bytes. */
8287 if (charmapencode_resize(res, respos, requiredsize)) {
8288 Py_DECREF(repunicode);
8289 return -1;
8290 }
8291 memcpy(PyBytes_AsString(*res) + *respos,
8292 PyBytes_AsString(repunicode), repsize);
8293 *respos += repsize;
8294 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008295 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008296 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008297 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008298 /* generate replacement */
8299 repsize = PyUnicode_GET_SIZE(repunicode);
8300 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008301 x = charmapencode_output(*uni2, mapping, res, respos);
8302 if (x==enc_EXCEPTION) {
8303 return -1;
8304 }
8305 else if (x==enc_FAILED) {
8306 Py_DECREF(repunicode);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008307 raise_encode_exception_obj(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008308 return -1;
8309 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008310 }
8311 *inpos = newpos;
8312 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008313 }
8314 return 0;
8315}
8316
Alexander Belopolsky40018472011-02-26 01:02:56 +00008317PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008318_PyUnicode_EncodeCharmap(PyObject *unicode,
8319 PyObject *mapping,
8320 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008321{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008322 /* output object */
8323 PyObject *res = NULL;
8324 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008325 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008326 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008327 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008328 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008329 PyObject *errorHandler = NULL;
8330 PyObject *exc = NULL;
8331 /* the following variable is used for caching string comparisons
8332 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8333 * 3=ignore, 4=xmlcharrefreplace */
8334 int known_errorHandler = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008335
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008336 if (PyUnicode_READY(unicode) < 0)
8337 return NULL;
8338 size = PyUnicode_GET_LENGTH(unicode);
8339
Guido van Rossumd57fd912000-03-10 22:53:23 +00008340 /* Default to Latin-1 */
8341 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008342 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008343
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008344 /* allocate enough for a simple encoding without
8345 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008346 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008347 if (res == NULL)
8348 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008349 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008350 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008351
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008352 while (inpos<size) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008353 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008354 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008355 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008356 if (x==enc_EXCEPTION) /* error */
8357 goto onError;
8358 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008359 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008360 &exc,
8361 &known_errorHandler, &errorHandler, errors,
8362 &res, &respos)) {
8363 goto onError;
8364 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008365 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008366 else
8367 /* done with this character => adjust input position */
8368 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008369 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008370
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008371 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008372 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008373 if (_PyBytes_Resize(&res, respos) < 0)
8374 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008375
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008376 Py_XDECREF(exc);
8377 Py_XDECREF(errorHandler);
8378 return res;
8379
Benjamin Peterson29060642009-01-31 22:14:21 +00008380 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008381 Py_XDECREF(res);
8382 Py_XDECREF(exc);
8383 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008384 return NULL;
8385}
8386
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008387/* Deprecated */
8388PyObject *
8389PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8390 Py_ssize_t size,
8391 PyObject *mapping,
8392 const char *errors)
8393{
8394 PyObject *result;
8395 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8396 if (unicode == NULL)
8397 return NULL;
8398 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8399 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008400 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008401}
8402
Alexander Belopolsky40018472011-02-26 01:02:56 +00008403PyObject *
8404PyUnicode_AsCharmapString(PyObject *unicode,
8405 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008406{
8407 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008408 PyErr_BadArgument();
8409 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008410 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008411 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008412}
8413
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008414/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008415static void
8416make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008417 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008418 Py_ssize_t startpos, Py_ssize_t endpos,
8419 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008420{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008421 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008422 *exceptionObject = _PyUnicodeTranslateError_Create(
8423 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008424 }
8425 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008426 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8427 goto onError;
8428 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8429 goto onError;
8430 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8431 goto onError;
8432 return;
8433 onError:
8434 Py_DECREF(*exceptionObject);
8435 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008436 }
8437}
8438
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008439/* raises a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008440static void
8441raise_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008442 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008443 Py_ssize_t startpos, Py_ssize_t endpos,
8444 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008445{
8446 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008447 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008448 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008449 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008450}
8451
8452/* error handling callback helper:
8453 build arguments, call the callback and check the arguments,
8454 put the result into newpos and return the replacement string, which
8455 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008456static PyObject *
8457unicode_translate_call_errorhandler(const char *errors,
8458 PyObject **errorHandler,
8459 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008460 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008461 Py_ssize_t startpos, Py_ssize_t endpos,
8462 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008463{
Benjamin Peterson142957c2008-07-04 19:55:29 +00008464 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008465
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008466 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008467 PyObject *restuple;
8468 PyObject *resunicode;
8469
8470 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008471 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008472 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008473 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008474 }
8475
8476 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008477 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008478 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008479 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008480
8481 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008482 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008483 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008484 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008485 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008486 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008487 Py_DECREF(restuple);
8488 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008489 }
8490 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008491 &resunicode, &i_newpos)) {
8492 Py_DECREF(restuple);
8493 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008494 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008495 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008496 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008497 else
8498 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008499 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008500 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
8501 Py_DECREF(restuple);
8502 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008503 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008504 Py_INCREF(resunicode);
8505 Py_DECREF(restuple);
8506 return resunicode;
8507}
8508
8509/* Lookup the character ch in the mapping and put the result in result,
8510 which must be decrefed by the caller.
8511 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008512static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008513charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008514{
Christian Heimes217cfd12007-12-02 14:31:20 +00008515 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008516 PyObject *x;
8517
8518 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008519 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008520 x = PyObject_GetItem(mapping, w);
8521 Py_DECREF(w);
8522 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008523 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8524 /* No mapping found means: use 1:1 mapping. */
8525 PyErr_Clear();
8526 *result = NULL;
8527 return 0;
8528 } else
8529 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008530 }
8531 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008532 *result = x;
8533 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008534 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008535 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008536 long value = PyLong_AS_LONG(x);
8537 long max = PyUnicode_GetMax();
8538 if (value < 0 || value > max) {
8539 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00008540 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008541 Py_DECREF(x);
8542 return -1;
8543 }
8544 *result = x;
8545 return 0;
8546 }
8547 else if (PyUnicode_Check(x)) {
8548 *result = x;
8549 return 0;
8550 }
8551 else {
8552 /* wrong return value */
8553 PyErr_SetString(PyExc_TypeError,
8554 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008555 Py_DECREF(x);
8556 return -1;
8557 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008558}
8559/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00008560 if not reallocate and adjust various state variables.
8561 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008562static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008563charmaptranslate_makespace(Py_UCS4 **outobj, Py_ssize_t *psize,
Benjamin Peterson29060642009-01-31 22:14:21 +00008564 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008565{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008566 Py_ssize_t oldsize = *psize;
Walter Dörwald4894c302003-10-24 14:25:28 +00008567 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008568 /* exponentially overallocate to minimize reallocations */
8569 if (requiredsize < 2 * oldsize)
8570 requiredsize = 2 * oldsize;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008571 *outobj = PyMem_Realloc(*outobj, requiredsize * sizeof(Py_UCS4));
8572 if (*outobj == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008573 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008574 *psize = requiredsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008575 }
8576 return 0;
8577}
8578/* lookup the character, put the result in the output string and adjust
8579 various state variables. Return a new reference to the object that
8580 was put in the output buffer in *result, or Py_None, if the mapping was
8581 undefined (in which case no character was written).
8582 The called must decref result.
8583 Return 0 on success, -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008584static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008585charmaptranslate_output(PyObject *input, Py_ssize_t ipos,
8586 PyObject *mapping, Py_UCS4 **output,
8587 Py_ssize_t *osize, Py_ssize_t *opos,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008588 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008589{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008590 Py_UCS4 curinp = PyUnicode_READ_CHAR(input, ipos);
8591 if (charmaptranslate_lookup(curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00008592 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008593 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008594 /* not found => default to 1:1 mapping */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008595 (*output)[(*opos)++] = curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008596 }
8597 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008598 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00008599 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008600 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008601 (*output)[(*opos)++] = (Py_UCS4)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008602 }
8603 else if (PyUnicode_Check(*res)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008604 Py_ssize_t repsize;
8605 if (PyUnicode_READY(*res) == -1)
8606 return -1;
8607 repsize = PyUnicode_GET_LENGTH(*res);
Benjamin Peterson29060642009-01-31 22:14:21 +00008608 if (repsize==1) {
8609 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008610 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00008611 }
8612 else if (repsize!=0) {
8613 /* more than one character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008614 Py_ssize_t requiredsize = *opos +
8615 (PyUnicode_GET_LENGTH(input) - ipos) +
Benjamin Peterson29060642009-01-31 22:14:21 +00008616 repsize - 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008617 Py_ssize_t i;
8618 if (charmaptranslate_makespace(output, osize, requiredsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00008619 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008620 for(i = 0; i < repsize; i++)
8621 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00008622 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008623 }
8624 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008625 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008626 return 0;
8627}
8628
Alexander Belopolsky40018472011-02-26 01:02:56 +00008629PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008630_PyUnicode_TranslateCharmap(PyObject *input,
8631 PyObject *mapping,
8632 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008633{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008634 /* input object */
8635 char *idata;
8636 Py_ssize_t size, i;
8637 int kind;
8638 /* output buffer */
8639 Py_UCS4 *output = NULL;
8640 Py_ssize_t osize;
8641 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008642 /* current output position */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008643 Py_ssize_t opos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008644 char *reason = "character maps to <undefined>";
8645 PyObject *errorHandler = NULL;
8646 PyObject *exc = NULL;
8647 /* the following variable is used for caching string comparisons
8648 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8649 * 3=ignore, 4=xmlcharrefreplace */
8650 int known_errorHandler = -1;
8651
Guido van Rossumd57fd912000-03-10 22:53:23 +00008652 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008653 PyErr_BadArgument();
8654 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008655 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008656
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008657 if (PyUnicode_READY(input) == -1)
8658 return NULL;
8659 idata = (char*)PyUnicode_DATA(input);
8660 kind = PyUnicode_KIND(input);
8661 size = PyUnicode_GET_LENGTH(input);
8662 i = 0;
8663
8664 if (size == 0) {
8665 Py_INCREF(input);
8666 return input;
8667 }
8668
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008669 /* allocate enough for a simple 1:1 translation without
8670 replacements, if we need more, we'll resize */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008671 osize = size;
8672 output = PyMem_Malloc(osize * sizeof(Py_UCS4));
8673 opos = 0;
8674 if (output == NULL) {
8675 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00008676 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008677 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008678
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008679 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008680 /* try to encode it */
8681 PyObject *x = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008682 if (charmaptranslate_output(input, i, mapping,
8683 &output, &osize, &opos, &x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008684 Py_XDECREF(x);
8685 goto onError;
8686 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008687 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00008688 if (x!=Py_None) /* it worked => adjust input pointer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008689 ++i;
Benjamin Peterson29060642009-01-31 22:14:21 +00008690 else { /* untranslatable character */
8691 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8692 Py_ssize_t repsize;
8693 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008694 Py_ssize_t uni2;
Benjamin Peterson29060642009-01-31 22:14:21 +00008695 /* startpos for collecting untranslatable chars */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008696 Py_ssize_t collstart = i;
8697 Py_ssize_t collend = i+1;
8698 Py_ssize_t coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008699
Benjamin Peterson29060642009-01-31 22:14:21 +00008700 /* find all untranslatable characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008701 while (collend < size) {
8702 if (charmaptranslate_lookup(PyUnicode_READ(kind,idata, collend), mapping, &x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008703 goto onError;
8704 Py_XDECREF(x);
8705 if (x!=Py_None)
8706 break;
8707 ++collend;
8708 }
8709 /* cache callback name lookup
8710 * (if not done yet, i.e. it's the first error) */
8711 if (known_errorHandler==-1) {
8712 if ((errors==NULL) || (!strcmp(errors, "strict")))
8713 known_errorHandler = 1;
8714 else if (!strcmp(errors, "replace"))
8715 known_errorHandler = 2;
8716 else if (!strcmp(errors, "ignore"))
8717 known_errorHandler = 3;
8718 else if (!strcmp(errors, "xmlcharrefreplace"))
8719 known_errorHandler = 4;
8720 else
8721 known_errorHandler = 0;
8722 }
8723 switch (known_errorHandler) {
8724 case 1: /* strict */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008725 raise_translate_exception(&exc, input, collstart,
8726 collend, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008727 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008728 case 2: /* replace */
8729 /* No need to check for space, this is a 1:1 replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008730 for (coll = collstart; coll<collend; coll++)
8731 output[opos++] = '?';
Benjamin Peterson29060642009-01-31 22:14:21 +00008732 /* fall through */
8733 case 3: /* ignore */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008734 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008735 break;
8736 case 4: /* xmlcharrefreplace */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008737 /* generate replacement (temporarily (mis)uses i) */
8738 for (i = collstart; i < collend; ++i) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008739 char buffer[2+29+1+1];
8740 char *cp;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008741 sprintf(buffer, "&#%d;", PyUnicode_READ(kind, idata, i));
8742 if (charmaptranslate_makespace(&output, &osize,
8743 opos+strlen(buffer)+(size-collend)))
Benjamin Peterson29060642009-01-31 22:14:21 +00008744 goto onError;
8745 for (cp = buffer; *cp; ++cp)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008746 output[opos++] = *cp;
Benjamin Peterson29060642009-01-31 22:14:21 +00008747 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008748 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008749 break;
8750 default:
8751 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008752 reason, input, &exc,
8753 collstart, collend, &newpos);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02008754 if (repunicode == NULL || _PyUnicode_READY_REPLACE(&repunicode))
Benjamin Peterson29060642009-01-31 22:14:21 +00008755 goto onError;
8756 /* generate replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008757 repsize = PyUnicode_GET_LENGTH(repunicode);
8758 if (charmaptranslate_makespace(&output, &osize,
8759 opos+repsize+(size-collend))) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008760 Py_DECREF(repunicode);
8761 goto onError;
8762 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008763 for (uni2 = 0; repsize-->0; ++uni2)
8764 output[opos++] = PyUnicode_READ_CHAR(repunicode, uni2);
8765 i = newpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00008766 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008767 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008768 }
8769 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008770 res = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, output, opos);
8771 if (!res)
8772 goto onError;
8773 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008774 Py_XDECREF(exc);
8775 Py_XDECREF(errorHandler);
8776 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008777
Benjamin Peterson29060642009-01-31 22:14:21 +00008778 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008779 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008780 Py_XDECREF(exc);
8781 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008782 return NULL;
8783}
8784
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008785/* Deprecated. Use PyUnicode_Translate instead. */
8786PyObject *
8787PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8788 Py_ssize_t size,
8789 PyObject *mapping,
8790 const char *errors)
8791{
8792 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8793 if (!unicode)
8794 return NULL;
8795 return _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8796}
8797
Alexander Belopolsky40018472011-02-26 01:02:56 +00008798PyObject *
8799PyUnicode_Translate(PyObject *str,
8800 PyObject *mapping,
8801 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008802{
8803 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008804
Guido van Rossumd57fd912000-03-10 22:53:23 +00008805 str = PyUnicode_FromObject(str);
8806 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008807 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008808 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008809 Py_DECREF(str);
8810 return result;
Tim Petersced69f82003-09-16 20:30:58 +00008811
Benjamin Peterson29060642009-01-31 22:14:21 +00008812 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00008813 Py_XDECREF(str);
8814 return NULL;
8815}
Tim Petersced69f82003-09-16 20:30:58 +00008816
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008817static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008818fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008819{
8820 /* No need to call PyUnicode_READY(self) because this function is only
8821 called as a callback from fixup() which does it already. */
8822 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8823 const int kind = PyUnicode_KIND(self);
8824 void *data = PyUnicode_DATA(self);
8825 Py_UCS4 maxchar = 0, ch, fixed;
8826 Py_ssize_t i;
8827
8828 for (i = 0; i < len; ++i) {
8829 ch = PyUnicode_READ(kind, data, i);
8830 fixed = 0;
8831 if (ch > 127) {
8832 if (Py_UNICODE_ISSPACE(ch))
8833 fixed = ' ';
8834 else {
8835 const int decimal = Py_UNICODE_TODECIMAL(ch);
8836 if (decimal >= 0)
8837 fixed = '0' + decimal;
8838 }
8839 if (fixed != 0) {
8840 if (fixed > maxchar)
8841 maxchar = fixed;
8842 PyUnicode_WRITE(kind, data, i, fixed);
8843 }
8844 else if (ch > maxchar)
8845 maxchar = ch;
8846 }
8847 else if (ch > maxchar)
8848 maxchar = ch;
8849 }
8850
8851 return maxchar;
8852}
8853
8854PyObject *
8855_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
8856{
8857 if (!PyUnicode_Check(unicode)) {
8858 PyErr_BadInternalCall();
8859 return NULL;
8860 }
8861 if (PyUnicode_READY(unicode) == -1)
8862 return NULL;
8863 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
8864 /* If the string is already ASCII, just return the same string */
8865 Py_INCREF(unicode);
8866 return unicode;
8867 }
Victor Stinner9310abb2011-10-05 00:59:23 +02008868 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008869}
8870
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008871PyObject *
8872PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
8873 Py_ssize_t length)
8874{
8875 PyObject *result;
8876 Py_UNICODE *p; /* write pointer into result */
8877 Py_ssize_t i;
8878 /* Copy to a new string */
8879 result = (PyObject *)_PyUnicode_New(length);
8880 Py_UNICODE_COPY(PyUnicode_AS_UNICODE(result), s, length);
8881 if (result == NULL)
8882 return result;
8883 p = PyUnicode_AS_UNICODE(result);
8884 /* Iterate over code points */
8885 for (i = 0; i < length; i++) {
8886 Py_UNICODE ch =s[i];
8887 if (ch > 127) {
8888 int decimal = Py_UNICODE_TODECIMAL(ch);
8889 if (decimal >= 0)
8890 p[i] = '0' + decimal;
8891 }
8892 }
Victor Stinner17efeed2011-10-04 20:05:46 +02008893#ifndef DONT_MAKE_RESULT_READY
8894 if (_PyUnicode_READY_REPLACE(&result)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008895 Py_DECREF(result);
8896 return NULL;
8897 }
Victor Stinner17efeed2011-10-04 20:05:46 +02008898#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02008899 assert(_PyUnicode_CheckConsistency(result, 1));
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008900 return result;
8901}
Guido van Rossum9e896b32000-04-05 20:11:21 +00008902/* --- Decimal Encoder ---------------------------------------------------- */
8903
Alexander Belopolsky40018472011-02-26 01:02:56 +00008904int
8905PyUnicode_EncodeDecimal(Py_UNICODE *s,
8906 Py_ssize_t length,
8907 char *output,
8908 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00008909{
8910 Py_UNICODE *p, *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008911 PyObject *errorHandler = NULL;
8912 PyObject *exc = NULL;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008913 PyObject *unicode;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008914 const char *encoding = "decimal";
8915 const char *reason = "invalid decimal Unicode string";
8916 /* the following variable is used for caching string comparisons
8917 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
8918 int known_errorHandler = -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008919
8920 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008921 PyErr_BadArgument();
8922 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008923 }
8924
8925 p = s;
8926 end = s + length;
8927 while (p < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008928 register Py_UNICODE ch = *p;
8929 int decimal;
8930 PyObject *repunicode;
8931 Py_ssize_t repsize;
8932 Py_ssize_t newpos;
8933 Py_UNICODE *uni2;
8934 Py_UNICODE *collstart;
8935 Py_UNICODE *collend;
Tim Petersced69f82003-09-16 20:30:58 +00008936
Benjamin Peterson29060642009-01-31 22:14:21 +00008937 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008938 *output++ = ' ';
Benjamin Peterson29060642009-01-31 22:14:21 +00008939 ++p;
8940 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008941 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008942 decimal = Py_UNICODE_TODECIMAL(ch);
8943 if (decimal >= 0) {
8944 *output++ = '0' + decimal;
8945 ++p;
8946 continue;
8947 }
8948 if (0 < ch && ch < 256) {
8949 *output++ = (char)ch;
8950 ++p;
8951 continue;
8952 }
8953 /* All other characters are considered unencodable */
8954 collstart = p;
8955 collend = p+1;
8956 while (collend < end) {
8957 if ((0 < *collend && *collend < 256) ||
8958 !Py_UNICODE_ISSPACE(*collend) ||
8959 Py_UNICODE_TODECIMAL(*collend))
8960 break;
8961 }
8962 /* cache callback name lookup
8963 * (if not done yet, i.e. it's the first error) */
8964 if (known_errorHandler==-1) {
8965 if ((errors==NULL) || (!strcmp(errors, "strict")))
8966 known_errorHandler = 1;
8967 else if (!strcmp(errors, "replace"))
8968 known_errorHandler = 2;
8969 else if (!strcmp(errors, "ignore"))
8970 known_errorHandler = 3;
8971 else if (!strcmp(errors, "xmlcharrefreplace"))
8972 known_errorHandler = 4;
8973 else
8974 known_errorHandler = 0;
8975 }
8976 switch (known_errorHandler) {
8977 case 1: /* strict */
8978 raise_encode_exception(&exc, encoding, s, length, collstart-s, collend-s, reason);
8979 goto onError;
8980 case 2: /* replace */
8981 for (p = collstart; p < collend; ++p)
8982 *output++ = '?';
8983 /* fall through */
8984 case 3: /* ignore */
8985 p = collend;
8986 break;
8987 case 4: /* xmlcharrefreplace */
8988 /* generate replacement (temporarily (mis)uses p) */
8989 for (p = collstart; p < collend; ++p)
8990 output += sprintf(output, "&#%d;", (int)*p);
8991 p = collend;
8992 break;
8993 default:
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008994 unicode = PyUnicode_FromUnicode(s, length);
8995 if (unicode == NULL)
8996 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008997 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008998 encoding, reason, unicode, &exc,
Benjamin Peterson29060642009-01-31 22:14:21 +00008999 collstart-s, collend-s, &newpos);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01009000 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00009001 if (repunicode == NULL)
9002 goto onError;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00009003 if (!PyUnicode_Check(repunicode)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00009004 /* Byte results not supported, since they have no decimal property. */
Martin v. Löwisdb12d452009-05-02 18:52:14 +00009005 PyErr_SetString(PyExc_TypeError, "error handler should return unicode");
9006 Py_DECREF(repunicode);
9007 goto onError;
9008 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009009 /* generate replacement */
9010 repsize = PyUnicode_GET_SIZE(repunicode);
9011 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
9012 Py_UNICODE ch = *uni2;
9013 if (Py_UNICODE_ISSPACE(ch))
9014 *output++ = ' ';
9015 else {
9016 decimal = Py_UNICODE_TODECIMAL(ch);
9017 if (decimal >= 0)
9018 *output++ = '0' + decimal;
9019 else if (0 < ch && ch < 256)
9020 *output++ = (char)ch;
9021 else {
9022 Py_DECREF(repunicode);
9023 raise_encode_exception(&exc, encoding,
9024 s, length, collstart-s, collend-s, reason);
9025 goto onError;
9026 }
9027 }
9028 }
9029 p = s + newpos;
9030 Py_DECREF(repunicode);
9031 }
Guido van Rossum9e896b32000-04-05 20:11:21 +00009032 }
9033 /* 0-terminate the output string */
9034 *output++ = '\0';
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009035 Py_XDECREF(exc);
9036 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00009037 return 0;
9038
Benjamin Peterson29060642009-01-31 22:14:21 +00009039 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009040 Py_XDECREF(exc);
9041 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00009042 return -1;
9043}
9044
Guido van Rossumd57fd912000-03-10 22:53:23 +00009045/* --- Helpers ------------------------------------------------------------ */
9046
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009047static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02009048any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009049 Py_ssize_t start,
9050 Py_ssize_t end)
9051{
9052 int kind1, kind2, kind;
9053 void *buf1, *buf2;
9054 Py_ssize_t len1, len2, result;
9055
9056 kind1 = PyUnicode_KIND(s1);
9057 kind2 = PyUnicode_KIND(s2);
9058 kind = kind1 > kind2 ? kind1 : kind2;
9059 buf1 = PyUnicode_DATA(s1);
9060 buf2 = PyUnicode_DATA(s2);
9061 if (kind1 != kind)
9062 buf1 = _PyUnicode_AsKind(s1, kind);
9063 if (!buf1)
9064 return -2;
9065 if (kind2 != kind)
9066 buf2 = _PyUnicode_AsKind(s2, kind);
9067 if (!buf2) {
9068 if (kind1 != kind) PyMem_Free(buf1);
9069 return -2;
9070 }
9071 len1 = PyUnicode_GET_LENGTH(s1);
9072 len2 = PyUnicode_GET_LENGTH(s2);
9073
Victor Stinner794d5672011-10-10 03:21:36 +02009074 if (direction > 0) {
9075 switch(kind) {
9076 case PyUnicode_1BYTE_KIND:
9077 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9078 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9079 else
9080 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9081 break;
9082 case PyUnicode_2BYTE_KIND:
9083 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9084 break;
9085 case PyUnicode_4BYTE_KIND:
9086 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9087 break;
9088 default:
9089 assert(0); result = -2;
9090 }
9091 }
9092 else {
9093 switch(kind) {
9094 case PyUnicode_1BYTE_KIND:
9095 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9096 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9097 else
9098 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9099 break;
9100 case PyUnicode_2BYTE_KIND:
9101 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9102 break;
9103 case PyUnicode_4BYTE_KIND:
9104 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9105 break;
9106 default:
9107 assert(0); result = -2;
9108 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009109 }
9110
9111 if (kind1 != kind)
9112 PyMem_Free(buf1);
9113 if (kind2 != kind)
9114 PyMem_Free(buf2);
9115
9116 return result;
9117}
9118
9119Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02009120_PyUnicode_InsertThousandsGrouping(PyObject *unicode, int kind, void *data,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009121 Py_ssize_t n_buffer,
9122 void *digits, Py_ssize_t n_digits,
9123 Py_ssize_t min_width,
9124 const char *grouping,
9125 const char *thousands_sep)
9126{
9127 switch(kind) {
9128 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009129 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
9130 return _PyUnicode_ascii_InsertThousandsGrouping(
9131 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
9132 min_width, grouping, thousands_sep);
9133 else
9134 return _PyUnicode_ucs1_InsertThousandsGrouping(
9135 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
9136 min_width, grouping, thousands_sep);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009137 case PyUnicode_2BYTE_KIND:
9138 return _PyUnicode_ucs2_InsertThousandsGrouping(
9139 (Py_UCS2*)data, n_buffer, (Py_UCS2*)digits, n_digits,
9140 min_width, grouping, thousands_sep);
9141 case PyUnicode_4BYTE_KIND:
9142 return _PyUnicode_ucs4_InsertThousandsGrouping(
9143 (Py_UCS4*)data, n_buffer, (Py_UCS4*)digits, n_digits,
9144 min_width, grouping, thousands_sep);
9145 }
9146 assert(0);
9147 return -1;
9148}
9149
9150
Thomas Wouters477c8d52006-05-27 19:21:47 +00009151/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009152#define ADJUST_INDICES(start, end, len) \
9153 if (end > len) \
9154 end = len; \
9155 else if (end < 0) { \
9156 end += len; \
9157 if (end < 0) \
9158 end = 0; \
9159 } \
9160 if (start < 0) { \
9161 start += len; \
9162 if (start < 0) \
9163 start = 0; \
9164 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009165
Alexander Belopolsky40018472011-02-26 01:02:56 +00009166Py_ssize_t
9167PyUnicode_Count(PyObject *str,
9168 PyObject *substr,
9169 Py_ssize_t start,
9170 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009171{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009172 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009173 PyObject* str_obj;
9174 PyObject* sub_obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009175 int kind1, kind2, kind;
9176 void *buf1 = NULL, *buf2 = NULL;
9177 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009178
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009179 str_obj = PyUnicode_FromObject(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009180 if (!str_obj || PyUnicode_READY(str_obj) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009181 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009182 sub_obj = PyUnicode_FromObject(substr);
Victor Stinnere9a29352011-10-01 02:14:59 +02009183 if (!sub_obj || PyUnicode_READY(sub_obj) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009184 Py_DECREF(str_obj);
9185 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009186 }
Tim Petersced69f82003-09-16 20:30:58 +00009187
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009188 kind1 = PyUnicode_KIND(str_obj);
9189 kind2 = PyUnicode_KIND(sub_obj);
9190 kind = kind1 > kind2 ? kind1 : kind2;
9191 buf1 = PyUnicode_DATA(str_obj);
9192 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009193 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009194 if (!buf1)
9195 goto onError;
9196 buf2 = PyUnicode_DATA(sub_obj);
9197 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009198 buf2 = _PyUnicode_AsKind(sub_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009199 if (!buf2)
9200 goto onError;
9201 len1 = PyUnicode_GET_LENGTH(str_obj);
9202 len2 = PyUnicode_GET_LENGTH(sub_obj);
9203
9204 ADJUST_INDICES(start, end, len1);
9205 switch(kind) {
9206 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009207 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
9208 result = asciilib_count(
9209 ((Py_UCS1*)buf1) + start, end - start,
9210 buf2, len2, PY_SSIZE_T_MAX
9211 );
9212 else
9213 result = ucs1lib_count(
9214 ((Py_UCS1*)buf1) + start, end - start,
9215 buf2, len2, PY_SSIZE_T_MAX
9216 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009217 break;
9218 case PyUnicode_2BYTE_KIND:
9219 result = ucs2lib_count(
9220 ((Py_UCS2*)buf1) + start, end - start,
9221 buf2, len2, PY_SSIZE_T_MAX
9222 );
9223 break;
9224 case PyUnicode_4BYTE_KIND:
9225 result = ucs4lib_count(
9226 ((Py_UCS4*)buf1) + start, end - start,
9227 buf2, len2, PY_SSIZE_T_MAX
9228 );
9229 break;
9230 default:
9231 assert(0); result = 0;
9232 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009233
9234 Py_DECREF(sub_obj);
9235 Py_DECREF(str_obj);
9236
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009237 if (kind1 != kind)
9238 PyMem_Free(buf1);
9239 if (kind2 != kind)
9240 PyMem_Free(buf2);
9241
Guido van Rossumd57fd912000-03-10 22:53:23 +00009242 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009243 onError:
9244 Py_DECREF(sub_obj);
9245 Py_DECREF(str_obj);
9246 if (kind1 != kind && buf1)
9247 PyMem_Free(buf1);
9248 if (kind2 != kind && buf2)
9249 PyMem_Free(buf2);
9250 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009251}
9252
Alexander Belopolsky40018472011-02-26 01:02:56 +00009253Py_ssize_t
9254PyUnicode_Find(PyObject *str,
9255 PyObject *sub,
9256 Py_ssize_t start,
9257 Py_ssize_t end,
9258 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009259{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009260 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009261
Guido van Rossumd57fd912000-03-10 22:53:23 +00009262 str = PyUnicode_FromObject(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009263 if (!str || PyUnicode_READY(str) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009264 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009265 sub = PyUnicode_FromObject(sub);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009266 if (!sub || PyUnicode_READY(sub) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009267 Py_DECREF(str);
9268 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009269 }
Tim Petersced69f82003-09-16 20:30:58 +00009270
Victor Stinner794d5672011-10-10 03:21:36 +02009271 result = any_find_slice(direction,
9272 str, sub, start, end
9273 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00009274
Guido van Rossumd57fd912000-03-10 22:53:23 +00009275 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009276 Py_DECREF(sub);
9277
Guido van Rossumd57fd912000-03-10 22:53:23 +00009278 return result;
9279}
9280
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009281Py_ssize_t
9282PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9283 Py_ssize_t start, Py_ssize_t end,
9284 int direction)
9285{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009286 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009287 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009288 if (PyUnicode_READY(str) == -1)
9289 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009290 if (start < 0 || end < 0) {
9291 PyErr_SetString(PyExc_IndexError, "string index out of range");
9292 return -2;
9293 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009294 if (end > PyUnicode_GET_LENGTH(str))
9295 end = PyUnicode_GET_LENGTH(str);
9296 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009297 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9298 kind, end-start, ch, direction);
9299 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009300 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009301 else
9302 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009303}
9304
Alexander Belopolsky40018472011-02-26 01:02:56 +00009305static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009306tailmatch(PyObject *self,
9307 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009308 Py_ssize_t start,
9309 Py_ssize_t end,
9310 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009311{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009312 int kind_self;
9313 int kind_sub;
9314 void *data_self;
9315 void *data_sub;
9316 Py_ssize_t offset;
9317 Py_ssize_t i;
9318 Py_ssize_t end_sub;
9319
9320 if (PyUnicode_READY(self) == -1 ||
9321 PyUnicode_READY(substring) == -1)
9322 return 0;
9323
9324 if (PyUnicode_GET_LENGTH(substring) == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009325 return 1;
9326
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009327 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9328 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009329 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009330 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009331
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009332 kind_self = PyUnicode_KIND(self);
9333 data_self = PyUnicode_DATA(self);
9334 kind_sub = PyUnicode_KIND(substring);
9335 data_sub = PyUnicode_DATA(substring);
9336 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9337
9338 if (direction > 0)
9339 offset = end;
9340 else
9341 offset = start;
9342
9343 if (PyUnicode_READ(kind_self, data_self, offset) ==
9344 PyUnicode_READ(kind_sub, data_sub, 0) &&
9345 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9346 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9347 /* If both are of the same kind, memcmp is sufficient */
9348 if (kind_self == kind_sub) {
9349 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009350 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009351 data_sub,
9352 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009353 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009354 }
9355 /* otherwise we have to compare each character by first accesing it */
9356 else {
9357 /* We do not need to compare 0 and len(substring)-1 because
9358 the if statement above ensured already that they are equal
9359 when we end up here. */
9360 // TODO: honor direction and do a forward or backwards search
9361 for (i = 1; i < end_sub; ++i) {
9362 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9363 PyUnicode_READ(kind_sub, data_sub, i))
9364 return 0;
9365 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009366 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009367 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009368 }
9369
9370 return 0;
9371}
9372
Alexander Belopolsky40018472011-02-26 01:02:56 +00009373Py_ssize_t
9374PyUnicode_Tailmatch(PyObject *str,
9375 PyObject *substr,
9376 Py_ssize_t start,
9377 Py_ssize_t end,
9378 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009379{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009380 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009381
Guido van Rossumd57fd912000-03-10 22:53:23 +00009382 str = PyUnicode_FromObject(str);
9383 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009384 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009385 substr = PyUnicode_FromObject(substr);
9386 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009387 Py_DECREF(str);
9388 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009389 }
Tim Petersced69f82003-09-16 20:30:58 +00009390
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009391 result = tailmatch(str, substr,
Benjamin Peterson29060642009-01-31 22:14:21 +00009392 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009393 Py_DECREF(str);
9394 Py_DECREF(substr);
9395 return result;
9396}
9397
Guido van Rossumd57fd912000-03-10 22:53:23 +00009398/* Apply fixfct filter to the Unicode object self and return a
9399 reference to the modified object */
9400
Alexander Belopolsky40018472011-02-26 01:02:56 +00009401static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009402fixup(PyObject *self,
9403 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009404{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009405 PyObject *u;
9406 Py_UCS4 maxchar_old, maxchar_new = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009407
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009408 if (PyUnicode_READY(self) == -1)
9409 return NULL;
9410 maxchar_old = PyUnicode_MAX_CHAR_VALUE(self);
9411 u = PyUnicode_New(PyUnicode_GET_LENGTH(self),
9412 maxchar_old);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009413 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009414 return NULL;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009415
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009416 Py_MEMCPY(PyUnicode_1BYTE_DATA(u), PyUnicode_1BYTE_DATA(self),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009417 PyUnicode_GET_LENGTH(u) * PyUnicode_KIND(u));
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009418
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009419 /* fix functions return the new maximum character in a string,
9420 if the kind of the resulting unicode object does not change,
9421 everything is fine. Otherwise we need to change the string kind
9422 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009423 maxchar_new = fixfct(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009424 if (maxchar_new == 0)
9425 /* do nothing, keep maxchar_new at 0 which means no changes. */;
9426 else if (maxchar_new <= 127)
9427 maxchar_new = 127;
9428 else if (maxchar_new <= 255)
9429 maxchar_new = 255;
9430 else if (maxchar_new <= 65535)
9431 maxchar_new = 65535;
9432 else
9433 maxchar_new = 1114111; /* 0x10ffff */
9434
9435 if (!maxchar_new && PyUnicode_CheckExact(self)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009436 /* fixfct should return TRUE if it modified the buffer. If
9437 FALSE, return a reference to the original buffer instead
9438 (to save space, not time) */
9439 Py_INCREF(self);
9440 Py_DECREF(u);
Victor Stinner7931d9a2011-11-04 00:22:48 +01009441 return self;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009442 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009443 else if (maxchar_new == maxchar_old) {
9444 return u;
9445 }
9446 else {
9447 /* In case the maximum character changed, we need to
9448 convert the string to the new category. */
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009449 PyObject *v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009450 if (v == NULL) {
9451 Py_DECREF(u);
9452 return NULL;
9453 }
9454 if (maxchar_new > maxchar_old) {
9455 /* If the maxchar increased so that the kind changed, not all
9456 characters are representable anymore and we need to fix the
9457 string again. This only happens in very few cases. */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009458 copy_characters(v, 0, self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinner9310abb2011-10-05 00:59:23 +02009459 maxchar_old = fixfct(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009460 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
9461 }
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009462 else {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009463 copy_characters(v, 0, u, 0, PyUnicode_GET_LENGTH(self));
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009464 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009465
9466 Py_DECREF(u);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009467 assert(_PyUnicode_CheckConsistency(v, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009468 return v;
9469 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009470}
9471
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009472static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009473fixupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009474{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009475 /* No need to call PyUnicode_READY(self) because this function is only
9476 called as a callback from fixup() which does it already. */
9477 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9478 const int kind = PyUnicode_KIND(self);
9479 void *data = PyUnicode_DATA(self);
9480 int touched = 0;
9481 Py_UCS4 maxchar = 0;
9482 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009483
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009484 for (i = 0; i < len; ++i) {
9485 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9486 const Py_UCS4 up = Py_UNICODE_TOUPPER(ch);
9487 if (up != ch) {
9488 if (up > maxchar)
9489 maxchar = up;
9490 PyUnicode_WRITE(kind, data, i, up);
9491 touched = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00009492 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009493 else if (ch > maxchar)
9494 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009495 }
9496
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009497 if (touched)
9498 return maxchar;
9499 else
9500 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009501}
9502
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009503static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009504fixlower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009505{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009506 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9507 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9508 const int kind = PyUnicode_KIND(self);
9509 void *data = PyUnicode_DATA(self);
9510 int touched = 0;
9511 Py_UCS4 maxchar = 0;
9512 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009513
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009514 for(i = 0; i < len; ++i) {
9515 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9516 const Py_UCS4 lo = Py_UNICODE_TOLOWER(ch);
9517 if (lo != ch) {
9518 if (lo > maxchar)
9519 maxchar = lo;
9520 PyUnicode_WRITE(kind, data, i, lo);
9521 touched = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00009522 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009523 else if (ch > maxchar)
9524 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009525 }
9526
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009527 if (touched)
9528 return maxchar;
9529 else
9530 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009531}
9532
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009533static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009534fixswapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009535{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009536 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9537 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9538 const int kind = PyUnicode_KIND(self);
9539 void *data = PyUnicode_DATA(self);
9540 int touched = 0;
9541 Py_UCS4 maxchar = 0;
9542 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009543
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009544 for(i = 0; i < len; ++i) {
9545 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9546 Py_UCS4 nu = 0;
9547
9548 if (Py_UNICODE_ISUPPER(ch))
9549 nu = Py_UNICODE_TOLOWER(ch);
9550 else if (Py_UNICODE_ISLOWER(ch))
9551 nu = Py_UNICODE_TOUPPER(ch);
9552
9553 if (nu != 0) {
9554 if (nu > maxchar)
9555 maxchar = nu;
9556 PyUnicode_WRITE(kind, data, i, nu);
9557 touched = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009558 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009559 else if (ch > maxchar)
9560 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009561 }
9562
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009563 if (touched)
9564 return maxchar;
9565 else
9566 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009567}
9568
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009569static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009570fixcapitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009571{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009572 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9573 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9574 const int kind = PyUnicode_KIND(self);
9575 void *data = PyUnicode_DATA(self);
9576 int touched = 0;
9577 Py_UCS4 maxchar = 0;
9578 Py_ssize_t i = 0;
9579 Py_UCS4 ch;
Tim Petersced69f82003-09-16 20:30:58 +00009580
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009581 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009582 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009583
9584 ch = PyUnicode_READ(kind, data, i);
9585 if (!Py_UNICODE_ISUPPER(ch)) {
9586 maxchar = Py_UNICODE_TOUPPER(ch);
9587 PyUnicode_WRITE(kind, data, i, maxchar);
9588 touched = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009589 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009590 ++i;
9591 for(; i < len; ++i) {
9592 ch = PyUnicode_READ(kind, data, i);
9593 if (!Py_UNICODE_ISLOWER(ch)) {
9594 const Py_UCS4 lo = Py_UNICODE_TOLOWER(ch);
9595 if (lo > maxchar)
9596 maxchar = lo;
9597 PyUnicode_WRITE(kind, data, i, lo);
9598 touched = 1;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009599 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009600 else if (ch > maxchar)
9601 maxchar = ch;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009602 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009603
9604 if (touched)
9605 return maxchar;
9606 else
9607 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009608}
9609
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009610static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009611fixtitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009612{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009613 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9614 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9615 const int kind = PyUnicode_KIND(self);
9616 void *data = PyUnicode_DATA(self);
9617 Py_UCS4 maxchar = 0;
9618 Py_ssize_t i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009619 int previous_is_cased;
9620
9621 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009622 if (len == 1) {
9623 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9624 const Py_UCS4 ti = Py_UNICODE_TOTITLE(ch);
9625 if (ti != ch) {
9626 PyUnicode_WRITE(kind, data, i, ti);
9627 return ti;
Benjamin Peterson29060642009-01-31 22:14:21 +00009628 }
9629 else
9630 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009631 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009632 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009633 for(; i < len; ++i) {
9634 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9635 Py_UCS4 nu;
Tim Petersced69f82003-09-16 20:30:58 +00009636
Benjamin Peterson29060642009-01-31 22:14:21 +00009637 if (previous_is_cased)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009638 nu = Py_UNICODE_TOLOWER(ch);
Benjamin Peterson29060642009-01-31 22:14:21 +00009639 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009640 nu = Py_UNICODE_TOTITLE(ch);
9641
9642 if (nu > maxchar)
9643 maxchar = nu;
9644 PyUnicode_WRITE(kind, data, i, nu);
Tim Petersced69f82003-09-16 20:30:58 +00009645
Benjamin Peterson29060642009-01-31 22:14:21 +00009646 if (Py_UNICODE_ISLOWER(ch) ||
9647 Py_UNICODE_ISUPPER(ch) ||
9648 Py_UNICODE_ISTITLE(ch))
9649 previous_is_cased = 1;
9650 else
9651 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009652 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009653 return maxchar;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009654}
9655
Tim Peters8ce9f162004-08-27 01:49:32 +00009656PyObject *
9657PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009658{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009659 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009660 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009661 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009662 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009663 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9664 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009665 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009666 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009667 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009668 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009669 int use_memcpy;
9670 unsigned char *res_data = NULL, *sep_data = NULL;
9671 PyObject *last_obj;
9672 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009673
Tim Peters05eba1f2004-08-27 21:32:02 +00009674 fseq = PySequence_Fast(seq, "");
9675 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009676 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009677 }
9678
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009679 /* NOTE: the following code can't call back into Python code,
9680 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009681 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009682
Tim Peters05eba1f2004-08-27 21:32:02 +00009683 seqlen = PySequence_Fast_GET_SIZE(fseq);
9684 /* If empty sequence, return u"". */
9685 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009686 Py_DECREF(fseq);
9687 Py_INCREF(unicode_empty);
9688 res = unicode_empty;
9689 return res;
Tim Peters05eba1f2004-08-27 21:32:02 +00009690 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009691
Tim Peters05eba1f2004-08-27 21:32:02 +00009692 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009693 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009694 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009695 if (seqlen == 1) {
9696 if (PyUnicode_CheckExact(items[0])) {
9697 res = items[0];
9698 Py_INCREF(res);
9699 Py_DECREF(fseq);
9700 return res;
9701 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009702 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009703 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009704 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009705 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009706 /* Set up sep and seplen */
9707 if (separator == NULL) {
9708 /* fall back to a blank space separator */
9709 sep = PyUnicode_FromOrdinal(' ');
9710 if (!sep)
9711 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009712 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009713 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009714 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009715 else {
9716 if (!PyUnicode_Check(separator)) {
9717 PyErr_Format(PyExc_TypeError,
9718 "separator: expected str instance,"
9719 " %.80s found",
9720 Py_TYPE(separator)->tp_name);
9721 goto onError;
9722 }
9723 if (PyUnicode_READY(separator))
9724 goto onError;
9725 sep = separator;
9726 seplen = PyUnicode_GET_LENGTH(separator);
9727 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9728 /* inc refcount to keep this code path symmetric with the
9729 above case of a blank separator */
9730 Py_INCREF(sep);
9731 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009732 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009733 }
9734
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009735 /* There are at least two things to join, or else we have a subclass
9736 * of str in the sequence.
9737 * Do a pre-pass to figure out the total amount of space we'll
9738 * need (sz), and see whether all argument are strings.
9739 */
9740 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009741#ifdef Py_DEBUG
9742 use_memcpy = 0;
9743#else
9744 use_memcpy = 1;
9745#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009746 for (i = 0; i < seqlen; i++) {
9747 const Py_ssize_t old_sz = sz;
9748 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009749 if (!PyUnicode_Check(item)) {
9750 PyErr_Format(PyExc_TypeError,
9751 "sequence item %zd: expected str instance,"
9752 " %.80s found",
9753 i, Py_TYPE(item)->tp_name);
9754 goto onError;
9755 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009756 if (PyUnicode_READY(item) == -1)
9757 goto onError;
9758 sz += PyUnicode_GET_LENGTH(item);
9759 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009760 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009761 if (i != 0)
9762 sz += seplen;
9763 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9764 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009765 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009766 goto onError;
9767 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009768 if (use_memcpy && last_obj != NULL) {
9769 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9770 use_memcpy = 0;
9771 }
9772 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009773 }
Tim Petersced69f82003-09-16 20:30:58 +00009774
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009775 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009776 if (res == NULL)
9777 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009778
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009779 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009780#ifdef Py_DEBUG
9781 use_memcpy = 0;
9782#else
9783 if (use_memcpy) {
9784 res_data = PyUnicode_1BYTE_DATA(res);
9785 kind = PyUnicode_KIND(res);
9786 if (seplen != 0)
9787 sep_data = PyUnicode_1BYTE_DATA(sep);
9788 }
9789#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009790 for (i = 0, res_offset = 0; i < seqlen; ++i) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009791 Py_ssize_t itemlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009792 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009793 /* Copy item, and maybe the separator. */
Victor Stinner9ce5a832011-10-03 23:36:02 +02009794 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009795 if (use_memcpy) {
9796 Py_MEMCPY(res_data,
9797 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009798 kind * seplen);
9799 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009800 }
9801 else {
9802 copy_characters(res, res_offset, sep, 0, seplen);
9803 res_offset += seplen;
9804 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009805 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009806 itemlen = PyUnicode_GET_LENGTH(item);
9807 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009808 if (use_memcpy) {
9809 Py_MEMCPY(res_data,
9810 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009811 kind * itemlen);
9812 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009813 }
9814 else {
9815 copy_characters(res, res_offset, item, 0, itemlen);
9816 res_offset += itemlen;
9817 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009818 }
Tim Peters05eba1f2004-08-27 21:32:02 +00009819 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009820 if (use_memcpy)
9821 assert(res_data == PyUnicode_1BYTE_DATA(res)
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009822 + kind * PyUnicode_GET_LENGTH(res));
Victor Stinnerdd077322011-10-07 17:02:31 +02009823 else
9824 assert(res_offset == PyUnicode_GET_LENGTH(res));
Tim Peters8ce9f162004-08-27 01:49:32 +00009825
Tim Peters05eba1f2004-08-27 21:32:02 +00009826 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009827 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009828 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009829 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009830
Benjamin Peterson29060642009-01-31 22:14:21 +00009831 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00009832 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009833 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009834 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009835 return NULL;
9836}
9837
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009838#define FILL(kind, data, value, start, length) \
9839 do { \
9840 Py_ssize_t i_ = 0; \
9841 assert(kind != PyUnicode_WCHAR_KIND); \
9842 switch ((kind)) { \
9843 case PyUnicode_1BYTE_KIND: { \
9844 unsigned char * to_ = (unsigned char *)((data)) + (start); \
9845 memset(to_, (unsigned char)value, length); \
9846 break; \
9847 } \
9848 case PyUnicode_2BYTE_KIND: { \
9849 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
9850 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9851 break; \
9852 } \
9853 default: { \
9854 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
9855 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9856 break; \
9857 } \
9858 } \
9859 } while (0)
9860
Victor Stinner9310abb2011-10-05 00:59:23 +02009861static PyObject *
9862pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009863 Py_ssize_t left,
9864 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009865 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009866{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009867 PyObject *u;
9868 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009869 int kind;
9870 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009871
9872 if (left < 0)
9873 left = 0;
9874 if (right < 0)
9875 right = 0;
9876
Tim Peters7a29bd52001-09-12 03:03:31 +00009877 if (left == 0 && right == 0 && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00009878 Py_INCREF(self);
9879 return self;
9880 }
9881
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009882 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
9883 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00009884 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
9885 return NULL;
9886 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009887 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
9888 if (fill > maxchar)
9889 maxchar = fill;
9890 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009891 if (!u)
9892 return NULL;
9893
9894 kind = PyUnicode_KIND(u);
9895 data = PyUnicode_DATA(u);
9896 if (left)
9897 FILL(kind, data, fill, 0, left);
9898 if (right)
9899 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009900 copy_characters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009901 assert(_PyUnicode_CheckConsistency(u, 1));
9902 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009903}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009904#undef FILL
Guido van Rossumd57fd912000-03-10 22:53:23 +00009905
Alexander Belopolsky40018472011-02-26 01:02:56 +00009906PyObject *
9907PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009908{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009909 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009910
9911 string = PyUnicode_FromObject(string);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009912 if (string == NULL || PyUnicode_READY(string) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009913 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009914
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009915 switch(PyUnicode_KIND(string)) {
9916 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009917 if (PyUnicode_IS_ASCII(string))
9918 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009919 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009920 PyUnicode_GET_LENGTH(string), keepends);
9921 else
9922 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009923 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009924 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009925 break;
9926 case PyUnicode_2BYTE_KIND:
9927 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009928 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009929 PyUnicode_GET_LENGTH(string), keepends);
9930 break;
9931 case PyUnicode_4BYTE_KIND:
9932 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009933 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009934 PyUnicode_GET_LENGTH(string), keepends);
9935 break;
9936 default:
9937 assert(0);
9938 list = 0;
9939 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009940 Py_DECREF(string);
9941 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009942}
9943
Alexander Belopolsky40018472011-02-26 01:02:56 +00009944static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009945split(PyObject *self,
9946 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009947 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009948{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009949 int kind1, kind2, kind;
9950 void *buf1, *buf2;
9951 Py_ssize_t len1, len2;
9952 PyObject* out;
9953
Guido van Rossumd57fd912000-03-10 22:53:23 +00009954 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009955 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009956
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009957 if (PyUnicode_READY(self) == -1)
9958 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009959
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009960 if (substring == NULL)
9961 switch(PyUnicode_KIND(self)) {
9962 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009963 if (PyUnicode_IS_ASCII(self))
9964 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009965 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009966 PyUnicode_GET_LENGTH(self), maxcount
9967 );
9968 else
9969 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009970 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009971 PyUnicode_GET_LENGTH(self), maxcount
9972 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009973 case PyUnicode_2BYTE_KIND:
9974 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009975 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009976 PyUnicode_GET_LENGTH(self), maxcount
9977 );
9978 case PyUnicode_4BYTE_KIND:
9979 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009980 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009981 PyUnicode_GET_LENGTH(self), maxcount
9982 );
9983 default:
9984 assert(0);
9985 return NULL;
9986 }
9987
9988 if (PyUnicode_READY(substring) == -1)
9989 return NULL;
9990
9991 kind1 = PyUnicode_KIND(self);
9992 kind2 = PyUnicode_KIND(substring);
9993 kind = kind1 > kind2 ? kind1 : kind2;
9994 buf1 = PyUnicode_DATA(self);
9995 buf2 = PyUnicode_DATA(substring);
9996 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009997 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009998 if (!buf1)
9999 return NULL;
10000 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010001 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010002 if (!buf2) {
10003 if (kind1 != kind) PyMem_Free(buf1);
10004 return NULL;
10005 }
10006 len1 = PyUnicode_GET_LENGTH(self);
10007 len2 = PyUnicode_GET_LENGTH(substring);
10008
10009 switch(kind) {
10010 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010011 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10012 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010013 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010014 else
10015 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010016 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010017 break;
10018 case PyUnicode_2BYTE_KIND:
10019 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010020 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010021 break;
10022 case PyUnicode_4BYTE_KIND:
10023 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010024 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010025 break;
10026 default:
10027 out = NULL;
10028 }
10029 if (kind1 != kind)
10030 PyMem_Free(buf1);
10031 if (kind2 != kind)
10032 PyMem_Free(buf2);
10033 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010034}
10035
Alexander Belopolsky40018472011-02-26 01:02:56 +000010036static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010037rsplit(PyObject *self,
10038 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010039 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010040{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010041 int kind1, kind2, kind;
10042 void *buf1, *buf2;
10043 Py_ssize_t len1, len2;
10044 PyObject* out;
10045
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010046 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010047 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010048
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010049 if (PyUnicode_READY(self) == -1)
10050 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010051
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010052 if (substring == NULL)
10053 switch(PyUnicode_KIND(self)) {
10054 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010055 if (PyUnicode_IS_ASCII(self))
10056 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010057 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010058 PyUnicode_GET_LENGTH(self), maxcount
10059 );
10060 else
10061 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010062 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010063 PyUnicode_GET_LENGTH(self), maxcount
10064 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010065 case PyUnicode_2BYTE_KIND:
10066 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010067 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010068 PyUnicode_GET_LENGTH(self), maxcount
10069 );
10070 case PyUnicode_4BYTE_KIND:
10071 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010072 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010073 PyUnicode_GET_LENGTH(self), maxcount
10074 );
10075 default:
10076 assert(0);
10077 return NULL;
10078 }
10079
10080 if (PyUnicode_READY(substring) == -1)
10081 return NULL;
10082
10083 kind1 = PyUnicode_KIND(self);
10084 kind2 = PyUnicode_KIND(substring);
10085 kind = kind1 > kind2 ? kind1 : kind2;
10086 buf1 = PyUnicode_DATA(self);
10087 buf2 = PyUnicode_DATA(substring);
10088 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010089 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010090 if (!buf1)
10091 return NULL;
10092 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010093 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010094 if (!buf2) {
10095 if (kind1 != kind) PyMem_Free(buf1);
10096 return NULL;
10097 }
10098 len1 = PyUnicode_GET_LENGTH(self);
10099 len2 = PyUnicode_GET_LENGTH(substring);
10100
10101 switch(kind) {
10102 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010103 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10104 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010105 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010106 else
10107 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010108 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010109 break;
10110 case PyUnicode_2BYTE_KIND:
10111 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010112 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010113 break;
10114 case PyUnicode_4BYTE_KIND:
10115 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010116 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010117 break;
10118 default:
10119 out = NULL;
10120 }
10121 if (kind1 != kind)
10122 PyMem_Free(buf1);
10123 if (kind2 != kind)
10124 PyMem_Free(buf2);
10125 return out;
10126}
10127
10128static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010129anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10130 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010131{
10132 switch(kind) {
10133 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010134 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10135 return asciilib_find(buf1, len1, buf2, len2, offset);
10136 else
10137 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010138 case PyUnicode_2BYTE_KIND:
10139 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10140 case PyUnicode_4BYTE_KIND:
10141 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10142 }
10143 assert(0);
10144 return -1;
10145}
10146
10147static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010148anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10149 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010150{
10151 switch(kind) {
10152 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010153 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10154 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10155 else
10156 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010157 case PyUnicode_2BYTE_KIND:
10158 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10159 case PyUnicode_4BYTE_KIND:
10160 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10161 }
10162 assert(0);
10163 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010164}
10165
Alexander Belopolsky40018472011-02-26 01:02:56 +000010166static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010167replace(PyObject *self, PyObject *str1,
10168 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010169{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010170 PyObject *u;
10171 char *sbuf = PyUnicode_DATA(self);
10172 char *buf1 = PyUnicode_DATA(str1);
10173 char *buf2 = PyUnicode_DATA(str2);
10174 int srelease = 0, release1 = 0, release2 = 0;
10175 int skind = PyUnicode_KIND(self);
10176 int kind1 = PyUnicode_KIND(str1);
10177 int kind2 = PyUnicode_KIND(str2);
10178 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10179 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10180 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010181 int mayshrink;
10182 Py_UCS4 maxchar, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010183
10184 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010185 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010186 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010187 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010188
Victor Stinner59de0ee2011-10-07 10:01:28 +020010189 if (str1 == str2)
10190 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010191 if (skind < kind1)
10192 /* substring too wide to be present */
10193 goto nothing;
10194
Victor Stinner49a0a212011-10-12 23:46:10 +020010195 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
10196 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10197 /* Replacing str1 with str2 may cause a maxchar reduction in the
10198 result string. */
10199 mayshrink = (maxchar_str2 < maxchar);
10200 maxchar = Py_MAX(maxchar, maxchar_str2);
10201
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010202 if (len1 == len2) {
Antoine Pitroucbfdee32010-01-13 08:58:08 +000010203 Py_ssize_t i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010204 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010205 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010206 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010207 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010208 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010209 Py_UCS4 u1, u2;
10210 int rkind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010211 u1 = PyUnicode_READ_CHAR(str1, 0);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +020010212 if (findchar(sbuf, PyUnicode_KIND(self),
10213 slen, u1, 1) < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010214 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010215 u2 = PyUnicode_READ_CHAR(str2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010216 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010217 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010218 goto error;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010219 copy_characters(u, 0, self, 0, slen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010220 rkind = PyUnicode_KIND(u);
10221 for (i = 0; i < PyUnicode_GET_LENGTH(u); i++)
10222 if (PyUnicode_READ(rkind, PyUnicode_DATA(u), i) == u1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010223 if (--maxcount < 0)
10224 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010225 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), i, u2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010226 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010227 }
10228 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010229 int rkind = skind;
10230 char *res;
Victor Stinner25a4b292011-10-06 12:31:55 +020010231
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010232 if (kind1 < rkind) {
10233 /* widen substring */
10234 buf1 = _PyUnicode_AsKind(str1, rkind);
10235 if (!buf1) goto error;
10236 release1 = 1;
10237 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010238 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010239 if (i < 0)
10240 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010241 if (rkind > kind2) {
10242 /* widen replacement */
10243 buf2 = _PyUnicode_AsKind(str2, rkind);
10244 if (!buf2) goto error;
10245 release2 = 1;
10246 }
10247 else if (rkind < kind2) {
10248 /* widen self and buf1 */
10249 rkind = kind2;
10250 if (release1) PyMem_Free(buf1);
10251 sbuf = _PyUnicode_AsKind(self, rkind);
10252 if (!sbuf) goto error;
10253 srelease = 1;
10254 buf1 = _PyUnicode_AsKind(str1, rkind);
10255 if (!buf1) goto error;
10256 release1 = 1;
10257 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010258 u = PyUnicode_New(slen, maxchar);
10259 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010260 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010261 assert(PyUnicode_KIND(u) == rkind);
10262 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010263
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010264 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010265 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010266 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010267 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010268 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010269 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010270
10271 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010272 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010273 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010274 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010275 if (i == -1)
10276 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010277 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010278 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010279 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010280 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010281 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010282 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010283 }
10284 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010285 Py_ssize_t n, i, j, ires;
10286 Py_ssize_t product, new_size;
10287 int rkind = skind;
10288 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010289
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010290 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010291 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010292 buf1 = _PyUnicode_AsKind(str1, rkind);
10293 if (!buf1) goto error;
10294 release1 = 1;
10295 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010296 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010297 if (n == 0)
10298 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010299 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010300 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010301 buf2 = _PyUnicode_AsKind(str2, rkind);
10302 if (!buf2) goto error;
10303 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010304 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010305 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010306 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010307 rkind = kind2;
10308 sbuf = _PyUnicode_AsKind(self, rkind);
10309 if (!sbuf) goto error;
10310 srelease = 1;
10311 if (release1) PyMem_Free(buf1);
10312 buf1 = _PyUnicode_AsKind(str1, rkind);
10313 if (!buf1) goto error;
10314 release1 = 1;
10315 }
10316 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10317 PyUnicode_GET_LENGTH(str1))); */
10318 product = n * (len2-len1);
10319 if ((product / (len2-len1)) != n) {
10320 PyErr_SetString(PyExc_OverflowError,
10321 "replace string is too long");
10322 goto error;
10323 }
10324 new_size = slen + product;
Victor Stinner49a0a212011-10-12 23:46:10 +020010325 if (new_size == 0) {
10326 Py_INCREF(unicode_empty);
10327 u = unicode_empty;
10328 goto done;
10329 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010330 if (new_size < 0 || new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
10331 PyErr_SetString(PyExc_OverflowError,
10332 "replace string is too long");
10333 goto error;
10334 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010335 u = PyUnicode_New(new_size, maxchar);
10336 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010337 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010338 assert(PyUnicode_KIND(u) == rkind);
10339 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010340 ires = i = 0;
10341 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010342 while (n-- > 0) {
10343 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010344 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010345 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010346 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010347 if (j == -1)
10348 break;
10349 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010350 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010351 memcpy(res + rkind * ires,
10352 sbuf + rkind * i,
10353 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010354 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010355 }
10356 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010357 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010358 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010359 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010360 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010361 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010362 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010363 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010364 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010365 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010366 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010367 memcpy(res + rkind * ires,
10368 sbuf + rkind * i,
10369 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010370 }
10371 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010372 /* interleave */
10373 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010374 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010375 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010376 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010377 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010378 if (--n <= 0)
10379 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010380 memcpy(res + rkind * ires,
10381 sbuf + rkind * i,
10382 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010383 ires++;
10384 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010385 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010386 memcpy(res + rkind * ires,
10387 sbuf + rkind * i,
10388 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010389 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010390 }
10391
10392 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010393 unicode_adjust_maxchar(&u);
10394 if (u == NULL)
10395 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010396 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010397
10398 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010399 if (srelease)
10400 PyMem_FREE(sbuf);
10401 if (release1)
10402 PyMem_FREE(buf1);
10403 if (release2)
10404 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010405 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010406 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010407
Benjamin Peterson29060642009-01-31 22:14:21 +000010408 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010409 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010410 if (srelease)
10411 PyMem_FREE(sbuf);
10412 if (release1)
10413 PyMem_FREE(buf1);
10414 if (release2)
10415 PyMem_FREE(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010416 if (PyUnicode_CheckExact(self)) {
10417 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010010418 return self;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010419 }
Victor Stinner034f6cf2011-09-30 02:26:44 +020010420 return PyUnicode_Copy(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010421 error:
10422 if (srelease && sbuf)
10423 PyMem_FREE(sbuf);
10424 if (release1 && buf1)
10425 PyMem_FREE(buf1);
10426 if (release2 && buf2)
10427 PyMem_FREE(buf2);
10428 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010429}
10430
10431/* --- Unicode Object Methods --------------------------------------------- */
10432
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010433PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010434 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010435\n\
10436Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010437characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010438
10439static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010440unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010441{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010442 return fixup(self, fixtitle);
10443}
10444
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010445PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010446 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010447\n\
10448Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010449have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010450
10451static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010452unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010453{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010454 return fixup(self, fixcapitalize);
10455}
10456
10457#if 0
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010458PyDoc_STRVAR(capwords__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010459 "S.capwords() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010460\n\
10461Apply .capitalize() to all words in S and return the result with\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010462normalized whitespace (all whitespace strings are replaced by ' ').");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010463
10464static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010465unicode_capwords(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010466{
10467 PyObject *list;
10468 PyObject *item;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010469 Py_ssize_t i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010470
Guido van Rossumd57fd912000-03-10 22:53:23 +000010471 /* Split into words */
10472 list = split(self, NULL, -1);
10473 if (!list)
10474 return NULL;
10475
10476 /* Capitalize each word */
10477 for (i = 0; i < PyList_GET_SIZE(list); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010478 item = fixup(PyList_GET_ITEM(list, i),
Benjamin Peterson29060642009-01-31 22:14:21 +000010479 fixcapitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010480 if (item == NULL)
10481 goto onError;
10482 Py_DECREF(PyList_GET_ITEM(list, i));
10483 PyList_SET_ITEM(list, i, item);
10484 }
10485
10486 /* Join the words to form a new string */
10487 item = PyUnicode_Join(NULL, list);
10488
Benjamin Peterson29060642009-01-31 22:14:21 +000010489 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010490 Py_DECREF(list);
Victor Stinner7931d9a2011-11-04 00:22:48 +010010491 return item;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010492}
10493#endif
10494
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010495/* Argument converter. Coerces to a single unicode character */
10496
10497static int
10498convert_uc(PyObject *obj, void *addr)
10499{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010500 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010501 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010502
Benjamin Peterson14339b62009-01-31 16:36:08 +000010503 uniobj = PyUnicode_FromObject(obj);
10504 if (uniobj == NULL) {
10505 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010506 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010507 return 0;
10508 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010509 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010510 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010511 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010512 Py_DECREF(uniobj);
10513 return 0;
10514 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010515 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010516 Py_DECREF(uniobj);
10517 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010518}
10519
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010520PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010521 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010522\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010523Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010524done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010525
10526static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010527unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010528{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010529 Py_ssize_t marg, left;
10530 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010531 Py_UCS4 fillchar = ' ';
10532
Victor Stinnere9a29352011-10-01 02:14:59 +020010533 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010534 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010535
Victor Stinnere9a29352011-10-01 02:14:59 +020010536 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010537 return NULL;
10538
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010539 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000010540 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010010541 return self;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010542 }
10543
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010544 marg = width - _PyUnicode_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010545 left = marg / 2 + (marg & width & 1);
10546
Victor Stinner9310abb2011-10-05 00:59:23 +020010547 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010548}
10549
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010550/* This function assumes that str1 and str2 are readied by the caller. */
10551
Marc-André Lemburge5034372000-08-08 08:04:29 +000010552static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010553unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010554{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010555 int kind1, kind2;
10556 void *data1, *data2;
10557 Py_ssize_t len1, len2, i;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010558
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010559 kind1 = PyUnicode_KIND(str1);
10560 kind2 = PyUnicode_KIND(str2);
10561 data1 = PyUnicode_DATA(str1);
10562 data2 = PyUnicode_DATA(str2);
10563 len1 = PyUnicode_GET_LENGTH(str1);
10564 len2 = PyUnicode_GET_LENGTH(str2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010565
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010566 for (i = 0; i < len1 && i < len2; ++i) {
10567 Py_UCS4 c1, c2;
10568 c1 = PyUnicode_READ(kind1, data1, i);
10569 c2 = PyUnicode_READ(kind2, data2, i);
Fredrik Lundh45714e92001-06-26 16:39:36 +000010570
10571 if (c1 != c2)
10572 return (c1 < c2) ? -1 : 1;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010573 }
10574
10575 return (len1 < len2) ? -1 : (len1 != len2);
10576}
10577
Alexander Belopolsky40018472011-02-26 01:02:56 +000010578int
10579PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010580{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010581 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10582 if (PyUnicode_READY(left) == -1 ||
10583 PyUnicode_READY(right) == -1)
10584 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010585 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010586 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010587 PyErr_Format(PyExc_TypeError,
10588 "Can't compare %.100s and %.100s",
10589 left->ob_type->tp_name,
10590 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010591 return -1;
10592}
10593
Martin v. Löwis5b222132007-06-10 09:51:05 +000010594int
10595PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10596{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010597 Py_ssize_t i;
10598 int kind;
10599 void *data;
10600 Py_UCS4 chr;
10601
Victor Stinner910337b2011-10-03 03:20:16 +020010602 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010603 if (PyUnicode_READY(uni) == -1)
10604 return -1;
10605 kind = PyUnicode_KIND(uni);
10606 data = PyUnicode_DATA(uni);
Martin v. Löwis5b222132007-06-10 09:51:05 +000010607 /* Compare Unicode string and source character set string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010608 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
10609 if (chr != str[i])
10610 return (chr < (unsigned char)(str[i])) ? -1 : 1;
Benjamin Peterson8667a9b2010-01-09 21:45:28 +000010611 /* This check keeps Python strings that end in '\0' from comparing equal
10612 to C strings identical up to that point. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010613 if (PyUnicode_GET_LENGTH(uni) != i || chr)
Benjamin Peterson29060642009-01-31 22:14:21 +000010614 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010615 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +000010616 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010617 return 0;
10618}
10619
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010620
Benjamin Peterson29060642009-01-31 22:14:21 +000010621#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010622 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010623
Alexander Belopolsky40018472011-02-26 01:02:56 +000010624PyObject *
10625PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010626{
10627 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010628
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010629 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10630 PyObject *v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010631 if (PyUnicode_READY(left) == -1 ||
10632 PyUnicode_READY(right) == -1)
10633 return NULL;
10634 if (PyUnicode_GET_LENGTH(left) != PyUnicode_GET_LENGTH(right) ||
10635 PyUnicode_KIND(left) != PyUnicode_KIND(right)) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010636 if (op == Py_EQ) {
10637 Py_INCREF(Py_False);
10638 return Py_False;
10639 }
10640 if (op == Py_NE) {
10641 Py_INCREF(Py_True);
10642 return Py_True;
10643 }
10644 }
10645 if (left == right)
10646 result = 0;
10647 else
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010648 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010649
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010650 /* Convert the return value to a Boolean */
10651 switch (op) {
10652 case Py_EQ:
10653 v = TEST_COND(result == 0);
10654 break;
10655 case Py_NE:
10656 v = TEST_COND(result != 0);
10657 break;
10658 case Py_LE:
10659 v = TEST_COND(result <= 0);
10660 break;
10661 case Py_GE:
10662 v = TEST_COND(result >= 0);
10663 break;
10664 case Py_LT:
10665 v = TEST_COND(result == -1);
10666 break;
10667 case Py_GT:
10668 v = TEST_COND(result == 1);
10669 break;
10670 default:
10671 PyErr_BadArgument();
10672 return NULL;
10673 }
10674 Py_INCREF(v);
10675 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010676 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010677
Brian Curtindfc80e32011-08-10 20:28:54 -050010678 Py_RETURN_NOTIMPLEMENTED;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010679}
10680
Alexander Belopolsky40018472011-02-26 01:02:56 +000010681int
10682PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010683{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010684 PyObject *str, *sub;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010685 int kind1, kind2, kind;
10686 void *buf1, *buf2;
10687 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010688 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010689
10690 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010691 sub = PyUnicode_FromObject(element);
10692 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010693 PyErr_Format(PyExc_TypeError,
10694 "'in <string>' requires string as left operand, not %s",
10695 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010696 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010697 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010698 if (PyUnicode_READY(sub) == -1)
10699 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010700
Thomas Wouters477c8d52006-05-27 19:21:47 +000010701 str = PyUnicode_FromObject(container);
Victor Stinnere9a29352011-10-01 02:14:59 +020010702 if (!str || PyUnicode_READY(str) == -1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010703 Py_DECREF(sub);
10704 return -1;
10705 }
10706
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010707 kind1 = PyUnicode_KIND(str);
10708 kind2 = PyUnicode_KIND(sub);
10709 kind = kind1 > kind2 ? kind1 : kind2;
10710 buf1 = PyUnicode_DATA(str);
10711 buf2 = PyUnicode_DATA(sub);
10712 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010713 buf1 = _PyUnicode_AsKind(str, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010714 if (!buf1) {
10715 Py_DECREF(sub);
10716 return -1;
10717 }
10718 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010719 buf2 = _PyUnicode_AsKind(sub, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010720 if (!buf2) {
10721 Py_DECREF(sub);
10722 if (kind1 != kind) PyMem_Free(buf1);
10723 return -1;
10724 }
10725 len1 = PyUnicode_GET_LENGTH(str);
10726 len2 = PyUnicode_GET_LENGTH(sub);
10727
10728 switch(kind) {
10729 case PyUnicode_1BYTE_KIND:
10730 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10731 break;
10732 case PyUnicode_2BYTE_KIND:
10733 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
10734 break;
10735 case PyUnicode_4BYTE_KIND:
10736 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
10737 break;
10738 default:
10739 result = -1;
10740 assert(0);
10741 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010742
10743 Py_DECREF(str);
10744 Py_DECREF(sub);
10745
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010746 if (kind1 != kind)
10747 PyMem_Free(buf1);
10748 if (kind2 != kind)
10749 PyMem_Free(buf2);
10750
Guido van Rossum403d68b2000-03-13 15:55:09 +000010751 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010752}
10753
Guido van Rossumd57fd912000-03-10 22:53:23 +000010754/* Concat to string or Unicode object giving a new Unicode object. */
10755
Alexander Belopolsky40018472011-02-26 01:02:56 +000010756PyObject *
10757PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010758{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010759 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020010760 Py_UCS4 maxchar, maxchar2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010761
10762 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010763 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010764 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010765 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010766 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010767 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010768 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010769
10770 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020010771 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010772 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010773 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010774 }
Victor Stinnera464fc12011-10-02 20:39:30 +020010775 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010776 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010777 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010778 }
10779
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010780 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020010781 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
10782 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010783
Guido van Rossumd57fd912000-03-10 22:53:23 +000010784 /* Concat the two Unicode strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010785 w = PyUnicode_New(
10786 PyUnicode_GET_LENGTH(u) + PyUnicode_GET_LENGTH(v),
10787 maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010788 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010789 goto onError;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010790 copy_characters(w, 0, u, 0, PyUnicode_GET_LENGTH(u));
10791 copy_characters(w, PyUnicode_GET_LENGTH(u), v, 0, PyUnicode_GET_LENGTH(v));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010792 Py_DECREF(u);
10793 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010794 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010795 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010796
Benjamin Peterson29060642009-01-31 22:14:21 +000010797 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010798 Py_XDECREF(u);
10799 Py_XDECREF(v);
10800 return NULL;
10801}
10802
Victor Stinnerb0923652011-10-04 01:17:31 +020010803static void
10804unicode_append_inplace(PyObject **p_left, PyObject *right)
10805{
10806 Py_ssize_t left_len, right_len, new_len;
Victor Stinnerb0923652011-10-04 01:17:31 +020010807
10808 assert(PyUnicode_IS_READY(*p_left));
10809 assert(PyUnicode_IS_READY(right));
10810
10811 left_len = PyUnicode_GET_LENGTH(*p_left);
10812 right_len = PyUnicode_GET_LENGTH(right);
10813 if (left_len > PY_SSIZE_T_MAX - right_len) {
10814 PyErr_SetString(PyExc_OverflowError,
10815 "strings are too large to concat");
10816 goto error;
10817 }
10818 new_len = left_len + right_len;
10819
10820 /* Now we own the last reference to 'left', so we can resize it
10821 * in-place.
10822 */
10823 if (unicode_resize(p_left, new_len) != 0) {
10824 /* XXX if _PyUnicode_Resize() fails, 'left' has been
10825 * deallocated so it cannot be put back into
10826 * 'variable'. The MemoryError is raised when there
10827 * is no value in 'variable', which might (very
10828 * remotely) be a cause of incompatibilities.
10829 */
10830 goto error;
10831 }
10832 /* copy 'right' into the newly allocated area of 'left' */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010833 copy_characters(*p_left, left_len, right, 0, right_len);
10834 _PyUnicode_DIRTY(*p_left);
Victor Stinnerb0923652011-10-04 01:17:31 +020010835 return;
10836
10837error:
10838 Py_DECREF(*p_left);
10839 *p_left = NULL;
10840}
10841
Walter Dörwald1ab83302007-05-18 17:15:44 +000010842void
Victor Stinner23e56682011-10-03 03:54:37 +020010843PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000010844{
Victor Stinner23e56682011-10-03 03:54:37 +020010845 PyObject *left, *res;
10846
10847 if (p_left == NULL) {
10848 if (!PyErr_Occurred())
10849 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000010850 return;
10851 }
Victor Stinner23e56682011-10-03 03:54:37 +020010852 left = *p_left;
10853 if (right == NULL || !PyUnicode_Check(left)) {
10854 if (!PyErr_Occurred())
10855 PyErr_BadInternalCall();
10856 goto error;
10857 }
10858
Victor Stinnere1335c72011-10-04 20:53:03 +020010859 if (PyUnicode_READY(left))
10860 goto error;
10861 if (PyUnicode_READY(right))
10862 goto error;
10863
Victor Stinner23e56682011-10-03 03:54:37 +020010864 if (PyUnicode_CheckExact(left) && left != unicode_empty
10865 && PyUnicode_CheckExact(right) && right != unicode_empty
10866 && unicode_resizable(left)
10867 && (_PyUnicode_KIND(right) <= _PyUnicode_KIND(left)
10868 || _PyUnicode_WSTR(left) != NULL))
10869 {
Victor Stinnerb0923652011-10-04 01:17:31 +020010870 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
10871 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020010872 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020010873 not so different than duplicating the string. */
10874 if (!(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
Victor Stinner23e56682011-10-03 03:54:37 +020010875 {
Victor Stinnerb0923652011-10-04 01:17:31 +020010876 unicode_append_inplace(p_left, right);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010877 if (p_left != NULL)
10878 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020010879 return;
10880 }
10881 }
10882
10883 res = PyUnicode_Concat(left, right);
10884 if (res == NULL)
10885 goto error;
10886 Py_DECREF(left);
10887 *p_left = res;
10888 return;
10889
10890error:
10891 Py_DECREF(*p_left);
10892 *p_left = NULL;
Walter Dörwald1ab83302007-05-18 17:15:44 +000010893}
10894
10895void
10896PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
10897{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010898 PyUnicode_Append(pleft, right);
10899 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010900}
10901
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010902PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010903 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010904\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000010905Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010906string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010907interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010908
10909static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010910unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010911{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010912 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010913 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010914 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010915 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010916 int kind1, kind2, kind;
10917 void *buf1, *buf2;
10918 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010919
Jesus Ceaac451502011-04-20 17:09:23 +020010920 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
10921 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000010922 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000010923
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010924 kind1 = PyUnicode_KIND(self);
10925 kind2 = PyUnicode_KIND(substring);
10926 kind = kind1 > kind2 ? kind1 : kind2;
10927 buf1 = PyUnicode_DATA(self);
10928 buf2 = PyUnicode_DATA(substring);
10929 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010930 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010931 if (!buf1) {
10932 Py_DECREF(substring);
10933 return NULL;
10934 }
10935 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010936 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010937 if (!buf2) {
10938 Py_DECREF(substring);
10939 if (kind1 != kind) PyMem_Free(buf1);
10940 return NULL;
10941 }
10942 len1 = PyUnicode_GET_LENGTH(self);
10943 len2 = PyUnicode_GET_LENGTH(substring);
10944
10945 ADJUST_INDICES(start, end, len1);
10946 switch(kind) {
10947 case PyUnicode_1BYTE_KIND:
10948 iresult = ucs1lib_count(
10949 ((Py_UCS1*)buf1) + start, end - start,
10950 buf2, len2, PY_SSIZE_T_MAX
10951 );
10952 break;
10953 case PyUnicode_2BYTE_KIND:
10954 iresult = ucs2lib_count(
10955 ((Py_UCS2*)buf1) + start, end - start,
10956 buf2, len2, PY_SSIZE_T_MAX
10957 );
10958 break;
10959 case PyUnicode_4BYTE_KIND:
10960 iresult = ucs4lib_count(
10961 ((Py_UCS4*)buf1) + start, end - start,
10962 buf2, len2, PY_SSIZE_T_MAX
10963 );
10964 break;
10965 default:
10966 assert(0); iresult = 0;
10967 }
10968
10969 result = PyLong_FromSsize_t(iresult);
10970
10971 if (kind1 != kind)
10972 PyMem_Free(buf1);
10973 if (kind2 != kind)
10974 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010975
10976 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010977
Guido van Rossumd57fd912000-03-10 22:53:23 +000010978 return result;
10979}
10980
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010981PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000010982 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010983\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000010984Encode S using the codec registered for encoding. Default encoding\n\
10985is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000010986handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000010987a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
10988'xmlcharrefreplace' as well as any other name registered with\n\
10989codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010990
10991static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010992unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010993{
Benjamin Peterson308d6372009-09-18 21:42:35 +000010994 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000010995 char *encoding = NULL;
10996 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000010997
Benjamin Peterson308d6372009-09-18 21:42:35 +000010998 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
10999 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011000 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011001 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000011002}
11003
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011004PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011005 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011006\n\
11007Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011008If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011009
11010static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011011unicode_expandtabs(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011012{
Antoine Pitroue71d5742011-10-04 15:55:09 +020011013 Py_ssize_t i, j, line_pos, src_len, incr;
11014 Py_UCS4 ch;
11015 PyObject *u;
11016 void *src_data, *dest_data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011017 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011018 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011019 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011020
11021 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000011022 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011023
Antoine Pitrou22425222011-10-04 19:10:51 +020011024 if (PyUnicode_READY(self) == -1)
11025 return NULL;
11026
Thomas Wouters7e474022000-07-16 12:04:32 +000011027 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011028 src_len = PyUnicode_GET_LENGTH(self);
11029 i = j = line_pos = 0;
11030 kind = PyUnicode_KIND(self);
11031 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020011032 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011033 for (; i < src_len; i++) {
11034 ch = PyUnicode_READ(kind, src_data, i);
11035 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020011036 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000011037 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011038 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000011039 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011040 goto overflow;
11041 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011042 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011043 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011044 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011045 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011046 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011047 goto overflow;
11048 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011049 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011050 if (ch == '\n' || ch == '\r')
11051 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011052 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011053 }
Antoine Pitroue19aa382011-10-04 16:04:01 +020011054 if (!found && PyUnicode_CheckExact(self)) {
Victor Stinner7931d9a2011-11-04 00:22:48 +010011055 Py_INCREF(self);
11056 return self;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011057 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011058
Guido van Rossumd57fd912000-03-10 22:53:23 +000011059 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011060 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011061 if (!u)
11062 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011063 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011064
Antoine Pitroue71d5742011-10-04 15:55:09 +020011065 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011066
Antoine Pitroue71d5742011-10-04 15:55:09 +020011067 for (; i < src_len; i++) {
11068 ch = PyUnicode_READ(kind, src_data, i);
11069 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011070 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011071 incr = tabsize - (line_pos % tabsize);
11072 line_pos += incr;
11073 while (incr--) {
11074 PyUnicode_WRITE(kind, dest_data, j, ' ');
11075 j++;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011076 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011077 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011078 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011079 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011080 line_pos++;
11081 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011082 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011083 if (ch == '\n' || ch == '\r')
11084 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011085 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011086 }
11087 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinner17efeed2011-10-04 20:05:46 +020011088#ifndef DONT_MAKE_RESULT_READY
11089 if (_PyUnicode_READY_REPLACE(&u)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011090 Py_DECREF(u);
11091 return NULL;
11092 }
Victor Stinner17efeed2011-10-04 20:05:46 +020011093#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011094 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010011095 return u;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011096
Antoine Pitroue71d5742011-10-04 15:55:09 +020011097 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011098 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11099 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011100}
11101
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011102PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011103 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011104\n\
11105Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011106such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011107arguments start and end are interpreted as in slice notation.\n\
11108\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011109Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011110
11111static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011112unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011113{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011114 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011115 Py_ssize_t start;
11116 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011117 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011118
Jesus Ceaac451502011-04-20 17:09:23 +020011119 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
11120 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011121 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011122
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011123 if (PyUnicode_READY(self) == -1)
11124 return NULL;
11125 if (PyUnicode_READY(substring) == -1)
11126 return NULL;
11127
Victor Stinner7931d9a2011-11-04 00:22:48 +010011128 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011129
11130 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011131
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011132 if (result == -2)
11133 return NULL;
11134
Christian Heimes217cfd12007-12-02 14:31:20 +000011135 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011136}
11137
11138static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011139unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011140{
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011141 Py_UCS4 ch = PyUnicode_ReadChar(self, index);
11142 if (ch == (Py_UCS4)-1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011143 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011144 return PyUnicode_FromOrdinal(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011145}
11146
Guido van Rossumc2504932007-09-18 19:42:40 +000011147/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011148 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011149static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011150unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011151{
Guido van Rossumc2504932007-09-18 19:42:40 +000011152 Py_ssize_t len;
Mark Dickinson57e683e2011-09-24 18:18:40 +010011153 Py_uhash_t x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011154
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011155 if (_PyUnicode_HASH(self) != -1)
11156 return _PyUnicode_HASH(self);
11157 if (PyUnicode_READY(self) == -1)
11158 return -1;
11159 len = PyUnicode_GET_LENGTH(self);
11160
11161 /* The hash function as a macro, gets expanded three times below. */
11162#define HASH(P) \
11163 x = (Py_uhash_t)*P << 7; \
11164 while (--len >= 0) \
11165 x = (1000003*x) ^ (Py_uhash_t)*P++;
11166
11167 switch (PyUnicode_KIND(self)) {
11168 case PyUnicode_1BYTE_KIND: {
11169 const unsigned char *c = PyUnicode_1BYTE_DATA(self);
11170 HASH(c);
11171 break;
11172 }
11173 case PyUnicode_2BYTE_KIND: {
11174 const Py_UCS2 *s = PyUnicode_2BYTE_DATA(self);
11175 HASH(s);
11176 break;
11177 }
11178 default: {
11179 Py_UCS4 *l;
11180 assert(PyUnicode_KIND(self) == PyUnicode_4BYTE_KIND &&
11181 "Impossible switch case in unicode_hash");
11182 l = PyUnicode_4BYTE_DATA(self);
11183 HASH(l);
11184 break;
11185 }
11186 }
11187 x ^= (Py_uhash_t)PyUnicode_GET_LENGTH(self);
11188
Guido van Rossumc2504932007-09-18 19:42:40 +000011189 if (x == -1)
11190 x = -2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011191 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011192 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011193}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011194#undef HASH
Guido van Rossumd57fd912000-03-10 22:53:23 +000011195
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011196PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011197 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011198\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011199Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011200
11201static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011202unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011203{
Martin v. Löwis18e16552006-02-15 17:27:45 +000011204 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011205 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011206 Py_ssize_t start;
11207 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011208
Jesus Ceaac451502011-04-20 17:09:23 +020011209 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
11210 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011211 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011212
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011213 if (PyUnicode_READY(self) == -1)
11214 return NULL;
11215 if (PyUnicode_READY(substring) == -1)
11216 return NULL;
11217
Victor Stinner7931d9a2011-11-04 00:22:48 +010011218 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011219
11220 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011221
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011222 if (result == -2)
11223 return NULL;
11224
Guido van Rossumd57fd912000-03-10 22:53:23 +000011225 if (result < 0) {
11226 PyErr_SetString(PyExc_ValueError, "substring not found");
11227 return NULL;
11228 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011229
Christian Heimes217cfd12007-12-02 14:31:20 +000011230 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011231}
11232
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011233PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011234 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011235\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011236Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011237at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011238
11239static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011240unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011241{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011242 Py_ssize_t i, length;
11243 int kind;
11244 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011245 int cased;
11246
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011247 if (PyUnicode_READY(self) == -1)
11248 return NULL;
11249 length = PyUnicode_GET_LENGTH(self);
11250 kind = PyUnicode_KIND(self);
11251 data = PyUnicode_DATA(self);
11252
Guido van Rossumd57fd912000-03-10 22:53:23 +000011253 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011254 if (length == 1)
11255 return PyBool_FromLong(
11256 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011257
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011258 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011259 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011260 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011261
Guido van Rossumd57fd912000-03-10 22:53:23 +000011262 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011263 for (i = 0; i < length; i++) {
11264 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011265
Benjamin Peterson29060642009-01-31 22:14:21 +000011266 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11267 return PyBool_FromLong(0);
11268 else if (!cased && Py_UNICODE_ISLOWER(ch))
11269 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011270 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011271 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011272}
11273
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011274PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011275 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011276\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011277Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011278at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011279
11280static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011281unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011282{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011283 Py_ssize_t i, length;
11284 int kind;
11285 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011286 int cased;
11287
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011288 if (PyUnicode_READY(self) == -1)
11289 return NULL;
11290 length = PyUnicode_GET_LENGTH(self);
11291 kind = PyUnicode_KIND(self);
11292 data = PyUnicode_DATA(self);
11293
Guido van Rossumd57fd912000-03-10 22:53:23 +000011294 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011295 if (length == 1)
11296 return PyBool_FromLong(
11297 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011298
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011299 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011300 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011301 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011302
Guido van Rossumd57fd912000-03-10 22:53:23 +000011303 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011304 for (i = 0; i < length; i++) {
11305 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011306
Benjamin Peterson29060642009-01-31 22:14:21 +000011307 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11308 return PyBool_FromLong(0);
11309 else if (!cased && Py_UNICODE_ISUPPER(ch))
11310 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011311 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011312 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011313}
11314
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011315PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011316 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011317\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011318Return True if S is a titlecased string and there is at least one\n\
11319character in S, i.e. upper- and titlecase characters may only\n\
11320follow uncased characters and lowercase characters only cased ones.\n\
11321Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011322
11323static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011324unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011325{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011326 Py_ssize_t i, length;
11327 int kind;
11328 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011329 int cased, previous_is_cased;
11330
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011331 if (PyUnicode_READY(self) == -1)
11332 return NULL;
11333 length = PyUnicode_GET_LENGTH(self);
11334 kind = PyUnicode_KIND(self);
11335 data = PyUnicode_DATA(self);
11336
Guido van Rossumd57fd912000-03-10 22:53:23 +000011337 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011338 if (length == 1) {
11339 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11340 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11341 (Py_UNICODE_ISUPPER(ch) != 0));
11342 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011343
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011344 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011345 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011346 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011347
Guido van Rossumd57fd912000-03-10 22:53:23 +000011348 cased = 0;
11349 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011350 for (i = 0; i < length; i++) {
11351 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011352
Benjamin Peterson29060642009-01-31 22:14:21 +000011353 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11354 if (previous_is_cased)
11355 return PyBool_FromLong(0);
11356 previous_is_cased = 1;
11357 cased = 1;
11358 }
11359 else if (Py_UNICODE_ISLOWER(ch)) {
11360 if (!previous_is_cased)
11361 return PyBool_FromLong(0);
11362 previous_is_cased = 1;
11363 cased = 1;
11364 }
11365 else
11366 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011367 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011368 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011369}
11370
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011371PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011372 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011373\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011374Return True if all characters in S are whitespace\n\
11375and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011376
11377static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011378unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011379{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011380 Py_ssize_t i, length;
11381 int kind;
11382 void *data;
11383
11384 if (PyUnicode_READY(self) == -1)
11385 return NULL;
11386 length = PyUnicode_GET_LENGTH(self);
11387 kind = PyUnicode_KIND(self);
11388 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011389
Guido van Rossumd57fd912000-03-10 22:53:23 +000011390 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011391 if (length == 1)
11392 return PyBool_FromLong(
11393 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011394
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011395 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011396 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011397 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011398
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011399 for (i = 0; i < length; i++) {
11400 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011401 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011402 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011403 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011404 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011405}
11406
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011407PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011408 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011409\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011410Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011411and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011412
11413static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011414unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011415{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011416 Py_ssize_t i, length;
11417 int kind;
11418 void *data;
11419
11420 if (PyUnicode_READY(self) == -1)
11421 return NULL;
11422 length = PyUnicode_GET_LENGTH(self);
11423 kind = PyUnicode_KIND(self);
11424 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011425
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011426 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011427 if (length == 1)
11428 return PyBool_FromLong(
11429 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011430
11431 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011432 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011433 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011434
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011435 for (i = 0; i < length; i++) {
11436 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011437 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011438 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011439 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011440}
11441
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011442PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011443 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011444\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011445Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011446and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011447
11448static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011449unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011450{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011451 int kind;
11452 void *data;
11453 Py_ssize_t len, i;
11454
11455 if (PyUnicode_READY(self) == -1)
11456 return NULL;
11457
11458 kind = PyUnicode_KIND(self);
11459 data = PyUnicode_DATA(self);
11460 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011461
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011462 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011463 if (len == 1) {
11464 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11465 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11466 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011467
11468 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011469 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011470 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011471
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011472 for (i = 0; i < len; i++) {
11473 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011474 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011475 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011476 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011477 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011478}
11479
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011480PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011481 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011482\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011483Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011484False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011485
11486static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011487unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011488{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011489 Py_ssize_t i, length;
11490 int kind;
11491 void *data;
11492
11493 if (PyUnicode_READY(self) == -1)
11494 return NULL;
11495 length = PyUnicode_GET_LENGTH(self);
11496 kind = PyUnicode_KIND(self);
11497 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011498
Guido van Rossumd57fd912000-03-10 22:53:23 +000011499 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011500 if (length == 1)
11501 return PyBool_FromLong(
11502 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011503
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011504 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011505 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011506 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011507
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011508 for (i = 0; i < length; i++) {
11509 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011510 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011511 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011512 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011513}
11514
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011515PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011516 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011517\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011518Return True if all characters in S are digits\n\
11519and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011520
11521static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011522unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011523{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011524 Py_ssize_t i, length;
11525 int kind;
11526 void *data;
11527
11528 if (PyUnicode_READY(self) == -1)
11529 return NULL;
11530 length = PyUnicode_GET_LENGTH(self);
11531 kind = PyUnicode_KIND(self);
11532 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011533
Guido van Rossumd57fd912000-03-10 22:53:23 +000011534 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011535 if (length == 1) {
11536 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11537 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11538 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011539
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011540 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011541 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011542 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011543
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011544 for (i = 0; i < length; i++) {
11545 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011546 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011547 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011548 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011549}
11550
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011551PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011552 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011553\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011554Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011555False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011556
11557static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011558unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011559{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011560 Py_ssize_t i, length;
11561 int kind;
11562 void *data;
11563
11564 if (PyUnicode_READY(self) == -1)
11565 return NULL;
11566 length = PyUnicode_GET_LENGTH(self);
11567 kind = PyUnicode_KIND(self);
11568 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011569
Guido van Rossumd57fd912000-03-10 22:53:23 +000011570 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011571 if (length == 1)
11572 return PyBool_FromLong(
11573 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011574
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011575 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011576 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011577 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011578
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011579 for (i = 0; i < length; i++) {
11580 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011581 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011582 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011583 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011584}
11585
Martin v. Löwis47383402007-08-15 07:32:56 +000011586int
11587PyUnicode_IsIdentifier(PyObject *self)
11588{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011589 int kind;
11590 void *data;
11591 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011592 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011593
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011594 if (PyUnicode_READY(self) == -1) {
11595 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011596 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011597 }
11598
11599 /* Special case for empty strings */
11600 if (PyUnicode_GET_LENGTH(self) == 0)
11601 return 0;
11602 kind = PyUnicode_KIND(self);
11603 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011604
11605 /* PEP 3131 says that the first character must be in
11606 XID_Start and subsequent characters in XID_Continue,
11607 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011608 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011609 letters, digits, underscore). However, given the current
11610 definition of XID_Start and XID_Continue, it is sufficient
11611 to check just for these, except that _ must be allowed
11612 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011613 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011614 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011615 return 0;
11616
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011617 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011618 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011619 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011620 return 1;
11621}
11622
11623PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011624 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011625\n\
11626Return True if S is a valid identifier according\n\
11627to the language definition.");
11628
11629static PyObject*
11630unicode_isidentifier(PyObject *self)
11631{
11632 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11633}
11634
Georg Brandl559e5d72008-06-11 18:37:52 +000011635PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011636 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011637\n\
11638Return True if all characters in S are considered\n\
11639printable in repr() or S is empty, False otherwise.");
11640
11641static PyObject*
11642unicode_isprintable(PyObject *self)
11643{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011644 Py_ssize_t i, length;
11645 int kind;
11646 void *data;
11647
11648 if (PyUnicode_READY(self) == -1)
11649 return NULL;
11650 length = PyUnicode_GET_LENGTH(self);
11651 kind = PyUnicode_KIND(self);
11652 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011653
11654 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011655 if (length == 1)
11656 return PyBool_FromLong(
11657 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011658
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011659 for (i = 0; i < length; i++) {
11660 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011661 Py_RETURN_FALSE;
11662 }
11663 }
11664 Py_RETURN_TRUE;
11665}
11666
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011667PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011668 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011669\n\
11670Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011671iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011672
11673static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011674unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011675{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011676 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011677}
11678
Martin v. Löwis18e16552006-02-15 17:27:45 +000011679static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011680unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011681{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011682 if (PyUnicode_READY(self) == -1)
11683 return -1;
11684 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011685}
11686
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011687PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011688 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011689\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011690Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011691done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011692
11693static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011694unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011695{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011696 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011697 Py_UCS4 fillchar = ' ';
11698
11699 if (PyUnicode_READY(self) == -1)
11700 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011701
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011702 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011703 return NULL;
11704
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011705 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000011706 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010011707 return self;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011708 }
11709
Victor Stinner7931d9a2011-11-04 00:22:48 +010011710 return pad(self, 0, width - _PyUnicode_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011711}
11712
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011713PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011714 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011715\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011716Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011717
11718static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011719unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011720{
Guido van Rossumd57fd912000-03-10 22:53:23 +000011721 return fixup(self, fixlower);
11722}
11723
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011724#define LEFTSTRIP 0
11725#define RIGHTSTRIP 1
11726#define BOTHSTRIP 2
11727
11728/* Arrays indexed by above */
11729static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11730
11731#define STRIPNAME(i) (stripformat[i]+3)
11732
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011733/* externally visible for str.strip(unicode) */
11734PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011735_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011736{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011737 void *data;
11738 int kind;
11739 Py_ssize_t i, j, len;
11740 BLOOM_MASK sepmask;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011741
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011742 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
11743 return NULL;
11744
11745 kind = PyUnicode_KIND(self);
11746 data = PyUnicode_DATA(self);
11747 len = PyUnicode_GET_LENGTH(self);
11748 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
11749 PyUnicode_DATA(sepobj),
11750 PyUnicode_GET_LENGTH(sepobj));
Thomas Wouters477c8d52006-05-27 19:21:47 +000011751
Benjamin Peterson14339b62009-01-31 16:36:08 +000011752 i = 0;
11753 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011754 while (i < len &&
11755 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, i), sepobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011756 i++;
11757 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011758 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011759
Benjamin Peterson14339b62009-01-31 16:36:08 +000011760 j = len;
11761 if (striptype != LEFTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011762 do {
11763 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011764 } while (j >= i &&
11765 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, j), sepobj));
Benjamin Peterson29060642009-01-31 22:14:21 +000011766 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011767 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011768
Victor Stinner7931d9a2011-11-04 00:22:48 +010011769 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011770}
11771
11772PyObject*
11773PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
11774{
11775 unsigned char *data;
11776 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020011777 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011778
Victor Stinnerde636f32011-10-01 03:55:54 +020011779 if (PyUnicode_READY(self) == -1)
11780 return NULL;
11781
11782 end = Py_MIN(end, PyUnicode_GET_LENGTH(self));
11783
Victor Stinner12bab6d2011-10-01 01:53:49 +020011784 if (start == 0 && end == PyUnicode_GET_LENGTH(self))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011785 {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011786 if (PyUnicode_CheckExact(self)) {
11787 Py_INCREF(self);
11788 return self;
11789 }
11790 else
11791 return PyUnicode_Copy(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011792 }
11793
Victor Stinner12bab6d2011-10-01 01:53:49 +020011794 length = end - start;
11795 if (length == 1)
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011796 return unicode_getitem(self, start);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011797
Victor Stinnerde636f32011-10-01 03:55:54 +020011798 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011799 PyErr_SetString(PyExc_IndexError, "string index out of range");
11800 return NULL;
11801 }
11802
Victor Stinnerb9275c12011-10-05 14:01:42 +020011803 if (PyUnicode_IS_ASCII(self)) {
11804 kind = PyUnicode_KIND(self);
11805 data = PyUnicode_1BYTE_DATA(self);
11806 return unicode_fromascii(data + start, length);
11807 }
11808 else {
11809 kind = PyUnicode_KIND(self);
11810 data = PyUnicode_1BYTE_DATA(self);
11811 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011812 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020011813 length);
11814 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011815}
Guido van Rossumd57fd912000-03-10 22:53:23 +000011816
11817static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011818do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011819{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011820 int kind;
11821 void *data;
11822 Py_ssize_t len, i, j;
11823
11824 if (PyUnicode_READY(self) == -1)
11825 return NULL;
11826
11827 kind = PyUnicode_KIND(self);
11828 data = PyUnicode_DATA(self);
11829 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011830
Benjamin Peterson14339b62009-01-31 16:36:08 +000011831 i = 0;
11832 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011833 while (i < len && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, i))) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000011834 i++;
11835 }
11836 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011837
Benjamin Peterson14339b62009-01-31 16:36:08 +000011838 j = len;
11839 if (striptype != LEFTSTRIP) {
11840 do {
11841 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011842 } while (j >= i && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, j)));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011843 j++;
11844 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011845
Victor Stinner7931d9a2011-11-04 00:22:48 +010011846 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011847}
11848
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011849
11850static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011851do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011852{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011853 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011854
Benjamin Peterson14339b62009-01-31 16:36:08 +000011855 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
11856 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011857
Benjamin Peterson14339b62009-01-31 16:36:08 +000011858 if (sep != NULL && sep != Py_None) {
11859 if (PyUnicode_Check(sep))
11860 return _PyUnicode_XStrip(self, striptype, sep);
11861 else {
11862 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000011863 "%s arg must be None or str",
11864 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011865 return NULL;
11866 }
11867 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011868
Benjamin Peterson14339b62009-01-31 16:36:08 +000011869 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011870}
11871
11872
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011873PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011874 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011875\n\
11876Return a copy of the string S with leading and trailing\n\
11877whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011878If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011879
11880static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011881unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011882{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011883 if (PyTuple_GET_SIZE(args) == 0)
11884 return do_strip(self, BOTHSTRIP); /* Common case */
11885 else
11886 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011887}
11888
11889
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011890PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011891 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011892\n\
11893Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011894If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011895
11896static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011897unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011898{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011899 if (PyTuple_GET_SIZE(args) == 0)
11900 return do_strip(self, LEFTSTRIP); /* Common case */
11901 else
11902 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011903}
11904
11905
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011906PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011907 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011908\n\
11909Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011910If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011911
11912static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011913unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011914{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011915 if (PyTuple_GET_SIZE(args) == 0)
11916 return do_strip(self, RIGHTSTRIP); /* Common case */
11917 else
11918 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011919}
11920
11921
Guido van Rossumd57fd912000-03-10 22:53:23 +000011922static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011923unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011924{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011925 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011926 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011927
Georg Brandl222de0f2009-04-12 12:01:50 +000011928 if (len < 1) {
11929 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +020011930 return unicode_empty;
Georg Brandl222de0f2009-04-12 12:01:50 +000011931 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011932
Tim Peters7a29bd52001-09-12 03:03:31 +000011933 if (len == 1 && PyUnicode_CheckExact(str)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000011934 /* no repeat, return original string */
11935 Py_INCREF(str);
Victor Stinner7931d9a2011-11-04 00:22:48 +010011936 return str;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011937 }
Tim Peters8f422462000-09-09 06:13:41 +000011938
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011939 if (PyUnicode_READY(str) == -1)
11940 return NULL;
11941
Victor Stinnerc759f3e2011-10-01 03:09:58 +020011942 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020011943 PyErr_SetString(PyExc_OverflowError,
11944 "repeated string is too long");
11945 return NULL;
11946 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011947 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011948
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011949 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011950 if (!u)
11951 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011952 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011953
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011954 if (PyUnicode_GET_LENGTH(str) == 1) {
11955 const int kind = PyUnicode_KIND(str);
11956 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
11957 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011958 if (kind == PyUnicode_1BYTE_KIND)
11959 memset(to, (unsigned char)fill_char, len);
11960 else {
11961 for (n = 0; n < len; ++n)
11962 PyUnicode_WRITE(kind, to, n, fill_char);
11963 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011964 }
11965 else {
11966 /* number of characters copied this far */
11967 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011968 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011969 char *to = (char *) PyUnicode_DATA(u);
11970 Py_MEMCPY(to, PyUnicode_DATA(str),
11971 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000011972 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011973 n = (done <= nchars-done) ? done : nchars-done;
11974 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011975 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000011976 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011977 }
11978
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011979 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011980 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011981}
11982
Alexander Belopolsky40018472011-02-26 01:02:56 +000011983PyObject *
11984PyUnicode_Replace(PyObject *obj,
11985 PyObject *subobj,
11986 PyObject *replobj,
11987 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011988{
11989 PyObject *self;
11990 PyObject *str1;
11991 PyObject *str2;
11992 PyObject *result;
11993
11994 self = PyUnicode_FromObject(obj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011995 if (self == NULL || PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011996 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011997 str1 = PyUnicode_FromObject(subobj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011998 if (str1 == NULL || PyUnicode_READY(str1) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011999 Py_DECREF(self);
12000 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012001 }
12002 str2 = PyUnicode_FromObject(replobj);
Victor Stinnere9a29352011-10-01 02:14:59 +020012003 if (str2 == NULL || PyUnicode_READY(str2)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012004 Py_DECREF(self);
12005 Py_DECREF(str1);
12006 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012007 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012008 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012009 Py_DECREF(self);
12010 Py_DECREF(str1);
12011 Py_DECREF(str2);
12012 return result;
12013}
12014
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012015PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000012016 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012017\n\
12018Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000012019old replaced by new. If the optional argument count is\n\
12020given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012021
12022static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012023unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012024{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012025 PyObject *str1;
12026 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012027 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012028 PyObject *result;
12029
Martin v. Löwis18e16552006-02-15 17:27:45 +000012030 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012031 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012032 if (!PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012033 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012034 str1 = PyUnicode_FromObject(str1);
12035 if (str1 == NULL || PyUnicode_READY(str1) == -1)
12036 return NULL;
12037 str2 = PyUnicode_FromObject(str2);
Victor Stinnere9a29352011-10-01 02:14:59 +020012038 if (str2 == NULL || PyUnicode_READY(str2) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012039 Py_DECREF(str1);
12040 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000012041 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012042
12043 result = replace(self, str1, str2, maxcount);
12044
12045 Py_DECREF(str1);
12046 Py_DECREF(str2);
12047 return result;
12048}
12049
Alexander Belopolsky40018472011-02-26 01:02:56 +000012050static PyObject *
12051unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012052{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012053 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012054 Py_ssize_t isize;
12055 Py_ssize_t osize, squote, dquote, i, o;
12056 Py_UCS4 max, quote;
12057 int ikind, okind;
12058 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012059
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012060 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012061 return NULL;
12062
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012063 isize = PyUnicode_GET_LENGTH(unicode);
12064 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012065
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012066 /* Compute length of output, quote characters, and
12067 maximum character */
12068 osize = 2; /* quotes */
12069 max = 127;
12070 squote = dquote = 0;
12071 ikind = PyUnicode_KIND(unicode);
12072 for (i = 0; i < isize; i++) {
12073 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
12074 switch (ch) {
12075 case '\'': squote++; osize++; break;
12076 case '"': dquote++; osize++; break;
12077 case '\\': case '\t': case '\r': case '\n':
12078 osize += 2; break;
12079 default:
12080 /* Fast-path ASCII */
12081 if (ch < ' ' || ch == 0x7f)
12082 osize += 4; /* \xHH */
12083 else if (ch < 0x7f)
12084 osize++;
12085 else if (Py_UNICODE_ISPRINTABLE(ch)) {
12086 osize++;
12087 max = ch > max ? ch : max;
12088 }
12089 else if (ch < 0x100)
12090 osize += 4; /* \xHH */
12091 else if (ch < 0x10000)
12092 osize += 6; /* \uHHHH */
12093 else
12094 osize += 10; /* \uHHHHHHHH */
12095 }
12096 }
12097
12098 quote = '\'';
12099 if (squote) {
12100 if (dquote)
12101 /* Both squote and dquote present. Use squote,
12102 and escape them */
12103 osize += squote;
12104 else
12105 quote = '"';
12106 }
12107
12108 repr = PyUnicode_New(osize, max);
12109 if (repr == NULL)
12110 return NULL;
12111 okind = PyUnicode_KIND(repr);
12112 odata = PyUnicode_DATA(repr);
12113
12114 PyUnicode_WRITE(okind, odata, 0, quote);
12115 PyUnicode_WRITE(okind, odata, osize-1, quote);
12116
12117 for (i = 0, o = 1; i < isize; i++) {
12118 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012119
12120 /* Escape quotes and backslashes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012121 if ((ch == quote) || (ch == '\\')) {
12122 PyUnicode_WRITE(okind, odata, o++, '\\');
12123 PyUnicode_WRITE(okind, odata, o++, ch);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012124 continue;
12125 }
12126
Benjamin Peterson29060642009-01-31 22:14:21 +000012127 /* Map special whitespace to '\t', \n', '\r' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012128 if (ch == '\t') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012129 PyUnicode_WRITE(okind, odata, o++, '\\');
12130 PyUnicode_WRITE(okind, odata, o++, 't');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012131 }
12132 else if (ch == '\n') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012133 PyUnicode_WRITE(okind, odata, o++, '\\');
12134 PyUnicode_WRITE(okind, odata, o++, 'n');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012135 }
12136 else if (ch == '\r') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012137 PyUnicode_WRITE(okind, odata, o++, '\\');
12138 PyUnicode_WRITE(okind, odata, o++, 'r');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012139 }
12140
12141 /* Map non-printable US ASCII to '\xhh' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012142 else if (ch < ' ' || ch == 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012143 PyUnicode_WRITE(okind, odata, o++, '\\');
12144 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012145 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12146 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012147 }
12148
Georg Brandl559e5d72008-06-11 18:37:52 +000012149 /* Copy ASCII characters as-is */
12150 else if (ch < 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012151 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012152 }
12153
Benjamin Peterson29060642009-01-31 22:14:21 +000012154 /* Non-ASCII characters */
Georg Brandl559e5d72008-06-11 18:37:52 +000012155 else {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012156 /* Map Unicode whitespace and control characters
Georg Brandl559e5d72008-06-11 18:37:52 +000012157 (categories Z* and C* except ASCII space)
12158 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012159 if (!Py_UNICODE_ISPRINTABLE(ch)) {
Georg Brandl559e5d72008-06-11 18:37:52 +000012160 /* Map 8-bit characters to '\xhh' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012161 if (ch <= 0xff) {
12162 PyUnicode_WRITE(okind, odata, o++, '\\');
12163 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012164 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12165 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012166 }
12167 /* Map 21-bit characters to '\U00xxxxxx' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012168 else if (ch >= 0x10000) {
12169 PyUnicode_WRITE(okind, odata, o++, '\\');
12170 PyUnicode_WRITE(okind, odata, o++, 'U');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012171 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12172 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12173 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12174 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12175 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12176 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12177 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12178 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012179 }
12180 /* Map 16-bit characters to '\uxxxx' */
12181 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012182 PyUnicode_WRITE(okind, odata, o++, '\\');
12183 PyUnicode_WRITE(okind, odata, o++, 'u');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012184 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12185 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12186 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12187 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012188 }
12189 }
12190 /* Copy characters as-is */
12191 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012192 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012193 }
12194 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012195 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012196 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012197 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012198 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012199}
12200
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012201PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012202 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012203\n\
12204Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012205such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012206arguments start and end are interpreted as in slice notation.\n\
12207\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012208Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012209
12210static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012211unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012212{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012213 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012214 Py_ssize_t start;
12215 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012216 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012217
Jesus Ceaac451502011-04-20 17:09:23 +020012218 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
12219 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012220 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012221
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012222 if (PyUnicode_READY(self) == -1)
12223 return NULL;
12224 if (PyUnicode_READY(substring) == -1)
12225 return NULL;
12226
Victor Stinner7931d9a2011-11-04 00:22:48 +010012227 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012228
12229 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012230
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012231 if (result == -2)
12232 return NULL;
12233
Christian Heimes217cfd12007-12-02 14:31:20 +000012234 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012235}
12236
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012237PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012238 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012239\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012240Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012241
12242static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012243unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012244{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012245 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012246 Py_ssize_t start;
12247 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012248 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012249
Jesus Ceaac451502011-04-20 17:09:23 +020012250 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12251 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012252 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012253
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012254 if (PyUnicode_READY(self) == -1)
12255 return NULL;
12256 if (PyUnicode_READY(substring) == -1)
12257 return NULL;
12258
Victor Stinner7931d9a2011-11-04 00:22:48 +010012259 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012260
12261 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012262
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012263 if (result == -2)
12264 return NULL;
12265
Guido van Rossumd57fd912000-03-10 22:53:23 +000012266 if (result < 0) {
12267 PyErr_SetString(PyExc_ValueError, "substring not found");
12268 return NULL;
12269 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012270
Christian Heimes217cfd12007-12-02 14:31:20 +000012271 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012272}
12273
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012274PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012275 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012276\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012277Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012278done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012279
12280static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012281unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012282{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012283 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012284 Py_UCS4 fillchar = ' ';
12285
Victor Stinnere9a29352011-10-01 02:14:59 +020012286 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012287 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012288
Victor Stinnere9a29352011-10-01 02:14:59 +020012289 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012290 return NULL;
12291
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012292 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012293 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010012294 return self;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012295 }
12296
Victor Stinner7931d9a2011-11-04 00:22:48 +010012297 return pad(self, width - _PyUnicode_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012298}
12299
Alexander Belopolsky40018472011-02-26 01:02:56 +000012300PyObject *
12301PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012302{
12303 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012304
Guido van Rossumd57fd912000-03-10 22:53:23 +000012305 s = PyUnicode_FromObject(s);
12306 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012307 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012308 if (sep != NULL) {
12309 sep = PyUnicode_FromObject(sep);
12310 if (sep == NULL) {
12311 Py_DECREF(s);
12312 return NULL;
12313 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012314 }
12315
Victor Stinner9310abb2011-10-05 00:59:23 +020012316 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012317
12318 Py_DECREF(s);
12319 Py_XDECREF(sep);
12320 return result;
12321}
12322
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012323PyDoc_STRVAR(split__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012324 "S.split([sep[, maxsplit]]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012325\n\
12326Return a list of the words in S, using sep as the\n\
12327delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012328splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012329whitespace string is a separator and empty strings are\n\
12330removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012331
12332static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012333unicode_split(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012334{
12335 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012336 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012337
Martin v. Löwis18e16552006-02-15 17:27:45 +000012338 if (!PyArg_ParseTuple(args, "|On:split", &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012339 return NULL;
12340
12341 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012342 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012343 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012344 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012345 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012346 return PyUnicode_Split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012347}
12348
Thomas Wouters477c8d52006-05-27 19:21:47 +000012349PyObject *
12350PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12351{
12352 PyObject* str_obj;
12353 PyObject* sep_obj;
12354 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012355 int kind1, kind2, kind;
12356 void *buf1 = NULL, *buf2 = NULL;
12357 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012358
12359 str_obj = PyUnicode_FromObject(str_in);
Victor Stinnere9a29352011-10-01 02:14:59 +020012360 if (!str_obj || PyUnicode_READY(str_obj) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012361 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012362 sep_obj = PyUnicode_FromObject(sep_in);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012363 if (!sep_obj || PyUnicode_READY(sep_obj) == -1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000012364 Py_DECREF(str_obj);
12365 return NULL;
12366 }
12367
Victor Stinner14f8f022011-10-05 20:58:25 +020012368 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012369 kind2 = PyUnicode_KIND(sep_obj);
Victor Stinner14f8f022011-10-05 20:58:25 +020012370 kind = Py_MAX(kind1, kind2);
12371 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012372 if (kind1 != kind)
Victor Stinner14f8f022011-10-05 20:58:25 +020012373 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012374 if (!buf1)
12375 goto onError;
12376 buf2 = PyUnicode_DATA(sep_obj);
12377 if (kind2 != kind)
12378 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12379 if (!buf2)
12380 goto onError;
12381 len1 = PyUnicode_GET_LENGTH(str_obj);
12382 len2 = PyUnicode_GET_LENGTH(sep_obj);
12383
Victor Stinner14f8f022011-10-05 20:58:25 +020012384 switch(PyUnicode_KIND(str_obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012385 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012386 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12387 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12388 else
12389 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012390 break;
12391 case PyUnicode_2BYTE_KIND:
12392 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12393 break;
12394 case PyUnicode_4BYTE_KIND:
12395 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12396 break;
12397 default:
12398 assert(0);
12399 out = 0;
12400 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012401
12402 Py_DECREF(sep_obj);
12403 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012404 if (kind1 != kind)
12405 PyMem_Free(buf1);
12406 if (kind2 != kind)
12407 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012408
12409 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012410 onError:
12411 Py_DECREF(sep_obj);
12412 Py_DECREF(str_obj);
12413 if (kind1 != kind && buf1)
12414 PyMem_Free(buf1);
12415 if (kind2 != kind && buf2)
12416 PyMem_Free(buf2);
12417 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012418}
12419
12420
12421PyObject *
12422PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12423{
12424 PyObject* str_obj;
12425 PyObject* sep_obj;
12426 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012427 int kind1, kind2, kind;
12428 void *buf1 = NULL, *buf2 = NULL;
12429 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012430
12431 str_obj = PyUnicode_FromObject(str_in);
12432 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012433 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012434 sep_obj = PyUnicode_FromObject(sep_in);
12435 if (!sep_obj) {
12436 Py_DECREF(str_obj);
12437 return NULL;
12438 }
12439
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012440 kind1 = PyUnicode_KIND(str_in);
12441 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020012442 kind = Py_MAX(kind1, kind2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012443 buf1 = PyUnicode_DATA(str_in);
12444 if (kind1 != kind)
12445 buf1 = _PyUnicode_AsKind(str_in, kind);
12446 if (!buf1)
12447 goto onError;
12448 buf2 = PyUnicode_DATA(sep_obj);
12449 if (kind2 != kind)
12450 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12451 if (!buf2)
12452 goto onError;
12453 len1 = PyUnicode_GET_LENGTH(str_obj);
12454 len2 = PyUnicode_GET_LENGTH(sep_obj);
12455
12456 switch(PyUnicode_KIND(str_in)) {
12457 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012458 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12459 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12460 else
12461 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012462 break;
12463 case PyUnicode_2BYTE_KIND:
12464 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12465 break;
12466 case PyUnicode_4BYTE_KIND:
12467 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12468 break;
12469 default:
12470 assert(0);
12471 out = 0;
12472 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012473
12474 Py_DECREF(sep_obj);
12475 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012476 if (kind1 != kind)
12477 PyMem_Free(buf1);
12478 if (kind2 != kind)
12479 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012480
12481 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012482 onError:
12483 Py_DECREF(sep_obj);
12484 Py_DECREF(str_obj);
12485 if (kind1 != kind && buf1)
12486 PyMem_Free(buf1);
12487 if (kind2 != kind && buf2)
12488 PyMem_Free(buf2);
12489 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012490}
12491
12492PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012493 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012494\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012495Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012496the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012497found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012498
12499static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012500unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012501{
Victor Stinner9310abb2011-10-05 00:59:23 +020012502 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012503}
12504
12505PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012506 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012507\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012508Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012509the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012510separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012511
12512static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012513unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012514{
Victor Stinner9310abb2011-10-05 00:59:23 +020012515 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012516}
12517
Alexander Belopolsky40018472011-02-26 01:02:56 +000012518PyObject *
12519PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012520{
12521 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012522
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012523 s = PyUnicode_FromObject(s);
12524 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012525 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012526 if (sep != NULL) {
12527 sep = PyUnicode_FromObject(sep);
12528 if (sep == NULL) {
12529 Py_DECREF(s);
12530 return NULL;
12531 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012532 }
12533
Victor Stinner9310abb2011-10-05 00:59:23 +020012534 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012535
12536 Py_DECREF(s);
12537 Py_XDECREF(sep);
12538 return result;
12539}
12540
12541PyDoc_STRVAR(rsplit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012542 "S.rsplit([sep[, maxsplit]]) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012543\n\
12544Return a list of the words in S, using sep as the\n\
12545delimiter string, starting at the end of the string and\n\
12546working to the front. If maxsplit is given, at most maxsplit\n\
12547splits are done. If sep is not specified, any whitespace string\n\
12548is a separator.");
12549
12550static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012551unicode_rsplit(PyObject *self, PyObject *args)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012552{
12553 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012554 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012555
Martin v. Löwis18e16552006-02-15 17:27:45 +000012556 if (!PyArg_ParseTuple(args, "|On:rsplit", &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012557 return NULL;
12558
12559 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012560 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012561 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012562 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012563 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012564 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012565}
12566
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012567PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012568 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012569\n\
12570Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012571Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012572is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012573
12574static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012575unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012576{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012577 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012578 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012579
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012580 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12581 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012582 return NULL;
12583
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012584 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012585}
12586
12587static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012588PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012589{
Walter Dörwald346737f2007-05-31 10:44:43 +000012590 if (PyUnicode_CheckExact(self)) {
12591 Py_INCREF(self);
12592 return self;
12593 } else
12594 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinner034f6cf2011-09-30 02:26:44 +020012595 return PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012596}
12597
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012598PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012599 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012600\n\
12601Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012602and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012603
12604static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012605unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012606{
Guido van Rossumd57fd912000-03-10 22:53:23 +000012607 return fixup(self, fixswapcase);
12608}
12609
Georg Brandlceee0772007-11-27 23:48:05 +000012610PyDoc_STRVAR(maketrans__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012611 "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012612\n\
12613Return a translation table usable for str.translate().\n\
12614If there is only one argument, it must be a dictionary mapping Unicode\n\
12615ordinals (integers) or characters to Unicode ordinals, strings or None.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012616Character keys will be then converted to ordinals.\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012617If there are two arguments, they must be strings of equal length, and\n\
12618in the resulting dictionary, each character in x will be mapped to the\n\
12619character at the same position in y. If there is a third argument, it\n\
12620must be a string, whose characters will be mapped to None in the result.");
12621
12622static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012623unicode_maketrans(PyObject *null, PyObject *args)
Georg Brandlceee0772007-11-27 23:48:05 +000012624{
12625 PyObject *x, *y = NULL, *z = NULL;
12626 PyObject *new = NULL, *key, *value;
12627 Py_ssize_t i = 0;
12628 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012629
Georg Brandlceee0772007-11-27 23:48:05 +000012630 if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
12631 return NULL;
12632 new = PyDict_New();
12633 if (!new)
12634 return NULL;
12635 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012636 int x_kind, y_kind, z_kind;
12637 void *x_data, *y_data, *z_data;
12638
Georg Brandlceee0772007-11-27 23:48:05 +000012639 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012640 if (!PyUnicode_Check(x)) {
12641 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12642 "be a string if there is a second argument");
12643 goto err;
12644 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012645 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012646 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12647 "arguments must have equal length");
12648 goto err;
12649 }
12650 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012651 x_kind = PyUnicode_KIND(x);
12652 y_kind = PyUnicode_KIND(y);
12653 x_data = PyUnicode_DATA(x);
12654 y_data = PyUnicode_DATA(y);
12655 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
12656 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
12657 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012658 if (!key || !value)
12659 goto err;
12660 res = PyDict_SetItem(new, key, value);
12661 Py_DECREF(key);
12662 Py_DECREF(value);
12663 if (res < 0)
12664 goto err;
12665 }
12666 /* create entries for deleting chars in z */
12667 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012668 z_kind = PyUnicode_KIND(z);
12669 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012670 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012671 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012672 if (!key)
12673 goto err;
12674 res = PyDict_SetItem(new, key, Py_None);
12675 Py_DECREF(key);
12676 if (res < 0)
12677 goto err;
12678 }
12679 }
12680 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012681 int kind;
12682 void *data;
12683
Georg Brandlceee0772007-11-27 23:48:05 +000012684 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000012685 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012686 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
12687 "to maketrans it must be a dict");
12688 goto err;
12689 }
12690 /* copy entries into the new dict, converting string keys to int keys */
12691 while (PyDict_Next(x, &i, &key, &value)) {
12692 if (PyUnicode_Check(key)) {
12693 /* convert string keys to integer keys */
12694 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012695 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000012696 PyErr_SetString(PyExc_ValueError, "string keys in translate "
12697 "table must be of length 1");
12698 goto err;
12699 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012700 kind = PyUnicode_KIND(key);
12701 data = PyUnicode_DATA(key);
12702 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000012703 if (!newkey)
12704 goto err;
12705 res = PyDict_SetItem(new, newkey, value);
12706 Py_DECREF(newkey);
12707 if (res < 0)
12708 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000012709 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012710 /* just keep integer keys */
12711 if (PyDict_SetItem(new, key, value) < 0)
12712 goto err;
12713 } else {
12714 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
12715 "be strings or integers");
12716 goto err;
12717 }
12718 }
12719 }
12720 return new;
12721 err:
12722 Py_DECREF(new);
12723 return NULL;
12724}
12725
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012726PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012727 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012728\n\
12729Return a copy of the string S, where all characters have been mapped\n\
12730through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012731Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000012732Unmapped characters are left untouched. Characters mapped to None\n\
12733are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012734
12735static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012736unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012737{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012738 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012739}
12740
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012741PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012742 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012743\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012744Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012745
12746static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012747unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012748{
Guido van Rossumd57fd912000-03-10 22:53:23 +000012749 return fixup(self, fixupper);
12750}
12751
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012752PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012753 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012754\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000012755Pad a numeric string S with zeros on the left, to fill a field\n\
12756of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012757
12758static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012759unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012760{
Martin v. Löwis18e16552006-02-15 17:27:45 +000012761 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020012762 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012763 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012764 int kind;
12765 void *data;
12766 Py_UCS4 chr;
12767
12768 if (PyUnicode_READY(self) == -1)
12769 return NULL;
12770
Martin v. Löwis18e16552006-02-15 17:27:45 +000012771 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012772 return NULL;
12773
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012774 if (PyUnicode_GET_LENGTH(self) >= width) {
Walter Dörwald0fe940c2002-04-15 18:42:15 +000012775 if (PyUnicode_CheckExact(self)) {
12776 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010012777 return self;
Walter Dörwald0fe940c2002-04-15 18:42:15 +000012778 }
12779 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012780 return PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012781 }
12782
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012783 fill = width - _PyUnicode_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012784
12785 u = pad(self, fill, 0, '0');
12786
Walter Dörwald068325e2002-04-15 13:36:47 +000012787 if (u == NULL)
12788 return NULL;
12789
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012790 kind = PyUnicode_KIND(u);
12791 data = PyUnicode_DATA(u);
12792 chr = PyUnicode_READ(kind, data, fill);
12793
12794 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012795 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012796 PyUnicode_WRITE(kind, data, 0, chr);
12797 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000012798 }
12799
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012800 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010012801 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012802}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012803
12804#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012805static PyObject *
12806unicode__decimal2ascii(PyObject *self)
12807{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012808 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012809}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012810#endif
12811
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012812PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012813 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012814\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012815Return True if S starts with the specified prefix, False otherwise.\n\
12816With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012817With optional end, stop comparing S at that position.\n\
12818prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012819
12820static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012821unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012822 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012823{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012824 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012825 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012826 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012827 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012828 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012829
Jesus Ceaac451502011-04-20 17:09:23 +020012830 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012831 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012832 if (PyTuple_Check(subobj)) {
12833 Py_ssize_t i;
12834 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012835 substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012836 if (substring == NULL)
12837 return NULL;
12838 result = tailmatch(self, substring, start, end, -1);
12839 Py_DECREF(substring);
12840 if (result) {
12841 Py_RETURN_TRUE;
12842 }
12843 }
12844 /* nothing matched */
12845 Py_RETURN_FALSE;
12846 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012847 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012848 if (substring == NULL) {
12849 if (PyErr_ExceptionMatches(PyExc_TypeError))
12850 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
12851 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012852 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012853 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012854 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012855 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012856 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012857}
12858
12859
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012860PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012861 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012862\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012863Return True if S ends with the specified suffix, False otherwise.\n\
12864With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012865With optional end, stop comparing S at that position.\n\
12866suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012867
12868static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012869unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012870 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012871{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012872 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012873 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012874 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012875 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012876 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012877
Jesus Ceaac451502011-04-20 17:09:23 +020012878 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012879 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012880 if (PyTuple_Check(subobj)) {
12881 Py_ssize_t i;
12882 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012883 substring = PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000012884 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012885 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012886 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012887 result = tailmatch(self, substring, start, end, +1);
12888 Py_DECREF(substring);
12889 if (result) {
12890 Py_RETURN_TRUE;
12891 }
12892 }
12893 Py_RETURN_FALSE;
12894 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012895 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012896 if (substring == NULL) {
12897 if (PyErr_ExceptionMatches(PyExc_TypeError))
12898 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
12899 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012900 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012901 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012902 result = tailmatch(self, substring, start, end, +1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012903 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012904 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012905}
12906
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012907#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000012908
12909PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012910 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012911\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012912Return a formatted version of S, using substitutions from args and kwargs.\n\
12913The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000012914
Eric Smith27bbca62010-11-04 17:06:58 +000012915PyDoc_STRVAR(format_map__doc__,
12916 "S.format_map(mapping) -> str\n\
12917\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012918Return a formatted version of S, using substitutions from mapping.\n\
12919The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000012920
Eric Smith4a7d76d2008-05-30 18:10:19 +000012921static PyObject *
12922unicode__format__(PyObject* self, PyObject* args)
12923{
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012924 PyObject *format_spec, *out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012925
12926 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
12927 return NULL;
12928
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012929 out = _PyUnicode_FormatAdvanced(self, format_spec, 0,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012930 PyUnicode_GET_LENGTH(format_spec));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012931 return out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012932}
12933
Eric Smith8c663262007-08-25 02:26:07 +000012934PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012935 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012936\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012937Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000012938
12939static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012940unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012941{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012942 Py_ssize_t size;
12943
12944 /* If it's a compact object, account for base structure +
12945 character data. */
12946 if (PyUnicode_IS_COMPACT_ASCII(v))
12947 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
12948 else if (PyUnicode_IS_COMPACT(v))
12949 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012950 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012951 else {
12952 /* If it is a two-block object, account for base object, and
12953 for character block if present. */
12954 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020012955 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012956 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012957 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012958 }
12959 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020012960 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020012961 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012962 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020012963 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020012964 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012965
12966 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012967}
12968
12969PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012970 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012971
12972static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020012973unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000012974{
Victor Stinner034f6cf2011-09-30 02:26:44 +020012975 PyObject *copy = PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012976 if (!copy)
12977 return NULL;
12978 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000012979}
12980
Guido van Rossumd57fd912000-03-10 22:53:23 +000012981static PyMethodDef unicode_methods[] = {
12982
12983 /* Order is according to common usage: often used methods should
12984 appear first, since lookup is done sequentially. */
12985
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000012986 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012987 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
12988 {"split", (PyCFunction) unicode_split, METH_VARARGS, split__doc__},
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012989 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012990 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
12991 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
12992 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
12993 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
12994 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
12995 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
12996 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000012997 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012998 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
12999 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
13000 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013001 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013002 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13003 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
13004 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013005 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013006 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010013007 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013008 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013009 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
13010 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
13011 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
13012 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13013 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
13014 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
13015 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
13016 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
13017 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
13018 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
13019 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
13020 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
13021 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
13022 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000013023 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000013024 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013025 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000013026 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013027 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000013028 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Georg Brandlceee0772007-11-27 23:48:05 +000013029 {"maketrans", (PyCFunction) unicode_maketrans,
13030 METH_VARARGS | METH_STATIC, maketrans__doc__},
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013031 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000013032#if 0
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013033 {"capwords", (PyCFunction) unicode_capwords, METH_NOARGS, capwords__doc__},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013034#endif
13035
13036#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013037 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013038 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013039#endif
13040
Benjamin Peterson14339b62009-01-31 16:36:08 +000013041 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013042 {NULL, NULL}
13043};
13044
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013045static PyObject *
13046unicode_mod(PyObject *v, PyObject *w)
13047{
Brian Curtindfc80e32011-08-10 20:28:54 -050013048 if (!PyUnicode_Check(v))
13049 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013050 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013051}
13052
13053static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013054 0, /*nb_add*/
13055 0, /*nb_subtract*/
13056 0, /*nb_multiply*/
13057 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013058};
13059
Guido van Rossumd57fd912000-03-10 22:53:23 +000013060static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013061 (lenfunc) unicode_length, /* sq_length */
13062 PyUnicode_Concat, /* sq_concat */
13063 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13064 (ssizeargfunc) unicode_getitem, /* sq_item */
13065 0, /* sq_slice */
13066 0, /* sq_ass_item */
13067 0, /* sq_ass_slice */
13068 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013069};
13070
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013071static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013072unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013073{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013074 if (PyUnicode_READY(self) == -1)
13075 return NULL;
13076
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013077 if (PyIndex_Check(item)) {
13078 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013079 if (i == -1 && PyErr_Occurred())
13080 return NULL;
13081 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013082 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013083 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013084 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013085 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013086 PyObject *result;
13087 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013088 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013089 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013090
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013091 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013092 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013093 return NULL;
13094 }
13095
13096 if (slicelength <= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013097 return PyUnicode_New(0, 0);
13098 } else if (start == 0 && step == 1 &&
13099 slicelength == PyUnicode_GET_LENGTH(self) &&
Thomas Woutersed03b412007-08-28 21:37:11 +000013100 PyUnicode_CheckExact(self)) {
13101 Py_INCREF(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013102 return self;
Thomas Woutersed03b412007-08-28 21:37:11 +000013103 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013104 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013105 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013106 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013107 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013108 src_kind = PyUnicode_KIND(self);
13109 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013110 if (!PyUnicode_IS_ASCII(self)) {
13111 kind_limit = kind_maxchar_limit(src_kind);
13112 max_char = 0;
13113 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13114 ch = PyUnicode_READ(src_kind, src_data, cur);
13115 if (ch > max_char) {
13116 max_char = ch;
13117 if (max_char >= kind_limit)
13118 break;
13119 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013120 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013121 }
Victor Stinner55c99112011-10-13 01:17:06 +020013122 else
13123 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013124 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013125 if (result == NULL)
13126 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013127 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013128 dest_data = PyUnicode_DATA(result);
13129
13130 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013131 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13132 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013133 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013134 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013135 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013136 } else {
13137 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13138 return NULL;
13139 }
13140}
13141
13142static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013143 (lenfunc)unicode_length, /* mp_length */
13144 (binaryfunc)unicode_subscript, /* mp_subscript */
13145 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013146};
13147
Guido van Rossumd57fd912000-03-10 22:53:23 +000013148
Guido van Rossumd57fd912000-03-10 22:53:23 +000013149/* Helpers for PyUnicode_Format() */
13150
13151static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +000013152getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013153{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013154 Py_ssize_t argidx = *p_argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013155 if (argidx < arglen) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013156 (*p_argidx)++;
13157 if (arglen < 0)
13158 return args;
13159 else
13160 return PyTuple_GetItem(args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013161 }
13162 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013163 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013164 return NULL;
13165}
13166
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013167/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013168
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013169static PyObject *
13170formatfloat(PyObject *v, int flags, int prec, int type)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013171{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013172 char *p;
13173 PyObject *result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013174 double x;
Tim Petersced69f82003-09-16 20:30:58 +000013175
Guido van Rossumd57fd912000-03-10 22:53:23 +000013176 x = PyFloat_AsDouble(v);
13177 if (x == -1.0 && PyErr_Occurred())
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013178 return NULL;
13179
Guido van Rossumd57fd912000-03-10 22:53:23 +000013180 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013181 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013182
Eric Smith0923d1d2009-04-16 20:16:10 +000013183 p = PyOS_double_to_string(x, type, prec,
13184 (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013185 if (p == NULL)
13186 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013187 result = PyUnicode_DecodeASCII(p, strlen(p), NULL);
Eric Smith0923d1d2009-04-16 20:16:10 +000013188 PyMem_Free(p);
13189 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013190}
13191
Tim Peters38fd5b62000-09-21 05:43:11 +000013192static PyObject*
13193formatlong(PyObject *val, int flags, int prec, int type)
13194{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013195 char *buf;
13196 int len;
13197 PyObject *str; /* temporary string object. */
13198 PyObject *result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013199
Benjamin Peterson14339b62009-01-31 16:36:08 +000013200 str = _PyBytes_FormatLong(val, flags, prec, type, &buf, &len);
13201 if (!str)
13202 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013203 result = PyUnicode_DecodeASCII(buf, len, NULL);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013204 Py_DECREF(str);
13205 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013206}
13207
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013208static Py_UCS4
13209formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013210{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013211 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013212 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013213 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013214 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000013215 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013216 goto onError;
13217 }
13218 else {
13219 /* Integer input truncated to a character */
13220 long x;
13221 x = PyLong_AsLong(v);
13222 if (x == -1 && PyErr_Occurred())
13223 goto onError;
13224
13225 if (x < 0 || x > 0x10ffff) {
13226 PyErr_SetString(PyExc_OverflowError,
13227 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013228 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013229 }
13230
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013231 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013232 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013233
Benjamin Peterson29060642009-01-31 22:14:21 +000013234 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013235 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013236 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013237 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013238}
13239
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013240static int
13241repeat_accumulate(_PyAccu *acc, PyObject *obj, Py_ssize_t count)
13242{
13243 int r;
13244 assert(count > 0);
13245 assert(PyUnicode_Check(obj));
13246 if (count > 5) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013247 PyObject *repeated = unicode_repeat(obj, count);
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013248 if (repeated == NULL)
13249 return -1;
13250 r = _PyAccu_Accumulate(acc, repeated);
13251 Py_DECREF(repeated);
13252 return r;
13253 }
13254 else {
13255 do {
13256 if (_PyAccu_Accumulate(acc, obj))
13257 return -1;
13258 } while (--count);
13259 return 0;
13260 }
13261}
13262
Alexander Belopolsky40018472011-02-26 01:02:56 +000013263PyObject *
13264PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013265{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013266 void *fmt;
13267 int fmtkind;
13268 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013269 int kind;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013270 int r;
13271 Py_ssize_t fmtcnt, fmtpos, arglen, argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013272 int args_owned = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013273 PyObject *dict = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013274 PyObject *temp = NULL;
13275 PyObject *second = NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013276 PyObject *uformat;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013277 _PyAccu acc;
13278 static PyObject *plus, *minus, *blank, *zero, *percent;
13279
13280 if (!plus && !(plus = get_latin1_char('+')))
13281 return NULL;
13282 if (!minus && !(minus = get_latin1_char('-')))
13283 return NULL;
13284 if (!blank && !(blank = get_latin1_char(' ')))
13285 return NULL;
13286 if (!zero && !(zero = get_latin1_char('0')))
13287 return NULL;
13288 if (!percent && !(percent = get_latin1_char('%')))
13289 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000013290
Guido van Rossumd57fd912000-03-10 22:53:23 +000013291 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013292 PyErr_BadInternalCall();
13293 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013294 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013295 uformat = PyUnicode_FromObject(format);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013296 if (uformat == NULL || PyUnicode_READY(uformat) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013297 return NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013298 if (_PyAccu_Init(&acc))
13299 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013300 fmt = PyUnicode_DATA(uformat);
13301 fmtkind = PyUnicode_KIND(uformat);
13302 fmtcnt = PyUnicode_GET_LENGTH(uformat);
13303 fmtpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013304
Guido van Rossumd57fd912000-03-10 22:53:23 +000013305 if (PyTuple_Check(args)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013306 arglen = PyTuple_Size(args);
13307 argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013308 }
13309 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013310 arglen = -1;
13311 argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013312 }
Christian Heimes90aa7642007-12-19 02:45:37 +000013313 if (Py_TYPE(args)->tp_as_mapping && !PyTuple_Check(args) &&
Christian Heimesf3863112007-11-22 07:46:41 +000013314 !PyUnicode_Check(args))
Benjamin Peterson29060642009-01-31 22:14:21 +000013315 dict = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013316
13317 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013318 if (PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013319 PyObject *nonfmt;
13320 Py_ssize_t nonfmtpos;
13321 nonfmtpos = fmtpos++;
13322 while (fmtcnt >= 0 &&
13323 PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
13324 fmtpos++;
13325 fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013326 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010013327 nonfmt = PyUnicode_Substring(uformat, nonfmtpos, fmtpos);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013328 if (nonfmt == NULL)
13329 goto onError;
13330 r = _PyAccu_Accumulate(&acc, nonfmt);
13331 Py_DECREF(nonfmt);
13332 if (r)
13333 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013334 }
13335 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013336 /* Got a format specifier */
13337 int flags = 0;
13338 Py_ssize_t width = -1;
13339 int prec = -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013340 Py_UCS4 c = '\0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013341 Py_UCS4 fill, sign;
Benjamin Peterson29060642009-01-31 22:14:21 +000013342 int isnumok;
13343 PyObject *v = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013344 void *pbuf = NULL;
13345 Py_ssize_t pindex, len;
13346 PyObject *signobj = NULL, *fillobj = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013347
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013348 fmtpos++;
13349 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(') {
13350 Py_ssize_t keystart;
Benjamin Peterson29060642009-01-31 22:14:21 +000013351 Py_ssize_t keylen;
13352 PyObject *key;
13353 int pcount = 1;
Christian Heimesa612dc02008-02-24 13:08:18 +000013354
Benjamin Peterson29060642009-01-31 22:14:21 +000013355 if (dict == NULL) {
13356 PyErr_SetString(PyExc_TypeError,
13357 "format requires a mapping");
13358 goto onError;
13359 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013360 ++fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013361 --fmtcnt;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013362 keystart = fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013363 /* Skip over balanced parentheses */
13364 while (pcount > 0 && --fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013365 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == ')')
Benjamin Peterson29060642009-01-31 22:14:21 +000013366 --pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013367 else if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(')
Benjamin Peterson29060642009-01-31 22:14:21 +000013368 ++pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013369 fmtpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013370 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013371 keylen = fmtpos - keystart - 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013372 if (fmtcnt < 0 || pcount > 0) {
13373 PyErr_SetString(PyExc_ValueError,
13374 "incomplete format key");
13375 goto onError;
13376 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010013377 key = PyUnicode_Substring(uformat,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013378 keystart, keystart + keylen);
Benjamin Peterson29060642009-01-31 22:14:21 +000013379 if (key == NULL)
13380 goto onError;
13381 if (args_owned) {
13382 Py_DECREF(args);
13383 args_owned = 0;
13384 }
13385 args = PyObject_GetItem(dict, key);
13386 Py_DECREF(key);
13387 if (args == NULL) {
13388 goto onError;
13389 }
13390 args_owned = 1;
13391 arglen = -1;
13392 argidx = -2;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013393 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013394 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013395 switch (c = PyUnicode_READ(fmtkind, fmt, fmtpos++)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013396 case '-': flags |= F_LJUST; continue;
13397 case '+': flags |= F_SIGN; continue;
13398 case ' ': flags |= F_BLANK; continue;
13399 case '#': flags |= F_ALT; continue;
13400 case '0': flags |= F_ZERO; continue;
13401 }
13402 break;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013403 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013404 if (c == '*') {
13405 v = getnextarg(args, arglen, &argidx);
13406 if (v == NULL)
13407 goto onError;
13408 if (!PyLong_Check(v)) {
13409 PyErr_SetString(PyExc_TypeError,
13410 "* wants int");
13411 goto onError;
13412 }
13413 width = PyLong_AsLong(v);
13414 if (width == -1 && PyErr_Occurred())
13415 goto onError;
13416 if (width < 0) {
13417 flags |= F_LJUST;
13418 width = -width;
13419 }
13420 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013421 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013422 }
13423 else if (c >= '0' && c <= '9') {
13424 width = c - '0';
13425 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013426 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013427 if (c < '0' || c > '9')
13428 break;
13429 if ((width*10) / 10 != width) {
13430 PyErr_SetString(PyExc_ValueError,
13431 "width too big");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013432 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013433 }
13434 width = width*10 + (c - '0');
13435 }
13436 }
13437 if (c == '.') {
13438 prec = 0;
13439 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013440 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013441 if (c == '*') {
13442 v = getnextarg(args, arglen, &argidx);
13443 if (v == NULL)
13444 goto onError;
13445 if (!PyLong_Check(v)) {
13446 PyErr_SetString(PyExc_TypeError,
13447 "* wants int");
13448 goto onError;
13449 }
13450 prec = PyLong_AsLong(v);
13451 if (prec == -1 && PyErr_Occurred())
13452 goto onError;
13453 if (prec < 0)
13454 prec = 0;
13455 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013456 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013457 }
13458 else if (c >= '0' && c <= '9') {
13459 prec = c - '0';
13460 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013461 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013462 if (c < '0' || c > '9')
13463 break;
13464 if ((prec*10) / 10 != prec) {
13465 PyErr_SetString(PyExc_ValueError,
13466 "prec too big");
13467 goto onError;
13468 }
13469 prec = prec*10 + (c - '0');
13470 }
13471 }
13472 } /* prec */
13473 if (fmtcnt >= 0) {
13474 if (c == 'h' || c == 'l' || c == 'L') {
13475 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013476 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013477 }
13478 }
13479 if (fmtcnt < 0) {
13480 PyErr_SetString(PyExc_ValueError,
13481 "incomplete format");
13482 goto onError;
13483 }
13484 if (c != '%') {
13485 v = getnextarg(args, arglen, &argidx);
13486 if (v == NULL)
13487 goto onError;
13488 }
13489 sign = 0;
13490 fill = ' ';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013491 fillobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013492 switch (c) {
13493
13494 case '%':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013495 _PyAccu_Accumulate(&acc, percent);
13496 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +000013497
13498 case 's':
13499 case 'r':
13500 case 'a':
Victor Stinner808fc0a2010-03-22 12:50:40 +000013501 if (PyUnicode_CheckExact(v) && c == 's') {
Benjamin Peterson29060642009-01-31 22:14:21 +000013502 temp = v;
13503 Py_INCREF(temp);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013504 }
13505 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013506 if (c == 's')
13507 temp = PyObject_Str(v);
13508 else if (c == 'r')
13509 temp = PyObject_Repr(v);
13510 else
13511 temp = PyObject_ASCII(v);
13512 if (temp == NULL)
13513 goto onError;
13514 if (PyUnicode_Check(temp))
13515 /* nothing to do */;
13516 else {
13517 Py_DECREF(temp);
13518 PyErr_SetString(PyExc_TypeError,
13519 "%s argument has non-string str()");
13520 goto onError;
13521 }
13522 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013523 if (PyUnicode_READY(temp) == -1) {
13524 Py_CLEAR(temp);
13525 goto onError;
13526 }
13527 pbuf = PyUnicode_DATA(temp);
13528 kind = PyUnicode_KIND(temp);
13529 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013530 if (prec >= 0 && len > prec)
13531 len = prec;
13532 break;
13533
13534 case 'i':
13535 case 'd':
13536 case 'u':
13537 case 'o':
13538 case 'x':
13539 case 'X':
Benjamin Peterson29060642009-01-31 22:14:21 +000013540 isnumok = 0;
13541 if (PyNumber_Check(v)) {
13542 PyObject *iobj=NULL;
13543
13544 if (PyLong_Check(v)) {
13545 iobj = v;
13546 Py_INCREF(iobj);
13547 }
13548 else {
13549 iobj = PyNumber_Long(v);
13550 }
13551 if (iobj!=NULL) {
13552 if (PyLong_Check(iobj)) {
13553 isnumok = 1;
Senthil Kumaran9ebe08d2011-07-03 21:03:16 -070013554 temp = formatlong(iobj, flags, prec, (c == 'i'? 'd': c));
Benjamin Peterson29060642009-01-31 22:14:21 +000013555 Py_DECREF(iobj);
13556 if (!temp)
13557 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013558 if (PyUnicode_READY(temp) == -1) {
13559 Py_CLEAR(temp);
13560 goto onError;
13561 }
13562 pbuf = PyUnicode_DATA(temp);
13563 kind = PyUnicode_KIND(temp);
13564 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013565 sign = 1;
13566 }
13567 else {
13568 Py_DECREF(iobj);
13569 }
13570 }
13571 }
13572 if (!isnumok) {
13573 PyErr_Format(PyExc_TypeError,
13574 "%%%c format: a number is required, "
13575 "not %.200s", (char)c, Py_TYPE(v)->tp_name);
13576 goto onError;
13577 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013578 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013579 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013580 fillobj = zero;
13581 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013582 break;
13583
13584 case 'e':
13585 case 'E':
13586 case 'f':
13587 case 'F':
13588 case 'g':
13589 case 'G':
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013590 temp = formatfloat(v, flags, prec, c);
13591 if (!temp)
Benjamin Peterson29060642009-01-31 22:14:21 +000013592 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013593 if (PyUnicode_READY(temp) == -1) {
13594 Py_CLEAR(temp);
13595 goto onError;
13596 }
13597 pbuf = PyUnicode_DATA(temp);
13598 kind = PyUnicode_KIND(temp);
13599 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013600 sign = 1;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013601 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013602 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013603 fillobj = zero;
13604 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013605 break;
13606
13607 case 'c':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013608 {
13609 Py_UCS4 ch = formatchar(v);
13610 if (ch == (Py_UCS4) -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013611 goto onError;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013612 temp = _PyUnicode_FromUCS4(&ch, 1);
13613 if (temp == NULL)
13614 goto onError;
13615 pbuf = PyUnicode_DATA(temp);
13616 kind = PyUnicode_KIND(temp);
13617 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013618 break;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013619 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013620
13621 default:
13622 PyErr_Format(PyExc_ValueError,
13623 "unsupported format character '%c' (0x%x) "
13624 "at index %zd",
13625 (31<=c && c<=126) ? (char)c : '?',
13626 (int)c,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013627 fmtpos - 1);
Benjamin Peterson29060642009-01-31 22:14:21 +000013628 goto onError;
13629 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013630 /* pbuf is initialized here. */
13631 pindex = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +000013632 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013633 if (PyUnicode_READ(kind, pbuf, pindex) == '-') {
13634 signobj = minus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013635 len--;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013636 pindex++;
13637 }
13638 else if (PyUnicode_READ(kind, pbuf, pindex) == '+') {
13639 signobj = plus;
13640 len--;
13641 pindex++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013642 }
13643 else if (flags & F_SIGN)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013644 signobj = plus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013645 else if (flags & F_BLANK)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013646 signobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013647 else
13648 sign = 0;
13649 }
13650 if (width < len)
13651 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013652 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013653 if (fill != ' ') {
13654 assert(signobj != NULL);
13655 if (_PyAccu_Accumulate(&acc, signobj))
13656 goto onError;
13657 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013658 if (width > len)
13659 width--;
13660 }
13661 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013662 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013663 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == c);
Benjamin Peterson29060642009-01-31 22:14:21 +000013664 if (fill != ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013665 second = get_latin1_char(
13666 PyUnicode_READ(kind, pbuf, pindex + 1));
13667 pindex += 2;
13668 if (second == NULL ||
13669 _PyAccu_Accumulate(&acc, zero) ||
13670 _PyAccu_Accumulate(&acc, second))
13671 goto onError;
13672 Py_CLEAR(second);
Benjamin Peterson29060642009-01-31 22:14:21 +000013673 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013674 width -= 2;
13675 if (width < 0)
13676 width = 0;
13677 len -= 2;
13678 }
13679 if (width > len && !(flags & F_LJUST)) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013680 assert(fillobj != NULL);
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013681 if (repeat_accumulate(&acc, fillobj, width - len))
13682 goto onError;
13683 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013684 }
13685 if (fill == ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013686 if (sign) {
13687 assert(signobj != NULL);
13688 if (_PyAccu_Accumulate(&acc, signobj))
13689 goto onError;
13690 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013691 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013692 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
13693 assert(PyUnicode_READ(kind, pbuf, pindex+1) == c);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013694 second = get_latin1_char(
13695 PyUnicode_READ(kind, pbuf, pindex + 1));
13696 pindex += 2;
13697 if (second == NULL ||
13698 _PyAccu_Accumulate(&acc, zero) ||
13699 _PyAccu_Accumulate(&acc, second))
13700 goto onError;
13701 Py_CLEAR(second);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013702 }
13703 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013704 /* Copy all characters, preserving len */
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013705 if (temp != NULL) {
13706 assert(pbuf == PyUnicode_DATA(temp));
13707 v = PyUnicode_Substring(temp, pindex, pindex + len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013708 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013709 else {
13710 const char *p = (const char *) pbuf;
13711 assert(pbuf != NULL);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013712 p += kind * pindex;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013713 v = PyUnicode_FromKindAndData(kind, p, len);
13714 }
13715 if (v == NULL)
13716 goto onError;
13717 r = _PyAccu_Accumulate(&acc, v);
13718 Py_DECREF(v);
13719 if (r)
13720 goto onError;
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013721 if (width > len && repeat_accumulate(&acc, blank, width - len))
13722 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013723 if (dict && (argidx < arglen) && c != '%') {
13724 PyErr_SetString(PyExc_TypeError,
13725 "not all arguments converted during string formatting");
Benjamin Peterson29060642009-01-31 22:14:21 +000013726 goto onError;
13727 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013728 Py_CLEAR(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013729 } /* '%' */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013730 } /* until end */
13731 if (argidx < arglen && !dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013732 PyErr_SetString(PyExc_TypeError,
13733 "not all arguments converted during string formatting");
13734 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013735 }
13736
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013737 result = _PyAccu_Finish(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013738 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013739 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013740 }
13741 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013742 Py_XDECREF(temp);
13743 Py_XDECREF(second);
Victor Stinner7931d9a2011-11-04 00:22:48 +010013744 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013745
Benjamin Peterson29060642009-01-31 22:14:21 +000013746 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013747 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013748 Py_XDECREF(temp);
13749 Py_XDECREF(second);
13750 _PyAccu_Destroy(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013751 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013752 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013753 }
13754 return NULL;
13755}
13756
Jeremy Hylton938ace62002-07-17 16:30:39 +000013757static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000013758unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
13759
Tim Peters6d6c1a32001-08-02 04:15:00 +000013760static PyObject *
13761unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13762{
Benjamin Peterson29060642009-01-31 22:14:21 +000013763 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013764 static char *kwlist[] = {"object", "encoding", "errors", 0};
13765 char *encoding = NULL;
13766 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000013767
Benjamin Peterson14339b62009-01-31 16:36:08 +000013768 if (type != &PyUnicode_Type)
13769 return unicode_subtype_new(type, args, kwds);
13770 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000013771 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000013772 return NULL;
13773 if (x == NULL)
Victor Stinner7931d9a2011-11-04 00:22:48 +010013774 return PyUnicode_New(0, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013775 if (encoding == NULL && errors == NULL)
13776 return PyObject_Str(x);
13777 else
Benjamin Peterson29060642009-01-31 22:14:21 +000013778 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000013779}
13780
Guido van Rossume023fe02001-08-30 03:12:59 +000013781static PyObject *
13782unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13783{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013784 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013785 Py_ssize_t length, char_size;
13786 int share_wstr, share_utf8;
13787 unsigned int kind;
13788 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000013789
Benjamin Peterson14339b62009-01-31 16:36:08 +000013790 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013791
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013792 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013793 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013794 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020013795 assert(_PyUnicode_CHECK(unicode));
Victor Stinnere06e1452011-10-04 20:52:31 +020013796 if (PyUnicode_READY(unicode))
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013797 return NULL;
13798
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013799 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013800 if (self == NULL) {
13801 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013802 return NULL;
13803 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013804 kind = PyUnicode_KIND(unicode);
13805 length = PyUnicode_GET_LENGTH(unicode);
13806
13807 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013808#ifdef Py_DEBUG
13809 _PyUnicode_HASH(self) = -1;
13810#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013811 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013812#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013813 _PyUnicode_STATE(self).interned = 0;
13814 _PyUnicode_STATE(self).kind = kind;
13815 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020013816 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013817 _PyUnicode_STATE(self).ready = 1;
13818 _PyUnicode_WSTR(self) = NULL;
13819 _PyUnicode_UTF8_LENGTH(self) = 0;
13820 _PyUnicode_UTF8(self) = NULL;
13821 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020013822 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013823
13824 share_utf8 = 0;
13825 share_wstr = 0;
13826 if (kind == PyUnicode_1BYTE_KIND) {
13827 char_size = 1;
13828 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
13829 share_utf8 = 1;
13830 }
13831 else if (kind == PyUnicode_2BYTE_KIND) {
13832 char_size = 2;
13833 if (sizeof(wchar_t) == 2)
13834 share_wstr = 1;
13835 }
13836 else {
13837 assert(kind == PyUnicode_4BYTE_KIND);
13838 char_size = 4;
13839 if (sizeof(wchar_t) == 4)
13840 share_wstr = 1;
13841 }
13842
13843 /* Ensure we won't overflow the length. */
13844 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
13845 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013846 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013847 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013848 data = PyObject_MALLOC((length + 1) * char_size);
13849 if (data == NULL) {
13850 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013851 goto onError;
13852 }
13853
Victor Stinnerc3c74152011-10-02 20:39:55 +020013854 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013855 if (share_utf8) {
13856 _PyUnicode_UTF8_LENGTH(self) = length;
13857 _PyUnicode_UTF8(self) = data;
13858 }
13859 if (share_wstr) {
13860 _PyUnicode_WSTR_LENGTH(self) = length;
13861 _PyUnicode_WSTR(self) = (wchar_t *)data;
13862 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013863
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013864 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013865 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013866 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013867#ifdef Py_DEBUG
13868 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
13869#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020013870 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010013871 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013872
13873onError:
13874 Py_DECREF(unicode);
13875 Py_DECREF(self);
13876 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000013877}
13878
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013879PyDoc_STRVAR(unicode_doc,
Benjamin Peterson29060642009-01-31 22:14:21 +000013880 "str(string[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000013881\n\
Collin Winterd474ce82007-08-07 19:42:11 +000013882Create a new string object from the given encoded string.\n\
Skip Montanaro35b37a52002-07-26 16:22:46 +000013883encoding defaults to the current default string encoding.\n\
13884errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000013885
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013886static PyObject *unicode_iter(PyObject *seq);
13887
Guido van Rossumd57fd912000-03-10 22:53:23 +000013888PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000013889 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013890 "str", /* tp_name */
13891 sizeof(PyUnicodeObject), /* tp_size */
13892 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013893 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013894 (destructor)unicode_dealloc, /* tp_dealloc */
13895 0, /* tp_print */
13896 0, /* tp_getattr */
13897 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000013898 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013899 unicode_repr, /* tp_repr */
13900 &unicode_as_number, /* tp_as_number */
13901 &unicode_as_sequence, /* tp_as_sequence */
13902 &unicode_as_mapping, /* tp_as_mapping */
13903 (hashfunc) unicode_hash, /* tp_hash*/
13904 0, /* tp_call*/
13905 (reprfunc) unicode_str, /* tp_str */
13906 PyObject_GenericGetAttr, /* tp_getattro */
13907 0, /* tp_setattro */
13908 0, /* tp_as_buffer */
13909 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000013910 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013911 unicode_doc, /* tp_doc */
13912 0, /* tp_traverse */
13913 0, /* tp_clear */
13914 PyUnicode_RichCompare, /* tp_richcompare */
13915 0, /* tp_weaklistoffset */
13916 unicode_iter, /* tp_iter */
13917 0, /* tp_iternext */
13918 unicode_methods, /* tp_methods */
13919 0, /* tp_members */
13920 0, /* tp_getset */
13921 &PyBaseObject_Type, /* tp_base */
13922 0, /* tp_dict */
13923 0, /* tp_descr_get */
13924 0, /* tp_descr_set */
13925 0, /* tp_dictoffset */
13926 0, /* tp_init */
13927 0, /* tp_alloc */
13928 unicode_new, /* tp_new */
13929 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013930};
13931
13932/* Initialize the Unicode implementation */
13933
Victor Stinner3a50e702011-10-18 21:21:00 +020013934int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013935{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013936 int i;
13937
Thomas Wouters477c8d52006-05-27 19:21:47 +000013938 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013939 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000013940 0x000A, /* LINE FEED */
13941 0x000D, /* CARRIAGE RETURN */
13942 0x001C, /* FILE SEPARATOR */
13943 0x001D, /* GROUP SEPARATOR */
13944 0x001E, /* RECORD SEPARATOR */
13945 0x0085, /* NEXT LINE */
13946 0x2028, /* LINE SEPARATOR */
13947 0x2029, /* PARAGRAPH SEPARATOR */
13948 };
13949
Fred Drakee4315f52000-05-09 19:53:39 +000013950 /* Init the implementation */
Victor Stinnera464fc12011-10-02 20:39:30 +020013951 unicode_empty = PyUnicode_New(0, 0);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013952 assert(_PyUnicode_CheckConsistency(unicode_empty, 1));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013953 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013954 Py_FatalError("Can't create empty string");
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013955
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013956 for (i = 0; i < 256; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +000013957 unicode_latin1[i] = NULL;
Guido van Rossumcacfc072002-05-24 19:01:59 +000013958 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013959 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000013960
13961 /* initialize the linebreak bloom filter */
13962 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013963 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020013964 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013965
13966 PyType_Ready(&EncodingMapType);
Victor Stinner3a50e702011-10-18 21:21:00 +020013967
13968#ifdef HAVE_MBCS
13969 winver.dwOSVersionInfoSize = sizeof(winver);
13970 if (!GetVersionEx((OSVERSIONINFO*)&winver)) {
13971 PyErr_SetFromWindowsErr(0);
13972 return -1;
13973 }
13974#endif
13975 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013976}
13977
13978/* Finalize the Unicode implementation */
13979
Christian Heimesa156e092008-02-16 07:38:31 +000013980int
13981PyUnicode_ClearFreeList(void)
13982{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013983 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000013984}
13985
Guido van Rossumd57fd912000-03-10 22:53:23 +000013986void
Thomas Wouters78890102000-07-22 19:25:51 +000013987_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013988{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013989 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013990
Guido van Rossum4ae8ef82000-10-03 18:09:04 +000013991 Py_XDECREF(unicode_empty);
13992 unicode_empty = NULL;
Barry Warsaw5b4c2282000-10-03 20:45:26 +000013993
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013994 for (i = 0; i < 256; i++) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013995 if (unicode_latin1[i]) {
13996 Py_DECREF(unicode_latin1[i]);
13997 unicode_latin1[i] = NULL;
13998 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013999 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020014000 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000014001 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000014002}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000014003
Walter Dörwald16807132007-05-25 13:52:07 +000014004void
14005PyUnicode_InternInPlace(PyObject **p)
14006{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014007 register PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014008 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020014009#ifdef Py_DEBUG
14010 assert(s != NULL);
14011 assert(_PyUnicode_CHECK(s));
14012#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000014013 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020014014 return;
14015#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000014016 /* If it's a subclass, we don't really know what putting
14017 it in the interned dict might do. */
14018 if (!PyUnicode_CheckExact(s))
14019 return;
14020 if (PyUnicode_CHECK_INTERNED(s))
14021 return;
Victor Stinner1b4f9ce2011-10-03 13:28:14 +020014022 if (_PyUnicode_READY_REPLACE(p)) {
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014023 assert(0 && "_PyUnicode_READY_REPLACE fail in PyUnicode_InternInPlace");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014024 return;
14025 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014026 s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014027 if (interned == NULL) {
14028 interned = PyDict_New();
14029 if (interned == NULL) {
14030 PyErr_Clear(); /* Don't leave an exception */
14031 return;
14032 }
14033 }
14034 /* It might be that the GetItem call fails even
14035 though the key is present in the dictionary,
14036 namely when this happens during a stack overflow. */
14037 Py_ALLOW_RECURSION
Victor Stinner7931d9a2011-11-04 00:22:48 +010014038 t = PyDict_GetItem(interned, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014039 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000014040
Benjamin Peterson29060642009-01-31 22:14:21 +000014041 if (t) {
14042 Py_INCREF(t);
14043 Py_DECREF(*p);
14044 *p = t;
14045 return;
14046 }
Walter Dörwald16807132007-05-25 13:52:07 +000014047
Benjamin Peterson14339b62009-01-31 16:36:08 +000014048 PyThreadState_GET()->recursion_critical = 1;
Victor Stinner7931d9a2011-11-04 00:22:48 +010014049 if (PyDict_SetItem(interned, s, s) < 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014050 PyErr_Clear();
14051 PyThreadState_GET()->recursion_critical = 0;
14052 return;
14053 }
14054 PyThreadState_GET()->recursion_critical = 0;
14055 /* The two references in interned are not counted by refcnt.
14056 The deallocator will take care of this */
14057 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014058 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000014059}
14060
14061void
14062PyUnicode_InternImmortal(PyObject **p)
14063{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014064 PyUnicode_InternInPlace(p);
14065 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020014066 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014067 Py_INCREF(*p);
14068 }
Walter Dörwald16807132007-05-25 13:52:07 +000014069}
14070
14071PyObject *
14072PyUnicode_InternFromString(const char *cp)
14073{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014074 PyObject *s = PyUnicode_FromString(cp);
14075 if (s == NULL)
14076 return NULL;
14077 PyUnicode_InternInPlace(&s);
14078 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000014079}
14080
Alexander Belopolsky40018472011-02-26 01:02:56 +000014081void
14082_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000014083{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014084 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014085 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014086 Py_ssize_t i, n;
14087 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000014088
Benjamin Peterson14339b62009-01-31 16:36:08 +000014089 if (interned == NULL || !PyDict_Check(interned))
14090 return;
14091 keys = PyDict_Keys(interned);
14092 if (keys == NULL || !PyList_Check(keys)) {
14093 PyErr_Clear();
14094 return;
14095 }
Walter Dörwald16807132007-05-25 13:52:07 +000014096
Benjamin Peterson14339b62009-01-31 16:36:08 +000014097 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
14098 detector, interned unicode strings are not forcibly deallocated;
14099 rather, we give them their stolen references back, and then clear
14100 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000014101
Benjamin Peterson14339b62009-01-31 16:36:08 +000014102 n = PyList_GET_SIZE(keys);
14103 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000014104 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014105 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014106 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014107 if (PyUnicode_READY(s) == -1) {
14108 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014109 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014110 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014111 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014112 case SSTATE_NOT_INTERNED:
14113 /* XXX Shouldn't happen */
14114 break;
14115 case SSTATE_INTERNED_IMMORTAL:
14116 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014117 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014118 break;
14119 case SSTATE_INTERNED_MORTAL:
14120 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014121 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014122 break;
14123 default:
14124 Py_FatalError("Inconsistent interned string state.");
14125 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014126 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014127 }
14128 fprintf(stderr, "total size of all interned strings: "
14129 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
14130 "mortal/immortal\n", mortal_size, immortal_size);
14131 Py_DECREF(keys);
14132 PyDict_Clear(interned);
14133 Py_DECREF(interned);
14134 interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +000014135}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014136
14137
14138/********************* Unicode Iterator **************************/
14139
14140typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014141 PyObject_HEAD
14142 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014143 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014144} unicodeiterobject;
14145
14146static void
14147unicodeiter_dealloc(unicodeiterobject *it)
14148{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014149 _PyObject_GC_UNTRACK(it);
14150 Py_XDECREF(it->it_seq);
14151 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014152}
14153
14154static int
14155unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
14156{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014157 Py_VISIT(it->it_seq);
14158 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014159}
14160
14161static PyObject *
14162unicodeiter_next(unicodeiterobject *it)
14163{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014164 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014165
Benjamin Peterson14339b62009-01-31 16:36:08 +000014166 assert(it != NULL);
14167 seq = it->it_seq;
14168 if (seq == NULL)
14169 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014170 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014171
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014172 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
14173 int kind = PyUnicode_KIND(seq);
14174 void *data = PyUnicode_DATA(seq);
14175 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
14176 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014177 if (item != NULL)
14178 ++it->it_index;
14179 return item;
14180 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014181
Benjamin Peterson14339b62009-01-31 16:36:08 +000014182 Py_DECREF(seq);
14183 it->it_seq = NULL;
14184 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014185}
14186
14187static PyObject *
14188unicodeiter_len(unicodeiterobject *it)
14189{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014190 Py_ssize_t len = 0;
14191 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020014192 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014193 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014194}
14195
14196PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
14197
14198static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014199 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000014200 length_hint_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000014201 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014202};
14203
14204PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014205 PyVarObject_HEAD_INIT(&PyType_Type, 0)
14206 "str_iterator", /* tp_name */
14207 sizeof(unicodeiterobject), /* tp_basicsize */
14208 0, /* tp_itemsize */
14209 /* methods */
14210 (destructor)unicodeiter_dealloc, /* tp_dealloc */
14211 0, /* tp_print */
14212 0, /* tp_getattr */
14213 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014214 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014215 0, /* tp_repr */
14216 0, /* tp_as_number */
14217 0, /* tp_as_sequence */
14218 0, /* tp_as_mapping */
14219 0, /* tp_hash */
14220 0, /* tp_call */
14221 0, /* tp_str */
14222 PyObject_GenericGetAttr, /* tp_getattro */
14223 0, /* tp_setattro */
14224 0, /* tp_as_buffer */
14225 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
14226 0, /* tp_doc */
14227 (traverseproc)unicodeiter_traverse, /* tp_traverse */
14228 0, /* tp_clear */
14229 0, /* tp_richcompare */
14230 0, /* tp_weaklistoffset */
14231 PyObject_SelfIter, /* tp_iter */
14232 (iternextfunc)unicodeiter_next, /* tp_iternext */
14233 unicodeiter_methods, /* tp_methods */
14234 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014235};
14236
14237static PyObject *
14238unicode_iter(PyObject *seq)
14239{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014240 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014241
Benjamin Peterson14339b62009-01-31 16:36:08 +000014242 if (!PyUnicode_Check(seq)) {
14243 PyErr_BadInternalCall();
14244 return NULL;
14245 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014246 if (PyUnicode_READY(seq) == -1)
14247 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014248 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
14249 if (it == NULL)
14250 return NULL;
14251 it->it_index = 0;
14252 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014253 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014254 _PyObject_GC_TRACK(it);
14255 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014256}
14257
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010014258
14259size_t
14260Py_UNICODE_strlen(const Py_UNICODE *u)
14261{
14262 int res = 0;
14263 while(*u++)
14264 res++;
14265 return res;
14266}
14267
14268Py_UNICODE*
14269Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
14270{
14271 Py_UNICODE *u = s1;
14272 while ((*u++ = *s2++));
14273 return s1;
14274}
14275
14276Py_UNICODE*
14277Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14278{
14279 Py_UNICODE *u = s1;
14280 while ((*u++ = *s2++))
14281 if (n-- == 0)
14282 break;
14283 return s1;
14284}
14285
14286Py_UNICODE*
14287Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
14288{
14289 Py_UNICODE *u1 = s1;
14290 u1 += Py_UNICODE_strlen(u1);
14291 Py_UNICODE_strcpy(u1, s2);
14292 return s1;
14293}
14294
14295int
14296Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
14297{
14298 while (*s1 && *s2 && *s1 == *s2)
14299 s1++, s2++;
14300 if (*s1 && *s2)
14301 return (*s1 < *s2) ? -1 : +1;
14302 if (*s1)
14303 return 1;
14304 if (*s2)
14305 return -1;
14306 return 0;
14307}
14308
14309int
14310Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14311{
14312 register Py_UNICODE u1, u2;
14313 for (; n != 0; n--) {
14314 u1 = *s1;
14315 u2 = *s2;
14316 if (u1 != u2)
14317 return (u1 < u2) ? -1 : +1;
14318 if (u1 == '\0')
14319 return 0;
14320 s1++;
14321 s2++;
14322 }
14323 return 0;
14324}
14325
14326Py_UNICODE*
14327Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
14328{
14329 const Py_UNICODE *p;
14330 for (p = s; *p; p++)
14331 if (*p == c)
14332 return (Py_UNICODE*)p;
14333 return NULL;
14334}
14335
14336Py_UNICODE*
14337Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
14338{
14339 const Py_UNICODE *p;
14340 p = s + Py_UNICODE_strlen(s);
14341 while (p != s) {
14342 p--;
14343 if (*p == c)
14344 return (Py_UNICODE*)p;
14345 }
14346 return NULL;
14347}
Victor Stinner331ea922010-08-10 16:37:20 +000014348
Victor Stinner71133ff2010-09-01 23:43:53 +000014349Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014350PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000014351{
Victor Stinner577db2c2011-10-11 22:12:48 +020014352 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014353 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000014354
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014355 if (!PyUnicode_Check(unicode)) {
14356 PyErr_BadArgument();
14357 return NULL;
14358 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014359 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020014360 if (u == NULL)
14361 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000014362 /* Ensure we won't overflow the size. */
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014363 if (len > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000014364 PyErr_NoMemory();
14365 return NULL;
14366 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014367 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000014368 size *= sizeof(Py_UNICODE);
14369 copy = PyMem_Malloc(size);
14370 if (copy == NULL) {
14371 PyErr_NoMemory();
14372 return NULL;
14373 }
Victor Stinner577db2c2011-10-11 22:12:48 +020014374 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000014375 return copy;
14376}
Martin v. Löwis5b222132007-06-10 09:51:05 +000014377
Georg Brandl66c221e2010-10-14 07:04:07 +000014378/* A _string module, to export formatter_parser and formatter_field_name_split
14379 to the string.Formatter class implemented in Python. */
14380
14381static PyMethodDef _string_methods[] = {
14382 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
14383 METH_O, PyDoc_STR("split the argument as a field name")},
14384 {"formatter_parser", (PyCFunction) formatter_parser,
14385 METH_O, PyDoc_STR("parse the argument as a format string")},
14386 {NULL, NULL}
14387};
14388
14389static struct PyModuleDef _string_module = {
14390 PyModuleDef_HEAD_INIT,
14391 "_string",
14392 PyDoc_STR("string helper module"),
14393 0,
14394 _string_methods,
14395 NULL,
14396 NULL,
14397 NULL,
14398 NULL
14399};
14400
14401PyMODINIT_FUNC
14402PyInit__string(void)
14403{
14404 return PyModule_Create(&_string_module);
14405}
14406
14407
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014408#ifdef __cplusplus
14409}
14410#endif