blob: b756afc5260980cbe2d1af133e73346df4a2c794 [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"
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050044#include "bytes_methods.h"
Guido van Rossumd57fd912000-03-10 22:53:23 +000045
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000046#ifdef MS_WINDOWS
Guido van Rossumb7a40ba2000-03-28 02:01:52 +000047#include <windows.h>
48#endif
Guido van Rossumfd4b9572000-04-10 13:51:10 +000049
Guido van Rossumd57fd912000-03-10 22:53:23 +000050/* Endianness switches; defaults to little endian */
51
52#ifdef WORDS_BIGENDIAN
53# define BYTEORDER_IS_BIG_ENDIAN
54#else
55# define BYTEORDER_IS_LITTLE_ENDIAN
56#endif
57
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000058/* --- Globals ------------------------------------------------------------
59
60 The globals are initialized by the _PyUnicode_Init() API and should
61 not be used before calling that API.
62
63*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000064
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000065
66#ifdef __cplusplus
67extern "C" {
68#endif
69
Victor Stinner8faf8212011-12-08 22:14:11 +010070/* Maximum code point of Unicode 6.0: 0x10ffff (1,114,111) */
71#define MAX_UNICODE 0x10ffff
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 Stinnerc379ead2011-10-03 12:52:27 +0200121#define _PyUnicode_SHARE_UTF8(op) \
122 (assert(_PyUnicode_CHECK(op)), \
123 assert(!PyUnicode_IS_COMPACT_ASCII(op)), \
124 (_PyUnicode_UTF8(op) == PyUnicode_DATA(op)))
125#define _PyUnicode_SHARE_WSTR(op) \
126 (assert(_PyUnicode_CHECK(op)), \
127 (_PyUnicode_WSTR(unicode) == PyUnicode_DATA(op)))
128
Victor Stinner829c0ad2011-10-03 01:08:02 +0200129/* true if the Unicode object has an allocated UTF-8 memory block
130 (not shared with other data) */
Victor Stinner910337b2011-10-03 03:20:16 +0200131#define _PyUnicode_HAS_UTF8_MEMORY(op) \
132 (assert(_PyUnicode_CHECK(op)), \
133 (!PyUnicode_IS_COMPACT_ASCII(op) \
134 && _PyUnicode_UTF8(op) \
Victor Stinner829c0ad2011-10-03 01:08:02 +0200135 && _PyUnicode_UTF8(op) != PyUnicode_DATA(op)))
136
Victor Stinner03490912011-10-03 23:45:12 +0200137/* true if the Unicode object has an allocated wstr memory block
138 (not shared with other data) */
139#define _PyUnicode_HAS_WSTR_MEMORY(op) \
140 (assert(_PyUnicode_CHECK(op)), \
141 (_PyUnicode_WSTR(op) && \
142 (!PyUnicode_IS_READY(op) || \
143 _PyUnicode_WSTR(op) != PyUnicode_DATA(op))))
144
Victor Stinner910337b2011-10-03 03:20:16 +0200145/* Generic helper macro to convert characters of different types.
146 from_type and to_type have to be valid type names, begin and end
147 are pointers to the source characters which should be of type
148 "from_type *". to is a pointer of type "to_type *" and points to the
149 buffer where the result characters are written to. */
150#define _PyUnicode_CONVERT_BYTES(from_type, to_type, begin, end, to) \
151 do { \
Antoine Pitroue459a082011-10-11 20:58:41 +0200152 to_type *_to = (to_type *) to; \
153 const from_type *_iter = (begin); \
154 const from_type *_end = (end); \
155 Py_ssize_t n = (_end) - (_iter); \
156 const from_type *_unrolled_end = \
157 _iter + (n & ~ (Py_ssize_t) 3); \
158 while (_iter < (_unrolled_end)) { \
159 _to[0] = (to_type) _iter[0]; \
160 _to[1] = (to_type) _iter[1]; \
161 _to[2] = (to_type) _iter[2]; \
162 _to[3] = (to_type) _iter[3]; \
163 _iter += 4; _to += 4; \
Victor Stinner910337b2011-10-03 03:20:16 +0200164 } \
Antoine Pitroue459a082011-10-11 20:58:41 +0200165 while (_iter < (_end)) \
166 *_to++ = (to_type) *_iter++; \
Victor Stinner910337b2011-10-03 03:20:16 +0200167 } while (0)
Victor Stinner829c0ad2011-10-03 01:08:02 +0200168
Walter Dörwald16807132007-05-25 13:52:07 +0000169/* This dictionary holds all interned unicode strings. Note that references
170 to strings in this dictionary are *not* counted in the string's ob_refcnt.
171 When the interned string reaches a refcnt of 0 the string deallocation
172 function will delete the reference from this dictionary.
173
174 Another way to look at this is that to say that the actual reference
Guido van Rossum98297ee2007-11-06 21:34:58 +0000175 count of a string is: s->ob_refcnt + (s->state ? 2 : 0)
Walter Dörwald16807132007-05-25 13:52:07 +0000176*/
177static PyObject *interned;
178
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000179/* The empty Unicode object is shared to improve performance. */
Victor Stinnera464fc12011-10-02 20:39:30 +0200180static PyObject *unicode_empty;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000181
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200182/* List of static strings. */
183static _Py_Identifier *static_strings;
184
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000185/* Single character Unicode strings in the Latin-1 range are being
186 shared as well. */
Victor Stinnera464fc12011-10-02 20:39:30 +0200187static PyObject *unicode_latin1[256];
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000188
Christian Heimes190d79e2008-01-30 11:58:22 +0000189/* Fast detection of the most frequent whitespace characters */
190const unsigned char _Py_ascii_whitespace[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000191 0, 0, 0, 0, 0, 0, 0, 0,
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000192/* case 0x0009: * CHARACTER TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000193/* case 0x000A: * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000194/* case 0x000B: * LINE TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000195/* case 0x000C: * FORM FEED */
196/* case 0x000D: * CARRIAGE RETURN */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000197 0, 1, 1, 1, 1, 1, 0, 0,
198 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000199/* case 0x001C: * FILE SEPARATOR */
200/* case 0x001D: * GROUP SEPARATOR */
201/* case 0x001E: * RECORD SEPARATOR */
202/* case 0x001F: * UNIT SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000203 0, 0, 0, 0, 1, 1, 1, 1,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000204/* case 0x0020: * SPACE */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000205 1, 0, 0, 0, 0, 0, 0, 0,
206 0, 0, 0, 0, 0, 0, 0, 0,
207 0, 0, 0, 0, 0, 0, 0, 0,
208 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000209
Benjamin Peterson14339b62009-01-31 16:36:08 +0000210 0, 0, 0, 0, 0, 0, 0, 0,
211 0, 0, 0, 0, 0, 0, 0, 0,
212 0, 0, 0, 0, 0, 0, 0, 0,
213 0, 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,
217 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000218};
219
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200220/* forward */
Victor Stinnerfe226c02011-10-03 03:52:20 +0200221static PyUnicodeObject *_PyUnicode_New(Py_ssize_t length);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200222static PyObject* get_latin1_char(unsigned char ch);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200223static void copy_characters(
224 PyObject *to, Py_ssize_t to_start,
225 PyObject *from, Py_ssize_t from_start,
226 Py_ssize_t how_many);
Victor Stinner488fa492011-12-12 00:01:39 +0100227static int unicode_modifiable(PyObject *unicode);
228
Victor Stinnerfe226c02011-10-03 03:52:20 +0200229
Alexander Belopolsky40018472011-02-26 01:02:56 +0000230static PyObject *
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200231unicode_fromascii(const unsigned char *s, Py_ssize_t size);
232static PyObject *
233_PyUnicode_FromUCS1(const unsigned char *s, Py_ssize_t size);
234static PyObject *
235_PyUnicode_FromUCS2(const Py_UCS2 *s, Py_ssize_t size);
236static PyObject *
237_PyUnicode_FromUCS4(const Py_UCS4 *s, Py_ssize_t size);
238
239static PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +0000240unicode_encode_call_errorhandler(const char *errors,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000241 PyObject **errorHandler,const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +0100242 PyObject *unicode, PyObject **exceptionObject,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000243 Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos);
244
Alexander Belopolsky40018472011-02-26 01:02:56 +0000245static void
246raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +0300247 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +0100248 PyObject *unicode,
249 Py_ssize_t startpos, Py_ssize_t endpos,
250 const char *reason);
Victor Stinner31be90b2010-04-22 19:38:16 +0000251
Christian Heimes190d79e2008-01-30 11:58:22 +0000252/* Same for linebreaks */
253static unsigned char ascii_linebreak[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000254 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000255/* 0x000A, * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000256/* 0x000B, * LINE TABULATION */
257/* 0x000C, * FORM FEED */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000258/* 0x000D, * CARRIAGE RETURN */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000259 0, 0, 1, 1, 1, 1, 0, 0,
Benjamin Peterson14339b62009-01-31 16:36:08 +0000260 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000261/* 0x001C, * FILE SEPARATOR */
262/* 0x001D, * GROUP SEPARATOR */
263/* 0x001E, * RECORD SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000264 0, 0, 0, 0, 1, 1, 1, 0,
265 0, 0, 0, 0, 0, 0, 0, 0,
266 0, 0, 0, 0, 0, 0, 0, 0,
267 0, 0, 0, 0, 0, 0, 0, 0,
268 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000269
Benjamin Peterson14339b62009-01-31 16:36:08 +0000270 0, 0, 0, 0, 0, 0, 0, 0,
271 0, 0, 0, 0, 0, 0, 0, 0,
272 0, 0, 0, 0, 0, 0, 0, 0,
273 0, 0, 0, 0, 0, 0, 0, 0,
274 0, 0, 0, 0, 0, 0, 0, 0,
275 0, 0, 0, 0, 0, 0, 0, 0,
276 0, 0, 0, 0, 0, 0, 0, 0,
277 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000278};
279
Ezio Melotti48a2f8f2011-09-29 00:18:19 +0300280/* The max unicode value is always 0x10FFFF while using the PEP-393 API.
281 This function is kept for backward compatibility with the old API. */
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000282Py_UNICODE
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +0000283PyUnicode_GetMax(void)
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000284{
Fredrik Lundh8f455852001-06-27 18:59:43 +0000285#ifdef Py_UNICODE_WIDE
Benjamin Peterson14339b62009-01-31 16:36:08 +0000286 return 0x10FFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000287#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000288 /* This is actually an illegal character, so it should
289 not be passed to unichr. */
290 return 0xFFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000291#endif
292}
293
Victor Stinner910337b2011-10-03 03:20:16 +0200294#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200295int
Victor Stinner7931d9a2011-11-04 00:22:48 +0100296_PyUnicode_CheckConsistency(PyObject *op, int check_content)
Victor Stinner910337b2011-10-03 03:20:16 +0200297{
298 PyASCIIObject *ascii;
299 unsigned int kind;
300
301 assert(PyUnicode_Check(op));
302
303 ascii = (PyASCIIObject *)op;
304 kind = ascii->state.kind;
305
Victor Stinnera3b334d2011-10-03 13:53:37 +0200306 if (ascii->state.ascii == 1 && ascii->state.compact == 1) {
Victor Stinner910337b2011-10-03 03:20:16 +0200307 assert(kind == PyUnicode_1BYTE_KIND);
Victor Stinner910337b2011-10-03 03:20:16 +0200308 assert(ascii->state.ready == 1);
309 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200310 else {
Victor Stinner85041a52011-10-03 14:42:39 +0200311 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
Victor Stinner7f11ad42011-10-04 00:00:20 +0200312 void *data;
Victor Stinner910337b2011-10-03 03:20:16 +0200313
Victor Stinnera41463c2011-10-04 01:05:08 +0200314 if (ascii->state.compact == 1) {
315 data = compact + 1;
Victor Stinner910337b2011-10-03 03:20:16 +0200316 assert(kind == PyUnicode_1BYTE_KIND
317 || kind == PyUnicode_2BYTE_KIND
318 || kind == PyUnicode_4BYTE_KIND);
Victor Stinnera41463c2011-10-04 01:05:08 +0200319 assert(ascii->state.ascii == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200320 assert(ascii->state.ready == 1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200321 assert (compact->utf8 != data);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100322 }
323 else {
Victor Stinnera41463c2011-10-04 01:05:08 +0200324 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
325
326 data = unicode->data.any;
327 if (kind == PyUnicode_WCHAR_KIND) {
Victor Stinnere30c0a12011-11-04 20:54:05 +0100328 assert(ascii->length == 0);
329 assert(ascii->hash == -1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200330 assert(ascii->state.compact == 0);
331 assert(ascii->state.ascii == 0);
332 assert(ascii->state.ready == 0);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100333 assert(ascii->state.interned == SSTATE_NOT_INTERNED);
Victor Stinnera41463c2011-10-04 01:05:08 +0200334 assert(ascii->wstr != NULL);
335 assert(data == NULL);
336 assert(compact->utf8 == NULL);
Victor Stinnera41463c2011-10-04 01:05:08 +0200337 }
338 else {
339 assert(kind == PyUnicode_1BYTE_KIND
340 || kind == PyUnicode_2BYTE_KIND
341 || kind == PyUnicode_4BYTE_KIND);
342 assert(ascii->state.compact == 0);
343 assert(ascii->state.ready == 1);
344 assert(data != NULL);
345 if (ascii->state.ascii) {
346 assert (compact->utf8 == data);
347 assert (compact->utf8_length == ascii->length);
348 }
349 else
350 assert (compact->utf8 != data);
351 }
352 }
353 if (kind != PyUnicode_WCHAR_KIND) {
Victor Stinner7f11ad42011-10-04 00:00:20 +0200354 if (
355#if SIZEOF_WCHAR_T == 2
356 kind == PyUnicode_2BYTE_KIND
357#else
358 kind == PyUnicode_4BYTE_KIND
359#endif
360 )
Victor Stinnera41463c2011-10-04 01:05:08 +0200361 {
362 assert(ascii->wstr == data);
363 assert(compact->wstr_length == ascii->length);
364 } else
365 assert(ascii->wstr != data);
Victor Stinner910337b2011-10-03 03:20:16 +0200366 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200367
368 if (compact->utf8 == NULL)
369 assert(compact->utf8_length == 0);
370 if (ascii->wstr == NULL)
371 assert(compact->wstr_length == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200372 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200373 /* check that the best kind is used */
374 if (check_content && kind != PyUnicode_WCHAR_KIND)
375 {
376 Py_ssize_t i;
377 Py_UCS4 maxchar = 0;
378 void *data = PyUnicode_DATA(ascii);
379 for (i=0; i < ascii->length; i++)
380 {
381 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
382 if (ch > maxchar)
383 maxchar = ch;
384 }
385 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinner77faf692011-11-20 18:56:05 +0100386 if (ascii->state.ascii == 0) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200387 assert(maxchar >= 128);
Victor Stinner77faf692011-11-20 18:56:05 +0100388 assert(maxchar <= 255);
389 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200390 else
391 assert(maxchar < 128);
392 }
Victor Stinner77faf692011-11-20 18:56:05 +0100393 else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200394 assert(maxchar >= 0x100);
Victor Stinner77faf692011-11-20 18:56:05 +0100395 assert(maxchar <= 0xFFFF);
396 }
397 else {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200398 assert(maxchar >= 0x10000);
Victor Stinner8faf8212011-12-08 22:14:11 +0100399 assert(maxchar <= MAX_UNICODE);
Victor Stinner77faf692011-11-20 18:56:05 +0100400 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200401 }
Benjamin Petersonccc51c12011-10-03 19:34:12 -0400402 return 1;
403}
Victor Stinner910337b2011-10-03 03:20:16 +0200404#endif
405
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100406static PyObject*
407unicode_result_wchar(PyObject *unicode)
408{
409#ifndef Py_DEBUG
410 Py_ssize_t len;
411
412 assert(Py_REFCNT(unicode) == 1);
413
414 len = _PyUnicode_WSTR_LENGTH(unicode);
415 if (len == 0) {
416 Py_INCREF(unicode_empty);
417 Py_DECREF(unicode);
418 return unicode_empty;
419 }
420
421 if (len == 1) {
422 wchar_t ch = _PyUnicode_WSTR(unicode)[0];
423 if (ch < 256) {
424 PyObject *latin1_char = get_latin1_char((unsigned char)ch);
425 Py_DECREF(unicode);
426 return latin1_char;
427 }
428 }
429
430 if (_PyUnicode_Ready(unicode) < 0) {
431 Py_XDECREF(unicode);
432 return NULL;
433 }
434#else
435 /* don't make the result ready in debug mode to ensure that the caller
436 makes the string ready before using it */
437 assert(_PyUnicode_CheckConsistency(unicode, 1));
438#endif
439 return unicode;
440}
441
442static PyObject*
443unicode_result_ready(PyObject *unicode)
444{
445 Py_ssize_t length;
446
447 length = PyUnicode_GET_LENGTH(unicode);
448 if (length == 0) {
449 if (unicode != unicode_empty) {
450 Py_INCREF(unicode_empty);
451 Py_DECREF(unicode);
452 }
453 return unicode_empty;
454 }
455
456 if (length == 1) {
457 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
458 if (ch < 256) {
459 PyObject *latin1_char = unicode_latin1[ch];
460 if (latin1_char != NULL) {
461 if (unicode != latin1_char) {
462 Py_INCREF(latin1_char);
463 Py_DECREF(unicode);
464 }
465 return latin1_char;
466 }
467 else {
468 assert(_PyUnicode_CheckConsistency(unicode, 1));
469 Py_INCREF(unicode);
470 unicode_latin1[ch] = unicode;
471 return unicode;
472 }
473 }
474 }
475
476 assert(_PyUnicode_CheckConsistency(unicode, 1));
477 return unicode;
478}
479
480static PyObject*
481unicode_result(PyObject *unicode)
482{
483 assert(_PyUnicode_CHECK(unicode));
484 if (PyUnicode_IS_READY(unicode))
485 return unicode_result_ready(unicode);
486 else
487 return unicode_result_wchar(unicode);
488}
489
Victor Stinnerc4b49542011-12-11 22:44:26 +0100490static PyObject*
491unicode_result_unchanged(PyObject *unicode)
492{
493 if (PyUnicode_CheckExact(unicode)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -0500494 if (PyUnicode_READY(unicode) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +0100495 return NULL;
496 Py_INCREF(unicode);
497 return unicode;
498 }
499 else
500 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +0100501 return _PyUnicode_Copy(unicode);
Victor Stinnerc4b49542011-12-11 22:44:26 +0100502}
503
Victor Stinner3a50e702011-10-18 21:21:00 +0200504#ifdef HAVE_MBCS
505static OSVERSIONINFOEX winver;
506#endif
507
Thomas Wouters477c8d52006-05-27 19:21:47 +0000508/* --- Bloom Filters ----------------------------------------------------- */
509
510/* stuff to implement simple "bloom filters" for Unicode characters.
511 to keep things simple, we use a single bitmask, using the least 5
512 bits from each unicode characters as the bit index. */
513
514/* the linebreak mask is set up by Unicode_Init below */
515
Antoine Pitrouf068f942010-01-13 14:19:12 +0000516#if LONG_BIT >= 128
517#define BLOOM_WIDTH 128
518#elif LONG_BIT >= 64
519#define BLOOM_WIDTH 64
520#elif LONG_BIT >= 32
521#define BLOOM_WIDTH 32
522#else
523#error "LONG_BIT is smaller than 32"
524#endif
525
Thomas Wouters477c8d52006-05-27 19:21:47 +0000526#define BLOOM_MASK unsigned long
527
528static BLOOM_MASK bloom_linebreak;
529
Antoine Pitrouf068f942010-01-13 14:19:12 +0000530#define BLOOM_ADD(mask, ch) ((mask |= (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
531#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000532
Benjamin Peterson29060642009-01-31 22:14:21 +0000533#define BLOOM_LINEBREAK(ch) \
534 ((ch) < 128U ? ascii_linebreak[(ch)] : \
535 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000536
Alexander Belopolsky40018472011-02-26 01:02:56 +0000537Py_LOCAL_INLINE(BLOOM_MASK)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200538make_bloom_mask(int kind, void* ptr, Py_ssize_t len)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000539{
540 /* calculate simple bloom-style bitmask for a given unicode string */
541
Antoine Pitrouf068f942010-01-13 14:19:12 +0000542 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000543 Py_ssize_t i;
544
545 mask = 0;
546 for (i = 0; i < len; i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200547 BLOOM_ADD(mask, PyUnicode_READ(kind, ptr, i));
Thomas Wouters477c8d52006-05-27 19:21:47 +0000548
549 return mask;
550}
551
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200552#define BLOOM_MEMBER(mask, chr, str) \
553 (BLOOM(mask, chr) \
554 && (PyUnicode_FindChar(str, chr, 0, PyUnicode_GET_LENGTH(str), 1) >= 0))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000555
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200556/* Compilation of templated routines */
557
558#include "stringlib/asciilib.h"
559#include "stringlib/fastsearch.h"
560#include "stringlib/partition.h"
561#include "stringlib/split.h"
562#include "stringlib/count.h"
563#include "stringlib/find.h"
564#include "stringlib/find_max_char.h"
565#include "stringlib/localeutil.h"
566#include "stringlib/undef.h"
567
568#include "stringlib/ucs1lib.h"
569#include "stringlib/fastsearch.h"
570#include "stringlib/partition.h"
571#include "stringlib/split.h"
572#include "stringlib/count.h"
573#include "stringlib/find.h"
574#include "stringlib/find_max_char.h"
575#include "stringlib/localeutil.h"
576#include "stringlib/undef.h"
577
578#include "stringlib/ucs2lib.h"
579#include "stringlib/fastsearch.h"
580#include "stringlib/partition.h"
581#include "stringlib/split.h"
582#include "stringlib/count.h"
583#include "stringlib/find.h"
584#include "stringlib/find_max_char.h"
585#include "stringlib/localeutil.h"
586#include "stringlib/undef.h"
587
588#include "stringlib/ucs4lib.h"
589#include "stringlib/fastsearch.h"
590#include "stringlib/partition.h"
591#include "stringlib/split.h"
592#include "stringlib/count.h"
593#include "stringlib/find.h"
594#include "stringlib/find_max_char.h"
595#include "stringlib/localeutil.h"
596#include "stringlib/undef.h"
597
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200598#include "stringlib/unicodedefs.h"
599#include "stringlib/fastsearch.h"
600#include "stringlib/count.h"
601#include "stringlib/find.h"
Antoine Pitrou0a3229d2011-11-21 20:39:13 +0100602#include "stringlib/undef.h"
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200603
Guido van Rossumd57fd912000-03-10 22:53:23 +0000604/* --- Unicode Object ----------------------------------------------------- */
605
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200606static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +0200607fixup(PyObject *self, Py_UCS4 (*fixfct)(PyObject *s));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200608
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200609Py_LOCAL_INLINE(Py_ssize_t) findchar(void *s, int kind,
610 Py_ssize_t size, Py_UCS4 ch,
611 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200612{
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200613 int mode = (direction == 1) ? FAST_SEARCH : FAST_RSEARCH;
614
615 switch (kind) {
616 case PyUnicode_1BYTE_KIND:
617 {
618 Py_UCS1 ch1 = (Py_UCS1) ch;
619 if (ch1 == ch)
620 return ucs1lib_fastsearch((Py_UCS1 *) s, size, &ch1, 1, 0, mode);
621 else
622 return -1;
623 }
624 case PyUnicode_2BYTE_KIND:
625 {
626 Py_UCS2 ch2 = (Py_UCS2) ch;
627 if (ch2 == ch)
628 return ucs2lib_fastsearch((Py_UCS2 *) s, size, &ch2, 1, 0, mode);
629 else
630 return -1;
631 }
632 case PyUnicode_4BYTE_KIND:
633 return ucs4lib_fastsearch((Py_UCS4 *) s, size, &ch, 1, 0, mode);
634 default:
635 assert(0);
636 return -1;
Victor Stinner9e7a1bc2011-10-13 00:18:12 +0200637 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200638}
639
Victor Stinnerfe226c02011-10-03 03:52:20 +0200640static PyObject*
641resize_compact(PyObject *unicode, Py_ssize_t length)
642{
643 Py_ssize_t char_size;
644 Py_ssize_t struct_size;
645 Py_ssize_t new_size;
646 int share_wstr;
Victor Stinner84def372011-12-11 20:04:56 +0100647 PyObject *new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200648 assert(PyUnicode_IS_READY(unicode));
Victor Stinner488fa492011-12-12 00:01:39 +0100649 assert(PyUnicode_IS_COMPACT(unicode));
650
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200651 char_size = PyUnicode_KIND(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100652 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerfe226c02011-10-03 03:52:20 +0200653 struct_size = sizeof(PyASCIIObject);
654 else
655 struct_size = sizeof(PyCompactUnicodeObject);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200656 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200657
Victor Stinnerfe226c02011-10-03 03:52:20 +0200658 if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
659 PyErr_NoMemory();
660 return NULL;
661 }
662 new_size = (struct_size + (length + 1) * char_size);
663
Victor Stinner84def372011-12-11 20:04:56 +0100664 _Py_DEC_REFTOTAL;
665 _Py_ForgetReference(unicode);
666
667 new_unicode = (PyObject *)PyObject_REALLOC((char *)unicode, new_size);
668 if (new_unicode == NULL) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100669 _Py_NewReference(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200670 PyErr_NoMemory();
671 return NULL;
672 }
Victor Stinner84def372011-12-11 20:04:56 +0100673 unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200674 _Py_NewReference(unicode);
Victor Stinner84def372011-12-11 20:04:56 +0100675
Victor Stinnerfe226c02011-10-03 03:52:20 +0200676 _PyUnicode_LENGTH(unicode) = length;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200677 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200678 _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100679 if (!PyUnicode_IS_ASCII(unicode))
Victor Stinnerc379ead2011-10-03 12:52:27 +0200680 _PyUnicode_WSTR_LENGTH(unicode) = length;
681 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200682 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
683 length, 0);
684 return unicode;
685}
686
Alexander Belopolsky40018472011-02-26 01:02:56 +0000687static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200688resize_inplace(PyObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000689{
Victor Stinner95663112011-10-04 01:03:50 +0200690 wchar_t *wstr;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100691 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200692 assert(!PyUnicode_IS_COMPACT(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200693 assert(Py_REFCNT(unicode) == 1);
Tim Petersced69f82003-09-16 20:30:58 +0000694
Victor Stinnerfe226c02011-10-03 03:52:20 +0200695 if (PyUnicode_IS_READY(unicode)) {
696 Py_ssize_t char_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200697 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200698 void *data;
699
700 data = _PyUnicode_DATA_ANY(unicode);
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200701 char_size = PyUnicode_KIND(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200702 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
703 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200704
705 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
706 PyErr_NoMemory();
707 return -1;
708 }
709 new_size = (length + 1) * char_size;
710
Victor Stinner7a9105a2011-12-12 00:13:42 +0100711 if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
712 {
713 PyObject_DEL(_PyUnicode_UTF8(unicode));
714 _PyUnicode_UTF8(unicode) = NULL;
715 _PyUnicode_UTF8_LENGTH(unicode) = 0;
716 }
717
Victor Stinnerfe226c02011-10-03 03:52:20 +0200718 data = (PyObject *)PyObject_REALLOC(data, new_size);
719 if (data == NULL) {
720 PyErr_NoMemory();
721 return -1;
722 }
723 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200724 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200725 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200726 _PyUnicode_WSTR_LENGTH(unicode) = length;
727 }
728 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200729 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200730 _PyUnicode_UTF8_LENGTH(unicode) = length;
731 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200732 _PyUnicode_LENGTH(unicode) = length;
733 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
Victor Stinner95663112011-10-04 01:03:50 +0200734 if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200735 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200736 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200737 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200738 }
Victor Stinner95663112011-10-04 01:03:50 +0200739 assert(_PyUnicode_WSTR(unicode) != NULL);
740
741 /* check for integer overflow */
742 if (length > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
743 PyErr_NoMemory();
744 return -1;
745 }
Victor Stinner7a9105a2011-12-12 00:13:42 +0100746 new_size = sizeof(wchar_t) * (length + 1);
Victor Stinner95663112011-10-04 01:03:50 +0200747 wstr = _PyUnicode_WSTR(unicode);
Victor Stinner7a9105a2011-12-12 00:13:42 +0100748 wstr = PyObject_REALLOC(wstr, new_size);
Victor Stinner95663112011-10-04 01:03:50 +0200749 if (!wstr) {
750 PyErr_NoMemory();
751 return -1;
752 }
753 _PyUnicode_WSTR(unicode) = wstr;
754 _PyUnicode_WSTR(unicode)[length] = 0;
755 _PyUnicode_WSTR_LENGTH(unicode) = length;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200756 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000757 return 0;
758}
759
Victor Stinnerfe226c02011-10-03 03:52:20 +0200760static PyObject*
761resize_copy(PyObject *unicode, Py_ssize_t length)
762{
763 Py_ssize_t copy_length;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100764 if (_PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200765 PyObject *copy;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100766
Benjamin Petersonbac79492012-01-14 13:34:47 -0500767 if (PyUnicode_READY(unicode) == -1)
Victor Stinner7a9105a2011-12-12 00:13:42 +0100768 return NULL;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200769
770 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
771 if (copy == NULL)
772 return NULL;
773
774 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200775 copy_characters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200776 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +0200777 }
778 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200779 PyObject *w;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100780
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200781 w = (PyObject*)_PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200782 if (w == NULL)
783 return NULL;
784 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
785 copy_length = Py_MIN(copy_length, length);
786 Py_UNICODE_COPY(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
787 copy_length);
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200788 return w;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200789 }
790}
791
Guido van Rossumd57fd912000-03-10 22:53:23 +0000792/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +0000793 Ux0000 terminated; some code (e.g. new_identifier)
794 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000795
796 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +0000797 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000798
799*/
800
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200801#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +0200802static int unicode_old_new_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200803#endif
804
Alexander Belopolsky40018472011-02-26 01:02:56 +0000805static PyUnicodeObject *
806_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000807{
808 register PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200809 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000810
Thomas Wouters477c8d52006-05-27 19:21:47 +0000811 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +0000812 if (length == 0 && unicode_empty != NULL) {
813 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200814 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000815 }
816
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000817 /* Ensure we won't overflow the size. */
818 if (length > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
819 return (PyUnicodeObject *)PyErr_NoMemory();
820 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200821 if (length < 0) {
822 PyErr_SetString(PyExc_SystemError,
823 "Negative size passed to _PyUnicode_New");
824 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000825 }
826
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200827#ifdef Py_DEBUG
828 ++unicode_old_new_calls;
829#endif
830
831 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
832 if (unicode == NULL)
833 return NULL;
834 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
835 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
836 if (!_PyUnicode_WSTR(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100837 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +0000838 PyErr_NoMemory();
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100839 return NULL;
Guido van Rossum3c1bb802000-04-27 20:13:50 +0000840 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200841
Jeremy Hyltond8082792003-09-16 19:41:39 +0000842 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +0000843 * the caller fails before initializing str -- unicode_resize()
844 * reads str[0], and the Keep-Alive optimization can keep memory
845 * allocated for str alive across a call to unicode_dealloc(unicode).
846 * We don't want unicode_resize to read uninitialized memory in
847 * that case.
848 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200849 _PyUnicode_WSTR(unicode)[0] = 0;
850 _PyUnicode_WSTR(unicode)[length] = 0;
851 _PyUnicode_WSTR_LENGTH(unicode) = length;
852 _PyUnicode_HASH(unicode) = -1;
853 _PyUnicode_STATE(unicode).interned = 0;
854 _PyUnicode_STATE(unicode).kind = 0;
855 _PyUnicode_STATE(unicode).compact = 0;
856 _PyUnicode_STATE(unicode).ready = 0;
857 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +0200858 _PyUnicode_DATA_ANY(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200859 _PyUnicode_LENGTH(unicode) = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200860 _PyUnicode_UTF8(unicode) = NULL;
861 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner7931d9a2011-11-04 00:22:48 +0100862 assert(_PyUnicode_CheckConsistency((PyObject *)unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000863 return unicode;
864}
865
Victor Stinnerf42dc442011-10-02 23:33:16 +0200866static const char*
867unicode_kind_name(PyObject *unicode)
868{
Victor Stinner42dfd712011-10-03 14:41:45 +0200869 /* don't check consistency: unicode_kind_name() is called from
870 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +0200871 if (!PyUnicode_IS_COMPACT(unicode))
872 {
873 if (!PyUnicode_IS_READY(unicode))
874 return "wstr";
Benjamin Petersonead6b532011-12-20 17:23:42 -0600875 switch (PyUnicode_KIND(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200876 {
877 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200878 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200879 return "legacy ascii";
880 else
881 return "legacy latin1";
882 case PyUnicode_2BYTE_KIND:
883 return "legacy UCS2";
884 case PyUnicode_4BYTE_KIND:
885 return "legacy UCS4";
886 default:
887 return "<legacy invalid kind>";
888 }
889 }
890 assert(PyUnicode_IS_READY(unicode));
Benjamin Petersonead6b532011-12-20 17:23:42 -0600891 switch (PyUnicode_KIND(unicode)) {
Victor Stinnerf42dc442011-10-02 23:33:16 +0200892 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200893 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200894 return "ascii";
895 else
Victor Stinnera3b334d2011-10-03 13:53:37 +0200896 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200897 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200898 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200899 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200900 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200901 default:
902 return "<invalid compact kind>";
903 }
904}
905
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200906#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +0200907static int unicode_new_new_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200908
909/* Functions wrapping macros for use in debugger */
910char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200911 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200912}
913
914void *_PyUnicode_compact_data(void *unicode) {
915 return _PyUnicode_COMPACT_DATA(unicode);
916}
917void *_PyUnicode_data(void *unicode){
918 printf("obj %p\n", unicode);
919 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
920 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
921 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
922 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
923 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
924 return PyUnicode_DATA(unicode);
925}
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200926
927void
928_PyUnicode_Dump(PyObject *op)
929{
930 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +0200931 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
932 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
933 void *data;
Victor Stinner0d60e872011-10-23 19:47:19 +0200934
Victor Stinnera849a4b2011-10-03 12:12:11 +0200935 if (ascii->state.compact)
Victor Stinner0d60e872011-10-23 19:47:19 +0200936 {
937 if (ascii->state.ascii)
938 data = (ascii + 1);
939 else
940 data = (compact + 1);
941 }
Victor Stinnera849a4b2011-10-03 12:12:11 +0200942 else
943 data = unicode->data.any;
Victor Stinner0d60e872011-10-23 19:47:19 +0200944 printf("%s: len=%zu, ",unicode_kind_name(op), ascii->length);
945
Victor Stinnera849a4b2011-10-03 12:12:11 +0200946 if (ascii->wstr == data)
947 printf("shared ");
948 printf("wstr=%p", ascii->wstr);
Victor Stinner0d60e872011-10-23 19:47:19 +0200949
Victor Stinnera3b334d2011-10-03 13:53:37 +0200950 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinnera849a4b2011-10-03 12:12:11 +0200951 printf(" (%zu), ", compact->wstr_length);
952 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
953 printf("shared ");
954 printf("utf8=%p (%zu)", compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200955 }
Victor Stinnera849a4b2011-10-03 12:12:11 +0200956 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200957}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200958#endif
959
960PyObject *
961PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
962{
963 PyObject *obj;
964 PyCompactUnicodeObject *unicode;
965 void *data;
966 int kind_state;
Victor Stinner9e9d6892011-10-04 01:02:02 +0200967 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200968 Py_ssize_t char_size;
969 Py_ssize_t struct_size;
970
971 /* Optimization for empty strings */
972 if (size == 0 && unicode_empty != NULL) {
973 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200974 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200975 }
976
977#ifdef Py_DEBUG
978 ++unicode_new_new_calls;
979#endif
980
Victor Stinner9e9d6892011-10-04 01:02:02 +0200981 is_ascii = 0;
982 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200983 struct_size = sizeof(PyCompactUnicodeObject);
984 if (maxchar < 128) {
985 kind_state = PyUnicode_1BYTE_KIND;
986 char_size = 1;
987 is_ascii = 1;
988 struct_size = sizeof(PyASCIIObject);
989 }
990 else if (maxchar < 256) {
991 kind_state = PyUnicode_1BYTE_KIND;
992 char_size = 1;
993 }
994 else if (maxchar < 65536) {
995 kind_state = PyUnicode_2BYTE_KIND;
996 char_size = 2;
997 if (sizeof(wchar_t) == 2)
998 is_sharing = 1;
999 }
1000 else {
Victor Stinnerc9590ad2012-03-04 01:34:37 +01001001 if (maxchar > MAX_UNICODE) {
1002 PyErr_SetString(PyExc_SystemError,
1003 "invalid maximum character passed to PyUnicode_New");
1004 return NULL;
1005 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001006 kind_state = PyUnicode_4BYTE_KIND;
1007 char_size = 4;
1008 if (sizeof(wchar_t) == 4)
1009 is_sharing = 1;
1010 }
1011
1012 /* Ensure we won't overflow the size. */
1013 if (size < 0) {
1014 PyErr_SetString(PyExc_SystemError,
1015 "Negative size passed to PyUnicode_New");
1016 return NULL;
1017 }
1018 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
1019 return PyErr_NoMemory();
1020
1021 /* Duplicated allocation code from _PyObject_New() instead of a call to
1022 * PyObject_New() so we are able to allocate space for the object and
1023 * it's data buffer.
1024 */
1025 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
1026 if (obj == NULL)
1027 return PyErr_NoMemory();
1028 obj = PyObject_INIT(obj, &PyUnicode_Type);
1029 if (obj == NULL)
1030 return NULL;
1031
1032 unicode = (PyCompactUnicodeObject *)obj;
1033 if (is_ascii)
1034 data = ((PyASCIIObject*)obj) + 1;
1035 else
1036 data = unicode + 1;
1037 _PyUnicode_LENGTH(unicode) = size;
1038 _PyUnicode_HASH(unicode) = -1;
1039 _PyUnicode_STATE(unicode).interned = 0;
1040 _PyUnicode_STATE(unicode).kind = kind_state;
1041 _PyUnicode_STATE(unicode).compact = 1;
1042 _PyUnicode_STATE(unicode).ready = 1;
1043 _PyUnicode_STATE(unicode).ascii = is_ascii;
1044 if (is_ascii) {
1045 ((char*)data)[size] = 0;
1046 _PyUnicode_WSTR(unicode) = NULL;
1047 }
1048 else if (kind_state == PyUnicode_1BYTE_KIND) {
1049 ((char*)data)[size] = 0;
1050 _PyUnicode_WSTR(unicode) = NULL;
1051 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001052 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001053 unicode->utf8_length = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001054 }
1055 else {
1056 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001057 unicode->utf8_length = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001058 if (kind_state == PyUnicode_2BYTE_KIND)
1059 ((Py_UCS2*)data)[size] = 0;
1060 else /* kind_state == PyUnicode_4BYTE_KIND */
1061 ((Py_UCS4*)data)[size] = 0;
1062 if (is_sharing) {
1063 _PyUnicode_WSTR_LENGTH(unicode) = size;
1064 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
1065 }
1066 else {
1067 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1068 _PyUnicode_WSTR(unicode) = NULL;
1069 }
1070 }
Victor Stinner7931d9a2011-11-04 00:22:48 +01001071 assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001072 return obj;
1073}
1074
1075#if SIZEOF_WCHAR_T == 2
1076/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
1077 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +02001078 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001079
1080 This function assumes that unicode can hold one more code point than wstr
1081 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001082static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001083unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001084 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001085{
1086 const wchar_t *iter;
1087 Py_UCS4 *ucs4_out;
1088
Victor Stinner910337b2011-10-03 03:20:16 +02001089 assert(unicode != NULL);
1090 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001091 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1092 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
1093
1094 for (iter = begin; iter < end; ) {
1095 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1096 _PyUnicode_GET_LENGTH(unicode)));
Victor Stinner551ac952011-11-29 22:58:13 +01001097 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1098 && (iter+1) < end
1099 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001100 {
Victor Stinner551ac952011-11-29 22:58:13 +01001101 *ucs4_out++ = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001102 iter += 2;
1103 }
1104 else {
1105 *ucs4_out++ = *iter;
1106 iter++;
1107 }
1108 }
1109 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1110 _PyUnicode_GET_LENGTH(unicode)));
1111
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001112}
1113#endif
1114
Victor Stinnercd9950f2011-10-02 00:34:53 +02001115static int
Victor Stinner488fa492011-12-12 00:01:39 +01001116unicode_check_modifiable(PyObject *unicode)
Victor Stinnercd9950f2011-10-02 00:34:53 +02001117{
Victor Stinner488fa492011-12-12 00:01:39 +01001118 if (!unicode_modifiable(unicode)) {
Victor Stinner01698042011-10-04 00:04:26 +02001119 PyErr_SetString(PyExc_SystemError,
Victor Stinner488fa492011-12-12 00:01:39 +01001120 "Cannot modify a string currently used");
Victor Stinnercd9950f2011-10-02 00:34:53 +02001121 return -1;
1122 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02001123 return 0;
1124}
1125
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001126static int
1127_copy_characters(PyObject *to, Py_ssize_t to_start,
1128 PyObject *from, Py_ssize_t from_start,
1129 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001130{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001131 unsigned int from_kind, to_kind;
1132 void *from_data, *to_data;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001133 int fast;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001134
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001135 assert(PyUnicode_Check(from));
1136 assert(PyUnicode_Check(to));
1137 assert(PyUnicode_IS_READY(from));
1138 assert(PyUnicode_IS_READY(to));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001139
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001140 assert(PyUnicode_GET_LENGTH(from) >= how_many);
1141 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1142 assert(0 <= how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001143
Victor Stinnerf5ca1a22011-09-28 23:54:59 +02001144 if (how_many == 0)
1145 return 0;
1146
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001147 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001148 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001149 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001150 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001151
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001152#ifdef Py_DEBUG
1153 if (!check_maxchar
1154 && (from_kind > to_kind
1155 || (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001156 {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001157 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1158 Py_UCS4 ch;
1159 Py_ssize_t i;
1160 for (i=0; i < how_many; i++) {
1161 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1162 assert(ch <= to_maxchar);
1163 }
1164 }
1165#endif
1166 fast = (from_kind == to_kind);
1167 if (check_maxchar
1168 && (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to)))
1169 {
1170 /* deny latin1 => ascii */
1171 fast = 0;
1172 }
1173
1174 if (fast) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001175 Py_MEMCPY((char*)to_data + to_kind * to_start,
1176 (char*)from_data + from_kind * from_start,
1177 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001178 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001179 else if (from_kind == PyUnicode_1BYTE_KIND
1180 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001181 {
1182 _PyUnicode_CONVERT_BYTES(
1183 Py_UCS1, Py_UCS2,
1184 PyUnicode_1BYTE_DATA(from) + from_start,
1185 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1186 PyUnicode_2BYTE_DATA(to) + to_start
1187 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001188 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001189 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001190 && to_kind == PyUnicode_4BYTE_KIND)
1191 {
1192 _PyUnicode_CONVERT_BYTES(
1193 Py_UCS1, Py_UCS4,
1194 PyUnicode_1BYTE_DATA(from) + from_start,
1195 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1196 PyUnicode_4BYTE_DATA(to) + to_start
1197 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001198 }
1199 else if (from_kind == PyUnicode_2BYTE_KIND
1200 && to_kind == PyUnicode_4BYTE_KIND)
1201 {
1202 _PyUnicode_CONVERT_BYTES(
1203 Py_UCS2, Py_UCS4,
1204 PyUnicode_2BYTE_DATA(from) + from_start,
1205 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1206 PyUnicode_4BYTE_DATA(to) + to_start
1207 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001208 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001209 else {
Victor Stinnerf42dc442011-10-02 23:33:16 +02001210 /* check if max_char(from substring) <= max_char(to) */
1211 if (from_kind > to_kind
1212 /* latin1 => ascii */
Victor Stinnerb9275c12011-10-05 14:01:42 +02001213 || (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to)))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001214 {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001215 /* slow path to check for character overflow */
1216 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001217 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001218 Py_ssize_t i;
1219
Victor Stinner56c161a2011-10-06 02:47:11 +02001220#ifdef Py_DEBUG
Victor Stinnera0702ab2011-09-29 14:14:38 +02001221 for (i=0; i < how_many; i++) {
1222 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinner56c161a2011-10-06 02:47:11 +02001223 assert(ch <= to_maxchar);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001224 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1225 }
Victor Stinner56c161a2011-10-06 02:47:11 +02001226#else
1227 if (!check_maxchar) {
1228 for (i=0; i < how_many; i++) {
1229 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1230 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1231 }
1232 }
1233 else {
1234 for (i=0; i < how_many; i++) {
1235 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1236 if (ch > to_maxchar)
1237 return 1;
1238 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1239 }
1240 }
1241#endif
Victor Stinnera0702ab2011-09-29 14:14:38 +02001242 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001243 else {
Victor Stinner56c161a2011-10-06 02:47:11 +02001244 assert(0 && "inconsistent state");
1245 return 1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001246 }
1247 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001248 return 0;
1249}
1250
1251static void
1252copy_characters(PyObject *to, Py_ssize_t to_start,
1253 PyObject *from, Py_ssize_t from_start,
1254 Py_ssize_t how_many)
1255{
1256 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1257}
1258
1259Py_ssize_t
1260PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1261 PyObject *from, Py_ssize_t from_start,
1262 Py_ssize_t how_many)
1263{
1264 int err;
1265
1266 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1267 PyErr_BadInternalCall();
1268 return -1;
1269 }
1270
Benjamin Petersonbac79492012-01-14 13:34:47 -05001271 if (PyUnicode_READY(from) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001272 return -1;
Benjamin Petersonbac79492012-01-14 13:34:47 -05001273 if (PyUnicode_READY(to) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001274 return -1;
1275
1276 how_many = Py_MIN(PyUnicode_GET_LENGTH(from), how_many);
1277 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1278 PyErr_Format(PyExc_SystemError,
1279 "Cannot write %zi characters at %zi "
1280 "in a string of %zi characters",
1281 how_many, to_start, PyUnicode_GET_LENGTH(to));
1282 return -1;
1283 }
1284
1285 if (how_many == 0)
1286 return 0;
1287
Victor Stinner488fa492011-12-12 00:01:39 +01001288 if (unicode_check_modifiable(to))
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001289 return -1;
1290
1291 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1292 if (err) {
1293 PyErr_Format(PyExc_SystemError,
1294 "Cannot copy %s characters "
1295 "into a string of %s characters",
1296 unicode_kind_name(from),
1297 unicode_kind_name(to));
1298 return -1;
1299 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001300 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001301}
1302
Victor Stinner17222162011-09-28 22:15:37 +02001303/* Find the maximum code point and count the number of surrogate pairs so a
1304 correct string length can be computed before converting a string to UCS4.
1305 This function counts single surrogates as a character and not as a pair.
1306
1307 Return 0 on success, or -1 on error. */
1308static int
1309find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1310 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001311{
1312 const wchar_t *iter;
Victor Stinner8faf8212011-12-08 22:14:11 +01001313 Py_UCS4 ch;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001314
Victor Stinnerc53be962011-10-02 21:33:54 +02001315 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001316 *num_surrogates = 0;
1317 *maxchar = 0;
1318
1319 for (iter = begin; iter < end; ) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001320#if SIZEOF_WCHAR_T == 2
Victor Stinnerca4f2072011-11-22 03:38:40 +01001321 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1322 && (iter+1) < end
1323 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001324 {
Victor Stinner8faf8212011-12-08 22:14:11 +01001325 ch = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001326 ++(*num_surrogates);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001327 iter += 2;
1328 }
1329 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001330#endif
Victor Stinner8faf8212011-12-08 22:14:11 +01001331 {
1332 ch = *iter;
1333 iter++;
1334 }
1335 if (ch > *maxchar) {
1336 *maxchar = ch;
1337 if (*maxchar > MAX_UNICODE) {
1338 PyErr_Format(PyExc_ValueError,
1339 "character U+%x is not in range [U+0000; U+10ffff]",
1340 ch);
1341 return -1;
1342 }
1343 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001344 }
1345 return 0;
1346}
1347
1348#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +02001349static int unicode_ready_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001350#endif
1351
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001352int
1353_PyUnicode_Ready(PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001354{
1355 wchar_t *end;
1356 Py_UCS4 maxchar = 0;
1357 Py_ssize_t num_surrogates;
1358#if SIZEOF_WCHAR_T == 2
1359 Py_ssize_t length_wo_surrogates;
1360#endif
1361
Georg Brandl7597add2011-10-05 16:36:47 +02001362 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001363 strings were created using _PyObject_New() and where no canonical
1364 representation (the str field) has been set yet aka strings
1365 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001366 assert(_PyUnicode_CHECK(unicode));
1367 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001368 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001369 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001370 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001371 /* Actually, it should neither be interned nor be anything else: */
1372 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001373
1374#ifdef Py_DEBUG
1375 ++unicode_ready_calls;
1376#endif
1377
1378 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001379 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001380 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001381 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001382
1383 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001384 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1385 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001386 PyErr_NoMemory();
1387 return -1;
1388 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001389 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001390 _PyUnicode_WSTR(unicode), end,
1391 PyUnicode_1BYTE_DATA(unicode));
1392 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1393 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1394 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1395 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001396 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001397 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001398 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001399 }
1400 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001401 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001402 _PyUnicode_UTF8(unicode) = NULL;
1403 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001404 }
1405 PyObject_FREE(_PyUnicode_WSTR(unicode));
1406 _PyUnicode_WSTR(unicode) = NULL;
1407 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1408 }
1409 /* In this case we might have to convert down from 4-byte native
1410 wchar_t to 2-byte unicode. */
1411 else if (maxchar < 65536) {
1412 assert(num_surrogates == 0 &&
1413 "FindMaxCharAndNumSurrogatePairs() messed up");
1414
Victor Stinner506f5922011-09-28 22:34:18 +02001415#if SIZEOF_WCHAR_T == 2
1416 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001417 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001418 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1419 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1420 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001421 _PyUnicode_UTF8(unicode) = NULL;
1422 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001423#else
1424 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001425 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001426 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001427 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001428 PyErr_NoMemory();
1429 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001430 }
Victor Stinner506f5922011-09-28 22:34:18 +02001431 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1432 _PyUnicode_WSTR(unicode), end,
1433 PyUnicode_2BYTE_DATA(unicode));
1434 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1435 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1436 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001437 _PyUnicode_UTF8(unicode) = NULL;
1438 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001439 PyObject_FREE(_PyUnicode_WSTR(unicode));
1440 _PyUnicode_WSTR(unicode) = NULL;
1441 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1442#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001443 }
1444 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1445 else {
1446#if SIZEOF_WCHAR_T == 2
1447 /* in case the native representation is 2-bytes, we need to allocate a
1448 new normalized 4-byte version. */
1449 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001450 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1451 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001452 PyErr_NoMemory();
1453 return -1;
1454 }
1455 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1456 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001457 _PyUnicode_UTF8(unicode) = NULL;
1458 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001459 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1460 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001461 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001462 PyObject_FREE(_PyUnicode_WSTR(unicode));
1463 _PyUnicode_WSTR(unicode) = NULL;
1464 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1465#else
1466 assert(num_surrogates == 0);
1467
Victor Stinnerc3c74152011-10-02 20:39:55 +02001468 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001469 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001470 _PyUnicode_UTF8(unicode) = NULL;
1471 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001472 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1473#endif
1474 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1475 }
1476 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001477 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001478 return 0;
1479}
1480
Alexander Belopolsky40018472011-02-26 01:02:56 +00001481static void
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001482unicode_dealloc(register PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001483{
Walter Dörwald16807132007-05-25 13:52:07 +00001484 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001485 case SSTATE_NOT_INTERNED:
1486 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001487
Benjamin Peterson29060642009-01-31 22:14:21 +00001488 case SSTATE_INTERNED_MORTAL:
1489 /* revive dead object temporarily for DelItem */
1490 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001491 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001492 Py_FatalError(
1493 "deletion of interned string failed");
1494 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001495
Benjamin Peterson29060642009-01-31 22:14:21 +00001496 case SSTATE_INTERNED_IMMORTAL:
1497 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001498
Benjamin Peterson29060642009-01-31 22:14:21 +00001499 default:
1500 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001501 }
1502
Victor Stinner03490912011-10-03 23:45:12 +02001503 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001504 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001505 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001506 PyObject_DEL(_PyUnicode_UTF8(unicode));
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001507 if (!PyUnicode_IS_COMPACT(unicode) && _PyUnicode_DATA_ANY(unicode))
1508 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001509
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001510 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001511}
1512
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001513#ifdef Py_DEBUG
1514static int
1515unicode_is_singleton(PyObject *unicode)
1516{
1517 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1518 if (unicode == unicode_empty)
1519 return 1;
1520 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1521 {
1522 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1523 if (ch < 256 && unicode_latin1[ch] == unicode)
1524 return 1;
1525 }
1526 return 0;
1527}
1528#endif
1529
Alexander Belopolsky40018472011-02-26 01:02:56 +00001530static int
Victor Stinner488fa492011-12-12 00:01:39 +01001531unicode_modifiable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001532{
Victor Stinner488fa492011-12-12 00:01:39 +01001533 assert(_PyUnicode_CHECK(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001534 if (Py_REFCNT(unicode) != 1)
1535 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001536 if (_PyUnicode_HASH(unicode) != -1)
1537 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001538 if (PyUnicode_CHECK_INTERNED(unicode))
1539 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001540 if (!PyUnicode_CheckExact(unicode))
1541 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001542#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001543 /* singleton refcount is greater than 1 */
1544 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001545#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001546 return 1;
1547}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001548
Victor Stinnerfe226c02011-10-03 03:52:20 +02001549static int
1550unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1551{
1552 PyObject *unicode;
1553 Py_ssize_t old_length;
1554
1555 assert(p_unicode != NULL);
1556 unicode = *p_unicode;
1557
1558 assert(unicode != NULL);
1559 assert(PyUnicode_Check(unicode));
1560 assert(0 <= length);
1561
Victor Stinner910337b2011-10-03 03:20:16 +02001562 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001563 old_length = PyUnicode_WSTR_LENGTH(unicode);
1564 else
1565 old_length = PyUnicode_GET_LENGTH(unicode);
1566 if (old_length == length)
1567 return 0;
1568
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001569 if (length == 0) {
1570 Py_DECREF(*p_unicode);
1571 *p_unicode = unicode_empty;
1572 Py_INCREF(*p_unicode);
1573 return 0;
1574 }
1575
Victor Stinner488fa492011-12-12 00:01:39 +01001576 if (!unicode_modifiable(unicode)) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001577 PyObject *copy = resize_copy(unicode, length);
1578 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001579 return -1;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001580 Py_DECREF(*p_unicode);
1581 *p_unicode = copy;
Benjamin Peterson29060642009-01-31 22:14:21 +00001582 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001583 }
1584
Victor Stinnerfe226c02011-10-03 03:52:20 +02001585 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001586 PyObject *new_unicode = resize_compact(unicode, length);
1587 if (new_unicode == NULL)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001588 return -1;
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001589 *p_unicode = new_unicode;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001590 assert(_PyUnicode_CheckConsistency(*p_unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001591 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001592 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001593 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001594}
1595
Alexander Belopolsky40018472011-02-26 01:02:56 +00001596int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001597PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001598{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001599 PyObject *unicode;
1600 if (p_unicode == NULL) {
1601 PyErr_BadInternalCall();
1602 return -1;
1603 }
1604 unicode = *p_unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001605 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001606 {
1607 PyErr_BadInternalCall();
1608 return -1;
1609 }
1610 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001611}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001612
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001613static int
Victor Stinner0a045ef2011-11-09 00:02:42 +01001614unicode_widen(PyObject **p_unicode, unsigned int maxchar)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001615{
1616 PyObject *result;
1617 assert(PyUnicode_IS_READY(*p_unicode));
1618 if (maxchar <= PyUnicode_MAX_CHAR_VALUE(*p_unicode))
1619 return 0;
1620 result = PyUnicode_New(PyUnicode_GET_LENGTH(*p_unicode),
1621 maxchar);
1622 if (result == NULL)
1623 return -1;
1624 PyUnicode_CopyCharacters(result, 0, *p_unicode, 0,
1625 PyUnicode_GET_LENGTH(*p_unicode));
1626 Py_DECREF(*p_unicode);
1627 *p_unicode = result;
1628 return 0;
1629}
1630
1631static int
1632unicode_putchar(PyObject **p_unicode, Py_ssize_t *pos,
1633 Py_UCS4 ch)
1634{
Victor Stinner15e9ed22012-02-22 13:36:20 +01001635 assert(ch <= MAX_UNICODE);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001636 if (unicode_widen(p_unicode, ch) < 0)
1637 return -1;
1638 PyUnicode_WRITE(PyUnicode_KIND(*p_unicode),
1639 PyUnicode_DATA(*p_unicode),
1640 (*pos)++, ch);
1641 return 0;
1642}
1643
Victor Stinnerc5166102012-02-22 13:55:02 +01001644/* Copy a ASCII or latin1 char* string into a Python Unicode string.
1645 Return the length of the input string.
1646
Victor Stinnerb429d3b2012-02-22 21:22:20 +01001647 WARNING: The function doesn't copy the terminating null character and
1648 doesn't check the maximum character (may write a latin1 character in an
1649 ASCII string). */
Victor Stinnerc5166102012-02-22 13:55:02 +01001650static Py_ssize_t
1651unicode_write_cstr(PyObject *unicode, Py_ssize_t index, const char *str)
1652{
1653 enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
1654 void *data = PyUnicode_DATA(unicode);
1655
1656 switch (kind) {
1657 case PyUnicode_1BYTE_KIND: {
1658 Py_ssize_t len = strlen(str);
1659 assert(index + len <= PyUnicode_GET_LENGTH(unicode));
Antoine Pitrouba6bafc2012-02-22 16:41:50 +01001660 memcpy((char *) data + index, str, len);
Victor Stinnerc5166102012-02-22 13:55:02 +01001661 return len;
1662 }
1663 case PyUnicode_2BYTE_KIND: {
1664 Py_UCS2 *start = (Py_UCS2 *)data + index;
1665 Py_UCS2 *ucs2 = start;
1666 assert(index <= PyUnicode_GET_LENGTH(unicode));
1667
1668 for (; *str; ++ucs2, ++str)
1669 *ucs2 = (Py_UCS2)*str;
1670
1671 assert((ucs2 - start) <= PyUnicode_GET_LENGTH(unicode));
1672 return ucs2 - start;
1673 }
1674 default: {
1675 Py_UCS4 *start = (Py_UCS4 *)data + index;
1676 Py_UCS4 *ucs4 = start;
1677 assert(kind == PyUnicode_4BYTE_KIND);
1678 assert(index <= PyUnicode_GET_LENGTH(unicode));
1679
1680 for (; *str; ++ucs4, ++str)
1681 *ucs4 = (Py_UCS4)*str;
1682
1683 assert((ucs4 - start) <= PyUnicode_GET_LENGTH(unicode));
1684 return ucs4 - start;
1685 }
1686 }
1687}
1688
1689
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001690static PyObject*
1691get_latin1_char(unsigned char ch)
1692{
Victor Stinnera464fc12011-10-02 20:39:30 +02001693 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001694 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001695 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001696 if (!unicode)
1697 return NULL;
1698 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001699 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001700 unicode_latin1[ch] = unicode;
1701 }
1702 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001703 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001704}
1705
Alexander Belopolsky40018472011-02-26 01:02:56 +00001706PyObject *
1707PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001708{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001709 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001710 Py_UCS4 maxchar = 0;
1711 Py_ssize_t num_surrogates;
1712
1713 if (u == NULL)
1714 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001715
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001716 /* If the Unicode data is known at construction time, we can apply
1717 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001718
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001719 /* Optimization for empty strings */
1720 if (size == 0 && unicode_empty != NULL) {
1721 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001722 return unicode_empty;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001723 }
Tim Petersced69f82003-09-16 20:30:58 +00001724
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001725 /* Single character Unicode objects in the Latin-1 range are
1726 shared when using this constructor */
1727 if (size == 1 && *u < 256)
1728 return get_latin1_char((unsigned char)*u);
1729
1730 /* If not empty and not single character, copy the Unicode data
1731 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02001732 if (find_maxchar_surrogates(u, u + size,
1733 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001734 return NULL;
1735
Victor Stinner8faf8212011-12-08 22:14:11 +01001736 unicode = PyUnicode_New(size - num_surrogates, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001737 if (!unicode)
1738 return NULL;
1739
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001740 switch (PyUnicode_KIND(unicode)) {
1741 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001742 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001743 u, u + size, PyUnicode_1BYTE_DATA(unicode));
1744 break;
1745 case PyUnicode_2BYTE_KIND:
1746#if Py_UNICODE_SIZE == 2
1747 Py_MEMCPY(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
1748#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001749 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001750 u, u + size, PyUnicode_2BYTE_DATA(unicode));
1751#endif
1752 break;
1753 case PyUnicode_4BYTE_KIND:
1754#if SIZEOF_WCHAR_T == 2
1755 /* This is the only case which has to process surrogates, thus
1756 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001757 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001758#else
1759 assert(num_surrogates == 0);
1760 Py_MEMCPY(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
1761#endif
1762 break;
1763 default:
1764 assert(0 && "Impossible state");
1765 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001766
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001767 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001768}
1769
Alexander Belopolsky40018472011-02-26 01:02:56 +00001770PyObject *
1771PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001772{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001773 if (size < 0) {
1774 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00001775 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00001776 return NULL;
1777 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001778 if (u != NULL)
1779 return PyUnicode_DecodeUTF8Stateful(u, size, NULL, NULL);
1780 else
1781 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001782}
1783
Alexander Belopolsky40018472011-02-26 01:02:56 +00001784PyObject *
1785PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00001786{
1787 size_t size = strlen(u);
1788 if (size > PY_SSIZE_T_MAX) {
1789 PyErr_SetString(PyExc_OverflowError, "input too long");
1790 return NULL;
1791 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001792 return PyUnicode_DecodeUTF8Stateful(u, (Py_ssize_t)size, NULL, NULL);
Walter Dörwaldd2034312007-05-18 16:29:38 +00001793}
1794
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001795PyObject *
1796_PyUnicode_FromId(_Py_Identifier *id)
1797{
1798 if (!id->object) {
Victor Stinnerd1cd99b2012-02-07 23:05:55 +01001799 id->object = PyUnicode_DecodeUTF8Stateful(id->string,
1800 strlen(id->string),
1801 NULL, NULL);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001802 if (!id->object)
1803 return NULL;
1804 PyUnicode_InternInPlace(&id->object);
1805 assert(!id->next);
1806 id->next = static_strings;
1807 static_strings = id;
1808 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001809 return id->object;
1810}
1811
1812void
1813_PyUnicode_ClearStaticStrings()
1814{
1815 _Py_Identifier *i;
1816 for (i = static_strings; i; i = i->next) {
1817 Py_DECREF(i->object);
1818 i->object = NULL;
1819 i->next = NULL;
1820 }
1821}
1822
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001823/* Internal function, don't check maximum character */
1824
Victor Stinnere57b1c02011-09-28 22:20:48 +02001825static PyObject*
Victor Stinner0617b6e2011-10-05 23:26:01 +02001826unicode_fromascii(const unsigned char* s, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02001827{
Victor Stinner785938e2011-12-11 20:09:03 +01001828 PyObject *unicode;
Victor Stinnere6b2d442011-12-11 21:54:30 +01001829 if (size == 1) {
Victor Stinner0617b6e2011-10-05 23:26:01 +02001830#ifdef Py_DEBUG
Victor Stinnere6b2d442011-12-11 21:54:30 +01001831 assert(s[0] < 128);
Victor Stinner0617b6e2011-10-05 23:26:01 +02001832#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001833 return get_latin1_char(s[0]);
Victor Stinnere6b2d442011-12-11 21:54:30 +01001834 }
Victor Stinner785938e2011-12-11 20:09:03 +01001835 unicode = PyUnicode_New(size, 127);
1836 if (!unicode)
Victor Stinner702c7342011-10-05 13:50:52 +02001837 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01001838 memcpy(PyUnicode_1BYTE_DATA(unicode), s, size);
1839 assert(_PyUnicode_CheckConsistency(unicode, 1));
1840 return unicode;
Victor Stinner702c7342011-10-05 13:50:52 +02001841}
1842
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001843static Py_UCS4
1844kind_maxchar_limit(unsigned int kind)
1845{
Benjamin Petersonead6b532011-12-20 17:23:42 -06001846 switch (kind) {
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001847 case PyUnicode_1BYTE_KIND:
1848 return 0x80;
1849 case PyUnicode_2BYTE_KIND:
1850 return 0x100;
1851 case PyUnicode_4BYTE_KIND:
1852 return 0x10000;
1853 default:
1854 assert(0 && "invalid kind");
Victor Stinner8faf8212011-12-08 22:14:11 +01001855 return MAX_UNICODE;
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001856 }
1857}
1858
Victor Stinner702c7342011-10-05 13:50:52 +02001859static PyObject*
Victor Stinnere57b1c02011-09-28 22:20:48 +02001860_PyUnicode_FromUCS1(const unsigned char* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00001861{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001862 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001863 unsigned char max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001864
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001865 if (size == 0) {
1866 Py_INCREF(unicode_empty);
1867 return unicode_empty;
1868 }
1869 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001870 if (size == 1)
1871 return get_latin1_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001872
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001873 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001874 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001875 if (!res)
1876 return NULL;
1877 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001878 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001879 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001880}
1881
Victor Stinnere57b1c02011-09-28 22:20:48 +02001882static PyObject*
1883_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001884{
1885 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001886 Py_UCS2 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001887
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001888 if (size == 0) {
1889 Py_INCREF(unicode_empty);
1890 return unicode_empty;
1891 }
1892 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001893 if (size == 1 && u[0] < 256)
Victor Stinner4e101002011-10-11 23:27:52 +02001894 return get_latin1_char((unsigned char)u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001895
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001896 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001897 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001898 if (!res)
1899 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001900 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001901 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001902 else {
1903 _PyUnicode_CONVERT_BYTES(
1904 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
1905 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001906 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001907 return res;
1908}
1909
Victor Stinnere57b1c02011-09-28 22:20:48 +02001910static PyObject*
1911_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001912{
1913 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001914 Py_UCS4 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001915
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001916 if (size == 0) {
1917 Py_INCREF(unicode_empty);
1918 return unicode_empty;
1919 }
1920 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001921 if (size == 1 && u[0] < 256)
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001922 return get_latin1_char((unsigned char)u[0]);
1923
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001924 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001925 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001926 if (!res)
1927 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02001928 if (max_char < 256)
1929 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
1930 PyUnicode_1BYTE_DATA(res));
1931 else if (max_char < 0x10000)
1932 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
1933 PyUnicode_2BYTE_DATA(res));
1934 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001935 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001936 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001937 return res;
1938}
1939
1940PyObject*
1941PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
1942{
Victor Stinnercfed46e2011-11-22 01:29:14 +01001943 if (size < 0) {
1944 PyErr_SetString(PyExc_ValueError, "size must be positive");
1945 return NULL;
1946 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06001947 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001948 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001949 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001950 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001951 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001952 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001953 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001954 default:
Victor Stinnerb9275c12011-10-05 14:01:42 +02001955 PyErr_SetString(PyExc_SystemError, "invalid kind");
1956 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001957 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001958}
1959
Victor Stinner25a4b292011-10-06 12:31:55 +02001960/* Ensure that a string uses the most efficient storage, if it is not the
1961 case: create a new string with of the right kind. Write NULL into *p_unicode
1962 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02001963static void
Victor Stinner25a4b292011-10-06 12:31:55 +02001964unicode_adjust_maxchar(PyObject **p_unicode)
1965{
1966 PyObject *unicode, *copy;
1967 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001968 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02001969 unsigned int kind;
1970
1971 assert(p_unicode != NULL);
1972 unicode = *p_unicode;
1973 assert(PyUnicode_IS_READY(unicode));
1974 if (PyUnicode_IS_ASCII(unicode))
1975 return;
1976
1977 len = PyUnicode_GET_LENGTH(unicode);
1978 kind = PyUnicode_KIND(unicode);
1979 if (kind == PyUnicode_1BYTE_KIND) {
1980 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001981 max_char = ucs1lib_find_max_char(u, u + len);
1982 if (max_char >= 128)
1983 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001984 }
1985 else if (kind == PyUnicode_2BYTE_KIND) {
1986 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001987 max_char = ucs2lib_find_max_char(u, u + len);
1988 if (max_char >= 256)
1989 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001990 }
1991 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001992 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02001993 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001994 max_char = ucs4lib_find_max_char(u, u + len);
1995 if (max_char >= 0x10000)
1996 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001997 }
Victor Stinner25a4b292011-10-06 12:31:55 +02001998 copy = PyUnicode_New(len, max_char);
1999 copy_characters(copy, 0, unicode, 0, len);
2000 Py_DECREF(unicode);
2001 *p_unicode = copy;
2002}
2003
Victor Stinner034f6cf2011-09-30 02:26:44 +02002004PyObject*
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002005_PyUnicode_Copy(PyObject *unicode)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002006{
Victor Stinner87af4f22011-11-21 23:03:47 +01002007 Py_ssize_t length;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002008 PyObject *copy;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002009
Victor Stinner034f6cf2011-09-30 02:26:44 +02002010 if (!PyUnicode_Check(unicode)) {
2011 PyErr_BadInternalCall();
2012 return NULL;
2013 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05002014 if (PyUnicode_READY(unicode) == -1)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002015 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002016
Victor Stinner87af4f22011-11-21 23:03:47 +01002017 length = PyUnicode_GET_LENGTH(unicode);
2018 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002019 if (!copy)
2020 return NULL;
2021 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
2022
Victor Stinner87af4f22011-11-21 23:03:47 +01002023 Py_MEMCPY(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
2024 length * PyUnicode_KIND(unicode));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002025 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002026 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02002027}
2028
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002029
Victor Stinnerbc603d12011-10-02 01:00:40 +02002030/* Widen Unicode objects to larger buffers. Don't write terminating null
2031 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002032
2033void*
2034_PyUnicode_AsKind(PyObject *s, unsigned int kind)
2035{
Victor Stinnerbc603d12011-10-02 01:00:40 +02002036 Py_ssize_t len;
2037 void *result;
2038 unsigned int skind;
2039
Benjamin Petersonbac79492012-01-14 13:34:47 -05002040 if (PyUnicode_READY(s) == -1)
Victor Stinnerbc603d12011-10-02 01:00:40 +02002041 return NULL;
2042
2043 len = PyUnicode_GET_LENGTH(s);
2044 skind = PyUnicode_KIND(s);
2045 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02002046 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002047 return NULL;
2048 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002049 switch (kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02002050 case PyUnicode_2BYTE_KIND:
2051 result = PyMem_Malloc(len * sizeof(Py_UCS2));
2052 if (!result)
2053 return PyErr_NoMemory();
2054 assert(skind == PyUnicode_1BYTE_KIND);
2055 _PyUnicode_CONVERT_BYTES(
2056 Py_UCS1, Py_UCS2,
2057 PyUnicode_1BYTE_DATA(s),
2058 PyUnicode_1BYTE_DATA(s) + len,
2059 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002060 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002061 case PyUnicode_4BYTE_KIND:
2062 result = PyMem_Malloc(len * sizeof(Py_UCS4));
2063 if (!result)
2064 return PyErr_NoMemory();
2065 if (skind == PyUnicode_2BYTE_KIND) {
2066 _PyUnicode_CONVERT_BYTES(
2067 Py_UCS2, Py_UCS4,
2068 PyUnicode_2BYTE_DATA(s),
2069 PyUnicode_2BYTE_DATA(s) + len,
2070 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002071 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02002072 else {
2073 assert(skind == PyUnicode_1BYTE_KIND);
2074 _PyUnicode_CONVERT_BYTES(
2075 Py_UCS1, Py_UCS4,
2076 PyUnicode_1BYTE_DATA(s),
2077 PyUnicode_1BYTE_DATA(s) + len,
2078 result);
2079 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002080 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002081 default:
2082 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002083 }
Victor Stinner01698042011-10-04 00:04:26 +02002084 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002085 return NULL;
2086}
2087
2088static Py_UCS4*
2089as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2090 int copy_null)
2091{
2092 int kind;
2093 void *data;
2094 Py_ssize_t len, targetlen;
2095 if (PyUnicode_READY(string) == -1)
2096 return NULL;
2097 kind = PyUnicode_KIND(string);
2098 data = PyUnicode_DATA(string);
2099 len = PyUnicode_GET_LENGTH(string);
2100 targetlen = len;
2101 if (copy_null)
2102 targetlen++;
2103 if (!target) {
2104 if (PY_SSIZE_T_MAX / sizeof(Py_UCS4) < targetlen) {
2105 PyErr_NoMemory();
2106 return NULL;
2107 }
2108 target = PyMem_Malloc(targetlen * sizeof(Py_UCS4));
2109 if (!target) {
2110 PyErr_NoMemory();
2111 return NULL;
2112 }
2113 }
2114 else {
2115 if (targetsize < targetlen) {
2116 PyErr_Format(PyExc_SystemError,
2117 "string is longer than the buffer");
2118 if (copy_null && 0 < targetsize)
2119 target[0] = 0;
2120 return NULL;
2121 }
2122 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002123 if (kind == PyUnicode_1BYTE_KIND) {
2124 Py_UCS1 *start = (Py_UCS1 *) data;
2125 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002126 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002127 else if (kind == PyUnicode_2BYTE_KIND) {
2128 Py_UCS2 *start = (Py_UCS2 *) data;
2129 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2130 }
2131 else {
2132 assert(kind == PyUnicode_4BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002133 Py_MEMCPY(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002134 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002135 if (copy_null)
2136 target[len] = 0;
2137 return target;
2138}
2139
2140Py_UCS4*
2141PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2142 int copy_null)
2143{
Antoine Pitroude20b0b2011-11-10 21:47:38 +01002144 if (target == NULL || targetsize < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002145 PyErr_BadInternalCall();
2146 return NULL;
2147 }
2148 return as_ucs4(string, target, targetsize, copy_null);
2149}
2150
2151Py_UCS4*
2152PyUnicode_AsUCS4Copy(PyObject *string)
2153{
2154 return as_ucs4(string, NULL, 0, 1);
2155}
2156
2157#ifdef HAVE_WCHAR_H
Mark Dickinson081dfee2009-03-18 14:47:41 +00002158
Alexander Belopolsky40018472011-02-26 01:02:56 +00002159PyObject *
2160PyUnicode_FromWideChar(register const wchar_t *w, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002161{
Guido van Rossumd57fd912000-03-10 22:53:23 +00002162 if (w == NULL) {
Victor Stinner382955f2011-12-11 21:44:00 +01002163 if (size == 0) {
2164 Py_INCREF(unicode_empty);
2165 return unicode_empty;
2166 }
Benjamin Peterson29060642009-01-31 22:14:21 +00002167 PyErr_BadInternalCall();
2168 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002169 }
2170
Martin v. Löwis790465f2008-04-05 20:41:37 +00002171 if (size == -1) {
2172 size = wcslen(w);
2173 }
2174
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002175 return PyUnicode_FromUnicode(w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002176}
2177
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002178#endif /* HAVE_WCHAR_H */
Mark Dickinson081dfee2009-03-18 14:47:41 +00002179
Walter Dörwald346737f2007-05-31 10:44:43 +00002180static void
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002181makefmt(char *fmt, int longflag, int longlongflag, int size_tflag,
2182 int zeropad, int width, int precision, char c)
Walter Dörwald346737f2007-05-31 10:44:43 +00002183{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002184 *fmt++ = '%';
2185 if (width) {
2186 if (zeropad)
2187 *fmt++ = '0';
2188 fmt += sprintf(fmt, "%d", width);
2189 }
2190 if (precision)
2191 fmt += sprintf(fmt, ".%d", precision);
2192 if (longflag)
2193 *fmt++ = 'l';
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002194 else if (longlongflag) {
2195 /* longlongflag should only ever be nonzero on machines with
2196 HAVE_LONG_LONG defined */
2197#ifdef HAVE_LONG_LONG
2198 char *f = PY_FORMAT_LONG_LONG;
2199 while (*f)
2200 *fmt++ = *f++;
2201#else
2202 /* we shouldn't ever get here */
2203 assert(0);
2204 *fmt++ = 'l';
2205#endif
2206 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002207 else if (size_tflag) {
2208 char *f = PY_FORMAT_SIZE_T;
2209 while (*f)
2210 *fmt++ = *f++;
2211 }
2212 *fmt++ = c;
2213 *fmt = '\0';
Walter Dörwald346737f2007-05-31 10:44:43 +00002214}
2215
Victor Stinner96865452011-03-01 23:44:09 +00002216/* helper for PyUnicode_FromFormatV() */
2217
2218static const char*
2219parse_format_flags(const char *f,
2220 int *p_width, int *p_precision,
2221 int *p_longflag, int *p_longlongflag, int *p_size_tflag)
2222{
2223 int width, precision, longflag, longlongflag, size_tflag;
2224
2225 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
2226 f++;
2227 width = 0;
2228 while (Py_ISDIGIT((unsigned)*f))
2229 width = (width*10) + *f++ - '0';
2230 precision = 0;
2231 if (*f == '.') {
2232 f++;
2233 while (Py_ISDIGIT((unsigned)*f))
2234 precision = (precision*10) + *f++ - '0';
2235 if (*f == '%') {
2236 /* "%.3%s" => f points to "3" */
2237 f--;
2238 }
2239 }
2240 if (*f == '\0') {
2241 /* bogus format "%.1" => go backward, f points to "1" */
2242 f--;
2243 }
2244 if (p_width != NULL)
2245 *p_width = width;
2246 if (p_precision != NULL)
2247 *p_precision = precision;
2248
2249 /* Handle %ld, %lu, %lld and %llu. */
2250 longflag = 0;
2251 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002252 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002253
2254 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002255 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002256 longflag = 1;
2257 ++f;
2258 }
2259#ifdef HAVE_LONG_LONG
2260 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002261 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002262 longlongflag = 1;
2263 f += 2;
2264 }
2265#endif
2266 }
2267 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002268 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002269 size_tflag = 1;
2270 ++f;
2271 }
2272 if (p_longflag != NULL)
2273 *p_longflag = longflag;
2274 if (p_longlongflag != NULL)
2275 *p_longlongflag = longlongflag;
2276 if (p_size_tflag != NULL)
2277 *p_size_tflag = size_tflag;
2278 return f;
2279}
2280
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002281/* maximum number of characters required for output of %ld. 21 characters
2282 allows for 64-bit integers (in decimal) and an optional sign. */
2283#define MAX_LONG_CHARS 21
2284/* maximum number of characters required for output of %lld.
2285 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2286 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2287#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
2288
Walter Dörwaldd2034312007-05-18 16:29:38 +00002289PyObject *
2290PyUnicode_FromFormatV(const char *format, va_list vargs)
2291{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002292 va_list count;
2293 Py_ssize_t callcount = 0;
2294 PyObject **callresults = NULL;
2295 PyObject **callresult = NULL;
2296 Py_ssize_t n = 0;
2297 int width = 0;
2298 int precision = 0;
2299 int zeropad;
2300 const char* f;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002301 PyObject *string;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002302 /* used by sprintf */
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002303 char fmt[61]; /* should be enough for %0width.precisionlld */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002304 Py_UCS4 maxchar = 127; /* result is ASCII by default */
2305 Py_UCS4 argmaxchar;
2306 Py_ssize_t numbersize = 0;
2307 char *numberresults = NULL;
2308 char *numberresult = NULL;
2309 Py_ssize_t i;
2310 int kind;
2311 void *data;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002312
Victor Stinner4a2b7a12010-08-13 14:03:48 +00002313 Py_VA_COPY(count, vargs);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002314 /* step 1: count the number of %S/%R/%A/%s format specifications
2315 * (we call PyObject_Str()/PyObject_Repr()/PyObject_ASCII()/
2316 * PyUnicode_DecodeUTF8() for these objects once during step 3 and put the
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002317 * result in an array)
Georg Brandl7597add2011-10-05 16:36:47 +02002318 * also estimate a upper bound for all the number formats in the string,
2319 * numbers will be formatted in step 3 and be kept in a '\0'-separated
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002320 * buffer before putting everything together. */
Benjamin Peterson14339b62009-01-31 16:36:08 +00002321 for (f = format; *f; f++) {
2322 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002323 int longlongflag;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002324 /* skip width or width.precision (eg. "1.2" of "%1.2f") */
2325 f = parse_format_flags(f, &width, NULL, NULL, &longlongflag, NULL);
2326 if (*f == 's' || *f=='S' || *f=='R' || *f=='A' || *f=='V')
2327 ++callcount;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002328
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002329 else if (*f == 'd' || *f=='u' || *f=='i' || *f=='x' || *f=='p') {
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002330#ifdef HAVE_LONG_LONG
2331 if (longlongflag) {
2332 if (width < MAX_LONG_LONG_CHARS)
2333 width = MAX_LONG_LONG_CHARS;
2334 }
2335 else
2336#endif
2337 /* MAX_LONG_CHARS is enough to hold a 64-bit integer,
2338 including sign. Decimal takes the most space. This
2339 isn't enough for octal. If a width is specified we
2340 need more (which we allocate later). */
2341 if (width < MAX_LONG_CHARS)
2342 width = MAX_LONG_CHARS;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002343
2344 /* account for the size + '\0' to separate numbers
2345 inside of the numberresults buffer */
2346 numbersize += (width + 1);
2347 }
2348 }
2349 else if ((unsigned char)*f > 127) {
2350 PyErr_Format(PyExc_ValueError,
2351 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2352 "string, got a non-ASCII byte: 0x%02x",
2353 (unsigned char)*f);
2354 return NULL;
2355 }
2356 }
2357 /* step 2: allocate memory for the results of
2358 * PyObject_Str()/PyObject_Repr()/PyUnicode_DecodeUTF8() calls */
2359 if (callcount) {
2360 callresults = PyObject_Malloc(sizeof(PyObject *) * callcount);
2361 if (!callresults) {
2362 PyErr_NoMemory();
2363 return NULL;
2364 }
2365 callresult = callresults;
2366 }
2367 /* step 2.5: allocate memory for the results of formating numbers */
2368 if (numbersize) {
2369 numberresults = PyObject_Malloc(numbersize);
2370 if (!numberresults) {
2371 PyErr_NoMemory();
2372 goto fail;
2373 }
2374 numberresult = numberresults;
2375 }
2376
2377 /* step 3: format numbers and figure out how large a buffer we need */
2378 for (f = format; *f; f++) {
2379 if (*f == '%') {
2380 const char* p;
2381 int longflag;
2382 int longlongflag;
2383 int size_tflag;
2384 int numprinted;
2385
2386 p = f;
2387 zeropad = (f[1] == '0');
2388 f = parse_format_flags(f, &width, &precision,
2389 &longflag, &longlongflag, &size_tflag);
2390 switch (*f) {
2391 case 'c':
2392 {
2393 Py_UCS4 ordinal = va_arg(count, int);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002394 maxchar = Py_MAX(maxchar, ordinal);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002395 n++;
2396 break;
2397 }
2398 case '%':
2399 n++;
2400 break;
2401 case 'i':
2402 case 'd':
2403 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2404 width, precision, *f);
2405 if (longflag)
2406 numprinted = sprintf(numberresult, fmt,
2407 va_arg(count, long));
2408#ifdef HAVE_LONG_LONG
2409 else if (longlongflag)
2410 numprinted = sprintf(numberresult, fmt,
2411 va_arg(count, PY_LONG_LONG));
2412#endif
2413 else if (size_tflag)
2414 numprinted = sprintf(numberresult, fmt,
2415 va_arg(count, Py_ssize_t));
2416 else
2417 numprinted = sprintf(numberresult, fmt,
2418 va_arg(count, int));
2419 n += numprinted;
2420 /* advance by +1 to skip over the '\0' */
2421 numberresult += (numprinted + 1);
2422 assert(*(numberresult - 1) == '\0');
2423 assert(*(numberresult - 2) != '\0');
2424 assert(numprinted >= 0);
2425 assert(numberresult <= numberresults + numbersize);
2426 break;
2427 case 'u':
2428 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2429 width, precision, 'u');
2430 if (longflag)
2431 numprinted = sprintf(numberresult, fmt,
2432 va_arg(count, unsigned long));
2433#ifdef HAVE_LONG_LONG
2434 else if (longlongflag)
2435 numprinted = sprintf(numberresult, fmt,
2436 va_arg(count, unsigned PY_LONG_LONG));
2437#endif
2438 else if (size_tflag)
2439 numprinted = sprintf(numberresult, fmt,
2440 va_arg(count, size_t));
2441 else
2442 numprinted = sprintf(numberresult, fmt,
2443 va_arg(count, unsigned int));
2444 n += numprinted;
2445 numberresult += (numprinted + 1);
2446 assert(*(numberresult - 1) == '\0');
2447 assert(*(numberresult - 2) != '\0');
2448 assert(numprinted >= 0);
2449 assert(numberresult <= numberresults + numbersize);
2450 break;
2451 case 'x':
2452 makefmt(fmt, 0, 0, 0, zeropad, width, precision, 'x');
2453 numprinted = sprintf(numberresult, fmt, va_arg(count, int));
2454 n += numprinted;
2455 numberresult += (numprinted + 1);
2456 assert(*(numberresult - 1) == '\0');
2457 assert(*(numberresult - 2) != '\0');
2458 assert(numprinted >= 0);
2459 assert(numberresult <= numberresults + numbersize);
2460 break;
2461 case 'p':
2462 numprinted = sprintf(numberresult, "%p", va_arg(count, void*));
2463 /* %p is ill-defined: ensure leading 0x. */
2464 if (numberresult[1] == 'X')
2465 numberresult[1] = 'x';
2466 else if (numberresult[1] != 'x') {
2467 memmove(numberresult + 2, numberresult,
2468 strlen(numberresult) + 1);
2469 numberresult[0] = '0';
2470 numberresult[1] = 'x';
2471 numprinted += 2;
2472 }
2473 n += numprinted;
2474 numberresult += (numprinted + 1);
2475 assert(*(numberresult - 1) == '\0');
2476 assert(*(numberresult - 2) != '\0');
2477 assert(numprinted >= 0);
2478 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002479 break;
2480 case 's':
2481 {
2482 /* UTF-8 */
Georg Brandl780b2a62009-05-05 09:19:59 +00002483 const char *s = va_arg(count, const char*);
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002484 PyObject *str = PyUnicode_DecodeUTF8Stateful(s, strlen(s), "replace", NULL);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002485 if (!str)
2486 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002487 /* since PyUnicode_DecodeUTF8 returns already flexible
2488 unicode objects, there is no need to call ready on them */
2489 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002490 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002491 n += PyUnicode_GET_LENGTH(str);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002492 /* Remember the str and switch to the next slot */
2493 *callresult++ = str;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002494 break;
2495 }
2496 case 'U':
2497 {
2498 PyObject *obj = va_arg(count, PyObject *);
Victor Stinner910337b2011-10-03 03:20:16 +02002499 assert(obj && _PyUnicode_CHECK(obj));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002500 if (PyUnicode_READY(obj) == -1)
2501 goto fail;
2502 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002503 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002504 n += PyUnicode_GET_LENGTH(obj);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002505 break;
2506 }
2507 case 'V':
2508 {
2509 PyObject *obj = va_arg(count, PyObject *);
2510 const char *str = va_arg(count, const char *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002511 PyObject *str_obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002512 assert(obj || str);
Victor Stinner910337b2011-10-03 03:20:16 +02002513 assert(!obj || _PyUnicode_CHECK(obj));
Victor Stinner2512a8b2011-03-01 22:46:52 +00002514 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002515 if (PyUnicode_READY(obj) == -1)
2516 goto fail;
2517 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002518 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002519 n += PyUnicode_GET_LENGTH(obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002520 *callresult++ = NULL;
2521 }
2522 else {
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002523 str_obj = PyUnicode_DecodeUTF8Stateful(str, strlen(str), "replace", NULL);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002524 if (!str_obj)
2525 goto fail;
Benjamin Petersonbac79492012-01-14 13:34:47 -05002526 if (PyUnicode_READY(str_obj) == -1) {
Victor Stinnere1335c72011-10-04 20:53:03 +02002527 Py_DECREF(str_obj);
2528 goto fail;
2529 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002530 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002531 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002532 n += PyUnicode_GET_LENGTH(str_obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002533 *callresult++ = str_obj;
2534 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002535 break;
2536 }
2537 case 'S':
2538 {
2539 PyObject *obj = va_arg(count, PyObject *);
2540 PyObject *str;
2541 assert(obj);
2542 str = PyObject_Str(obj);
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002543 if (!str)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002544 goto fail;
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002545 if (PyUnicode_READY(str) == -1) {
2546 Py_DECREF(str);
2547 goto fail;
2548 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002549 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002550 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002551 n += PyUnicode_GET_LENGTH(str);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002552 /* Remember the str and switch to the next slot */
2553 *callresult++ = str;
2554 break;
2555 }
2556 case 'R':
2557 {
2558 PyObject *obj = va_arg(count, PyObject *);
2559 PyObject *repr;
2560 assert(obj);
2561 repr = PyObject_Repr(obj);
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002562 if (!repr)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002563 goto fail;
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002564 if (PyUnicode_READY(repr) == -1) {
2565 Py_DECREF(repr);
2566 goto fail;
2567 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002568 argmaxchar = PyUnicode_MAX_CHAR_VALUE(repr);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002569 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002570 n += PyUnicode_GET_LENGTH(repr);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002571 /* Remember the repr and switch to the next slot */
2572 *callresult++ = repr;
2573 break;
2574 }
2575 case 'A':
2576 {
2577 PyObject *obj = va_arg(count, PyObject *);
2578 PyObject *ascii;
2579 assert(obj);
2580 ascii = PyObject_ASCII(obj);
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002581 if (!ascii)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002582 goto fail;
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002583 if (PyUnicode_READY(ascii) == -1) {
2584 Py_DECREF(ascii);
2585 goto fail;
2586 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002587 argmaxchar = PyUnicode_MAX_CHAR_VALUE(ascii);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002588 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002589 n += PyUnicode_GET_LENGTH(ascii);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002590 /* Remember the repr and switch to the next slot */
2591 *callresult++ = ascii;
2592 break;
2593 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002594 default:
2595 /* if we stumble upon an unknown
2596 formatting code, copy the rest of
2597 the format string to the output
2598 string. (we cannot just skip the
2599 code, since there's no way to know
2600 what's in the argument list) */
2601 n += strlen(p);
2602 goto expand;
2603 }
2604 } else
2605 n++;
2606 }
Benjamin Peterson29060642009-01-31 22:14:21 +00002607 expand:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002608 /* step 4: fill the buffer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002609 /* Since we've analyzed how much space we need,
Benjamin Peterson14339b62009-01-31 16:36:08 +00002610 we don't have to resize the string.
2611 There can be no errors beyond this point. */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002612 string = PyUnicode_New(n, maxchar);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002613 if (!string)
2614 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002615 kind = PyUnicode_KIND(string);
2616 data = PyUnicode_DATA(string);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002617 callresult = callresults;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002618 numberresult = numberresults;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002619
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002620 for (i = 0, f = format; *f; f++) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002621 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002622 const char* p;
Victor Stinner96865452011-03-01 23:44:09 +00002623
2624 p = f;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002625 f = parse_format_flags(f, NULL, NULL, NULL, NULL, NULL);
2626 /* checking for == because the last argument could be a empty
2627 string, which causes i to point to end, the assert at the end of
2628 the loop */
2629 assert(i <= PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002630
Benjamin Peterson14339b62009-01-31 16:36:08 +00002631 switch (*f) {
2632 case 'c':
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002633 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002634 const int ordinal = va_arg(vargs, int);
2635 PyUnicode_WRITE(kind, data, i++, ordinal);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002636 break;
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002637 }
Victor Stinner6d970f42011-03-02 00:04:25 +00002638 case 'i':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002639 case 'd':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002640 case 'u':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002641 case 'x':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002642 case 'p':
Victor Stinnerc5166102012-02-22 13:55:02 +01002643 {
2644 Py_ssize_t written;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002645 /* unused, since we already have the result */
2646 if (*f == 'p')
2647 (void) va_arg(vargs, void *);
2648 else
2649 (void) va_arg(vargs, int);
2650 /* extract the result from numberresults and append. */
Victor Stinnerc5166102012-02-22 13:55:02 +01002651 written = unicode_write_cstr(string, i, numberresult);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002652 /* skip over the separating '\0' */
Victor Stinnerc5166102012-02-22 13:55:02 +01002653 i += written;
2654 numberresult += written;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002655 assert(*numberresult == '\0');
2656 numberresult++;
2657 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002658 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01002659 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002660 case 's':
2661 {
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002662 /* unused, since we already have the result */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002663 Py_ssize_t size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002664 (void) va_arg(vargs, char *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002665 size = PyUnicode_GET_LENGTH(*callresult);
2666 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002667 copy_characters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002668 i += size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002669 /* We're done with the unicode()/repr() => forget it */
2670 Py_DECREF(*callresult);
2671 /* switch to next unicode()/repr() result */
2672 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002673 break;
2674 }
2675 case 'U':
2676 {
2677 PyObject *obj = va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002678 Py_ssize_t size;
2679 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
2680 size = PyUnicode_GET_LENGTH(obj);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002681 copy_characters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002682 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002683 break;
2684 }
2685 case 'V':
2686 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002687 Py_ssize_t size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002688 PyObject *obj = va_arg(vargs, PyObject *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002689 va_arg(vargs, const char *);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002690 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002691 size = PyUnicode_GET_LENGTH(obj);
2692 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002693 copy_characters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002694 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002695 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002696 size = PyUnicode_GET_LENGTH(*callresult);
2697 assert(PyUnicode_KIND(*callresult) <=
2698 PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002699 copy_characters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002700 i += size;
Victor Stinner2512a8b2011-03-01 22:46:52 +00002701 Py_DECREF(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002702 }
Victor Stinner2512a8b2011-03-01 22:46:52 +00002703 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002704 break;
2705 }
2706 case 'S':
2707 case 'R':
Victor Stinner9a909002010-10-18 20:59:24 +00002708 case 'A':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002709 {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002710 Py_ssize_t size = PyUnicode_GET_LENGTH(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002711 /* unused, since we already have the result */
2712 (void) va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002713 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002714 copy_characters(string, i, *callresult, 0, size);
2715 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002716 /* We're done with the unicode()/repr() => forget it */
2717 Py_DECREF(*callresult);
2718 /* switch to next unicode()/repr() result */
2719 ++callresult;
2720 break;
2721 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002722 case '%':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002723 PyUnicode_WRITE(kind, data, i++, '%');
Benjamin Peterson14339b62009-01-31 16:36:08 +00002724 break;
2725 default:
Victor Stinnerc5166102012-02-22 13:55:02 +01002726 i += unicode_write_cstr(string, i, p);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002727 assert(i == PyUnicode_GET_LENGTH(string));
Benjamin Peterson14339b62009-01-31 16:36:08 +00002728 goto end;
2729 }
Victor Stinner1205f272010-09-11 00:54:47 +00002730 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002731 else {
2732 assert(i < PyUnicode_GET_LENGTH(string));
2733 PyUnicode_WRITE(kind, data, i++, *f);
2734 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002735 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002736 assert(i == PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002737
Benjamin Peterson29060642009-01-31 22:14:21 +00002738 end:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002739 if (callresults)
2740 PyObject_Free(callresults);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002741 if (numberresults)
2742 PyObject_Free(numberresults);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002743 return unicode_result(string);
Benjamin Peterson29060642009-01-31 22:14:21 +00002744 fail:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002745 if (callresults) {
2746 PyObject **callresult2 = callresults;
2747 while (callresult2 < callresult) {
Victor Stinner2512a8b2011-03-01 22:46:52 +00002748 Py_XDECREF(*callresult2);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002749 ++callresult2;
2750 }
2751 PyObject_Free(callresults);
2752 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002753 if (numberresults)
2754 PyObject_Free(numberresults);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002755 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002756}
2757
Walter Dörwaldd2034312007-05-18 16:29:38 +00002758PyObject *
2759PyUnicode_FromFormat(const char *format, ...)
2760{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002761 PyObject* ret;
2762 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002763
2764#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002765 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002766#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002767 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002768#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002769 ret = PyUnicode_FromFormatV(format, vargs);
2770 va_end(vargs);
2771 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002772}
2773
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002774#ifdef HAVE_WCHAR_H
2775
Victor Stinner5593d8a2010-10-02 11:11:27 +00002776/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2777 convert a Unicode object to a wide character string.
2778
Victor Stinnerd88d9832011-09-06 02:00:05 +02002779 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002780 character) required to convert the unicode object. Ignore size argument.
2781
Victor Stinnerd88d9832011-09-06 02:00:05 +02002782 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002783 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002784 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002785static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002786unicode_aswidechar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002787 wchar_t *w,
2788 Py_ssize_t size)
2789{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002790 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002791 const wchar_t *wstr;
2792
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002793 wstr = PyUnicode_AsUnicodeAndSize(unicode, &res);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002794 if (wstr == NULL)
2795 return -1;
2796
Victor Stinner5593d8a2010-10-02 11:11:27 +00002797 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002798 if (size > res)
2799 size = res + 1;
2800 else
2801 res = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002802 Py_MEMCPY(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002803 return res;
2804 }
2805 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002806 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002807}
2808
2809Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002810PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002811 wchar_t *w,
2812 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002813{
2814 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002815 PyErr_BadInternalCall();
2816 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002817 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002818 return unicode_aswidechar(unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002819}
2820
Victor Stinner137c34c2010-09-29 10:25:54 +00002821wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002822PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002823 Py_ssize_t *size)
2824{
2825 wchar_t* buffer;
2826 Py_ssize_t buflen;
2827
2828 if (unicode == NULL) {
2829 PyErr_BadInternalCall();
2830 return NULL;
2831 }
2832
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002833 buflen = unicode_aswidechar(unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002834 if (buflen == -1)
2835 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002836 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < buflen) {
Victor Stinner137c34c2010-09-29 10:25:54 +00002837 PyErr_NoMemory();
2838 return NULL;
2839 }
2840
Victor Stinner137c34c2010-09-29 10:25:54 +00002841 buffer = PyMem_MALLOC(buflen * sizeof(wchar_t));
2842 if (buffer == NULL) {
2843 PyErr_NoMemory();
2844 return NULL;
2845 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002846 buflen = unicode_aswidechar(unicode, buffer, buflen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002847 if (buflen == -1)
2848 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002849 if (size != NULL)
2850 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00002851 return buffer;
2852}
2853
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002854#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002855
Alexander Belopolsky40018472011-02-26 01:02:56 +00002856PyObject *
2857PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002858{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002859 PyObject *v;
Victor Stinner8faf8212011-12-08 22:14:11 +01002860 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002861 PyErr_SetString(PyExc_ValueError,
2862 "chr() arg not in range(0x110000)");
2863 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002864 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00002865
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002866 if (ordinal < 256)
2867 return get_latin1_char(ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002868
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002869 v = PyUnicode_New(1, ordinal);
2870 if (v == NULL)
2871 return NULL;
2872 PyUnicode_WRITE(PyUnicode_KIND(v), PyUnicode_DATA(v), 0, ordinal);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002873 assert(_PyUnicode_CheckConsistency(v, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002874 return v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002875}
2876
Alexander Belopolsky40018472011-02-26 01:02:56 +00002877PyObject *
2878PyUnicode_FromObject(register PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002879{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002880 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00002881 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002882 if (PyUnicode_CheckExact(obj)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05002883 if (PyUnicode_READY(obj) == -1)
Victor Stinnerd3a83d52011-10-01 03:09:33 +02002884 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00002885 Py_INCREF(obj);
2886 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002887 }
2888 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002889 /* For a Unicode subtype that's not a Unicode object,
2890 return a true Unicode object with the same data. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002891 return _PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002892 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00002893 PyErr_Format(PyExc_TypeError,
2894 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00002895 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002896 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002897}
2898
Alexander Belopolsky40018472011-02-26 01:02:56 +00002899PyObject *
2900PyUnicode_FromEncodedObject(register PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002901 const char *encoding,
2902 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002903{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002904 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002905 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00002906
Guido van Rossumd57fd912000-03-10 22:53:23 +00002907 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002908 PyErr_BadInternalCall();
2909 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002910 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002911
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002912 /* Decoding bytes objects is the most common case and should be fast */
2913 if (PyBytes_Check(obj)) {
2914 if (PyBytes_GET_SIZE(obj) == 0) {
2915 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002916 v = unicode_empty;
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002917 }
2918 else {
2919 v = PyUnicode_Decode(
2920 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
2921 encoding, errors);
2922 }
2923 return v;
2924 }
2925
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002926 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002927 PyErr_SetString(PyExc_TypeError,
2928 "decoding str is not supported");
2929 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002930 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002931
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002932 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
2933 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
2934 PyErr_Format(PyExc_TypeError,
2935 "coercing to str: need bytes, bytearray "
2936 "or buffer-like object, %.80s found",
2937 Py_TYPE(obj)->tp_name);
2938 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00002939 }
Tim Petersced69f82003-09-16 20:30:58 +00002940
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002941 if (buffer.len == 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002942 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002943 v = unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002944 }
Tim Petersced69f82003-09-16 20:30:58 +00002945 else
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002946 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00002947
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002948 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002949 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002950}
2951
Victor Stinner600d3be2010-06-10 12:00:55 +00002952/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00002953 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
2954 1 on success. */
2955static int
2956normalize_encoding(const char *encoding,
2957 char *lower,
2958 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002959{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002960 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00002961 char *l;
2962 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002963
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04002964 if (encoding == NULL) {
2965 strcpy(lower, "utf-8");
2966 return 1;
2967 }
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002968 e = encoding;
2969 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00002970 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00002971 while (*e) {
2972 if (l == l_end)
2973 return 0;
David Malcolm96960882010-11-05 17:23:41 +00002974 if (Py_ISUPPER(*e)) {
2975 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002976 }
2977 else if (*e == '_') {
2978 *l++ = '-';
2979 e++;
2980 }
2981 else {
2982 *l++ = *e++;
2983 }
2984 }
2985 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00002986 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00002987}
2988
Alexander Belopolsky40018472011-02-26 01:02:56 +00002989PyObject *
2990PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002991 Py_ssize_t size,
2992 const char *encoding,
2993 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00002994{
2995 PyObject *buffer = NULL, *unicode;
2996 Py_buffer info;
2997 char lower[11]; /* Enough for any encoding shortcut */
2998
Fred Drakee4315f52000-05-09 19:53:39 +00002999 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00003000 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003001 if ((strcmp(lower, "utf-8") == 0) ||
3002 (strcmp(lower, "utf8") == 0))
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003003 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
Victor Stinner37296e82010-06-10 13:36:23 +00003004 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003005 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00003006 (strcmp(lower, "iso-8859-1") == 0))
3007 return PyUnicode_DecodeLatin1(s, size, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003008#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00003009 else if (strcmp(lower, "mbcs") == 0)
3010 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003011#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003012 else if (strcmp(lower, "ascii") == 0)
3013 return PyUnicode_DecodeASCII(s, size, errors);
3014 else if (strcmp(lower, "utf-16") == 0)
3015 return PyUnicode_DecodeUTF16(s, size, errors, 0);
3016 else if (strcmp(lower, "utf-32") == 0)
3017 return PyUnicode_DecodeUTF32(s, size, errors, 0);
3018 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003019
3020 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003021 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00003022 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003023 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00003024 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003025 if (buffer == NULL)
3026 goto onError;
3027 unicode = PyCodec_Decode(buffer, encoding, errors);
3028 if (unicode == NULL)
3029 goto onError;
3030 if (!PyUnicode_Check(unicode)) {
3031 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003032 "decoder did not return a str object (type=%.400s)",
Christian Heimes90aa7642007-12-19 02:45:37 +00003033 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003034 Py_DECREF(unicode);
3035 goto onError;
3036 }
3037 Py_DECREF(buffer);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003038 return unicode_result(unicode);
Tim Petersced69f82003-09-16 20:30:58 +00003039
Benjamin Peterson29060642009-01-31 22:14:21 +00003040 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003041 Py_XDECREF(buffer);
3042 return NULL;
3043}
3044
Alexander Belopolsky40018472011-02-26 01:02:56 +00003045PyObject *
3046PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003047 const char *encoding,
3048 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003049{
3050 PyObject *v;
3051
3052 if (!PyUnicode_Check(unicode)) {
3053 PyErr_BadArgument();
3054 goto onError;
3055 }
3056
3057 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003058 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003059
3060 /* Decode via the codec registry */
3061 v = PyCodec_Decode(unicode, encoding, errors);
3062 if (v == NULL)
3063 goto onError;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003064 return unicode_result(v);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003065
Benjamin Peterson29060642009-01-31 22:14:21 +00003066 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003067 return NULL;
3068}
3069
Alexander Belopolsky40018472011-02-26 01:02:56 +00003070PyObject *
3071PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003072 const char *encoding,
3073 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003074{
3075 PyObject *v;
3076
3077 if (!PyUnicode_Check(unicode)) {
3078 PyErr_BadArgument();
3079 goto onError;
3080 }
3081
3082 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003083 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003084
3085 /* Decode via the codec registry */
3086 v = PyCodec_Decode(unicode, encoding, errors);
3087 if (v == NULL)
3088 goto onError;
3089 if (!PyUnicode_Check(v)) {
3090 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003091 "decoder did not return a str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003092 Py_TYPE(v)->tp_name);
3093 Py_DECREF(v);
3094 goto onError;
3095 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003096 return unicode_result(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003097
Benjamin Peterson29060642009-01-31 22:14:21 +00003098 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003099 return NULL;
3100}
3101
Alexander Belopolsky40018472011-02-26 01:02:56 +00003102PyObject *
3103PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003104 Py_ssize_t size,
3105 const char *encoding,
3106 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003107{
3108 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003109
Guido van Rossumd57fd912000-03-10 22:53:23 +00003110 unicode = PyUnicode_FromUnicode(s, size);
3111 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003112 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003113 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3114 Py_DECREF(unicode);
3115 return v;
3116}
3117
Alexander Belopolsky40018472011-02-26 01:02:56 +00003118PyObject *
3119PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003120 const char *encoding,
3121 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003122{
3123 PyObject *v;
3124
3125 if (!PyUnicode_Check(unicode)) {
3126 PyErr_BadArgument();
3127 goto onError;
3128 }
3129
3130 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003131 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003132
3133 /* Encode via the codec registry */
3134 v = PyCodec_Encode(unicode, encoding, errors);
3135 if (v == NULL)
3136 goto onError;
3137 return v;
3138
Benjamin Peterson29060642009-01-31 22:14:21 +00003139 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003140 return NULL;
3141}
3142
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003143static size_t
3144wcstombs_errorpos(const wchar_t *wstr)
3145{
3146 size_t len;
3147#if SIZEOF_WCHAR_T == 2
3148 wchar_t buf[3];
3149#else
3150 wchar_t buf[2];
3151#endif
3152 char outbuf[MB_LEN_MAX];
3153 const wchar_t *start, *previous;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003154
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003155#if SIZEOF_WCHAR_T == 2
3156 buf[2] = 0;
3157#else
3158 buf[1] = 0;
3159#endif
3160 start = wstr;
3161 while (*wstr != L'\0')
3162 {
3163 previous = wstr;
3164#if SIZEOF_WCHAR_T == 2
3165 if (Py_UNICODE_IS_HIGH_SURROGATE(wstr[0])
3166 && Py_UNICODE_IS_LOW_SURROGATE(wstr[1]))
3167 {
3168 buf[0] = wstr[0];
3169 buf[1] = wstr[1];
3170 wstr += 2;
3171 }
3172 else {
3173 buf[0] = *wstr;
3174 buf[1] = 0;
3175 wstr++;
3176 }
3177#else
3178 buf[0] = *wstr;
3179 wstr++;
3180#endif
3181 len = wcstombs(outbuf, buf, sizeof(outbuf));
Victor Stinner2f197072011-12-17 07:08:30 +01003182 if (len == (size_t)-1)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003183 return previous - start;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003184 }
3185
3186 /* failed to find the unencodable character */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003187 return 0;
3188}
3189
Victor Stinner1b579672011-12-17 05:47:23 +01003190static int
3191locale_error_handler(const char *errors, int *surrogateescape)
3192{
3193 if (errors == NULL) {
3194 *surrogateescape = 0;
3195 return 0;
3196 }
3197
3198 if (strcmp(errors, "strict") == 0) {
3199 *surrogateescape = 0;
3200 return 0;
3201 }
3202 if (strcmp(errors, "surrogateescape") == 0) {
3203 *surrogateescape = 1;
3204 return 0;
3205 }
3206 PyErr_Format(PyExc_ValueError,
3207 "only 'strict' and 'surrogateescape' error handlers "
3208 "are supported, not '%s'",
3209 errors);
3210 return -1;
3211}
3212
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003213PyObject *
Victor Stinner1b579672011-12-17 05:47:23 +01003214PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003215{
3216 Py_ssize_t wlen, wlen2;
3217 wchar_t *wstr;
3218 PyObject *bytes = NULL;
3219 char *errmsg;
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003220 PyObject *reason;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003221 PyObject *exc;
3222 size_t error_pos;
Victor Stinner1b579672011-12-17 05:47:23 +01003223 int surrogateescape;
3224
3225 if (locale_error_handler(errors, &surrogateescape) < 0)
3226 return NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003227
3228 wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3229 if (wstr == NULL)
3230 return NULL;
3231
3232 wlen2 = wcslen(wstr);
3233 if (wlen2 != wlen) {
3234 PyMem_Free(wstr);
3235 PyErr_SetString(PyExc_TypeError, "embedded null character");
3236 return NULL;
3237 }
3238
3239 if (surrogateescape) {
3240 /* locale encoding with surrogateescape */
3241 char *str;
3242
3243 str = _Py_wchar2char(wstr, &error_pos);
3244 if (str == NULL) {
3245 if (error_pos == (size_t)-1) {
3246 PyErr_NoMemory();
3247 PyMem_Free(wstr);
3248 return NULL;
3249 }
3250 else {
3251 goto encode_error;
3252 }
3253 }
3254 PyMem_Free(wstr);
3255
3256 bytes = PyBytes_FromString(str);
3257 PyMem_Free(str);
3258 }
3259 else {
3260 size_t len, len2;
3261
3262 len = wcstombs(NULL, wstr, 0);
3263 if (len == (size_t)-1) {
Victor Stinner2f197072011-12-17 07:08:30 +01003264 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003265 goto encode_error;
3266 }
3267
3268 bytes = PyBytes_FromStringAndSize(NULL, len);
3269 if (bytes == NULL) {
3270 PyMem_Free(wstr);
3271 return NULL;
3272 }
3273
3274 len2 = wcstombs(PyBytes_AS_STRING(bytes), wstr, len+1);
3275 if (len2 == (size_t)-1 || len2 > len) {
Victor Stinner2f197072011-12-17 07:08:30 +01003276 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003277 goto encode_error;
3278 }
3279 PyMem_Free(wstr);
3280 }
3281 return bytes;
3282
3283encode_error:
3284 errmsg = strerror(errno);
3285 assert(errmsg != NULL);
Victor Stinner2f197072011-12-17 07:08:30 +01003286
3287 if (error_pos == (size_t)-1)
3288 error_pos = wcstombs_errorpos(wstr);
3289
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003290 PyMem_Free(wstr);
3291 Py_XDECREF(bytes);
3292
Victor Stinner2f197072011-12-17 07:08:30 +01003293 if (errmsg != NULL) {
3294 size_t errlen;
3295 wstr = _Py_char2wchar(errmsg, &errlen);
3296 if (wstr != NULL) {
3297 reason = PyUnicode_FromWideChar(wstr, errlen);
3298 PyMem_Free(wstr);
3299 } else
3300 errmsg = NULL;
3301 }
3302 if (errmsg == NULL)
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003303 reason = PyUnicode_FromString(
3304 "wcstombs() encountered an unencodable "
3305 "wide character");
3306 if (reason == NULL)
3307 return NULL;
3308
3309 exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnnO",
3310 "locale", unicode,
3311 (Py_ssize_t)error_pos,
3312 (Py_ssize_t)(error_pos+1),
3313 reason);
3314 Py_DECREF(reason);
3315 if (exc != NULL) {
3316 PyCodec_StrictErrors(exc);
3317 Py_XDECREF(exc);
3318 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003319 return NULL;
3320}
3321
Victor Stinnerad158722010-10-27 00:25:46 +00003322PyObject *
3323PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003324{
Victor Stinner99b95382011-07-04 14:23:54 +02003325#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003326 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003327#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003328 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00003329#else
Victor Stinner793b5312011-04-27 00:24:21 +02003330 PyInterpreterState *interp = PyThreadState_GET()->interp;
3331 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3332 cannot use it to encode and decode filenames before it is loaded. Load
3333 the Python codec requires to encode at least its own filename. Use the C
3334 version of the locale codec until the codec registry is initialized and
3335 the Python codec is loaded.
3336
3337 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3338 cannot only rely on it: check also interp->fscodec_initialized for
3339 subinterpreters. */
3340 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003341 return PyUnicode_AsEncodedString(unicode,
3342 Py_FileSystemDefaultEncoding,
3343 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003344 }
3345 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003346 return PyUnicode_EncodeLocale(unicode, "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003347 }
Victor Stinnerad158722010-10-27 00:25:46 +00003348#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003349}
3350
Alexander Belopolsky40018472011-02-26 01:02:56 +00003351PyObject *
3352PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003353 const char *encoding,
3354 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003355{
3356 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00003357 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003358
Guido van Rossumd57fd912000-03-10 22:53:23 +00003359 if (!PyUnicode_Check(unicode)) {
3360 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003361 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003362 }
Fred Drakee4315f52000-05-09 19:53:39 +00003363
Fred Drakee4315f52000-05-09 19:53:39 +00003364 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00003365 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003366 if ((strcmp(lower, "utf-8") == 0) ||
3367 (strcmp(lower, "utf8") == 0))
Victor Stinnera5c68c32011-03-02 01:03:14 +00003368 {
Victor Stinner2f283c22011-03-02 01:21:46 +00003369 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003370 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00003371 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003372 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinnera5c68c32011-03-02 01:03:14 +00003373 }
Victor Stinner37296e82010-06-10 13:36:23 +00003374 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003375 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00003376 (strcmp(lower, "iso-8859-1") == 0))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003377 return _PyUnicode_AsLatin1String(unicode, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003378#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003379 else if (strcmp(lower, "mbcs") == 0)
3380 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003381#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003382 else if (strcmp(lower, "ascii") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003383 return _PyUnicode_AsASCIIString(unicode, errors);
Victor Stinner37296e82010-06-10 13:36:23 +00003384 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003385
3386 /* Encode via the codec registry */
3387 v = PyCodec_Encode(unicode, encoding, errors);
3388 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003389 return NULL;
3390
3391 /* The normal path */
3392 if (PyBytes_Check(v))
3393 return v;
3394
3395 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003396 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003397 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003398 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003399
3400 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
3401 "encoder %s returned bytearray instead of bytes",
3402 encoding);
3403 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003404 Py_DECREF(v);
3405 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003406 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003407
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003408 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3409 Py_DECREF(v);
3410 return b;
3411 }
3412
3413 PyErr_Format(PyExc_TypeError,
3414 "encoder did not return a bytes object (type=%.400s)",
3415 Py_TYPE(v)->tp_name);
3416 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003417 return NULL;
3418}
3419
Alexander Belopolsky40018472011-02-26 01:02:56 +00003420PyObject *
3421PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003422 const char *encoding,
3423 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003424{
3425 PyObject *v;
3426
3427 if (!PyUnicode_Check(unicode)) {
3428 PyErr_BadArgument();
3429 goto onError;
3430 }
3431
3432 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003433 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003434
3435 /* Encode via the codec registry */
3436 v = PyCodec_Encode(unicode, encoding, errors);
3437 if (v == NULL)
3438 goto onError;
3439 if (!PyUnicode_Check(v)) {
3440 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003441 "encoder did not return an str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003442 Py_TYPE(v)->tp_name);
3443 Py_DECREF(v);
3444 goto onError;
3445 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003446 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003447
Benjamin Peterson29060642009-01-31 22:14:21 +00003448 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003449 return NULL;
3450}
3451
Victor Stinner2f197072011-12-17 07:08:30 +01003452static size_t
3453mbstowcs_errorpos(const char *str, size_t len)
3454{
3455#ifdef HAVE_MBRTOWC
3456 const char *start = str;
3457 mbstate_t mbs;
3458 size_t converted;
3459 wchar_t ch;
3460
3461 memset(&mbs, 0, sizeof mbs);
3462 while (len)
3463 {
3464 converted = mbrtowc(&ch, (char*)str, len, &mbs);
3465 if (converted == 0)
3466 /* Reached end of string */
3467 break;
3468 if (converted == (size_t)-1 || converted == (size_t)-2) {
3469 /* Conversion error or incomplete character */
3470 return str - start;
3471 }
3472 else {
3473 str += converted;
3474 len -= converted;
3475 }
3476 }
3477 /* failed to find the undecodable byte sequence */
3478 return 0;
3479#endif
3480 return 0;
3481}
3482
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003483PyObject*
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003484PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
Victor Stinner1b579672011-12-17 05:47:23 +01003485 const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003486{
3487 wchar_t smallbuf[256];
3488 size_t smallbuf_len = Py_ARRAY_LENGTH(smallbuf);
3489 wchar_t *wstr;
3490 size_t wlen, wlen2;
3491 PyObject *unicode;
Victor Stinner1b579672011-12-17 05:47:23 +01003492 int surrogateescape;
Victor Stinner2f197072011-12-17 07:08:30 +01003493 size_t error_pos;
3494 char *errmsg;
3495 PyObject *reason, *exc;
Victor Stinner1b579672011-12-17 05:47:23 +01003496
3497 if (locale_error_handler(errors, &surrogateescape) < 0)
3498 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003499
3500 if (str[len] != '\0' || len != strlen(str)) {
3501 PyErr_SetString(PyExc_TypeError, "embedded null character");
3502 return NULL;
3503 }
3504
3505 if (surrogateescape)
3506 {
3507 wstr = _Py_char2wchar(str, &wlen);
3508 if (wstr == NULL) {
3509 if (wlen == (size_t)-1)
3510 PyErr_NoMemory();
3511 else
3512 PyErr_SetFromErrno(PyExc_OSError);
3513 return NULL;
3514 }
3515
3516 unicode = PyUnicode_FromWideChar(wstr, wlen);
3517 PyMem_Free(wstr);
3518 }
3519 else {
3520#ifndef HAVE_BROKEN_MBSTOWCS
3521 wlen = mbstowcs(NULL, str, 0);
3522#else
3523 wlen = len;
3524#endif
Victor Stinner2f197072011-12-17 07:08:30 +01003525 if (wlen == (size_t)-1)
3526 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003527 if (wlen+1 <= smallbuf_len) {
3528 wstr = smallbuf;
3529 }
3530 else {
3531 if (wlen > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1)
3532 return PyErr_NoMemory();
3533
3534 wstr = PyMem_Malloc((wlen+1) * sizeof(wchar_t));
3535 if (!wstr)
3536 return PyErr_NoMemory();
3537 }
3538
3539 /* This shouldn't fail now */
3540 wlen2 = mbstowcs(wstr, str, wlen+1);
3541 if (wlen2 == (size_t)-1) {
3542 if (wstr != smallbuf)
3543 PyMem_Free(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003544 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003545 }
3546#ifdef HAVE_BROKEN_MBSTOWCS
3547 assert(wlen2 == wlen);
3548#endif
3549 unicode = PyUnicode_FromWideChar(wstr, wlen2);
3550 if (wstr != smallbuf)
3551 PyMem_Free(wstr);
3552 }
3553 return unicode;
Victor Stinner2f197072011-12-17 07:08:30 +01003554
3555decode_error:
3556 errmsg = strerror(errno);
3557 assert(errmsg != NULL);
3558
3559 error_pos = mbstowcs_errorpos(str, len);
3560 if (errmsg != NULL) {
3561 size_t errlen;
3562 wstr = _Py_char2wchar(errmsg, &errlen);
3563 if (wstr != NULL) {
3564 reason = PyUnicode_FromWideChar(wstr, errlen);
3565 PyMem_Free(wstr);
3566 } else
3567 errmsg = NULL;
3568 }
3569 if (errmsg == NULL)
3570 reason = PyUnicode_FromString(
3571 "mbstowcs() encountered an invalid multibyte sequence");
3572 if (reason == NULL)
3573 return NULL;
3574
3575 exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nnO",
3576 "locale", str, len,
3577 (Py_ssize_t)error_pos,
3578 (Py_ssize_t)(error_pos+1),
3579 reason);
3580 Py_DECREF(reason);
3581 if (exc != NULL) {
3582 PyCodec_StrictErrors(exc);
3583 Py_XDECREF(exc);
3584 }
3585 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003586}
3587
3588PyObject*
Victor Stinner1b579672011-12-17 05:47:23 +01003589PyUnicode_DecodeLocale(const char *str, const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003590{
3591 Py_ssize_t size = (Py_ssize_t)strlen(str);
Victor Stinner1b579672011-12-17 05:47:23 +01003592 return PyUnicode_DecodeLocaleAndSize(str, size, errors);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003593}
3594
3595
3596PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003597PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003598 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003599 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3600}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003601
Christian Heimes5894ba72007-11-04 11:43:14 +00003602PyObject*
3603PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3604{
Victor Stinner99b95382011-07-04 14:23:54 +02003605#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003606 return PyUnicode_DecodeMBCS(s, size, NULL);
3607#elif defined(__APPLE__)
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003608 return PyUnicode_DecodeUTF8Stateful(s, size, "surrogateescape", NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003609#else
Victor Stinner793b5312011-04-27 00:24:21 +02003610 PyInterpreterState *interp = PyThreadState_GET()->interp;
3611 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3612 cannot use it to encode and decode filenames before it is loaded. Load
3613 the Python codec requires to encode at least its own filename. Use the C
3614 version of the locale codec until the codec registry is initialized and
3615 the Python codec is loaded.
3616
3617 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3618 cannot only rely on it: check also interp->fscodec_initialized for
3619 subinterpreters. */
3620 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003621 return PyUnicode_Decode(s, size,
3622 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00003623 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003624 }
3625 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003626 return PyUnicode_DecodeLocaleAndSize(s, size, "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003627 }
Victor Stinnerad158722010-10-27 00:25:46 +00003628#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003629}
3630
Martin v. Löwis011e8422009-05-05 04:43:17 +00003631
3632int
Antoine Pitrou13348842012-01-29 18:36:34 +01003633_PyUnicode_HasNULChars(PyObject* s)
3634{
3635 static PyObject *nul = NULL;
3636
3637 if (nul == NULL)
3638 nul = PyUnicode_FromStringAndSize("\0", 1);
3639 if (nul == NULL)
3640 return -1;
3641 return PyUnicode_Contains(s, nul);
3642}
3643
3644
3645int
Martin v. Löwis011e8422009-05-05 04:43:17 +00003646PyUnicode_FSConverter(PyObject* arg, void* addr)
3647{
3648 PyObject *output = NULL;
3649 Py_ssize_t size;
3650 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003651 if (arg == NULL) {
3652 Py_DECREF(*(PyObject**)addr);
3653 return 1;
3654 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00003655 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00003656 output = arg;
3657 Py_INCREF(output);
3658 }
3659 else {
3660 arg = PyUnicode_FromObject(arg);
3661 if (!arg)
3662 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00003663 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003664 Py_DECREF(arg);
3665 if (!output)
3666 return 0;
3667 if (!PyBytes_Check(output)) {
3668 Py_DECREF(output);
3669 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
3670 return 0;
3671 }
3672 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00003673 size = PyBytes_GET_SIZE(output);
3674 data = PyBytes_AS_STRING(output);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003675 if (size != strlen(data)) {
Benjamin Peterson7a6b44a2011-08-18 13:51:47 -05003676 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003677 Py_DECREF(output);
3678 return 0;
3679 }
3680 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003681 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003682}
3683
3684
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003685int
3686PyUnicode_FSDecoder(PyObject* arg, void* addr)
3687{
3688 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003689 if (arg == NULL) {
3690 Py_DECREF(*(PyObject**)addr);
3691 return 1;
3692 }
3693 if (PyUnicode_Check(arg)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05003694 if (PyUnicode_READY(arg) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003695 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003696 output = arg;
3697 Py_INCREF(output);
3698 }
3699 else {
3700 arg = PyBytes_FromObject(arg);
3701 if (!arg)
3702 return 0;
3703 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
3704 PyBytes_GET_SIZE(arg));
3705 Py_DECREF(arg);
3706 if (!output)
3707 return 0;
3708 if (!PyUnicode_Check(output)) {
3709 Py_DECREF(output);
3710 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
3711 return 0;
3712 }
3713 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05003714 if (PyUnicode_READY(output) == -1) {
Victor Stinner065836e2011-10-27 01:56:33 +02003715 Py_DECREF(output);
3716 return 0;
3717 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003718 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003719 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003720 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3721 Py_DECREF(output);
3722 return 0;
3723 }
3724 *(PyObject**)addr = output;
3725 return Py_CLEANUP_SUPPORTED;
3726}
3727
3728
Martin v. Löwis5b222132007-06-10 09:51:05 +00003729char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003730PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003731{
Christian Heimesf3863112007-11-22 07:46:41 +00003732 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003733
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003734 if (!PyUnicode_Check(unicode)) {
3735 PyErr_BadArgument();
3736 return NULL;
3737 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003738 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003739 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003740
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003741 if (PyUnicode_UTF8(unicode) == NULL) {
3742 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003743 bytes = _PyUnicode_AsUTF8String(unicode, "strict");
3744 if (bytes == NULL)
3745 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003746 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3747 if (_PyUnicode_UTF8(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003748 Py_DECREF(bytes);
3749 return NULL;
3750 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003751 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
3752 Py_MEMCPY(_PyUnicode_UTF8(unicode),
3753 PyBytes_AS_STRING(bytes),
3754 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003755 Py_DECREF(bytes);
3756 }
3757
3758 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003759 *psize = PyUnicode_UTF8_LENGTH(unicode);
3760 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003761}
3762
3763char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003764PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003765{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003766 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3767}
3768
3769#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +02003770static int unicode_as_unicode_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003771#endif
3772
3773
3774Py_UNICODE *
3775PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3776{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003777 const unsigned char *one_byte;
3778#if SIZEOF_WCHAR_T == 4
3779 const Py_UCS2 *two_bytes;
3780#else
3781 const Py_UCS4 *four_bytes;
3782 const Py_UCS4 *ucs4_end;
3783 Py_ssize_t num_surrogates;
3784#endif
3785 wchar_t *w;
3786 wchar_t *wchar_end;
3787
3788 if (!PyUnicode_Check(unicode)) {
3789 PyErr_BadArgument();
3790 return NULL;
3791 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003792 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003793 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003794 assert(_PyUnicode_KIND(unicode) != 0);
3795 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003796
3797#ifdef Py_DEBUG
3798 ++unicode_as_unicode_calls;
3799#endif
3800
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003801 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003802#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003803 four_bytes = PyUnicode_4BYTE_DATA(unicode);
3804 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003805 num_surrogates = 0;
3806
3807 for (; four_bytes < ucs4_end; ++four_bytes) {
3808 if (*four_bytes > 0xFFFF)
3809 ++num_surrogates;
3810 }
3811
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003812 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
3813 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
3814 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003815 PyErr_NoMemory();
3816 return NULL;
3817 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003818 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003819
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003820 w = _PyUnicode_WSTR(unicode);
3821 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
3822 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003823 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3824 if (*four_bytes > 0xFFFF) {
Victor Stinner8faf8212011-12-08 22:14:11 +01003825 assert(*four_bytes <= MAX_UNICODE);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003826 /* encode surrogate pair in this case */
Victor Stinner551ac952011-11-29 22:58:13 +01003827 *w++ = Py_UNICODE_HIGH_SURROGATE(*four_bytes);
3828 *w = Py_UNICODE_LOW_SURROGATE(*four_bytes);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003829 }
3830 else
3831 *w = *four_bytes;
3832
3833 if (w > wchar_end) {
3834 assert(0 && "Miscalculated string end");
3835 }
3836 }
3837 *w = 0;
3838#else
3839 /* sizeof(wchar_t) == 4 */
3840 Py_FatalError("Impossible unicode object state, wstr and str "
3841 "should share memory already.");
3842 return NULL;
3843#endif
3844 }
3845 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003846 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3847 (_PyUnicode_LENGTH(unicode) + 1));
3848 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003849 PyErr_NoMemory();
3850 return NULL;
3851 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003852 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
3853 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
3854 w = _PyUnicode_WSTR(unicode);
3855 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003856
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003857 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3858 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003859 for (; w < wchar_end; ++one_byte, ++w)
3860 *w = *one_byte;
3861 /* null-terminate the wstr */
3862 *w = 0;
3863 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003864 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003865#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003866 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003867 for (; w < wchar_end; ++two_bytes, ++w)
3868 *w = *two_bytes;
3869 /* null-terminate the wstr */
3870 *w = 0;
3871#else
3872 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003873 PyObject_FREE(_PyUnicode_WSTR(unicode));
3874 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003875 Py_FatalError("Impossible unicode object state, wstr "
3876 "and str should share memory already.");
3877 return NULL;
3878#endif
3879 }
3880 else {
3881 assert(0 && "This should never happen.");
3882 }
3883 }
3884 }
3885 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003886 *size = PyUnicode_WSTR_LENGTH(unicode);
3887 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00003888}
3889
Alexander Belopolsky40018472011-02-26 01:02:56 +00003890Py_UNICODE *
3891PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003892{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003893 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003894}
3895
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003896
Alexander Belopolsky40018472011-02-26 01:02:56 +00003897Py_ssize_t
3898PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003899{
3900 if (!PyUnicode_Check(unicode)) {
3901 PyErr_BadArgument();
3902 goto onError;
3903 }
3904 return PyUnicode_GET_SIZE(unicode);
3905
Benjamin Peterson29060642009-01-31 22:14:21 +00003906 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003907 return -1;
3908}
3909
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003910Py_ssize_t
3911PyUnicode_GetLength(PyObject *unicode)
3912{
Victor Stinner5a706cf2011-10-02 00:36:53 +02003913 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003914 PyErr_BadArgument();
3915 return -1;
3916 }
3917
3918 return PyUnicode_GET_LENGTH(unicode);
3919}
3920
3921Py_UCS4
3922PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
3923{
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003924 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
3925 PyErr_BadArgument();
3926 return (Py_UCS4)-1;
3927 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01003928 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003929 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003930 return (Py_UCS4)-1;
3931 }
3932 return PyUnicode_READ_CHAR(unicode, index);
3933}
3934
3935int
3936PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
3937{
Victor Stinnerc9590ad2012-03-04 01:34:37 +01003938 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003939 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003940 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003941 return -1;
3942 }
Victor Stinner488fa492011-12-12 00:01:39 +01003943 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01003944 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003945 PyErr_SetString(PyExc_IndexError, "string index out of range");
3946 return -1;
3947 }
Victor Stinner488fa492011-12-12 00:01:39 +01003948 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02003949 return -1;
Victor Stinnerc9590ad2012-03-04 01:34:37 +01003950 if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
3951 PyErr_SetString(PyExc_ValueError, "character out of range");
3952 return -1;
3953 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003954 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
3955 index, ch);
3956 return 0;
3957}
3958
Alexander Belopolsky40018472011-02-26 01:02:56 +00003959const char *
3960PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00003961{
Victor Stinner42cb4622010-09-01 19:39:01 +00003962 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00003963}
3964
Victor Stinner554f3f02010-06-16 23:33:54 +00003965/* create or adjust a UnicodeDecodeError */
3966static void
3967make_decode_exception(PyObject **exceptionObject,
3968 const char *encoding,
3969 const char *input, Py_ssize_t length,
3970 Py_ssize_t startpos, Py_ssize_t endpos,
3971 const char *reason)
3972{
3973 if (*exceptionObject == NULL) {
3974 *exceptionObject = PyUnicodeDecodeError_Create(
3975 encoding, input, length, startpos, endpos, reason);
3976 }
3977 else {
3978 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
3979 goto onError;
3980 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
3981 goto onError;
3982 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
3983 goto onError;
3984 }
3985 return;
3986
3987onError:
3988 Py_DECREF(*exceptionObject);
3989 *exceptionObject = NULL;
3990}
3991
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003992/* error handling callback helper:
3993 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00003994 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003995 and adjust various state variables.
3996 return 0 on success, -1 on error
3997*/
3998
Alexander Belopolsky40018472011-02-26 01:02:56 +00003999static int
4000unicode_decode_call_errorhandler(const char *errors, PyObject **errorHandler,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004001 const char *encoding, const char *reason,
4002 const char **input, const char **inend, Py_ssize_t *startinpos,
4003 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004004 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004005{
Benjamin Peterson142957c2008-07-04 19:55:29 +00004006 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004007
4008 PyObject *restuple = NULL;
4009 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01004010 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004011 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004012 Py_ssize_t requiredsize;
4013 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004014 PyObject *inputobj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004015 int res = -1;
4016
Victor Stinner596a6c42011-11-09 00:02:18 +01004017 if (_PyUnicode_KIND(*output) != PyUnicode_WCHAR_KIND)
4018 outsize = PyUnicode_GET_LENGTH(*output);
4019 else
4020 outsize = _PyUnicode_WSTR_LENGTH(*output);
4021
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004022 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004023 *errorHandler = PyCodec_LookupError(errors);
4024 if (*errorHandler == NULL)
4025 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004026 }
4027
Victor Stinner554f3f02010-06-16 23:33:54 +00004028 make_decode_exception(exceptionObject,
4029 encoding,
4030 *input, *inend - *input,
4031 *startinpos, *endinpos,
4032 reason);
4033 if (*exceptionObject == NULL)
4034 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004035
4036 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4037 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004038 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004039 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00004040 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004041 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004042 }
4043 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004044 goto onError;
Benjamin Petersonbac79492012-01-14 13:34:47 -05004045 if (PyUnicode_READY(repunicode) == -1)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004046 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004047
4048 /* Copy back the bytes variables, which might have been modified by the
4049 callback */
4050 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4051 if (!inputobj)
4052 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00004053 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004054 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00004055 }
Christian Heimes72b710a2008-05-26 13:28:38 +00004056 *input = PyBytes_AS_STRING(inputobj);
4057 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004058 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00004059 /* we can DECREF safely, as the exception has another reference,
4060 so the object won't go away. */
4061 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004062
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004063 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004064 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004065 if (newpos<0 || newpos>insize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004066 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
4067 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004068 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004069
Victor Stinner596a6c42011-11-09 00:02:18 +01004070 if (_PyUnicode_KIND(*output) != PyUnicode_WCHAR_KIND) {
4071 /* need more space? (at least enough for what we
4072 have+the replacement+the rest of the string (starting
4073 at the new input position), so we won't have to check space
4074 when there are no errors in the rest of the string) */
4075 Py_ssize_t replen = PyUnicode_GET_LENGTH(repunicode);
4076 requiredsize = *outpos + replen + insize-newpos;
4077 if (requiredsize > outsize) {
4078 if (requiredsize<2*outsize)
4079 requiredsize = 2*outsize;
4080 if (unicode_resize(output, requiredsize) < 0)
4081 goto onError;
4082 }
4083 if (unicode_widen(output, PyUnicode_MAX_CHAR_VALUE(repunicode)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004084 goto onError;
Victor Stinner596a6c42011-11-09 00:02:18 +01004085 copy_characters(*output, *outpos, repunicode, 0, replen);
4086 *outpos += replen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004087 }
Victor Stinner596a6c42011-11-09 00:02:18 +01004088 else {
4089 wchar_t *repwstr;
4090 Py_ssize_t repwlen;
4091 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4092 if (repwstr == NULL)
4093 goto onError;
4094 /* need more space? (at least enough for what we
4095 have+the replacement+the rest of the string (starting
4096 at the new input position), so we won't have to check space
4097 when there are no errors in the rest of the string) */
4098 requiredsize = *outpos + repwlen + insize-newpos;
4099 if (requiredsize > outsize) {
4100 if (requiredsize < 2*outsize)
4101 requiredsize = 2*outsize;
4102 if (unicode_resize(output, requiredsize) < 0)
4103 goto onError;
4104 }
4105 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
4106 *outpos += repwlen;
4107 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004108 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004109 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004110
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004111 /* we made it! */
4112 res = 0;
4113
Benjamin Peterson29060642009-01-31 22:14:21 +00004114 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004115 Py_XDECREF(restuple);
4116 return res;
4117}
4118
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004119/* --- UTF-7 Codec -------------------------------------------------------- */
4120
Antoine Pitrou244651a2009-05-04 18:56:13 +00004121/* See RFC2152 for details. We encode conservatively and decode liberally. */
4122
4123/* Three simple macros defining base-64. */
4124
4125/* Is c a base-64 character? */
4126
4127#define IS_BASE64(c) \
4128 (((c) >= 'A' && (c) <= 'Z') || \
4129 ((c) >= 'a' && (c) <= 'z') || \
4130 ((c) >= '0' && (c) <= '9') || \
4131 (c) == '+' || (c) == '/')
4132
4133/* given that c is a base-64 character, what is its base-64 value? */
4134
4135#define FROM_BASE64(c) \
4136 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4137 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4138 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4139 (c) == '+' ? 62 : 63)
4140
4141/* What is the base-64 character of the bottom 6 bits of n? */
4142
4143#define TO_BASE64(n) \
4144 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4145
4146/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4147 * decoded as itself. We are permissive on decoding; the only ASCII
4148 * byte not decoding to itself is the + which begins a base64
4149 * string. */
4150
4151#define DECODE_DIRECT(c) \
4152 ((c) <= 127 && (c) != '+')
4153
4154/* The UTF-7 encoder treats ASCII characters differently according to
4155 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4156 * the above). See RFC2152. This array identifies these different
4157 * sets:
4158 * 0 : "Set D"
4159 * alphanumeric and '(),-./:?
4160 * 1 : "Set O"
4161 * !"#$%&*;<=>@[]^_`{|}
4162 * 2 : "whitespace"
4163 * ht nl cr sp
4164 * 3 : special (must be base64 encoded)
4165 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4166 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004167
Tim Petersced69f82003-09-16 20:30:58 +00004168static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004169char utf7_category[128] = {
4170/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4171 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4172/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4173 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4174/* sp ! " # $ % & ' ( ) * + , - . / */
4175 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4176/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4177 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4178/* @ A B C D E F G H I J K L M N O */
4179 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4180/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4181 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4182/* ` a b c d e f g h i j k l m n o */
4183 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4184/* p q r s t u v w x y z { | } ~ del */
4185 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004186};
4187
Antoine Pitrou244651a2009-05-04 18:56:13 +00004188/* ENCODE_DIRECT: this character should be encoded as itself. The
4189 * answer depends on whether we are encoding set O as itself, and also
4190 * on whether we are encoding whitespace as itself. RFC2152 makes it
4191 * clear that the answers to these questions vary between
4192 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004193
Antoine Pitrou244651a2009-05-04 18:56:13 +00004194#define ENCODE_DIRECT(c, directO, directWS) \
4195 ((c) < 128 && (c) > 0 && \
4196 ((utf7_category[(c)] == 0) || \
4197 (directWS && (utf7_category[(c)] == 2)) || \
4198 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004199
Alexander Belopolsky40018472011-02-26 01:02:56 +00004200PyObject *
4201PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004202 Py_ssize_t size,
4203 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004204{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004205 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4206}
4207
Antoine Pitrou244651a2009-05-04 18:56:13 +00004208/* The decoder. The only state we preserve is our read position,
4209 * i.e. how many characters we have consumed. So if we end in the
4210 * middle of a shift sequence we have to back off the read position
4211 * and the output to the beginning of the sequence, otherwise we lose
4212 * all the shift state (seen bits, number of bits seen, high
4213 * surrogate). */
4214
Alexander Belopolsky40018472011-02-26 01:02:56 +00004215PyObject *
4216PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004217 Py_ssize_t size,
4218 const char *errors,
4219 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004220{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004221 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004222 Py_ssize_t startinpos;
4223 Py_ssize_t endinpos;
4224 Py_ssize_t outpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004225 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004226 PyObject *unicode;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004227 const char *errmsg = "";
4228 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004229 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004230 unsigned int base64bits = 0;
4231 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004232 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004233 PyObject *errorHandler = NULL;
4234 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004235
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004236 /* Start off assuming it's all ASCII. Widen later as necessary. */
4237 unicode = PyUnicode_New(size, 127);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004238 if (!unicode)
4239 return NULL;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004240 if (size == 0) {
4241 if (consumed)
4242 *consumed = 0;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004243 return unicode;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004244 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004245
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004246 shiftOutStart = outpos = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004247 e = s + size;
4248
4249 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004250 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004251 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004252 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004253
Antoine Pitrou244651a2009-05-04 18:56:13 +00004254 if (inShift) { /* in a base-64 section */
4255 if (IS_BASE64(ch)) { /* consume a base-64 character */
4256 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4257 base64bits += 6;
4258 s++;
4259 if (base64bits >= 16) {
4260 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004261 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004262 base64bits -= 16;
4263 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
4264 if (surrogate) {
4265 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004266 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4267 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004268 if (unicode_putchar(&unicode, &outpos, ch2) < 0)
4269 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004270 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004271 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004272 }
4273 else {
Antoine Pitrou78edf752011-11-15 01:44:16 +01004274 if (unicode_putchar(&unicode, &outpos, surrogate) < 0)
4275 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004276 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004277 }
4278 }
Victor Stinner551ac952011-11-29 22:58:13 +01004279 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004280 /* first surrogate */
4281 surrogate = outCh;
4282 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004283 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004284 if (unicode_putchar(&unicode, &outpos, outCh) < 0)
4285 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004286 }
4287 }
4288 }
4289 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004290 inShift = 0;
4291 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004292 if (surrogate) {
Antoine Pitrou78edf752011-11-15 01:44:16 +01004293 if (unicode_putchar(&unicode, &outpos, surrogate) < 0)
4294 goto onError;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004295 surrogate = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004296 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004297 if (base64bits > 0) { /* left-over bits */
4298 if (base64bits >= 6) {
4299 /* We've seen at least one base-64 character */
4300 errmsg = "partial character in shift sequence";
4301 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004302 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004303 else {
4304 /* Some bits remain; they should be zero */
4305 if (base64buffer != 0) {
4306 errmsg = "non-zero padding bits in shift sequence";
4307 goto utf7Error;
4308 }
4309 }
4310 }
4311 if (ch != '-') {
4312 /* '-' is absorbed; other terminating
4313 characters are preserved */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004314 if (unicode_putchar(&unicode, &outpos, ch) < 0)
4315 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004316 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004317 }
4318 }
4319 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004320 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004321 s++; /* consume '+' */
4322 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004323 s++;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004324 if (unicode_putchar(&unicode, &outpos, '+') < 0)
4325 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004326 }
4327 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004328 inShift = 1;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004329 shiftOutStart = outpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004330 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004331 }
4332 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004333 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004334 if (unicode_putchar(&unicode, &outpos, ch) < 0)
4335 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004336 s++;
4337 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004338 else {
4339 startinpos = s-starts;
4340 s++;
4341 errmsg = "unexpected special character";
4342 goto utf7Error;
4343 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004344 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004345utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004346 endinpos = s-starts;
4347 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00004348 errors, &errorHandler,
4349 "utf7", errmsg,
4350 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004351 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004352 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004353 }
4354
Antoine Pitrou244651a2009-05-04 18:56:13 +00004355 /* end of string */
4356
4357 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4358 /* if we're in an inconsistent state, that's an error */
4359 if (surrogate ||
4360 (base64bits >= 6) ||
4361 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004362 endinpos = size;
4363 if (unicode_decode_call_errorhandler(
4364 errors, &errorHandler,
4365 "utf7", "unterminated shift sequence",
4366 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004367 &unicode, &outpos))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004368 goto onError;
4369 if (s < e)
4370 goto restart;
4371 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004372 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004373
4374 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004375 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004376 if (inShift) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004377 outpos = shiftOutStart; /* back off output */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004378 *consumed = startinpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004379 }
4380 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004381 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004382 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004383 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004384
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004385 if (unicode_resize(&unicode, outpos) < 0)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004386 goto onError;
4387
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004388 Py_XDECREF(errorHandler);
4389 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01004390 return unicode_result(unicode);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004391
Benjamin Peterson29060642009-01-31 22:14:21 +00004392 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004393 Py_XDECREF(errorHandler);
4394 Py_XDECREF(exc);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004395 Py_DECREF(unicode);
4396 return NULL;
4397}
4398
4399
Alexander Belopolsky40018472011-02-26 01:02:56 +00004400PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004401_PyUnicode_EncodeUTF7(PyObject *str,
4402 int base64SetO,
4403 int base64WhiteSpace,
4404 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004405{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004406 int kind;
4407 void *data;
4408 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004409 PyObject *v;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004410 Py_ssize_t allocated;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004411 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004412 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004413 unsigned int base64bits = 0;
4414 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004415 char * out;
4416 char * start;
4417
Benjamin Petersonbac79492012-01-14 13:34:47 -05004418 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004419 return NULL;
4420 kind = PyUnicode_KIND(str);
4421 data = PyUnicode_DATA(str);
4422 len = PyUnicode_GET_LENGTH(str);
4423
4424 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004425 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004426
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004427 /* It might be possible to tighten this worst case */
4428 allocated = 8 * len;
4429 if (allocated / 8 != len)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004430 return PyErr_NoMemory();
4431
Antoine Pitrou244651a2009-05-04 18:56:13 +00004432 v = PyBytes_FromStringAndSize(NULL, allocated);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004433 if (v == NULL)
4434 return NULL;
4435
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004436 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004437 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004438 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004439
Antoine Pitrou244651a2009-05-04 18:56:13 +00004440 if (inShift) {
4441 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4442 /* shifting out */
4443 if (base64bits) { /* output remaining bits */
4444 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4445 base64buffer = 0;
4446 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004447 }
4448 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004449 /* Characters not in the BASE64 set implicitly unshift the sequence
4450 so no '-' is required, except if the character is itself a '-' */
4451 if (IS_BASE64(ch) || ch == '-') {
4452 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004453 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004454 *out++ = (char) ch;
4455 }
4456 else {
4457 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004458 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004459 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004460 else { /* not in a shift sequence */
4461 if (ch == '+') {
4462 *out++ = '+';
4463 *out++ = '-';
4464 }
4465 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4466 *out++ = (char) ch;
4467 }
4468 else {
4469 *out++ = '+';
4470 inShift = 1;
4471 goto encode_char;
4472 }
4473 }
4474 continue;
4475encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004476 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004477 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004478
Antoine Pitrou244651a2009-05-04 18:56:13 +00004479 /* code first surrogate */
4480 base64bits += 16;
4481 base64buffer = (base64buffer << 16) | 0xd800 | ((ch-0x10000) >> 10);
4482 while (base64bits >= 6) {
4483 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4484 base64bits -= 6;
4485 }
4486 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004487 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004488 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004489 base64bits += 16;
4490 base64buffer = (base64buffer << 16) | ch;
4491 while (base64bits >= 6) {
4492 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4493 base64bits -= 6;
4494 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004495 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004496 if (base64bits)
4497 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4498 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004499 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004500 if (_PyBytes_Resize(&v, out - start) < 0)
4501 return NULL;
4502 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004503}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004504PyObject *
4505PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4506 Py_ssize_t size,
4507 int base64SetO,
4508 int base64WhiteSpace,
4509 const char *errors)
4510{
4511 PyObject *result;
4512 PyObject *tmp = PyUnicode_FromUnicode(s, size);
4513 if (tmp == NULL)
4514 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004515 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004516 base64WhiteSpace, errors);
4517 Py_DECREF(tmp);
4518 return result;
4519}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004520
Antoine Pitrou244651a2009-05-04 18:56:13 +00004521#undef IS_BASE64
4522#undef FROM_BASE64
4523#undef TO_BASE64
4524#undef DECODE_DIRECT
4525#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004526
Guido van Rossumd57fd912000-03-10 22:53:23 +00004527/* --- UTF-8 Codec -------------------------------------------------------- */
4528
Tim Petersced69f82003-09-16 20:30:58 +00004529static
Guido van Rossumd57fd912000-03-10 22:53:23 +00004530char utf8_code_length[256] = {
Ezio Melotti57221d02010-07-01 07:32:02 +00004531 /* Map UTF-8 encoded prefix byte to sequence length. Zero means
4532 illegal prefix. See RFC 3629 for details */
4533 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 00-0F */
4534 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Victor Stinner4a2b7a12010-08-13 14:03:48 +00004535 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Guido van Rossumd57fd912000-03-10 22:53:23 +00004536 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4537 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4538 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4539 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Ezio Melotti57221d02010-07-01 07:32:02 +00004540 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 70-7F */
4541 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 +00004542 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4543 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
Ezio Melotti57221d02010-07-01 07:32:02 +00004544 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* B0-BF */
4545 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* C0-C1 + C2-CF */
4546 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* D0-DF */
4547 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* E0-EF */
4548 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 +00004549};
4550
Alexander Belopolsky40018472011-02-26 01:02:56 +00004551PyObject *
4552PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004553 Py_ssize_t size,
4554 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004555{
Walter Dörwald69652032004-09-07 20:24:22 +00004556 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4557}
4558
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004559#include "stringlib/ucs1lib.h"
4560#include "stringlib/codecs.h"
4561#include "stringlib/undef.h"
4562
4563#include "stringlib/ucs2lib.h"
4564#include "stringlib/codecs.h"
4565#include "stringlib/undef.h"
4566
4567#include "stringlib/ucs4lib.h"
4568#include "stringlib/codecs.h"
4569#include "stringlib/undef.h"
4570
Antoine Pitrouab868312009-01-10 15:40:25 +00004571/* Mask to check or force alignment of a pointer to C 'long' boundaries */
4572#define LONG_PTR_MASK (size_t) (SIZEOF_LONG - 1)
4573
4574/* Mask to quickly check whether a C 'long' contains a
4575 non-ASCII, UTF8-encoded char. */
4576#if (SIZEOF_LONG == 8)
4577# define ASCII_CHAR_MASK 0x8080808080808080L
4578#elif (SIZEOF_LONG == 4)
4579# define ASCII_CHAR_MASK 0x80808080L
4580#else
4581# error C 'long' size should be either 4 or 8!
4582#endif
4583
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004584/* Scans a UTF-8 string and returns the maximum character to be expected
4585 and the size of the decoded unicode string.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004586
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004587 This function doesn't check for errors, these checks are performed in
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004588 PyUnicode_DecodeUTF8Stateful.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004589 */
4590static Py_UCS4
Victor Stinnera1d12bb2011-12-11 21:53:09 +01004591utf8_scanner(const unsigned char *p, Py_ssize_t string_size, Py_ssize_t *unicode_size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004592{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004593 Py_ssize_t char_count = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004594 const unsigned char *end = p + string_size;
4595 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004596
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004597 assert(unicode_size != NULL);
4598
4599 /* By having a cascade of independent loops which fallback onto each
4600 other, we minimize the amount of work done in the average loop
4601 iteration, and we also maximize the CPU's ability to predict
4602 branches correctly (because a given condition will have always the
4603 same boolean outcome except perhaps in the last iteration of the
4604 corresponding loop).
4605 In the general case this brings us rather close to decoding
4606 performance pre-PEP 393, despite the two-pass decoding.
4607
4608 Note that the pure ASCII loop is not duplicated once a non-ASCII
4609 character has been encountered. It is actually a pessimization (by
4610 a significant factor) to use this loop on text with many non-ASCII
4611 characters, and it is important to avoid bad performance on valid
4612 utf-8 data (invalid utf-8 being a different can of worms).
4613 */
4614
4615 /* ASCII */
4616 for (; p < end; ++p) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004617 /* Only check value if it's not a ASCII char... */
4618 if (*p < 0x80) {
4619 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
4620 an explanation. */
4621 if (!((size_t) p & LONG_PTR_MASK)) {
4622 /* Help register allocation */
4623 register const unsigned char *_p = p;
4624 while (_p < aligned_end) {
4625 unsigned long value = *(unsigned long *) _p;
4626 if (value & ASCII_CHAR_MASK)
4627 break;
4628 _p += SIZEOF_LONG;
4629 char_count += SIZEOF_LONG;
4630 }
4631 p = _p;
4632 if (p == end)
4633 break;
4634 }
4635 }
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004636 if (*p < 0x80)
4637 ++char_count;
4638 else
4639 goto _ucs1loop;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004640 }
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004641 *unicode_size = char_count;
4642 return 127;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004643
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004644_ucs1loop:
4645 for (; p < end; ++p) {
4646 if (*p < 0xc4)
4647 char_count += ((*p & 0xc0) != 0x80);
4648 else
4649 goto _ucs2loop;
4650 }
4651 *unicode_size = char_count;
4652 return 255;
4653
4654_ucs2loop:
4655 for (; p < end; ++p) {
4656 if (*p < 0xf0)
4657 char_count += ((*p & 0xc0) != 0x80);
4658 else
4659 goto _ucs4loop;
4660 }
4661 *unicode_size = char_count;
4662 return 65535;
4663
4664_ucs4loop:
4665 for (; p < end; ++p) {
4666 char_count += ((*p & 0xc0) != 0x80);
4667 }
4668 *unicode_size = char_count;
4669 return 65537;
4670}
4671
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004672/* Similar to PyUnicode_WRITE but may attempt to widen and resize the string
Victor Stinner785938e2011-12-11 20:09:03 +01004673 in case of errors. Implicit parameters: unicode, kind, data, onError.
4674 Potential resizing overallocates, so the result needs to shrink at the end.
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004675*/
Victor Stinner785938e2011-12-11 20:09:03 +01004676#define WRITE_MAYBE_FAIL(index, value) \
4677 do { \
4678 Py_ssize_t pos = index; \
4679 if (pos > PyUnicode_GET_LENGTH(unicode) && \
4680 unicode_resize(&unicode, pos + pos/8) < 0) \
4681 goto onError; \
4682 if (unicode_putchar(&unicode, &pos, value) < 0) \
4683 goto onError; \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004684 } while (0)
4685
Victor Stinnerbf6e5602011-12-12 01:53:47 +01004686static PyObject *
Victor Stinner785938e2011-12-11 20:09:03 +01004687decode_utf8_errors(const char *starts,
4688 Py_ssize_t size,
4689 const char *errors,
4690 Py_ssize_t *consumed,
4691 const char *s,
4692 PyObject *unicode,
4693 Py_ssize_t i)
Walter Dörwald69652032004-09-07 20:24:22 +00004694{
Guido van Rossumd57fd912000-03-10 22:53:23 +00004695 int n;
Ezio Melotti57221d02010-07-01 07:32:02 +00004696 int k;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004697 Py_ssize_t startinpos;
4698 Py_ssize_t endinpos;
Victor Stinner785938e2011-12-11 20:09:03 +01004699 const char *e = starts + size;
4700 const char *aligned_end;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004701 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004702 PyObject *errorHandler = NULL;
4703 PyObject *exc = NULL;
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004704
Antoine Pitrouab868312009-01-10 15:40:25 +00004705 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004706
4707 while (s < e) {
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004708 Py_UCS4 ch = (unsigned char)*s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004709
4710 if (ch < 0x80) {
Antoine Pitrouab868312009-01-10 15:40:25 +00004711 /* Fast path for runs of ASCII characters. Given that common UTF-8
4712 input will consist of an overwhelming majority of ASCII
4713 characters, we try to optimize for this case by checking
4714 as many characters as a C 'long' can contain.
4715 First, check if we can do an aligned read, as most CPUs have
4716 a penalty for unaligned reads.
4717 */
4718 if (!((size_t) s & LONG_PTR_MASK)) {
4719 /* Help register allocation */
4720 register const char *_s = s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004721 register Py_ssize_t _i = i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004722 while (_s < aligned_end) {
4723 /* Read a whole long at a time (either 4 or 8 bytes),
4724 and do a fast unrolled copy if it only contains ASCII
4725 characters. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004726 unsigned long value = *(unsigned long *) _s;
4727 if (value & ASCII_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00004728 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004729 WRITE_MAYBE_FAIL(_i+0, _s[0]);
4730 WRITE_MAYBE_FAIL(_i+1, _s[1]);
4731 WRITE_MAYBE_FAIL(_i+2, _s[2]);
4732 WRITE_MAYBE_FAIL(_i+3, _s[3]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004733#if (SIZEOF_LONG == 8)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004734 WRITE_MAYBE_FAIL(_i+4, _s[4]);
4735 WRITE_MAYBE_FAIL(_i+5, _s[5]);
4736 WRITE_MAYBE_FAIL(_i+6, _s[6]);
4737 WRITE_MAYBE_FAIL(_i+7, _s[7]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004738#endif
4739 _s += SIZEOF_LONG;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004740 _i += SIZEOF_LONG;
Antoine Pitrouab868312009-01-10 15:40:25 +00004741 }
4742 s = _s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004743 i = _i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004744 if (s == e)
4745 break;
4746 ch = (unsigned char)*s;
4747 }
4748 }
4749
4750 if (ch < 0x80) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004751 WRITE_MAYBE_FAIL(i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004752 s++;
4753 continue;
4754 }
4755
4756 n = utf8_code_length[ch];
4757
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004758 if (s + n > e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004759 if (consumed)
4760 break;
4761 else {
4762 errmsg = "unexpected end of data";
4763 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004764 endinpos = startinpos+1;
4765 for (k=1; (k < size-startinpos) && ((s[k]&0xC0) == 0x80); k++)
4766 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004767 goto utf8Error;
4768 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00004769 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004770
4771 switch (n) {
4772
4773 case 0:
Ezio Melotti57221d02010-07-01 07:32:02 +00004774 errmsg = "invalid start byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004775 startinpos = s-starts;
4776 endinpos = startinpos+1;
4777 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004778
4779 case 1:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004780 errmsg = "internal error";
Benjamin Peterson29060642009-01-31 22:14:21 +00004781 startinpos = s-starts;
4782 endinpos = startinpos+1;
4783 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004784
4785 case 2:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004786 if ((s[1] & 0xc0) != 0x80) {
Ezio Melotti57221d02010-07-01 07:32:02 +00004787 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004788 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004789 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00004790 goto utf8Error;
4791 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004792 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004793 assert ((ch > 0x007F) && (ch <= 0x07FF));
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004794 WRITE_MAYBE_FAIL(i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004795 break;
4796
4797 case 3:
Ezio Melotti9bf2b3a2010-07-03 04:52:19 +00004798 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
4799 will result in surrogates in range d800-dfff. Surrogates are
4800 not valid UTF-8 so they are rejected.
4801 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
4802 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
Tim Petersced69f82003-09-16 20:30:58 +00004803 if ((s[1] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004804 (s[2] & 0xc0) != 0x80 ||
4805 ((unsigned char)s[0] == 0xE0 &&
4806 (unsigned char)s[1] < 0xA0) ||
4807 ((unsigned char)s[0] == 0xED &&
4808 (unsigned char)s[1] > 0x9F)) {
4809 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004810 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004811 endinpos = startinpos + 1;
4812
4813 /* if s[1] first two bits are 1 and 0, then the invalid
4814 continuation byte is s[2], so increment endinpos by 1,
4815 if not, s[1] is invalid and endinpos doesn't need to
4816 be incremented. */
4817 if ((s[1] & 0xC0) == 0x80)
4818 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004819 goto utf8Error;
4820 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004821 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004822 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004823 WRITE_MAYBE_FAIL(i++, ch);
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004824 break;
4825
4826 case 4:
4827 if ((s[1] & 0xc0) != 0x80 ||
4828 (s[2] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004829 (s[3] & 0xc0) != 0x80 ||
4830 ((unsigned char)s[0] == 0xF0 &&
4831 (unsigned char)s[1] < 0x90) ||
4832 ((unsigned char)s[0] == 0xF4 &&
4833 (unsigned char)s[1] > 0x8F)) {
4834 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004835 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004836 endinpos = startinpos + 1;
4837 if ((s[1] & 0xC0) == 0x80) {
4838 endinpos++;
4839 if ((s[2] & 0xC0) == 0x80)
4840 endinpos++;
4841 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004842 goto utf8Error;
4843 }
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004844 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
Ezio Melotti57221d02010-07-01 07:32:02 +00004845 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
Victor Stinner8faf8212011-12-08 22:14:11 +01004846 assert ((ch > 0xFFFF) && (ch <= MAX_UNICODE));
Ezio Melotti57221d02010-07-01 07:32:02 +00004847
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004848 WRITE_MAYBE_FAIL(i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004849 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004850 }
4851 s += n;
Benjamin Peterson29060642009-01-31 22:14:21 +00004852 continue;
Tim Petersced69f82003-09-16 20:30:58 +00004853
Benjamin Peterson29060642009-01-31 22:14:21 +00004854 utf8Error:
Benjamin Peterson29060642009-01-31 22:14:21 +00004855 if (unicode_decode_call_errorhandler(
4856 errors, &errorHandler,
Victor Stinnercbe01342012-02-14 01:17:45 +01004857 "utf-8", errmsg,
Benjamin Peterson29060642009-01-31 22:14:21 +00004858 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004859 &unicode, &i))
Benjamin Peterson29060642009-01-31 22:14:21 +00004860 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004861 /* Update data because unicode_decode_call_errorhandler might have
4862 re-created or resized the unicode object. */
Benjamin Peterson29060642009-01-31 22:14:21 +00004863 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004864 }
Walter Dörwald69652032004-09-07 20:24:22 +00004865 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00004866 *consumed = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004867
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004868 /* Adjust length and ready string when it contained errors and
4869 is of the old resizable kind. */
Victor Stinner785938e2011-12-11 20:09:03 +01004870 if (unicode_resize(&unicode, i) < 0)
4871 goto onError;
4872 unicode_adjust_maxchar(&unicode);
4873 if (unicode == NULL)
4874 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004875
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004876 Py_XDECREF(errorHandler);
4877 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02004878 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01004879 return unicode;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004880
Benjamin Peterson29060642009-01-31 22:14:21 +00004881 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004882 Py_XDECREF(errorHandler);
4883 Py_XDECREF(exc);
Victor Stinner785938e2011-12-11 20:09:03 +01004884 Py_XDECREF(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004885 return NULL;
4886}
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004887#undef WRITE_MAYBE_FAIL
Antoine Pitrouab868312009-01-10 15:40:25 +00004888
Victor Stinner785938e2011-12-11 20:09:03 +01004889PyObject *
4890PyUnicode_DecodeUTF8Stateful(const char *s,
4891 Py_ssize_t size,
4892 const char *errors,
4893 Py_ssize_t *consumed)
4894{
4895 Py_UCS4 maxchar = 0;
4896 Py_ssize_t unicode_size;
4897 int has_errors = 0;
4898 PyObject *unicode;
4899 int kind;
4900 void *data;
4901 const char *starts = s;
4902 const char *e;
4903 Py_ssize_t i;
4904
4905 if (size == 0) {
4906 if (consumed)
4907 *consumed = 0;
Victor Stinner382955f2011-12-11 21:44:00 +01004908 Py_INCREF(unicode_empty);
4909 return unicode_empty;
Victor Stinner785938e2011-12-11 20:09:03 +01004910 }
4911
Victor Stinnera1d12bb2011-12-11 21:53:09 +01004912 maxchar = utf8_scanner((const unsigned char *)s, size, &unicode_size);
Victor Stinner785938e2011-12-11 20:09:03 +01004913
4914 /* When the string is ASCII only, just use memcpy and return.
4915 unicode_size may be != size if there is an incomplete UTF-8
4916 sequence at the end of the ASCII block. */
4917 if (maxchar < 128 && size == unicode_size) {
4918 if (consumed)
4919 *consumed = size;
Victor Stinnerab870212011-12-17 22:39:43 +01004920 return unicode_fromascii((const unsigned char *)s, size);
Victor Stinner785938e2011-12-11 20:09:03 +01004921 }
4922
4923 unicode = PyUnicode_New(unicode_size, maxchar);
4924 if (!unicode)
4925 return NULL;
4926 kind = PyUnicode_KIND(unicode);
4927 data = PyUnicode_DATA(unicode);
4928
4929 /* Unpack UTF-8 encoded data */
4930 i = 0;
4931 e = starts + size;
4932 switch (kind) {
4933 case PyUnicode_1BYTE_KIND:
4934 has_errors = ucs1lib_utf8_try_decode(s, e, (Py_UCS1 *) data, &s, &i);
4935 break;
4936 case PyUnicode_2BYTE_KIND:
4937 has_errors = ucs2lib_utf8_try_decode(s, e, (Py_UCS2 *) data, &s, &i);
4938 break;
4939 case PyUnicode_4BYTE_KIND:
4940 has_errors = ucs4lib_utf8_try_decode(s, e, (Py_UCS4 *) data, &s, &i);
4941 break;
4942 }
4943 if (!has_errors) {
4944 /* Ensure the unicode size calculation was correct */
4945 assert(i == unicode_size);
4946 assert(s == e);
4947 if (consumed)
4948 *consumed = size;
4949 return unicode;
4950 }
4951
4952 /* In case of errors, maxchar and size computation might be incorrect;
4953 code below refits and resizes as necessary. */
4954 return decode_utf8_errors(starts, size, errors, consumed, s, unicode, i);
4955}
4956
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004957#ifdef __APPLE__
4958
4959/* Simplified UTF-8 decoder using surrogateescape error handler,
4960 used to decode the command line arguments on Mac OS X. */
4961
4962wchar_t*
4963_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4964{
4965 int n;
4966 const char *e;
4967 wchar_t *unicode, *p;
4968
4969 /* Note: size will always be longer than the resulting Unicode
4970 character count */
4971 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1)) {
4972 PyErr_NoMemory();
4973 return NULL;
4974 }
4975 unicode = PyMem_Malloc((size + 1) * sizeof(wchar_t));
4976 if (!unicode)
4977 return NULL;
4978
4979 /* Unpack UTF-8 encoded data */
4980 p = unicode;
4981 e = s + size;
4982 while (s < e) {
4983 Py_UCS4 ch = (unsigned char)*s;
4984
4985 if (ch < 0x80) {
4986 *p++ = (wchar_t)ch;
4987 s++;
4988 continue;
4989 }
4990
4991 n = utf8_code_length[ch];
4992 if (s + n > e) {
4993 goto surrogateescape;
4994 }
4995
4996 switch (n) {
4997 case 0:
4998 case 1:
4999 goto surrogateescape;
5000
5001 case 2:
5002 if ((s[1] & 0xc0) != 0x80)
5003 goto surrogateescape;
5004 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
5005 assert ((ch > 0x007F) && (ch <= 0x07FF));
5006 *p++ = (wchar_t)ch;
5007 break;
5008
5009 case 3:
5010 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
5011 will result in surrogates in range d800-dfff. Surrogates are
5012 not valid UTF-8 so they are rejected.
5013 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
5014 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
5015 if ((s[1] & 0xc0) != 0x80 ||
5016 (s[2] & 0xc0) != 0x80 ||
5017 ((unsigned char)s[0] == 0xE0 &&
5018 (unsigned char)s[1] < 0xA0) ||
5019 ((unsigned char)s[0] == 0xED &&
5020 (unsigned char)s[1] > 0x9F)) {
5021
5022 goto surrogateescape;
5023 }
5024 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
5025 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005026 *p++ = (wchar_t)ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005027 break;
5028
5029 case 4:
5030 if ((s[1] & 0xc0) != 0x80 ||
5031 (s[2] & 0xc0) != 0x80 ||
5032 (s[3] & 0xc0) != 0x80 ||
5033 ((unsigned char)s[0] == 0xF0 &&
5034 (unsigned char)s[1] < 0x90) ||
5035 ((unsigned char)s[0] == 0xF4 &&
5036 (unsigned char)s[1] > 0x8F)) {
5037 goto surrogateescape;
5038 }
5039 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
5040 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
Victor Stinner8faf8212011-12-08 22:14:11 +01005041 assert ((ch > 0xFFFF) && (ch <= MAX_UNICODE));
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005042
5043#if SIZEOF_WCHAR_T == 4
5044 *p++ = (wchar_t)ch;
5045#else
5046 /* compute and append the two surrogates: */
Victor Stinner551ac952011-11-29 22:58:13 +01005047 *p++ = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
5048 *p++ = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005049#endif
5050 break;
5051 }
5052 s += n;
5053 continue;
5054
5055 surrogateescape:
5056 *p++ = 0xDC00 + ch;
5057 s++;
5058 }
5059 *p = L'\0';
5060 return unicode;
5061}
5062
5063#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00005064
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005065/* Primary internal function which creates utf8 encoded bytes objects.
5066
5067 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00005068 and allocate exactly as much space needed at the end. Else allocate the
5069 maximum possible needed (4 result bytes per Unicode character), and return
5070 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00005071*/
Tim Peters7e3d9612002-04-21 03:26:37 +00005072PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01005073_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005074{
Victor Stinner6099a032011-12-18 14:22:26 +01005075 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005076 void *data;
5077 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00005078
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005079 if (!PyUnicode_Check(unicode)) {
5080 PyErr_BadArgument();
5081 return NULL;
5082 }
5083
5084 if (PyUnicode_READY(unicode) == -1)
5085 return NULL;
5086
Victor Stinnere90fe6a2011-10-01 16:48:13 +02005087 if (PyUnicode_UTF8(unicode))
5088 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
5089 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005090
5091 kind = PyUnicode_KIND(unicode);
5092 data = PyUnicode_DATA(unicode);
5093 size = PyUnicode_GET_LENGTH(unicode);
5094
Benjamin Petersonead6b532011-12-20 17:23:42 -06005095 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01005096 default:
5097 assert(0);
5098 case PyUnicode_1BYTE_KIND:
5099 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
5100 assert(!PyUnicode_IS_ASCII(unicode));
5101 return ucs1lib_utf8_encoder(unicode, data, size, errors);
5102 case PyUnicode_2BYTE_KIND:
5103 return ucs2lib_utf8_encoder(unicode, data, size, errors);
5104 case PyUnicode_4BYTE_KIND:
5105 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00005106 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005107}
5108
Alexander Belopolsky40018472011-02-26 01:02:56 +00005109PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005110PyUnicode_EncodeUTF8(const Py_UNICODE *s,
5111 Py_ssize_t size,
5112 const char *errors)
5113{
5114 PyObject *v, *unicode;
5115
5116 unicode = PyUnicode_FromUnicode(s, size);
5117 if (unicode == NULL)
5118 return NULL;
5119 v = _PyUnicode_AsUTF8String(unicode, errors);
5120 Py_DECREF(unicode);
5121 return v;
5122}
5123
5124PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005125PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005126{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005127 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005128}
5129
Walter Dörwald41980ca2007-08-16 21:55:45 +00005130/* --- UTF-32 Codec ------------------------------------------------------- */
5131
5132PyObject *
5133PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005134 Py_ssize_t size,
5135 const char *errors,
5136 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005137{
5138 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
5139}
5140
5141PyObject *
5142PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005143 Py_ssize_t size,
5144 const char *errors,
5145 int *byteorder,
5146 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005147{
5148 const char *starts = s;
5149 Py_ssize_t startinpos;
5150 Py_ssize_t endinpos;
5151 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005152 PyObject *unicode;
Mark Dickinson7db923c2010-06-12 09:10:14 +00005153 const unsigned char *q, *e;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005154 int bo = 0; /* assume native ordering by default */
5155 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00005156 /* Offsets from q for retrieving bytes in the right order. */
5157#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5158 int iorder[] = {0, 1, 2, 3};
5159#else
5160 int iorder[] = {3, 2, 1, 0};
5161#endif
5162 PyObject *errorHandler = NULL;
5163 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00005164
Walter Dörwald41980ca2007-08-16 21:55:45 +00005165 q = (unsigned char *)s;
5166 e = q + size;
5167
5168 if (byteorder)
5169 bo = *byteorder;
5170
5171 /* Check for BOM marks (U+FEFF) in the input and adjust current
5172 byte order setting accordingly. In native mode, the leading BOM
5173 mark is skipped, in all other modes, it is copied to the output
5174 stream as-is (giving a ZWNBSP character). */
5175 if (bo == 0) {
5176 if (size >= 4) {
5177 const Py_UCS4 bom = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
Benjamin Peterson29060642009-01-31 22:14:21 +00005178 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00005179#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00005180 if (bom == 0x0000FEFF) {
5181 q += 4;
5182 bo = -1;
5183 }
5184 else if (bom == 0xFFFE0000) {
5185 q += 4;
5186 bo = 1;
5187 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005188#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005189 if (bom == 0x0000FEFF) {
5190 q += 4;
5191 bo = 1;
5192 }
5193 else if (bom == 0xFFFE0000) {
5194 q += 4;
5195 bo = -1;
5196 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005197#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005198 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005199 }
5200
5201 if (bo == -1) {
5202 /* force LE */
5203 iorder[0] = 0;
5204 iorder[1] = 1;
5205 iorder[2] = 2;
5206 iorder[3] = 3;
5207 }
5208 else if (bo == 1) {
5209 /* force BE */
5210 iorder[0] = 3;
5211 iorder[1] = 2;
5212 iorder[2] = 1;
5213 iorder[3] = 0;
5214 }
5215
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005216 /* This might be one to much, because of a BOM */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005217 unicode = PyUnicode_New((size+3)/4, 127);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005218 if (!unicode)
5219 return NULL;
5220 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005221 return unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005222 outpos = 0;
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005223
Walter Dörwald41980ca2007-08-16 21:55:45 +00005224 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005225 Py_UCS4 ch;
5226 /* remaining bytes at the end? (size should be divisible by 4) */
5227 if (e-q<4) {
5228 if (consumed)
5229 break;
5230 errmsg = "truncated data";
5231 startinpos = ((const char *)q)-starts;
5232 endinpos = ((const char *)e)-starts;
5233 goto utf32Error;
5234 /* The remaining input chars are ignored if the callback
5235 chooses to skip the input */
5236 }
5237 ch = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
5238 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00005239
Benjamin Peterson29060642009-01-31 22:14:21 +00005240 if (ch >= 0x110000)
5241 {
5242 errmsg = "codepoint not in range(0x110000)";
5243 startinpos = ((const char *)q)-starts;
5244 endinpos = startinpos+4;
5245 goto utf32Error;
5246 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005247 if (unicode_putchar(&unicode, &outpos, ch) < 0)
5248 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005249 q += 4;
5250 continue;
5251 utf32Error:
Benjamin Peterson29060642009-01-31 22:14:21 +00005252 if (unicode_decode_call_errorhandler(
5253 errors, &errorHandler,
5254 "utf32", errmsg,
5255 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005256 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005257 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005258 }
5259
5260 if (byteorder)
5261 *byteorder = bo;
5262
5263 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005264 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005265
5266 /* Adjust length */
Victor Stinner16e6a802011-12-12 13:24:15 +01005267 if (unicode_resize(&unicode, outpos) < 0)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005268 goto onError;
5269
5270 Py_XDECREF(errorHandler);
5271 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005272 return unicode_result(unicode);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005273
Benjamin Peterson29060642009-01-31 22:14:21 +00005274 onError:
Walter Dörwald41980ca2007-08-16 21:55:45 +00005275 Py_DECREF(unicode);
5276 Py_XDECREF(errorHandler);
5277 Py_XDECREF(exc);
5278 return NULL;
5279}
5280
5281PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005282_PyUnicode_EncodeUTF32(PyObject *str,
5283 const char *errors,
5284 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005285{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005286 int kind;
5287 void *data;
5288 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005289 PyObject *v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005290 unsigned char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005291 Py_ssize_t nsize, bytesize, i;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005292 /* Offsets from p for storing byte pairs in the right order. */
5293#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5294 int iorder[] = {0, 1, 2, 3};
5295#else
5296 int iorder[] = {3, 2, 1, 0};
5297#endif
5298
Benjamin Peterson29060642009-01-31 22:14:21 +00005299#define STORECHAR(CH) \
5300 do { \
5301 p[iorder[3]] = ((CH) >> 24) & 0xff; \
5302 p[iorder[2]] = ((CH) >> 16) & 0xff; \
5303 p[iorder[1]] = ((CH) >> 8) & 0xff; \
5304 p[iorder[0]] = (CH) & 0xff; \
5305 p += 4; \
Walter Dörwald41980ca2007-08-16 21:55:45 +00005306 } while(0)
5307
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005308 if (!PyUnicode_Check(str)) {
5309 PyErr_BadArgument();
5310 return NULL;
5311 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005312 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005313 return NULL;
5314 kind = PyUnicode_KIND(str);
5315 data = PyUnicode_DATA(str);
5316 len = PyUnicode_GET_LENGTH(str);
5317
5318 nsize = len + (byteorder == 0);
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005319 bytesize = nsize * 4;
5320 if (bytesize / 4 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005321 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005322 v = PyBytes_FromStringAndSize(NULL, bytesize);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005323 if (v == NULL)
5324 return NULL;
5325
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005326 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005327 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005328 STORECHAR(0xFEFF);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005329 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005330 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005331
5332 if (byteorder == -1) {
5333 /* force LE */
5334 iorder[0] = 0;
5335 iorder[1] = 1;
5336 iorder[2] = 2;
5337 iorder[3] = 3;
5338 }
5339 else if (byteorder == 1) {
5340 /* force BE */
5341 iorder[0] = 3;
5342 iorder[1] = 2;
5343 iorder[2] = 1;
5344 iorder[3] = 0;
5345 }
5346
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005347 for (i = 0; i < len; i++)
5348 STORECHAR(PyUnicode_READ(kind, data, i));
Guido van Rossum98297ee2007-11-06 21:34:58 +00005349
5350 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005351 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005352#undef STORECHAR
5353}
5354
Alexander Belopolsky40018472011-02-26 01:02:56 +00005355PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005356PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5357 Py_ssize_t size,
5358 const char *errors,
5359 int byteorder)
5360{
5361 PyObject *result;
5362 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5363 if (tmp == NULL)
5364 return NULL;
5365 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5366 Py_DECREF(tmp);
5367 return result;
5368}
5369
5370PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005371PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005372{
Victor Stinnerb960b342011-11-20 19:12:52 +01005373 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005374}
5375
Guido van Rossumd57fd912000-03-10 22:53:23 +00005376/* --- UTF-16 Codec ------------------------------------------------------- */
5377
Tim Peters772747b2001-08-09 22:21:55 +00005378PyObject *
5379PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005380 Py_ssize_t size,
5381 const char *errors,
5382 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005383{
Walter Dörwald69652032004-09-07 20:24:22 +00005384 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5385}
5386
Antoine Pitrouab868312009-01-10 15:40:25 +00005387/* Two masks for fast checking of whether a C 'long' may contain
5388 UTF16-encoded surrogate characters. This is an efficient heuristic,
5389 assuming that non-surrogate characters with a code point >= 0x8000 are
5390 rare in most input.
5391 FAST_CHAR_MASK is used when the input is in native byte ordering,
5392 SWAPPED_FAST_CHAR_MASK when the input is in byteswapped ordering.
Benjamin Peterson29060642009-01-31 22:14:21 +00005393*/
Antoine Pitrouab868312009-01-10 15:40:25 +00005394#if (SIZEOF_LONG == 8)
5395# define FAST_CHAR_MASK 0x8000800080008000L
5396# define SWAPPED_FAST_CHAR_MASK 0x0080008000800080L
5397#elif (SIZEOF_LONG == 4)
5398# define FAST_CHAR_MASK 0x80008000L
5399# define SWAPPED_FAST_CHAR_MASK 0x00800080L
5400#else
5401# error C 'long' size should be either 4 or 8!
5402#endif
5403
Walter Dörwald69652032004-09-07 20:24:22 +00005404PyObject *
5405PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005406 Py_ssize_t size,
5407 const char *errors,
5408 int *byteorder,
5409 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005410{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005411 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005412 Py_ssize_t startinpos;
5413 Py_ssize_t endinpos;
5414 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005415 PyObject *unicode;
Antoine Pitrouab868312009-01-10 15:40:25 +00005416 const unsigned char *q, *e, *aligned_end;
Tim Peters772747b2001-08-09 22:21:55 +00005417 int bo = 0; /* assume native ordering by default */
Antoine Pitrouab868312009-01-10 15:40:25 +00005418 int native_ordering = 0;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005419 const char *errmsg = "";
Tim Peters772747b2001-08-09 22:21:55 +00005420 /* Offsets from q for retrieving byte pairs in the right order. */
5421#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5422 int ihi = 1, ilo = 0;
5423#else
5424 int ihi = 0, ilo = 1;
5425#endif
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005426 PyObject *errorHandler = NULL;
5427 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005428
5429 /* Note: size will always be longer than the resulting Unicode
5430 character count */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005431 unicode = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005432 if (!unicode)
5433 return NULL;
5434 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005435 return unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005436 outpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005437
Tim Peters772747b2001-08-09 22:21:55 +00005438 q = (unsigned char *)s;
Antoine Pitrouab868312009-01-10 15:40:25 +00005439 e = q + size - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005440
5441 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005442 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005443
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005444 /* Check for BOM marks (U+FEFF) in the input and adjust current
5445 byte order setting accordingly. In native mode, the leading BOM
5446 mark is skipped, in all other modes, it is copied to the output
5447 stream as-is (giving a ZWNBSP character). */
5448 if (bo == 0) {
Walter Dörwald69652032004-09-07 20:24:22 +00005449 if (size >= 2) {
Victor Stinner24729f32011-11-10 20:31:37 +01005450 const Py_UCS4 bom = (q[ihi] << 8) | q[ilo];
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005451#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00005452 if (bom == 0xFEFF) {
5453 q += 2;
5454 bo = -1;
5455 }
5456 else if (bom == 0xFFFE) {
5457 q += 2;
5458 bo = 1;
5459 }
Tim Petersced69f82003-09-16 20:30:58 +00005460#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005461 if (bom == 0xFEFF) {
5462 q += 2;
5463 bo = 1;
5464 }
5465 else if (bom == 0xFFFE) {
5466 q += 2;
5467 bo = -1;
5468 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005469#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005470 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005471 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005472
Tim Peters772747b2001-08-09 22:21:55 +00005473 if (bo == -1) {
5474 /* force LE */
5475 ihi = 1;
5476 ilo = 0;
5477 }
5478 else if (bo == 1) {
5479 /* force BE */
5480 ihi = 0;
5481 ilo = 1;
5482 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005483#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5484 native_ordering = ilo < ihi;
5485#else
5486 native_ordering = ilo > ihi;
5487#endif
Tim Peters772747b2001-08-09 22:21:55 +00005488
Antoine Pitrouab868312009-01-10 15:40:25 +00005489 aligned_end = (const unsigned char *) ((size_t) e & ~LONG_PTR_MASK);
Tim Peters772747b2001-08-09 22:21:55 +00005490 while (q < e) {
Victor Stinner24729f32011-11-10 20:31:37 +01005491 Py_UCS4 ch;
Antoine Pitrouab868312009-01-10 15:40:25 +00005492 /* First check for possible aligned read of a C 'long'. Unaligned
5493 reads are more expensive, better to defer to another iteration. */
5494 if (!((size_t) q & LONG_PTR_MASK)) {
5495 /* Fast path for runs of non-surrogate chars. */
5496 register const unsigned char *_q = q;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005497 int kind = PyUnicode_KIND(unicode);
5498 void *data = PyUnicode_DATA(unicode);
5499 while (_q < aligned_end) {
5500 unsigned long block = * (unsigned long *) _q;
5501 unsigned short *pblock = (unsigned short*)&block;
5502 Py_UCS4 maxch;
5503 if (native_ordering) {
5504 /* Can use buffer directly */
5505 if (block & FAST_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00005506 break;
Antoine Pitrouab868312009-01-10 15:40:25 +00005507 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005508 else {
5509 /* Need to byte-swap */
5510 unsigned char *_p = (unsigned char*)pblock;
5511 if (block & SWAPPED_FAST_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00005512 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005513 _p[0] = _q[1];
5514 _p[1] = _q[0];
5515 _p[2] = _q[3];
5516 _p[3] = _q[2];
Antoine Pitrouab868312009-01-10 15:40:25 +00005517#if (SIZEOF_LONG == 8)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005518 _p[4] = _q[5];
5519 _p[5] = _q[4];
5520 _p[6] = _q[7];
5521 _p[7] = _q[6];
Antoine Pitrouab868312009-01-10 15:40:25 +00005522#endif
Antoine Pitrouab868312009-01-10 15:40:25 +00005523 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005524 maxch = Py_MAX(pblock[0], pblock[1]);
5525#if SIZEOF_LONG == 8
5526 maxch = Py_MAX(maxch, Py_MAX(pblock[2], pblock[3]));
5527#endif
5528 if (maxch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
5529 if (unicode_widen(&unicode, maxch) < 0)
5530 goto onError;
5531 kind = PyUnicode_KIND(unicode);
5532 data = PyUnicode_DATA(unicode);
5533 }
5534 PyUnicode_WRITE(kind, data, outpos++, pblock[0]);
5535 PyUnicode_WRITE(kind, data, outpos++, pblock[1]);
5536#if SIZEOF_LONG == 8
5537 PyUnicode_WRITE(kind, data, outpos++, pblock[2]);
5538 PyUnicode_WRITE(kind, data, outpos++, pblock[3]);
5539#endif
5540 _q += SIZEOF_LONG;
Antoine Pitrouab868312009-01-10 15:40:25 +00005541 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005542 q = _q;
5543 if (q >= e)
5544 break;
5545 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005546 ch = (q[ihi] << 8) | q[ilo];
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005547
Benjamin Peterson14339b62009-01-31 16:36:08 +00005548 q += 2;
Benjamin Peterson29060642009-01-31 22:14:21 +00005549
Victor Stinner551ac952011-11-29 22:58:13 +01005550 if (!Py_UNICODE_IS_SURROGATE(ch)) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005551 if (unicode_putchar(&unicode, &outpos, ch) < 0)
5552 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005553 continue;
5554 }
5555
5556 /* UTF-16 code pair: */
5557 if (q > e) {
5558 errmsg = "unexpected end of data";
5559 startinpos = (((const char *)q) - 2) - starts;
5560 endinpos = ((const char *)e) + 1 - starts;
5561 goto utf16Error;
5562 }
Victor Stinner2e9cfad2011-11-20 18:40:27 +01005563 if (Py_UNICODE_IS_HIGH_SURROGATE(ch)) {
5564 Py_UCS4 ch2 = (q[ihi] << 8) | q[ilo];
Benjamin Peterson29060642009-01-31 22:14:21 +00005565 q += 2;
Victor Stinner2e9cfad2011-11-20 18:40:27 +01005566 if (Py_UNICODE_IS_LOW_SURROGATE(ch2)) {
Victor Stinner62aa4d02011-11-09 00:03:45 +01005567 if (unicode_putchar(&unicode, &outpos,
Victor Stinner2e9cfad2011-11-20 18:40:27 +01005568 Py_UNICODE_JOIN_SURROGATES(ch, ch2)) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005569 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005570 continue;
5571 }
5572 else {
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005573 errmsg = "illegal UTF-16 surrogate";
Benjamin Peterson29060642009-01-31 22:14:21 +00005574 startinpos = (((const char *)q)-4)-starts;
5575 endinpos = startinpos+2;
5576 goto utf16Error;
5577 }
5578
Benjamin Peterson14339b62009-01-31 16:36:08 +00005579 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005580 errmsg = "illegal encoding";
5581 startinpos = (((const char *)q)-2)-starts;
5582 endinpos = startinpos+2;
5583 /* Fall through to report the error */
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005584
Benjamin Peterson29060642009-01-31 22:14:21 +00005585 utf16Error:
Benjamin Peterson29060642009-01-31 22:14:21 +00005586 if (unicode_decode_call_errorhandler(
Antoine Pitrouab868312009-01-10 15:40:25 +00005587 errors,
5588 &errorHandler,
5589 "utf16", errmsg,
5590 &starts,
5591 (const char **)&e,
5592 &startinpos,
5593 &endinpos,
5594 &exc,
5595 (const char **)&q,
5596 &unicode,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005597 &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005598 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005599 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005600 /* remaining byte at the end? (size should be even) */
5601 if (e == q) {
5602 if (!consumed) {
5603 errmsg = "truncated data";
5604 startinpos = ((const char *)q) - starts;
5605 endinpos = ((const char *)e) + 1 - starts;
Antoine Pitrouab868312009-01-10 15:40:25 +00005606 if (unicode_decode_call_errorhandler(
5607 errors,
5608 &errorHandler,
5609 "utf16", errmsg,
5610 &starts,
5611 (const char **)&e,
5612 &startinpos,
5613 &endinpos,
5614 &exc,
5615 (const char **)&q,
5616 &unicode,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005617 &outpos))
Antoine Pitrouab868312009-01-10 15:40:25 +00005618 goto onError;
5619 /* The remaining input chars are ignored if the callback
5620 chooses to skip the input */
5621 }
5622 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005623
5624 if (byteorder)
5625 *byteorder = bo;
5626
Walter Dörwald69652032004-09-07 20:24:22 +00005627 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005628 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005629
Guido van Rossumd57fd912000-03-10 22:53:23 +00005630 /* Adjust length */
Victor Stinner16e6a802011-12-12 13:24:15 +01005631 if (unicode_resize(&unicode, outpos) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005632 goto onError;
5633
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005634 Py_XDECREF(errorHandler);
5635 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005636 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005637
Benjamin Peterson29060642009-01-31 22:14:21 +00005638 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005639 Py_DECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005640 Py_XDECREF(errorHandler);
5641 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005642 return NULL;
5643}
5644
Antoine Pitrouab868312009-01-10 15:40:25 +00005645#undef FAST_CHAR_MASK
5646#undef SWAPPED_FAST_CHAR_MASK
5647
Tim Peters772747b2001-08-09 22:21:55 +00005648PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005649_PyUnicode_EncodeUTF16(PyObject *str,
5650 const char *errors,
5651 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005652{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005653 int kind;
5654 void *data;
5655 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005656 PyObject *v;
Tim Peters772747b2001-08-09 22:21:55 +00005657 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005658 Py_ssize_t nsize, bytesize;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005659 Py_ssize_t i, pairs;
Tim Peters772747b2001-08-09 22:21:55 +00005660 /* Offsets from p for storing byte pairs in the right order. */
5661#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5662 int ihi = 1, ilo = 0;
5663#else
5664 int ihi = 0, ilo = 1;
5665#endif
5666
Benjamin Peterson29060642009-01-31 22:14:21 +00005667#define STORECHAR(CH) \
5668 do { \
5669 p[ihi] = ((CH) >> 8) & 0xff; \
5670 p[ilo] = (CH) & 0xff; \
5671 p += 2; \
Tim Peters772747b2001-08-09 22:21:55 +00005672 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005673
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005674 if (!PyUnicode_Check(str)) {
5675 PyErr_BadArgument();
5676 return NULL;
5677 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005678 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005679 return NULL;
5680 kind = PyUnicode_KIND(str);
5681 data = PyUnicode_DATA(str);
5682 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005683
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005684 pairs = 0;
5685 if (kind == PyUnicode_4BYTE_KIND)
5686 for (i = 0; i < len; i++)
5687 if (PyUnicode_READ(kind, data, i) >= 0x10000)
5688 pairs++;
5689 /* 2 * (len + pairs + (byteorder == 0)) */
5690 if (len > PY_SSIZE_T_MAX - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005691 return PyErr_NoMemory();
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005692 nsize = len + pairs + (byteorder == 0);
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005693 bytesize = nsize * 2;
5694 if (bytesize / 2 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005695 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005696 v = PyBytes_FromStringAndSize(NULL, bytesize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005697 if (v == NULL)
5698 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005699
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005700 p = (unsigned char *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005701 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005702 STORECHAR(0xFEFF);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005703 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005704 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005705
5706 if (byteorder == -1) {
5707 /* force LE */
5708 ihi = 1;
5709 ilo = 0;
5710 }
5711 else if (byteorder == 1) {
5712 /* force BE */
5713 ihi = 0;
5714 ilo = 1;
5715 }
5716
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005717 for (i = 0; i < len; i++) {
5718 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
5719 Py_UCS4 ch2 = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +00005720 if (ch >= 0x10000) {
Victor Stinner551ac952011-11-29 22:58:13 +01005721 ch2 = Py_UNICODE_LOW_SURROGATE(ch);
5722 ch = Py_UNICODE_HIGH_SURROGATE(ch);
Benjamin Peterson29060642009-01-31 22:14:21 +00005723 }
Tim Peters772747b2001-08-09 22:21:55 +00005724 STORECHAR(ch);
5725 if (ch2)
5726 STORECHAR(ch2);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005727 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005728
5729 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005730 return v;
Tim Peters772747b2001-08-09 22:21:55 +00005731#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005732}
5733
Alexander Belopolsky40018472011-02-26 01:02:56 +00005734PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005735PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5736 Py_ssize_t size,
5737 const char *errors,
5738 int byteorder)
5739{
5740 PyObject *result;
5741 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5742 if (tmp == NULL)
5743 return NULL;
5744 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5745 Py_DECREF(tmp);
5746 return result;
5747}
5748
5749PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005750PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005751{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005752 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005753}
5754
5755/* --- Unicode Escape Codec ----------------------------------------------- */
5756
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005757/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5758 if all the escapes in the string make it still a valid ASCII string.
5759 Returns -1 if any escapes were found which cause the string to
5760 pop out of ASCII range. Otherwise returns the length of the
5761 required buffer to hold the string.
5762 */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02005763static Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005764length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5765{
5766 const unsigned char *p = (const unsigned char *)s;
5767 const unsigned char *end = p + size;
5768 Py_ssize_t length = 0;
5769
5770 if (size < 0)
5771 return -1;
5772
5773 for (; p < end; ++p) {
5774 if (*p > 127) {
5775 /* Non-ASCII */
5776 return -1;
5777 }
5778 else if (*p != '\\') {
5779 /* Normal character */
5780 ++length;
5781 }
5782 else {
5783 /* Backslash-escape, check next char */
5784 ++p;
5785 /* Escape sequence reaches till end of string or
5786 non-ASCII follow-up. */
5787 if (p >= end || *p > 127)
5788 return -1;
5789 switch (*p) {
5790 case '\n':
5791 /* backslash + \n result in zero characters */
5792 break;
5793 case '\\': case '\'': case '\"':
5794 case 'b': case 'f': case 't':
5795 case 'n': case 'r': case 'v': case 'a':
5796 ++length;
5797 break;
5798 case '0': case '1': case '2': case '3':
5799 case '4': case '5': case '6': case '7':
5800 case 'x': case 'u': case 'U': case 'N':
5801 /* these do not guarantee ASCII characters */
5802 return -1;
5803 default:
5804 /* count the backslash + the other character */
5805 length += 2;
5806 }
5807 }
5808 }
5809 return length;
5810}
5811
Fredrik Lundh06d12682001-01-24 07:59:11 +00005812static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005813
Alexander Belopolsky40018472011-02-26 01:02:56 +00005814PyObject *
5815PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005816 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005817 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005818{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005819 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005820 Py_ssize_t startinpos;
5821 Py_ssize_t endinpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005822 int j;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005823 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005824 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005825 char* message;
5826 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005827 PyObject *errorHandler = NULL;
5828 PyObject *exc = NULL;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005829 Py_ssize_t len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005830 Py_ssize_t i;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005831
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005832 len = length_of_escaped_ascii_string(s, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005833
5834 /* After length_of_escaped_ascii_string() there are two alternatives,
5835 either the string is pure ASCII with named escapes like \n, etc.
5836 and we determined it's exact size (common case)
5837 or it contains \x, \u, ... escape sequences. then we create a
5838 legacy wchar string and resize it at the end of this function. */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005839 if (len >= 0) {
5840 v = PyUnicode_New(len, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005841 if (!v)
5842 goto onError;
5843 assert(PyUnicode_KIND(v) == PyUnicode_1BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005844 }
5845 else {
5846 /* Escaped strings will always be longer than the resulting
5847 Unicode string, so we start with size here and then reduce the
5848 length after conversion to the true value.
5849 (but if the error callback returns a long replacement string
5850 we'll have to allocate more space) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005851 v = PyUnicode_New(size, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005852 if (!v)
5853 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005854 len = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005855 }
5856
Guido van Rossumd57fd912000-03-10 22:53:23 +00005857 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005858 return v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005859 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005860 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005861
Guido van Rossumd57fd912000-03-10 22:53:23 +00005862 while (s < end) {
5863 unsigned char c;
Victor Stinner24729f32011-11-10 20:31:37 +01005864 Py_UCS4 x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005865 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005866
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005867 /* The only case in which i == ascii_length is a backslash
5868 followed by a newline. */
5869 assert(i <= len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005870
Guido van Rossumd57fd912000-03-10 22:53:23 +00005871 /* Non-escape characters are interpreted as Unicode ordinals */
5872 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005873 if (unicode_putchar(&v, &i, (unsigned char) *s++) < 0)
5874 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005875 continue;
5876 }
5877
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005878 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005879 /* \ - Escapes */
5880 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005881 c = *s++;
5882 if (s > end)
5883 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005884
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005885 /* The only case in which i == ascii_length is a backslash
5886 followed by a newline. */
5887 assert(i < len || (i == len && c == '\n'));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005888
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005889 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005890
Benjamin Peterson29060642009-01-31 22:14:21 +00005891 /* \x escapes */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005892#define WRITECHAR(ch) \
5893 do { \
5894 if (unicode_putchar(&v, &i, ch) < 0) \
5895 goto onError; \
5896 }while(0)
5897
Guido van Rossumd57fd912000-03-10 22:53:23 +00005898 case '\n': break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005899 case '\\': WRITECHAR('\\'); break;
5900 case '\'': WRITECHAR('\''); break;
5901 case '\"': WRITECHAR('\"'); break;
5902 case 'b': WRITECHAR('\b'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005903 /* FF */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005904 case 'f': WRITECHAR('\014'); break;
5905 case 't': WRITECHAR('\t'); break;
5906 case 'n': WRITECHAR('\n'); break;
5907 case 'r': WRITECHAR('\r'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005908 /* VT */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005909 case 'v': WRITECHAR('\013'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005910 /* BEL, not classic C */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005911 case 'a': WRITECHAR('\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005912
Benjamin Peterson29060642009-01-31 22:14:21 +00005913 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005914 case '0': case '1': case '2': case '3':
5915 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005916 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005917 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005918 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005919 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005920 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00005921 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005922 WRITECHAR(x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005923 break;
5924
Benjamin Peterson29060642009-01-31 22:14:21 +00005925 /* hex escapes */
5926 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005927 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005928 digits = 2;
5929 message = "truncated \\xXX escape";
5930 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005931
Benjamin Peterson29060642009-01-31 22:14:21 +00005932 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005933 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005934 digits = 4;
5935 message = "truncated \\uXXXX escape";
5936 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005937
Benjamin Peterson29060642009-01-31 22:14:21 +00005938 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005939 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005940 digits = 8;
5941 message = "truncated \\UXXXXXXXX escape";
5942 hexescape:
5943 chr = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005944 if (s+digits>end) {
5945 endinpos = size;
5946 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005947 errors, &errorHandler,
5948 "unicodeescape", "end of string in escape sequence",
5949 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005950 &v, &i))
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005951 goto onError;
5952 goto nextByte;
5953 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005954 for (j = 0; j < digits; ++j) {
5955 c = (unsigned char) s[j];
David Malcolm96960882010-11-05 17:23:41 +00005956 if (!Py_ISXDIGIT(c)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005957 endinpos = (s+j+1)-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005958 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005959 errors, &errorHandler,
5960 "unicodeescape", message,
5961 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005962 &v, &i))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005963 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005964 len = PyUnicode_GET_LENGTH(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005965 goto nextByte;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005966 }
5967 chr = (chr<<4) & ~0xF;
5968 if (c >= '0' && c <= '9')
5969 chr += c - '0';
5970 else if (c >= 'a' && c <= 'f')
5971 chr += 10 + c - 'a';
5972 else
5973 chr += 10 + c - 'A';
5974 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005975 s += j;
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005976 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005977 /* _decoding_error will have already written into the
5978 target buffer. */
5979 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005980 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005981 /* when we get here, chr is a 32-bit unicode character */
Victor Stinner8faf8212011-12-08 22:14:11 +01005982 if (chr <= MAX_UNICODE) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005983 WRITECHAR(chr);
Fredrik Lundhdf846752000-09-03 11:29:49 +00005984 } else {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005985 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005986 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005987 errors, &errorHandler,
5988 "unicodeescape", "illegal Unicode character",
5989 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005990 &v, &i))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005991 goto onError;
5992 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005993 break;
5994
Benjamin Peterson29060642009-01-31 22:14:21 +00005995 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005996 case 'N':
5997 message = "malformed \\N character escape";
5998 if (ucnhash_CAPI == NULL) {
5999 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006000 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
6001 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00006002 if (ucnhash_CAPI == NULL)
6003 goto ucnhashError;
6004 }
6005 if (*s == '{') {
6006 const char *start = s+1;
6007 /* look for the closing brace */
6008 while (*s != '}' && s < end)
6009 s++;
6010 if (s > start && s < end && *s == '}') {
6011 /* found a name. look it up in the unicode database */
6012 message = "unknown Unicode character name";
6013 s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006014 if (ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
Ezio Melotti931b8aa2011-10-21 21:57:36 +03006015 &chr, 0))
Fredrik Lundhccc74732001-02-18 22:13:49 +00006016 goto store;
6017 }
6018 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006019 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006020 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00006021 errors, &errorHandler,
6022 "unicodeescape", message,
6023 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006024 &v, &i))
Fredrik Lundhccc74732001-02-18 22:13:49 +00006025 goto onError;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006026 break;
6027
6028 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00006029 if (s > end) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006030 message = "\\ at end of string";
6031 s--;
6032 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006033 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00006034 errors, &errorHandler,
6035 "unicodeescape", message,
6036 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006037 &v, &i))
Walter Dörwald8c077222002-03-25 11:16:18 +00006038 goto onError;
6039 }
6040 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006041 WRITECHAR('\\');
6042 WRITECHAR(s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00006043 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00006044 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006045 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006046 nextByte:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006047 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006048 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006049#undef WRITECHAR
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006050
Victor Stinner16e6a802011-12-12 13:24:15 +01006051 if (unicode_resize(&v, i) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006052 goto onError;
Walter Dörwaldd4ade082003-08-15 15:00:26 +00006053 Py_XDECREF(errorHandler);
6054 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006055 return unicode_result(v);
Walter Dörwald8c077222002-03-25 11:16:18 +00006056
Benjamin Peterson29060642009-01-31 22:14:21 +00006057 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00006058 PyErr_SetString(
6059 PyExc_UnicodeError,
6060 "\\N escapes not supported (can't load unicodedata module)"
6061 );
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00006062 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006063 Py_XDECREF(errorHandler);
6064 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00006065 return NULL;
6066
Benjamin Peterson29060642009-01-31 22:14:21 +00006067 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006068 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006069 Py_XDECREF(errorHandler);
6070 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006071 return NULL;
6072}
6073
6074/* Return a Unicode-Escape string version of the Unicode object.
6075
6076 If quotes is true, the string is enclosed in u"" or u'' quotes as
6077 appropriate.
6078
6079*/
6080
Alexander Belopolsky40018472011-02-26 01:02:56 +00006081PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006082PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006083{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006084 Py_ssize_t i, len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006085 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006086 char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006087 int kind;
6088 void *data;
6089 Py_ssize_t expandsize = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006090
Thomas Wouters89f507f2006-12-13 04:49:30 +00006091 /* Initial allocation is based on the longest-possible unichr
6092 escape.
6093
6094 In wide (UTF-32) builds '\U00xxxxxx' is 10 chars per source
6095 unichr, so in this case it's the longest unichr escape. In
6096 narrow (UTF-16) builds this is five chars per source unichr
6097 since there are two unichrs in the surrogate pair, so in narrow
6098 (UTF-16) builds it's not the longest unichr escape.
6099
6100 In wide or narrow builds '\uxxxx' is 6 chars per source unichr,
6101 so in the narrow (UTF-16) build case it's the longest unichr
6102 escape.
6103 */
6104
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006105 if (!PyUnicode_Check(unicode)) {
6106 PyErr_BadArgument();
6107 return NULL;
6108 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05006109 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006110 return NULL;
6111 len = PyUnicode_GET_LENGTH(unicode);
6112 kind = PyUnicode_KIND(unicode);
6113 data = PyUnicode_DATA(unicode);
Benjamin Petersonead6b532011-12-20 17:23:42 -06006114 switch (kind) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006115 case PyUnicode_1BYTE_KIND: expandsize = 4; break;
6116 case PyUnicode_2BYTE_KIND: expandsize = 6; break;
6117 case PyUnicode_4BYTE_KIND: expandsize = 10; break;
6118 }
6119
6120 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006121 return PyBytes_FromStringAndSize(NULL, 0);
6122
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006123 if (len > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006124 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00006125
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006126 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00006127 2
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006128 + expandsize*len
Benjamin Peterson29060642009-01-31 22:14:21 +00006129 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006130 if (repr == NULL)
6131 return NULL;
6132
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006133 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006134
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006135 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01006136 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006137
Walter Dörwald79e913e2007-05-12 11:08:06 +00006138 /* Escape backslashes */
6139 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006140 *p++ = '\\';
6141 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00006142 continue;
Tim Petersced69f82003-09-16 20:30:58 +00006143 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006144
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00006145 /* Map 21-bit characters to '\U00xxxxxx' */
6146 else if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01006147 assert(ch <= MAX_UNICODE);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00006148 *p++ = '\\';
6149 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006150 *p++ = Py_hexdigits[(ch >> 28) & 0x0000000F];
6151 *p++ = Py_hexdigits[(ch >> 24) & 0x0000000F];
6152 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
6153 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
6154 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
6155 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
6156 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
6157 *p++ = Py_hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00006158 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00006159 }
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00006160
Guido van Rossumd57fd912000-03-10 22:53:23 +00006161 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00006162 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006163 *p++ = '\\';
6164 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006165 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
6166 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
6167 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6168 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006169 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006170
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006171 /* Map special whitespace to '\t', \n', '\r' */
6172 else if (ch == '\t') {
6173 *p++ = '\\';
6174 *p++ = 't';
6175 }
6176 else if (ch == '\n') {
6177 *p++ = '\\';
6178 *p++ = 'n';
6179 }
6180 else if (ch == '\r') {
6181 *p++ = '\\';
6182 *p++ = 'r';
6183 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006184
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006185 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00006186 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006187 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006188 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006189 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6190 *p++ = Py_hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00006191 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006192
Guido van Rossumd57fd912000-03-10 22:53:23 +00006193 /* Copy everything else as-is */
6194 else
6195 *p++ = (char) ch;
6196 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006197
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006198 assert(p - PyBytes_AS_STRING(repr) > 0);
6199 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
6200 return NULL;
6201 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006202}
6203
Alexander Belopolsky40018472011-02-26 01:02:56 +00006204PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006205PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
6206 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006207{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006208 PyObject *result;
6209 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6210 if (tmp == NULL)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006211 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006212 result = PyUnicode_AsUnicodeEscapeString(tmp);
6213 Py_DECREF(tmp);
6214 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006215}
6216
6217/* --- Raw Unicode Escape Codec ------------------------------------------- */
6218
Alexander Belopolsky40018472011-02-26 01:02:56 +00006219PyObject *
6220PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006221 Py_ssize_t size,
6222 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006223{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006224 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006225 Py_ssize_t startinpos;
6226 Py_ssize_t endinpos;
6227 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006228 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006229 const char *end;
6230 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006231 PyObject *errorHandler = NULL;
6232 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006233
Guido van Rossumd57fd912000-03-10 22:53:23 +00006234 /* Escaped strings will always be longer than the resulting
6235 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006236 length after conversion to the true value. (But decoding error
6237 handler might have to resize the string) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006238 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006239 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006240 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006241 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006242 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006243 outpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006244 end = s + size;
6245 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006246 unsigned char c;
6247 Py_UCS4 x;
6248 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006249 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006250
Benjamin Peterson29060642009-01-31 22:14:21 +00006251 /* Non-escape characters are interpreted as Unicode ordinals */
6252 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006253 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
6254 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006255 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006256 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006257 startinpos = s-starts;
6258
6259 /* \u-escapes are only interpreted iff the number of leading
6260 backslashes if odd */
6261 bs = s;
6262 for (;s < end;) {
6263 if (*s != '\\')
6264 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006265 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
6266 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006267 }
6268 if (((s - bs) & 1) == 0 ||
6269 s >= end ||
6270 (*s != 'u' && *s != 'U')) {
6271 continue;
6272 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006273 outpos--;
Benjamin Peterson29060642009-01-31 22:14:21 +00006274 count = *s=='u' ? 4 : 8;
6275 s++;
6276
6277 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
Benjamin Peterson29060642009-01-31 22:14:21 +00006278 for (x = 0, i = 0; i < count; ++i, ++s) {
6279 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00006280 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006281 endinpos = s-starts;
6282 if (unicode_decode_call_errorhandler(
6283 errors, &errorHandler,
6284 "rawunicodeescape", "truncated \\uXXXX",
6285 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006286 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006287 goto onError;
6288 goto nextByte;
6289 }
6290 x = (x<<4) & ~0xF;
6291 if (c >= '0' && c <= '9')
6292 x += c - '0';
6293 else if (c >= 'a' && c <= 'f')
6294 x += 10 + c - 'a';
6295 else
6296 x += 10 + c - 'A';
6297 }
Victor Stinner8faf8212011-12-08 22:14:11 +01006298 if (x <= MAX_UNICODE) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006299 if (unicode_putchar(&v, &outpos, x) < 0)
6300 goto onError;
Christian Heimesfe337bf2008-03-23 21:54:12 +00006301 } else {
6302 endinpos = s-starts;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006303 if (unicode_decode_call_errorhandler(
6304 errors, &errorHandler,
6305 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00006306 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006307 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006308 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006309 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006310 nextByte:
6311 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006312 }
Victor Stinner16e6a802011-12-12 13:24:15 +01006313 if (unicode_resize(&v, outpos) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006314 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006315 Py_XDECREF(errorHandler);
6316 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006317 return unicode_result(v);
Tim Petersced69f82003-09-16 20:30:58 +00006318
Benjamin Peterson29060642009-01-31 22:14:21 +00006319 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006320 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006321 Py_XDECREF(errorHandler);
6322 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006323 return NULL;
6324}
6325
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006326
Alexander Belopolsky40018472011-02-26 01:02:56 +00006327PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006328PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006329{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006330 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006331 char *p;
6332 char *q;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006333 Py_ssize_t expandsize, pos;
6334 int kind;
6335 void *data;
6336 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006337
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006338 if (!PyUnicode_Check(unicode)) {
6339 PyErr_BadArgument();
6340 return NULL;
6341 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05006342 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006343 return NULL;
6344 kind = PyUnicode_KIND(unicode);
6345 data = PyUnicode_DATA(unicode);
6346 len = PyUnicode_GET_LENGTH(unicode);
Benjamin Peterson1518e872011-11-23 10:44:52 -06006347 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6348 bytes, and 1 byte characters 4. */
6349 expandsize = kind * 2 + 2;
Victor Stinner0e368262011-11-10 20:12:49 +01006350
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006351 if (len > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006352 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00006353
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006354 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006355 if (repr == NULL)
6356 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006357 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006358 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006359
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006360 p = q = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006361 for (pos = 0; pos < len; pos++) {
6362 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006363 /* Map 32-bit characters to '\Uxxxxxxxx' */
6364 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01006365 assert(ch <= MAX_UNICODE);
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006366 *p++ = '\\';
6367 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006368 *p++ = Py_hexdigits[(ch >> 28) & 0xf];
6369 *p++ = Py_hexdigits[(ch >> 24) & 0xf];
6370 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6371 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6372 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6373 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6374 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6375 *p++ = Py_hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00006376 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006377 /* Map 16-bit characters to '\uxxxx' */
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006378 else if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006379 *p++ = '\\';
6380 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006381 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6382 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6383 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6384 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006385 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006386 /* Copy everything else as-is */
6387 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00006388 *p++ = (char) ch;
6389 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006390
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006391 assert(p > q);
6392 if (_PyBytes_Resize(&repr, p - q) < 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006393 return NULL;
6394 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006395}
6396
Alexander Belopolsky40018472011-02-26 01:02:56 +00006397PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006398PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6399 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006400{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006401 PyObject *result;
6402 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6403 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006404 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006405 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6406 Py_DECREF(tmp);
6407 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006408}
6409
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006410/* --- Unicode Internal Codec ------------------------------------------- */
6411
Alexander Belopolsky40018472011-02-26 01:02:56 +00006412PyObject *
6413_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006414 Py_ssize_t size,
6415 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006416{
6417 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006418 Py_ssize_t startinpos;
6419 Py_ssize_t endinpos;
6420 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006421 PyObject *v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006422 const char *end;
6423 const char *reason;
6424 PyObject *errorHandler = NULL;
6425 PyObject *exc = NULL;
6426
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006427 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006428 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006429 1))
6430 return NULL;
6431
Thomas Wouters89f507f2006-12-13 04:49:30 +00006432 /* XXX overflow detection missing */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006433 v = PyUnicode_New((size+Py_UNICODE_SIZE-1)/ Py_UNICODE_SIZE, 127);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006434 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006435 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006436 if (PyUnicode_GET_LENGTH(v) == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006437 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006438 outpos = 0;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006439 end = s + size;
6440
6441 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006442 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006443 Py_UCS4 ch;
6444 /* We copy the raw representation one byte at a time because the
6445 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006446 ((char *) &uch)[0] = s[0];
6447 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006448#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006449 ((char *) &uch)[2] = s[2];
6450 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006451#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006452 ch = uch;
6453
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006454 /* We have to sanity check the raw data, otherwise doom looms for
6455 some malformed UCS-4 data. */
6456 if (
Benjamin Peterson29060642009-01-31 22:14:21 +00006457#ifdef Py_UNICODE_WIDE
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006458 ch > 0x10ffff ||
Benjamin Peterson29060642009-01-31 22:14:21 +00006459#endif
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006460 end-s < Py_UNICODE_SIZE
6461 )
Benjamin Peterson29060642009-01-31 22:14:21 +00006462 {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006463 startinpos = s - starts;
6464 if (end-s < Py_UNICODE_SIZE) {
6465 endinpos = end-starts;
6466 reason = "truncated input";
6467 }
6468 else {
6469 endinpos = s - starts + Py_UNICODE_SIZE;
6470 reason = "illegal code point (> 0x10FFFF)";
6471 }
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006472 if (unicode_decode_call_errorhandler(
6473 errors, &errorHandler,
6474 "unicode_internal", reason,
Walter Dörwalde78178e2007-07-30 13:31:40 +00006475 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006476 &v, &outpos))
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006477 goto onError;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006478 continue;
6479 }
6480
6481 s += Py_UNICODE_SIZE;
6482#ifndef Py_UNICODE_WIDE
Victor Stinner551ac952011-11-29 22:58:13 +01006483 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && s < end)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006484 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006485 Py_UNICODE uch2;
6486 ((char *) &uch2)[0] = s[0];
6487 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006488 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006489 {
Victor Stinner551ac952011-11-29 22:58:13 +01006490 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006491 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006492 }
6493 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006494#endif
6495
6496 if (unicode_putchar(&v, &outpos, ch) < 0)
6497 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006498 }
6499
Victor Stinner16e6a802011-12-12 13:24:15 +01006500 if (unicode_resize(&v, outpos) < 0)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006501 goto onError;
6502 Py_XDECREF(errorHandler);
6503 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006504 return unicode_result(v);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006505
Benjamin Peterson29060642009-01-31 22:14:21 +00006506 onError:
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006507 Py_XDECREF(v);
6508 Py_XDECREF(errorHandler);
6509 Py_XDECREF(exc);
6510 return NULL;
6511}
6512
Guido van Rossumd57fd912000-03-10 22:53:23 +00006513/* --- Latin-1 Codec ------------------------------------------------------ */
6514
Alexander Belopolsky40018472011-02-26 01:02:56 +00006515PyObject *
6516PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006517 Py_ssize_t size,
6518 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006519{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006520 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006521 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006522}
6523
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006524/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006525static void
6526make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006527 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006528 PyObject *unicode,
6529 Py_ssize_t startpos, Py_ssize_t endpos,
6530 const char *reason)
6531{
6532 if (*exceptionObject == NULL) {
6533 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006534 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006535 encoding, unicode, startpos, endpos, reason);
6536 }
6537 else {
6538 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6539 goto onError;
6540 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6541 goto onError;
6542 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6543 goto onError;
6544 return;
6545 onError:
6546 Py_DECREF(*exceptionObject);
6547 *exceptionObject = NULL;
6548 }
6549}
6550
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006551/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006552static void
6553raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006554 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006555 PyObject *unicode,
6556 Py_ssize_t startpos, Py_ssize_t endpos,
6557 const char *reason)
6558{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006559 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006560 encoding, unicode, startpos, endpos, reason);
6561 if (*exceptionObject != NULL)
6562 PyCodec_StrictErrors(*exceptionObject);
6563}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006564
6565/* error handling callback helper:
6566 build arguments, call the callback and check the arguments,
6567 put the result into newpos and return the replacement string, which
6568 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006569static PyObject *
6570unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006571 PyObject **errorHandler,
6572 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006573 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006574 Py_ssize_t startpos, Py_ssize_t endpos,
6575 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006576{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006577 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006578 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006579 PyObject *restuple;
6580 PyObject *resunicode;
6581
6582 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006583 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006584 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006585 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006586 }
6587
Benjamin Petersonbac79492012-01-14 13:34:47 -05006588 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006589 return NULL;
6590 len = PyUnicode_GET_LENGTH(unicode);
6591
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006592 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006593 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006594 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006595 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006596
6597 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006598 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006599 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006600 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006601 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006602 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006603 Py_DECREF(restuple);
6604 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006605 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006606 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006607 &resunicode, newpos)) {
6608 Py_DECREF(restuple);
6609 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006610 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006611 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6612 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6613 Py_DECREF(restuple);
6614 return NULL;
6615 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006616 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006617 *newpos = len + *newpos;
6618 if (*newpos<0 || *newpos>len) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006619 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
6620 Py_DECREF(restuple);
6621 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006622 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006623 Py_INCREF(resunicode);
6624 Py_DECREF(restuple);
6625 return resunicode;
6626}
6627
Alexander Belopolsky40018472011-02-26 01:02:56 +00006628static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006629unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006630 const char *errors,
Victor Stinnerfcd96532011-11-04 00:28:50 +01006631 unsigned int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006632{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006633 /* input state */
6634 Py_ssize_t pos=0, size;
6635 int kind;
6636 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006637 /* output object */
6638 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006639 /* pointer into the output */
6640 char *str;
6641 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006642 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006643 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6644 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006645 PyObject *errorHandler = NULL;
6646 PyObject *exc = NULL;
6647 /* the following variable is used for caching string comparisons
6648 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6649 int known_errorHandler = -1;
6650
Benjamin Petersonbac79492012-01-14 13:34:47 -05006651 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006652 return NULL;
6653 size = PyUnicode_GET_LENGTH(unicode);
6654 kind = PyUnicode_KIND(unicode);
6655 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006656 /* allocate enough for a simple encoding without
6657 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006658 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006659 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006660 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006661 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006662 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006663 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006664 ressize = size;
6665
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006666 while (pos < size) {
6667 Py_UCS4 c = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006668
Benjamin Peterson29060642009-01-31 22:14:21 +00006669 /* can we encode this? */
6670 if (c<limit) {
6671 /* no overflow check, because we know that the space is enough */
6672 *str++ = (char)c;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006673 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006674 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006675 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006676 Py_ssize_t requiredsize;
6677 PyObject *repunicode;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006678 Py_ssize_t repsize, newpos, respos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006679 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006680 Py_ssize_t collstart = pos;
6681 Py_ssize_t collend = pos;
Benjamin Peterson29060642009-01-31 22:14:21 +00006682 /* find all unecodable characters */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006683 while ((collend < size) && (PyUnicode_READ(kind, data, collend)>=limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006684 ++collend;
6685 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
6686 if (known_errorHandler==-1) {
6687 if ((errors==NULL) || (!strcmp(errors, "strict")))
6688 known_errorHandler = 1;
6689 else if (!strcmp(errors, "replace"))
6690 known_errorHandler = 2;
6691 else if (!strcmp(errors, "ignore"))
6692 known_errorHandler = 3;
6693 else if (!strcmp(errors, "xmlcharrefreplace"))
6694 known_errorHandler = 4;
6695 else
6696 known_errorHandler = 0;
6697 }
6698 switch (known_errorHandler) {
6699 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006700 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006701 goto onError;
6702 case 2: /* replace */
6703 while (collstart++<collend)
6704 *str++ = '?'; /* fall through */
6705 case 3: /* ignore */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006706 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006707 break;
6708 case 4: /* xmlcharrefreplace */
6709 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006710 /* determine replacement size */
6711 for (i = collstart, repsize = 0; i < collend; ++i) {
6712 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
6713 if (ch < 10)
Benjamin Peterson29060642009-01-31 22:14:21 +00006714 repsize += 2+1+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006715 else if (ch < 100)
Benjamin Peterson29060642009-01-31 22:14:21 +00006716 repsize += 2+2+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006717 else if (ch < 1000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006718 repsize += 2+3+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006719 else if (ch < 10000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006720 repsize += 2+4+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006721 else if (ch < 100000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006722 repsize += 2+5+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006723 else if (ch < 1000000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006724 repsize += 2+6+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006725 else {
Victor Stinner8faf8212011-12-08 22:14:11 +01006726 assert(ch <= MAX_UNICODE);
Benjamin Peterson29060642009-01-31 22:14:21 +00006727 repsize += 2+7+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006728 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006729 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006730 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006731 if (requiredsize > ressize) {
6732 if (requiredsize<2*ressize)
6733 requiredsize = 2*ressize;
6734 if (_PyBytes_Resize(&res, requiredsize))
6735 goto onError;
6736 str = PyBytes_AS_STRING(res) + respos;
6737 ressize = requiredsize;
6738 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006739 /* generate replacement */
6740 for (i = collstart; i < collend; ++i) {
6741 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
Benjamin Peterson29060642009-01-31 22:14:21 +00006742 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006743 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006744 break;
6745 default:
6746 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006747 encoding, reason, unicode, &exc,
6748 collstart, collend, &newpos);
6749 if (repunicode == NULL || (PyUnicode_Check(repunicode) &&
Benjamin Petersonbac79492012-01-14 13:34:47 -05006750 PyUnicode_READY(repunicode) == -1))
Benjamin Peterson29060642009-01-31 22:14:21 +00006751 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006752 if (PyBytes_Check(repunicode)) {
6753 /* Directly copy bytes result to output. */
6754 repsize = PyBytes_Size(repunicode);
6755 if (repsize > 1) {
6756 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006757 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006758 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
6759 Py_DECREF(repunicode);
6760 goto onError;
6761 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006762 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006763 ressize += repsize-1;
6764 }
6765 memcpy(str, PyBytes_AsString(repunicode), repsize);
6766 str += repsize;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006767 pos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006768 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006769 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006770 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006771 /* need more space? (at least enough for what we
6772 have+the replacement+the rest of the string, so
6773 we won't have to check space for encodable characters) */
6774 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006775 repsize = PyUnicode_GET_LENGTH(repunicode);
6776 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006777 if (requiredsize > ressize) {
6778 if (requiredsize<2*ressize)
6779 requiredsize = 2*ressize;
6780 if (_PyBytes_Resize(&res, requiredsize)) {
6781 Py_DECREF(repunicode);
6782 goto onError;
6783 }
6784 str = PyBytes_AS_STRING(res) + respos;
6785 ressize = requiredsize;
6786 }
6787 /* check if there is anything unencodable in the replacement
6788 and copy it to the output */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006789 for (i = 0; repsize-->0; ++i, ++str) {
6790 c = PyUnicode_READ_CHAR(repunicode, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00006791 if (c >= limit) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006792 raise_encode_exception(&exc, encoding, unicode,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006793 pos, pos+1, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006794 Py_DECREF(repunicode);
6795 goto onError;
6796 }
6797 *str = (char)c;
6798 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006799 pos = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006800 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006801 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006802 }
6803 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006804 /* Resize if we allocated to much */
6805 size = str - PyBytes_AS_STRING(res);
6806 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00006807 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006808 if (_PyBytes_Resize(&res, size) < 0)
6809 goto onError;
6810 }
6811
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006812 Py_XDECREF(errorHandler);
6813 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006814 return res;
6815
6816 onError:
6817 Py_XDECREF(res);
6818 Py_XDECREF(errorHandler);
6819 Py_XDECREF(exc);
6820 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006821}
6822
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006823/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006824PyObject *
6825PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006826 Py_ssize_t size,
6827 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006828{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006829 PyObject *result;
6830 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6831 if (unicode == NULL)
6832 return NULL;
6833 result = unicode_encode_ucs1(unicode, errors, 256);
6834 Py_DECREF(unicode);
6835 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006836}
6837
Alexander Belopolsky40018472011-02-26 01:02:56 +00006838PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006839_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006840{
6841 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006842 PyErr_BadArgument();
6843 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006844 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006845 if (PyUnicode_READY(unicode) == -1)
6846 return NULL;
6847 /* Fast path: if it is a one-byte string, construct
6848 bytes object directly. */
6849 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6850 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6851 PyUnicode_GET_LENGTH(unicode));
6852 /* Non-Latin-1 characters present. Defer to above function to
6853 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006854 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006855}
6856
6857PyObject*
6858PyUnicode_AsLatin1String(PyObject *unicode)
6859{
6860 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006861}
6862
6863/* --- 7-bit ASCII Codec -------------------------------------------------- */
6864
Alexander Belopolsky40018472011-02-26 01:02:56 +00006865PyObject *
6866PyUnicode_DecodeASCII(const char *s,
6867 Py_ssize_t size,
6868 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006869{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006870 const char *starts = s;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006871 PyObject *v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006872 int kind;
6873 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006874 Py_ssize_t startinpos;
6875 Py_ssize_t endinpos;
6876 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006877 const char *e;
Victor Stinner702c7342011-10-05 13:50:52 +02006878 int has_error;
6879 const unsigned char *p = (const unsigned char *)s;
6880 const unsigned char *end = p + size;
6881 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006882 PyObject *errorHandler = NULL;
6883 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006884
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006885 if (size == 0) {
6886 Py_INCREF(unicode_empty);
6887 return unicode_empty;
6888 }
6889
Guido van Rossumd57fd912000-03-10 22:53:23 +00006890 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006891 if (size == 1 && (unsigned char)s[0] < 128)
6892 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006893
Victor Stinner702c7342011-10-05 13:50:52 +02006894 has_error = 0;
6895 while (p < end && !has_error) {
6896 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
6897 an explanation. */
6898 if (!((size_t) p & LONG_PTR_MASK)) {
6899 /* Help register allocation */
6900 register const unsigned char *_p = p;
6901 while (_p < aligned_end) {
6902 unsigned long value = *(unsigned long *) _p;
6903 if (value & ASCII_CHAR_MASK) {
6904 has_error = 1;
6905 break;
6906 }
6907 _p += SIZEOF_LONG;
6908 }
6909 if (_p == end)
6910 break;
6911 if (has_error)
6912 break;
6913 p = _p;
6914 }
6915 if (*p & 0x80) {
6916 has_error = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006917 break;
Victor Stinner702c7342011-10-05 13:50:52 +02006918 }
6919 else {
6920 ++p;
6921 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00006922 }
Victor Stinner702c7342011-10-05 13:50:52 +02006923 if (!has_error)
6924 return unicode_fromascii((const unsigned char *)s, size);
Tim Petersced69f82003-09-16 20:30:58 +00006925
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006926 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006927 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006928 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006929 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006930 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006931 kind = PyUnicode_KIND(v);
6932 data = PyUnicode_DATA(v);
6933 outpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006934 e = s + size;
6935 while (s < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006936 register unsigned char c = (unsigned char)*s;
6937 if (c < 128) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006938 PyUnicode_WRITE(kind, data, outpos++, c);
Benjamin Peterson29060642009-01-31 22:14:21 +00006939 ++s;
6940 }
6941 else {
6942 startinpos = s-starts;
6943 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006944 if (unicode_decode_call_errorhandler(
6945 errors, &errorHandler,
6946 "ascii", "ordinal not in range(128)",
6947 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006948 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006949 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006950 kind = PyUnicode_KIND(v);
6951 data = PyUnicode_DATA(v);
Benjamin Peterson29060642009-01-31 22:14:21 +00006952 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006953 }
Victor Stinner16e6a802011-12-12 13:24:15 +01006954 if (unicode_resize(&v, outpos) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006955 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006956 Py_XDECREF(errorHandler);
6957 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006958 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01006959 return v;
Tim Petersced69f82003-09-16 20:30:58 +00006960
Benjamin Peterson29060642009-01-31 22:14:21 +00006961 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006962 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006963 Py_XDECREF(errorHandler);
6964 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006965 return NULL;
6966}
6967
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006968/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006969PyObject *
6970PyUnicode_EncodeASCII(const Py_UNICODE *p,
6971 Py_ssize_t size,
6972 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006973{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006974 PyObject *result;
6975 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6976 if (unicode == NULL)
6977 return NULL;
6978 result = unicode_encode_ucs1(unicode, errors, 128);
6979 Py_DECREF(unicode);
6980 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006981}
6982
Alexander Belopolsky40018472011-02-26 01:02:56 +00006983PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006984_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006985{
6986 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006987 PyErr_BadArgument();
6988 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006989 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006990 if (PyUnicode_READY(unicode) == -1)
6991 return NULL;
6992 /* Fast path: if it is an ASCII-only string, construct bytes object
6993 directly. Else defer to above function to raise the exception. */
6994 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
6995 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6996 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006997 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006998}
6999
7000PyObject *
7001PyUnicode_AsASCIIString(PyObject *unicode)
7002{
7003 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007004}
7005
Victor Stinner99b95382011-07-04 14:23:54 +02007006#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007007
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007008/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007009
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00007010#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007011#define NEED_RETRY
7012#endif
7013
Victor Stinner3a50e702011-10-18 21:21:00 +02007014#ifndef WC_ERR_INVALID_CHARS
7015# define WC_ERR_INVALID_CHARS 0x0080
7016#endif
7017
7018static char*
7019code_page_name(UINT code_page, PyObject **obj)
7020{
7021 *obj = NULL;
7022 if (code_page == CP_ACP)
7023 return "mbcs";
7024 if (code_page == CP_UTF7)
7025 return "CP_UTF7";
7026 if (code_page == CP_UTF8)
7027 return "CP_UTF8";
7028
7029 *obj = PyBytes_FromFormat("cp%u", code_page);
7030 if (*obj == NULL)
7031 return NULL;
7032 return PyBytes_AS_STRING(*obj);
7033}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007034
Alexander Belopolsky40018472011-02-26 01:02:56 +00007035static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007036is_dbcs_lead_byte(UINT code_page, const char *s, int offset)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007037{
7038 const char *curr = s + offset;
Victor Stinner3a50e702011-10-18 21:21:00 +02007039 const char *prev;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007040
Victor Stinner3a50e702011-10-18 21:21:00 +02007041 if (!IsDBCSLeadByteEx(code_page, *curr))
7042 return 0;
7043
7044 prev = CharPrevExA(code_page, s, curr, 0);
7045 if (prev == curr)
7046 return 1;
7047 /* FIXME: This code is limited to "true" double-byte encodings,
7048 as it assumes an incomplete character consists of a single
7049 byte. */
7050 if (curr - prev == 2)
7051 return 1;
7052 if (!IsDBCSLeadByteEx(code_page, *prev))
7053 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007054 return 0;
7055}
7056
Victor Stinner3a50e702011-10-18 21:21:00 +02007057static DWORD
7058decode_code_page_flags(UINT code_page)
7059{
7060 if (code_page == CP_UTF7) {
7061 /* The CP_UTF7 decoder only supports flags=0 */
7062 return 0;
7063 }
7064 else
7065 return MB_ERR_INVALID_CHARS;
7066}
7067
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007068/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007069 * Decode a byte string from a Windows code page into unicode object in strict
7070 * mode.
7071 *
7072 * Returns consumed size if succeed, returns -2 on decode error, or raise a
7073 * WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007074 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007075static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007076decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007077 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02007078 const char *in,
7079 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007080{
Victor Stinner3a50e702011-10-18 21:21:00 +02007081 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01007082 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007083 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007084
7085 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007086 assert(insize > 0);
7087 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
7088 if (outsize <= 0)
7089 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007090
7091 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007092 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01007093 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007094 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00007095 if (*v == NULL)
7096 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007097 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007098 }
7099 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007100 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007101 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01007102 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007103 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007104 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007105 }
7106
7107 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007108 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
7109 if (outsize <= 0)
7110 goto error;
7111 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007112
Victor Stinner3a50e702011-10-18 21:21:00 +02007113error:
7114 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7115 return -2;
7116 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007117 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007118}
7119
Victor Stinner3a50e702011-10-18 21:21:00 +02007120/*
7121 * Decode a byte string from a code page into unicode object with an error
7122 * handler.
7123 *
7124 * Returns consumed size if succeed, or raise a WindowsError or
7125 * UnicodeDecodeError exception and returns -1 on error.
7126 */
7127static int
7128decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007129 PyObject **v,
7130 const char *in, const int size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007131 const char *errors)
7132{
7133 const char *startin = in;
7134 const char *endin = in + size;
7135 const DWORD flags = decode_code_page_flags(code_page);
7136 /* Ideally, we should get reason from FormatMessage. This is the Windows
7137 2000 English version of the message. */
7138 const char *reason = "No mapping for the Unicode character exists "
7139 "in the target code page.";
7140 /* each step cannot decode more than 1 character, but a character can be
7141 represented as a surrogate pair */
7142 wchar_t buffer[2], *startout, *out;
7143 int insize, outsize;
7144 PyObject *errorHandler = NULL;
7145 PyObject *exc = NULL;
7146 PyObject *encoding_obj = NULL;
7147 char *encoding;
7148 DWORD err;
7149 int ret = -1;
7150
7151 assert(size > 0);
7152
7153 encoding = code_page_name(code_page, &encoding_obj);
7154 if (encoding == NULL)
7155 return -1;
7156
7157 if (errors == NULL || strcmp(errors, "strict") == 0) {
7158 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
7159 UnicodeDecodeError. */
7160 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
7161 if (exc != NULL) {
7162 PyCodec_StrictErrors(exc);
7163 Py_CLEAR(exc);
7164 }
7165 goto error;
7166 }
7167
7168 if (*v == NULL) {
7169 /* Create unicode object */
7170 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7171 PyErr_NoMemory();
7172 goto error;
7173 }
Victor Stinnerab595942011-12-17 04:59:06 +01007174 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007175 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02007176 if (*v == NULL)
7177 goto error;
7178 startout = PyUnicode_AS_UNICODE(*v);
7179 }
7180 else {
7181 /* Extend unicode object */
7182 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
7183 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7184 PyErr_NoMemory();
7185 goto error;
7186 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007187 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007188 goto error;
7189 startout = PyUnicode_AS_UNICODE(*v) + n;
7190 }
7191
7192 /* Decode the byte string character per character */
7193 out = startout;
7194 while (in < endin)
7195 {
7196 /* Decode a character */
7197 insize = 1;
7198 do
7199 {
7200 outsize = MultiByteToWideChar(code_page, flags,
7201 in, insize,
7202 buffer, Py_ARRAY_LENGTH(buffer));
7203 if (outsize > 0)
7204 break;
7205 err = GetLastError();
7206 if (err != ERROR_NO_UNICODE_TRANSLATION
7207 && err != ERROR_INSUFFICIENT_BUFFER)
7208 {
7209 PyErr_SetFromWindowsErr(0);
7210 goto error;
7211 }
7212 insize++;
7213 }
7214 /* 4=maximum length of a UTF-8 sequence */
7215 while (insize <= 4 && (in + insize) <= endin);
7216
7217 if (outsize <= 0) {
7218 Py_ssize_t startinpos, endinpos, outpos;
7219
7220 startinpos = in - startin;
7221 endinpos = startinpos + 1;
7222 outpos = out - PyUnicode_AS_UNICODE(*v);
7223 if (unicode_decode_call_errorhandler(
7224 errors, &errorHandler,
7225 encoding, reason,
7226 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01007227 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02007228 {
7229 goto error;
7230 }
Victor Stinner596a6c42011-11-09 00:02:18 +01007231 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007232 }
7233 else {
7234 in += insize;
7235 memcpy(out, buffer, outsize * sizeof(wchar_t));
7236 out += outsize;
7237 }
7238 }
7239
7240 /* write a NUL character at the end */
7241 *out = 0;
7242
7243 /* Extend unicode object */
7244 outsize = out - startout;
7245 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01007246 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007247 goto error;
Victor Stinner76a31a62011-11-04 00:05:13 +01007248 ret = size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007249
7250error:
7251 Py_XDECREF(encoding_obj);
7252 Py_XDECREF(errorHandler);
7253 Py_XDECREF(exc);
7254 return ret;
7255}
7256
Victor Stinner3a50e702011-10-18 21:21:00 +02007257static PyObject *
7258decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007259 const char *s, Py_ssize_t size,
7260 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007261{
Victor Stinner76a31a62011-11-04 00:05:13 +01007262 PyObject *v = NULL;
7263 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007264
Victor Stinner3a50e702011-10-18 21:21:00 +02007265 if (code_page < 0) {
7266 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7267 return NULL;
7268 }
7269
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007270 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007271 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007272
Victor Stinner76a31a62011-11-04 00:05:13 +01007273 do
7274 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007275#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007276 if (size > INT_MAX) {
7277 chunk_size = INT_MAX;
7278 final = 0;
7279 done = 0;
7280 }
7281 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007282#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007283 {
7284 chunk_size = (int)size;
7285 final = (consumed == NULL);
7286 done = 1;
7287 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007288
Victor Stinner76a31a62011-11-04 00:05:13 +01007289 /* Skip trailing lead-byte unless 'final' is set */
7290 if (!final && is_dbcs_lead_byte(code_page, s, chunk_size - 1))
7291 --chunk_size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007292
Victor Stinner76a31a62011-11-04 00:05:13 +01007293 if (chunk_size == 0 && done) {
7294 if (v != NULL)
7295 break;
7296 Py_INCREF(unicode_empty);
7297 return unicode_empty;
7298 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007299
Victor Stinner76a31a62011-11-04 00:05:13 +01007300
7301 converted = decode_code_page_strict(code_page, &v,
7302 s, chunk_size);
7303 if (converted == -2)
7304 converted = decode_code_page_errors(code_page, &v,
7305 s, chunk_size,
7306 errors);
7307 assert(converted != 0);
7308
7309 if (converted < 0) {
7310 Py_XDECREF(v);
7311 return NULL;
7312 }
7313
7314 if (consumed)
7315 *consumed += converted;
7316
7317 s += converted;
7318 size -= converted;
7319 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007320
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007321 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007322}
7323
Alexander Belopolsky40018472011-02-26 01:02:56 +00007324PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007325PyUnicode_DecodeCodePageStateful(int code_page,
7326 const char *s,
7327 Py_ssize_t size,
7328 const char *errors,
7329 Py_ssize_t *consumed)
7330{
7331 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7332}
7333
7334PyObject *
7335PyUnicode_DecodeMBCSStateful(const char *s,
7336 Py_ssize_t size,
7337 const char *errors,
7338 Py_ssize_t *consumed)
7339{
7340 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7341}
7342
7343PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007344PyUnicode_DecodeMBCS(const char *s,
7345 Py_ssize_t size,
7346 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007347{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007348 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7349}
7350
Victor Stinner3a50e702011-10-18 21:21:00 +02007351static DWORD
7352encode_code_page_flags(UINT code_page, const char *errors)
7353{
7354 if (code_page == CP_UTF8) {
7355 if (winver.dwMajorVersion >= 6)
7356 /* CP_UTF8 supports WC_ERR_INVALID_CHARS on Windows Vista
7357 and later */
7358 return WC_ERR_INVALID_CHARS;
7359 else
7360 /* CP_UTF8 only supports flags=0 on Windows older than Vista */
7361 return 0;
7362 }
7363 else if (code_page == CP_UTF7) {
7364 /* CP_UTF7 only supports flags=0 */
7365 return 0;
7366 }
7367 else {
7368 if (errors != NULL && strcmp(errors, "replace") == 0)
7369 return 0;
7370 else
7371 return WC_NO_BEST_FIT_CHARS;
7372 }
7373}
7374
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007375/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007376 * Encode a Unicode string to a Windows code page into a byte string in strict
7377 * mode.
7378 *
7379 * Returns consumed characters if succeed, returns -2 on encode error, or raise
7380 * a WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007381 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007382static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007383encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007384 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007385 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007386{
Victor Stinner554f3f02010-06-16 23:33:54 +00007387 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007388 BOOL *pusedDefaultChar = &usedDefaultChar;
7389 int outsize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007390 PyObject *exc = NULL;
Victor Stinner24729f32011-11-10 20:31:37 +01007391 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007392 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007393 const DWORD flags = encode_code_page_flags(code_page, NULL);
7394 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007395 /* Create a substring so that we can get the UTF-16 representation
7396 of just the slice under consideration. */
7397 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007398
Martin v. Löwis3d325192011-11-04 18:23:06 +01007399 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007400
Victor Stinner3a50e702011-10-18 21:21:00 +02007401 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007402 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007403 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007404 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007405
Victor Stinner2fc507f2011-11-04 20:06:39 +01007406 substring = PyUnicode_Substring(unicode, offset, offset+len);
7407 if (substring == NULL)
7408 return -1;
7409 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7410 if (p == NULL) {
7411 Py_DECREF(substring);
7412 return -1;
7413 }
Martin v. Löwis3d325192011-11-04 18:23:06 +01007414
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007415 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007416 outsize = WideCharToMultiByte(code_page, flags,
7417 p, size,
7418 NULL, 0,
7419 NULL, pusedDefaultChar);
7420 if (outsize <= 0)
7421 goto error;
7422 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007423 if (pusedDefaultChar && *pusedDefaultChar) {
7424 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007425 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007426 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007427
Victor Stinner3a50e702011-10-18 21:21:00 +02007428 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007429 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007430 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007431 if (*outbytes == NULL) {
7432 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007433 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007434 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007435 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007436 }
7437 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007438 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007439 const Py_ssize_t n = PyBytes_Size(*outbytes);
7440 if (outsize > PY_SSIZE_T_MAX - n) {
7441 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007442 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007443 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007444 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007445 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7446 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007447 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007448 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007449 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007450 }
7451
7452 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007453 outsize = WideCharToMultiByte(code_page, flags,
7454 p, size,
7455 out, outsize,
7456 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007457 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007458 if (outsize <= 0)
7459 goto error;
7460 if (pusedDefaultChar && *pusedDefaultChar)
7461 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007462 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007463
Victor Stinner3a50e702011-10-18 21:21:00 +02007464error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007465 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007466 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7467 return -2;
7468 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007469 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007470}
7471
Victor Stinner3a50e702011-10-18 21:21:00 +02007472/*
7473 * Encode a Unicode string to a Windows code page into a byte string using a
7474 * error handler.
7475 *
7476 * Returns consumed characters if succeed, or raise a WindowsError and returns
7477 * -1 on other error.
7478 */
7479static int
7480encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007481 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007482 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007483{
Victor Stinner3a50e702011-10-18 21:21:00 +02007484 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007485 Py_ssize_t pos = unicode_offset;
7486 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007487 /* Ideally, we should get reason from FormatMessage. This is the Windows
7488 2000 English version of the message. */
7489 const char *reason = "invalid character";
7490 /* 4=maximum length of a UTF-8 sequence */
7491 char buffer[4];
7492 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7493 Py_ssize_t outsize;
7494 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007495 PyObject *errorHandler = NULL;
7496 PyObject *exc = NULL;
7497 PyObject *encoding_obj = NULL;
7498 char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007499 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007500 PyObject *rep;
7501 int ret = -1;
7502
7503 assert(insize > 0);
7504
7505 encoding = code_page_name(code_page, &encoding_obj);
7506 if (encoding == NULL)
7507 return -1;
7508
7509 if (errors == NULL || strcmp(errors, "strict") == 0) {
7510 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7511 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007512 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007513 if (exc != NULL) {
7514 PyCodec_StrictErrors(exc);
7515 Py_DECREF(exc);
7516 }
7517 Py_XDECREF(encoding_obj);
7518 return -1;
7519 }
7520
7521 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7522 pusedDefaultChar = &usedDefaultChar;
7523 else
7524 pusedDefaultChar = NULL;
7525
7526 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7527 PyErr_NoMemory();
7528 goto error;
7529 }
7530 outsize = insize * Py_ARRAY_LENGTH(buffer);
7531
7532 if (*outbytes == NULL) {
7533 /* Create string object */
7534 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7535 if (*outbytes == NULL)
7536 goto error;
7537 out = PyBytes_AS_STRING(*outbytes);
7538 }
7539 else {
7540 /* Extend string object */
7541 Py_ssize_t n = PyBytes_Size(*outbytes);
7542 if (n > PY_SSIZE_T_MAX - outsize) {
7543 PyErr_NoMemory();
7544 goto error;
7545 }
7546 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7547 goto error;
7548 out = PyBytes_AS_STRING(*outbytes) + n;
7549 }
7550
7551 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007552 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007553 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007554 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7555 wchar_t chars[2];
7556 int charsize;
7557 if (ch < 0x10000) {
7558 chars[0] = (wchar_t)ch;
7559 charsize = 1;
7560 }
7561 else {
7562 ch -= 0x10000;
7563 chars[0] = 0xd800 + (ch >> 10);
7564 chars[1] = 0xdc00 + (ch & 0x3ff);
7565 charsize = 2;
7566 }
7567
Victor Stinner3a50e702011-10-18 21:21:00 +02007568 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007569 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007570 buffer, Py_ARRAY_LENGTH(buffer),
7571 NULL, pusedDefaultChar);
7572 if (outsize > 0) {
7573 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7574 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007575 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007576 memcpy(out, buffer, outsize);
7577 out += outsize;
7578 continue;
7579 }
7580 }
7581 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7582 PyErr_SetFromWindowsErr(0);
7583 goto error;
7584 }
7585
Victor Stinner3a50e702011-10-18 21:21:00 +02007586 rep = unicode_encode_call_errorhandler(
7587 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007588 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007589 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007590 if (rep == NULL)
7591 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007592 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007593
7594 if (PyBytes_Check(rep)) {
7595 outsize = PyBytes_GET_SIZE(rep);
7596 if (outsize != 1) {
7597 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7598 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7599 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7600 Py_DECREF(rep);
7601 goto error;
7602 }
7603 out = PyBytes_AS_STRING(*outbytes) + offset;
7604 }
7605 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7606 out += outsize;
7607 }
7608 else {
7609 Py_ssize_t i;
7610 enum PyUnicode_Kind kind;
7611 void *data;
7612
Benjamin Petersonbac79492012-01-14 13:34:47 -05007613 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007614 Py_DECREF(rep);
7615 goto error;
7616 }
7617
7618 outsize = PyUnicode_GET_LENGTH(rep);
7619 if (outsize != 1) {
7620 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7621 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7622 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7623 Py_DECREF(rep);
7624 goto error;
7625 }
7626 out = PyBytes_AS_STRING(*outbytes) + offset;
7627 }
7628 kind = PyUnicode_KIND(rep);
7629 data = PyUnicode_DATA(rep);
7630 for (i=0; i < outsize; i++) {
7631 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7632 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007633 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007634 encoding, unicode,
7635 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007636 "unable to encode error handler result to ASCII");
7637 Py_DECREF(rep);
7638 goto error;
7639 }
7640 *out = (unsigned char)ch;
7641 out++;
7642 }
7643 }
7644 Py_DECREF(rep);
7645 }
7646 /* write a NUL byte */
7647 *out = 0;
7648 outsize = out - PyBytes_AS_STRING(*outbytes);
7649 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7650 if (_PyBytes_Resize(outbytes, outsize) < 0)
7651 goto error;
7652 ret = 0;
7653
7654error:
7655 Py_XDECREF(encoding_obj);
7656 Py_XDECREF(errorHandler);
7657 Py_XDECREF(exc);
7658 return ret;
7659}
7660
Victor Stinner3a50e702011-10-18 21:21:00 +02007661static PyObject *
7662encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007663 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007664 const char *errors)
7665{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007666 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007667 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007668 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007669 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007670
Benjamin Petersonbac79492012-01-14 13:34:47 -05007671 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007672 return NULL;
7673 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007674
Victor Stinner3a50e702011-10-18 21:21:00 +02007675 if (code_page < 0) {
7676 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7677 return NULL;
7678 }
7679
Martin v. Löwis3d325192011-11-04 18:23:06 +01007680 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007681 return PyBytes_FromStringAndSize(NULL, 0);
7682
Victor Stinner7581cef2011-11-03 22:32:33 +01007683 offset = 0;
7684 do
7685 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007686#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007687 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007688 chunks. */
7689 if (len > INT_MAX/2) {
7690 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007691 done = 0;
7692 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007693 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007694#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007695 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007696 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007697 done = 1;
7698 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007699
Victor Stinner76a31a62011-11-04 00:05:13 +01007700 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007701 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007702 errors);
7703 if (ret == -2)
7704 ret = encode_code_page_errors(code_page, &outbytes,
7705 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007706 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007707 if (ret < 0) {
7708 Py_XDECREF(outbytes);
7709 return NULL;
7710 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007711
Victor Stinner7581cef2011-11-03 22:32:33 +01007712 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007713 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007714 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007715
Victor Stinner3a50e702011-10-18 21:21:00 +02007716 return outbytes;
7717}
7718
7719PyObject *
7720PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7721 Py_ssize_t size,
7722 const char *errors)
7723{
Victor Stinner7581cef2011-11-03 22:32:33 +01007724 PyObject *unicode, *res;
7725 unicode = PyUnicode_FromUnicode(p, size);
7726 if (unicode == NULL)
7727 return NULL;
7728 res = encode_code_page(CP_ACP, unicode, errors);
7729 Py_DECREF(unicode);
7730 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007731}
7732
7733PyObject *
7734PyUnicode_EncodeCodePage(int code_page,
7735 PyObject *unicode,
7736 const char *errors)
7737{
Victor Stinner7581cef2011-11-03 22:32:33 +01007738 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007739}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007740
Alexander Belopolsky40018472011-02-26 01:02:56 +00007741PyObject *
7742PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007743{
7744 if (!PyUnicode_Check(unicode)) {
7745 PyErr_BadArgument();
7746 return NULL;
7747 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007748 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007749}
7750
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007751#undef NEED_RETRY
7752
Victor Stinner99b95382011-07-04 14:23:54 +02007753#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007754
Guido van Rossumd57fd912000-03-10 22:53:23 +00007755/* --- Character Mapping Codec -------------------------------------------- */
7756
Alexander Belopolsky40018472011-02-26 01:02:56 +00007757PyObject *
7758PyUnicode_DecodeCharmap(const char *s,
7759 Py_ssize_t size,
7760 PyObject *mapping,
7761 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007762{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007763 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007764 Py_ssize_t startinpos;
7765 Py_ssize_t endinpos;
7766 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007767 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01007768 PyObject *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007769 Py_ssize_t extrachars = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007770 PyObject *errorHandler = NULL;
7771 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00007772
Guido van Rossumd57fd912000-03-10 22:53:23 +00007773 /* Default to Latin-1 */
7774 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007775 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007776
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007777 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007778 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007779 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007780 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01007781 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007782 outpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007783 e = s + size;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007784 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007785 Py_ssize_t maplen;
7786 enum PyUnicode_Kind kind;
7787 void *data;
7788 Py_UCS4 x;
7789
Benjamin Petersonbac79492012-01-14 13:34:47 -05007790 if (PyUnicode_READY(mapping) == -1)
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007791 return NULL;
7792
7793 maplen = PyUnicode_GET_LENGTH(mapping);
7794 data = PyUnicode_DATA(mapping);
7795 kind = PyUnicode_KIND(mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007796 while (s < e) {
7797 unsigned char ch = *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007798
Benjamin Peterson29060642009-01-31 22:14:21 +00007799 if (ch < maplen)
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007800 x = PyUnicode_READ(kind, data, ch);
7801 else
7802 x = 0xfffe; /* invalid value */
Guido van Rossumd57fd912000-03-10 22:53:23 +00007803
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007804 if (x == 0xfffe)
7805 {
Benjamin Peterson29060642009-01-31 22:14:21 +00007806 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007807 startinpos = s-starts;
7808 endinpos = startinpos+1;
7809 if (unicode_decode_call_errorhandler(
7810 errors, &errorHandler,
7811 "charmap", "character maps to <undefined>",
7812 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007813 &v, &outpos)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007814 goto onError;
7815 }
7816 continue;
7817 }
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007818
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007819 if (unicode_putchar(&v, &outpos, x) < 0)
7820 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007821 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007822 }
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007823 }
7824 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007825 while (s < e) {
7826 unsigned char ch = *s;
7827 PyObject *w, *x;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007828
Benjamin Peterson29060642009-01-31 22:14:21 +00007829 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7830 w = PyLong_FromLong((long)ch);
7831 if (w == NULL)
7832 goto onError;
7833 x = PyObject_GetItem(mapping, w);
7834 Py_DECREF(w);
7835 if (x == NULL) {
7836 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7837 /* No mapping found means: mapping is undefined. */
7838 PyErr_Clear();
7839 x = Py_None;
7840 Py_INCREF(x);
7841 } else
7842 goto onError;
7843 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007844
Benjamin Peterson29060642009-01-31 22:14:21 +00007845 /* Apply mapping */
7846 if (PyLong_Check(x)) {
7847 long value = PyLong_AS_LONG(x);
7848 if (value < 0 || value > 65535) {
7849 PyErr_SetString(PyExc_TypeError,
7850 "character mapping must be in range(65536)");
7851 Py_DECREF(x);
7852 goto onError;
7853 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007854 if (unicode_putchar(&v, &outpos, value) < 0)
7855 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007856 }
7857 else if (x == Py_None) {
7858 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007859 startinpos = s-starts;
7860 endinpos = startinpos+1;
7861 if (unicode_decode_call_errorhandler(
7862 errors, &errorHandler,
7863 "charmap", "character maps to <undefined>",
7864 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007865 &v, &outpos)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007866 Py_DECREF(x);
7867 goto onError;
7868 }
7869 Py_DECREF(x);
7870 continue;
7871 }
7872 else if (PyUnicode_Check(x)) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007873 Py_ssize_t targetsize;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007874
Benjamin Petersonbac79492012-01-14 13:34:47 -05007875 if (PyUnicode_READY(x) == -1)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007876 goto onError;
7877 targetsize = PyUnicode_GET_LENGTH(x);
7878
7879 if (targetsize == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007880 /* 1-1 mapping */
Victor Stinner62aa4d02011-11-09 00:03:45 +01007881 if (unicode_putchar(&v, &outpos,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007882 PyUnicode_READ_CHAR(x, 0)) < 0)
7883 goto onError;
7884 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007885 else if (targetsize > 1) {
7886 /* 1-n mapping */
7887 if (targetsize > extrachars) {
7888 /* resize first */
Benjamin Peterson29060642009-01-31 22:14:21 +00007889 Py_ssize_t needed = (targetsize - extrachars) + \
7890 (targetsize << 2);
7891 extrachars += needed;
7892 /* XXX overflow detection missing */
Victor Stinner16e6a802011-12-12 13:24:15 +01007893 if (unicode_resize(&v,
7894 PyUnicode_GET_LENGTH(v) + needed) < 0)
7895 {
Benjamin Peterson29060642009-01-31 22:14:21 +00007896 Py_DECREF(x);
7897 goto onError;
7898 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007899 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007900 if (unicode_widen(&v, PyUnicode_MAX_CHAR_VALUE(x)) < 0)
7901 goto onError;
7902 PyUnicode_CopyCharacters(v, outpos, x, 0, targetsize);
7903 outpos += targetsize;
Benjamin Peterson29060642009-01-31 22:14:21 +00007904 extrachars -= targetsize;
7905 }
7906 /* 1-0 mapping: skip the character */
7907 }
7908 else {
7909 /* wrong return value */
7910 PyErr_SetString(PyExc_TypeError,
7911 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00007912 Py_DECREF(x);
7913 goto onError;
7914 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007915 Py_DECREF(x);
7916 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007917 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007918 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007919 if (unicode_resize(&v, outpos) < 0)
Antoine Pitroua8f63c02011-11-08 18:37:16 +01007920 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007921 Py_XDECREF(errorHandler);
7922 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007923 return unicode_result(v);
Tim Petersced69f82003-09-16 20:30:58 +00007924
Benjamin Peterson29060642009-01-31 22:14:21 +00007925 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007926 Py_XDECREF(errorHandler);
7927 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007928 Py_XDECREF(v);
7929 return NULL;
7930}
7931
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007932/* Charmap encoding: the lookup table */
7933
Alexander Belopolsky40018472011-02-26 01:02:56 +00007934struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007935 PyObject_HEAD
7936 unsigned char level1[32];
7937 int count2, count3;
7938 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007939};
7940
7941static PyObject*
7942encoding_map_size(PyObject *obj, PyObject* args)
7943{
7944 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007945 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007946 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007947}
7948
7949static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007950 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007951 PyDoc_STR("Return the size (in bytes) of this object") },
7952 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007953};
7954
7955static void
7956encoding_map_dealloc(PyObject* o)
7957{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007958 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007959}
7960
7961static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007962 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007963 "EncodingMap", /*tp_name*/
7964 sizeof(struct encoding_map), /*tp_basicsize*/
7965 0, /*tp_itemsize*/
7966 /* methods */
7967 encoding_map_dealloc, /*tp_dealloc*/
7968 0, /*tp_print*/
7969 0, /*tp_getattr*/
7970 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007971 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007972 0, /*tp_repr*/
7973 0, /*tp_as_number*/
7974 0, /*tp_as_sequence*/
7975 0, /*tp_as_mapping*/
7976 0, /*tp_hash*/
7977 0, /*tp_call*/
7978 0, /*tp_str*/
7979 0, /*tp_getattro*/
7980 0, /*tp_setattro*/
7981 0, /*tp_as_buffer*/
7982 Py_TPFLAGS_DEFAULT, /*tp_flags*/
7983 0, /*tp_doc*/
7984 0, /*tp_traverse*/
7985 0, /*tp_clear*/
7986 0, /*tp_richcompare*/
7987 0, /*tp_weaklistoffset*/
7988 0, /*tp_iter*/
7989 0, /*tp_iternext*/
7990 encoding_map_methods, /*tp_methods*/
7991 0, /*tp_members*/
7992 0, /*tp_getset*/
7993 0, /*tp_base*/
7994 0, /*tp_dict*/
7995 0, /*tp_descr_get*/
7996 0, /*tp_descr_set*/
7997 0, /*tp_dictoffset*/
7998 0, /*tp_init*/
7999 0, /*tp_alloc*/
8000 0, /*tp_new*/
8001 0, /*tp_free*/
8002 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008003};
8004
8005PyObject*
8006PyUnicode_BuildEncodingMap(PyObject* string)
8007{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008008 PyObject *result;
8009 struct encoding_map *mresult;
8010 int i;
8011 int need_dict = 0;
8012 unsigned char level1[32];
8013 unsigned char level2[512];
8014 unsigned char *mlevel1, *mlevel2, *mlevel3;
8015 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008016 int kind;
8017 void *data;
8018 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008019
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008020 if (!PyUnicode_Check(string) || PyUnicode_GET_LENGTH(string) != 256) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008021 PyErr_BadArgument();
8022 return NULL;
8023 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008024 kind = PyUnicode_KIND(string);
8025 data = PyUnicode_DATA(string);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008026 memset(level1, 0xFF, sizeof level1);
8027 memset(level2, 0xFF, sizeof level2);
8028
8029 /* If there isn't a one-to-one mapping of NULL to \0,
8030 or if there are non-BMP characters, we need to use
8031 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008032 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008033 need_dict = 1;
8034 for (i = 1; i < 256; i++) {
8035 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008036 ch = PyUnicode_READ(kind, data, i);
8037 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008038 need_dict = 1;
8039 break;
8040 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008041 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008042 /* unmapped character */
8043 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008044 l1 = ch >> 11;
8045 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008046 if (level1[l1] == 0xFF)
8047 level1[l1] = count2++;
8048 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00008049 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008050 }
8051
8052 if (count2 >= 0xFF || count3 >= 0xFF)
8053 need_dict = 1;
8054
8055 if (need_dict) {
8056 PyObject *result = PyDict_New();
8057 PyObject *key, *value;
8058 if (!result)
8059 return NULL;
8060 for (i = 0; i < 256; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008061 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00008062 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008063 if (!key || !value)
8064 goto failed1;
8065 if (PyDict_SetItem(result, key, value) == -1)
8066 goto failed1;
8067 Py_DECREF(key);
8068 Py_DECREF(value);
8069 }
8070 return result;
8071 failed1:
8072 Py_XDECREF(key);
8073 Py_XDECREF(value);
8074 Py_DECREF(result);
8075 return NULL;
8076 }
8077
8078 /* Create a three-level trie */
8079 result = PyObject_MALLOC(sizeof(struct encoding_map) +
8080 16*count2 + 128*count3 - 1);
8081 if (!result)
8082 return PyErr_NoMemory();
8083 PyObject_Init(result, &EncodingMapType);
8084 mresult = (struct encoding_map*)result;
8085 mresult->count2 = count2;
8086 mresult->count3 = count3;
8087 mlevel1 = mresult->level1;
8088 mlevel2 = mresult->level23;
8089 mlevel3 = mresult->level23 + 16*count2;
8090 memcpy(mlevel1, level1, 32);
8091 memset(mlevel2, 0xFF, 16*count2);
8092 memset(mlevel3, 0, 128*count3);
8093 count3 = 0;
8094 for (i = 1; i < 256; i++) {
8095 int o1, o2, o3, i2, i3;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008096 if (PyUnicode_READ(kind, data, i) == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008097 /* unmapped character */
8098 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008099 o1 = PyUnicode_READ(kind, data, i)>>11;
8100 o2 = (PyUnicode_READ(kind, data, i)>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008101 i2 = 16*mlevel1[o1] + o2;
8102 if (mlevel2[i2] == 0xFF)
8103 mlevel2[i2] = count3++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008104 o3 = PyUnicode_READ(kind, data, i) & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008105 i3 = 128*mlevel2[i2] + o3;
8106 mlevel3[i3] = i;
8107 }
8108 return result;
8109}
8110
8111static int
Victor Stinner22168992011-11-20 17:09:18 +01008112encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008113{
8114 struct encoding_map *map = (struct encoding_map*)mapping;
8115 int l1 = c>>11;
8116 int l2 = (c>>7) & 0xF;
8117 int l3 = c & 0x7F;
8118 int i;
8119
Victor Stinner22168992011-11-20 17:09:18 +01008120 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00008121 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008122 if (c == 0)
8123 return 0;
8124 /* level 1*/
8125 i = map->level1[l1];
8126 if (i == 0xFF) {
8127 return -1;
8128 }
8129 /* level 2*/
8130 i = map->level23[16*i+l2];
8131 if (i == 0xFF) {
8132 return -1;
8133 }
8134 /* level 3 */
8135 i = map->level23[16*map->count2 + 128*i + l3];
8136 if (i == 0) {
8137 return -1;
8138 }
8139 return i;
8140}
8141
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008142/* Lookup the character ch in the mapping. If the character
8143 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00008144 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008145static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01008146charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008147{
Christian Heimes217cfd12007-12-02 14:31:20 +00008148 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008149 PyObject *x;
8150
8151 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008152 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008153 x = PyObject_GetItem(mapping, w);
8154 Py_DECREF(w);
8155 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008156 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8157 /* No mapping found means: mapping is undefined. */
8158 PyErr_Clear();
8159 x = Py_None;
8160 Py_INCREF(x);
8161 return x;
8162 } else
8163 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008164 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00008165 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008166 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00008167 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008168 long value = PyLong_AS_LONG(x);
8169 if (value < 0 || value > 255) {
8170 PyErr_SetString(PyExc_TypeError,
8171 "character mapping must be in range(256)");
8172 Py_DECREF(x);
8173 return NULL;
8174 }
8175 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008176 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008177 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008178 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008179 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008180 /* wrong return value */
8181 PyErr_Format(PyExc_TypeError,
8182 "character mapping must return integer, bytes or None, not %.400s",
8183 x->ob_type->tp_name);
8184 Py_DECREF(x);
8185 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008186 }
8187}
8188
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008189static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008190charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008191{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008192 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8193 /* exponentially overallocate to minimize reallocations */
8194 if (requiredsize < 2*outsize)
8195 requiredsize = 2*outsize;
8196 if (_PyBytes_Resize(outobj, requiredsize))
8197 return -1;
8198 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008199}
8200
Benjamin Peterson14339b62009-01-31 16:36:08 +00008201typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008202 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008203} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008204/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008205 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008206 space is available. Return a new reference to the object that
8207 was put in the output buffer, or Py_None, if the mapping was undefined
8208 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008209 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008210static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01008211charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008212 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008213{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008214 PyObject *rep;
8215 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008216 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008217
Christian Heimes90aa7642007-12-19 02:45:37 +00008218 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008219 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008220 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008221 if (res == -1)
8222 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008223 if (outsize<requiredsize)
8224 if (charmapencode_resize(outobj, outpos, requiredsize))
8225 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008226 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008227 outstart[(*outpos)++] = (char)res;
8228 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008229 }
8230
8231 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008232 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008233 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008234 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008235 Py_DECREF(rep);
8236 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008237 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008238 if (PyLong_Check(rep)) {
8239 Py_ssize_t requiredsize = *outpos+1;
8240 if (outsize<requiredsize)
8241 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8242 Py_DECREF(rep);
8243 return enc_EXCEPTION;
8244 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008245 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008246 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008247 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008248 else {
8249 const char *repchars = PyBytes_AS_STRING(rep);
8250 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8251 Py_ssize_t requiredsize = *outpos+repsize;
8252 if (outsize<requiredsize)
8253 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8254 Py_DECREF(rep);
8255 return enc_EXCEPTION;
8256 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008257 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008258 memcpy(outstart + *outpos, repchars, repsize);
8259 *outpos += repsize;
8260 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008261 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008262 Py_DECREF(rep);
8263 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008264}
8265
8266/* handle an error in PyUnicode_EncodeCharmap
8267 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008268static int
8269charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008270 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008271 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00008272 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008273 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008274{
8275 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008276 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008277 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008278 enum PyUnicode_Kind kind;
8279 void *data;
8280 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008281 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008282 Py_ssize_t collstartpos = *inpos;
8283 Py_ssize_t collendpos = *inpos+1;
8284 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008285 char *encoding = "charmap";
8286 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008287 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008288 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008289 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008290
Benjamin Petersonbac79492012-01-14 13:34:47 -05008291 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008292 return -1;
8293 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008294 /* find all unencodable characters */
8295 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008296 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008297 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008298 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008299 val = encoding_map_lookup(ch, mapping);
8300 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008301 break;
8302 ++collendpos;
8303 continue;
8304 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008305
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008306 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8307 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008308 if (rep==NULL)
8309 return -1;
8310 else if (rep!=Py_None) {
8311 Py_DECREF(rep);
8312 break;
8313 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008314 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008315 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008316 }
8317 /* cache callback name lookup
8318 * (if not done yet, i.e. it's the first error) */
8319 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008320 if ((errors==NULL) || (!strcmp(errors, "strict")))
8321 *known_errorHandler = 1;
8322 else if (!strcmp(errors, "replace"))
8323 *known_errorHandler = 2;
8324 else if (!strcmp(errors, "ignore"))
8325 *known_errorHandler = 3;
8326 else if (!strcmp(errors, "xmlcharrefreplace"))
8327 *known_errorHandler = 4;
8328 else
8329 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008330 }
8331 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008332 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008333 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008334 return -1;
8335 case 2: /* replace */
8336 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008337 x = charmapencode_output('?', mapping, res, respos);
8338 if (x==enc_EXCEPTION) {
8339 return -1;
8340 }
8341 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008342 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008343 return -1;
8344 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008345 }
8346 /* fall through */
8347 case 3: /* ignore */
8348 *inpos = collendpos;
8349 break;
8350 case 4: /* xmlcharrefreplace */
8351 /* generate replacement (temporarily (mis)uses p) */
8352 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008353 char buffer[2+29+1+1];
8354 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008355 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008356 for (cp = buffer; *cp; ++cp) {
8357 x = charmapencode_output(*cp, mapping, res, respos);
8358 if (x==enc_EXCEPTION)
8359 return -1;
8360 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008361 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008362 return -1;
8363 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008364 }
8365 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008366 *inpos = collendpos;
8367 break;
8368 default:
8369 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008370 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008371 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008372 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008373 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008374 if (PyBytes_Check(repunicode)) {
8375 /* Directly copy bytes result to output. */
8376 Py_ssize_t outsize = PyBytes_Size(*res);
8377 Py_ssize_t requiredsize;
8378 repsize = PyBytes_Size(repunicode);
8379 requiredsize = *respos + repsize;
8380 if (requiredsize > outsize)
8381 /* Make room for all additional bytes. */
8382 if (charmapencode_resize(res, respos, requiredsize)) {
8383 Py_DECREF(repunicode);
8384 return -1;
8385 }
8386 memcpy(PyBytes_AsString(*res) + *respos,
8387 PyBytes_AsString(repunicode), repsize);
8388 *respos += repsize;
8389 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008390 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008391 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008392 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008393 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008394 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008395 Py_DECREF(repunicode);
8396 return -1;
8397 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008398 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008399 data = PyUnicode_DATA(repunicode);
8400 kind = PyUnicode_KIND(repunicode);
8401 for (index = 0; index < repsize; index++) {
8402 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8403 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008404 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008405 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008406 return -1;
8407 }
8408 else if (x==enc_FAILED) {
8409 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008410 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008411 return -1;
8412 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008413 }
8414 *inpos = newpos;
8415 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008416 }
8417 return 0;
8418}
8419
Alexander Belopolsky40018472011-02-26 01:02:56 +00008420PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008421_PyUnicode_EncodeCharmap(PyObject *unicode,
8422 PyObject *mapping,
8423 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008424{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008425 /* output object */
8426 PyObject *res = NULL;
8427 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008428 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008429 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008430 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008431 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008432 PyObject *errorHandler = NULL;
8433 PyObject *exc = NULL;
8434 /* the following variable is used for caching string comparisons
8435 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8436 * 3=ignore, 4=xmlcharrefreplace */
8437 int known_errorHandler = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008438
Benjamin Petersonbac79492012-01-14 13:34:47 -05008439 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008440 return NULL;
8441 size = PyUnicode_GET_LENGTH(unicode);
8442
Guido van Rossumd57fd912000-03-10 22:53:23 +00008443 /* Default to Latin-1 */
8444 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008445 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008446
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008447 /* allocate enough for a simple encoding without
8448 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008449 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008450 if (res == NULL)
8451 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008452 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008453 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008454
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008455 while (inpos<size) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008456 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008457 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008458 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008459 if (x==enc_EXCEPTION) /* error */
8460 goto onError;
8461 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008462 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008463 &exc,
8464 &known_errorHandler, &errorHandler, errors,
8465 &res, &respos)) {
8466 goto onError;
8467 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008468 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008469 else
8470 /* done with this character => adjust input position */
8471 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008472 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008473
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008474 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008475 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008476 if (_PyBytes_Resize(&res, respos) < 0)
8477 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008478
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008479 Py_XDECREF(exc);
8480 Py_XDECREF(errorHandler);
8481 return res;
8482
Benjamin Peterson29060642009-01-31 22:14:21 +00008483 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008484 Py_XDECREF(res);
8485 Py_XDECREF(exc);
8486 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008487 return NULL;
8488}
8489
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008490/* Deprecated */
8491PyObject *
8492PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8493 Py_ssize_t size,
8494 PyObject *mapping,
8495 const char *errors)
8496{
8497 PyObject *result;
8498 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8499 if (unicode == NULL)
8500 return NULL;
8501 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8502 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008503 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008504}
8505
Alexander Belopolsky40018472011-02-26 01:02:56 +00008506PyObject *
8507PyUnicode_AsCharmapString(PyObject *unicode,
8508 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008509{
8510 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008511 PyErr_BadArgument();
8512 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008513 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008514 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008515}
8516
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008517/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008518static void
8519make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008520 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008521 Py_ssize_t startpos, Py_ssize_t endpos,
8522 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008523{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008524 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008525 *exceptionObject = _PyUnicodeTranslateError_Create(
8526 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008527 }
8528 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008529 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8530 goto onError;
8531 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8532 goto onError;
8533 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8534 goto onError;
8535 return;
8536 onError:
8537 Py_DECREF(*exceptionObject);
8538 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008539 }
8540}
8541
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008542/* raises a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008543static void
8544raise_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008545 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008546 Py_ssize_t startpos, Py_ssize_t endpos,
8547 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008548{
8549 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008550 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008551 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008552 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008553}
8554
8555/* error handling callback helper:
8556 build arguments, call the callback and check the arguments,
8557 put the result into newpos and return the replacement string, which
8558 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008559static PyObject *
8560unicode_translate_call_errorhandler(const char *errors,
8561 PyObject **errorHandler,
8562 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008563 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008564 Py_ssize_t startpos, Py_ssize_t endpos,
8565 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008566{
Benjamin Peterson142957c2008-07-04 19:55:29 +00008567 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008568
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008569 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008570 PyObject *restuple;
8571 PyObject *resunicode;
8572
8573 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008574 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008575 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008576 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008577 }
8578
8579 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008580 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008581 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008582 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008583
8584 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008585 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008586 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008587 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008588 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008589 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008590 Py_DECREF(restuple);
8591 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008592 }
8593 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008594 &resunicode, &i_newpos)) {
8595 Py_DECREF(restuple);
8596 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008597 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008598 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008599 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008600 else
8601 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008602 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008603 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
8604 Py_DECREF(restuple);
8605 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008606 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008607 Py_INCREF(resunicode);
8608 Py_DECREF(restuple);
8609 return resunicode;
8610}
8611
8612/* Lookup the character ch in the mapping and put the result in result,
8613 which must be decrefed by the caller.
8614 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008615static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008616charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008617{
Christian Heimes217cfd12007-12-02 14:31:20 +00008618 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008619 PyObject *x;
8620
8621 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008622 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008623 x = PyObject_GetItem(mapping, w);
8624 Py_DECREF(w);
8625 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008626 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8627 /* No mapping found means: use 1:1 mapping. */
8628 PyErr_Clear();
8629 *result = NULL;
8630 return 0;
8631 } else
8632 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008633 }
8634 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008635 *result = x;
8636 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008637 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008638 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008639 long value = PyLong_AS_LONG(x);
8640 long max = PyUnicode_GetMax();
8641 if (value < 0 || value > max) {
8642 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00008643 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008644 Py_DECREF(x);
8645 return -1;
8646 }
8647 *result = x;
8648 return 0;
8649 }
8650 else if (PyUnicode_Check(x)) {
8651 *result = x;
8652 return 0;
8653 }
8654 else {
8655 /* wrong return value */
8656 PyErr_SetString(PyExc_TypeError,
8657 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008658 Py_DECREF(x);
8659 return -1;
8660 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008661}
8662/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00008663 if not reallocate and adjust various state variables.
8664 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008665static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008666charmaptranslate_makespace(Py_UCS4 **outobj, Py_ssize_t *psize,
Benjamin Peterson29060642009-01-31 22:14:21 +00008667 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008668{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008669 Py_ssize_t oldsize = *psize;
Walter Dörwald4894c302003-10-24 14:25:28 +00008670 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008671 /* exponentially overallocate to minimize reallocations */
8672 if (requiredsize < 2 * oldsize)
8673 requiredsize = 2 * oldsize;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008674 *outobj = PyMem_Realloc(*outobj, requiredsize * sizeof(Py_UCS4));
8675 if (*outobj == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008676 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008677 *psize = requiredsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008678 }
8679 return 0;
8680}
8681/* lookup the character, put the result in the output string and adjust
8682 various state variables. Return a new reference to the object that
8683 was put in the output buffer in *result, or Py_None, if the mapping was
8684 undefined (in which case no character was written).
8685 The called must decref result.
8686 Return 0 on success, -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008687static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008688charmaptranslate_output(PyObject *input, Py_ssize_t ipos,
8689 PyObject *mapping, Py_UCS4 **output,
8690 Py_ssize_t *osize, Py_ssize_t *opos,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008691 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008692{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008693 Py_UCS4 curinp = PyUnicode_READ_CHAR(input, ipos);
8694 if (charmaptranslate_lookup(curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00008695 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008696 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008697 /* not found => default to 1:1 mapping */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008698 (*output)[(*opos)++] = curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008699 }
8700 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008701 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00008702 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008703 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008704 (*output)[(*opos)++] = (Py_UCS4)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008705 }
8706 else if (PyUnicode_Check(*res)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008707 Py_ssize_t repsize;
8708 if (PyUnicode_READY(*res) == -1)
8709 return -1;
8710 repsize = PyUnicode_GET_LENGTH(*res);
Benjamin Peterson29060642009-01-31 22:14:21 +00008711 if (repsize==1) {
8712 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008713 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00008714 }
8715 else if (repsize!=0) {
8716 /* more than one character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008717 Py_ssize_t requiredsize = *opos +
8718 (PyUnicode_GET_LENGTH(input) - ipos) +
Benjamin Peterson29060642009-01-31 22:14:21 +00008719 repsize - 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008720 Py_ssize_t i;
8721 if (charmaptranslate_makespace(output, osize, requiredsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00008722 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008723 for(i = 0; i < repsize; i++)
8724 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00008725 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008726 }
8727 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008728 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008729 return 0;
8730}
8731
Alexander Belopolsky40018472011-02-26 01:02:56 +00008732PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008733_PyUnicode_TranslateCharmap(PyObject *input,
8734 PyObject *mapping,
8735 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008736{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008737 /* input object */
8738 char *idata;
8739 Py_ssize_t size, i;
8740 int kind;
8741 /* output buffer */
8742 Py_UCS4 *output = NULL;
8743 Py_ssize_t osize;
8744 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008745 /* current output position */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008746 Py_ssize_t opos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008747 char *reason = "character maps to <undefined>";
8748 PyObject *errorHandler = NULL;
8749 PyObject *exc = NULL;
8750 /* the following variable is used for caching string comparisons
8751 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8752 * 3=ignore, 4=xmlcharrefreplace */
8753 int known_errorHandler = -1;
8754
Guido van Rossumd57fd912000-03-10 22:53:23 +00008755 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008756 PyErr_BadArgument();
8757 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008758 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008759
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008760 if (PyUnicode_READY(input) == -1)
8761 return NULL;
8762 idata = (char*)PyUnicode_DATA(input);
8763 kind = PyUnicode_KIND(input);
8764 size = PyUnicode_GET_LENGTH(input);
8765 i = 0;
8766
8767 if (size == 0) {
8768 Py_INCREF(input);
8769 return input;
8770 }
8771
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008772 /* allocate enough for a simple 1:1 translation without
8773 replacements, if we need more, we'll resize */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008774 osize = size;
8775 output = PyMem_Malloc(osize * sizeof(Py_UCS4));
8776 opos = 0;
8777 if (output == NULL) {
8778 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00008779 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008780 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008781
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008782 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008783 /* try to encode it */
8784 PyObject *x = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008785 if (charmaptranslate_output(input, i, mapping,
8786 &output, &osize, &opos, &x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008787 Py_XDECREF(x);
8788 goto onError;
8789 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008790 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00008791 if (x!=Py_None) /* it worked => adjust input pointer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008792 ++i;
Benjamin Peterson29060642009-01-31 22:14:21 +00008793 else { /* untranslatable character */
8794 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8795 Py_ssize_t repsize;
8796 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008797 Py_ssize_t uni2;
Benjamin Peterson29060642009-01-31 22:14:21 +00008798 /* startpos for collecting untranslatable chars */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008799 Py_ssize_t collstart = i;
8800 Py_ssize_t collend = i+1;
8801 Py_ssize_t coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008802
Benjamin Peterson29060642009-01-31 22:14:21 +00008803 /* find all untranslatable characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008804 while (collend < size) {
8805 if (charmaptranslate_lookup(PyUnicode_READ(kind,idata, collend), mapping, &x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008806 goto onError;
8807 Py_XDECREF(x);
8808 if (x!=Py_None)
8809 break;
8810 ++collend;
8811 }
8812 /* cache callback name lookup
8813 * (if not done yet, i.e. it's the first error) */
8814 if (known_errorHandler==-1) {
8815 if ((errors==NULL) || (!strcmp(errors, "strict")))
8816 known_errorHandler = 1;
8817 else if (!strcmp(errors, "replace"))
8818 known_errorHandler = 2;
8819 else if (!strcmp(errors, "ignore"))
8820 known_errorHandler = 3;
8821 else if (!strcmp(errors, "xmlcharrefreplace"))
8822 known_errorHandler = 4;
8823 else
8824 known_errorHandler = 0;
8825 }
8826 switch (known_errorHandler) {
8827 case 1: /* strict */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008828 raise_translate_exception(&exc, input, collstart,
8829 collend, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008830 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008831 case 2: /* replace */
8832 /* No need to check for space, this is a 1:1 replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008833 for (coll = collstart; coll<collend; coll++)
8834 output[opos++] = '?';
Benjamin Peterson29060642009-01-31 22:14:21 +00008835 /* fall through */
8836 case 3: /* ignore */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008837 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008838 break;
8839 case 4: /* xmlcharrefreplace */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008840 /* generate replacement (temporarily (mis)uses i) */
8841 for (i = collstart; i < collend; ++i) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008842 char buffer[2+29+1+1];
8843 char *cp;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008844 sprintf(buffer, "&#%d;", PyUnicode_READ(kind, idata, i));
8845 if (charmaptranslate_makespace(&output, &osize,
8846 opos+strlen(buffer)+(size-collend)))
Benjamin Peterson29060642009-01-31 22:14:21 +00008847 goto onError;
8848 for (cp = buffer; *cp; ++cp)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008849 output[opos++] = *cp;
Benjamin Peterson29060642009-01-31 22:14:21 +00008850 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008851 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008852 break;
8853 default:
8854 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008855 reason, input, &exc,
8856 collstart, collend, &newpos);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008857 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008858 goto onError;
Benjamin Peterson9ca3ffa2012-01-01 16:04:29 -06008859 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008860 Py_DECREF(repunicode);
8861 goto onError;
8862 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008863 /* generate replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008864 repsize = PyUnicode_GET_LENGTH(repunicode);
8865 if (charmaptranslate_makespace(&output, &osize,
8866 opos+repsize+(size-collend))) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008867 Py_DECREF(repunicode);
8868 goto onError;
8869 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008870 for (uni2 = 0; repsize-->0; ++uni2)
8871 output[opos++] = PyUnicode_READ_CHAR(repunicode, uni2);
8872 i = newpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00008873 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008874 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008875 }
8876 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008877 res = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, output, opos);
8878 if (!res)
8879 goto onError;
8880 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008881 Py_XDECREF(exc);
8882 Py_XDECREF(errorHandler);
8883 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008884
Benjamin Peterson29060642009-01-31 22:14:21 +00008885 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008886 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008887 Py_XDECREF(exc);
8888 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008889 return NULL;
8890}
8891
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008892/* Deprecated. Use PyUnicode_Translate instead. */
8893PyObject *
8894PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8895 Py_ssize_t size,
8896 PyObject *mapping,
8897 const char *errors)
8898{
8899 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8900 if (!unicode)
8901 return NULL;
8902 return _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8903}
8904
Alexander Belopolsky40018472011-02-26 01:02:56 +00008905PyObject *
8906PyUnicode_Translate(PyObject *str,
8907 PyObject *mapping,
8908 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008909{
8910 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008911
Guido van Rossumd57fd912000-03-10 22:53:23 +00008912 str = PyUnicode_FromObject(str);
8913 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008914 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008915 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008916 Py_DECREF(str);
8917 return result;
Tim Petersced69f82003-09-16 20:30:58 +00008918
Benjamin Peterson29060642009-01-31 22:14:21 +00008919 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00008920 Py_XDECREF(str);
8921 return NULL;
8922}
Tim Petersced69f82003-09-16 20:30:58 +00008923
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008924static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008925fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008926{
8927 /* No need to call PyUnicode_READY(self) because this function is only
8928 called as a callback from fixup() which does it already. */
8929 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8930 const int kind = PyUnicode_KIND(self);
8931 void *data = PyUnicode_DATA(self);
8932 Py_UCS4 maxchar = 0, ch, fixed;
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008933 int modified = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008934 Py_ssize_t i;
8935
8936 for (i = 0; i < len; ++i) {
8937 ch = PyUnicode_READ(kind, data, i);
8938 fixed = 0;
8939 if (ch > 127) {
8940 if (Py_UNICODE_ISSPACE(ch))
8941 fixed = ' ';
8942 else {
8943 const int decimal = Py_UNICODE_TODECIMAL(ch);
8944 if (decimal >= 0)
8945 fixed = '0' + decimal;
8946 }
8947 if (fixed != 0) {
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008948 modified = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008949 if (fixed > maxchar)
8950 maxchar = fixed;
8951 PyUnicode_WRITE(kind, data, i, fixed);
8952 }
8953 else if (ch > maxchar)
8954 maxchar = ch;
8955 }
8956 else if (ch > maxchar)
8957 maxchar = ch;
8958 }
8959
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008960 return (modified) ? maxchar : 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008961}
8962
8963PyObject *
8964_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
8965{
8966 if (!PyUnicode_Check(unicode)) {
8967 PyErr_BadInternalCall();
8968 return NULL;
8969 }
8970 if (PyUnicode_READY(unicode) == -1)
8971 return NULL;
8972 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
8973 /* If the string is already ASCII, just return the same string */
8974 Py_INCREF(unicode);
8975 return unicode;
8976 }
Victor Stinner9310abb2011-10-05 00:59:23 +02008977 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008978}
8979
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008980PyObject *
8981PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
8982 Py_ssize_t length)
8983{
Victor Stinnerf0124502011-11-21 23:12:56 +01008984 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008985 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01008986 Py_UCS4 maxchar;
8987 enum PyUnicode_Kind kind;
8988 void *data;
8989
Victor Stinner99d7ad02012-02-22 13:37:39 +01008990 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008991 for (i = 0; i < length; i++) {
Victor Stinnerf0124502011-11-21 23:12:56 +01008992 Py_UNICODE ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008993 if (ch > 127) {
8994 int decimal = Py_UNICODE_TODECIMAL(ch);
8995 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01008996 ch = '0' + decimal;
Victor Stinner99d7ad02012-02-22 13:37:39 +01008997 maxchar = Py_MAX(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008998 }
8999 }
Victor Stinnerf0124502011-11-21 23:12:56 +01009000
9001 /* Copy to a new string */
9002 decimal = PyUnicode_New(length, maxchar);
9003 if (decimal == NULL)
9004 return decimal;
9005 kind = PyUnicode_KIND(decimal);
9006 data = PyUnicode_DATA(decimal);
9007 /* Iterate over code points */
9008 for (i = 0; i < length; i++) {
9009 Py_UNICODE ch = s[i];
9010 if (ch > 127) {
9011 int decimal = Py_UNICODE_TODECIMAL(ch);
9012 if (decimal >= 0)
9013 ch = '0' + decimal;
9014 }
9015 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009016 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01009017 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009018}
Guido van Rossum9e896b32000-04-05 20:11:21 +00009019/* --- Decimal Encoder ---------------------------------------------------- */
9020
Alexander Belopolsky40018472011-02-26 01:02:56 +00009021int
9022PyUnicode_EncodeDecimal(Py_UNICODE *s,
9023 Py_ssize_t length,
9024 char *output,
9025 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00009026{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01009027 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01009028 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01009029 enum PyUnicode_Kind kind;
9030 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009031
9032 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009033 PyErr_BadArgument();
9034 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009035 }
9036
Victor Stinner42bf7752011-11-21 22:52:58 +01009037 unicode = PyUnicode_FromUnicode(s, length);
9038 if (unicode == NULL)
9039 return -1;
9040
Benjamin Petersonbac79492012-01-14 13:34:47 -05009041 if (PyUnicode_READY(unicode) == -1) {
Victor Stinner6345be92011-11-25 20:09:01 +01009042 Py_DECREF(unicode);
9043 return -1;
9044 }
Victor Stinner42bf7752011-11-21 22:52:58 +01009045 kind = PyUnicode_KIND(unicode);
9046 data = PyUnicode_DATA(unicode);
9047
Victor Stinnerb84d7232011-11-22 01:50:07 +01009048 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01009049 PyObject *exc;
9050 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00009051 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01009052 Py_ssize_t startpos;
9053
9054 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00009055
Benjamin Peterson29060642009-01-31 22:14:21 +00009056 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009057 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01009058 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009059 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009060 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009061 decimal = Py_UNICODE_TODECIMAL(ch);
9062 if (decimal >= 0) {
9063 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009064 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009065 continue;
9066 }
9067 if (0 < ch && ch < 256) {
9068 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009069 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009070 continue;
9071 }
Victor Stinner6345be92011-11-25 20:09:01 +01009072
Victor Stinner42bf7752011-11-21 22:52:58 +01009073 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01009074 exc = NULL;
9075 raise_encode_exception(&exc, "decimal", unicode,
9076 startpos, startpos+1,
9077 "invalid decimal Unicode string");
9078 Py_XDECREF(exc);
9079 Py_DECREF(unicode);
9080 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009081 }
9082 /* 0-terminate the output string */
9083 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01009084 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00009085 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009086}
9087
Guido van Rossumd57fd912000-03-10 22:53:23 +00009088/* --- Helpers ------------------------------------------------------------ */
9089
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009090static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02009091any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009092 Py_ssize_t start,
9093 Py_ssize_t end)
9094{
9095 int kind1, kind2, kind;
9096 void *buf1, *buf2;
9097 Py_ssize_t len1, len2, result;
9098
9099 kind1 = PyUnicode_KIND(s1);
9100 kind2 = PyUnicode_KIND(s2);
9101 kind = kind1 > kind2 ? kind1 : kind2;
9102 buf1 = PyUnicode_DATA(s1);
9103 buf2 = PyUnicode_DATA(s2);
9104 if (kind1 != kind)
9105 buf1 = _PyUnicode_AsKind(s1, kind);
9106 if (!buf1)
9107 return -2;
9108 if (kind2 != kind)
9109 buf2 = _PyUnicode_AsKind(s2, kind);
9110 if (!buf2) {
9111 if (kind1 != kind) PyMem_Free(buf1);
9112 return -2;
9113 }
9114 len1 = PyUnicode_GET_LENGTH(s1);
9115 len2 = PyUnicode_GET_LENGTH(s2);
9116
Victor Stinner794d5672011-10-10 03:21:36 +02009117 if (direction > 0) {
Benjamin Petersonead6b532011-12-20 17:23:42 -06009118 switch (kind) {
Victor Stinner794d5672011-10-10 03:21:36 +02009119 case PyUnicode_1BYTE_KIND:
9120 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9121 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9122 else
9123 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9124 break;
9125 case PyUnicode_2BYTE_KIND:
9126 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9127 break;
9128 case PyUnicode_4BYTE_KIND:
9129 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9130 break;
9131 default:
9132 assert(0); result = -2;
9133 }
9134 }
9135 else {
Benjamin Petersonead6b532011-12-20 17:23:42 -06009136 switch (kind) {
Victor Stinner794d5672011-10-10 03:21:36 +02009137 case PyUnicode_1BYTE_KIND:
9138 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9139 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9140 else
9141 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9142 break;
9143 case PyUnicode_2BYTE_KIND:
9144 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9145 break;
9146 case PyUnicode_4BYTE_KIND:
9147 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9148 break;
9149 default:
9150 assert(0); result = -2;
9151 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009152 }
9153
9154 if (kind1 != kind)
9155 PyMem_Free(buf1);
9156 if (kind2 != kind)
9157 PyMem_Free(buf2);
9158
9159 return result;
9160}
9161
9162Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01009163_PyUnicode_InsertThousandsGrouping(
9164 PyObject *unicode, Py_ssize_t index,
9165 Py_ssize_t n_buffer,
9166 void *digits, Py_ssize_t n_digits,
9167 Py_ssize_t min_width,
9168 const char *grouping, PyObject *thousands_sep,
9169 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009170{
Victor Stinner41a863c2012-02-24 00:37:51 +01009171 unsigned int kind, thousands_sep_kind;
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009172 char *data, *thousands_sep_data;
Victor Stinner41a863c2012-02-24 00:37:51 +01009173 Py_ssize_t thousands_sep_len;
9174 Py_ssize_t len;
9175
9176 if (unicode != NULL) {
9177 kind = PyUnicode_KIND(unicode);
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009178 data = (char *) PyUnicode_DATA(unicode) + index * kind;
Victor Stinner41a863c2012-02-24 00:37:51 +01009179 }
9180 else {
9181 kind = PyUnicode_1BYTE_KIND;
9182 data = NULL;
9183 }
9184 thousands_sep_kind = PyUnicode_KIND(thousands_sep);
9185 thousands_sep_data = PyUnicode_DATA(thousands_sep);
9186 thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
9187 if (unicode != NULL && thousands_sep_kind != kind) {
Victor Stinner90f50d42012-02-24 01:44:47 +01009188 if (thousands_sep_kind < kind) {
9189 thousands_sep_data = _PyUnicode_AsKind(thousands_sep, kind);
9190 if (!thousands_sep_data)
9191 return -1;
9192 }
9193 else {
9194 data = _PyUnicode_AsKind(unicode, thousands_sep_kind);
9195 if (!data)
9196 return -1;
9197 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009198 }
9199
Benjamin Petersonead6b532011-12-20 17:23:42 -06009200 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009201 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009202 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
Victor Stinner41a863c2012-02-24 00:37:51 +01009203 len = asciilib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009204 (Py_UCS1 *) data, n_buffer, (Py_UCS1 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009205 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009206 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009207 else
Victor Stinner41a863c2012-02-24 00:37:51 +01009208 len = ucs1lib_InsertThousandsGrouping(
Victor Stinnerc3cec782011-10-05 21:24:08 +02009209 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009210 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009211 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009212 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009213 case PyUnicode_2BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009214 len = ucs2lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009215 (Py_UCS2 *) data, n_buffer, (Py_UCS2 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009216 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009217 (Py_UCS2 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009218 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009219 case PyUnicode_4BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009220 len = ucs4lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009221 (Py_UCS4 *) data, n_buffer, (Py_UCS4 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009222 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009223 (Py_UCS4 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009224 break;
9225 default:
9226 assert(0);
9227 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009228 }
Victor Stinner90f50d42012-02-24 01:44:47 +01009229 if (unicode != NULL && thousands_sep_kind != kind) {
9230 if (thousands_sep_kind < kind)
9231 PyMem_Free(thousands_sep_data);
9232 else
9233 PyMem_Free(data);
9234 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009235 if (unicode == NULL) {
9236 *maxchar = 127;
9237 if (len != n_digits) {
9238 *maxchar = Py_MAX(*maxchar,
9239 PyUnicode_MAX_CHAR_VALUE(thousands_sep));
9240 }
9241 }
9242 return len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009243}
9244
9245
Thomas Wouters477c8d52006-05-27 19:21:47 +00009246/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009247#define ADJUST_INDICES(start, end, len) \
9248 if (end > len) \
9249 end = len; \
9250 else if (end < 0) { \
9251 end += len; \
9252 if (end < 0) \
9253 end = 0; \
9254 } \
9255 if (start < 0) { \
9256 start += len; \
9257 if (start < 0) \
9258 start = 0; \
9259 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009260
Alexander Belopolsky40018472011-02-26 01:02:56 +00009261Py_ssize_t
9262PyUnicode_Count(PyObject *str,
9263 PyObject *substr,
9264 Py_ssize_t start,
9265 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009266{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009267 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009268 PyObject* str_obj;
9269 PyObject* sub_obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009270 int kind1, kind2, kind;
9271 void *buf1 = NULL, *buf2 = NULL;
9272 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009273
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009274 str_obj = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009275 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00009276 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009277 sub_obj = PyUnicode_FromObject(substr);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009278 if (!sub_obj) {
9279 Py_DECREF(str_obj);
9280 return -1;
9281 }
Benjamin Peterson4c13a4a2012-01-02 09:07:38 -06009282 if (PyUnicode_READY(sub_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
Benjamin Peterson5e458f52012-01-02 10:12:13 -06009283 Py_DECREF(sub_obj);
Benjamin Peterson29060642009-01-31 22:14:21 +00009284 Py_DECREF(str_obj);
9285 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009286 }
Tim Petersced69f82003-09-16 20:30:58 +00009287
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009288 kind1 = PyUnicode_KIND(str_obj);
9289 kind2 = PyUnicode_KIND(sub_obj);
9290 kind = kind1 > kind2 ? kind1 : kind2;
9291 buf1 = PyUnicode_DATA(str_obj);
9292 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009293 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009294 if (!buf1)
9295 goto onError;
9296 buf2 = PyUnicode_DATA(sub_obj);
9297 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009298 buf2 = _PyUnicode_AsKind(sub_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009299 if (!buf2)
9300 goto onError;
9301 len1 = PyUnicode_GET_LENGTH(str_obj);
9302 len2 = PyUnicode_GET_LENGTH(sub_obj);
9303
9304 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -06009305 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009306 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009307 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
9308 result = asciilib_count(
9309 ((Py_UCS1*)buf1) + start, end - start,
9310 buf2, len2, PY_SSIZE_T_MAX
9311 );
9312 else
9313 result = ucs1lib_count(
9314 ((Py_UCS1*)buf1) + start, end - start,
9315 buf2, len2, PY_SSIZE_T_MAX
9316 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009317 break;
9318 case PyUnicode_2BYTE_KIND:
9319 result = ucs2lib_count(
9320 ((Py_UCS2*)buf1) + start, end - start,
9321 buf2, len2, PY_SSIZE_T_MAX
9322 );
9323 break;
9324 case PyUnicode_4BYTE_KIND:
9325 result = ucs4lib_count(
9326 ((Py_UCS4*)buf1) + start, end - start,
9327 buf2, len2, PY_SSIZE_T_MAX
9328 );
9329 break;
9330 default:
9331 assert(0); result = 0;
9332 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009333
9334 Py_DECREF(sub_obj);
9335 Py_DECREF(str_obj);
9336
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009337 if (kind1 != kind)
9338 PyMem_Free(buf1);
9339 if (kind2 != kind)
9340 PyMem_Free(buf2);
9341
Guido van Rossumd57fd912000-03-10 22:53:23 +00009342 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009343 onError:
9344 Py_DECREF(sub_obj);
9345 Py_DECREF(str_obj);
9346 if (kind1 != kind && buf1)
9347 PyMem_Free(buf1);
9348 if (kind2 != kind && buf2)
9349 PyMem_Free(buf2);
9350 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009351}
9352
Alexander Belopolsky40018472011-02-26 01:02:56 +00009353Py_ssize_t
9354PyUnicode_Find(PyObject *str,
9355 PyObject *sub,
9356 Py_ssize_t start,
9357 Py_ssize_t end,
9358 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009359{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009360 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009361
Guido van Rossumd57fd912000-03-10 22:53:23 +00009362 str = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009363 if (!str)
Benjamin Peterson29060642009-01-31 22:14:21 +00009364 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009365 sub = PyUnicode_FromObject(sub);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009366 if (!sub) {
9367 Py_DECREF(str);
9368 return -2;
9369 }
9370 if (PyUnicode_READY(sub) == -1 || PyUnicode_READY(str) == -1) {
9371 Py_DECREF(sub);
Benjamin Peterson29060642009-01-31 22:14:21 +00009372 Py_DECREF(str);
9373 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009374 }
Tim Petersced69f82003-09-16 20:30:58 +00009375
Victor Stinner794d5672011-10-10 03:21:36 +02009376 result = any_find_slice(direction,
9377 str, sub, start, end
9378 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00009379
Guido van Rossumd57fd912000-03-10 22:53:23 +00009380 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009381 Py_DECREF(sub);
9382
Guido van Rossumd57fd912000-03-10 22:53:23 +00009383 return result;
9384}
9385
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009386Py_ssize_t
9387PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9388 Py_ssize_t start, Py_ssize_t end,
9389 int direction)
9390{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009391 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009392 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009393 if (PyUnicode_READY(str) == -1)
9394 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009395 if (start < 0 || end < 0) {
9396 PyErr_SetString(PyExc_IndexError, "string index out of range");
9397 return -2;
9398 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009399 if (end > PyUnicode_GET_LENGTH(str))
9400 end = PyUnicode_GET_LENGTH(str);
9401 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009402 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9403 kind, end-start, ch, direction);
9404 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009405 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009406 else
9407 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009408}
9409
Alexander Belopolsky40018472011-02-26 01:02:56 +00009410static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009411tailmatch(PyObject *self,
9412 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009413 Py_ssize_t start,
9414 Py_ssize_t end,
9415 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009416{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009417 int kind_self;
9418 int kind_sub;
9419 void *data_self;
9420 void *data_sub;
9421 Py_ssize_t offset;
9422 Py_ssize_t i;
9423 Py_ssize_t end_sub;
9424
9425 if (PyUnicode_READY(self) == -1 ||
9426 PyUnicode_READY(substring) == -1)
9427 return 0;
9428
9429 if (PyUnicode_GET_LENGTH(substring) == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009430 return 1;
9431
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009432 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9433 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009434 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009435 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009436
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009437 kind_self = PyUnicode_KIND(self);
9438 data_self = PyUnicode_DATA(self);
9439 kind_sub = PyUnicode_KIND(substring);
9440 data_sub = PyUnicode_DATA(substring);
9441 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9442
9443 if (direction > 0)
9444 offset = end;
9445 else
9446 offset = start;
9447
9448 if (PyUnicode_READ(kind_self, data_self, offset) ==
9449 PyUnicode_READ(kind_sub, data_sub, 0) &&
9450 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9451 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9452 /* If both are of the same kind, memcmp is sufficient */
9453 if (kind_self == kind_sub) {
9454 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009455 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009456 data_sub,
9457 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009458 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009459 }
9460 /* otherwise we have to compare each character by first accesing it */
9461 else {
9462 /* We do not need to compare 0 and len(substring)-1 because
9463 the if statement above ensured already that they are equal
9464 when we end up here. */
9465 // TODO: honor direction and do a forward or backwards search
9466 for (i = 1; i < end_sub; ++i) {
9467 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9468 PyUnicode_READ(kind_sub, data_sub, i))
9469 return 0;
9470 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009471 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009472 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009473 }
9474
9475 return 0;
9476}
9477
Alexander Belopolsky40018472011-02-26 01:02:56 +00009478Py_ssize_t
9479PyUnicode_Tailmatch(PyObject *str,
9480 PyObject *substr,
9481 Py_ssize_t start,
9482 Py_ssize_t end,
9483 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009484{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009485 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009486
Guido van Rossumd57fd912000-03-10 22:53:23 +00009487 str = PyUnicode_FromObject(str);
9488 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009489 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009490 substr = PyUnicode_FromObject(substr);
9491 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009492 Py_DECREF(str);
9493 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009494 }
Tim Petersced69f82003-09-16 20:30:58 +00009495
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009496 result = tailmatch(str, substr,
Benjamin Peterson29060642009-01-31 22:14:21 +00009497 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009498 Py_DECREF(str);
9499 Py_DECREF(substr);
9500 return result;
9501}
9502
Guido van Rossumd57fd912000-03-10 22:53:23 +00009503/* Apply fixfct filter to the Unicode object self and return a
9504 reference to the modified object */
9505
Alexander Belopolsky40018472011-02-26 01:02:56 +00009506static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009507fixup(PyObject *self,
9508 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009509{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009510 PyObject *u;
9511 Py_UCS4 maxchar_old, maxchar_new = 0;
Victor Stinnereaab6042011-12-11 22:22:39 +01009512 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009513
Victor Stinnerbf6e5602011-12-12 01:53:47 +01009514 u = _PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009515 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009516 return NULL;
Victor Stinner87af4f22011-11-21 23:03:47 +01009517 maxchar_old = PyUnicode_MAX_CHAR_VALUE(u);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009518
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009519 /* fix functions return the new maximum character in a string,
9520 if the kind of the resulting unicode object does not change,
9521 everything is fine. Otherwise we need to change the string kind
9522 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009523 maxchar_new = fixfct(u);
Victor Stinnereaab6042011-12-11 22:22:39 +01009524
9525 if (maxchar_new == 0) {
9526 /* no changes */;
9527 if (PyUnicode_CheckExact(self)) {
9528 Py_DECREF(u);
9529 Py_INCREF(self);
9530 return self;
9531 }
9532 else
9533 return u;
9534 }
9535
9536 if (maxchar_new <= 127)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009537 maxchar_new = 127;
9538 else if (maxchar_new <= 255)
9539 maxchar_new = 255;
9540 else if (maxchar_new <= 65535)
9541 maxchar_new = 65535;
9542 else
Victor Stinner8faf8212011-12-08 22:14:11 +01009543 maxchar_new = MAX_UNICODE;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009544
Victor Stinnereaab6042011-12-11 22:22:39 +01009545 if (maxchar_new == maxchar_old)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009546 return u;
Victor Stinnereaab6042011-12-11 22:22:39 +01009547
9548 /* In case the maximum character changed, we need to
9549 convert the string to the new category. */
9550 v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
9551 if (v == NULL) {
9552 Py_DECREF(u);
9553 return NULL;
9554 }
9555 if (maxchar_new > maxchar_old) {
9556 /* If the maxchar increased so that the kind changed, not all
9557 characters are representable anymore and we need to fix the
9558 string again. This only happens in very few cases. */
9559 copy_characters(v, 0, self, 0, PyUnicode_GET_LENGTH(self));
9560 maxchar_old = fixfct(v);
9561 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009562 }
9563 else {
Victor Stinnereaab6042011-12-11 22:22:39 +01009564 copy_characters(v, 0, u, 0, PyUnicode_GET_LENGTH(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009565 }
Victor Stinnereaab6042011-12-11 22:22:39 +01009566 Py_DECREF(u);
9567 assert(_PyUnicode_CheckConsistency(v, 1));
9568 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009569}
9570
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009571static PyObject *
9572ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009573{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009574 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9575 char *resdata, *data = PyUnicode_DATA(self);
9576 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009577
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009578 res = PyUnicode_New(len, 127);
9579 if (res == NULL)
9580 return NULL;
9581 resdata = PyUnicode_DATA(res);
9582 if (lower)
9583 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009584 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009585 _Py_bytes_upper(resdata, data, len);
9586 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009587}
9588
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009589static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009590handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009591{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009592 Py_ssize_t j;
9593 int final_sigma;
9594 Py_UCS4 c;
9595 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009596
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009597 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9598
9599 where ! is a negation and \p{xxx} is a character with property xxx.
9600 */
9601 for (j = i - 1; j >= 0; j--) {
9602 c = PyUnicode_READ(kind, data, j);
9603 if (!_PyUnicode_IsCaseIgnorable(c))
9604 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009605 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009606 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9607 if (final_sigma) {
9608 for (j = i + 1; j < length; j++) {
9609 c = PyUnicode_READ(kind, data, j);
9610 if (!_PyUnicode_IsCaseIgnorable(c))
9611 break;
9612 }
9613 final_sigma = j == length || !_PyUnicode_IsCased(c);
9614 }
9615 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009616}
9617
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009618static int
9619lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9620 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009621{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009622 /* Obscure special case. */
9623 if (c == 0x3A3) {
9624 mapped[0] = handle_capital_sigma(kind, data, length, i);
9625 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009626 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009627 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009628}
9629
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009630static Py_ssize_t
9631do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009632{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009633 Py_ssize_t i, k = 0;
9634 int n_res, j;
9635 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009636
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009637 c = PyUnicode_READ(kind, data, 0);
9638 n_res = _PyUnicode_ToUpperFull(c, mapped);
9639 for (j = 0; j < n_res; j++) {
9640 if (mapped[j] > *maxchar)
9641 *maxchar = mapped[j];
9642 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009643 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009644 for (i = 1; i < length; i++) {
9645 c = PyUnicode_READ(kind, data, i);
9646 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9647 for (j = 0; j < n_res; j++) {
9648 if (mapped[j] > *maxchar)
9649 *maxchar = mapped[j];
9650 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009651 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009652 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009653 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009654}
9655
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009656static Py_ssize_t
9657do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9658 Py_ssize_t i, k = 0;
9659
9660 for (i = 0; i < length; i++) {
9661 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9662 int n_res, j;
9663 if (Py_UNICODE_ISUPPER(c)) {
9664 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9665 }
9666 else if (Py_UNICODE_ISLOWER(c)) {
9667 n_res = _PyUnicode_ToUpperFull(c, mapped);
9668 }
9669 else {
9670 n_res = 1;
9671 mapped[0] = c;
9672 }
9673 for (j = 0; j < n_res; j++) {
9674 if (mapped[j] > *maxchar)
9675 *maxchar = mapped[j];
9676 res[k++] = mapped[j];
9677 }
9678 }
9679 return k;
9680}
9681
9682static Py_ssize_t
9683do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9684 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009685{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009686 Py_ssize_t i, k = 0;
9687
9688 for (i = 0; i < length; i++) {
9689 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9690 int n_res, j;
9691 if (lower)
9692 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9693 else
9694 n_res = _PyUnicode_ToUpperFull(c, mapped);
9695 for (j = 0; j < n_res; j++) {
9696 if (mapped[j] > *maxchar)
9697 *maxchar = mapped[j];
9698 res[k++] = mapped[j];
9699 }
9700 }
9701 return k;
9702}
9703
9704static Py_ssize_t
9705do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9706{
9707 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9708}
9709
9710static Py_ssize_t
9711do_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9712{
9713 return do_upper_or_lower(kind, data, length, res, maxchar, 1);
9714}
9715
Benjamin Petersone51757f2012-01-12 21:10:29 -05009716static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009717do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9718{
9719 Py_ssize_t i, k = 0;
9720
9721 for (i = 0; i < length; i++) {
9722 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9723 Py_UCS4 mapped[3];
9724 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9725 for (j = 0; j < n_res; j++) {
9726 if (mapped[j] > *maxchar)
9727 *maxchar = mapped[j];
9728 res[k++] = mapped[j];
9729 }
9730 }
9731 return k;
9732}
9733
9734static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009735do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9736{
9737 Py_ssize_t i, k = 0;
9738 int previous_is_cased;
9739
9740 previous_is_cased = 0;
9741 for (i = 0; i < length; i++) {
9742 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9743 Py_UCS4 mapped[3];
9744 int n_res, j;
9745
9746 if (previous_is_cased)
9747 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9748 else
9749 n_res = _PyUnicode_ToTitleFull(c, mapped);
9750
9751 for (j = 0; j < n_res; j++) {
9752 if (mapped[j] > *maxchar)
9753 *maxchar = mapped[j];
9754 res[k++] = mapped[j];
9755 }
9756
9757 previous_is_cased = _PyUnicode_IsCased(c);
9758 }
9759 return k;
9760}
9761
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009762static PyObject *
9763case_operation(PyObject *self,
9764 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9765{
9766 PyObject *res = NULL;
9767 Py_ssize_t length, newlength = 0;
9768 int kind, outkind;
9769 void *data, *outdata;
9770 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9771
Benjamin Petersoneea48462012-01-16 14:28:50 -05009772 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009773
9774 kind = PyUnicode_KIND(self);
9775 data = PyUnicode_DATA(self);
9776 length = PyUnicode_GET_LENGTH(self);
9777 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
9778 if (tmp == NULL)
9779 return PyErr_NoMemory();
9780 newlength = perform(kind, data, length, tmp, &maxchar);
9781 res = PyUnicode_New(newlength, maxchar);
9782 if (res == NULL)
9783 goto leave;
9784 tmpend = tmp + newlength;
9785 outdata = PyUnicode_DATA(res);
9786 outkind = PyUnicode_KIND(res);
9787 switch (outkind) {
9788 case PyUnicode_1BYTE_KIND:
9789 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9790 break;
9791 case PyUnicode_2BYTE_KIND:
9792 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9793 break;
9794 case PyUnicode_4BYTE_KIND:
9795 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9796 break;
9797 default:
9798 assert(0);
9799 break;
9800 }
9801 leave:
9802 PyMem_FREE(tmp);
9803 return res;
9804}
9805
Tim Peters8ce9f162004-08-27 01:49:32 +00009806PyObject *
9807PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009808{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009809 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009810 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009811 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009812 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009813 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9814 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009815 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009816 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009817 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009818 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009819 int use_memcpy;
9820 unsigned char *res_data = NULL, *sep_data = NULL;
9821 PyObject *last_obj;
9822 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009823
Tim Peters05eba1f2004-08-27 21:32:02 +00009824 fseq = PySequence_Fast(seq, "");
9825 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009826 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009827 }
9828
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009829 /* NOTE: the following code can't call back into Python code,
9830 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009831 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009832
Tim Peters05eba1f2004-08-27 21:32:02 +00009833 seqlen = PySequence_Fast_GET_SIZE(fseq);
9834 /* If empty sequence, return u"". */
9835 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009836 Py_DECREF(fseq);
9837 Py_INCREF(unicode_empty);
9838 res = unicode_empty;
9839 return res;
Tim Peters05eba1f2004-08-27 21:32:02 +00009840 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009841
Tim Peters05eba1f2004-08-27 21:32:02 +00009842 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009843 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009844 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009845 if (seqlen == 1) {
9846 if (PyUnicode_CheckExact(items[0])) {
9847 res = items[0];
9848 Py_INCREF(res);
9849 Py_DECREF(fseq);
9850 return res;
9851 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009852 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009853 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009854 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009855 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009856 /* Set up sep and seplen */
9857 if (separator == NULL) {
9858 /* fall back to a blank space separator */
9859 sep = PyUnicode_FromOrdinal(' ');
9860 if (!sep)
9861 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009862 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009863 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009864 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009865 else {
9866 if (!PyUnicode_Check(separator)) {
9867 PyErr_Format(PyExc_TypeError,
9868 "separator: expected str instance,"
9869 " %.80s found",
9870 Py_TYPE(separator)->tp_name);
9871 goto onError;
9872 }
9873 if (PyUnicode_READY(separator))
9874 goto onError;
9875 sep = separator;
9876 seplen = PyUnicode_GET_LENGTH(separator);
9877 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9878 /* inc refcount to keep this code path symmetric with the
9879 above case of a blank separator */
9880 Py_INCREF(sep);
9881 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009882 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009883 }
9884
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009885 /* There are at least two things to join, or else we have a subclass
9886 * of str in the sequence.
9887 * Do a pre-pass to figure out the total amount of space we'll
9888 * need (sz), and see whether all argument are strings.
9889 */
9890 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009891#ifdef Py_DEBUG
9892 use_memcpy = 0;
9893#else
9894 use_memcpy = 1;
9895#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009896 for (i = 0; i < seqlen; i++) {
9897 const Py_ssize_t old_sz = sz;
9898 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009899 if (!PyUnicode_Check(item)) {
9900 PyErr_Format(PyExc_TypeError,
9901 "sequence item %zd: expected str instance,"
9902 " %.80s found",
9903 i, Py_TYPE(item)->tp_name);
9904 goto onError;
9905 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009906 if (PyUnicode_READY(item) == -1)
9907 goto onError;
9908 sz += PyUnicode_GET_LENGTH(item);
9909 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009910 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009911 if (i != 0)
9912 sz += seplen;
9913 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9914 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009915 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009916 goto onError;
9917 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009918 if (use_memcpy && last_obj != NULL) {
9919 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9920 use_memcpy = 0;
9921 }
9922 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009923 }
Tim Petersced69f82003-09-16 20:30:58 +00009924
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009925 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009926 if (res == NULL)
9927 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009928
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009929 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009930#ifdef Py_DEBUG
9931 use_memcpy = 0;
9932#else
9933 if (use_memcpy) {
9934 res_data = PyUnicode_1BYTE_DATA(res);
9935 kind = PyUnicode_KIND(res);
9936 if (seplen != 0)
9937 sep_data = PyUnicode_1BYTE_DATA(sep);
9938 }
9939#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009940 for (i = 0, res_offset = 0; i < seqlen; ++i) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009941 Py_ssize_t itemlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009942 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009943 /* Copy item, and maybe the separator. */
Victor Stinner9ce5a832011-10-03 23:36:02 +02009944 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009945 if (use_memcpy) {
9946 Py_MEMCPY(res_data,
9947 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009948 kind * seplen);
9949 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009950 }
9951 else {
9952 copy_characters(res, res_offset, sep, 0, seplen);
9953 res_offset += seplen;
9954 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009955 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009956 itemlen = PyUnicode_GET_LENGTH(item);
9957 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009958 if (use_memcpy) {
9959 Py_MEMCPY(res_data,
9960 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009961 kind * itemlen);
9962 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009963 }
9964 else {
9965 copy_characters(res, res_offset, item, 0, itemlen);
9966 res_offset += itemlen;
9967 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009968 }
Tim Peters05eba1f2004-08-27 21:32:02 +00009969 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009970 if (use_memcpy)
9971 assert(res_data == PyUnicode_1BYTE_DATA(res)
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009972 + kind * PyUnicode_GET_LENGTH(res));
Victor Stinnerdd077322011-10-07 17:02:31 +02009973 else
9974 assert(res_offset == PyUnicode_GET_LENGTH(res));
Tim Peters8ce9f162004-08-27 01:49:32 +00009975
Tim Peters05eba1f2004-08-27 21:32:02 +00009976 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009977 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009978 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009979 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009980
Benjamin Peterson29060642009-01-31 22:14:21 +00009981 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00009982 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009983 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009984 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009985 return NULL;
9986}
9987
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009988#define FILL(kind, data, value, start, length) \
9989 do { \
9990 Py_ssize_t i_ = 0; \
9991 assert(kind != PyUnicode_WCHAR_KIND); \
9992 switch ((kind)) { \
9993 case PyUnicode_1BYTE_KIND: { \
9994 unsigned char * to_ = (unsigned char *)((data)) + (start); \
9995 memset(to_, (unsigned char)value, length); \
9996 break; \
9997 } \
9998 case PyUnicode_2BYTE_KIND: { \
9999 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
10000 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
10001 break; \
10002 } \
Benjamin Petersone157cf12012-01-01 15:56:20 -060010003 case PyUnicode_4BYTE_KIND: { \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010004 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
10005 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
10006 break; \
Benjamin Petersone157cf12012-01-01 15:56:20 -060010007 default: assert(0); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010008 } \
10009 } \
10010 } while (0)
10011
Victor Stinner3fe55312012-01-04 00:33:50 +010010012Py_ssize_t
10013PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10014 Py_UCS4 fill_char)
10015{
10016 Py_ssize_t maxlen;
10017 enum PyUnicode_Kind kind;
10018 void *data;
10019
10020 if (!PyUnicode_Check(unicode)) {
10021 PyErr_BadInternalCall();
10022 return -1;
10023 }
10024 if (PyUnicode_READY(unicode) == -1)
10025 return -1;
10026 if (unicode_check_modifiable(unicode))
10027 return -1;
10028
10029 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
10030 PyErr_SetString(PyExc_ValueError,
10031 "fill character is bigger than "
10032 "the string maximum character");
10033 return -1;
10034 }
10035
10036 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
10037 length = Py_MIN(maxlen, length);
10038 if (length <= 0)
10039 return 0;
10040
10041 kind = PyUnicode_KIND(unicode);
10042 data = PyUnicode_DATA(unicode);
10043 FILL(kind, data, fill_char, start, length);
10044 return length;
10045}
10046
Victor Stinner9310abb2011-10-05 00:59:23 +020010047static PyObject *
10048pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010049 Py_ssize_t left,
10050 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010051 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010052{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010053 PyObject *u;
10054 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010055 int kind;
10056 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010057
10058 if (left < 0)
10059 left = 0;
10060 if (right < 0)
10061 right = 0;
10062
Victor Stinnerc4b49542011-12-11 22:44:26 +010010063 if (left == 0 && right == 0)
10064 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010065
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010066 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
10067 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +000010068 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
10069 return NULL;
10070 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010071 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
10072 if (fill > maxchar)
10073 maxchar = fill;
10074 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010075 if (!u)
10076 return NULL;
10077
10078 kind = PyUnicode_KIND(u);
10079 data = PyUnicode_DATA(u);
10080 if (left)
10081 FILL(kind, data, fill, 0, left);
10082 if (right)
10083 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010084 copy_characters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010085 assert(_PyUnicode_CheckConsistency(u, 1));
10086 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010087}
10088
Alexander Belopolsky40018472011-02-26 01:02:56 +000010089PyObject *
10090PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010091{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010092 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010093
10094 string = PyUnicode_FromObject(string);
Benjamin Peterson22a29702012-01-02 09:00:30 -060010095 if (string == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010096 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060010097 if (PyUnicode_READY(string) == -1) {
10098 Py_DECREF(string);
10099 return NULL;
10100 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010101
Benjamin Petersonead6b532011-12-20 17:23:42 -060010102 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010103 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010104 if (PyUnicode_IS_ASCII(string))
10105 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010106 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010107 PyUnicode_GET_LENGTH(string), keepends);
10108 else
10109 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010110 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010111 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010112 break;
10113 case PyUnicode_2BYTE_KIND:
10114 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010115 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010116 PyUnicode_GET_LENGTH(string), keepends);
10117 break;
10118 case PyUnicode_4BYTE_KIND:
10119 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010120 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010121 PyUnicode_GET_LENGTH(string), keepends);
10122 break;
10123 default:
10124 assert(0);
10125 list = 0;
10126 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010127 Py_DECREF(string);
10128 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010129}
10130
Alexander Belopolsky40018472011-02-26 01:02:56 +000010131static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010132split(PyObject *self,
10133 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010134 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010135{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010136 int kind1, kind2, kind;
10137 void *buf1, *buf2;
10138 Py_ssize_t len1, len2;
10139 PyObject* out;
10140
Guido van Rossumd57fd912000-03-10 22:53:23 +000010141 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010142 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010143
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010144 if (PyUnicode_READY(self) == -1)
10145 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010146
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010147 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010148 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010149 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010150 if (PyUnicode_IS_ASCII(self))
10151 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010152 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010153 PyUnicode_GET_LENGTH(self), maxcount
10154 );
10155 else
10156 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010157 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010158 PyUnicode_GET_LENGTH(self), maxcount
10159 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010160 case PyUnicode_2BYTE_KIND:
10161 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010162 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010163 PyUnicode_GET_LENGTH(self), maxcount
10164 );
10165 case PyUnicode_4BYTE_KIND:
10166 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010167 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010168 PyUnicode_GET_LENGTH(self), maxcount
10169 );
10170 default:
10171 assert(0);
10172 return NULL;
10173 }
10174
10175 if (PyUnicode_READY(substring) == -1)
10176 return NULL;
10177
10178 kind1 = PyUnicode_KIND(self);
10179 kind2 = PyUnicode_KIND(substring);
10180 kind = kind1 > kind2 ? kind1 : kind2;
10181 buf1 = PyUnicode_DATA(self);
10182 buf2 = PyUnicode_DATA(substring);
10183 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010184 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010185 if (!buf1)
10186 return NULL;
10187 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010188 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010189 if (!buf2) {
10190 if (kind1 != kind) PyMem_Free(buf1);
10191 return NULL;
10192 }
10193 len1 = PyUnicode_GET_LENGTH(self);
10194 len2 = PyUnicode_GET_LENGTH(substring);
10195
Benjamin Petersonead6b532011-12-20 17:23:42 -060010196 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010197 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010198 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10199 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010200 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010201 else
10202 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010203 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010204 break;
10205 case PyUnicode_2BYTE_KIND:
10206 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010207 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010208 break;
10209 case PyUnicode_4BYTE_KIND:
10210 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010211 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010212 break;
10213 default:
10214 out = NULL;
10215 }
10216 if (kind1 != kind)
10217 PyMem_Free(buf1);
10218 if (kind2 != kind)
10219 PyMem_Free(buf2);
10220 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010221}
10222
Alexander Belopolsky40018472011-02-26 01:02:56 +000010223static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010224rsplit(PyObject *self,
10225 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010226 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010227{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010228 int kind1, kind2, kind;
10229 void *buf1, *buf2;
10230 Py_ssize_t len1, len2;
10231 PyObject* out;
10232
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010233 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010234 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010235
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010236 if (PyUnicode_READY(self) == -1)
10237 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010238
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010239 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010240 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010241 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010242 if (PyUnicode_IS_ASCII(self))
10243 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010244 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010245 PyUnicode_GET_LENGTH(self), maxcount
10246 );
10247 else
10248 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010249 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010250 PyUnicode_GET_LENGTH(self), maxcount
10251 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010252 case PyUnicode_2BYTE_KIND:
10253 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010254 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010255 PyUnicode_GET_LENGTH(self), maxcount
10256 );
10257 case PyUnicode_4BYTE_KIND:
10258 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010259 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010260 PyUnicode_GET_LENGTH(self), maxcount
10261 );
10262 default:
10263 assert(0);
10264 return NULL;
10265 }
10266
10267 if (PyUnicode_READY(substring) == -1)
10268 return NULL;
10269
10270 kind1 = PyUnicode_KIND(self);
10271 kind2 = PyUnicode_KIND(substring);
10272 kind = kind1 > kind2 ? kind1 : kind2;
10273 buf1 = PyUnicode_DATA(self);
10274 buf2 = PyUnicode_DATA(substring);
10275 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010276 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010277 if (!buf1)
10278 return NULL;
10279 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010280 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010281 if (!buf2) {
10282 if (kind1 != kind) PyMem_Free(buf1);
10283 return NULL;
10284 }
10285 len1 = PyUnicode_GET_LENGTH(self);
10286 len2 = PyUnicode_GET_LENGTH(substring);
10287
Benjamin Petersonead6b532011-12-20 17:23:42 -060010288 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010289 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010290 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10291 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010292 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010293 else
10294 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010295 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010296 break;
10297 case PyUnicode_2BYTE_KIND:
10298 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010299 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010300 break;
10301 case PyUnicode_4BYTE_KIND:
10302 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010303 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010304 break;
10305 default:
10306 out = NULL;
10307 }
10308 if (kind1 != kind)
10309 PyMem_Free(buf1);
10310 if (kind2 != kind)
10311 PyMem_Free(buf2);
10312 return out;
10313}
10314
10315static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010316anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10317 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010318{
Benjamin Petersonead6b532011-12-20 17:23:42 -060010319 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010320 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010321 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10322 return asciilib_find(buf1, len1, buf2, len2, offset);
10323 else
10324 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010325 case PyUnicode_2BYTE_KIND:
10326 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10327 case PyUnicode_4BYTE_KIND:
10328 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10329 }
10330 assert(0);
10331 return -1;
10332}
10333
10334static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010335anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10336 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010337{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -060010338 switch (kind) {
10339 case PyUnicode_1BYTE_KIND:
10340 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10341 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10342 else
10343 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10344 case PyUnicode_2BYTE_KIND:
10345 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10346 case PyUnicode_4BYTE_KIND:
10347 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10348 }
10349 assert(0);
10350 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010351}
10352
Alexander Belopolsky40018472011-02-26 01:02:56 +000010353static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010354replace(PyObject *self, PyObject *str1,
10355 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010356{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010357 PyObject *u;
10358 char *sbuf = PyUnicode_DATA(self);
10359 char *buf1 = PyUnicode_DATA(str1);
10360 char *buf2 = PyUnicode_DATA(str2);
10361 int srelease = 0, release1 = 0, release2 = 0;
10362 int skind = PyUnicode_KIND(self);
10363 int kind1 = PyUnicode_KIND(str1);
10364 int kind2 = PyUnicode_KIND(str2);
10365 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10366 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10367 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010368 int mayshrink;
10369 Py_UCS4 maxchar, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010370
10371 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010372 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010373 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010374 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010375
Victor Stinner59de0ee2011-10-07 10:01:28 +020010376 if (str1 == str2)
10377 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010378 if (skind < kind1)
10379 /* substring too wide to be present */
10380 goto nothing;
10381
Victor Stinner49a0a212011-10-12 23:46:10 +020010382 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
10383 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10384 /* Replacing str1 with str2 may cause a maxchar reduction in the
10385 result string. */
10386 mayshrink = (maxchar_str2 < maxchar);
10387 maxchar = Py_MAX(maxchar, maxchar_str2);
10388
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010389 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010390 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010391 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010392 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010393 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010394 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010395 Py_UCS4 u1, u2;
10396 int rkind;
Victor Stinnerf6441102011-12-18 02:43:08 +010010397 Py_ssize_t index, pos;
10398 char *src;
10399
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010400 u1 = PyUnicode_READ_CHAR(str1, 0);
Victor Stinnerf6441102011-12-18 02:43:08 +010010401 pos = findchar(sbuf, PyUnicode_KIND(self), slen, u1, 1);
10402 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010403 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010404 u2 = PyUnicode_READ_CHAR(str2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010405 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010406 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010407 goto error;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010408 copy_characters(u, 0, self, 0, slen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010409 rkind = PyUnicode_KIND(u);
Victor Stinnerf6441102011-12-18 02:43:08 +010010410
10411 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), pos, u2);
10412 index = 0;
10413 src = sbuf;
10414 while (--maxcount)
10415 {
10416 pos++;
10417 src += pos * PyUnicode_KIND(self);
10418 slen -= pos;
10419 index += pos;
10420 pos = findchar(src, PyUnicode_KIND(self), slen, u1, 1);
10421 if (pos < 0)
10422 break;
10423 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), index + pos, u2);
10424 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010425 }
10426 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010427 int rkind = skind;
10428 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010429 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010430
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010431 if (kind1 < rkind) {
10432 /* widen substring */
10433 buf1 = _PyUnicode_AsKind(str1, rkind);
10434 if (!buf1) goto error;
10435 release1 = 1;
10436 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010437 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010438 if (i < 0)
10439 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010440 if (rkind > kind2) {
10441 /* widen replacement */
10442 buf2 = _PyUnicode_AsKind(str2, rkind);
10443 if (!buf2) goto error;
10444 release2 = 1;
10445 }
10446 else if (rkind < kind2) {
10447 /* widen self and buf1 */
10448 rkind = kind2;
10449 if (release1) PyMem_Free(buf1);
10450 sbuf = _PyUnicode_AsKind(self, rkind);
10451 if (!sbuf) goto error;
10452 srelease = 1;
10453 buf1 = _PyUnicode_AsKind(str1, rkind);
10454 if (!buf1) goto error;
10455 release1 = 1;
10456 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010457 u = PyUnicode_New(slen, maxchar);
10458 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010459 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010460 assert(PyUnicode_KIND(u) == rkind);
10461 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010462
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010463 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010464 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010465 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010466 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010467 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010468 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010469
10470 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010471 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010472 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010473 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010474 if (i == -1)
10475 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010476 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010477 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010478 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010479 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010480 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010481 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010482 }
10483 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010484 Py_ssize_t n, i, j, ires;
10485 Py_ssize_t product, new_size;
10486 int rkind = skind;
10487 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010488
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010489 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010490 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010491 buf1 = _PyUnicode_AsKind(str1, rkind);
10492 if (!buf1) goto error;
10493 release1 = 1;
10494 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010495 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010496 if (n == 0)
10497 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010498 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010499 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010500 buf2 = _PyUnicode_AsKind(str2, rkind);
10501 if (!buf2) goto error;
10502 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010503 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010504 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010505 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010506 rkind = kind2;
10507 sbuf = _PyUnicode_AsKind(self, rkind);
10508 if (!sbuf) goto error;
10509 srelease = 1;
10510 if (release1) PyMem_Free(buf1);
10511 buf1 = _PyUnicode_AsKind(str1, rkind);
10512 if (!buf1) goto error;
10513 release1 = 1;
10514 }
10515 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10516 PyUnicode_GET_LENGTH(str1))); */
10517 product = n * (len2-len1);
10518 if ((product / (len2-len1)) != n) {
10519 PyErr_SetString(PyExc_OverflowError,
10520 "replace string is too long");
10521 goto error;
10522 }
10523 new_size = slen + product;
Victor Stinner49a0a212011-10-12 23:46:10 +020010524 if (new_size == 0) {
10525 Py_INCREF(unicode_empty);
10526 u = unicode_empty;
10527 goto done;
10528 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010529 if (new_size < 0 || new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
10530 PyErr_SetString(PyExc_OverflowError,
10531 "replace string is too long");
10532 goto error;
10533 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010534 u = PyUnicode_New(new_size, maxchar);
10535 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010536 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010537 assert(PyUnicode_KIND(u) == rkind);
10538 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010539 ires = i = 0;
10540 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010541 while (n-- > 0) {
10542 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010543 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010544 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010545 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010546 if (j == -1)
10547 break;
10548 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010549 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010550 memcpy(res + rkind * ires,
10551 sbuf + rkind * i,
10552 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010553 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010554 }
10555 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010556 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010557 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010558 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010559 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010560 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010561 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010562 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010563 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010564 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010565 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010566 memcpy(res + rkind * ires,
10567 sbuf + rkind * i,
10568 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010569 }
10570 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010571 /* interleave */
10572 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010573 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010574 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010575 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010576 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010577 if (--n <= 0)
10578 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010579 memcpy(res + rkind * ires,
10580 sbuf + rkind * i,
10581 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010582 ires++;
10583 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010584 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010585 memcpy(res + rkind * ires,
10586 sbuf + rkind * i,
10587 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010588 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010589 }
10590
10591 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010592 unicode_adjust_maxchar(&u);
10593 if (u == NULL)
10594 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010595 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010596
10597 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010598 if (srelease)
10599 PyMem_FREE(sbuf);
10600 if (release1)
10601 PyMem_FREE(buf1);
10602 if (release2)
10603 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010604 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010605 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010606
Benjamin Peterson29060642009-01-31 22:14:21 +000010607 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010608 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010609 if (srelease)
10610 PyMem_FREE(sbuf);
10611 if (release1)
10612 PyMem_FREE(buf1);
10613 if (release2)
10614 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010615 return unicode_result_unchanged(self);
10616
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010617 error:
10618 if (srelease && sbuf)
10619 PyMem_FREE(sbuf);
10620 if (release1 && buf1)
10621 PyMem_FREE(buf1);
10622 if (release2 && buf2)
10623 PyMem_FREE(buf2);
10624 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010625}
10626
10627/* --- Unicode Object Methods --------------------------------------------- */
10628
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010629PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010630 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010631\n\
10632Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010633characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010634
10635static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010636unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010637{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010638 if (PyUnicode_READY(self) == -1)
10639 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010640 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010641}
10642
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010643PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010644 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010645\n\
10646Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010647have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010648
10649static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010650unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010651{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010652 if (PyUnicode_READY(self) == -1)
10653 return NULL;
10654 if (PyUnicode_GET_LENGTH(self) == 0)
10655 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010656 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010657}
10658
Benjamin Petersond5890c82012-01-14 13:23:30 -050010659PyDoc_STRVAR(casefold__doc__,
10660 "S.casefold() -> str\n\
10661\n\
10662Return a version of S suitable for caseless comparisons.");
10663
10664static PyObject *
10665unicode_casefold(PyObject *self)
10666{
10667 if (PyUnicode_READY(self) == -1)
10668 return NULL;
10669 if (PyUnicode_IS_ASCII(self))
10670 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010671 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010672}
10673
10674
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010675/* Argument converter. Coerces to a single unicode character */
10676
10677static int
10678convert_uc(PyObject *obj, void *addr)
10679{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010680 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010681 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010682
Benjamin Peterson14339b62009-01-31 16:36:08 +000010683 uniobj = PyUnicode_FromObject(obj);
10684 if (uniobj == NULL) {
10685 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010686 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010687 return 0;
10688 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010689 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010690 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010691 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010692 Py_DECREF(uniobj);
10693 return 0;
10694 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010695 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010696 Py_DECREF(uniobj);
10697 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010698}
10699
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010700PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010701 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010702\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010703Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010704done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010705
10706static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010707unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010708{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010709 Py_ssize_t marg, left;
10710 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010711 Py_UCS4 fillchar = ' ';
10712
Victor Stinnere9a29352011-10-01 02:14:59 +020010713 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010714 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010715
Benjamin Petersonbac79492012-01-14 13:34:47 -050010716 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010717 return NULL;
10718
Victor Stinnerc4b49542011-12-11 22:44:26 +010010719 if (PyUnicode_GET_LENGTH(self) >= width)
10720 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010721
Victor Stinnerc4b49542011-12-11 22:44:26 +010010722 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010723 left = marg / 2 + (marg & width & 1);
10724
Victor Stinner9310abb2011-10-05 00:59:23 +020010725 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010726}
10727
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010728/* This function assumes that str1 and str2 are readied by the caller. */
10729
Marc-André Lemburge5034372000-08-08 08:04:29 +000010730static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010731unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010732{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010733 int kind1, kind2;
10734 void *data1, *data2;
10735 Py_ssize_t len1, len2, i;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010736
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010737 kind1 = PyUnicode_KIND(str1);
10738 kind2 = PyUnicode_KIND(str2);
10739 data1 = PyUnicode_DATA(str1);
10740 data2 = PyUnicode_DATA(str2);
10741 len1 = PyUnicode_GET_LENGTH(str1);
10742 len2 = PyUnicode_GET_LENGTH(str2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010743
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010744 for (i = 0; i < len1 && i < len2; ++i) {
10745 Py_UCS4 c1, c2;
10746 c1 = PyUnicode_READ(kind1, data1, i);
10747 c2 = PyUnicode_READ(kind2, data2, i);
Fredrik Lundh45714e92001-06-26 16:39:36 +000010748
10749 if (c1 != c2)
10750 return (c1 < c2) ? -1 : 1;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010751 }
10752
10753 return (len1 < len2) ? -1 : (len1 != len2);
10754}
10755
Alexander Belopolsky40018472011-02-26 01:02:56 +000010756int
10757PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010758{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010759 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10760 if (PyUnicode_READY(left) == -1 ||
10761 PyUnicode_READY(right) == -1)
10762 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010763 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010764 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010765 PyErr_Format(PyExc_TypeError,
10766 "Can't compare %.100s and %.100s",
10767 left->ob_type->tp_name,
10768 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010769 return -1;
10770}
10771
Martin v. Löwis5b222132007-06-10 09:51:05 +000010772int
10773PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10774{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010775 Py_ssize_t i;
10776 int kind;
10777 void *data;
10778 Py_UCS4 chr;
10779
Victor Stinner910337b2011-10-03 03:20:16 +020010780 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010781 if (PyUnicode_READY(uni) == -1)
10782 return -1;
10783 kind = PyUnicode_KIND(uni);
10784 data = PyUnicode_DATA(uni);
Martin v. Löwis5b222132007-06-10 09:51:05 +000010785 /* Compare Unicode string and source character set string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010786 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
10787 if (chr != str[i])
10788 return (chr < (unsigned char)(str[i])) ? -1 : 1;
Benjamin Peterson8667a9b2010-01-09 21:45:28 +000010789 /* This check keeps Python strings that end in '\0' from comparing equal
10790 to C strings identical up to that point. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010791 if (PyUnicode_GET_LENGTH(uni) != i || chr)
Benjamin Peterson29060642009-01-31 22:14:21 +000010792 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010793 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +000010794 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010795 return 0;
10796}
10797
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010798
Benjamin Peterson29060642009-01-31 22:14:21 +000010799#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010800 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010801
Alexander Belopolsky40018472011-02-26 01:02:56 +000010802PyObject *
10803PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010804{
10805 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010806
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010807 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10808 PyObject *v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010809 if (PyUnicode_READY(left) == -1 ||
10810 PyUnicode_READY(right) == -1)
10811 return NULL;
10812 if (PyUnicode_GET_LENGTH(left) != PyUnicode_GET_LENGTH(right) ||
10813 PyUnicode_KIND(left) != PyUnicode_KIND(right)) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010814 if (op == Py_EQ) {
10815 Py_INCREF(Py_False);
10816 return Py_False;
10817 }
10818 if (op == Py_NE) {
10819 Py_INCREF(Py_True);
10820 return Py_True;
10821 }
10822 }
10823 if (left == right)
10824 result = 0;
10825 else
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010826 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010827
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010828 /* Convert the return value to a Boolean */
10829 switch (op) {
10830 case Py_EQ:
10831 v = TEST_COND(result == 0);
10832 break;
10833 case Py_NE:
10834 v = TEST_COND(result != 0);
10835 break;
10836 case Py_LE:
10837 v = TEST_COND(result <= 0);
10838 break;
10839 case Py_GE:
10840 v = TEST_COND(result >= 0);
10841 break;
10842 case Py_LT:
10843 v = TEST_COND(result == -1);
10844 break;
10845 case Py_GT:
10846 v = TEST_COND(result == 1);
10847 break;
10848 default:
10849 PyErr_BadArgument();
10850 return NULL;
10851 }
10852 Py_INCREF(v);
10853 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010854 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010855
Brian Curtindfc80e32011-08-10 20:28:54 -050010856 Py_RETURN_NOTIMPLEMENTED;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010857}
10858
Alexander Belopolsky40018472011-02-26 01:02:56 +000010859int
10860PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010861{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010862 PyObject *str, *sub;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010863 int kind1, kind2, kind;
10864 void *buf1, *buf2;
10865 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010866 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010867
10868 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010869 sub = PyUnicode_FromObject(element);
10870 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010871 PyErr_Format(PyExc_TypeError,
10872 "'in <string>' requires string as left operand, not %s",
10873 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010874 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010875 }
10876
Thomas Wouters477c8d52006-05-27 19:21:47 +000010877 str = PyUnicode_FromObject(container);
Benjamin Peterson22a29702012-01-02 09:00:30 -060010878 if (!str) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010879 Py_DECREF(sub);
10880 return -1;
10881 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060010882 if (PyUnicode_READY(sub) == -1 || PyUnicode_READY(str) == -1) {
10883 Py_DECREF(sub);
10884 Py_DECREF(str);
10885 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010886
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010887 kind1 = PyUnicode_KIND(str);
10888 kind2 = PyUnicode_KIND(sub);
10889 kind = kind1 > kind2 ? kind1 : kind2;
10890 buf1 = PyUnicode_DATA(str);
10891 buf2 = PyUnicode_DATA(sub);
10892 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010893 buf1 = _PyUnicode_AsKind(str, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010894 if (!buf1) {
10895 Py_DECREF(sub);
10896 return -1;
10897 }
10898 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010899 buf2 = _PyUnicode_AsKind(sub, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010900 if (!buf2) {
10901 Py_DECREF(sub);
10902 if (kind1 != kind) PyMem_Free(buf1);
10903 return -1;
10904 }
10905 len1 = PyUnicode_GET_LENGTH(str);
10906 len2 = PyUnicode_GET_LENGTH(sub);
10907
Benjamin Petersonead6b532011-12-20 17:23:42 -060010908 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010909 case PyUnicode_1BYTE_KIND:
10910 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10911 break;
10912 case PyUnicode_2BYTE_KIND:
10913 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
10914 break;
10915 case PyUnicode_4BYTE_KIND:
10916 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
10917 break;
10918 default:
10919 result = -1;
10920 assert(0);
10921 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010922
10923 Py_DECREF(str);
10924 Py_DECREF(sub);
10925
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010926 if (kind1 != kind)
10927 PyMem_Free(buf1);
10928 if (kind2 != kind)
10929 PyMem_Free(buf2);
10930
Guido van Rossum403d68b2000-03-13 15:55:09 +000010931 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010932}
10933
Guido van Rossumd57fd912000-03-10 22:53:23 +000010934/* Concat to string or Unicode object giving a new Unicode object. */
10935
Alexander Belopolsky40018472011-02-26 01:02:56 +000010936PyObject *
10937PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010938{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010939 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020010940 Py_UCS4 maxchar, maxchar2;
Victor Stinner488fa492011-12-12 00:01:39 +010010941 Py_ssize_t u_len, v_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010942
10943 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010944 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010945 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010946 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010947 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010948 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010949 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010950
10951 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020010952 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010953 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010954 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010955 }
Victor Stinnera464fc12011-10-02 20:39:30 +020010956 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010957 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010958 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010959 }
10960
Victor Stinner488fa492011-12-12 00:01:39 +010010961 u_len = PyUnicode_GET_LENGTH(u);
10962 v_len = PyUnicode_GET_LENGTH(v);
10963 if (u_len > PY_SSIZE_T_MAX - v_len) {
10964 PyErr_SetString(PyExc_OverflowError,
10965 "strings are too large to concat");
10966 goto onError;
10967 }
10968 new_len = u_len + v_len;
10969
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010970 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020010971 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
10972 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010973
Guido van Rossumd57fd912000-03-10 22:53:23 +000010974 /* Concat the two Unicode strings */
Victor Stinner488fa492011-12-12 00:01:39 +010010975 w = PyUnicode_New(new_len, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010976 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010977 goto onError;
Victor Stinner488fa492011-12-12 00:01:39 +010010978 copy_characters(w, 0, u, 0, u_len);
10979 copy_characters(w, u_len, v, 0, v_len);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010980 Py_DECREF(u);
10981 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010982 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010983 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010984
Benjamin Peterson29060642009-01-31 22:14:21 +000010985 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010986 Py_XDECREF(u);
10987 Py_XDECREF(v);
10988 return NULL;
10989}
10990
Walter Dörwald1ab83302007-05-18 17:15:44 +000010991void
Victor Stinner23e56682011-10-03 03:54:37 +020010992PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000010993{
Victor Stinner23e56682011-10-03 03:54:37 +020010994 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010010995 Py_UCS4 maxchar, maxchar2;
10996 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020010997
10998 if (p_left == NULL) {
10999 if (!PyErr_Occurred())
11000 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000011001 return;
11002 }
Victor Stinner23e56682011-10-03 03:54:37 +020011003 left = *p_left;
11004 if (right == NULL || !PyUnicode_Check(left)) {
11005 if (!PyErr_Occurred())
11006 PyErr_BadInternalCall();
11007 goto error;
11008 }
11009
Benjamin Petersonbac79492012-01-14 13:34:47 -050011010 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011011 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050011012 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011013 goto error;
11014
Victor Stinner488fa492011-12-12 00:01:39 +010011015 /* Shortcuts */
11016 if (left == unicode_empty) {
11017 Py_DECREF(left);
11018 Py_INCREF(right);
11019 *p_left = right;
11020 return;
11021 }
11022 if (right == unicode_empty)
11023 return;
11024
11025 left_len = PyUnicode_GET_LENGTH(left);
11026 right_len = PyUnicode_GET_LENGTH(right);
11027 if (left_len > PY_SSIZE_T_MAX - right_len) {
11028 PyErr_SetString(PyExc_OverflowError,
11029 "strings are too large to concat");
11030 goto error;
11031 }
11032 new_len = left_len + right_len;
11033
11034 if (unicode_modifiable(left)
11035 && PyUnicode_CheckExact(right)
11036 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020011037 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
11038 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020011039 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020011040 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010011041 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
11042 {
11043 /* append inplace */
11044 if (unicode_resize(p_left, new_len) != 0) {
11045 /* XXX if _PyUnicode_Resize() fails, 'left' has been
11046 * deallocated so it cannot be put back into
11047 * 'variable'. The MemoryError is raised when there
11048 * is no value in 'variable', which might (very
11049 * remotely) be a cause of incompatibilities.
11050 */
11051 goto error;
Victor Stinner23e56682011-10-03 03:54:37 +020011052 }
Victor Stinner488fa492011-12-12 00:01:39 +010011053 /* copy 'right' into the newly allocated area of 'left' */
11054 copy_characters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020011055 }
Victor Stinner488fa492011-12-12 00:01:39 +010011056 else {
11057 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11058 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
11059 maxchar = Py_MAX(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020011060
Victor Stinner488fa492011-12-12 00:01:39 +010011061 /* Concat the two Unicode strings */
11062 res = PyUnicode_New(new_len, maxchar);
11063 if (res == NULL)
11064 goto error;
11065 copy_characters(res, 0, left, 0, left_len);
11066 copy_characters(res, left_len, right, 0, right_len);
11067 Py_DECREF(left);
11068 *p_left = res;
11069 }
11070 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020011071 return;
11072
11073error:
Victor Stinner488fa492011-12-12 00:01:39 +010011074 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011075}
11076
11077void
11078PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
11079{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011080 PyUnicode_Append(pleft, right);
11081 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011082}
11083
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011084PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011085 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011086\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011087Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011088string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011089interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011090
11091static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011092unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011093{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011094 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011095 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011096 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011097 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011098 int kind1, kind2, kind;
11099 void *buf1, *buf2;
11100 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011101
Jesus Ceaac451502011-04-20 17:09:23 +020011102 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
11103 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000011104 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000011105
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011106 kind1 = PyUnicode_KIND(self);
11107 kind2 = PyUnicode_KIND(substring);
11108 kind = kind1 > kind2 ? kind1 : kind2;
11109 buf1 = PyUnicode_DATA(self);
11110 buf2 = PyUnicode_DATA(substring);
11111 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010011112 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011113 if (!buf1) {
11114 Py_DECREF(substring);
11115 return NULL;
11116 }
11117 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010011118 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011119 if (!buf2) {
11120 Py_DECREF(substring);
11121 if (kind1 != kind) PyMem_Free(buf1);
11122 return NULL;
11123 }
11124 len1 = PyUnicode_GET_LENGTH(self);
11125 len2 = PyUnicode_GET_LENGTH(substring);
11126
11127 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -060011128 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011129 case PyUnicode_1BYTE_KIND:
11130 iresult = ucs1lib_count(
11131 ((Py_UCS1*)buf1) + start, end - start,
11132 buf2, len2, PY_SSIZE_T_MAX
11133 );
11134 break;
11135 case PyUnicode_2BYTE_KIND:
11136 iresult = ucs2lib_count(
11137 ((Py_UCS2*)buf1) + start, end - start,
11138 buf2, len2, PY_SSIZE_T_MAX
11139 );
11140 break;
11141 case PyUnicode_4BYTE_KIND:
11142 iresult = ucs4lib_count(
11143 ((Py_UCS4*)buf1) + start, end - start,
11144 buf2, len2, PY_SSIZE_T_MAX
11145 );
11146 break;
11147 default:
11148 assert(0); iresult = 0;
11149 }
11150
11151 result = PyLong_FromSsize_t(iresult);
11152
11153 if (kind1 != kind)
11154 PyMem_Free(buf1);
11155 if (kind2 != kind)
11156 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011157
11158 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011159
Guido van Rossumd57fd912000-03-10 22:53:23 +000011160 return result;
11161}
11162
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011163PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000011164 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011165\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000011166Encode S using the codec registered for encoding. Default encoding\n\
11167is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000011168handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000011169a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
11170'xmlcharrefreplace' as well as any other name registered with\n\
11171codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011172
11173static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011174unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011175{
Benjamin Peterson308d6372009-09-18 21:42:35 +000011176 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011177 char *encoding = NULL;
11178 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000011179
Benjamin Peterson308d6372009-09-18 21:42:35 +000011180 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
11181 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011182 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011183 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000011184}
11185
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011186PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011187 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011188\n\
11189Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011190If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011191
11192static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011193unicode_expandtabs(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011194{
Antoine Pitroue71d5742011-10-04 15:55:09 +020011195 Py_ssize_t i, j, line_pos, src_len, incr;
11196 Py_UCS4 ch;
11197 PyObject *u;
11198 void *src_data, *dest_data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011199 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011200 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011201 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011202
11203 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000011204 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011205
Antoine Pitrou22425222011-10-04 19:10:51 +020011206 if (PyUnicode_READY(self) == -1)
11207 return NULL;
11208
Thomas Wouters7e474022000-07-16 12:04:32 +000011209 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011210 src_len = PyUnicode_GET_LENGTH(self);
11211 i = j = line_pos = 0;
11212 kind = PyUnicode_KIND(self);
11213 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020011214 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011215 for (; i < src_len; i++) {
11216 ch = PyUnicode_READ(kind, src_data, i);
11217 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020011218 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000011219 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011220 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000011221 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011222 goto overflow;
11223 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011224 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011225 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011226 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011227 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011228 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011229 goto overflow;
11230 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011231 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011232 if (ch == '\n' || ch == '\r')
11233 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011234 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011235 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010011236 if (!found)
11237 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011238
Guido van Rossumd57fd912000-03-10 22:53:23 +000011239 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011240 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011241 if (!u)
11242 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011243 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011244
Antoine Pitroue71d5742011-10-04 15:55:09 +020011245 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011246
Antoine Pitroue71d5742011-10-04 15:55:09 +020011247 for (; i < src_len; i++) {
11248 ch = PyUnicode_READ(kind, src_data, i);
11249 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011250 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011251 incr = tabsize - (line_pos % tabsize);
11252 line_pos += incr;
Victor Stinnerda79e632012-02-22 13:37:04 +010011253 FILL(kind, dest_data, ' ', j, incr);
11254 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011255 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011256 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011257 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011258 line_pos++;
11259 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011260 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011261 if (ch == '\n' || ch == '\r')
11262 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011263 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011264 }
11265 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010011266 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011267
Antoine Pitroue71d5742011-10-04 15:55:09 +020011268 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011269 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11270 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011271}
11272
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011273PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011274 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011275\n\
11276Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011277such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011278arguments start and end are interpreted as in slice notation.\n\
11279\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011280Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011281
11282static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011283unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011284{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011285 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011286 Py_ssize_t start;
11287 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011288 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011289
Jesus Ceaac451502011-04-20 17:09:23 +020011290 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
11291 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011292 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011293
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011294 if (PyUnicode_READY(self) == -1)
11295 return NULL;
11296 if (PyUnicode_READY(substring) == -1)
11297 return NULL;
11298
Victor Stinner7931d9a2011-11-04 00:22:48 +010011299 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011300
11301 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011302
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011303 if (result == -2)
11304 return NULL;
11305
Christian Heimes217cfd12007-12-02 14:31:20 +000011306 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011307}
11308
11309static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011310unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011311{
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011312 Py_UCS4 ch = PyUnicode_ReadChar(self, index);
11313 if (ch == (Py_UCS4)-1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011314 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011315 return PyUnicode_FromOrdinal(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011316}
11317
Guido van Rossumc2504932007-09-18 19:42:40 +000011318/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011319 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011320static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011321unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011322{
Guido van Rossumc2504932007-09-18 19:42:40 +000011323 Py_ssize_t len;
Mark Dickinson57e683e2011-09-24 18:18:40 +010011324 Py_uhash_t x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011325
Benjamin Peterson69e97272012-02-21 11:08:50 -050011326 assert(_Py_HashSecret_Initialized);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011327 if (_PyUnicode_HASH(self) != -1)
11328 return _PyUnicode_HASH(self);
11329 if (PyUnicode_READY(self) == -1)
11330 return -1;
11331 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010011332 /*
11333 We make the hash of the empty string be 0, rather than using
11334 (prefix ^ suffix), since this slightly obfuscates the hash secret
11335 */
11336 if (len == 0) {
11337 _PyUnicode_HASH(self) = 0;
11338 return 0;
11339 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011340
11341 /* The hash function as a macro, gets expanded three times below. */
Georg Brandl2fb477c2012-02-21 00:33:36 +010011342#define HASH(P) \
11343 x ^= (Py_uhash_t) *P << 7; \
11344 while (--len >= 0) \
11345 x = (_PyHASH_MULTIPLIER * x) ^ (Py_uhash_t) *P++; \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011346
Georg Brandl2fb477c2012-02-21 00:33:36 +010011347 x = (Py_uhash_t) _Py_HashSecret.prefix;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011348 switch (PyUnicode_KIND(self)) {
11349 case PyUnicode_1BYTE_KIND: {
11350 const unsigned char *c = PyUnicode_1BYTE_DATA(self);
11351 HASH(c);
11352 break;
11353 }
11354 case PyUnicode_2BYTE_KIND: {
11355 const Py_UCS2 *s = PyUnicode_2BYTE_DATA(self);
11356 HASH(s);
11357 break;
11358 }
11359 default: {
11360 Py_UCS4 *l;
11361 assert(PyUnicode_KIND(self) == PyUnicode_4BYTE_KIND &&
11362 "Impossible switch case in unicode_hash");
11363 l = PyUnicode_4BYTE_DATA(self);
11364 HASH(l);
11365 break;
11366 }
11367 }
Georg Brandl2fb477c2012-02-21 00:33:36 +010011368 x ^= (Py_uhash_t) PyUnicode_GET_LENGTH(self);
11369 x ^= (Py_uhash_t) _Py_HashSecret.suffix;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011370
Guido van Rossumc2504932007-09-18 19:42:40 +000011371 if (x == -1)
11372 x = -2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011373 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011374 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011375}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011376#undef HASH
Guido van Rossumd57fd912000-03-10 22:53:23 +000011377
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011378PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011379 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011380\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011381Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011382
11383static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011384unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011385{
Martin v. Löwis18e16552006-02-15 17:27:45 +000011386 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011387 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011388 Py_ssize_t start;
11389 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011390
Jesus Ceaac451502011-04-20 17:09:23 +020011391 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
11392 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011393 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011394
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011395 if (PyUnicode_READY(self) == -1)
11396 return NULL;
11397 if (PyUnicode_READY(substring) == -1)
11398 return NULL;
11399
Victor Stinner7931d9a2011-11-04 00:22:48 +010011400 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011401
11402 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011403
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011404 if (result == -2)
11405 return NULL;
11406
Guido van Rossumd57fd912000-03-10 22:53:23 +000011407 if (result < 0) {
11408 PyErr_SetString(PyExc_ValueError, "substring not found");
11409 return NULL;
11410 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011411
Christian Heimes217cfd12007-12-02 14:31:20 +000011412 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011413}
11414
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011415PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011416 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011417\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011418Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011419at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011420
11421static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011422unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011423{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011424 Py_ssize_t i, length;
11425 int kind;
11426 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011427 int cased;
11428
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011429 if (PyUnicode_READY(self) == -1)
11430 return NULL;
11431 length = PyUnicode_GET_LENGTH(self);
11432 kind = PyUnicode_KIND(self);
11433 data = PyUnicode_DATA(self);
11434
Guido van Rossumd57fd912000-03-10 22:53:23 +000011435 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011436 if (length == 1)
11437 return PyBool_FromLong(
11438 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011439
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011440 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011441 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011442 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011443
Guido van Rossumd57fd912000-03-10 22:53:23 +000011444 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011445 for (i = 0; i < length; i++) {
11446 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011447
Benjamin Peterson29060642009-01-31 22:14:21 +000011448 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11449 return PyBool_FromLong(0);
11450 else if (!cased && Py_UNICODE_ISLOWER(ch))
11451 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011452 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011453 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011454}
11455
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011456PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011457 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011458\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011459Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011460at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011461
11462static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011463unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011464{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011465 Py_ssize_t i, length;
11466 int kind;
11467 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011468 int cased;
11469
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011470 if (PyUnicode_READY(self) == -1)
11471 return NULL;
11472 length = PyUnicode_GET_LENGTH(self);
11473 kind = PyUnicode_KIND(self);
11474 data = PyUnicode_DATA(self);
11475
Guido van Rossumd57fd912000-03-10 22:53:23 +000011476 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011477 if (length == 1)
11478 return PyBool_FromLong(
11479 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011480
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011481 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011482 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011483 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011484
Guido van Rossumd57fd912000-03-10 22:53:23 +000011485 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011486 for (i = 0; i < length; i++) {
11487 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011488
Benjamin Peterson29060642009-01-31 22:14:21 +000011489 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11490 return PyBool_FromLong(0);
11491 else if (!cased && Py_UNICODE_ISUPPER(ch))
11492 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011493 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011494 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011495}
11496
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011497PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011498 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011499\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011500Return True if S is a titlecased string and there is at least one\n\
11501character in S, i.e. upper- and titlecase characters may only\n\
11502follow uncased characters and lowercase characters only cased ones.\n\
11503Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011504
11505static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011506unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011507{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011508 Py_ssize_t i, length;
11509 int kind;
11510 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011511 int cased, previous_is_cased;
11512
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011513 if (PyUnicode_READY(self) == -1)
11514 return NULL;
11515 length = PyUnicode_GET_LENGTH(self);
11516 kind = PyUnicode_KIND(self);
11517 data = PyUnicode_DATA(self);
11518
Guido van Rossumd57fd912000-03-10 22:53:23 +000011519 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011520 if (length == 1) {
11521 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11522 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11523 (Py_UNICODE_ISUPPER(ch) != 0));
11524 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011525
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011526 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011527 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011528 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011529
Guido van Rossumd57fd912000-03-10 22:53:23 +000011530 cased = 0;
11531 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011532 for (i = 0; i < length; i++) {
11533 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011534
Benjamin Peterson29060642009-01-31 22:14:21 +000011535 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11536 if (previous_is_cased)
11537 return PyBool_FromLong(0);
11538 previous_is_cased = 1;
11539 cased = 1;
11540 }
11541 else if (Py_UNICODE_ISLOWER(ch)) {
11542 if (!previous_is_cased)
11543 return PyBool_FromLong(0);
11544 previous_is_cased = 1;
11545 cased = 1;
11546 }
11547 else
11548 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011549 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011550 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011551}
11552
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011553PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011554 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011555\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011556Return True if all characters in S are whitespace\n\
11557and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011558
11559static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011560unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011561{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011562 Py_ssize_t i, length;
11563 int kind;
11564 void *data;
11565
11566 if (PyUnicode_READY(self) == -1)
11567 return NULL;
11568 length = PyUnicode_GET_LENGTH(self);
11569 kind = PyUnicode_KIND(self);
11570 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011571
Guido van Rossumd57fd912000-03-10 22:53:23 +000011572 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011573 if (length == 1)
11574 return PyBool_FromLong(
11575 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011576
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011577 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011578 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011579 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011580
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011581 for (i = 0; i < length; i++) {
11582 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011583 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011584 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011585 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011586 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011587}
11588
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011589PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011590 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011591\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011592Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011593and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011594
11595static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011596unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011597{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011598 Py_ssize_t i, length;
11599 int kind;
11600 void *data;
11601
11602 if (PyUnicode_READY(self) == -1)
11603 return NULL;
11604 length = PyUnicode_GET_LENGTH(self);
11605 kind = PyUnicode_KIND(self);
11606 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011607
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011608 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011609 if (length == 1)
11610 return PyBool_FromLong(
11611 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011612
11613 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011614 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011615 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011616
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011617 for (i = 0; i < length; i++) {
11618 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011619 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011620 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011621 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011622}
11623
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011624PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011625 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011626\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011627Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011628and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011629
11630static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011631unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011632{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011633 int kind;
11634 void *data;
11635 Py_ssize_t len, i;
11636
11637 if (PyUnicode_READY(self) == -1)
11638 return NULL;
11639
11640 kind = PyUnicode_KIND(self);
11641 data = PyUnicode_DATA(self);
11642 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011643
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011644 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011645 if (len == 1) {
11646 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11647 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11648 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011649
11650 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011651 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011652 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011653
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011654 for (i = 0; i < len; i++) {
11655 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011656 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011657 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011658 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011659 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011660}
11661
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011662PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011663 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011664\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011665Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011666False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011667
11668static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011669unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011670{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011671 Py_ssize_t i, length;
11672 int kind;
11673 void *data;
11674
11675 if (PyUnicode_READY(self) == -1)
11676 return NULL;
11677 length = PyUnicode_GET_LENGTH(self);
11678 kind = PyUnicode_KIND(self);
11679 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011680
Guido van Rossumd57fd912000-03-10 22:53:23 +000011681 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011682 if (length == 1)
11683 return PyBool_FromLong(
11684 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011685
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011686 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011687 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011688 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011689
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011690 for (i = 0; i < length; i++) {
11691 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011692 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011693 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011694 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011695}
11696
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011697PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011698 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011699\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011700Return True if all characters in S are digits\n\
11701and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011702
11703static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011704unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011705{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011706 Py_ssize_t i, length;
11707 int kind;
11708 void *data;
11709
11710 if (PyUnicode_READY(self) == -1)
11711 return NULL;
11712 length = PyUnicode_GET_LENGTH(self);
11713 kind = PyUnicode_KIND(self);
11714 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011715
Guido van Rossumd57fd912000-03-10 22:53:23 +000011716 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011717 if (length == 1) {
11718 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11719 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11720 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011721
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011722 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011723 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011724 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011725
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011726 for (i = 0; i < length; i++) {
11727 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011728 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011729 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011730 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011731}
11732
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011733PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011734 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011735\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011736Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011737False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011738
11739static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011740unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011741{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011742 Py_ssize_t i, length;
11743 int kind;
11744 void *data;
11745
11746 if (PyUnicode_READY(self) == -1)
11747 return NULL;
11748 length = PyUnicode_GET_LENGTH(self);
11749 kind = PyUnicode_KIND(self);
11750 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011751
Guido van Rossumd57fd912000-03-10 22:53:23 +000011752 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011753 if (length == 1)
11754 return PyBool_FromLong(
11755 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011756
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011757 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011758 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011759 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011760
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011761 for (i = 0; i < length; i++) {
11762 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011763 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011764 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011765 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011766}
11767
Martin v. Löwis47383402007-08-15 07:32:56 +000011768int
11769PyUnicode_IsIdentifier(PyObject *self)
11770{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011771 int kind;
11772 void *data;
11773 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011774 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011775
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011776 if (PyUnicode_READY(self) == -1) {
11777 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011778 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011779 }
11780
11781 /* Special case for empty strings */
11782 if (PyUnicode_GET_LENGTH(self) == 0)
11783 return 0;
11784 kind = PyUnicode_KIND(self);
11785 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011786
11787 /* PEP 3131 says that the first character must be in
11788 XID_Start and subsequent characters in XID_Continue,
11789 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011790 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011791 letters, digits, underscore). However, given the current
11792 definition of XID_Start and XID_Continue, it is sufficient
11793 to check just for these, except that _ must be allowed
11794 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011795 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011796 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011797 return 0;
11798
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011799 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011800 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011801 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011802 return 1;
11803}
11804
11805PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011806 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011807\n\
11808Return True if S is a valid identifier according\n\
11809to the language definition.");
11810
11811static PyObject*
11812unicode_isidentifier(PyObject *self)
11813{
11814 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11815}
11816
Georg Brandl559e5d72008-06-11 18:37:52 +000011817PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011818 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011819\n\
11820Return True if all characters in S are considered\n\
11821printable in repr() or S is empty, False otherwise.");
11822
11823static PyObject*
11824unicode_isprintable(PyObject *self)
11825{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011826 Py_ssize_t i, length;
11827 int kind;
11828 void *data;
11829
11830 if (PyUnicode_READY(self) == -1)
11831 return NULL;
11832 length = PyUnicode_GET_LENGTH(self);
11833 kind = PyUnicode_KIND(self);
11834 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011835
11836 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011837 if (length == 1)
11838 return PyBool_FromLong(
11839 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011840
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011841 for (i = 0; i < length; i++) {
11842 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011843 Py_RETURN_FALSE;
11844 }
11845 }
11846 Py_RETURN_TRUE;
11847}
11848
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011849PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011850 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011851\n\
11852Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011853iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011854
11855static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011856unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011857{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011858 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011859}
11860
Martin v. Löwis18e16552006-02-15 17:27:45 +000011861static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011862unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011863{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011864 if (PyUnicode_READY(self) == -1)
11865 return -1;
11866 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011867}
11868
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011869PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011870 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011871\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011872Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011873done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011874
11875static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011876unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011877{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011878 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011879 Py_UCS4 fillchar = ' ';
11880
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011881 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011882 return NULL;
11883
Benjamin Petersonbac79492012-01-14 13:34:47 -050011884 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010011885 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011886
Victor Stinnerc4b49542011-12-11 22:44:26 +010011887 if (PyUnicode_GET_LENGTH(self) >= width)
11888 return unicode_result_unchanged(self);
11889
11890 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011891}
11892
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011893PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011894 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011895\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011896Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011897
11898static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011899unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011900{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050011901 if (PyUnicode_READY(self) == -1)
11902 return NULL;
11903 if (PyUnicode_IS_ASCII(self))
11904 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010011905 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011906}
11907
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011908#define LEFTSTRIP 0
11909#define RIGHTSTRIP 1
11910#define BOTHSTRIP 2
11911
11912/* Arrays indexed by above */
11913static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11914
11915#define STRIPNAME(i) (stripformat[i]+3)
11916
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011917/* externally visible for str.strip(unicode) */
11918PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011919_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011920{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011921 void *data;
11922 int kind;
11923 Py_ssize_t i, j, len;
11924 BLOOM_MASK sepmask;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011925
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011926 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
11927 return NULL;
11928
11929 kind = PyUnicode_KIND(self);
11930 data = PyUnicode_DATA(self);
11931 len = PyUnicode_GET_LENGTH(self);
11932 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
11933 PyUnicode_DATA(sepobj),
11934 PyUnicode_GET_LENGTH(sepobj));
Thomas Wouters477c8d52006-05-27 19:21:47 +000011935
Benjamin Peterson14339b62009-01-31 16:36:08 +000011936 i = 0;
11937 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011938 while (i < len &&
11939 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, i), sepobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011940 i++;
11941 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011942 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011943
Benjamin Peterson14339b62009-01-31 16:36:08 +000011944 j = len;
11945 if (striptype != LEFTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011946 do {
11947 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011948 } while (j >= i &&
11949 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, j), sepobj));
Benjamin Peterson29060642009-01-31 22:14:21 +000011950 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011951 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011952
Victor Stinner7931d9a2011-11-04 00:22:48 +010011953 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011954}
11955
11956PyObject*
11957PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
11958{
11959 unsigned char *data;
11960 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020011961 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011962
Victor Stinnerde636f32011-10-01 03:55:54 +020011963 if (PyUnicode_READY(self) == -1)
11964 return NULL;
11965
11966 end = Py_MIN(end, PyUnicode_GET_LENGTH(self));
11967
Victor Stinner12bab6d2011-10-01 01:53:49 +020011968 if (start == 0 && end == PyUnicode_GET_LENGTH(self))
Victor Stinnerc4b49542011-12-11 22:44:26 +010011969 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011970
Victor Stinner12bab6d2011-10-01 01:53:49 +020011971 length = end - start;
11972 if (length == 1)
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011973 return unicode_getitem(self, start);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011974
Victor Stinnerde636f32011-10-01 03:55:54 +020011975 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011976 PyErr_SetString(PyExc_IndexError, "string index out of range");
11977 return NULL;
11978 }
11979
Victor Stinnerb9275c12011-10-05 14:01:42 +020011980 if (PyUnicode_IS_ASCII(self)) {
11981 kind = PyUnicode_KIND(self);
11982 data = PyUnicode_1BYTE_DATA(self);
11983 return unicode_fromascii(data + start, length);
11984 }
11985 else {
11986 kind = PyUnicode_KIND(self);
11987 data = PyUnicode_1BYTE_DATA(self);
11988 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011989 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020011990 length);
11991 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011992}
Guido van Rossumd57fd912000-03-10 22:53:23 +000011993
11994static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011995do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011996{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011997 int kind;
11998 void *data;
11999 Py_ssize_t len, i, j;
12000
12001 if (PyUnicode_READY(self) == -1)
12002 return NULL;
12003
12004 kind = PyUnicode_KIND(self);
12005 data = PyUnicode_DATA(self);
12006 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012007
Benjamin Peterson14339b62009-01-31 16:36:08 +000012008 i = 0;
12009 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012010 while (i < len && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, i))) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012011 i++;
12012 }
12013 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012014
Benjamin Peterson14339b62009-01-31 16:36:08 +000012015 j = len;
12016 if (striptype != LEFTSTRIP) {
12017 do {
12018 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012019 } while (j >= i && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, j)));
Benjamin Peterson14339b62009-01-31 16:36:08 +000012020 j++;
12021 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012022
Victor Stinner7931d9a2011-11-04 00:22:48 +010012023 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012024}
12025
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012026
12027static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012028do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012029{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012030 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012031
Benjamin Peterson14339b62009-01-31 16:36:08 +000012032 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
12033 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012034
Benjamin Peterson14339b62009-01-31 16:36:08 +000012035 if (sep != NULL && sep != Py_None) {
12036 if (PyUnicode_Check(sep))
12037 return _PyUnicode_XStrip(self, striptype, sep);
12038 else {
12039 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012040 "%s arg must be None or str",
12041 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000012042 return NULL;
12043 }
12044 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012045
Benjamin Peterson14339b62009-01-31 16:36:08 +000012046 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012047}
12048
12049
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012050PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012051 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012052\n\
12053Return a copy of the string S with leading and trailing\n\
12054whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012055If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012056
12057static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012058unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012059{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012060 if (PyTuple_GET_SIZE(args) == 0)
12061 return do_strip(self, BOTHSTRIP); /* Common case */
12062 else
12063 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012064}
12065
12066
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012067PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012068 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012069\n\
12070Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012071If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012072
12073static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012074unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012075{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012076 if (PyTuple_GET_SIZE(args) == 0)
12077 return do_strip(self, LEFTSTRIP); /* Common case */
12078 else
12079 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012080}
12081
12082
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012083PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012084 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012085\n\
12086Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012087If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012088
12089static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012090unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012091{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012092 if (PyTuple_GET_SIZE(args) == 0)
12093 return do_strip(self, RIGHTSTRIP); /* Common case */
12094 else
12095 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012096}
12097
12098
Guido van Rossumd57fd912000-03-10 22:53:23 +000012099static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012100unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012101{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012102 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012103 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012104
Georg Brandl222de0f2009-04-12 12:01:50 +000012105 if (len < 1) {
12106 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +020012107 return unicode_empty;
Georg Brandl222de0f2009-04-12 12:01:50 +000012108 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012109
Victor Stinnerc4b49542011-12-11 22:44:26 +010012110 /* no repeat, return original string */
12111 if (len == 1)
12112 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000012113
Benjamin Petersonbac79492012-01-14 13:34:47 -050012114 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012115 return NULL;
12116
Victor Stinnerc759f3e2011-10-01 03:09:58 +020012117 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020012118 PyErr_SetString(PyExc_OverflowError,
12119 "repeated string is too long");
12120 return NULL;
12121 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012122 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012123
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012124 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012125 if (!u)
12126 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012127 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012128
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012129 if (PyUnicode_GET_LENGTH(str) == 1) {
12130 const int kind = PyUnicode_KIND(str);
12131 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010012132 if (kind == PyUnicode_1BYTE_KIND) {
12133 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012134 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010012135 }
12136 else if (kind == PyUnicode_2BYTE_KIND) {
12137 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012138 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010012139 ucs2[n] = fill_char;
12140 } else {
12141 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
12142 assert(kind == PyUnicode_4BYTE_KIND);
12143 for (n = 0; n < len; ++n)
12144 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012145 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012146 }
12147 else {
12148 /* number of characters copied this far */
12149 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012150 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012151 char *to = (char *) PyUnicode_DATA(u);
12152 Py_MEMCPY(to, PyUnicode_DATA(str),
12153 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000012154 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012155 n = (done <= nchars-done) ? done : nchars-done;
12156 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012157 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000012158 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012159 }
12160
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012161 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012162 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012163}
12164
Alexander Belopolsky40018472011-02-26 01:02:56 +000012165PyObject *
12166PyUnicode_Replace(PyObject *obj,
12167 PyObject *subobj,
12168 PyObject *replobj,
12169 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012170{
12171 PyObject *self;
12172 PyObject *str1;
12173 PyObject *str2;
12174 PyObject *result;
12175
12176 self = PyUnicode_FromObject(obj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012177 if (self == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012178 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012179 str1 = PyUnicode_FromObject(subobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012180 if (str1 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012181 Py_DECREF(self);
12182 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012183 }
12184 str2 = PyUnicode_FromObject(replobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012185 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012186 Py_DECREF(self);
12187 Py_DECREF(str1);
12188 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012189 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060012190 if (PyUnicode_READY(self) == -1 ||
12191 PyUnicode_READY(str1) == -1 ||
12192 PyUnicode_READY(str2) == -1)
12193 result = NULL;
12194 else
12195 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012196 Py_DECREF(self);
12197 Py_DECREF(str1);
12198 Py_DECREF(str2);
12199 return result;
12200}
12201
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012202PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000012203 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012204\n\
12205Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000012206old replaced by new. If the optional argument count is\n\
12207given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012208
12209static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012210unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012211{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012212 PyObject *str1;
12213 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012214 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012215 PyObject *result;
12216
Martin v. Löwis18e16552006-02-15 17:27:45 +000012217 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012218 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060012219 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012220 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012221 str1 = PyUnicode_FromObject(str1);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012222 if (str1 == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012223 return NULL;
12224 str2 = PyUnicode_FromObject(str2);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012225 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012226 Py_DECREF(str1);
12227 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000012228 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060012229 if (PyUnicode_READY(str1) == -1 || PyUnicode_READY(str2) == -1)
12230 result = NULL;
12231 else
12232 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012233
12234 Py_DECREF(str1);
12235 Py_DECREF(str2);
12236 return result;
12237}
12238
Alexander Belopolsky40018472011-02-26 01:02:56 +000012239static PyObject *
12240unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012241{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012242 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012243 Py_ssize_t isize;
12244 Py_ssize_t osize, squote, dquote, i, o;
12245 Py_UCS4 max, quote;
12246 int ikind, okind;
12247 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012248
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012249 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012250 return NULL;
12251
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012252 isize = PyUnicode_GET_LENGTH(unicode);
12253 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012254
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012255 /* Compute length of output, quote characters, and
12256 maximum character */
12257 osize = 2; /* quotes */
12258 max = 127;
12259 squote = dquote = 0;
12260 ikind = PyUnicode_KIND(unicode);
12261 for (i = 0; i < isize; i++) {
12262 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
12263 switch (ch) {
12264 case '\'': squote++; osize++; break;
12265 case '"': dquote++; osize++; break;
12266 case '\\': case '\t': case '\r': case '\n':
12267 osize += 2; break;
12268 default:
12269 /* Fast-path ASCII */
12270 if (ch < ' ' || ch == 0x7f)
12271 osize += 4; /* \xHH */
12272 else if (ch < 0x7f)
12273 osize++;
12274 else if (Py_UNICODE_ISPRINTABLE(ch)) {
12275 osize++;
12276 max = ch > max ? ch : max;
12277 }
12278 else if (ch < 0x100)
12279 osize += 4; /* \xHH */
12280 else if (ch < 0x10000)
12281 osize += 6; /* \uHHHH */
12282 else
12283 osize += 10; /* \uHHHHHHHH */
12284 }
12285 }
12286
12287 quote = '\'';
12288 if (squote) {
12289 if (dquote)
12290 /* Both squote and dquote present. Use squote,
12291 and escape them */
12292 osize += squote;
12293 else
12294 quote = '"';
12295 }
12296
12297 repr = PyUnicode_New(osize, max);
12298 if (repr == NULL)
12299 return NULL;
12300 okind = PyUnicode_KIND(repr);
12301 odata = PyUnicode_DATA(repr);
12302
12303 PyUnicode_WRITE(okind, odata, 0, quote);
12304 PyUnicode_WRITE(okind, odata, osize-1, quote);
12305
12306 for (i = 0, o = 1; i < isize; i++) {
12307 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012308
12309 /* Escape quotes and backslashes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012310 if ((ch == quote) || (ch == '\\')) {
12311 PyUnicode_WRITE(okind, odata, o++, '\\');
12312 PyUnicode_WRITE(okind, odata, o++, ch);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012313 continue;
12314 }
12315
Benjamin Peterson29060642009-01-31 22:14:21 +000012316 /* Map special whitespace to '\t', \n', '\r' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012317 if (ch == '\t') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012318 PyUnicode_WRITE(okind, odata, o++, '\\');
12319 PyUnicode_WRITE(okind, odata, o++, 't');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012320 }
12321 else if (ch == '\n') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012322 PyUnicode_WRITE(okind, odata, o++, '\\');
12323 PyUnicode_WRITE(okind, odata, o++, 'n');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012324 }
12325 else if (ch == '\r') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012326 PyUnicode_WRITE(okind, odata, o++, '\\');
12327 PyUnicode_WRITE(okind, odata, o++, 'r');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012328 }
12329
12330 /* Map non-printable US ASCII to '\xhh' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012331 else if (ch < ' ' || ch == 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012332 PyUnicode_WRITE(okind, odata, o++, '\\');
12333 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012334 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12335 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012336 }
12337
Georg Brandl559e5d72008-06-11 18:37:52 +000012338 /* Copy ASCII characters as-is */
12339 else if (ch < 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012340 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012341 }
12342
Benjamin Peterson29060642009-01-31 22:14:21 +000012343 /* Non-ASCII characters */
Georg Brandl559e5d72008-06-11 18:37:52 +000012344 else {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012345 /* Map Unicode whitespace and control characters
Georg Brandl559e5d72008-06-11 18:37:52 +000012346 (categories Z* and C* except ASCII space)
12347 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012348 if (!Py_UNICODE_ISPRINTABLE(ch)) {
Georg Brandl559e5d72008-06-11 18:37:52 +000012349 /* Map 8-bit characters to '\xhh' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012350 if (ch <= 0xff) {
12351 PyUnicode_WRITE(okind, odata, o++, '\\');
12352 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012353 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12354 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012355 }
12356 /* Map 21-bit characters to '\U00xxxxxx' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012357 else if (ch >= 0x10000) {
12358 PyUnicode_WRITE(okind, odata, o++, '\\');
12359 PyUnicode_WRITE(okind, odata, o++, 'U');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012360 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12361 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12362 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12363 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12364 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12365 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12366 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12367 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012368 }
12369 /* Map 16-bit characters to '\uxxxx' */
12370 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012371 PyUnicode_WRITE(okind, odata, o++, '\\');
12372 PyUnicode_WRITE(okind, odata, o++, 'u');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012373 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12374 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12375 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12376 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012377 }
12378 }
12379 /* Copy characters as-is */
12380 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012381 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012382 }
12383 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012384 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012385 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012386 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012387 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012388}
12389
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012390PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012391 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012392\n\
12393Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012394such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012395arguments start and end are interpreted as in slice notation.\n\
12396\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012397Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012398
12399static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012400unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012401{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012402 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012403 Py_ssize_t start;
12404 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012405 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012406
Jesus Ceaac451502011-04-20 17:09:23 +020012407 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
12408 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012409 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012410
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012411 if (PyUnicode_READY(self) == -1)
12412 return NULL;
12413 if (PyUnicode_READY(substring) == -1)
12414 return NULL;
12415
Victor Stinner7931d9a2011-11-04 00:22:48 +010012416 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012417
12418 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012419
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012420 if (result == -2)
12421 return NULL;
12422
Christian Heimes217cfd12007-12-02 14:31:20 +000012423 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012424}
12425
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012426PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012427 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012428\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012429Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012430
12431static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012432unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012433{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012434 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012435 Py_ssize_t start;
12436 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012437 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012438
Jesus Ceaac451502011-04-20 17:09:23 +020012439 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12440 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012441 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012442
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012443 if (PyUnicode_READY(self) == -1)
12444 return NULL;
12445 if (PyUnicode_READY(substring) == -1)
12446 return NULL;
12447
Victor Stinner7931d9a2011-11-04 00:22:48 +010012448 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012449
12450 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012451
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012452 if (result == -2)
12453 return NULL;
12454
Guido van Rossumd57fd912000-03-10 22:53:23 +000012455 if (result < 0) {
12456 PyErr_SetString(PyExc_ValueError, "substring not found");
12457 return NULL;
12458 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012459
Christian Heimes217cfd12007-12-02 14:31:20 +000012460 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012461}
12462
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012463PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012464 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012465\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012466Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012467done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012468
12469static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012470unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012471{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012472 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012473 Py_UCS4 fillchar = ' ';
12474
Victor Stinnere9a29352011-10-01 02:14:59 +020012475 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012476 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012477
Benjamin Petersonbac79492012-01-14 13:34:47 -050012478 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012479 return NULL;
12480
Victor Stinnerc4b49542011-12-11 22:44:26 +010012481 if (PyUnicode_GET_LENGTH(self) >= width)
12482 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012483
Victor Stinnerc4b49542011-12-11 22:44:26 +010012484 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012485}
12486
Alexander Belopolsky40018472011-02-26 01:02:56 +000012487PyObject *
12488PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012489{
12490 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012491
Guido van Rossumd57fd912000-03-10 22:53:23 +000012492 s = PyUnicode_FromObject(s);
12493 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012494 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012495 if (sep != NULL) {
12496 sep = PyUnicode_FromObject(sep);
12497 if (sep == NULL) {
12498 Py_DECREF(s);
12499 return NULL;
12500 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012501 }
12502
Victor Stinner9310abb2011-10-05 00:59:23 +020012503 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012504
12505 Py_DECREF(s);
12506 Py_XDECREF(sep);
12507 return result;
12508}
12509
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012510PyDoc_STRVAR(split__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012511 "S.split(sep=None, maxsplit=-1) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012512\n\
12513Return a list of the words in S, using sep as the\n\
12514delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012515splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012516whitespace string is a separator and empty strings are\n\
12517removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012518
12519static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012520unicode_split(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012521{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012522 static char *kwlist[] = {"sep", "maxsplit", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000012523 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012524 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012525
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012526 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:split",
12527 kwlist, &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012528 return NULL;
12529
12530 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012531 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012532 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012533 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012534 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012535 return PyUnicode_Split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012536}
12537
Thomas Wouters477c8d52006-05-27 19:21:47 +000012538PyObject *
12539PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12540{
12541 PyObject* str_obj;
12542 PyObject* sep_obj;
12543 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012544 int kind1, kind2, kind;
12545 void *buf1 = NULL, *buf2 = NULL;
12546 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012547
12548 str_obj = PyUnicode_FromObject(str_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012549 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012550 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012551 sep_obj = PyUnicode_FromObject(sep_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012552 if (!sep_obj) {
12553 Py_DECREF(str_obj);
12554 return NULL;
12555 }
12556 if (PyUnicode_READY(sep_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
12557 Py_DECREF(sep_obj);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012558 Py_DECREF(str_obj);
12559 return NULL;
12560 }
12561
Victor Stinner14f8f022011-10-05 20:58:25 +020012562 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012563 kind2 = PyUnicode_KIND(sep_obj);
Victor Stinner14f8f022011-10-05 20:58:25 +020012564 kind = Py_MAX(kind1, kind2);
12565 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012566 if (kind1 != kind)
Victor Stinner14f8f022011-10-05 20:58:25 +020012567 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012568 if (!buf1)
12569 goto onError;
12570 buf2 = PyUnicode_DATA(sep_obj);
12571 if (kind2 != kind)
12572 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12573 if (!buf2)
12574 goto onError;
12575 len1 = PyUnicode_GET_LENGTH(str_obj);
12576 len2 = PyUnicode_GET_LENGTH(sep_obj);
12577
Benjamin Petersonead6b532011-12-20 17:23:42 -060012578 switch (PyUnicode_KIND(str_obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012579 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012580 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12581 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12582 else
12583 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012584 break;
12585 case PyUnicode_2BYTE_KIND:
12586 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12587 break;
12588 case PyUnicode_4BYTE_KIND:
12589 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12590 break;
12591 default:
12592 assert(0);
12593 out = 0;
12594 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012595
12596 Py_DECREF(sep_obj);
12597 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012598 if (kind1 != kind)
12599 PyMem_Free(buf1);
12600 if (kind2 != kind)
12601 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012602
12603 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012604 onError:
12605 Py_DECREF(sep_obj);
12606 Py_DECREF(str_obj);
12607 if (kind1 != kind && buf1)
12608 PyMem_Free(buf1);
12609 if (kind2 != kind && buf2)
12610 PyMem_Free(buf2);
12611 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012612}
12613
12614
12615PyObject *
12616PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12617{
12618 PyObject* str_obj;
12619 PyObject* sep_obj;
12620 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012621 int kind1, kind2, kind;
12622 void *buf1 = NULL, *buf2 = NULL;
12623 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012624
12625 str_obj = PyUnicode_FromObject(str_in);
12626 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012627 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012628 sep_obj = PyUnicode_FromObject(sep_in);
12629 if (!sep_obj) {
12630 Py_DECREF(str_obj);
12631 return NULL;
12632 }
12633
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012634 kind1 = PyUnicode_KIND(str_in);
12635 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020012636 kind = Py_MAX(kind1, kind2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012637 buf1 = PyUnicode_DATA(str_in);
12638 if (kind1 != kind)
12639 buf1 = _PyUnicode_AsKind(str_in, kind);
12640 if (!buf1)
12641 goto onError;
12642 buf2 = PyUnicode_DATA(sep_obj);
12643 if (kind2 != kind)
12644 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12645 if (!buf2)
12646 goto onError;
12647 len1 = PyUnicode_GET_LENGTH(str_obj);
12648 len2 = PyUnicode_GET_LENGTH(sep_obj);
12649
Benjamin Petersonead6b532011-12-20 17:23:42 -060012650 switch (PyUnicode_KIND(str_in)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012651 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012652 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12653 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12654 else
12655 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012656 break;
12657 case PyUnicode_2BYTE_KIND:
12658 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12659 break;
12660 case PyUnicode_4BYTE_KIND:
12661 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12662 break;
12663 default:
12664 assert(0);
12665 out = 0;
12666 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012667
12668 Py_DECREF(sep_obj);
12669 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012670 if (kind1 != kind)
12671 PyMem_Free(buf1);
12672 if (kind2 != kind)
12673 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012674
12675 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012676 onError:
12677 Py_DECREF(sep_obj);
12678 Py_DECREF(str_obj);
12679 if (kind1 != kind && buf1)
12680 PyMem_Free(buf1);
12681 if (kind2 != kind && buf2)
12682 PyMem_Free(buf2);
12683 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012684}
12685
12686PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012687 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012688\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012689Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012690the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012691found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012692
12693static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012694unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012695{
Victor Stinner9310abb2011-10-05 00:59:23 +020012696 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012697}
12698
12699PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012700 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012701\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012702Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012703the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012704separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012705
12706static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012707unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012708{
Victor Stinner9310abb2011-10-05 00:59:23 +020012709 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012710}
12711
Alexander Belopolsky40018472011-02-26 01:02:56 +000012712PyObject *
12713PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012714{
12715 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012716
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012717 s = PyUnicode_FromObject(s);
12718 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012719 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012720 if (sep != NULL) {
12721 sep = PyUnicode_FromObject(sep);
12722 if (sep == NULL) {
12723 Py_DECREF(s);
12724 return NULL;
12725 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012726 }
12727
Victor Stinner9310abb2011-10-05 00:59:23 +020012728 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012729
12730 Py_DECREF(s);
12731 Py_XDECREF(sep);
12732 return result;
12733}
12734
12735PyDoc_STRVAR(rsplit__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012736 "S.rsplit(sep=None, maxsplit=-1) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012737\n\
12738Return a list of the words in S, using sep as the\n\
12739delimiter string, starting at the end of the string and\n\
12740working to the front. If maxsplit is given, at most maxsplit\n\
12741splits are done. If sep is not specified, any whitespace string\n\
12742is a separator.");
12743
12744static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012745unicode_rsplit(PyObject *self, PyObject *args, PyObject *kwds)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012746{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012747 static char *kwlist[] = {"sep", "maxsplit", 0};
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012748 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012749 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012750
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012751 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:rsplit",
12752 kwlist, &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012753 return NULL;
12754
12755 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012756 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012757 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012758 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012759 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012760 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012761}
12762
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012763PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012764 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012765\n\
12766Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012767Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012768is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012769
12770static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012771unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012772{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012773 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012774 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012775
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012776 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12777 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012778 return NULL;
12779
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012780 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012781}
12782
12783static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012784PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012785{
Victor Stinnerc4b49542011-12-11 22:44:26 +010012786 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012787}
12788
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012789PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012790 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012791\n\
12792Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012793and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012794
12795static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012796unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012797{
Benjamin Petersoneea48462012-01-16 14:28:50 -050012798 if (PyUnicode_READY(self) == -1)
12799 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012800 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012801}
12802
Georg Brandlceee0772007-11-27 23:48:05 +000012803PyDoc_STRVAR(maketrans__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012804 "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012805\n\
12806Return a translation table usable for str.translate().\n\
12807If there is only one argument, it must be a dictionary mapping Unicode\n\
12808ordinals (integers) or characters to Unicode ordinals, strings or None.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012809Character keys will be then converted to ordinals.\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012810If there are two arguments, they must be strings of equal length, and\n\
12811in the resulting dictionary, each character in x will be mapped to the\n\
12812character at the same position in y. If there is a third argument, it\n\
12813must be a string, whose characters will be mapped to None in the result.");
12814
12815static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012816unicode_maketrans(PyObject *null, PyObject *args)
Georg Brandlceee0772007-11-27 23:48:05 +000012817{
12818 PyObject *x, *y = NULL, *z = NULL;
12819 PyObject *new = NULL, *key, *value;
12820 Py_ssize_t i = 0;
12821 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012822
Georg Brandlceee0772007-11-27 23:48:05 +000012823 if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
12824 return NULL;
12825 new = PyDict_New();
12826 if (!new)
12827 return NULL;
12828 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012829 int x_kind, y_kind, z_kind;
12830 void *x_data, *y_data, *z_data;
12831
Georg Brandlceee0772007-11-27 23:48:05 +000012832 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012833 if (!PyUnicode_Check(x)) {
12834 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12835 "be a string if there is a second argument");
12836 goto err;
12837 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012838 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012839 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12840 "arguments must have equal length");
12841 goto err;
12842 }
12843 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012844 x_kind = PyUnicode_KIND(x);
12845 y_kind = PyUnicode_KIND(y);
12846 x_data = PyUnicode_DATA(x);
12847 y_data = PyUnicode_DATA(y);
12848 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
12849 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012850 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000012851 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060012852 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012853 if (!value) {
12854 Py_DECREF(key);
12855 goto err;
12856 }
Georg Brandlceee0772007-11-27 23:48:05 +000012857 res = PyDict_SetItem(new, key, value);
12858 Py_DECREF(key);
12859 Py_DECREF(value);
12860 if (res < 0)
12861 goto err;
12862 }
12863 /* create entries for deleting chars in z */
12864 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012865 z_kind = PyUnicode_KIND(z);
12866 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012867 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012868 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012869 if (!key)
12870 goto err;
12871 res = PyDict_SetItem(new, key, Py_None);
12872 Py_DECREF(key);
12873 if (res < 0)
12874 goto err;
12875 }
12876 }
12877 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012878 int kind;
12879 void *data;
12880
Georg Brandlceee0772007-11-27 23:48:05 +000012881 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000012882 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012883 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
12884 "to maketrans it must be a dict");
12885 goto err;
12886 }
12887 /* copy entries into the new dict, converting string keys to int keys */
12888 while (PyDict_Next(x, &i, &key, &value)) {
12889 if (PyUnicode_Check(key)) {
12890 /* convert string keys to integer keys */
12891 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012892 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000012893 PyErr_SetString(PyExc_ValueError, "string keys in translate "
12894 "table must be of length 1");
12895 goto err;
12896 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012897 kind = PyUnicode_KIND(key);
12898 data = PyUnicode_DATA(key);
12899 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000012900 if (!newkey)
12901 goto err;
12902 res = PyDict_SetItem(new, newkey, value);
12903 Py_DECREF(newkey);
12904 if (res < 0)
12905 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000012906 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012907 /* just keep integer keys */
12908 if (PyDict_SetItem(new, key, value) < 0)
12909 goto err;
12910 } else {
12911 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
12912 "be strings or integers");
12913 goto err;
12914 }
12915 }
12916 }
12917 return new;
12918 err:
12919 Py_DECREF(new);
12920 return NULL;
12921}
12922
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012923PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012924 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012925\n\
12926Return a copy of the string S, where all characters have been mapped\n\
12927through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012928Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000012929Unmapped characters are left untouched. Characters mapped to None\n\
12930are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012931
12932static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012933unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012934{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012935 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012936}
12937
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012938PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012939 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012940\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012941Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012942
12943static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012944unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012945{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050012946 if (PyUnicode_READY(self) == -1)
12947 return NULL;
12948 if (PyUnicode_IS_ASCII(self))
12949 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012950 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012951}
12952
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012953PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012954 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012955\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000012956Pad a numeric string S with zeros on the left, to fill a field\n\
12957of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012958
12959static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012960unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012961{
Martin v. Löwis18e16552006-02-15 17:27:45 +000012962 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020012963 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012964 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012965 int kind;
12966 void *data;
12967 Py_UCS4 chr;
12968
Martin v. Löwis18e16552006-02-15 17:27:45 +000012969 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012970 return NULL;
12971
Benjamin Petersonbac79492012-01-14 13:34:47 -050012972 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012973 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012974
Victor Stinnerc4b49542011-12-11 22:44:26 +010012975 if (PyUnicode_GET_LENGTH(self) >= width)
12976 return unicode_result_unchanged(self);
12977
12978 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012979
12980 u = pad(self, fill, 0, '0');
12981
Walter Dörwald068325e2002-04-15 13:36:47 +000012982 if (u == NULL)
12983 return NULL;
12984
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012985 kind = PyUnicode_KIND(u);
12986 data = PyUnicode_DATA(u);
12987 chr = PyUnicode_READ(kind, data, fill);
12988
12989 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012990 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012991 PyUnicode_WRITE(kind, data, 0, chr);
12992 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000012993 }
12994
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012995 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010012996 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012997}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012998
12999#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013000static PyObject *
13001unicode__decimal2ascii(PyObject *self)
13002{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013003 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013004}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013005#endif
13006
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013007PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013008 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013009\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013010Return True if S starts with the specified prefix, False otherwise.\n\
13011With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013012With optional end, stop comparing S at that position.\n\
13013prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013014
13015static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013016unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013017 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013018{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013019 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013020 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013021 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013022 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013023 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013024
Jesus Ceaac451502011-04-20 17:09:23 +020013025 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013026 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013027 if (PyTuple_Check(subobj)) {
13028 Py_ssize_t i;
13029 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013030 substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013031 if (substring == NULL)
13032 return NULL;
13033 result = tailmatch(self, substring, start, end, -1);
13034 Py_DECREF(substring);
13035 if (result) {
13036 Py_RETURN_TRUE;
13037 }
13038 }
13039 /* nothing matched */
13040 Py_RETURN_FALSE;
13041 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013042 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030013043 if (substring == NULL) {
13044 if (PyErr_ExceptionMatches(PyExc_TypeError))
13045 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
13046 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013047 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013048 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013049 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013050 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013051 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013052}
13053
13054
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013055PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013056 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013057\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013058Return True if S ends with the specified suffix, False otherwise.\n\
13059With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013060With optional end, stop comparing S at that position.\n\
13061suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013062
13063static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013064unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013065 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013066{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013067 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013068 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013069 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013070 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013071 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013072
Jesus Ceaac451502011-04-20 17:09:23 +020013073 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013074 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013075 if (PyTuple_Check(subobj)) {
13076 Py_ssize_t i;
13077 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013078 substring = PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000013079 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013080 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000013081 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013082 result = tailmatch(self, substring, start, end, +1);
13083 Py_DECREF(substring);
13084 if (result) {
13085 Py_RETURN_TRUE;
13086 }
13087 }
13088 Py_RETURN_FALSE;
13089 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013090 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030013091 if (substring == NULL) {
13092 if (PyErr_ExceptionMatches(PyExc_TypeError))
13093 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
13094 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013095 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013096 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013097 result = tailmatch(self, substring, start, end, +1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013098 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013099 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013100}
13101
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013102#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000013103
13104PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013105 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013106\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013107Return a formatted version of S, using substitutions from args and kwargs.\n\
13108The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000013109
Eric Smith27bbca62010-11-04 17:06:58 +000013110PyDoc_STRVAR(format_map__doc__,
13111 "S.format_map(mapping) -> str\n\
13112\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013113Return a formatted version of S, using substitutions from mapping.\n\
13114The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000013115
Eric Smith4a7d76d2008-05-30 18:10:19 +000013116static PyObject *
13117unicode__format__(PyObject* self, PyObject* args)
13118{
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013119 PyObject *format_spec, *out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013120
13121 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
13122 return NULL;
13123
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013124 out = _PyUnicode_FormatAdvanced(self, format_spec, 0,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013125 PyUnicode_GET_LENGTH(format_spec));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013126 return out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013127}
13128
Eric Smith8c663262007-08-25 02:26:07 +000013129PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013130 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013131\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013132Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000013133
13134static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013135unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013136{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013137 Py_ssize_t size;
13138
13139 /* If it's a compact object, account for base structure +
13140 character data. */
13141 if (PyUnicode_IS_COMPACT_ASCII(v))
13142 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
13143 else if (PyUnicode_IS_COMPACT(v))
13144 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013145 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013146 else {
13147 /* If it is a two-block object, account for base object, and
13148 for character block if present. */
13149 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020013150 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013151 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013152 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013153 }
13154 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013155 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020013156 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013157 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020013158 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020013159 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013160
13161 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013162}
13163
13164PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013165 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013166
13167static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020013168unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013169{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013170 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013171 if (!copy)
13172 return NULL;
13173 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013174}
13175
Guido van Rossumd57fd912000-03-10 22:53:23 +000013176static PyMethodDef unicode_methods[] = {
13177
13178 /* Order is according to common usage: often used methods should
13179 appear first, since lookup is done sequentially. */
13180
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000013181 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013182 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013183 {"split", (PyCFunction) unicode_split, METH_VARARGS | METH_KEYWORDS, split__doc__},
13184 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS | METH_KEYWORDS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013185 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
13186 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
Benjamin Petersond5890c82012-01-14 13:23:30 -050013187 {"casefold", (PyCFunction) unicode_casefold, METH_NOARGS, casefold__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013188 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
13189 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
13190 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
13191 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
13192 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013193 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013194 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
13195 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
13196 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013197 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013198 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13199 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
13200 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013201 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013202 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010013203 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013204 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013205 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
13206 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
13207 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
13208 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13209 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
13210 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
13211 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
13212 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
13213 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
13214 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
13215 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
13216 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
13217 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
13218 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000013219 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000013220 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013221 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000013222 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013223 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000013224 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Georg Brandlceee0772007-11-27 23:48:05 +000013225 {"maketrans", (PyCFunction) unicode_maketrans,
13226 METH_VARARGS | METH_STATIC, maketrans__doc__},
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013227 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000013228#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013229 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013230 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013231#endif
13232
Benjamin Peterson14339b62009-01-31 16:36:08 +000013233 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013234 {NULL, NULL}
13235};
13236
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013237static PyObject *
13238unicode_mod(PyObject *v, PyObject *w)
13239{
Brian Curtindfc80e32011-08-10 20:28:54 -050013240 if (!PyUnicode_Check(v))
13241 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013242 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013243}
13244
13245static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013246 0, /*nb_add*/
13247 0, /*nb_subtract*/
13248 0, /*nb_multiply*/
13249 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013250};
13251
Guido van Rossumd57fd912000-03-10 22:53:23 +000013252static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013253 (lenfunc) unicode_length, /* sq_length */
13254 PyUnicode_Concat, /* sq_concat */
13255 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13256 (ssizeargfunc) unicode_getitem, /* sq_item */
13257 0, /* sq_slice */
13258 0, /* sq_ass_item */
13259 0, /* sq_ass_slice */
13260 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013261};
13262
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013263static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013264unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013265{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013266 if (PyUnicode_READY(self) == -1)
13267 return NULL;
13268
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013269 if (PyIndex_Check(item)) {
13270 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013271 if (i == -1 && PyErr_Occurred())
13272 return NULL;
13273 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013274 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013275 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013276 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013277 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013278 PyObject *result;
13279 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013280 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013281 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013282
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013283 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013284 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013285 return NULL;
13286 }
13287
13288 if (slicelength <= 0) {
Victor Stinner382955f2011-12-11 21:44:00 +010013289 Py_INCREF(unicode_empty);
13290 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013291 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013292 slicelength == PyUnicode_GET_LENGTH(self)) {
13293 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013294 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013295 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013296 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013297 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013298 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013299 src_kind = PyUnicode_KIND(self);
13300 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013301 if (!PyUnicode_IS_ASCII(self)) {
13302 kind_limit = kind_maxchar_limit(src_kind);
13303 max_char = 0;
13304 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13305 ch = PyUnicode_READ(src_kind, src_data, cur);
13306 if (ch > max_char) {
13307 max_char = ch;
13308 if (max_char >= kind_limit)
13309 break;
13310 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013311 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013312 }
Victor Stinner55c99112011-10-13 01:17:06 +020013313 else
13314 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013315 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013316 if (result == NULL)
13317 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013318 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013319 dest_data = PyUnicode_DATA(result);
13320
13321 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013322 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13323 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013324 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013325 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013326 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013327 } else {
13328 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13329 return NULL;
13330 }
13331}
13332
13333static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013334 (lenfunc)unicode_length, /* mp_length */
13335 (binaryfunc)unicode_subscript, /* mp_subscript */
13336 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013337};
13338
Guido van Rossumd57fd912000-03-10 22:53:23 +000013339
Guido van Rossumd57fd912000-03-10 22:53:23 +000013340/* Helpers for PyUnicode_Format() */
13341
13342static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +000013343getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013344{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013345 Py_ssize_t argidx = *p_argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013346 if (argidx < arglen) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013347 (*p_argidx)++;
13348 if (arglen < 0)
13349 return args;
13350 else
13351 return PyTuple_GetItem(args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013352 }
13353 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013354 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013355 return NULL;
13356}
13357
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013358/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013359
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013360static PyObject *
13361formatfloat(PyObject *v, int flags, int prec, int type)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013362{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013363 char *p;
13364 PyObject *result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013365 double x;
Tim Petersced69f82003-09-16 20:30:58 +000013366
Guido van Rossumd57fd912000-03-10 22:53:23 +000013367 x = PyFloat_AsDouble(v);
13368 if (x == -1.0 && PyErr_Occurred())
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013369 return NULL;
13370
Guido van Rossumd57fd912000-03-10 22:53:23 +000013371 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013372 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013373
Eric Smith0923d1d2009-04-16 20:16:10 +000013374 p = PyOS_double_to_string(x, type, prec,
13375 (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013376 if (p == NULL)
13377 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013378 result = PyUnicode_DecodeASCII(p, strlen(p), NULL);
Eric Smith0923d1d2009-04-16 20:16:10 +000013379 PyMem_Free(p);
13380 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013381}
13382
Tim Peters38fd5b62000-09-21 05:43:11 +000013383static PyObject*
13384formatlong(PyObject *val, int flags, int prec, int type)
13385{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013386 char *buf;
13387 int len;
13388 PyObject *str; /* temporary string object. */
13389 PyObject *result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013390
Benjamin Peterson14339b62009-01-31 16:36:08 +000013391 str = _PyBytes_FormatLong(val, flags, prec, type, &buf, &len);
13392 if (!str)
13393 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013394 result = PyUnicode_DecodeASCII(buf, len, NULL);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013395 Py_DECREF(str);
13396 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013397}
13398
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013399static Py_UCS4
13400formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013401{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013402 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013403 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013404 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013405 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000013406 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013407 goto onError;
13408 }
13409 else {
13410 /* Integer input truncated to a character */
13411 long x;
13412 x = PyLong_AsLong(v);
13413 if (x == -1 && PyErr_Occurred())
13414 goto onError;
13415
Victor Stinner8faf8212011-12-08 22:14:11 +010013416 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013417 PyErr_SetString(PyExc_OverflowError,
13418 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013419 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013420 }
13421
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013422 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013423 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013424
Benjamin Peterson29060642009-01-31 22:14:21 +000013425 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013426 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013427 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013428 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013429}
13430
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013431static int
13432repeat_accumulate(_PyAccu *acc, PyObject *obj, Py_ssize_t count)
13433{
13434 int r;
13435 assert(count > 0);
13436 assert(PyUnicode_Check(obj));
13437 if (count > 5) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013438 PyObject *repeated = unicode_repeat(obj, count);
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013439 if (repeated == NULL)
13440 return -1;
13441 r = _PyAccu_Accumulate(acc, repeated);
13442 Py_DECREF(repeated);
13443 return r;
13444 }
13445 else {
13446 do {
13447 if (_PyAccu_Accumulate(acc, obj))
13448 return -1;
13449 } while (--count);
13450 return 0;
13451 }
13452}
13453
Alexander Belopolsky40018472011-02-26 01:02:56 +000013454PyObject *
13455PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013456{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013457 void *fmt;
13458 int fmtkind;
13459 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013460 int kind;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013461 int r;
13462 Py_ssize_t fmtcnt, fmtpos, arglen, argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013463 int args_owned = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013464 PyObject *dict = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013465 PyObject *temp = NULL;
13466 PyObject *second = NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013467 PyObject *uformat;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013468 _PyAccu acc;
13469 static PyObject *plus, *minus, *blank, *zero, *percent;
13470
13471 if (!plus && !(plus = get_latin1_char('+')))
13472 return NULL;
13473 if (!minus && !(minus = get_latin1_char('-')))
13474 return NULL;
13475 if (!blank && !(blank = get_latin1_char(' ')))
13476 return NULL;
13477 if (!zero && !(zero = get_latin1_char('0')))
13478 return NULL;
13479 if (!percent && !(percent = get_latin1_char('%')))
13480 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000013481
Guido van Rossumd57fd912000-03-10 22:53:23 +000013482 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013483 PyErr_BadInternalCall();
13484 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013485 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013486 uformat = PyUnicode_FromObject(format);
Benjamin Peterson22a29702012-01-02 09:00:30 -060013487 if (uformat == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000013488 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060013489 if (PyUnicode_READY(uformat) == -1)
13490 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013491 if (_PyAccu_Init(&acc))
13492 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013493 fmt = PyUnicode_DATA(uformat);
13494 fmtkind = PyUnicode_KIND(uformat);
13495 fmtcnt = PyUnicode_GET_LENGTH(uformat);
13496 fmtpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013497
Guido van Rossumd57fd912000-03-10 22:53:23 +000013498 if (PyTuple_Check(args)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013499 arglen = PyTuple_Size(args);
13500 argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013501 }
13502 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013503 arglen = -1;
13504 argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013505 }
Christian Heimes90aa7642007-12-19 02:45:37 +000013506 if (Py_TYPE(args)->tp_as_mapping && !PyTuple_Check(args) &&
Christian Heimesf3863112007-11-22 07:46:41 +000013507 !PyUnicode_Check(args))
Benjamin Peterson29060642009-01-31 22:14:21 +000013508 dict = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013509
13510 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013511 if (PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013512 PyObject *nonfmt;
13513 Py_ssize_t nonfmtpos;
13514 nonfmtpos = fmtpos++;
13515 while (fmtcnt >= 0 &&
13516 PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
13517 fmtpos++;
13518 fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013519 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010013520 nonfmt = PyUnicode_Substring(uformat, nonfmtpos, fmtpos);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013521 if (nonfmt == NULL)
13522 goto onError;
13523 r = _PyAccu_Accumulate(&acc, nonfmt);
13524 Py_DECREF(nonfmt);
13525 if (r)
13526 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013527 }
13528 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013529 /* Got a format specifier */
13530 int flags = 0;
13531 Py_ssize_t width = -1;
13532 int prec = -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013533 Py_UCS4 c = '\0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013534 Py_UCS4 fill, sign;
Benjamin Peterson29060642009-01-31 22:14:21 +000013535 int isnumok;
13536 PyObject *v = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013537 void *pbuf = NULL;
13538 Py_ssize_t pindex, len;
13539 PyObject *signobj = NULL, *fillobj = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013540
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013541 fmtpos++;
13542 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(') {
13543 Py_ssize_t keystart;
Benjamin Peterson29060642009-01-31 22:14:21 +000013544 Py_ssize_t keylen;
13545 PyObject *key;
13546 int pcount = 1;
Christian Heimesa612dc02008-02-24 13:08:18 +000013547
Benjamin Peterson29060642009-01-31 22:14:21 +000013548 if (dict == NULL) {
13549 PyErr_SetString(PyExc_TypeError,
13550 "format requires a mapping");
13551 goto onError;
13552 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013553 ++fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013554 --fmtcnt;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013555 keystart = fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013556 /* Skip over balanced parentheses */
13557 while (pcount > 0 && --fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013558 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == ')')
Benjamin Peterson29060642009-01-31 22:14:21 +000013559 --pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013560 else if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(')
Benjamin Peterson29060642009-01-31 22:14:21 +000013561 ++pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013562 fmtpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013563 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013564 keylen = fmtpos - keystart - 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013565 if (fmtcnt < 0 || pcount > 0) {
13566 PyErr_SetString(PyExc_ValueError,
13567 "incomplete format key");
13568 goto onError;
13569 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010013570 key = PyUnicode_Substring(uformat,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013571 keystart, keystart + keylen);
Benjamin Peterson29060642009-01-31 22:14:21 +000013572 if (key == NULL)
13573 goto onError;
13574 if (args_owned) {
13575 Py_DECREF(args);
13576 args_owned = 0;
13577 }
13578 args = PyObject_GetItem(dict, key);
13579 Py_DECREF(key);
13580 if (args == NULL) {
13581 goto onError;
13582 }
13583 args_owned = 1;
13584 arglen = -1;
13585 argidx = -2;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013586 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013587 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013588 switch (c = PyUnicode_READ(fmtkind, fmt, fmtpos++)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013589 case '-': flags |= F_LJUST; continue;
13590 case '+': flags |= F_SIGN; continue;
13591 case ' ': flags |= F_BLANK; continue;
13592 case '#': flags |= F_ALT; continue;
13593 case '0': flags |= F_ZERO; continue;
13594 }
13595 break;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013596 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013597 if (c == '*') {
13598 v = getnextarg(args, arglen, &argidx);
13599 if (v == NULL)
13600 goto onError;
13601 if (!PyLong_Check(v)) {
13602 PyErr_SetString(PyExc_TypeError,
13603 "* wants int");
13604 goto onError;
13605 }
13606 width = PyLong_AsLong(v);
13607 if (width == -1 && PyErr_Occurred())
13608 goto onError;
13609 if (width < 0) {
13610 flags |= F_LJUST;
13611 width = -width;
13612 }
13613 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013614 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013615 }
13616 else if (c >= '0' && c <= '9') {
13617 width = c - '0';
13618 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013619 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013620 if (c < '0' || c > '9')
13621 break;
13622 if ((width*10) / 10 != width) {
13623 PyErr_SetString(PyExc_ValueError,
13624 "width too big");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013625 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013626 }
13627 width = width*10 + (c - '0');
13628 }
13629 }
13630 if (c == '.') {
13631 prec = 0;
13632 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013633 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013634 if (c == '*') {
13635 v = getnextarg(args, arglen, &argidx);
13636 if (v == NULL)
13637 goto onError;
13638 if (!PyLong_Check(v)) {
13639 PyErr_SetString(PyExc_TypeError,
13640 "* wants int");
13641 goto onError;
13642 }
13643 prec = PyLong_AsLong(v);
13644 if (prec == -1 && PyErr_Occurred())
13645 goto onError;
13646 if (prec < 0)
13647 prec = 0;
13648 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013649 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013650 }
13651 else if (c >= '0' && c <= '9') {
13652 prec = c - '0';
13653 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013654 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013655 if (c < '0' || c > '9')
13656 break;
13657 if ((prec*10) / 10 != prec) {
13658 PyErr_SetString(PyExc_ValueError,
13659 "prec too big");
13660 goto onError;
13661 }
13662 prec = prec*10 + (c - '0');
13663 }
13664 }
13665 } /* prec */
13666 if (fmtcnt >= 0) {
13667 if (c == 'h' || c == 'l' || c == 'L') {
13668 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013669 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013670 }
13671 }
13672 if (fmtcnt < 0) {
13673 PyErr_SetString(PyExc_ValueError,
13674 "incomplete format");
13675 goto onError;
13676 }
13677 if (c != '%') {
13678 v = getnextarg(args, arglen, &argidx);
13679 if (v == NULL)
13680 goto onError;
13681 }
13682 sign = 0;
13683 fill = ' ';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013684 fillobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013685 switch (c) {
13686
13687 case '%':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013688 _PyAccu_Accumulate(&acc, percent);
13689 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +000013690
13691 case 's':
13692 case 'r':
13693 case 'a':
Victor Stinner808fc0a2010-03-22 12:50:40 +000013694 if (PyUnicode_CheckExact(v) && c == 's') {
Benjamin Peterson29060642009-01-31 22:14:21 +000013695 temp = v;
13696 Py_INCREF(temp);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013697 }
13698 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013699 if (c == 's')
13700 temp = PyObject_Str(v);
13701 else if (c == 'r')
13702 temp = PyObject_Repr(v);
13703 else
13704 temp = PyObject_ASCII(v);
13705 if (temp == NULL)
13706 goto onError;
13707 if (PyUnicode_Check(temp))
13708 /* nothing to do */;
13709 else {
13710 Py_DECREF(temp);
13711 PyErr_SetString(PyExc_TypeError,
13712 "%s argument has non-string str()");
13713 goto onError;
13714 }
13715 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013716 if (PyUnicode_READY(temp) == -1) {
13717 Py_CLEAR(temp);
13718 goto onError;
13719 }
13720 pbuf = PyUnicode_DATA(temp);
13721 kind = PyUnicode_KIND(temp);
13722 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013723 if (prec >= 0 && len > prec)
13724 len = prec;
13725 break;
13726
13727 case 'i':
13728 case 'd':
13729 case 'u':
13730 case 'o':
13731 case 'x':
13732 case 'X':
Benjamin Peterson29060642009-01-31 22:14:21 +000013733 isnumok = 0;
13734 if (PyNumber_Check(v)) {
13735 PyObject *iobj=NULL;
13736
13737 if (PyLong_Check(v)) {
13738 iobj = v;
13739 Py_INCREF(iobj);
13740 }
13741 else {
13742 iobj = PyNumber_Long(v);
13743 }
13744 if (iobj!=NULL) {
13745 if (PyLong_Check(iobj)) {
13746 isnumok = 1;
Senthil Kumaran9ebe08d2011-07-03 21:03:16 -070013747 temp = formatlong(iobj, flags, prec, (c == 'i'? 'd': c));
Benjamin Peterson29060642009-01-31 22:14:21 +000013748 Py_DECREF(iobj);
13749 if (!temp)
13750 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013751 if (PyUnicode_READY(temp) == -1) {
13752 Py_CLEAR(temp);
13753 goto onError;
13754 }
13755 pbuf = PyUnicode_DATA(temp);
13756 kind = PyUnicode_KIND(temp);
13757 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013758 sign = 1;
13759 }
13760 else {
13761 Py_DECREF(iobj);
13762 }
13763 }
13764 }
13765 if (!isnumok) {
13766 PyErr_Format(PyExc_TypeError,
13767 "%%%c format: a number is required, "
13768 "not %.200s", (char)c, Py_TYPE(v)->tp_name);
13769 goto onError;
13770 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013771 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013772 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013773 fillobj = zero;
13774 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013775 break;
13776
13777 case 'e':
13778 case 'E':
13779 case 'f':
13780 case 'F':
13781 case 'g':
13782 case 'G':
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013783 temp = formatfloat(v, flags, prec, c);
13784 if (!temp)
Benjamin Peterson29060642009-01-31 22:14:21 +000013785 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013786 if (PyUnicode_READY(temp) == -1) {
13787 Py_CLEAR(temp);
13788 goto onError;
13789 }
13790 pbuf = PyUnicode_DATA(temp);
13791 kind = PyUnicode_KIND(temp);
13792 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013793 sign = 1;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013794 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013795 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013796 fillobj = zero;
13797 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013798 break;
13799
13800 case 'c':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013801 {
13802 Py_UCS4 ch = formatchar(v);
13803 if (ch == (Py_UCS4) -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013804 goto onError;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013805 temp = _PyUnicode_FromUCS4(&ch, 1);
13806 if (temp == NULL)
13807 goto onError;
13808 pbuf = PyUnicode_DATA(temp);
13809 kind = PyUnicode_KIND(temp);
13810 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013811 break;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013812 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013813
13814 default:
13815 PyErr_Format(PyExc_ValueError,
13816 "unsupported format character '%c' (0x%x) "
13817 "at index %zd",
13818 (31<=c && c<=126) ? (char)c : '?',
13819 (int)c,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013820 fmtpos - 1);
Benjamin Peterson29060642009-01-31 22:14:21 +000013821 goto onError;
13822 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013823 /* pbuf is initialized here. */
13824 pindex = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +000013825 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013826 if (PyUnicode_READ(kind, pbuf, pindex) == '-') {
13827 signobj = minus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013828 len--;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013829 pindex++;
13830 }
13831 else if (PyUnicode_READ(kind, pbuf, pindex) == '+') {
13832 signobj = plus;
13833 len--;
13834 pindex++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013835 }
13836 else if (flags & F_SIGN)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013837 signobj = plus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013838 else if (flags & F_BLANK)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013839 signobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013840 else
13841 sign = 0;
13842 }
13843 if (width < len)
13844 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013845 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013846 if (fill != ' ') {
13847 assert(signobj != NULL);
13848 if (_PyAccu_Accumulate(&acc, signobj))
13849 goto onError;
13850 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013851 if (width > len)
13852 width--;
13853 }
13854 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013855 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013856 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == c);
Benjamin Peterson29060642009-01-31 22:14:21 +000013857 if (fill != ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013858 second = get_latin1_char(
13859 PyUnicode_READ(kind, pbuf, pindex + 1));
13860 pindex += 2;
13861 if (second == NULL ||
13862 _PyAccu_Accumulate(&acc, zero) ||
13863 _PyAccu_Accumulate(&acc, second))
13864 goto onError;
13865 Py_CLEAR(second);
Benjamin Peterson29060642009-01-31 22:14:21 +000013866 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013867 width -= 2;
13868 if (width < 0)
13869 width = 0;
13870 len -= 2;
13871 }
13872 if (width > len && !(flags & F_LJUST)) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013873 assert(fillobj != NULL);
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013874 if (repeat_accumulate(&acc, fillobj, width - len))
13875 goto onError;
13876 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013877 }
13878 if (fill == ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013879 if (sign) {
13880 assert(signobj != NULL);
13881 if (_PyAccu_Accumulate(&acc, signobj))
13882 goto onError;
13883 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013884 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013885 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
13886 assert(PyUnicode_READ(kind, pbuf, pindex+1) == c);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013887 second = get_latin1_char(
13888 PyUnicode_READ(kind, pbuf, pindex + 1));
13889 pindex += 2;
13890 if (second == NULL ||
13891 _PyAccu_Accumulate(&acc, zero) ||
13892 _PyAccu_Accumulate(&acc, second))
13893 goto onError;
13894 Py_CLEAR(second);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013895 }
13896 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013897 /* Copy all characters, preserving len */
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013898 if (temp != NULL) {
13899 assert(pbuf == PyUnicode_DATA(temp));
13900 v = PyUnicode_Substring(temp, pindex, pindex + len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013901 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013902 else {
13903 const char *p = (const char *) pbuf;
13904 assert(pbuf != NULL);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013905 p += kind * pindex;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013906 v = PyUnicode_FromKindAndData(kind, p, len);
13907 }
13908 if (v == NULL)
13909 goto onError;
13910 r = _PyAccu_Accumulate(&acc, v);
13911 Py_DECREF(v);
13912 if (r)
13913 goto onError;
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013914 if (width > len && repeat_accumulate(&acc, blank, width - len))
13915 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013916 if (dict && (argidx < arglen) && c != '%') {
13917 PyErr_SetString(PyExc_TypeError,
13918 "not all arguments converted during string formatting");
Benjamin Peterson29060642009-01-31 22:14:21 +000013919 goto onError;
13920 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013921 Py_CLEAR(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013922 } /* '%' */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013923 } /* until end */
13924 if (argidx < arglen && !dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013925 PyErr_SetString(PyExc_TypeError,
13926 "not all arguments converted during string formatting");
13927 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013928 }
13929
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013930 result = _PyAccu_Finish(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013931 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013932 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013933 }
13934 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013935 Py_XDECREF(temp);
13936 Py_XDECREF(second);
Victor Stinner7931d9a2011-11-04 00:22:48 +010013937 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013938
Benjamin Peterson29060642009-01-31 22:14:21 +000013939 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013940 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013941 Py_XDECREF(temp);
13942 Py_XDECREF(second);
13943 _PyAccu_Destroy(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013944 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013945 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013946 }
13947 return NULL;
13948}
13949
Jeremy Hylton938ace62002-07-17 16:30:39 +000013950static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000013951unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
13952
Tim Peters6d6c1a32001-08-02 04:15:00 +000013953static PyObject *
13954unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13955{
Benjamin Peterson29060642009-01-31 22:14:21 +000013956 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013957 static char *kwlist[] = {"object", "encoding", "errors", 0};
13958 char *encoding = NULL;
13959 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000013960
Benjamin Peterson14339b62009-01-31 16:36:08 +000013961 if (type != &PyUnicode_Type)
13962 return unicode_subtype_new(type, args, kwds);
13963 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000013964 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000013965 return NULL;
Victor Stinner382955f2011-12-11 21:44:00 +010013966 if (x == NULL) {
13967 Py_INCREF(unicode_empty);
13968 return unicode_empty;
13969 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000013970 if (encoding == NULL && errors == NULL)
13971 return PyObject_Str(x);
13972 else
Benjamin Peterson29060642009-01-31 22:14:21 +000013973 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000013974}
13975
Guido van Rossume023fe02001-08-30 03:12:59 +000013976static PyObject *
13977unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13978{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013979 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013980 Py_ssize_t length, char_size;
13981 int share_wstr, share_utf8;
13982 unsigned int kind;
13983 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000013984
Benjamin Peterson14339b62009-01-31 16:36:08 +000013985 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013986
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013987 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013988 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013989 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020013990 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050013991 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060013992 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013993 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060013994 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013995
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013996 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013997 if (self == NULL) {
13998 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013999 return NULL;
14000 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014001 kind = PyUnicode_KIND(unicode);
14002 length = PyUnicode_GET_LENGTH(unicode);
14003
14004 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014005#ifdef Py_DEBUG
14006 _PyUnicode_HASH(self) = -1;
14007#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014008 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014009#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014010 _PyUnicode_STATE(self).interned = 0;
14011 _PyUnicode_STATE(self).kind = kind;
14012 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020014013 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014014 _PyUnicode_STATE(self).ready = 1;
14015 _PyUnicode_WSTR(self) = NULL;
14016 _PyUnicode_UTF8_LENGTH(self) = 0;
14017 _PyUnicode_UTF8(self) = NULL;
14018 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020014019 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014020
14021 share_utf8 = 0;
14022 share_wstr = 0;
14023 if (kind == PyUnicode_1BYTE_KIND) {
14024 char_size = 1;
14025 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
14026 share_utf8 = 1;
14027 }
14028 else if (kind == PyUnicode_2BYTE_KIND) {
14029 char_size = 2;
14030 if (sizeof(wchar_t) == 2)
14031 share_wstr = 1;
14032 }
14033 else {
14034 assert(kind == PyUnicode_4BYTE_KIND);
14035 char_size = 4;
14036 if (sizeof(wchar_t) == 4)
14037 share_wstr = 1;
14038 }
14039
14040 /* Ensure we won't overflow the length. */
14041 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
14042 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014043 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014044 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014045 data = PyObject_MALLOC((length + 1) * char_size);
14046 if (data == NULL) {
14047 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014048 goto onError;
14049 }
14050
Victor Stinnerc3c74152011-10-02 20:39:55 +020014051 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014052 if (share_utf8) {
14053 _PyUnicode_UTF8_LENGTH(self) = length;
14054 _PyUnicode_UTF8(self) = data;
14055 }
14056 if (share_wstr) {
14057 _PyUnicode_WSTR_LENGTH(self) = length;
14058 _PyUnicode_WSTR(self) = (wchar_t *)data;
14059 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014060
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014061 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020014062 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020014063 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014064#ifdef Py_DEBUG
14065 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
14066#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020014067 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010014068 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014069
14070onError:
14071 Py_DECREF(unicode);
14072 Py_DECREF(self);
14073 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000014074}
14075
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000014076PyDoc_STRVAR(unicode_doc,
Benjamin Peterson29060642009-01-31 22:14:21 +000014077 "str(string[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000014078\n\
Collin Winterd474ce82007-08-07 19:42:11 +000014079Create a new string object from the given encoded string.\n\
Skip Montanaro35b37a52002-07-26 16:22:46 +000014080encoding defaults to the current default string encoding.\n\
14081errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000014082
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014083static PyObject *unicode_iter(PyObject *seq);
14084
Guido van Rossumd57fd912000-03-10 22:53:23 +000014085PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000014086 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014087 "str", /* tp_name */
14088 sizeof(PyUnicodeObject), /* tp_size */
14089 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014090 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014091 (destructor)unicode_dealloc, /* tp_dealloc */
14092 0, /* tp_print */
14093 0, /* tp_getattr */
14094 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014095 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014096 unicode_repr, /* tp_repr */
14097 &unicode_as_number, /* tp_as_number */
14098 &unicode_as_sequence, /* tp_as_sequence */
14099 &unicode_as_mapping, /* tp_as_mapping */
14100 (hashfunc) unicode_hash, /* tp_hash*/
14101 0, /* tp_call*/
14102 (reprfunc) unicode_str, /* tp_str */
14103 PyObject_GenericGetAttr, /* tp_getattro */
14104 0, /* tp_setattro */
14105 0, /* tp_as_buffer */
14106 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000014107 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014108 unicode_doc, /* tp_doc */
14109 0, /* tp_traverse */
14110 0, /* tp_clear */
14111 PyUnicode_RichCompare, /* tp_richcompare */
14112 0, /* tp_weaklistoffset */
14113 unicode_iter, /* tp_iter */
14114 0, /* tp_iternext */
14115 unicode_methods, /* tp_methods */
14116 0, /* tp_members */
14117 0, /* tp_getset */
14118 &PyBaseObject_Type, /* tp_base */
14119 0, /* tp_dict */
14120 0, /* tp_descr_get */
14121 0, /* tp_descr_set */
14122 0, /* tp_dictoffset */
14123 0, /* tp_init */
14124 0, /* tp_alloc */
14125 unicode_new, /* tp_new */
14126 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014127};
14128
14129/* Initialize the Unicode implementation */
14130
Victor Stinner3a50e702011-10-18 21:21:00 +020014131int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014132{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014133 int i;
14134
Thomas Wouters477c8d52006-05-27 19:21:47 +000014135 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014136 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000014137 0x000A, /* LINE FEED */
14138 0x000D, /* CARRIAGE RETURN */
14139 0x001C, /* FILE SEPARATOR */
14140 0x001D, /* GROUP SEPARATOR */
14141 0x001E, /* RECORD SEPARATOR */
14142 0x0085, /* NEXT LINE */
14143 0x2028, /* LINE SEPARATOR */
14144 0x2029, /* PARAGRAPH SEPARATOR */
14145 };
14146
Fred Drakee4315f52000-05-09 19:53:39 +000014147 /* Init the implementation */
Victor Stinnera464fc12011-10-02 20:39:30 +020014148 unicode_empty = PyUnicode_New(0, 0);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014149 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014150 Py_FatalError("Can't create empty string");
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010014151 assert(_PyUnicode_CheckConsistency(unicode_empty, 1));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014152
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014153 for (i = 0; i < 256; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +000014154 unicode_latin1[i] = NULL;
Guido van Rossumcacfc072002-05-24 19:01:59 +000014155 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014156 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000014157
14158 /* initialize the linebreak bloom filter */
14159 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014160 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020014161 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014162
14163 PyType_Ready(&EncodingMapType);
Victor Stinner3a50e702011-10-18 21:21:00 +020014164
14165#ifdef HAVE_MBCS
14166 winver.dwOSVersionInfoSize = sizeof(winver);
14167 if (!GetVersionEx((OSVERSIONINFO*)&winver)) {
14168 PyErr_SetFromWindowsErr(0);
14169 return -1;
14170 }
14171#endif
14172 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014173}
14174
14175/* Finalize the Unicode implementation */
14176
Christian Heimesa156e092008-02-16 07:38:31 +000014177int
14178PyUnicode_ClearFreeList(void)
14179{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014180 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000014181}
14182
Guido van Rossumd57fd912000-03-10 22:53:23 +000014183void
Thomas Wouters78890102000-07-22 19:25:51 +000014184_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014185{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014186 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014187
Guido van Rossum4ae8ef82000-10-03 18:09:04 +000014188 Py_XDECREF(unicode_empty);
14189 unicode_empty = NULL;
Barry Warsaw5b4c2282000-10-03 20:45:26 +000014190
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014191 for (i = 0; i < 256; i++) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014192 if (unicode_latin1[i]) {
14193 Py_DECREF(unicode_latin1[i]);
14194 unicode_latin1[i] = NULL;
14195 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014196 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020014197 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000014198 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000014199}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000014200
Walter Dörwald16807132007-05-25 13:52:07 +000014201void
14202PyUnicode_InternInPlace(PyObject **p)
14203{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014204 register PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014205 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020014206#ifdef Py_DEBUG
14207 assert(s != NULL);
14208 assert(_PyUnicode_CHECK(s));
14209#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000014210 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020014211 return;
14212#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000014213 /* If it's a subclass, we don't really know what putting
14214 it in the interned dict might do. */
14215 if (!PyUnicode_CheckExact(s))
14216 return;
14217 if (PyUnicode_CHECK_INTERNED(s))
14218 return;
14219 if (interned == NULL) {
14220 interned = PyDict_New();
14221 if (interned == NULL) {
14222 PyErr_Clear(); /* Don't leave an exception */
14223 return;
14224 }
14225 }
14226 /* It might be that the GetItem call fails even
14227 though the key is present in the dictionary,
14228 namely when this happens during a stack overflow. */
14229 Py_ALLOW_RECURSION
Victor Stinner7931d9a2011-11-04 00:22:48 +010014230 t = PyDict_GetItem(interned, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014231 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000014232
Benjamin Peterson29060642009-01-31 22:14:21 +000014233 if (t) {
14234 Py_INCREF(t);
14235 Py_DECREF(*p);
14236 *p = t;
14237 return;
14238 }
Walter Dörwald16807132007-05-25 13:52:07 +000014239
Benjamin Peterson14339b62009-01-31 16:36:08 +000014240 PyThreadState_GET()->recursion_critical = 1;
Victor Stinner7931d9a2011-11-04 00:22:48 +010014241 if (PyDict_SetItem(interned, s, s) < 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014242 PyErr_Clear();
14243 PyThreadState_GET()->recursion_critical = 0;
14244 return;
14245 }
14246 PyThreadState_GET()->recursion_critical = 0;
14247 /* The two references in interned are not counted by refcnt.
14248 The deallocator will take care of this */
14249 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014250 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000014251}
14252
14253void
14254PyUnicode_InternImmortal(PyObject **p)
14255{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014256 PyUnicode_InternInPlace(p);
14257 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020014258 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014259 Py_INCREF(*p);
14260 }
Walter Dörwald16807132007-05-25 13:52:07 +000014261}
14262
14263PyObject *
14264PyUnicode_InternFromString(const char *cp)
14265{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014266 PyObject *s = PyUnicode_FromString(cp);
14267 if (s == NULL)
14268 return NULL;
14269 PyUnicode_InternInPlace(&s);
14270 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000014271}
14272
Alexander Belopolsky40018472011-02-26 01:02:56 +000014273void
14274_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000014275{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014276 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014277 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014278 Py_ssize_t i, n;
14279 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000014280
Benjamin Peterson14339b62009-01-31 16:36:08 +000014281 if (interned == NULL || !PyDict_Check(interned))
14282 return;
14283 keys = PyDict_Keys(interned);
14284 if (keys == NULL || !PyList_Check(keys)) {
14285 PyErr_Clear();
14286 return;
14287 }
Walter Dörwald16807132007-05-25 13:52:07 +000014288
Benjamin Peterson14339b62009-01-31 16:36:08 +000014289 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
14290 detector, interned unicode strings are not forcibly deallocated;
14291 rather, we give them their stolen references back, and then clear
14292 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000014293
Benjamin Peterson14339b62009-01-31 16:36:08 +000014294 n = PyList_GET_SIZE(keys);
14295 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000014296 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014297 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014298 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014299 if (PyUnicode_READY(s) == -1) {
14300 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014301 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014302 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014303 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014304 case SSTATE_NOT_INTERNED:
14305 /* XXX Shouldn't happen */
14306 break;
14307 case SSTATE_INTERNED_IMMORTAL:
14308 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014309 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014310 break;
14311 case SSTATE_INTERNED_MORTAL:
14312 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014313 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014314 break;
14315 default:
14316 Py_FatalError("Inconsistent interned string state.");
14317 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014318 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014319 }
14320 fprintf(stderr, "total size of all interned strings: "
14321 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
14322 "mortal/immortal\n", mortal_size, immortal_size);
14323 Py_DECREF(keys);
14324 PyDict_Clear(interned);
14325 Py_DECREF(interned);
14326 interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +000014327}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014328
14329
14330/********************* Unicode Iterator **************************/
14331
14332typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014333 PyObject_HEAD
14334 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014335 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014336} unicodeiterobject;
14337
14338static void
14339unicodeiter_dealloc(unicodeiterobject *it)
14340{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014341 _PyObject_GC_UNTRACK(it);
14342 Py_XDECREF(it->it_seq);
14343 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014344}
14345
14346static int
14347unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
14348{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014349 Py_VISIT(it->it_seq);
14350 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014351}
14352
14353static PyObject *
14354unicodeiter_next(unicodeiterobject *it)
14355{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014356 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014357
Benjamin Peterson14339b62009-01-31 16:36:08 +000014358 assert(it != NULL);
14359 seq = it->it_seq;
14360 if (seq == NULL)
14361 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014362 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014363
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014364 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
14365 int kind = PyUnicode_KIND(seq);
14366 void *data = PyUnicode_DATA(seq);
14367 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
14368 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014369 if (item != NULL)
14370 ++it->it_index;
14371 return item;
14372 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014373
Benjamin Peterson14339b62009-01-31 16:36:08 +000014374 Py_DECREF(seq);
14375 it->it_seq = NULL;
14376 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014377}
14378
14379static PyObject *
14380unicodeiter_len(unicodeiterobject *it)
14381{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014382 Py_ssize_t len = 0;
14383 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020014384 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014385 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014386}
14387
14388PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
14389
14390static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014391 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000014392 length_hint_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000014393 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014394};
14395
14396PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014397 PyVarObject_HEAD_INIT(&PyType_Type, 0)
14398 "str_iterator", /* tp_name */
14399 sizeof(unicodeiterobject), /* tp_basicsize */
14400 0, /* tp_itemsize */
14401 /* methods */
14402 (destructor)unicodeiter_dealloc, /* tp_dealloc */
14403 0, /* tp_print */
14404 0, /* tp_getattr */
14405 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014406 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014407 0, /* tp_repr */
14408 0, /* tp_as_number */
14409 0, /* tp_as_sequence */
14410 0, /* tp_as_mapping */
14411 0, /* tp_hash */
14412 0, /* tp_call */
14413 0, /* tp_str */
14414 PyObject_GenericGetAttr, /* tp_getattro */
14415 0, /* tp_setattro */
14416 0, /* tp_as_buffer */
14417 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
14418 0, /* tp_doc */
14419 (traverseproc)unicodeiter_traverse, /* tp_traverse */
14420 0, /* tp_clear */
14421 0, /* tp_richcompare */
14422 0, /* tp_weaklistoffset */
14423 PyObject_SelfIter, /* tp_iter */
14424 (iternextfunc)unicodeiter_next, /* tp_iternext */
14425 unicodeiter_methods, /* tp_methods */
14426 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014427};
14428
14429static PyObject *
14430unicode_iter(PyObject *seq)
14431{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014432 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014433
Benjamin Peterson14339b62009-01-31 16:36:08 +000014434 if (!PyUnicode_Check(seq)) {
14435 PyErr_BadInternalCall();
14436 return NULL;
14437 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014438 if (PyUnicode_READY(seq) == -1)
14439 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014440 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
14441 if (it == NULL)
14442 return NULL;
14443 it->it_index = 0;
14444 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014445 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014446 _PyObject_GC_TRACK(it);
14447 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014448}
14449
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010014450
14451size_t
14452Py_UNICODE_strlen(const Py_UNICODE *u)
14453{
14454 int res = 0;
14455 while(*u++)
14456 res++;
14457 return res;
14458}
14459
14460Py_UNICODE*
14461Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
14462{
14463 Py_UNICODE *u = s1;
14464 while ((*u++ = *s2++));
14465 return s1;
14466}
14467
14468Py_UNICODE*
14469Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14470{
14471 Py_UNICODE *u = s1;
14472 while ((*u++ = *s2++))
14473 if (n-- == 0)
14474 break;
14475 return s1;
14476}
14477
14478Py_UNICODE*
14479Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
14480{
14481 Py_UNICODE *u1 = s1;
14482 u1 += Py_UNICODE_strlen(u1);
14483 Py_UNICODE_strcpy(u1, s2);
14484 return s1;
14485}
14486
14487int
14488Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
14489{
14490 while (*s1 && *s2 && *s1 == *s2)
14491 s1++, s2++;
14492 if (*s1 && *s2)
14493 return (*s1 < *s2) ? -1 : +1;
14494 if (*s1)
14495 return 1;
14496 if (*s2)
14497 return -1;
14498 return 0;
14499}
14500
14501int
14502Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14503{
14504 register Py_UNICODE u1, u2;
14505 for (; n != 0; n--) {
14506 u1 = *s1;
14507 u2 = *s2;
14508 if (u1 != u2)
14509 return (u1 < u2) ? -1 : +1;
14510 if (u1 == '\0')
14511 return 0;
14512 s1++;
14513 s2++;
14514 }
14515 return 0;
14516}
14517
14518Py_UNICODE*
14519Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
14520{
14521 const Py_UNICODE *p;
14522 for (p = s; *p; p++)
14523 if (*p == c)
14524 return (Py_UNICODE*)p;
14525 return NULL;
14526}
14527
14528Py_UNICODE*
14529Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
14530{
14531 const Py_UNICODE *p;
14532 p = s + Py_UNICODE_strlen(s);
14533 while (p != s) {
14534 p--;
14535 if (*p == c)
14536 return (Py_UNICODE*)p;
14537 }
14538 return NULL;
14539}
Victor Stinner331ea922010-08-10 16:37:20 +000014540
Victor Stinner71133ff2010-09-01 23:43:53 +000014541Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014542PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000014543{
Victor Stinner577db2c2011-10-11 22:12:48 +020014544 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014545 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000014546
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014547 if (!PyUnicode_Check(unicode)) {
14548 PyErr_BadArgument();
14549 return NULL;
14550 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014551 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020014552 if (u == NULL)
14553 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000014554 /* Ensure we won't overflow the size. */
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014555 if (len > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000014556 PyErr_NoMemory();
14557 return NULL;
14558 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014559 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000014560 size *= sizeof(Py_UNICODE);
14561 copy = PyMem_Malloc(size);
14562 if (copy == NULL) {
14563 PyErr_NoMemory();
14564 return NULL;
14565 }
Victor Stinner577db2c2011-10-11 22:12:48 +020014566 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000014567 return copy;
14568}
Martin v. Löwis5b222132007-06-10 09:51:05 +000014569
Georg Brandl66c221e2010-10-14 07:04:07 +000014570/* A _string module, to export formatter_parser and formatter_field_name_split
14571 to the string.Formatter class implemented in Python. */
14572
14573static PyMethodDef _string_methods[] = {
14574 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
14575 METH_O, PyDoc_STR("split the argument as a field name")},
14576 {"formatter_parser", (PyCFunction) formatter_parser,
14577 METH_O, PyDoc_STR("parse the argument as a format string")},
14578 {NULL, NULL}
14579};
14580
14581static struct PyModuleDef _string_module = {
14582 PyModuleDef_HEAD_INIT,
14583 "_string",
14584 PyDoc_STR("string helper module"),
14585 0,
14586 _string_methods,
14587 NULL,
14588 NULL,
14589 NULL,
14590 NULL
14591};
14592
14593PyMODINIT_FUNC
14594PyInit__string(void)
14595{
14596 return PyModule_Create(&_string_module);
14597}
14598
14599
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014600#ifdef __cplusplus
14601}
14602#endif