blob: 8522a74b08aeaa224d05634668f1e74121027524 [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
Benjamin Peterson0df54292012-03-26 14:50:32 -04001823/* Internal function, doesn't check maximum character */
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001824
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{
3938 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003939 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003940 return -1;
3941 }
Victor Stinner488fa492011-12-12 00:01:39 +01003942 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01003943 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003944 PyErr_SetString(PyExc_IndexError, "string index out of range");
3945 return -1;
3946 }
Victor Stinner488fa492011-12-12 00:01:39 +01003947 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02003948 return -1;
Victor Stinnerc9590ad2012-03-04 01:34:37 +01003949 if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
3950 PyErr_SetString(PyExc_ValueError, "character out of range");
3951 return -1;
3952 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003953 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
3954 index, ch);
3955 return 0;
3956}
3957
Alexander Belopolsky40018472011-02-26 01:02:56 +00003958const char *
3959PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00003960{
Victor Stinner42cb4622010-09-01 19:39:01 +00003961 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00003962}
3963
Victor Stinner554f3f02010-06-16 23:33:54 +00003964/* create or adjust a UnicodeDecodeError */
3965static void
3966make_decode_exception(PyObject **exceptionObject,
3967 const char *encoding,
3968 const char *input, Py_ssize_t length,
3969 Py_ssize_t startpos, Py_ssize_t endpos,
3970 const char *reason)
3971{
3972 if (*exceptionObject == NULL) {
3973 *exceptionObject = PyUnicodeDecodeError_Create(
3974 encoding, input, length, startpos, endpos, reason);
3975 }
3976 else {
3977 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
3978 goto onError;
3979 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
3980 goto onError;
3981 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
3982 goto onError;
3983 }
3984 return;
3985
3986onError:
3987 Py_DECREF(*exceptionObject);
3988 *exceptionObject = NULL;
3989}
3990
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003991/* error handling callback helper:
3992 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00003993 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003994 and adjust various state variables.
3995 return 0 on success, -1 on error
3996*/
3997
Alexander Belopolsky40018472011-02-26 01:02:56 +00003998static int
3999unicode_decode_call_errorhandler(const char *errors, PyObject **errorHandler,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004000 const char *encoding, const char *reason,
4001 const char **input, const char **inend, Py_ssize_t *startinpos,
4002 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004003 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004004{
Benjamin Peterson142957c2008-07-04 19:55:29 +00004005 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004006
4007 PyObject *restuple = NULL;
4008 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01004009 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004010 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004011 Py_ssize_t requiredsize;
4012 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004013 PyObject *inputobj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004014 int res = -1;
4015
Victor Stinner596a6c42011-11-09 00:02:18 +01004016 if (_PyUnicode_KIND(*output) != PyUnicode_WCHAR_KIND)
4017 outsize = PyUnicode_GET_LENGTH(*output);
4018 else
4019 outsize = _PyUnicode_WSTR_LENGTH(*output);
4020
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004021 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004022 *errorHandler = PyCodec_LookupError(errors);
4023 if (*errorHandler == NULL)
4024 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004025 }
4026
Victor Stinner554f3f02010-06-16 23:33:54 +00004027 make_decode_exception(exceptionObject,
4028 encoding,
4029 *input, *inend - *input,
4030 *startinpos, *endinpos,
4031 reason);
4032 if (*exceptionObject == NULL)
4033 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004034
4035 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4036 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004037 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004038 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00004039 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004040 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004041 }
4042 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004043 goto onError;
Benjamin Petersonbac79492012-01-14 13:34:47 -05004044 if (PyUnicode_READY(repunicode) == -1)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004045 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004046
4047 /* Copy back the bytes variables, which might have been modified by the
4048 callback */
4049 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4050 if (!inputobj)
4051 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00004052 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004053 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00004054 }
Christian Heimes72b710a2008-05-26 13:28:38 +00004055 *input = PyBytes_AS_STRING(inputobj);
4056 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004057 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00004058 /* we can DECREF safely, as the exception has another reference,
4059 so the object won't go away. */
4060 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004061
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004062 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004063 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004064 if (newpos<0 || newpos>insize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004065 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
4066 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004067 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004068
Victor Stinner596a6c42011-11-09 00:02:18 +01004069 if (_PyUnicode_KIND(*output) != PyUnicode_WCHAR_KIND) {
4070 /* need more space? (at least enough for what we
4071 have+the replacement+the rest of the string (starting
4072 at the new input position), so we won't have to check space
4073 when there are no errors in the rest of the string) */
4074 Py_ssize_t replen = PyUnicode_GET_LENGTH(repunicode);
4075 requiredsize = *outpos + replen + insize-newpos;
4076 if (requiredsize > outsize) {
4077 if (requiredsize<2*outsize)
4078 requiredsize = 2*outsize;
4079 if (unicode_resize(output, requiredsize) < 0)
4080 goto onError;
4081 }
4082 if (unicode_widen(output, PyUnicode_MAX_CHAR_VALUE(repunicode)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004083 goto onError;
Victor Stinner596a6c42011-11-09 00:02:18 +01004084 copy_characters(*output, *outpos, repunicode, 0, replen);
4085 *outpos += replen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004086 }
Victor Stinner596a6c42011-11-09 00:02:18 +01004087 else {
4088 wchar_t *repwstr;
4089 Py_ssize_t repwlen;
4090 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4091 if (repwstr == NULL)
4092 goto onError;
4093 /* need more space? (at least enough for what we
4094 have+the replacement+the rest of the string (starting
4095 at the new input position), so we won't have to check space
4096 when there are no errors in the rest of the string) */
4097 requiredsize = *outpos + repwlen + insize-newpos;
4098 if (requiredsize > outsize) {
4099 if (requiredsize < 2*outsize)
4100 requiredsize = 2*outsize;
4101 if (unicode_resize(output, requiredsize) < 0)
4102 goto onError;
4103 }
4104 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
4105 *outpos += repwlen;
4106 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004107 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004108 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004109
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004110 /* we made it! */
4111 res = 0;
4112
Benjamin Peterson29060642009-01-31 22:14:21 +00004113 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004114 Py_XDECREF(restuple);
4115 return res;
4116}
4117
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004118/* --- UTF-7 Codec -------------------------------------------------------- */
4119
Antoine Pitrou244651a2009-05-04 18:56:13 +00004120/* See RFC2152 for details. We encode conservatively and decode liberally. */
4121
4122/* Three simple macros defining base-64. */
4123
4124/* Is c a base-64 character? */
4125
4126#define IS_BASE64(c) \
4127 (((c) >= 'A' && (c) <= 'Z') || \
4128 ((c) >= 'a' && (c) <= 'z') || \
4129 ((c) >= '0' && (c) <= '9') || \
4130 (c) == '+' || (c) == '/')
4131
4132/* given that c is a base-64 character, what is its base-64 value? */
4133
4134#define FROM_BASE64(c) \
4135 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4136 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4137 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4138 (c) == '+' ? 62 : 63)
4139
4140/* What is the base-64 character of the bottom 6 bits of n? */
4141
4142#define TO_BASE64(n) \
4143 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4144
4145/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4146 * decoded as itself. We are permissive on decoding; the only ASCII
4147 * byte not decoding to itself is the + which begins a base64
4148 * string. */
4149
4150#define DECODE_DIRECT(c) \
4151 ((c) <= 127 && (c) != '+')
4152
4153/* The UTF-7 encoder treats ASCII characters differently according to
4154 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4155 * the above). See RFC2152. This array identifies these different
4156 * sets:
4157 * 0 : "Set D"
4158 * alphanumeric and '(),-./:?
4159 * 1 : "Set O"
4160 * !"#$%&*;<=>@[]^_`{|}
4161 * 2 : "whitespace"
4162 * ht nl cr sp
4163 * 3 : special (must be base64 encoded)
4164 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4165 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004166
Tim Petersced69f82003-09-16 20:30:58 +00004167static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004168char utf7_category[128] = {
4169/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4170 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4171/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4172 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4173/* sp ! " # $ % & ' ( ) * + , - . / */
4174 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4175/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4176 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4177/* @ A B C D E F G H I J K L M N O */
4178 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4179/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4180 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4181/* ` a b c d e f g h i j k l m n o */
4182 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4183/* p q r s t u v w x y z { | } ~ del */
4184 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004185};
4186
Antoine Pitrou244651a2009-05-04 18:56:13 +00004187/* ENCODE_DIRECT: this character should be encoded as itself. The
4188 * answer depends on whether we are encoding set O as itself, and also
4189 * on whether we are encoding whitespace as itself. RFC2152 makes it
4190 * clear that the answers to these questions vary between
4191 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004192
Antoine Pitrou244651a2009-05-04 18:56:13 +00004193#define ENCODE_DIRECT(c, directO, directWS) \
4194 ((c) < 128 && (c) > 0 && \
4195 ((utf7_category[(c)] == 0) || \
4196 (directWS && (utf7_category[(c)] == 2)) || \
4197 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004198
Alexander Belopolsky40018472011-02-26 01:02:56 +00004199PyObject *
4200PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004201 Py_ssize_t size,
4202 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004203{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004204 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4205}
4206
Antoine Pitrou244651a2009-05-04 18:56:13 +00004207/* The decoder. The only state we preserve is our read position,
4208 * i.e. how many characters we have consumed. So if we end in the
4209 * middle of a shift sequence we have to back off the read position
4210 * and the output to the beginning of the sequence, otherwise we lose
4211 * all the shift state (seen bits, number of bits seen, high
4212 * surrogate). */
4213
Alexander Belopolsky40018472011-02-26 01:02:56 +00004214PyObject *
4215PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004216 Py_ssize_t size,
4217 const char *errors,
4218 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004219{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004220 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004221 Py_ssize_t startinpos;
4222 Py_ssize_t endinpos;
4223 Py_ssize_t outpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004224 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004225 PyObject *unicode;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004226 const char *errmsg = "";
4227 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004228 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004229 unsigned int base64bits = 0;
4230 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004231 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004232 PyObject *errorHandler = NULL;
4233 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004234
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004235 /* Start off assuming it's all ASCII. Widen later as necessary. */
4236 unicode = PyUnicode_New(size, 127);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004237 if (!unicode)
4238 return NULL;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004239 if (size == 0) {
4240 if (consumed)
4241 *consumed = 0;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004242 return unicode;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004243 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004244
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004245 shiftOutStart = outpos = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004246 e = s + size;
4247
4248 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004249 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004250 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004251 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004252
Antoine Pitrou244651a2009-05-04 18:56:13 +00004253 if (inShift) { /* in a base-64 section */
4254 if (IS_BASE64(ch)) { /* consume a base-64 character */
4255 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4256 base64bits += 6;
4257 s++;
4258 if (base64bits >= 16) {
4259 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004260 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004261 base64bits -= 16;
4262 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
4263 if (surrogate) {
4264 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004265 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4266 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004267 if (unicode_putchar(&unicode, &outpos, ch2) < 0)
4268 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004269 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004270 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004271 }
4272 else {
Antoine Pitrou78edf752011-11-15 01:44:16 +01004273 if (unicode_putchar(&unicode, &outpos, surrogate) < 0)
4274 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004275 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004276 }
4277 }
Victor Stinner551ac952011-11-29 22:58:13 +01004278 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004279 /* first surrogate */
4280 surrogate = outCh;
4281 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004282 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004283 if (unicode_putchar(&unicode, &outpos, outCh) < 0)
4284 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004285 }
4286 }
4287 }
4288 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004289 inShift = 0;
4290 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004291 if (surrogate) {
Antoine Pitrou78edf752011-11-15 01:44:16 +01004292 if (unicode_putchar(&unicode, &outpos, surrogate) < 0)
4293 goto onError;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004294 surrogate = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004295 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004296 if (base64bits > 0) { /* left-over bits */
4297 if (base64bits >= 6) {
4298 /* We've seen at least one base-64 character */
4299 errmsg = "partial character in shift sequence";
4300 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004301 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004302 else {
4303 /* Some bits remain; they should be zero */
4304 if (base64buffer != 0) {
4305 errmsg = "non-zero padding bits in shift sequence";
4306 goto utf7Error;
4307 }
4308 }
4309 }
4310 if (ch != '-') {
4311 /* '-' is absorbed; other terminating
4312 characters are preserved */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004313 if (unicode_putchar(&unicode, &outpos, ch) < 0)
4314 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004315 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004316 }
4317 }
4318 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004319 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004320 s++; /* consume '+' */
4321 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004322 s++;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004323 if (unicode_putchar(&unicode, &outpos, '+') < 0)
4324 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004325 }
4326 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004327 inShift = 1;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004328 shiftOutStart = outpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004329 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004330 }
4331 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004332 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004333 if (unicode_putchar(&unicode, &outpos, ch) < 0)
4334 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004335 s++;
4336 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004337 else {
4338 startinpos = s-starts;
4339 s++;
4340 errmsg = "unexpected special character";
4341 goto utf7Error;
4342 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004343 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004344utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004345 endinpos = s-starts;
4346 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00004347 errors, &errorHandler,
4348 "utf7", errmsg,
4349 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004350 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004351 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004352 }
4353
Antoine Pitrou244651a2009-05-04 18:56:13 +00004354 /* end of string */
4355
4356 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4357 /* if we're in an inconsistent state, that's an error */
4358 if (surrogate ||
4359 (base64bits >= 6) ||
4360 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004361 endinpos = size;
4362 if (unicode_decode_call_errorhandler(
4363 errors, &errorHandler,
4364 "utf7", "unterminated shift sequence",
4365 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004366 &unicode, &outpos))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004367 goto onError;
4368 if (s < e)
4369 goto restart;
4370 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004371 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004372
4373 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004374 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004375 if (inShift) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004376 outpos = shiftOutStart; /* back off output */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004377 *consumed = startinpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004378 }
4379 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004380 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004381 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004382 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004383
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004384 if (unicode_resize(&unicode, outpos) < 0)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004385 goto onError;
4386
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004387 Py_XDECREF(errorHandler);
4388 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01004389 return unicode_result(unicode);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004390
Benjamin Peterson29060642009-01-31 22:14:21 +00004391 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004392 Py_XDECREF(errorHandler);
4393 Py_XDECREF(exc);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004394 Py_DECREF(unicode);
4395 return NULL;
4396}
4397
4398
Alexander Belopolsky40018472011-02-26 01:02:56 +00004399PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004400_PyUnicode_EncodeUTF7(PyObject *str,
4401 int base64SetO,
4402 int base64WhiteSpace,
4403 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004404{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004405 int kind;
4406 void *data;
4407 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004408 PyObject *v;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004409 Py_ssize_t allocated;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004410 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004411 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004412 unsigned int base64bits = 0;
4413 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004414 char * out;
4415 char * start;
4416
Benjamin Petersonbac79492012-01-14 13:34:47 -05004417 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004418 return NULL;
4419 kind = PyUnicode_KIND(str);
4420 data = PyUnicode_DATA(str);
4421 len = PyUnicode_GET_LENGTH(str);
4422
4423 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004424 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004425
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004426 /* It might be possible to tighten this worst case */
4427 allocated = 8 * len;
4428 if (allocated / 8 != len)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004429 return PyErr_NoMemory();
4430
Antoine Pitrou244651a2009-05-04 18:56:13 +00004431 v = PyBytes_FromStringAndSize(NULL, allocated);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004432 if (v == NULL)
4433 return NULL;
4434
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004435 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004436 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004437 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004438
Antoine Pitrou244651a2009-05-04 18:56:13 +00004439 if (inShift) {
4440 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4441 /* shifting out */
4442 if (base64bits) { /* output remaining bits */
4443 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4444 base64buffer = 0;
4445 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004446 }
4447 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004448 /* Characters not in the BASE64 set implicitly unshift the sequence
4449 so no '-' is required, except if the character is itself a '-' */
4450 if (IS_BASE64(ch) || ch == '-') {
4451 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004452 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004453 *out++ = (char) ch;
4454 }
4455 else {
4456 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004457 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004458 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004459 else { /* not in a shift sequence */
4460 if (ch == '+') {
4461 *out++ = '+';
4462 *out++ = '-';
4463 }
4464 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4465 *out++ = (char) ch;
4466 }
4467 else {
4468 *out++ = '+';
4469 inShift = 1;
4470 goto encode_char;
4471 }
4472 }
4473 continue;
4474encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004475 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004476 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004477
Antoine Pitrou244651a2009-05-04 18:56:13 +00004478 /* code first surrogate */
4479 base64bits += 16;
4480 base64buffer = (base64buffer << 16) | 0xd800 | ((ch-0x10000) >> 10);
4481 while (base64bits >= 6) {
4482 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4483 base64bits -= 6;
4484 }
4485 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004486 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004487 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004488 base64bits += 16;
4489 base64buffer = (base64buffer << 16) | ch;
4490 while (base64bits >= 6) {
4491 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4492 base64bits -= 6;
4493 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004494 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004495 if (base64bits)
4496 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4497 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004498 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004499 if (_PyBytes_Resize(&v, out - start) < 0)
4500 return NULL;
4501 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004502}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004503PyObject *
4504PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4505 Py_ssize_t size,
4506 int base64SetO,
4507 int base64WhiteSpace,
4508 const char *errors)
4509{
4510 PyObject *result;
4511 PyObject *tmp = PyUnicode_FromUnicode(s, size);
4512 if (tmp == NULL)
4513 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004514 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004515 base64WhiteSpace, errors);
4516 Py_DECREF(tmp);
4517 return result;
4518}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004519
Antoine Pitrou244651a2009-05-04 18:56:13 +00004520#undef IS_BASE64
4521#undef FROM_BASE64
4522#undef TO_BASE64
4523#undef DECODE_DIRECT
4524#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004525
Guido van Rossumd57fd912000-03-10 22:53:23 +00004526/* --- UTF-8 Codec -------------------------------------------------------- */
4527
Tim Petersced69f82003-09-16 20:30:58 +00004528static
Guido van Rossumd57fd912000-03-10 22:53:23 +00004529char utf8_code_length[256] = {
Ezio Melotti57221d02010-07-01 07:32:02 +00004530 /* Map UTF-8 encoded prefix byte to sequence length. Zero means
4531 illegal prefix. See RFC 3629 for details */
4532 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 00-0F */
4533 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Victor Stinner4a2b7a12010-08-13 14:03:48 +00004534 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Guido van Rossumd57fd912000-03-10 22:53:23 +00004535 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4536 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,
Ezio Melotti57221d02010-07-01 07:32:02 +00004539 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 70-7F */
4540 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 +00004541 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4542 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
Ezio Melotti57221d02010-07-01 07:32:02 +00004543 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* B0-BF */
4544 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* C0-C1 + C2-CF */
4545 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* D0-DF */
4546 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* E0-EF */
4547 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 +00004548};
4549
Alexander Belopolsky40018472011-02-26 01:02:56 +00004550PyObject *
4551PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004552 Py_ssize_t size,
4553 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004554{
Walter Dörwald69652032004-09-07 20:24:22 +00004555 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4556}
4557
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004558#include "stringlib/ucs1lib.h"
4559#include "stringlib/codecs.h"
4560#include "stringlib/undef.h"
4561
4562#include "stringlib/ucs2lib.h"
4563#include "stringlib/codecs.h"
4564#include "stringlib/undef.h"
4565
4566#include "stringlib/ucs4lib.h"
4567#include "stringlib/codecs.h"
4568#include "stringlib/undef.h"
4569
Antoine Pitrouab868312009-01-10 15:40:25 +00004570/* Mask to check or force alignment of a pointer to C 'long' boundaries */
4571#define LONG_PTR_MASK (size_t) (SIZEOF_LONG - 1)
4572
4573/* Mask to quickly check whether a C 'long' contains a
4574 non-ASCII, UTF8-encoded char. */
4575#if (SIZEOF_LONG == 8)
4576# define ASCII_CHAR_MASK 0x8080808080808080L
4577#elif (SIZEOF_LONG == 4)
4578# define ASCII_CHAR_MASK 0x80808080L
4579#else
4580# error C 'long' size should be either 4 or 8!
4581#endif
4582
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004583/* Scans a UTF-8 string and returns the maximum character to be expected
4584 and the size of the decoded unicode string.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004585
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004586 This function doesn't check for errors, these checks are performed in
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004587 PyUnicode_DecodeUTF8Stateful.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004588 */
4589static Py_UCS4
Victor Stinnera1d12bb2011-12-11 21:53:09 +01004590utf8_scanner(const unsigned char *p, Py_ssize_t string_size, Py_ssize_t *unicode_size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004591{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004592 Py_ssize_t char_count = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004593 const unsigned char *end = p + string_size;
4594 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004595
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004596 assert(unicode_size != NULL);
4597
4598 /* By having a cascade of independent loops which fallback onto each
4599 other, we minimize the amount of work done in the average loop
4600 iteration, and we also maximize the CPU's ability to predict
4601 branches correctly (because a given condition will have always the
4602 same boolean outcome except perhaps in the last iteration of the
4603 corresponding loop).
4604 In the general case this brings us rather close to decoding
4605 performance pre-PEP 393, despite the two-pass decoding.
4606
4607 Note that the pure ASCII loop is not duplicated once a non-ASCII
4608 character has been encountered. It is actually a pessimization (by
4609 a significant factor) to use this loop on text with many non-ASCII
4610 characters, and it is important to avoid bad performance on valid
4611 utf-8 data (invalid utf-8 being a different can of worms).
4612 */
4613
4614 /* ASCII */
4615 for (; p < end; ++p) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004616 /* Only check value if it's not a ASCII char... */
4617 if (*p < 0x80) {
4618 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
4619 an explanation. */
4620 if (!((size_t) p & LONG_PTR_MASK)) {
4621 /* Help register allocation */
4622 register const unsigned char *_p = p;
4623 while (_p < aligned_end) {
4624 unsigned long value = *(unsigned long *) _p;
4625 if (value & ASCII_CHAR_MASK)
4626 break;
4627 _p += SIZEOF_LONG;
4628 char_count += SIZEOF_LONG;
4629 }
4630 p = _p;
4631 if (p == end)
4632 break;
4633 }
4634 }
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004635 if (*p < 0x80)
4636 ++char_count;
4637 else
4638 goto _ucs1loop;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004639 }
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004640 *unicode_size = char_count;
4641 return 127;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004642
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004643_ucs1loop:
4644 for (; p < end; ++p) {
4645 if (*p < 0xc4)
4646 char_count += ((*p & 0xc0) != 0x80);
4647 else
4648 goto _ucs2loop;
4649 }
4650 *unicode_size = char_count;
4651 return 255;
4652
4653_ucs2loop:
4654 for (; p < end; ++p) {
4655 if (*p < 0xf0)
4656 char_count += ((*p & 0xc0) != 0x80);
4657 else
4658 goto _ucs4loop;
4659 }
4660 *unicode_size = char_count;
4661 return 65535;
4662
4663_ucs4loop:
4664 for (; p < end; ++p) {
4665 char_count += ((*p & 0xc0) != 0x80);
4666 }
4667 *unicode_size = char_count;
4668 return 65537;
4669}
4670
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004671/* Similar to PyUnicode_WRITE but may attempt to widen and resize the string
Victor Stinner785938e2011-12-11 20:09:03 +01004672 in case of errors. Implicit parameters: unicode, kind, data, onError.
4673 Potential resizing overallocates, so the result needs to shrink at the end.
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004674*/
Victor Stinner785938e2011-12-11 20:09:03 +01004675#define WRITE_MAYBE_FAIL(index, value) \
4676 do { \
4677 Py_ssize_t pos = index; \
4678 if (pos > PyUnicode_GET_LENGTH(unicode) && \
4679 unicode_resize(&unicode, pos + pos/8) < 0) \
4680 goto onError; \
4681 if (unicode_putchar(&unicode, &pos, value) < 0) \
4682 goto onError; \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004683 } while (0)
4684
Victor Stinnerbf6e5602011-12-12 01:53:47 +01004685static PyObject *
Victor Stinner785938e2011-12-11 20:09:03 +01004686decode_utf8_errors(const char *starts,
4687 Py_ssize_t size,
4688 const char *errors,
4689 Py_ssize_t *consumed,
4690 const char *s,
4691 PyObject *unicode,
4692 Py_ssize_t i)
Walter Dörwald69652032004-09-07 20:24:22 +00004693{
Guido van Rossumd57fd912000-03-10 22:53:23 +00004694 int n;
Ezio Melotti57221d02010-07-01 07:32:02 +00004695 int k;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004696 Py_ssize_t startinpos;
4697 Py_ssize_t endinpos;
Victor Stinner785938e2011-12-11 20:09:03 +01004698 const char *e = starts + size;
4699 const char *aligned_end;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004700 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004701 PyObject *errorHandler = NULL;
4702 PyObject *exc = NULL;
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004703
Antoine Pitrouab868312009-01-10 15:40:25 +00004704 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004705
4706 while (s < e) {
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004707 Py_UCS4 ch = (unsigned char)*s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004708
4709 if (ch < 0x80) {
Antoine Pitrouab868312009-01-10 15:40:25 +00004710 /* Fast path for runs of ASCII characters. Given that common UTF-8
4711 input will consist of an overwhelming majority of ASCII
4712 characters, we try to optimize for this case by checking
4713 as many characters as a C 'long' can contain.
4714 First, check if we can do an aligned read, as most CPUs have
4715 a penalty for unaligned reads.
4716 */
4717 if (!((size_t) s & LONG_PTR_MASK)) {
4718 /* Help register allocation */
4719 register const char *_s = s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004720 register Py_ssize_t _i = i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004721 while (_s < aligned_end) {
4722 /* Read a whole long at a time (either 4 or 8 bytes),
4723 and do a fast unrolled copy if it only contains ASCII
4724 characters. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004725 unsigned long value = *(unsigned long *) _s;
4726 if (value & ASCII_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00004727 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004728 WRITE_MAYBE_FAIL(_i+0, _s[0]);
4729 WRITE_MAYBE_FAIL(_i+1, _s[1]);
4730 WRITE_MAYBE_FAIL(_i+2, _s[2]);
4731 WRITE_MAYBE_FAIL(_i+3, _s[3]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004732#if (SIZEOF_LONG == 8)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004733 WRITE_MAYBE_FAIL(_i+4, _s[4]);
4734 WRITE_MAYBE_FAIL(_i+5, _s[5]);
4735 WRITE_MAYBE_FAIL(_i+6, _s[6]);
4736 WRITE_MAYBE_FAIL(_i+7, _s[7]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004737#endif
4738 _s += SIZEOF_LONG;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004739 _i += SIZEOF_LONG;
Antoine Pitrouab868312009-01-10 15:40:25 +00004740 }
4741 s = _s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004742 i = _i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004743 if (s == e)
4744 break;
4745 ch = (unsigned char)*s;
4746 }
4747 }
4748
4749 if (ch < 0x80) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004750 WRITE_MAYBE_FAIL(i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004751 s++;
4752 continue;
4753 }
4754
4755 n = utf8_code_length[ch];
4756
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004757 if (s + n > e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004758 if (consumed)
4759 break;
4760 else {
4761 errmsg = "unexpected end of data";
4762 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004763 endinpos = startinpos+1;
4764 for (k=1; (k < size-startinpos) && ((s[k]&0xC0) == 0x80); k++)
4765 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004766 goto utf8Error;
4767 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00004768 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004769
4770 switch (n) {
4771
4772 case 0:
Ezio Melotti57221d02010-07-01 07:32:02 +00004773 errmsg = "invalid start byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004774 startinpos = s-starts;
4775 endinpos = startinpos+1;
4776 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004777
4778 case 1:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004779 errmsg = "internal error";
Benjamin Peterson29060642009-01-31 22:14:21 +00004780 startinpos = s-starts;
4781 endinpos = startinpos+1;
4782 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004783
4784 case 2:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004785 if ((s[1] & 0xc0) != 0x80) {
Ezio Melotti57221d02010-07-01 07:32:02 +00004786 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004787 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004788 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00004789 goto utf8Error;
4790 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004791 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004792 assert ((ch > 0x007F) && (ch <= 0x07FF));
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004793 WRITE_MAYBE_FAIL(i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004794 break;
4795
4796 case 3:
Ezio Melotti9bf2b3a2010-07-03 04:52:19 +00004797 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
4798 will result in surrogates in range d800-dfff. Surrogates are
4799 not valid UTF-8 so they are rejected.
4800 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
4801 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
Tim Petersced69f82003-09-16 20:30:58 +00004802 if ((s[1] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004803 (s[2] & 0xc0) != 0x80 ||
4804 ((unsigned char)s[0] == 0xE0 &&
4805 (unsigned char)s[1] < 0xA0) ||
4806 ((unsigned char)s[0] == 0xED &&
4807 (unsigned char)s[1] > 0x9F)) {
4808 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004809 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004810 endinpos = startinpos + 1;
4811
4812 /* if s[1] first two bits are 1 and 0, then the invalid
4813 continuation byte is s[2], so increment endinpos by 1,
4814 if not, s[1] is invalid and endinpos doesn't need to
4815 be incremented. */
4816 if ((s[1] & 0xC0) == 0x80)
4817 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004818 goto utf8Error;
4819 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004820 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004821 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004822 WRITE_MAYBE_FAIL(i++, ch);
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004823 break;
4824
4825 case 4:
4826 if ((s[1] & 0xc0) != 0x80 ||
4827 (s[2] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004828 (s[3] & 0xc0) != 0x80 ||
4829 ((unsigned char)s[0] == 0xF0 &&
4830 (unsigned char)s[1] < 0x90) ||
4831 ((unsigned char)s[0] == 0xF4 &&
4832 (unsigned char)s[1] > 0x8F)) {
4833 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004834 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004835 endinpos = startinpos + 1;
4836 if ((s[1] & 0xC0) == 0x80) {
4837 endinpos++;
4838 if ((s[2] & 0xC0) == 0x80)
4839 endinpos++;
4840 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004841 goto utf8Error;
4842 }
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004843 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
Ezio Melotti57221d02010-07-01 07:32:02 +00004844 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
Victor Stinner8faf8212011-12-08 22:14:11 +01004845 assert ((ch > 0xFFFF) && (ch <= MAX_UNICODE));
Ezio Melotti57221d02010-07-01 07:32:02 +00004846
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004847 WRITE_MAYBE_FAIL(i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004848 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004849 }
4850 s += n;
Benjamin Peterson29060642009-01-31 22:14:21 +00004851 continue;
Tim Petersced69f82003-09-16 20:30:58 +00004852
Benjamin Peterson29060642009-01-31 22:14:21 +00004853 utf8Error:
Benjamin Peterson29060642009-01-31 22:14:21 +00004854 if (unicode_decode_call_errorhandler(
4855 errors, &errorHandler,
Victor Stinnercbe01342012-02-14 01:17:45 +01004856 "utf-8", errmsg,
Benjamin Peterson29060642009-01-31 22:14:21 +00004857 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004858 &unicode, &i))
Benjamin Peterson29060642009-01-31 22:14:21 +00004859 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004860 /* Update data because unicode_decode_call_errorhandler might have
4861 re-created or resized the unicode object. */
Benjamin Peterson29060642009-01-31 22:14:21 +00004862 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004863 }
Walter Dörwald69652032004-09-07 20:24:22 +00004864 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00004865 *consumed = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004866
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004867 /* Adjust length and ready string when it contained errors and
4868 is of the old resizable kind. */
Victor Stinner785938e2011-12-11 20:09:03 +01004869 if (unicode_resize(&unicode, i) < 0)
4870 goto onError;
4871 unicode_adjust_maxchar(&unicode);
4872 if (unicode == NULL)
4873 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004874
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004875 Py_XDECREF(errorHandler);
4876 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02004877 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01004878 return unicode;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004879
Benjamin Peterson29060642009-01-31 22:14:21 +00004880 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004881 Py_XDECREF(errorHandler);
4882 Py_XDECREF(exc);
Victor Stinner785938e2011-12-11 20:09:03 +01004883 Py_XDECREF(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004884 return NULL;
4885}
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004886#undef WRITE_MAYBE_FAIL
Antoine Pitrouab868312009-01-10 15:40:25 +00004887
Victor Stinner785938e2011-12-11 20:09:03 +01004888PyObject *
4889PyUnicode_DecodeUTF8Stateful(const char *s,
4890 Py_ssize_t size,
4891 const char *errors,
4892 Py_ssize_t *consumed)
4893{
4894 Py_UCS4 maxchar = 0;
4895 Py_ssize_t unicode_size;
4896 int has_errors = 0;
4897 PyObject *unicode;
4898 int kind;
4899 void *data;
4900 const char *starts = s;
4901 const char *e;
4902 Py_ssize_t i;
4903
4904 if (size == 0) {
4905 if (consumed)
4906 *consumed = 0;
Victor Stinner382955f2011-12-11 21:44:00 +01004907 Py_INCREF(unicode_empty);
4908 return unicode_empty;
Victor Stinner785938e2011-12-11 20:09:03 +01004909 }
4910
Victor Stinnera1d12bb2011-12-11 21:53:09 +01004911 maxchar = utf8_scanner((const unsigned char *)s, size, &unicode_size);
Victor Stinner785938e2011-12-11 20:09:03 +01004912
4913 /* When the string is ASCII only, just use memcpy and return.
4914 unicode_size may be != size if there is an incomplete UTF-8
4915 sequence at the end of the ASCII block. */
4916 if (maxchar < 128 && size == unicode_size) {
4917 if (consumed)
4918 *consumed = size;
Victor Stinnerab870212011-12-17 22:39:43 +01004919 return unicode_fromascii((const unsigned char *)s, size);
Victor Stinner785938e2011-12-11 20:09:03 +01004920 }
4921
4922 unicode = PyUnicode_New(unicode_size, maxchar);
4923 if (!unicode)
4924 return NULL;
4925 kind = PyUnicode_KIND(unicode);
4926 data = PyUnicode_DATA(unicode);
4927
4928 /* Unpack UTF-8 encoded data */
4929 i = 0;
4930 e = starts + size;
4931 switch (kind) {
4932 case PyUnicode_1BYTE_KIND:
4933 has_errors = ucs1lib_utf8_try_decode(s, e, (Py_UCS1 *) data, &s, &i);
4934 break;
4935 case PyUnicode_2BYTE_KIND:
4936 has_errors = ucs2lib_utf8_try_decode(s, e, (Py_UCS2 *) data, &s, &i);
4937 break;
4938 case PyUnicode_4BYTE_KIND:
4939 has_errors = ucs4lib_utf8_try_decode(s, e, (Py_UCS4 *) data, &s, &i);
4940 break;
4941 }
4942 if (!has_errors) {
4943 /* Ensure the unicode size calculation was correct */
4944 assert(i == unicode_size);
4945 assert(s == e);
4946 if (consumed)
4947 *consumed = size;
4948 return unicode;
4949 }
4950
4951 /* In case of errors, maxchar and size computation might be incorrect;
4952 code below refits and resizes as necessary. */
4953 return decode_utf8_errors(starts, size, errors, consumed, s, unicode, i);
4954}
4955
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004956#ifdef __APPLE__
4957
4958/* Simplified UTF-8 decoder using surrogateescape error handler,
4959 used to decode the command line arguments on Mac OS X. */
4960
4961wchar_t*
4962_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4963{
4964 int n;
4965 const char *e;
4966 wchar_t *unicode, *p;
4967
4968 /* Note: size will always be longer than the resulting Unicode
4969 character count */
4970 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1)) {
4971 PyErr_NoMemory();
4972 return NULL;
4973 }
4974 unicode = PyMem_Malloc((size + 1) * sizeof(wchar_t));
4975 if (!unicode)
4976 return NULL;
4977
4978 /* Unpack UTF-8 encoded data */
4979 p = unicode;
4980 e = s + size;
4981 while (s < e) {
4982 Py_UCS4 ch = (unsigned char)*s;
4983
4984 if (ch < 0x80) {
4985 *p++ = (wchar_t)ch;
4986 s++;
4987 continue;
4988 }
4989
4990 n = utf8_code_length[ch];
4991 if (s + n > e) {
4992 goto surrogateescape;
4993 }
4994
4995 switch (n) {
4996 case 0:
4997 case 1:
4998 goto surrogateescape;
4999
5000 case 2:
5001 if ((s[1] & 0xc0) != 0x80)
5002 goto surrogateescape;
5003 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
5004 assert ((ch > 0x007F) && (ch <= 0x07FF));
5005 *p++ = (wchar_t)ch;
5006 break;
5007
5008 case 3:
5009 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
5010 will result in surrogates in range d800-dfff. Surrogates are
5011 not valid UTF-8 so they are rejected.
5012 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
5013 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
5014 if ((s[1] & 0xc0) != 0x80 ||
5015 (s[2] & 0xc0) != 0x80 ||
5016 ((unsigned char)s[0] == 0xE0 &&
5017 (unsigned char)s[1] < 0xA0) ||
5018 ((unsigned char)s[0] == 0xED &&
5019 (unsigned char)s[1] > 0x9F)) {
5020
5021 goto surrogateescape;
5022 }
5023 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
5024 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005025 *p++ = (wchar_t)ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005026 break;
5027
5028 case 4:
5029 if ((s[1] & 0xc0) != 0x80 ||
5030 (s[2] & 0xc0) != 0x80 ||
5031 (s[3] & 0xc0) != 0x80 ||
5032 ((unsigned char)s[0] == 0xF0 &&
5033 (unsigned char)s[1] < 0x90) ||
5034 ((unsigned char)s[0] == 0xF4 &&
5035 (unsigned char)s[1] > 0x8F)) {
5036 goto surrogateescape;
5037 }
5038 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
5039 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
Victor Stinner8faf8212011-12-08 22:14:11 +01005040 assert ((ch > 0xFFFF) && (ch <= MAX_UNICODE));
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005041
5042#if SIZEOF_WCHAR_T == 4
5043 *p++ = (wchar_t)ch;
5044#else
5045 /* compute and append the two surrogates: */
Victor Stinner551ac952011-11-29 22:58:13 +01005046 *p++ = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
5047 *p++ = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005048#endif
5049 break;
5050 }
5051 s += n;
5052 continue;
5053
5054 surrogateescape:
5055 *p++ = 0xDC00 + ch;
5056 s++;
5057 }
5058 *p = L'\0';
5059 return unicode;
5060}
5061
5062#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00005063
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005064/* Primary internal function which creates utf8 encoded bytes objects.
5065
5066 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00005067 and allocate exactly as much space needed at the end. Else allocate the
5068 maximum possible needed (4 result bytes per Unicode character), and return
5069 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00005070*/
Tim Peters7e3d9612002-04-21 03:26:37 +00005071PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01005072_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005073{
Victor Stinner6099a032011-12-18 14:22:26 +01005074 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005075 void *data;
5076 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00005077
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005078 if (!PyUnicode_Check(unicode)) {
5079 PyErr_BadArgument();
5080 return NULL;
5081 }
5082
5083 if (PyUnicode_READY(unicode) == -1)
5084 return NULL;
5085
Victor Stinnere90fe6a2011-10-01 16:48:13 +02005086 if (PyUnicode_UTF8(unicode))
5087 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
5088 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005089
5090 kind = PyUnicode_KIND(unicode);
5091 data = PyUnicode_DATA(unicode);
5092 size = PyUnicode_GET_LENGTH(unicode);
5093
Benjamin Petersonead6b532011-12-20 17:23:42 -06005094 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01005095 default:
5096 assert(0);
5097 case PyUnicode_1BYTE_KIND:
5098 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
5099 assert(!PyUnicode_IS_ASCII(unicode));
5100 return ucs1lib_utf8_encoder(unicode, data, size, errors);
5101 case PyUnicode_2BYTE_KIND:
5102 return ucs2lib_utf8_encoder(unicode, data, size, errors);
5103 case PyUnicode_4BYTE_KIND:
5104 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00005105 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005106}
5107
Alexander Belopolsky40018472011-02-26 01:02:56 +00005108PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005109PyUnicode_EncodeUTF8(const Py_UNICODE *s,
5110 Py_ssize_t size,
5111 const char *errors)
5112{
5113 PyObject *v, *unicode;
5114
5115 unicode = PyUnicode_FromUnicode(s, size);
5116 if (unicode == NULL)
5117 return NULL;
5118 v = _PyUnicode_AsUTF8String(unicode, errors);
5119 Py_DECREF(unicode);
5120 return v;
5121}
5122
5123PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005124PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005125{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005126 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005127}
5128
Walter Dörwald41980ca2007-08-16 21:55:45 +00005129/* --- UTF-32 Codec ------------------------------------------------------- */
5130
5131PyObject *
5132PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005133 Py_ssize_t size,
5134 const char *errors,
5135 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005136{
5137 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
5138}
5139
5140PyObject *
5141PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005142 Py_ssize_t size,
5143 const char *errors,
5144 int *byteorder,
5145 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005146{
5147 const char *starts = s;
5148 Py_ssize_t startinpos;
5149 Py_ssize_t endinpos;
5150 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005151 PyObject *unicode;
Mark Dickinson7db923c2010-06-12 09:10:14 +00005152 const unsigned char *q, *e;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005153 int bo = 0; /* assume native ordering by default */
5154 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00005155 /* Offsets from q for retrieving bytes in the right order. */
5156#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5157 int iorder[] = {0, 1, 2, 3};
5158#else
5159 int iorder[] = {3, 2, 1, 0};
5160#endif
5161 PyObject *errorHandler = NULL;
5162 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00005163
Walter Dörwald41980ca2007-08-16 21:55:45 +00005164 q = (unsigned char *)s;
5165 e = q + size;
5166
5167 if (byteorder)
5168 bo = *byteorder;
5169
5170 /* Check for BOM marks (U+FEFF) in the input and adjust current
5171 byte order setting accordingly. In native mode, the leading BOM
5172 mark is skipped, in all other modes, it is copied to the output
5173 stream as-is (giving a ZWNBSP character). */
5174 if (bo == 0) {
5175 if (size >= 4) {
5176 const Py_UCS4 bom = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
Benjamin Peterson29060642009-01-31 22:14:21 +00005177 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00005178#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00005179 if (bom == 0x0000FEFF) {
5180 q += 4;
5181 bo = -1;
5182 }
5183 else if (bom == 0xFFFE0000) {
5184 q += 4;
5185 bo = 1;
5186 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005187#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005188 if (bom == 0x0000FEFF) {
5189 q += 4;
5190 bo = 1;
5191 }
5192 else if (bom == 0xFFFE0000) {
5193 q += 4;
5194 bo = -1;
5195 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005196#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005197 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005198 }
5199
5200 if (bo == -1) {
5201 /* force LE */
5202 iorder[0] = 0;
5203 iorder[1] = 1;
5204 iorder[2] = 2;
5205 iorder[3] = 3;
5206 }
5207 else if (bo == 1) {
5208 /* force BE */
5209 iorder[0] = 3;
5210 iorder[1] = 2;
5211 iorder[2] = 1;
5212 iorder[3] = 0;
5213 }
5214
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005215 /* This might be one to much, because of a BOM */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005216 unicode = PyUnicode_New((size+3)/4, 127);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005217 if (!unicode)
5218 return NULL;
5219 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005220 return unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005221 outpos = 0;
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005222
Walter Dörwald41980ca2007-08-16 21:55:45 +00005223 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005224 Py_UCS4 ch;
5225 /* remaining bytes at the end? (size should be divisible by 4) */
5226 if (e-q<4) {
5227 if (consumed)
5228 break;
5229 errmsg = "truncated data";
5230 startinpos = ((const char *)q)-starts;
5231 endinpos = ((const char *)e)-starts;
5232 goto utf32Error;
5233 /* The remaining input chars are ignored if the callback
5234 chooses to skip the input */
5235 }
5236 ch = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
5237 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00005238
Benjamin Peterson29060642009-01-31 22:14:21 +00005239 if (ch >= 0x110000)
5240 {
5241 errmsg = "codepoint not in range(0x110000)";
5242 startinpos = ((const char *)q)-starts;
5243 endinpos = startinpos+4;
5244 goto utf32Error;
5245 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005246 if (unicode_putchar(&unicode, &outpos, ch) < 0)
5247 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005248 q += 4;
5249 continue;
5250 utf32Error:
Benjamin Peterson29060642009-01-31 22:14:21 +00005251 if (unicode_decode_call_errorhandler(
5252 errors, &errorHandler,
5253 "utf32", errmsg,
5254 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005255 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005256 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005257 }
5258
5259 if (byteorder)
5260 *byteorder = bo;
5261
5262 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005263 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005264
5265 /* Adjust length */
Victor Stinner16e6a802011-12-12 13:24:15 +01005266 if (unicode_resize(&unicode, outpos) < 0)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005267 goto onError;
5268
5269 Py_XDECREF(errorHandler);
5270 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005271 return unicode_result(unicode);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005272
Benjamin Peterson29060642009-01-31 22:14:21 +00005273 onError:
Walter Dörwald41980ca2007-08-16 21:55:45 +00005274 Py_DECREF(unicode);
5275 Py_XDECREF(errorHandler);
5276 Py_XDECREF(exc);
5277 return NULL;
5278}
5279
5280PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005281_PyUnicode_EncodeUTF32(PyObject *str,
5282 const char *errors,
5283 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005284{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005285 int kind;
5286 void *data;
5287 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005288 PyObject *v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005289 unsigned char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005290 Py_ssize_t nsize, bytesize, i;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005291 /* Offsets from p for storing byte pairs in the right order. */
5292#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5293 int iorder[] = {0, 1, 2, 3};
5294#else
5295 int iorder[] = {3, 2, 1, 0};
5296#endif
5297
Benjamin Peterson29060642009-01-31 22:14:21 +00005298#define STORECHAR(CH) \
5299 do { \
5300 p[iorder[3]] = ((CH) >> 24) & 0xff; \
5301 p[iorder[2]] = ((CH) >> 16) & 0xff; \
5302 p[iorder[1]] = ((CH) >> 8) & 0xff; \
5303 p[iorder[0]] = (CH) & 0xff; \
5304 p += 4; \
Walter Dörwald41980ca2007-08-16 21:55:45 +00005305 } while(0)
5306
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005307 if (!PyUnicode_Check(str)) {
5308 PyErr_BadArgument();
5309 return NULL;
5310 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005311 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005312 return NULL;
5313 kind = PyUnicode_KIND(str);
5314 data = PyUnicode_DATA(str);
5315 len = PyUnicode_GET_LENGTH(str);
5316
5317 nsize = len + (byteorder == 0);
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005318 bytesize = nsize * 4;
5319 if (bytesize / 4 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005320 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005321 v = PyBytes_FromStringAndSize(NULL, bytesize);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005322 if (v == NULL)
5323 return NULL;
5324
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005325 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005326 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005327 STORECHAR(0xFEFF);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005328 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005329 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005330
5331 if (byteorder == -1) {
5332 /* force LE */
5333 iorder[0] = 0;
5334 iorder[1] = 1;
5335 iorder[2] = 2;
5336 iorder[3] = 3;
5337 }
5338 else if (byteorder == 1) {
5339 /* force BE */
5340 iorder[0] = 3;
5341 iorder[1] = 2;
5342 iorder[2] = 1;
5343 iorder[3] = 0;
5344 }
5345
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005346 for (i = 0; i < len; i++)
5347 STORECHAR(PyUnicode_READ(kind, data, i));
Guido van Rossum98297ee2007-11-06 21:34:58 +00005348
5349 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005350 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005351#undef STORECHAR
5352}
5353
Alexander Belopolsky40018472011-02-26 01:02:56 +00005354PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005355PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5356 Py_ssize_t size,
5357 const char *errors,
5358 int byteorder)
5359{
5360 PyObject *result;
5361 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5362 if (tmp == NULL)
5363 return NULL;
5364 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5365 Py_DECREF(tmp);
5366 return result;
5367}
5368
5369PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005370PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005371{
Victor Stinnerb960b342011-11-20 19:12:52 +01005372 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005373}
5374
Guido van Rossumd57fd912000-03-10 22:53:23 +00005375/* --- UTF-16 Codec ------------------------------------------------------- */
5376
Tim Peters772747b2001-08-09 22:21:55 +00005377PyObject *
5378PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005379 Py_ssize_t size,
5380 const char *errors,
5381 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005382{
Walter Dörwald69652032004-09-07 20:24:22 +00005383 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5384}
5385
Antoine Pitrouab868312009-01-10 15:40:25 +00005386/* Two masks for fast checking of whether a C 'long' may contain
5387 UTF16-encoded surrogate characters. This is an efficient heuristic,
5388 assuming that non-surrogate characters with a code point >= 0x8000 are
5389 rare in most input.
5390 FAST_CHAR_MASK is used when the input is in native byte ordering,
5391 SWAPPED_FAST_CHAR_MASK when the input is in byteswapped ordering.
Benjamin Peterson29060642009-01-31 22:14:21 +00005392*/
Antoine Pitrouab868312009-01-10 15:40:25 +00005393#if (SIZEOF_LONG == 8)
5394# define FAST_CHAR_MASK 0x8000800080008000L
5395# define SWAPPED_FAST_CHAR_MASK 0x0080008000800080L
5396#elif (SIZEOF_LONG == 4)
5397# define FAST_CHAR_MASK 0x80008000L
5398# define SWAPPED_FAST_CHAR_MASK 0x00800080L
5399#else
5400# error C 'long' size should be either 4 or 8!
5401#endif
5402
Walter Dörwald69652032004-09-07 20:24:22 +00005403PyObject *
5404PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005405 Py_ssize_t size,
5406 const char *errors,
5407 int *byteorder,
5408 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005409{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005410 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005411 Py_ssize_t startinpos;
5412 Py_ssize_t endinpos;
5413 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005414 PyObject *unicode;
Antoine Pitrouab868312009-01-10 15:40:25 +00005415 const unsigned char *q, *e, *aligned_end;
Tim Peters772747b2001-08-09 22:21:55 +00005416 int bo = 0; /* assume native ordering by default */
Antoine Pitrouab868312009-01-10 15:40:25 +00005417 int native_ordering = 0;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005418 const char *errmsg = "";
Tim Peters772747b2001-08-09 22:21:55 +00005419 /* Offsets from q for retrieving byte pairs in the right order. */
5420#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5421 int ihi = 1, ilo = 0;
5422#else
5423 int ihi = 0, ilo = 1;
5424#endif
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005425 PyObject *errorHandler = NULL;
5426 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005427
5428 /* Note: size will always be longer than the resulting Unicode
5429 character count */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005430 unicode = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005431 if (!unicode)
5432 return NULL;
5433 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005434 return unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005435 outpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005436
Tim Peters772747b2001-08-09 22:21:55 +00005437 q = (unsigned char *)s;
Antoine Pitrouab868312009-01-10 15:40:25 +00005438 e = q + size - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005439
5440 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005441 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005442
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005443 /* Check for BOM marks (U+FEFF) in the input and adjust current
5444 byte order setting accordingly. In native mode, the leading BOM
5445 mark is skipped, in all other modes, it is copied to the output
5446 stream as-is (giving a ZWNBSP character). */
5447 if (bo == 0) {
Walter Dörwald69652032004-09-07 20:24:22 +00005448 if (size >= 2) {
Victor Stinner24729f32011-11-10 20:31:37 +01005449 const Py_UCS4 bom = (q[ihi] << 8) | q[ilo];
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005450#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00005451 if (bom == 0xFEFF) {
5452 q += 2;
5453 bo = -1;
5454 }
5455 else if (bom == 0xFFFE) {
5456 q += 2;
5457 bo = 1;
5458 }
Tim Petersced69f82003-09-16 20:30:58 +00005459#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005460 if (bom == 0xFEFF) {
5461 q += 2;
5462 bo = 1;
5463 }
5464 else if (bom == 0xFFFE) {
5465 q += 2;
5466 bo = -1;
5467 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005468#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005469 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005470 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005471
Tim Peters772747b2001-08-09 22:21:55 +00005472 if (bo == -1) {
5473 /* force LE */
5474 ihi = 1;
5475 ilo = 0;
5476 }
5477 else if (bo == 1) {
5478 /* force BE */
5479 ihi = 0;
5480 ilo = 1;
5481 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005482#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5483 native_ordering = ilo < ihi;
5484#else
5485 native_ordering = ilo > ihi;
5486#endif
Tim Peters772747b2001-08-09 22:21:55 +00005487
Antoine Pitrouab868312009-01-10 15:40:25 +00005488 aligned_end = (const unsigned char *) ((size_t) e & ~LONG_PTR_MASK);
Tim Peters772747b2001-08-09 22:21:55 +00005489 while (q < e) {
Victor Stinner24729f32011-11-10 20:31:37 +01005490 Py_UCS4 ch;
Antoine Pitrouab868312009-01-10 15:40:25 +00005491 /* First check for possible aligned read of a C 'long'. Unaligned
5492 reads are more expensive, better to defer to another iteration. */
5493 if (!((size_t) q & LONG_PTR_MASK)) {
5494 /* Fast path for runs of non-surrogate chars. */
5495 register const unsigned char *_q = q;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005496 int kind = PyUnicode_KIND(unicode);
5497 void *data = PyUnicode_DATA(unicode);
5498 while (_q < aligned_end) {
Victor Stinnere7eee012012-04-05 13:44:34 +02005499 union {
5500 unsigned long as_long;
5501 unsigned short units[sizeof(long) / sizeof(short)];
5502 unsigned char bytes[sizeof(long)];
5503 } block, block_copy;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005504 Py_UCS4 maxch;
Victor Stinnere7eee012012-04-05 13:44:34 +02005505
5506 block.as_long = *(unsigned long *) _q;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005507 if (native_ordering) {
5508 /* Can use buffer directly */
Victor Stinnere7eee012012-04-05 13:44:34 +02005509 if (block.as_long & FAST_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00005510 break;
Antoine Pitrouab868312009-01-10 15:40:25 +00005511 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005512 else {
5513 /* Need to byte-swap */
Victor Stinnere7eee012012-04-05 13:44:34 +02005514 block_copy = block;
5515
5516 if (block.as_long & SWAPPED_FAST_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00005517 break;
Victor Stinnere7eee012012-04-05 13:44:34 +02005518 block.bytes[0] = block_copy.bytes[1];
5519 block.bytes[1] = block_copy.bytes[0];
5520 block.bytes[2] = block_copy.bytes[3];
5521 block.bytes[3] = block_copy.bytes[2];
Antoine Pitrouab868312009-01-10 15:40:25 +00005522#if (SIZEOF_LONG == 8)
Victor Stinnere7eee012012-04-05 13:44:34 +02005523 block.bytes[4] = block_copy.bytes[5];
5524 block.bytes[5] = block_copy.bytes[4];
5525 block.bytes[6] = block_copy.bytes[7];
5526 block.bytes[7] = block_copy.bytes[6];
Antoine Pitrouab868312009-01-10 15:40:25 +00005527#endif
Antoine Pitrouab868312009-01-10 15:40:25 +00005528 }
Victor Stinnere7eee012012-04-05 13:44:34 +02005529 maxch = Py_MAX(block.units[0], block.units[1]);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005530#if SIZEOF_LONG == 8
Victor Stinnere7eee012012-04-05 13:44:34 +02005531 maxch = Py_MAX(maxch, Py_MAX(block.units[2], block.units[3]));
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005532#endif
5533 if (maxch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
5534 if (unicode_widen(&unicode, maxch) < 0)
5535 goto onError;
5536 kind = PyUnicode_KIND(unicode);
5537 data = PyUnicode_DATA(unicode);
5538 }
Victor Stinnere7eee012012-04-05 13:44:34 +02005539 PyUnicode_WRITE(kind, data, outpos++, block.units[0]);
5540 PyUnicode_WRITE(kind, data, outpos++, block.units[1]);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005541#if SIZEOF_LONG == 8
Victor Stinnere7eee012012-04-05 13:44:34 +02005542 PyUnicode_WRITE(kind, data, outpos++, block.units[2]);
5543 PyUnicode_WRITE(kind, data, outpos++, block.units[3]);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005544#endif
5545 _q += SIZEOF_LONG;
Antoine Pitrouab868312009-01-10 15:40:25 +00005546 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005547 q = _q;
5548 if (q >= e)
5549 break;
5550 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005551 ch = (q[ihi] << 8) | q[ilo];
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005552
Benjamin Peterson14339b62009-01-31 16:36:08 +00005553 q += 2;
Benjamin Peterson29060642009-01-31 22:14:21 +00005554
Victor Stinner551ac952011-11-29 22:58:13 +01005555 if (!Py_UNICODE_IS_SURROGATE(ch)) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005556 if (unicode_putchar(&unicode, &outpos, ch) < 0)
5557 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005558 continue;
5559 }
5560
5561 /* UTF-16 code pair: */
5562 if (q > e) {
5563 errmsg = "unexpected end of data";
5564 startinpos = (((const char *)q) - 2) - starts;
5565 endinpos = ((const char *)e) + 1 - starts;
5566 goto utf16Error;
5567 }
Victor Stinner2e9cfad2011-11-20 18:40:27 +01005568 if (Py_UNICODE_IS_HIGH_SURROGATE(ch)) {
5569 Py_UCS4 ch2 = (q[ihi] << 8) | q[ilo];
Benjamin Peterson29060642009-01-31 22:14:21 +00005570 q += 2;
Victor Stinner2e9cfad2011-11-20 18:40:27 +01005571 if (Py_UNICODE_IS_LOW_SURROGATE(ch2)) {
Victor Stinner62aa4d02011-11-09 00:03:45 +01005572 if (unicode_putchar(&unicode, &outpos,
Victor Stinner2e9cfad2011-11-20 18:40:27 +01005573 Py_UNICODE_JOIN_SURROGATES(ch, ch2)) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005574 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005575 continue;
5576 }
5577 else {
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005578 errmsg = "illegal UTF-16 surrogate";
Benjamin Peterson29060642009-01-31 22:14:21 +00005579 startinpos = (((const char *)q)-4)-starts;
5580 endinpos = startinpos+2;
5581 goto utf16Error;
5582 }
5583
Benjamin Peterson14339b62009-01-31 16:36:08 +00005584 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005585 errmsg = "illegal encoding";
5586 startinpos = (((const char *)q)-2)-starts;
5587 endinpos = startinpos+2;
5588 /* Fall through to report the error */
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005589
Benjamin Peterson29060642009-01-31 22:14:21 +00005590 utf16Error:
Benjamin Peterson29060642009-01-31 22:14:21 +00005591 if (unicode_decode_call_errorhandler(
Antoine Pitrouab868312009-01-10 15:40:25 +00005592 errors,
5593 &errorHandler,
5594 "utf16", errmsg,
5595 &starts,
5596 (const char **)&e,
5597 &startinpos,
5598 &endinpos,
5599 &exc,
5600 (const char **)&q,
5601 &unicode,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005602 &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005603 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005604 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005605 /* remaining byte at the end? (size should be even) */
5606 if (e == q) {
5607 if (!consumed) {
5608 errmsg = "truncated data";
5609 startinpos = ((const char *)q) - starts;
5610 endinpos = ((const char *)e) + 1 - starts;
Antoine Pitrouab868312009-01-10 15:40:25 +00005611 if (unicode_decode_call_errorhandler(
5612 errors,
5613 &errorHandler,
5614 "utf16", errmsg,
5615 &starts,
5616 (const char **)&e,
5617 &startinpos,
5618 &endinpos,
5619 &exc,
5620 (const char **)&q,
5621 &unicode,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005622 &outpos))
Antoine Pitrouab868312009-01-10 15:40:25 +00005623 goto onError;
5624 /* The remaining input chars are ignored if the callback
5625 chooses to skip the input */
5626 }
5627 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005628
5629 if (byteorder)
5630 *byteorder = bo;
5631
Walter Dörwald69652032004-09-07 20:24:22 +00005632 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005633 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005634
Guido van Rossumd57fd912000-03-10 22:53:23 +00005635 /* Adjust length */
Victor Stinner16e6a802011-12-12 13:24:15 +01005636 if (unicode_resize(&unicode, outpos) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005637 goto onError;
5638
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005639 Py_XDECREF(errorHandler);
5640 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005641 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005642
Benjamin Peterson29060642009-01-31 22:14:21 +00005643 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005644 Py_DECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005645 Py_XDECREF(errorHandler);
5646 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005647 return NULL;
5648}
5649
Antoine Pitrouab868312009-01-10 15:40:25 +00005650#undef FAST_CHAR_MASK
5651#undef SWAPPED_FAST_CHAR_MASK
5652
Tim Peters772747b2001-08-09 22:21:55 +00005653PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005654_PyUnicode_EncodeUTF16(PyObject *str,
5655 const char *errors,
5656 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005657{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005658 int kind;
5659 void *data;
5660 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005661 PyObject *v;
Tim Peters772747b2001-08-09 22:21:55 +00005662 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005663 Py_ssize_t nsize, bytesize;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005664 Py_ssize_t i, pairs;
Tim Peters772747b2001-08-09 22:21:55 +00005665 /* Offsets from p for storing byte pairs in the right order. */
5666#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5667 int ihi = 1, ilo = 0;
5668#else
5669 int ihi = 0, ilo = 1;
5670#endif
5671
Benjamin Peterson29060642009-01-31 22:14:21 +00005672#define STORECHAR(CH) \
5673 do { \
5674 p[ihi] = ((CH) >> 8) & 0xff; \
5675 p[ilo] = (CH) & 0xff; \
5676 p += 2; \
Tim Peters772747b2001-08-09 22:21:55 +00005677 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005678
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005679 if (!PyUnicode_Check(str)) {
5680 PyErr_BadArgument();
5681 return NULL;
5682 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005683 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005684 return NULL;
5685 kind = PyUnicode_KIND(str);
5686 data = PyUnicode_DATA(str);
5687 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005688
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005689 pairs = 0;
5690 if (kind == PyUnicode_4BYTE_KIND)
5691 for (i = 0; i < len; i++)
5692 if (PyUnicode_READ(kind, data, i) >= 0x10000)
5693 pairs++;
5694 /* 2 * (len + pairs + (byteorder == 0)) */
5695 if (len > PY_SSIZE_T_MAX - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005696 return PyErr_NoMemory();
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005697 nsize = len + pairs + (byteorder == 0);
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005698 bytesize = nsize * 2;
5699 if (bytesize / 2 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005700 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005701 v = PyBytes_FromStringAndSize(NULL, bytesize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005702 if (v == NULL)
5703 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005704
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005705 p = (unsigned char *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005706 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005707 STORECHAR(0xFEFF);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005708 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005709 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005710
5711 if (byteorder == -1) {
5712 /* force LE */
5713 ihi = 1;
5714 ilo = 0;
5715 }
5716 else if (byteorder == 1) {
5717 /* force BE */
5718 ihi = 0;
5719 ilo = 1;
5720 }
5721
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005722 for (i = 0; i < len; i++) {
5723 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
5724 Py_UCS4 ch2 = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +00005725 if (ch >= 0x10000) {
Victor Stinner551ac952011-11-29 22:58:13 +01005726 ch2 = Py_UNICODE_LOW_SURROGATE(ch);
5727 ch = Py_UNICODE_HIGH_SURROGATE(ch);
Benjamin Peterson29060642009-01-31 22:14:21 +00005728 }
Tim Peters772747b2001-08-09 22:21:55 +00005729 STORECHAR(ch);
5730 if (ch2)
5731 STORECHAR(ch2);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005732 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005733
5734 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005735 return v;
Tim Peters772747b2001-08-09 22:21:55 +00005736#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005737}
5738
Alexander Belopolsky40018472011-02-26 01:02:56 +00005739PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005740PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5741 Py_ssize_t size,
5742 const char *errors,
5743 int byteorder)
5744{
5745 PyObject *result;
5746 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5747 if (tmp == NULL)
5748 return NULL;
5749 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5750 Py_DECREF(tmp);
5751 return result;
5752}
5753
5754PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005755PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005756{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005757 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005758}
5759
5760/* --- Unicode Escape Codec ----------------------------------------------- */
5761
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005762/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5763 if all the escapes in the string make it still a valid ASCII string.
5764 Returns -1 if any escapes were found which cause the string to
5765 pop out of ASCII range. Otherwise returns the length of the
5766 required buffer to hold the string.
5767 */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02005768static Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005769length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5770{
5771 const unsigned char *p = (const unsigned char *)s;
5772 const unsigned char *end = p + size;
5773 Py_ssize_t length = 0;
5774
5775 if (size < 0)
5776 return -1;
5777
5778 for (; p < end; ++p) {
5779 if (*p > 127) {
5780 /* Non-ASCII */
5781 return -1;
5782 }
5783 else if (*p != '\\') {
5784 /* Normal character */
5785 ++length;
5786 }
5787 else {
5788 /* Backslash-escape, check next char */
5789 ++p;
5790 /* Escape sequence reaches till end of string or
5791 non-ASCII follow-up. */
5792 if (p >= end || *p > 127)
5793 return -1;
5794 switch (*p) {
5795 case '\n':
5796 /* backslash + \n result in zero characters */
5797 break;
5798 case '\\': case '\'': case '\"':
5799 case 'b': case 'f': case 't':
5800 case 'n': case 'r': case 'v': case 'a':
5801 ++length;
5802 break;
5803 case '0': case '1': case '2': case '3':
5804 case '4': case '5': case '6': case '7':
5805 case 'x': case 'u': case 'U': case 'N':
5806 /* these do not guarantee ASCII characters */
5807 return -1;
5808 default:
5809 /* count the backslash + the other character */
5810 length += 2;
5811 }
5812 }
5813 }
5814 return length;
5815}
5816
Fredrik Lundh06d12682001-01-24 07:59:11 +00005817static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005818
Alexander Belopolsky40018472011-02-26 01:02:56 +00005819PyObject *
5820PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005821 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005822 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005823{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005824 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005825 Py_ssize_t startinpos;
5826 Py_ssize_t endinpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005827 int j;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005828 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005829 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005830 char* message;
5831 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005832 PyObject *errorHandler = NULL;
5833 PyObject *exc = NULL;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005834 Py_ssize_t len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005835 Py_ssize_t i;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005836
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005837 len = length_of_escaped_ascii_string(s, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005838
5839 /* After length_of_escaped_ascii_string() there are two alternatives,
5840 either the string is pure ASCII with named escapes like \n, etc.
5841 and we determined it's exact size (common case)
5842 or it contains \x, \u, ... escape sequences. then we create a
5843 legacy wchar string and resize it at the end of this function. */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005844 if (len >= 0) {
5845 v = PyUnicode_New(len, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005846 if (!v)
5847 goto onError;
5848 assert(PyUnicode_KIND(v) == PyUnicode_1BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005849 }
5850 else {
5851 /* Escaped strings will always be longer than the resulting
5852 Unicode string, so we start with size here and then reduce the
5853 length after conversion to the true value.
5854 (but if the error callback returns a long replacement string
5855 we'll have to allocate more space) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005856 v = PyUnicode_New(size, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005857 if (!v)
5858 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005859 len = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005860 }
5861
Guido van Rossumd57fd912000-03-10 22:53:23 +00005862 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005863 return v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005864 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005865 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005866
Guido van Rossumd57fd912000-03-10 22:53:23 +00005867 while (s < end) {
5868 unsigned char c;
Victor Stinner24729f32011-11-10 20:31:37 +01005869 Py_UCS4 x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005870 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005871
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005872 /* The only case in which i == ascii_length is a backslash
5873 followed by a newline. */
5874 assert(i <= len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005875
Guido van Rossumd57fd912000-03-10 22:53:23 +00005876 /* Non-escape characters are interpreted as Unicode ordinals */
5877 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005878 if (unicode_putchar(&v, &i, (unsigned char) *s++) < 0)
5879 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005880 continue;
5881 }
5882
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005883 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005884 /* \ - Escapes */
5885 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005886 c = *s++;
5887 if (s > end)
5888 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005889
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005890 /* The only case in which i == ascii_length is a backslash
5891 followed by a newline. */
5892 assert(i < len || (i == len && c == '\n'));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005893
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005894 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005895
Benjamin Peterson29060642009-01-31 22:14:21 +00005896 /* \x escapes */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005897#define WRITECHAR(ch) \
5898 do { \
5899 if (unicode_putchar(&v, &i, ch) < 0) \
5900 goto onError; \
5901 }while(0)
5902
Guido van Rossumd57fd912000-03-10 22:53:23 +00005903 case '\n': break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005904 case '\\': WRITECHAR('\\'); break;
5905 case '\'': WRITECHAR('\''); break;
5906 case '\"': WRITECHAR('\"'); break;
5907 case 'b': WRITECHAR('\b'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005908 /* FF */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005909 case 'f': WRITECHAR('\014'); break;
5910 case 't': WRITECHAR('\t'); break;
5911 case 'n': WRITECHAR('\n'); break;
5912 case 'r': WRITECHAR('\r'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005913 /* VT */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005914 case 'v': WRITECHAR('\013'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005915 /* BEL, not classic C */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005916 case 'a': WRITECHAR('\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005917
Benjamin Peterson29060642009-01-31 22:14:21 +00005918 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005919 case '0': case '1': case '2': case '3':
5920 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005921 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005922 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005923 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005924 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005925 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00005926 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005927 WRITECHAR(x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005928 break;
5929
Benjamin Peterson29060642009-01-31 22:14:21 +00005930 /* hex escapes */
5931 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005932 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005933 digits = 2;
5934 message = "truncated \\xXX escape";
5935 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005936
Benjamin Peterson29060642009-01-31 22:14:21 +00005937 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005938 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005939 digits = 4;
5940 message = "truncated \\uXXXX escape";
5941 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005942
Benjamin Peterson29060642009-01-31 22:14:21 +00005943 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005944 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005945 digits = 8;
5946 message = "truncated \\UXXXXXXXX escape";
5947 hexescape:
5948 chr = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005949 if (s+digits>end) {
5950 endinpos = size;
5951 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005952 errors, &errorHandler,
5953 "unicodeescape", "end of string in escape sequence",
5954 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005955 &v, &i))
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005956 goto onError;
5957 goto nextByte;
5958 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005959 for (j = 0; j < digits; ++j) {
5960 c = (unsigned char) s[j];
David Malcolm96960882010-11-05 17:23:41 +00005961 if (!Py_ISXDIGIT(c)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005962 endinpos = (s+j+1)-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005963 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005964 errors, &errorHandler,
5965 "unicodeescape", message,
5966 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005967 &v, &i))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005968 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005969 len = PyUnicode_GET_LENGTH(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005970 goto nextByte;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005971 }
5972 chr = (chr<<4) & ~0xF;
5973 if (c >= '0' && c <= '9')
5974 chr += c - '0';
5975 else if (c >= 'a' && c <= 'f')
5976 chr += 10 + c - 'a';
5977 else
5978 chr += 10 + c - 'A';
5979 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005980 s += j;
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005981 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005982 /* _decoding_error will have already written into the
5983 target buffer. */
5984 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005985 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005986 /* when we get here, chr is a 32-bit unicode character */
Victor Stinner8faf8212011-12-08 22:14:11 +01005987 if (chr <= MAX_UNICODE) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005988 WRITECHAR(chr);
Fredrik Lundhdf846752000-09-03 11:29:49 +00005989 } else {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005990 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005991 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005992 errors, &errorHandler,
5993 "unicodeescape", "illegal Unicode character",
5994 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005995 &v, &i))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005996 goto onError;
5997 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005998 break;
5999
Benjamin Peterson29060642009-01-31 22:14:21 +00006000 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00006001 case 'N':
6002 message = "malformed \\N character escape";
6003 if (ucnhash_CAPI == NULL) {
6004 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006005 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
6006 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00006007 if (ucnhash_CAPI == NULL)
6008 goto ucnhashError;
6009 }
6010 if (*s == '{') {
6011 const char *start = s+1;
6012 /* look for the closing brace */
6013 while (*s != '}' && s < end)
6014 s++;
6015 if (s > start && s < end && *s == '}') {
6016 /* found a name. look it up in the unicode database */
6017 message = "unknown Unicode character name";
6018 s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006019 if (ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
Ezio Melotti931b8aa2011-10-21 21:57:36 +03006020 &chr, 0))
Fredrik Lundhccc74732001-02-18 22:13:49 +00006021 goto store;
6022 }
6023 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006024 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006025 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00006026 errors, &errorHandler,
6027 "unicodeescape", message,
6028 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006029 &v, &i))
Fredrik Lundhccc74732001-02-18 22:13:49 +00006030 goto onError;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006031 break;
6032
6033 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00006034 if (s > end) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006035 message = "\\ at end of string";
6036 s--;
6037 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006038 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00006039 errors, &errorHandler,
6040 "unicodeescape", message,
6041 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006042 &v, &i))
Walter Dörwald8c077222002-03-25 11:16:18 +00006043 goto onError;
6044 }
6045 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006046 WRITECHAR('\\');
6047 WRITECHAR(s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00006048 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00006049 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006050 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006051 nextByte:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006052 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006053 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006054#undef WRITECHAR
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006055
Victor Stinner16e6a802011-12-12 13:24:15 +01006056 if (unicode_resize(&v, i) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006057 goto onError;
Walter Dörwaldd4ade082003-08-15 15:00:26 +00006058 Py_XDECREF(errorHandler);
6059 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006060 return unicode_result(v);
Walter Dörwald8c077222002-03-25 11:16:18 +00006061
Benjamin Peterson29060642009-01-31 22:14:21 +00006062 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00006063 PyErr_SetString(
6064 PyExc_UnicodeError,
6065 "\\N escapes not supported (can't load unicodedata module)"
6066 );
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00006067 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006068 Py_XDECREF(errorHandler);
6069 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00006070 return NULL;
6071
Benjamin Peterson29060642009-01-31 22:14:21 +00006072 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006073 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006074 Py_XDECREF(errorHandler);
6075 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006076 return NULL;
6077}
6078
6079/* Return a Unicode-Escape string version of the Unicode object.
6080
6081 If quotes is true, the string is enclosed in u"" or u'' quotes as
6082 appropriate.
6083
6084*/
6085
Alexander Belopolsky40018472011-02-26 01:02:56 +00006086PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006087PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006088{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006089 Py_ssize_t i, len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006090 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006091 char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006092 int kind;
6093 void *data;
6094 Py_ssize_t expandsize = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006095
Thomas Wouters89f507f2006-12-13 04:49:30 +00006096 /* Initial allocation is based on the longest-possible unichr
6097 escape.
6098
6099 In wide (UTF-32) builds '\U00xxxxxx' is 10 chars per source
6100 unichr, so in this case it's the longest unichr escape. In
6101 narrow (UTF-16) builds this is five chars per source unichr
6102 since there are two unichrs in the surrogate pair, so in narrow
6103 (UTF-16) builds it's not the longest unichr escape.
6104
6105 In wide or narrow builds '\uxxxx' is 6 chars per source unichr,
6106 so in the narrow (UTF-16) build case it's the longest unichr
6107 escape.
6108 */
6109
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006110 if (!PyUnicode_Check(unicode)) {
6111 PyErr_BadArgument();
6112 return NULL;
6113 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05006114 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006115 return NULL;
6116 len = PyUnicode_GET_LENGTH(unicode);
6117 kind = PyUnicode_KIND(unicode);
6118 data = PyUnicode_DATA(unicode);
Benjamin Petersonead6b532011-12-20 17:23:42 -06006119 switch (kind) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006120 case PyUnicode_1BYTE_KIND: expandsize = 4; break;
6121 case PyUnicode_2BYTE_KIND: expandsize = 6; break;
6122 case PyUnicode_4BYTE_KIND: expandsize = 10; break;
6123 }
6124
6125 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006126 return PyBytes_FromStringAndSize(NULL, 0);
6127
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006128 if (len > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006129 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00006130
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006131 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00006132 2
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006133 + expandsize*len
Benjamin Peterson29060642009-01-31 22:14:21 +00006134 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006135 if (repr == NULL)
6136 return NULL;
6137
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006138 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006139
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006140 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01006141 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006142
Walter Dörwald79e913e2007-05-12 11:08:06 +00006143 /* Escape backslashes */
6144 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006145 *p++ = '\\';
6146 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00006147 continue;
Tim Petersced69f82003-09-16 20:30:58 +00006148 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006149
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00006150 /* Map 21-bit characters to '\U00xxxxxx' */
6151 else if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01006152 assert(ch <= MAX_UNICODE);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00006153 *p++ = '\\';
6154 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006155 *p++ = Py_hexdigits[(ch >> 28) & 0x0000000F];
6156 *p++ = Py_hexdigits[(ch >> 24) & 0x0000000F];
6157 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
6158 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
6159 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
6160 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
6161 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
6162 *p++ = Py_hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00006163 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00006164 }
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00006165
Guido van Rossumd57fd912000-03-10 22:53:23 +00006166 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00006167 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006168 *p++ = '\\';
6169 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006170 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
6171 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
6172 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6173 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006174 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006175
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006176 /* Map special whitespace to '\t', \n', '\r' */
6177 else if (ch == '\t') {
6178 *p++ = '\\';
6179 *p++ = 't';
6180 }
6181 else if (ch == '\n') {
6182 *p++ = '\\';
6183 *p++ = 'n';
6184 }
6185 else if (ch == '\r') {
6186 *p++ = '\\';
6187 *p++ = 'r';
6188 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006189
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006190 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00006191 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006192 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006193 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006194 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6195 *p++ = Py_hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00006196 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006197
Guido van Rossumd57fd912000-03-10 22:53:23 +00006198 /* Copy everything else as-is */
6199 else
6200 *p++ = (char) ch;
6201 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006202
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006203 assert(p - PyBytes_AS_STRING(repr) > 0);
6204 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
6205 return NULL;
6206 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006207}
6208
Alexander Belopolsky40018472011-02-26 01:02:56 +00006209PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006210PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
6211 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006212{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006213 PyObject *result;
6214 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6215 if (tmp == NULL)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006216 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006217 result = PyUnicode_AsUnicodeEscapeString(tmp);
6218 Py_DECREF(tmp);
6219 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006220}
6221
6222/* --- Raw Unicode Escape Codec ------------------------------------------- */
6223
Alexander Belopolsky40018472011-02-26 01:02:56 +00006224PyObject *
6225PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006226 Py_ssize_t size,
6227 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006228{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006229 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006230 Py_ssize_t startinpos;
6231 Py_ssize_t endinpos;
6232 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006233 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006234 const char *end;
6235 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006236 PyObject *errorHandler = NULL;
6237 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006238
Guido van Rossumd57fd912000-03-10 22:53:23 +00006239 /* Escaped strings will always be longer than the resulting
6240 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006241 length after conversion to the true value. (But decoding error
6242 handler might have to resize the string) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006243 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006244 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006245 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006246 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006247 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006248 outpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006249 end = s + size;
6250 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006251 unsigned char c;
6252 Py_UCS4 x;
6253 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006254 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006255
Benjamin Peterson29060642009-01-31 22:14:21 +00006256 /* Non-escape characters are interpreted as Unicode ordinals */
6257 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006258 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
6259 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006260 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006261 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006262 startinpos = s-starts;
6263
6264 /* \u-escapes are only interpreted iff the number of leading
6265 backslashes if odd */
6266 bs = s;
6267 for (;s < end;) {
6268 if (*s != '\\')
6269 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006270 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
6271 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006272 }
6273 if (((s - bs) & 1) == 0 ||
6274 s >= end ||
6275 (*s != 'u' && *s != 'U')) {
6276 continue;
6277 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006278 outpos--;
Benjamin Peterson29060642009-01-31 22:14:21 +00006279 count = *s=='u' ? 4 : 8;
6280 s++;
6281
6282 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
Benjamin Peterson29060642009-01-31 22:14:21 +00006283 for (x = 0, i = 0; i < count; ++i, ++s) {
6284 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00006285 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006286 endinpos = s-starts;
6287 if (unicode_decode_call_errorhandler(
6288 errors, &errorHandler,
6289 "rawunicodeescape", "truncated \\uXXXX",
6290 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006291 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006292 goto onError;
6293 goto nextByte;
6294 }
6295 x = (x<<4) & ~0xF;
6296 if (c >= '0' && c <= '9')
6297 x += c - '0';
6298 else if (c >= 'a' && c <= 'f')
6299 x += 10 + c - 'a';
6300 else
6301 x += 10 + c - 'A';
6302 }
Victor Stinner8faf8212011-12-08 22:14:11 +01006303 if (x <= MAX_UNICODE) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006304 if (unicode_putchar(&v, &outpos, x) < 0)
6305 goto onError;
Christian Heimesfe337bf2008-03-23 21:54:12 +00006306 } else {
6307 endinpos = s-starts;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006308 if (unicode_decode_call_errorhandler(
6309 errors, &errorHandler,
6310 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00006311 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006312 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006313 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006314 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006315 nextByte:
6316 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006317 }
Victor Stinner16e6a802011-12-12 13:24:15 +01006318 if (unicode_resize(&v, outpos) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006319 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006320 Py_XDECREF(errorHandler);
6321 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006322 return unicode_result(v);
Tim Petersced69f82003-09-16 20:30:58 +00006323
Benjamin Peterson29060642009-01-31 22:14:21 +00006324 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006325 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006326 Py_XDECREF(errorHandler);
6327 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006328 return NULL;
6329}
6330
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006331
Alexander Belopolsky40018472011-02-26 01:02:56 +00006332PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006333PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006334{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006335 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006336 char *p;
6337 char *q;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006338 Py_ssize_t expandsize, pos;
6339 int kind;
6340 void *data;
6341 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006342
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006343 if (!PyUnicode_Check(unicode)) {
6344 PyErr_BadArgument();
6345 return NULL;
6346 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05006347 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006348 return NULL;
6349 kind = PyUnicode_KIND(unicode);
6350 data = PyUnicode_DATA(unicode);
6351 len = PyUnicode_GET_LENGTH(unicode);
Benjamin Peterson1518e872011-11-23 10:44:52 -06006352 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6353 bytes, and 1 byte characters 4. */
6354 expandsize = kind * 2 + 2;
Victor Stinner0e368262011-11-10 20:12:49 +01006355
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006356 if (len > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006357 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00006358
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006359 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006360 if (repr == NULL)
6361 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006362 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006363 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006364
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006365 p = q = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006366 for (pos = 0; pos < len; pos++) {
6367 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006368 /* Map 32-bit characters to '\Uxxxxxxxx' */
6369 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01006370 assert(ch <= MAX_UNICODE);
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006371 *p++ = '\\';
6372 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006373 *p++ = Py_hexdigits[(ch >> 28) & 0xf];
6374 *p++ = Py_hexdigits[(ch >> 24) & 0xf];
6375 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6376 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6377 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6378 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6379 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6380 *p++ = Py_hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00006381 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006382 /* Map 16-bit characters to '\uxxxx' */
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006383 else if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006384 *p++ = '\\';
6385 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006386 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6387 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6388 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6389 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006390 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006391 /* Copy everything else as-is */
6392 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00006393 *p++ = (char) ch;
6394 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006395
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006396 assert(p > q);
6397 if (_PyBytes_Resize(&repr, p - q) < 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006398 return NULL;
6399 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006400}
6401
Alexander Belopolsky40018472011-02-26 01:02:56 +00006402PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006403PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6404 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006405{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006406 PyObject *result;
6407 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6408 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006409 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006410 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6411 Py_DECREF(tmp);
6412 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006413}
6414
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006415/* --- Unicode Internal Codec ------------------------------------------- */
6416
Alexander Belopolsky40018472011-02-26 01:02:56 +00006417PyObject *
6418_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006419 Py_ssize_t size,
6420 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006421{
6422 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006423 Py_ssize_t startinpos;
6424 Py_ssize_t endinpos;
6425 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006426 PyObject *v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006427 const char *end;
6428 const char *reason;
6429 PyObject *errorHandler = NULL;
6430 PyObject *exc = NULL;
6431
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006432 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006433 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006434 1))
6435 return NULL;
6436
Thomas Wouters89f507f2006-12-13 04:49:30 +00006437 /* XXX overflow detection missing */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006438 v = PyUnicode_New((size+Py_UNICODE_SIZE-1)/ Py_UNICODE_SIZE, 127);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006439 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006440 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006441 if (PyUnicode_GET_LENGTH(v) == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006442 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006443 outpos = 0;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006444 end = s + size;
6445
6446 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006447 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006448 Py_UCS4 ch;
6449 /* We copy the raw representation one byte at a time because the
6450 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006451 ((char *) &uch)[0] = s[0];
6452 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006453#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006454 ((char *) &uch)[2] = s[2];
6455 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006456#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006457 ch = uch;
6458
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006459 /* We have to sanity check the raw data, otherwise doom looms for
6460 some malformed UCS-4 data. */
6461 if (
Benjamin Peterson29060642009-01-31 22:14:21 +00006462#ifdef Py_UNICODE_WIDE
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006463 ch > 0x10ffff ||
Benjamin Peterson29060642009-01-31 22:14:21 +00006464#endif
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006465 end-s < Py_UNICODE_SIZE
6466 )
Benjamin Peterson29060642009-01-31 22:14:21 +00006467 {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006468 startinpos = s - starts;
6469 if (end-s < Py_UNICODE_SIZE) {
6470 endinpos = end-starts;
6471 reason = "truncated input";
6472 }
6473 else {
6474 endinpos = s - starts + Py_UNICODE_SIZE;
6475 reason = "illegal code point (> 0x10FFFF)";
6476 }
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006477 if (unicode_decode_call_errorhandler(
6478 errors, &errorHandler,
6479 "unicode_internal", reason,
Walter Dörwalde78178e2007-07-30 13:31:40 +00006480 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006481 &v, &outpos))
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006482 goto onError;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006483 continue;
6484 }
6485
6486 s += Py_UNICODE_SIZE;
6487#ifndef Py_UNICODE_WIDE
Victor Stinner551ac952011-11-29 22:58:13 +01006488 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && s < end)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006489 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006490 Py_UNICODE uch2;
6491 ((char *) &uch2)[0] = s[0];
6492 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006493 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006494 {
Victor Stinner551ac952011-11-29 22:58:13 +01006495 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006496 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006497 }
6498 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006499#endif
6500
6501 if (unicode_putchar(&v, &outpos, ch) < 0)
6502 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006503 }
6504
Victor Stinner16e6a802011-12-12 13:24:15 +01006505 if (unicode_resize(&v, outpos) < 0)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006506 goto onError;
6507 Py_XDECREF(errorHandler);
6508 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006509 return unicode_result(v);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006510
Benjamin Peterson29060642009-01-31 22:14:21 +00006511 onError:
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006512 Py_XDECREF(v);
6513 Py_XDECREF(errorHandler);
6514 Py_XDECREF(exc);
6515 return NULL;
6516}
6517
Guido van Rossumd57fd912000-03-10 22:53:23 +00006518/* --- Latin-1 Codec ------------------------------------------------------ */
6519
Alexander Belopolsky40018472011-02-26 01:02:56 +00006520PyObject *
6521PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006522 Py_ssize_t size,
6523 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006524{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006525 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006526 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006527}
6528
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006529/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006530static void
6531make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006532 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006533 PyObject *unicode,
6534 Py_ssize_t startpos, Py_ssize_t endpos,
6535 const char *reason)
6536{
6537 if (*exceptionObject == NULL) {
6538 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006539 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006540 encoding, unicode, startpos, endpos, reason);
6541 }
6542 else {
6543 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6544 goto onError;
6545 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6546 goto onError;
6547 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6548 goto onError;
6549 return;
6550 onError:
6551 Py_DECREF(*exceptionObject);
6552 *exceptionObject = NULL;
6553 }
6554}
6555
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006556/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006557static void
6558raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006559 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006560 PyObject *unicode,
6561 Py_ssize_t startpos, Py_ssize_t endpos,
6562 const char *reason)
6563{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006564 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006565 encoding, unicode, startpos, endpos, reason);
6566 if (*exceptionObject != NULL)
6567 PyCodec_StrictErrors(*exceptionObject);
6568}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006569
6570/* error handling callback helper:
6571 build arguments, call the callback and check the arguments,
6572 put the result into newpos and return the replacement string, which
6573 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006574static PyObject *
6575unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006576 PyObject **errorHandler,
6577 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006578 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006579 Py_ssize_t startpos, Py_ssize_t endpos,
6580 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006581{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006582 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006583 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006584 PyObject *restuple;
6585 PyObject *resunicode;
6586
6587 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006588 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006589 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006590 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006591 }
6592
Benjamin Petersonbac79492012-01-14 13:34:47 -05006593 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006594 return NULL;
6595 len = PyUnicode_GET_LENGTH(unicode);
6596
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006597 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006598 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006599 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006600 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006601
6602 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006603 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006604 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006605 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006606 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006607 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006608 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 (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006612 &resunicode, newpos)) {
6613 Py_DECREF(restuple);
6614 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006615 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006616 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6617 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6618 Py_DECREF(restuple);
6619 return NULL;
6620 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006621 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006622 *newpos = len + *newpos;
6623 if (*newpos<0 || *newpos>len) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006624 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
6625 Py_DECREF(restuple);
6626 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006627 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006628 Py_INCREF(resunicode);
6629 Py_DECREF(restuple);
6630 return resunicode;
6631}
6632
Alexander Belopolsky40018472011-02-26 01:02:56 +00006633static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006634unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006635 const char *errors,
Victor Stinnerfcd96532011-11-04 00:28:50 +01006636 unsigned int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006637{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006638 /* input state */
6639 Py_ssize_t pos=0, size;
6640 int kind;
6641 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006642 /* output object */
6643 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006644 /* pointer into the output */
6645 char *str;
6646 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006647 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006648 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6649 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006650 PyObject *errorHandler = NULL;
6651 PyObject *exc = NULL;
6652 /* the following variable is used for caching string comparisons
6653 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6654 int known_errorHandler = -1;
6655
Benjamin Petersonbac79492012-01-14 13:34:47 -05006656 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006657 return NULL;
6658 size = PyUnicode_GET_LENGTH(unicode);
6659 kind = PyUnicode_KIND(unicode);
6660 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006661 /* allocate enough for a simple encoding without
6662 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006663 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006664 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006665 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006666 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006667 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006668 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006669 ressize = size;
6670
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006671 while (pos < size) {
6672 Py_UCS4 c = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006673
Benjamin Peterson29060642009-01-31 22:14:21 +00006674 /* can we encode this? */
6675 if (c<limit) {
6676 /* no overflow check, because we know that the space is enough */
6677 *str++ = (char)c;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006678 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006679 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006680 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006681 Py_ssize_t requiredsize;
6682 PyObject *repunicode;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006683 Py_ssize_t repsize, newpos, respos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006684 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006685 Py_ssize_t collstart = pos;
6686 Py_ssize_t collend = pos;
Benjamin Peterson29060642009-01-31 22:14:21 +00006687 /* find all unecodable characters */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006688 while ((collend < size) && (PyUnicode_READ(kind, data, collend)>=limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006689 ++collend;
6690 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
6691 if (known_errorHandler==-1) {
6692 if ((errors==NULL) || (!strcmp(errors, "strict")))
6693 known_errorHandler = 1;
6694 else if (!strcmp(errors, "replace"))
6695 known_errorHandler = 2;
6696 else if (!strcmp(errors, "ignore"))
6697 known_errorHandler = 3;
6698 else if (!strcmp(errors, "xmlcharrefreplace"))
6699 known_errorHandler = 4;
6700 else
6701 known_errorHandler = 0;
6702 }
6703 switch (known_errorHandler) {
6704 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006705 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006706 goto onError;
6707 case 2: /* replace */
6708 while (collstart++<collend)
6709 *str++ = '?'; /* fall through */
6710 case 3: /* ignore */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006711 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006712 break;
6713 case 4: /* xmlcharrefreplace */
6714 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006715 /* determine replacement size */
6716 for (i = collstart, repsize = 0; i < collend; ++i) {
6717 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
6718 if (ch < 10)
Benjamin Peterson29060642009-01-31 22:14:21 +00006719 repsize += 2+1+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006720 else if (ch < 100)
Benjamin Peterson29060642009-01-31 22:14:21 +00006721 repsize += 2+2+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006722 else if (ch < 1000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006723 repsize += 2+3+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006724 else if (ch < 10000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006725 repsize += 2+4+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006726 else if (ch < 100000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006727 repsize += 2+5+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006728 else if (ch < 1000000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006729 repsize += 2+6+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006730 else {
Victor Stinner8faf8212011-12-08 22:14:11 +01006731 assert(ch <= MAX_UNICODE);
Benjamin Peterson29060642009-01-31 22:14:21 +00006732 repsize += 2+7+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006733 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006734 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006735 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006736 if (requiredsize > ressize) {
6737 if (requiredsize<2*ressize)
6738 requiredsize = 2*ressize;
6739 if (_PyBytes_Resize(&res, requiredsize))
6740 goto onError;
6741 str = PyBytes_AS_STRING(res) + respos;
6742 ressize = requiredsize;
6743 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006744 /* generate replacement */
6745 for (i = collstart; i < collend; ++i) {
6746 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
Benjamin Peterson29060642009-01-31 22:14:21 +00006747 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006748 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006749 break;
6750 default:
6751 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006752 encoding, reason, unicode, &exc,
6753 collstart, collend, &newpos);
6754 if (repunicode == NULL || (PyUnicode_Check(repunicode) &&
Benjamin Petersonbac79492012-01-14 13:34:47 -05006755 PyUnicode_READY(repunicode) == -1))
Benjamin Peterson29060642009-01-31 22:14:21 +00006756 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006757 if (PyBytes_Check(repunicode)) {
6758 /* Directly copy bytes result to output. */
6759 repsize = PyBytes_Size(repunicode);
6760 if (repsize > 1) {
6761 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006762 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006763 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
6764 Py_DECREF(repunicode);
6765 goto onError;
6766 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006767 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006768 ressize += repsize-1;
6769 }
6770 memcpy(str, PyBytes_AsString(repunicode), repsize);
6771 str += repsize;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006772 pos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006773 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006774 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006775 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006776 /* need more space? (at least enough for what we
6777 have+the replacement+the rest of the string, so
6778 we won't have to check space for encodable characters) */
6779 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006780 repsize = PyUnicode_GET_LENGTH(repunicode);
6781 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006782 if (requiredsize > ressize) {
6783 if (requiredsize<2*ressize)
6784 requiredsize = 2*ressize;
6785 if (_PyBytes_Resize(&res, requiredsize)) {
6786 Py_DECREF(repunicode);
6787 goto onError;
6788 }
6789 str = PyBytes_AS_STRING(res) + respos;
6790 ressize = requiredsize;
6791 }
6792 /* check if there is anything unencodable in the replacement
6793 and copy it to the output */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006794 for (i = 0; repsize-->0; ++i, ++str) {
6795 c = PyUnicode_READ_CHAR(repunicode, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00006796 if (c >= limit) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006797 raise_encode_exception(&exc, encoding, unicode,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006798 pos, pos+1, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006799 Py_DECREF(repunicode);
6800 goto onError;
6801 }
6802 *str = (char)c;
6803 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006804 pos = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006805 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006806 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006807 }
6808 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006809 /* Resize if we allocated to much */
6810 size = str - PyBytes_AS_STRING(res);
6811 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00006812 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006813 if (_PyBytes_Resize(&res, size) < 0)
6814 goto onError;
6815 }
6816
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006817 Py_XDECREF(errorHandler);
6818 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006819 return res;
6820
6821 onError:
6822 Py_XDECREF(res);
6823 Py_XDECREF(errorHandler);
6824 Py_XDECREF(exc);
6825 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006826}
6827
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006828/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006829PyObject *
6830PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006831 Py_ssize_t size,
6832 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006833{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006834 PyObject *result;
6835 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6836 if (unicode == NULL)
6837 return NULL;
6838 result = unicode_encode_ucs1(unicode, errors, 256);
6839 Py_DECREF(unicode);
6840 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006841}
6842
Alexander Belopolsky40018472011-02-26 01:02:56 +00006843PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006844_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006845{
6846 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006847 PyErr_BadArgument();
6848 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006849 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006850 if (PyUnicode_READY(unicode) == -1)
6851 return NULL;
6852 /* Fast path: if it is a one-byte string, construct
6853 bytes object directly. */
6854 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6855 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6856 PyUnicode_GET_LENGTH(unicode));
6857 /* Non-Latin-1 characters present. Defer to above function to
6858 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006859 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006860}
6861
6862PyObject*
6863PyUnicode_AsLatin1String(PyObject *unicode)
6864{
6865 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006866}
6867
6868/* --- 7-bit ASCII Codec -------------------------------------------------- */
6869
Alexander Belopolsky40018472011-02-26 01:02:56 +00006870PyObject *
6871PyUnicode_DecodeASCII(const char *s,
6872 Py_ssize_t size,
6873 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006874{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006875 const char *starts = s;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006876 PyObject *v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006877 int kind;
6878 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006879 Py_ssize_t startinpos;
6880 Py_ssize_t endinpos;
6881 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006882 const char *e;
Victor Stinner702c7342011-10-05 13:50:52 +02006883 int has_error;
6884 const unsigned char *p = (const unsigned char *)s;
6885 const unsigned char *end = p + size;
6886 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006887 PyObject *errorHandler = NULL;
6888 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006889
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006890 if (size == 0) {
6891 Py_INCREF(unicode_empty);
6892 return unicode_empty;
6893 }
6894
Guido van Rossumd57fd912000-03-10 22:53:23 +00006895 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006896 if (size == 1 && (unsigned char)s[0] < 128)
6897 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006898
Victor Stinner702c7342011-10-05 13:50:52 +02006899 has_error = 0;
6900 while (p < end && !has_error) {
6901 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
6902 an explanation. */
6903 if (!((size_t) p & LONG_PTR_MASK)) {
6904 /* Help register allocation */
6905 register const unsigned char *_p = p;
6906 while (_p < aligned_end) {
6907 unsigned long value = *(unsigned long *) _p;
6908 if (value & ASCII_CHAR_MASK) {
6909 has_error = 1;
6910 break;
6911 }
6912 _p += SIZEOF_LONG;
6913 }
6914 if (_p == end)
6915 break;
6916 if (has_error)
6917 break;
6918 p = _p;
6919 }
6920 if (*p & 0x80) {
6921 has_error = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006922 break;
Victor Stinner702c7342011-10-05 13:50:52 +02006923 }
6924 else {
6925 ++p;
6926 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00006927 }
Victor Stinner702c7342011-10-05 13:50:52 +02006928 if (!has_error)
6929 return unicode_fromascii((const unsigned char *)s, size);
Tim Petersced69f82003-09-16 20:30:58 +00006930
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006931 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006932 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006933 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006934 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006935 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006936 kind = PyUnicode_KIND(v);
6937 data = PyUnicode_DATA(v);
6938 outpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006939 e = s + size;
6940 while (s < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006941 register unsigned char c = (unsigned char)*s;
6942 if (c < 128) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006943 PyUnicode_WRITE(kind, data, outpos++, c);
Benjamin Peterson29060642009-01-31 22:14:21 +00006944 ++s;
6945 }
6946 else {
6947 startinpos = s-starts;
6948 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006949 if (unicode_decode_call_errorhandler(
6950 errors, &errorHandler,
6951 "ascii", "ordinal not in range(128)",
6952 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006953 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006954 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006955 kind = PyUnicode_KIND(v);
6956 data = PyUnicode_DATA(v);
Benjamin Peterson29060642009-01-31 22:14:21 +00006957 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006958 }
Victor Stinner16e6a802011-12-12 13:24:15 +01006959 if (unicode_resize(&v, outpos) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006960 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006961 Py_XDECREF(errorHandler);
6962 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006963 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01006964 return v;
Tim Petersced69f82003-09-16 20:30:58 +00006965
Benjamin Peterson29060642009-01-31 22:14:21 +00006966 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006967 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006968 Py_XDECREF(errorHandler);
6969 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006970 return NULL;
6971}
6972
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006973/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006974PyObject *
6975PyUnicode_EncodeASCII(const Py_UNICODE *p,
6976 Py_ssize_t size,
6977 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006978{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006979 PyObject *result;
6980 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6981 if (unicode == NULL)
6982 return NULL;
6983 result = unicode_encode_ucs1(unicode, errors, 128);
6984 Py_DECREF(unicode);
6985 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006986}
6987
Alexander Belopolsky40018472011-02-26 01:02:56 +00006988PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006989_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006990{
6991 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006992 PyErr_BadArgument();
6993 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006994 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006995 if (PyUnicode_READY(unicode) == -1)
6996 return NULL;
6997 /* Fast path: if it is an ASCII-only string, construct bytes object
6998 directly. Else defer to above function to raise the exception. */
6999 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
7000 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
7001 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007002 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007003}
7004
7005PyObject *
7006PyUnicode_AsASCIIString(PyObject *unicode)
7007{
7008 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007009}
7010
Victor Stinner99b95382011-07-04 14:23:54 +02007011#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007012
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007013/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007014
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00007015#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007016#define NEED_RETRY
7017#endif
7018
Victor Stinner3a50e702011-10-18 21:21:00 +02007019#ifndef WC_ERR_INVALID_CHARS
7020# define WC_ERR_INVALID_CHARS 0x0080
7021#endif
7022
7023static char*
7024code_page_name(UINT code_page, PyObject **obj)
7025{
7026 *obj = NULL;
7027 if (code_page == CP_ACP)
7028 return "mbcs";
7029 if (code_page == CP_UTF7)
7030 return "CP_UTF7";
7031 if (code_page == CP_UTF8)
7032 return "CP_UTF8";
7033
7034 *obj = PyBytes_FromFormat("cp%u", code_page);
7035 if (*obj == NULL)
7036 return NULL;
7037 return PyBytes_AS_STRING(*obj);
7038}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007039
Alexander Belopolsky40018472011-02-26 01:02:56 +00007040static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007041is_dbcs_lead_byte(UINT code_page, const char *s, int offset)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007042{
7043 const char *curr = s + offset;
Victor Stinner3a50e702011-10-18 21:21:00 +02007044 const char *prev;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007045
Victor Stinner3a50e702011-10-18 21:21:00 +02007046 if (!IsDBCSLeadByteEx(code_page, *curr))
7047 return 0;
7048
7049 prev = CharPrevExA(code_page, s, curr, 0);
7050 if (prev == curr)
7051 return 1;
7052 /* FIXME: This code is limited to "true" double-byte encodings,
7053 as it assumes an incomplete character consists of a single
7054 byte. */
7055 if (curr - prev == 2)
7056 return 1;
7057 if (!IsDBCSLeadByteEx(code_page, *prev))
7058 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007059 return 0;
7060}
7061
Victor Stinner3a50e702011-10-18 21:21:00 +02007062static DWORD
7063decode_code_page_flags(UINT code_page)
7064{
7065 if (code_page == CP_UTF7) {
7066 /* The CP_UTF7 decoder only supports flags=0 */
7067 return 0;
7068 }
7069 else
7070 return MB_ERR_INVALID_CHARS;
7071}
7072
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007073/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007074 * Decode a byte string from a Windows code page into unicode object in strict
7075 * mode.
7076 *
7077 * Returns consumed size if succeed, returns -2 on decode error, or raise a
7078 * WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007079 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007080static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007081decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007082 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02007083 const char *in,
7084 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007085{
Victor Stinner3a50e702011-10-18 21:21:00 +02007086 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01007087 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007088 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007089
7090 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007091 assert(insize > 0);
7092 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
7093 if (outsize <= 0)
7094 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007095
7096 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007097 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01007098 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007099 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00007100 if (*v == NULL)
7101 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007102 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007103 }
7104 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007105 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007106 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01007107 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007108 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007109 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007110 }
7111
7112 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007113 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
7114 if (outsize <= 0)
7115 goto error;
7116 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007117
Victor Stinner3a50e702011-10-18 21:21:00 +02007118error:
7119 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7120 return -2;
7121 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007122 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007123}
7124
Victor Stinner3a50e702011-10-18 21:21:00 +02007125/*
7126 * Decode a byte string from a code page into unicode object with an error
7127 * handler.
7128 *
7129 * Returns consumed size if succeed, or raise a WindowsError or
7130 * UnicodeDecodeError exception and returns -1 on error.
7131 */
7132static int
7133decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007134 PyObject **v,
7135 const char *in, const int size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007136 const char *errors)
7137{
7138 const char *startin = in;
7139 const char *endin = in + size;
7140 const DWORD flags = decode_code_page_flags(code_page);
7141 /* Ideally, we should get reason from FormatMessage. This is the Windows
7142 2000 English version of the message. */
7143 const char *reason = "No mapping for the Unicode character exists "
7144 "in the target code page.";
7145 /* each step cannot decode more than 1 character, but a character can be
7146 represented as a surrogate pair */
7147 wchar_t buffer[2], *startout, *out;
7148 int insize, outsize;
7149 PyObject *errorHandler = NULL;
7150 PyObject *exc = NULL;
7151 PyObject *encoding_obj = NULL;
7152 char *encoding;
7153 DWORD err;
7154 int ret = -1;
7155
7156 assert(size > 0);
7157
7158 encoding = code_page_name(code_page, &encoding_obj);
7159 if (encoding == NULL)
7160 return -1;
7161
7162 if (errors == NULL || strcmp(errors, "strict") == 0) {
7163 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
7164 UnicodeDecodeError. */
7165 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
7166 if (exc != NULL) {
7167 PyCodec_StrictErrors(exc);
7168 Py_CLEAR(exc);
7169 }
7170 goto error;
7171 }
7172
7173 if (*v == NULL) {
7174 /* Create unicode object */
7175 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7176 PyErr_NoMemory();
7177 goto error;
7178 }
Victor Stinnerab595942011-12-17 04:59:06 +01007179 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007180 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02007181 if (*v == NULL)
7182 goto error;
7183 startout = PyUnicode_AS_UNICODE(*v);
7184 }
7185 else {
7186 /* Extend unicode object */
7187 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
7188 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7189 PyErr_NoMemory();
7190 goto error;
7191 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007192 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007193 goto error;
7194 startout = PyUnicode_AS_UNICODE(*v) + n;
7195 }
7196
7197 /* Decode the byte string character per character */
7198 out = startout;
7199 while (in < endin)
7200 {
7201 /* Decode a character */
7202 insize = 1;
7203 do
7204 {
7205 outsize = MultiByteToWideChar(code_page, flags,
7206 in, insize,
7207 buffer, Py_ARRAY_LENGTH(buffer));
7208 if (outsize > 0)
7209 break;
7210 err = GetLastError();
7211 if (err != ERROR_NO_UNICODE_TRANSLATION
7212 && err != ERROR_INSUFFICIENT_BUFFER)
7213 {
7214 PyErr_SetFromWindowsErr(0);
7215 goto error;
7216 }
7217 insize++;
7218 }
7219 /* 4=maximum length of a UTF-8 sequence */
7220 while (insize <= 4 && (in + insize) <= endin);
7221
7222 if (outsize <= 0) {
7223 Py_ssize_t startinpos, endinpos, outpos;
7224
7225 startinpos = in - startin;
7226 endinpos = startinpos + 1;
7227 outpos = out - PyUnicode_AS_UNICODE(*v);
7228 if (unicode_decode_call_errorhandler(
7229 errors, &errorHandler,
7230 encoding, reason,
7231 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01007232 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02007233 {
7234 goto error;
7235 }
Victor Stinner596a6c42011-11-09 00:02:18 +01007236 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007237 }
7238 else {
7239 in += insize;
7240 memcpy(out, buffer, outsize * sizeof(wchar_t));
7241 out += outsize;
7242 }
7243 }
7244
7245 /* write a NUL character at the end */
7246 *out = 0;
7247
7248 /* Extend unicode object */
7249 outsize = out - startout;
7250 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01007251 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007252 goto error;
Victor Stinner76a31a62011-11-04 00:05:13 +01007253 ret = size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007254
7255error:
7256 Py_XDECREF(encoding_obj);
7257 Py_XDECREF(errorHandler);
7258 Py_XDECREF(exc);
7259 return ret;
7260}
7261
Victor Stinner3a50e702011-10-18 21:21:00 +02007262static PyObject *
7263decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007264 const char *s, Py_ssize_t size,
7265 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007266{
Victor Stinner76a31a62011-11-04 00:05:13 +01007267 PyObject *v = NULL;
7268 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007269
Victor Stinner3a50e702011-10-18 21:21:00 +02007270 if (code_page < 0) {
7271 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7272 return NULL;
7273 }
7274
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007275 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007276 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007277
Victor Stinner76a31a62011-11-04 00:05:13 +01007278 do
7279 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007280#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007281 if (size > INT_MAX) {
7282 chunk_size = INT_MAX;
7283 final = 0;
7284 done = 0;
7285 }
7286 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007287#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007288 {
7289 chunk_size = (int)size;
7290 final = (consumed == NULL);
7291 done = 1;
7292 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007293
Victor Stinner76a31a62011-11-04 00:05:13 +01007294 /* Skip trailing lead-byte unless 'final' is set */
7295 if (!final && is_dbcs_lead_byte(code_page, s, chunk_size - 1))
7296 --chunk_size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007297
Victor Stinner76a31a62011-11-04 00:05:13 +01007298 if (chunk_size == 0 && done) {
7299 if (v != NULL)
7300 break;
7301 Py_INCREF(unicode_empty);
7302 return unicode_empty;
7303 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007304
Victor Stinner76a31a62011-11-04 00:05:13 +01007305
7306 converted = decode_code_page_strict(code_page, &v,
7307 s, chunk_size);
7308 if (converted == -2)
7309 converted = decode_code_page_errors(code_page, &v,
7310 s, chunk_size,
7311 errors);
7312 assert(converted != 0);
7313
7314 if (converted < 0) {
7315 Py_XDECREF(v);
7316 return NULL;
7317 }
7318
7319 if (consumed)
7320 *consumed += converted;
7321
7322 s += converted;
7323 size -= converted;
7324 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007325
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007326 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007327}
7328
Alexander Belopolsky40018472011-02-26 01:02:56 +00007329PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007330PyUnicode_DecodeCodePageStateful(int code_page,
7331 const char *s,
7332 Py_ssize_t size,
7333 const char *errors,
7334 Py_ssize_t *consumed)
7335{
7336 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7337}
7338
7339PyObject *
7340PyUnicode_DecodeMBCSStateful(const char *s,
7341 Py_ssize_t size,
7342 const char *errors,
7343 Py_ssize_t *consumed)
7344{
7345 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7346}
7347
7348PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007349PyUnicode_DecodeMBCS(const char *s,
7350 Py_ssize_t size,
7351 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007352{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007353 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7354}
7355
Victor Stinner3a50e702011-10-18 21:21:00 +02007356static DWORD
7357encode_code_page_flags(UINT code_page, const char *errors)
7358{
7359 if (code_page == CP_UTF8) {
7360 if (winver.dwMajorVersion >= 6)
7361 /* CP_UTF8 supports WC_ERR_INVALID_CHARS on Windows Vista
7362 and later */
7363 return WC_ERR_INVALID_CHARS;
7364 else
7365 /* CP_UTF8 only supports flags=0 on Windows older than Vista */
7366 return 0;
7367 }
7368 else if (code_page == CP_UTF7) {
7369 /* CP_UTF7 only supports flags=0 */
7370 return 0;
7371 }
7372 else {
7373 if (errors != NULL && strcmp(errors, "replace") == 0)
7374 return 0;
7375 else
7376 return WC_NO_BEST_FIT_CHARS;
7377 }
7378}
7379
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007380/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007381 * Encode a Unicode string to a Windows code page into a byte string in strict
7382 * mode.
7383 *
7384 * Returns consumed characters if succeed, returns -2 on encode error, or raise
7385 * a WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007386 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007387static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007388encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007389 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007390 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007391{
Victor Stinner554f3f02010-06-16 23:33:54 +00007392 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007393 BOOL *pusedDefaultChar = &usedDefaultChar;
7394 int outsize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007395 PyObject *exc = NULL;
Victor Stinner24729f32011-11-10 20:31:37 +01007396 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007397 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007398 const DWORD flags = encode_code_page_flags(code_page, NULL);
7399 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007400 /* Create a substring so that we can get the UTF-16 representation
7401 of just the slice under consideration. */
7402 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007403
Martin v. Löwis3d325192011-11-04 18:23:06 +01007404 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007405
Victor Stinner3a50e702011-10-18 21:21:00 +02007406 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007407 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007408 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007409 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007410
Victor Stinner2fc507f2011-11-04 20:06:39 +01007411 substring = PyUnicode_Substring(unicode, offset, offset+len);
7412 if (substring == NULL)
7413 return -1;
7414 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7415 if (p == NULL) {
7416 Py_DECREF(substring);
7417 return -1;
7418 }
Martin v. Löwis3d325192011-11-04 18:23:06 +01007419
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007420 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007421 outsize = WideCharToMultiByte(code_page, flags,
7422 p, size,
7423 NULL, 0,
7424 NULL, pusedDefaultChar);
7425 if (outsize <= 0)
7426 goto error;
7427 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007428 if (pusedDefaultChar && *pusedDefaultChar) {
7429 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007430 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007431 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007432
Victor Stinner3a50e702011-10-18 21:21:00 +02007433 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007434 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007435 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007436 if (*outbytes == NULL) {
7437 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007438 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007439 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007440 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007441 }
7442 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007443 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007444 const Py_ssize_t n = PyBytes_Size(*outbytes);
7445 if (outsize > PY_SSIZE_T_MAX - n) {
7446 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007447 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007448 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007449 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007450 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7451 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007452 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007453 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007454 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007455 }
7456
7457 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007458 outsize = WideCharToMultiByte(code_page, flags,
7459 p, size,
7460 out, outsize,
7461 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007462 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007463 if (outsize <= 0)
7464 goto error;
7465 if (pusedDefaultChar && *pusedDefaultChar)
7466 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007467 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007468
Victor Stinner3a50e702011-10-18 21:21:00 +02007469error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007470 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007471 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7472 return -2;
7473 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007474 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007475}
7476
Victor Stinner3a50e702011-10-18 21:21:00 +02007477/*
7478 * Encode a Unicode string to a Windows code page into a byte string using a
7479 * error handler.
7480 *
7481 * Returns consumed characters if succeed, or raise a WindowsError and returns
7482 * -1 on other error.
7483 */
7484static int
7485encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007486 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007487 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007488{
Victor Stinner3a50e702011-10-18 21:21:00 +02007489 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007490 Py_ssize_t pos = unicode_offset;
7491 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007492 /* Ideally, we should get reason from FormatMessage. This is the Windows
7493 2000 English version of the message. */
7494 const char *reason = "invalid character";
7495 /* 4=maximum length of a UTF-8 sequence */
7496 char buffer[4];
7497 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7498 Py_ssize_t outsize;
7499 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007500 PyObject *errorHandler = NULL;
7501 PyObject *exc = NULL;
7502 PyObject *encoding_obj = NULL;
7503 char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007504 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007505 PyObject *rep;
7506 int ret = -1;
7507
7508 assert(insize > 0);
7509
7510 encoding = code_page_name(code_page, &encoding_obj);
7511 if (encoding == NULL)
7512 return -1;
7513
7514 if (errors == NULL || strcmp(errors, "strict") == 0) {
7515 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7516 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007517 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007518 if (exc != NULL) {
7519 PyCodec_StrictErrors(exc);
7520 Py_DECREF(exc);
7521 }
7522 Py_XDECREF(encoding_obj);
7523 return -1;
7524 }
7525
7526 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7527 pusedDefaultChar = &usedDefaultChar;
7528 else
7529 pusedDefaultChar = NULL;
7530
7531 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7532 PyErr_NoMemory();
7533 goto error;
7534 }
7535 outsize = insize * Py_ARRAY_LENGTH(buffer);
7536
7537 if (*outbytes == NULL) {
7538 /* Create string object */
7539 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7540 if (*outbytes == NULL)
7541 goto error;
7542 out = PyBytes_AS_STRING(*outbytes);
7543 }
7544 else {
7545 /* Extend string object */
7546 Py_ssize_t n = PyBytes_Size(*outbytes);
7547 if (n > PY_SSIZE_T_MAX - outsize) {
7548 PyErr_NoMemory();
7549 goto error;
7550 }
7551 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7552 goto error;
7553 out = PyBytes_AS_STRING(*outbytes) + n;
7554 }
7555
7556 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007557 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007558 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007559 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7560 wchar_t chars[2];
7561 int charsize;
7562 if (ch < 0x10000) {
7563 chars[0] = (wchar_t)ch;
7564 charsize = 1;
7565 }
7566 else {
7567 ch -= 0x10000;
7568 chars[0] = 0xd800 + (ch >> 10);
7569 chars[1] = 0xdc00 + (ch & 0x3ff);
7570 charsize = 2;
7571 }
7572
Victor Stinner3a50e702011-10-18 21:21:00 +02007573 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007574 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007575 buffer, Py_ARRAY_LENGTH(buffer),
7576 NULL, pusedDefaultChar);
7577 if (outsize > 0) {
7578 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7579 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007580 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007581 memcpy(out, buffer, outsize);
7582 out += outsize;
7583 continue;
7584 }
7585 }
7586 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7587 PyErr_SetFromWindowsErr(0);
7588 goto error;
7589 }
7590
Victor Stinner3a50e702011-10-18 21:21:00 +02007591 rep = unicode_encode_call_errorhandler(
7592 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007593 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007594 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007595 if (rep == NULL)
7596 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007597 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007598
7599 if (PyBytes_Check(rep)) {
7600 outsize = PyBytes_GET_SIZE(rep);
7601 if (outsize != 1) {
7602 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7603 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7604 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7605 Py_DECREF(rep);
7606 goto error;
7607 }
7608 out = PyBytes_AS_STRING(*outbytes) + offset;
7609 }
7610 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7611 out += outsize;
7612 }
7613 else {
7614 Py_ssize_t i;
7615 enum PyUnicode_Kind kind;
7616 void *data;
7617
Benjamin Petersonbac79492012-01-14 13:34:47 -05007618 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007619 Py_DECREF(rep);
7620 goto error;
7621 }
7622
7623 outsize = PyUnicode_GET_LENGTH(rep);
7624 if (outsize != 1) {
7625 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7626 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7627 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7628 Py_DECREF(rep);
7629 goto error;
7630 }
7631 out = PyBytes_AS_STRING(*outbytes) + offset;
7632 }
7633 kind = PyUnicode_KIND(rep);
7634 data = PyUnicode_DATA(rep);
7635 for (i=0; i < outsize; i++) {
7636 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7637 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007638 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007639 encoding, unicode,
7640 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007641 "unable to encode error handler result to ASCII");
7642 Py_DECREF(rep);
7643 goto error;
7644 }
7645 *out = (unsigned char)ch;
7646 out++;
7647 }
7648 }
7649 Py_DECREF(rep);
7650 }
7651 /* write a NUL byte */
7652 *out = 0;
7653 outsize = out - PyBytes_AS_STRING(*outbytes);
7654 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7655 if (_PyBytes_Resize(outbytes, outsize) < 0)
7656 goto error;
7657 ret = 0;
7658
7659error:
7660 Py_XDECREF(encoding_obj);
7661 Py_XDECREF(errorHandler);
7662 Py_XDECREF(exc);
7663 return ret;
7664}
7665
Victor Stinner3a50e702011-10-18 21:21:00 +02007666static PyObject *
7667encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007668 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007669 const char *errors)
7670{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007671 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007672 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007673 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007674 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007675
Benjamin Petersonbac79492012-01-14 13:34:47 -05007676 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007677 return NULL;
7678 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007679
Victor Stinner3a50e702011-10-18 21:21:00 +02007680 if (code_page < 0) {
7681 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7682 return NULL;
7683 }
7684
Martin v. Löwis3d325192011-11-04 18:23:06 +01007685 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007686 return PyBytes_FromStringAndSize(NULL, 0);
7687
Victor Stinner7581cef2011-11-03 22:32:33 +01007688 offset = 0;
7689 do
7690 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007691#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007692 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007693 chunks. */
7694 if (len > INT_MAX/2) {
7695 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007696 done = 0;
7697 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007698 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007699#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007700 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007701 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007702 done = 1;
7703 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007704
Victor Stinner76a31a62011-11-04 00:05:13 +01007705 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007706 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007707 errors);
7708 if (ret == -2)
7709 ret = encode_code_page_errors(code_page, &outbytes,
7710 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007711 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007712 if (ret < 0) {
7713 Py_XDECREF(outbytes);
7714 return NULL;
7715 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007716
Victor Stinner7581cef2011-11-03 22:32:33 +01007717 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007718 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007719 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007720
Victor Stinner3a50e702011-10-18 21:21:00 +02007721 return outbytes;
7722}
7723
7724PyObject *
7725PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7726 Py_ssize_t size,
7727 const char *errors)
7728{
Victor Stinner7581cef2011-11-03 22:32:33 +01007729 PyObject *unicode, *res;
7730 unicode = PyUnicode_FromUnicode(p, size);
7731 if (unicode == NULL)
7732 return NULL;
7733 res = encode_code_page(CP_ACP, unicode, errors);
7734 Py_DECREF(unicode);
7735 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007736}
7737
7738PyObject *
7739PyUnicode_EncodeCodePage(int code_page,
7740 PyObject *unicode,
7741 const char *errors)
7742{
Victor Stinner7581cef2011-11-03 22:32:33 +01007743 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007744}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007745
Alexander Belopolsky40018472011-02-26 01:02:56 +00007746PyObject *
7747PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007748{
7749 if (!PyUnicode_Check(unicode)) {
7750 PyErr_BadArgument();
7751 return NULL;
7752 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007753 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007754}
7755
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007756#undef NEED_RETRY
7757
Victor Stinner99b95382011-07-04 14:23:54 +02007758#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007759
Guido van Rossumd57fd912000-03-10 22:53:23 +00007760/* --- Character Mapping Codec -------------------------------------------- */
7761
Alexander Belopolsky40018472011-02-26 01:02:56 +00007762PyObject *
7763PyUnicode_DecodeCharmap(const char *s,
7764 Py_ssize_t size,
7765 PyObject *mapping,
7766 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007767{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007768 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007769 Py_ssize_t startinpos;
7770 Py_ssize_t endinpos;
7771 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007772 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01007773 PyObject *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007774 Py_ssize_t extrachars = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007775 PyObject *errorHandler = NULL;
7776 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00007777
Guido van Rossumd57fd912000-03-10 22:53:23 +00007778 /* Default to Latin-1 */
7779 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007780 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007781
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007782 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007783 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007784 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007785 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01007786 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007787 outpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007788 e = s + size;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007789 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007790 Py_ssize_t maplen;
7791 enum PyUnicode_Kind kind;
7792 void *data;
7793 Py_UCS4 x;
7794
Benjamin Petersonbac79492012-01-14 13:34:47 -05007795 if (PyUnicode_READY(mapping) == -1)
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007796 return NULL;
7797
7798 maplen = PyUnicode_GET_LENGTH(mapping);
7799 data = PyUnicode_DATA(mapping);
7800 kind = PyUnicode_KIND(mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007801 while (s < e) {
7802 unsigned char ch = *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007803
Benjamin Peterson29060642009-01-31 22:14:21 +00007804 if (ch < maplen)
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007805 x = PyUnicode_READ(kind, data, ch);
7806 else
7807 x = 0xfffe; /* invalid value */
Guido van Rossumd57fd912000-03-10 22:53:23 +00007808
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007809 if (x == 0xfffe)
7810 {
Benjamin Peterson29060642009-01-31 22:14:21 +00007811 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007812 startinpos = s-starts;
7813 endinpos = startinpos+1;
7814 if (unicode_decode_call_errorhandler(
7815 errors, &errorHandler,
7816 "charmap", "character maps to <undefined>",
7817 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007818 &v, &outpos)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007819 goto onError;
7820 }
7821 continue;
7822 }
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007823
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007824 if (unicode_putchar(&v, &outpos, x) < 0)
7825 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007826 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007827 }
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007828 }
7829 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007830 while (s < e) {
7831 unsigned char ch = *s;
7832 PyObject *w, *x;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007833
Benjamin Peterson29060642009-01-31 22:14:21 +00007834 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7835 w = PyLong_FromLong((long)ch);
7836 if (w == NULL)
7837 goto onError;
7838 x = PyObject_GetItem(mapping, w);
7839 Py_DECREF(w);
7840 if (x == NULL) {
7841 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7842 /* No mapping found means: mapping is undefined. */
7843 PyErr_Clear();
7844 x = Py_None;
7845 Py_INCREF(x);
7846 } else
7847 goto onError;
7848 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007849
Benjamin Peterson29060642009-01-31 22:14:21 +00007850 /* Apply mapping */
7851 if (PyLong_Check(x)) {
7852 long value = PyLong_AS_LONG(x);
7853 if (value < 0 || value > 65535) {
7854 PyErr_SetString(PyExc_TypeError,
7855 "character mapping must be in range(65536)");
7856 Py_DECREF(x);
7857 goto onError;
7858 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007859 if (unicode_putchar(&v, &outpos, value) < 0)
7860 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007861 }
7862 else if (x == Py_None) {
7863 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007864 startinpos = s-starts;
7865 endinpos = startinpos+1;
7866 if (unicode_decode_call_errorhandler(
7867 errors, &errorHandler,
7868 "charmap", "character maps to <undefined>",
7869 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007870 &v, &outpos)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007871 Py_DECREF(x);
7872 goto onError;
7873 }
7874 Py_DECREF(x);
7875 continue;
7876 }
7877 else if (PyUnicode_Check(x)) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007878 Py_ssize_t targetsize;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007879
Benjamin Petersonbac79492012-01-14 13:34:47 -05007880 if (PyUnicode_READY(x) == -1)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007881 goto onError;
7882 targetsize = PyUnicode_GET_LENGTH(x);
7883
7884 if (targetsize == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007885 /* 1-1 mapping */
Victor Stinner62aa4d02011-11-09 00:03:45 +01007886 if (unicode_putchar(&v, &outpos,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007887 PyUnicode_READ_CHAR(x, 0)) < 0)
7888 goto onError;
7889 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007890 else if (targetsize > 1) {
7891 /* 1-n mapping */
7892 if (targetsize > extrachars) {
7893 /* resize first */
Benjamin Peterson29060642009-01-31 22:14:21 +00007894 Py_ssize_t needed = (targetsize - extrachars) + \
7895 (targetsize << 2);
7896 extrachars += needed;
7897 /* XXX overflow detection missing */
Victor Stinner16e6a802011-12-12 13:24:15 +01007898 if (unicode_resize(&v,
7899 PyUnicode_GET_LENGTH(v) + needed) < 0)
7900 {
Benjamin Peterson29060642009-01-31 22:14:21 +00007901 Py_DECREF(x);
7902 goto onError;
7903 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007904 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007905 if (unicode_widen(&v, PyUnicode_MAX_CHAR_VALUE(x)) < 0)
7906 goto onError;
7907 PyUnicode_CopyCharacters(v, outpos, x, 0, targetsize);
7908 outpos += targetsize;
Benjamin Peterson29060642009-01-31 22:14:21 +00007909 extrachars -= targetsize;
7910 }
7911 /* 1-0 mapping: skip the character */
7912 }
7913 else {
7914 /* wrong return value */
7915 PyErr_SetString(PyExc_TypeError,
7916 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00007917 Py_DECREF(x);
7918 goto onError;
7919 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007920 Py_DECREF(x);
7921 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007922 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007923 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007924 if (unicode_resize(&v, outpos) < 0)
Antoine Pitroua8f63c02011-11-08 18:37:16 +01007925 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007926 Py_XDECREF(errorHandler);
7927 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007928 return unicode_result(v);
Tim Petersced69f82003-09-16 20:30:58 +00007929
Benjamin Peterson29060642009-01-31 22:14:21 +00007930 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007931 Py_XDECREF(errorHandler);
7932 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007933 Py_XDECREF(v);
7934 return NULL;
7935}
7936
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007937/* Charmap encoding: the lookup table */
7938
Alexander Belopolsky40018472011-02-26 01:02:56 +00007939struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007940 PyObject_HEAD
7941 unsigned char level1[32];
7942 int count2, count3;
7943 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007944};
7945
7946static PyObject*
7947encoding_map_size(PyObject *obj, PyObject* args)
7948{
7949 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007950 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007951 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007952}
7953
7954static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007955 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007956 PyDoc_STR("Return the size (in bytes) of this object") },
7957 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007958};
7959
7960static void
7961encoding_map_dealloc(PyObject* o)
7962{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007963 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007964}
7965
7966static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007967 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007968 "EncodingMap", /*tp_name*/
7969 sizeof(struct encoding_map), /*tp_basicsize*/
7970 0, /*tp_itemsize*/
7971 /* methods */
7972 encoding_map_dealloc, /*tp_dealloc*/
7973 0, /*tp_print*/
7974 0, /*tp_getattr*/
7975 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007976 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007977 0, /*tp_repr*/
7978 0, /*tp_as_number*/
7979 0, /*tp_as_sequence*/
7980 0, /*tp_as_mapping*/
7981 0, /*tp_hash*/
7982 0, /*tp_call*/
7983 0, /*tp_str*/
7984 0, /*tp_getattro*/
7985 0, /*tp_setattro*/
7986 0, /*tp_as_buffer*/
7987 Py_TPFLAGS_DEFAULT, /*tp_flags*/
7988 0, /*tp_doc*/
7989 0, /*tp_traverse*/
7990 0, /*tp_clear*/
7991 0, /*tp_richcompare*/
7992 0, /*tp_weaklistoffset*/
7993 0, /*tp_iter*/
7994 0, /*tp_iternext*/
7995 encoding_map_methods, /*tp_methods*/
7996 0, /*tp_members*/
7997 0, /*tp_getset*/
7998 0, /*tp_base*/
7999 0, /*tp_dict*/
8000 0, /*tp_descr_get*/
8001 0, /*tp_descr_set*/
8002 0, /*tp_dictoffset*/
8003 0, /*tp_init*/
8004 0, /*tp_alloc*/
8005 0, /*tp_new*/
8006 0, /*tp_free*/
8007 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008008};
8009
8010PyObject*
8011PyUnicode_BuildEncodingMap(PyObject* string)
8012{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008013 PyObject *result;
8014 struct encoding_map *mresult;
8015 int i;
8016 int need_dict = 0;
8017 unsigned char level1[32];
8018 unsigned char level2[512];
8019 unsigned char *mlevel1, *mlevel2, *mlevel3;
8020 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008021 int kind;
8022 void *data;
8023 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008024
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008025 if (!PyUnicode_Check(string) || PyUnicode_GET_LENGTH(string) != 256) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008026 PyErr_BadArgument();
8027 return NULL;
8028 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008029 kind = PyUnicode_KIND(string);
8030 data = PyUnicode_DATA(string);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008031 memset(level1, 0xFF, sizeof level1);
8032 memset(level2, 0xFF, sizeof level2);
8033
8034 /* If there isn't a one-to-one mapping of NULL to \0,
8035 or if there are non-BMP characters, we need to use
8036 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008037 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008038 need_dict = 1;
8039 for (i = 1; i < 256; i++) {
8040 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008041 ch = PyUnicode_READ(kind, data, i);
8042 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008043 need_dict = 1;
8044 break;
8045 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008046 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008047 /* unmapped character */
8048 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008049 l1 = ch >> 11;
8050 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008051 if (level1[l1] == 0xFF)
8052 level1[l1] = count2++;
8053 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00008054 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008055 }
8056
8057 if (count2 >= 0xFF || count3 >= 0xFF)
8058 need_dict = 1;
8059
8060 if (need_dict) {
8061 PyObject *result = PyDict_New();
8062 PyObject *key, *value;
8063 if (!result)
8064 return NULL;
8065 for (i = 0; i < 256; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008066 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00008067 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008068 if (!key || !value)
8069 goto failed1;
8070 if (PyDict_SetItem(result, key, value) == -1)
8071 goto failed1;
8072 Py_DECREF(key);
8073 Py_DECREF(value);
8074 }
8075 return result;
8076 failed1:
8077 Py_XDECREF(key);
8078 Py_XDECREF(value);
8079 Py_DECREF(result);
8080 return NULL;
8081 }
8082
8083 /* Create a three-level trie */
8084 result = PyObject_MALLOC(sizeof(struct encoding_map) +
8085 16*count2 + 128*count3 - 1);
8086 if (!result)
8087 return PyErr_NoMemory();
8088 PyObject_Init(result, &EncodingMapType);
8089 mresult = (struct encoding_map*)result;
8090 mresult->count2 = count2;
8091 mresult->count3 = count3;
8092 mlevel1 = mresult->level1;
8093 mlevel2 = mresult->level23;
8094 mlevel3 = mresult->level23 + 16*count2;
8095 memcpy(mlevel1, level1, 32);
8096 memset(mlevel2, 0xFF, 16*count2);
8097 memset(mlevel3, 0, 128*count3);
8098 count3 = 0;
8099 for (i = 1; i < 256; i++) {
8100 int o1, o2, o3, i2, i3;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008101 if (PyUnicode_READ(kind, data, i) == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008102 /* unmapped character */
8103 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008104 o1 = PyUnicode_READ(kind, data, i)>>11;
8105 o2 = (PyUnicode_READ(kind, data, i)>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008106 i2 = 16*mlevel1[o1] + o2;
8107 if (mlevel2[i2] == 0xFF)
8108 mlevel2[i2] = count3++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008109 o3 = PyUnicode_READ(kind, data, i) & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008110 i3 = 128*mlevel2[i2] + o3;
8111 mlevel3[i3] = i;
8112 }
8113 return result;
8114}
8115
8116static int
Victor Stinner22168992011-11-20 17:09:18 +01008117encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008118{
8119 struct encoding_map *map = (struct encoding_map*)mapping;
8120 int l1 = c>>11;
8121 int l2 = (c>>7) & 0xF;
8122 int l3 = c & 0x7F;
8123 int i;
8124
Victor Stinner22168992011-11-20 17:09:18 +01008125 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00008126 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008127 if (c == 0)
8128 return 0;
8129 /* level 1*/
8130 i = map->level1[l1];
8131 if (i == 0xFF) {
8132 return -1;
8133 }
8134 /* level 2*/
8135 i = map->level23[16*i+l2];
8136 if (i == 0xFF) {
8137 return -1;
8138 }
8139 /* level 3 */
8140 i = map->level23[16*map->count2 + 128*i + l3];
8141 if (i == 0) {
8142 return -1;
8143 }
8144 return i;
8145}
8146
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008147/* Lookup the character ch in the mapping. If the character
8148 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00008149 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008150static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01008151charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008152{
Christian Heimes217cfd12007-12-02 14:31:20 +00008153 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008154 PyObject *x;
8155
8156 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008157 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008158 x = PyObject_GetItem(mapping, w);
8159 Py_DECREF(w);
8160 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008161 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8162 /* No mapping found means: mapping is undefined. */
8163 PyErr_Clear();
8164 x = Py_None;
8165 Py_INCREF(x);
8166 return x;
8167 } else
8168 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008169 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00008170 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008171 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00008172 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008173 long value = PyLong_AS_LONG(x);
8174 if (value < 0 || value > 255) {
8175 PyErr_SetString(PyExc_TypeError,
8176 "character mapping must be in range(256)");
8177 Py_DECREF(x);
8178 return NULL;
8179 }
8180 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008181 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008182 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008183 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008184 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008185 /* wrong return value */
8186 PyErr_Format(PyExc_TypeError,
8187 "character mapping must return integer, bytes or None, not %.400s",
8188 x->ob_type->tp_name);
8189 Py_DECREF(x);
8190 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008191 }
8192}
8193
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008194static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008195charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008196{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008197 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8198 /* exponentially overallocate to minimize reallocations */
8199 if (requiredsize < 2*outsize)
8200 requiredsize = 2*outsize;
8201 if (_PyBytes_Resize(outobj, requiredsize))
8202 return -1;
8203 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008204}
8205
Benjamin Peterson14339b62009-01-31 16:36:08 +00008206typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008207 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008208} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008209/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008210 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008211 space is available. Return a new reference to the object that
8212 was put in the output buffer, or Py_None, if the mapping was undefined
8213 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008214 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008215static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01008216charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008217 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008218{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008219 PyObject *rep;
8220 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008221 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008222
Christian Heimes90aa7642007-12-19 02:45:37 +00008223 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008224 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008225 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008226 if (res == -1)
8227 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008228 if (outsize<requiredsize)
8229 if (charmapencode_resize(outobj, outpos, requiredsize))
8230 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008231 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008232 outstart[(*outpos)++] = (char)res;
8233 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008234 }
8235
8236 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008237 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008238 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008239 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008240 Py_DECREF(rep);
8241 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008242 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008243 if (PyLong_Check(rep)) {
8244 Py_ssize_t requiredsize = *outpos+1;
8245 if (outsize<requiredsize)
8246 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8247 Py_DECREF(rep);
8248 return enc_EXCEPTION;
8249 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008250 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008251 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008252 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008253 else {
8254 const char *repchars = PyBytes_AS_STRING(rep);
8255 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8256 Py_ssize_t requiredsize = *outpos+repsize;
8257 if (outsize<requiredsize)
8258 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8259 Py_DECREF(rep);
8260 return enc_EXCEPTION;
8261 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008262 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008263 memcpy(outstart + *outpos, repchars, repsize);
8264 *outpos += repsize;
8265 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008266 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008267 Py_DECREF(rep);
8268 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008269}
8270
8271/* handle an error in PyUnicode_EncodeCharmap
8272 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008273static int
8274charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008275 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008276 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00008277 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008278 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008279{
8280 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008281 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008282 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008283 enum PyUnicode_Kind kind;
8284 void *data;
8285 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008286 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008287 Py_ssize_t collstartpos = *inpos;
8288 Py_ssize_t collendpos = *inpos+1;
8289 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008290 char *encoding = "charmap";
8291 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008292 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008293 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008294 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008295
Benjamin Petersonbac79492012-01-14 13:34:47 -05008296 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008297 return -1;
8298 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008299 /* find all unencodable characters */
8300 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008301 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008302 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008303 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008304 val = encoding_map_lookup(ch, mapping);
8305 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008306 break;
8307 ++collendpos;
8308 continue;
8309 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008310
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008311 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8312 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008313 if (rep==NULL)
8314 return -1;
8315 else if (rep!=Py_None) {
8316 Py_DECREF(rep);
8317 break;
8318 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008319 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008320 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008321 }
8322 /* cache callback name lookup
8323 * (if not done yet, i.e. it's the first error) */
8324 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008325 if ((errors==NULL) || (!strcmp(errors, "strict")))
8326 *known_errorHandler = 1;
8327 else if (!strcmp(errors, "replace"))
8328 *known_errorHandler = 2;
8329 else if (!strcmp(errors, "ignore"))
8330 *known_errorHandler = 3;
8331 else if (!strcmp(errors, "xmlcharrefreplace"))
8332 *known_errorHandler = 4;
8333 else
8334 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008335 }
8336 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008337 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008338 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008339 return -1;
8340 case 2: /* replace */
8341 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008342 x = charmapencode_output('?', mapping, res, respos);
8343 if (x==enc_EXCEPTION) {
8344 return -1;
8345 }
8346 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008347 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008348 return -1;
8349 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008350 }
8351 /* fall through */
8352 case 3: /* ignore */
8353 *inpos = collendpos;
8354 break;
8355 case 4: /* xmlcharrefreplace */
8356 /* generate replacement (temporarily (mis)uses p) */
8357 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008358 char buffer[2+29+1+1];
8359 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008360 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008361 for (cp = buffer; *cp; ++cp) {
8362 x = charmapencode_output(*cp, mapping, res, respos);
8363 if (x==enc_EXCEPTION)
8364 return -1;
8365 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008366 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008367 return -1;
8368 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008369 }
8370 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008371 *inpos = collendpos;
8372 break;
8373 default:
8374 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008375 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008376 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008377 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008378 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008379 if (PyBytes_Check(repunicode)) {
8380 /* Directly copy bytes result to output. */
8381 Py_ssize_t outsize = PyBytes_Size(*res);
8382 Py_ssize_t requiredsize;
8383 repsize = PyBytes_Size(repunicode);
8384 requiredsize = *respos + repsize;
8385 if (requiredsize > outsize)
8386 /* Make room for all additional bytes. */
8387 if (charmapencode_resize(res, respos, requiredsize)) {
8388 Py_DECREF(repunicode);
8389 return -1;
8390 }
8391 memcpy(PyBytes_AsString(*res) + *respos,
8392 PyBytes_AsString(repunicode), repsize);
8393 *respos += repsize;
8394 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008395 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008396 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008397 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008398 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008399 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008400 Py_DECREF(repunicode);
8401 return -1;
8402 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008403 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008404 data = PyUnicode_DATA(repunicode);
8405 kind = PyUnicode_KIND(repunicode);
8406 for (index = 0; index < repsize; index++) {
8407 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8408 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008409 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008410 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008411 return -1;
8412 }
8413 else if (x==enc_FAILED) {
8414 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008415 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008416 return -1;
8417 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008418 }
8419 *inpos = newpos;
8420 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008421 }
8422 return 0;
8423}
8424
Alexander Belopolsky40018472011-02-26 01:02:56 +00008425PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008426_PyUnicode_EncodeCharmap(PyObject *unicode,
8427 PyObject *mapping,
8428 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008429{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008430 /* output object */
8431 PyObject *res = NULL;
8432 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008433 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008434 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008435 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008436 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008437 PyObject *errorHandler = NULL;
8438 PyObject *exc = NULL;
8439 /* the following variable is used for caching string comparisons
8440 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8441 * 3=ignore, 4=xmlcharrefreplace */
8442 int known_errorHandler = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008443
Benjamin Petersonbac79492012-01-14 13:34:47 -05008444 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008445 return NULL;
8446 size = PyUnicode_GET_LENGTH(unicode);
8447
Guido van Rossumd57fd912000-03-10 22:53:23 +00008448 /* Default to Latin-1 */
8449 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008450 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008451
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008452 /* allocate enough for a simple encoding without
8453 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008454 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008455 if (res == NULL)
8456 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008457 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008458 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008459
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008460 while (inpos<size) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008461 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008462 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008463 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008464 if (x==enc_EXCEPTION) /* error */
8465 goto onError;
8466 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008467 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008468 &exc,
8469 &known_errorHandler, &errorHandler, errors,
8470 &res, &respos)) {
8471 goto onError;
8472 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008473 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008474 else
8475 /* done with this character => adjust input position */
8476 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008477 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008478
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008479 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008480 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008481 if (_PyBytes_Resize(&res, respos) < 0)
8482 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008483
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008484 Py_XDECREF(exc);
8485 Py_XDECREF(errorHandler);
8486 return res;
8487
Benjamin Peterson29060642009-01-31 22:14:21 +00008488 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008489 Py_XDECREF(res);
8490 Py_XDECREF(exc);
8491 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008492 return NULL;
8493}
8494
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008495/* Deprecated */
8496PyObject *
8497PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8498 Py_ssize_t size,
8499 PyObject *mapping,
8500 const char *errors)
8501{
8502 PyObject *result;
8503 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8504 if (unicode == NULL)
8505 return NULL;
8506 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8507 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008508 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008509}
8510
Alexander Belopolsky40018472011-02-26 01:02:56 +00008511PyObject *
8512PyUnicode_AsCharmapString(PyObject *unicode,
8513 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008514{
8515 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008516 PyErr_BadArgument();
8517 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008518 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008519 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008520}
8521
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008522/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008523static void
8524make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008525 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008526 Py_ssize_t startpos, Py_ssize_t endpos,
8527 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008528{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008529 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008530 *exceptionObject = _PyUnicodeTranslateError_Create(
8531 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008532 }
8533 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008534 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8535 goto onError;
8536 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8537 goto onError;
8538 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8539 goto onError;
8540 return;
8541 onError:
8542 Py_DECREF(*exceptionObject);
8543 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008544 }
8545}
8546
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008547/* raises a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008548static void
8549raise_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008550 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008551 Py_ssize_t startpos, Py_ssize_t endpos,
8552 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008553{
8554 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008555 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008556 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008557 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008558}
8559
8560/* error handling callback helper:
8561 build arguments, call the callback and check the arguments,
8562 put the result into newpos and return the replacement string, which
8563 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008564static PyObject *
8565unicode_translate_call_errorhandler(const char *errors,
8566 PyObject **errorHandler,
8567 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008568 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008569 Py_ssize_t startpos, Py_ssize_t endpos,
8570 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008571{
Benjamin Peterson142957c2008-07-04 19:55:29 +00008572 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008573
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008574 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008575 PyObject *restuple;
8576 PyObject *resunicode;
8577
8578 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008579 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008580 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008581 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008582 }
8583
8584 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008585 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008586 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008587 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008588
8589 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008590 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008591 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008592 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008593 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008594 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008595 Py_DECREF(restuple);
8596 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008597 }
8598 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008599 &resunicode, &i_newpos)) {
8600 Py_DECREF(restuple);
8601 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008602 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008603 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008604 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008605 else
8606 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008607 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008608 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
8609 Py_DECREF(restuple);
8610 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008611 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008612 Py_INCREF(resunicode);
8613 Py_DECREF(restuple);
8614 return resunicode;
8615}
8616
8617/* Lookup the character ch in the mapping and put the result in result,
8618 which must be decrefed by the caller.
8619 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008620static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008621charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008622{
Christian Heimes217cfd12007-12-02 14:31:20 +00008623 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008624 PyObject *x;
8625
8626 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008627 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008628 x = PyObject_GetItem(mapping, w);
8629 Py_DECREF(w);
8630 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008631 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8632 /* No mapping found means: use 1:1 mapping. */
8633 PyErr_Clear();
8634 *result = NULL;
8635 return 0;
8636 } else
8637 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008638 }
8639 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008640 *result = x;
8641 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008642 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008643 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008644 long value = PyLong_AS_LONG(x);
8645 long max = PyUnicode_GetMax();
8646 if (value < 0 || value > max) {
8647 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00008648 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008649 Py_DECREF(x);
8650 return -1;
8651 }
8652 *result = x;
8653 return 0;
8654 }
8655 else if (PyUnicode_Check(x)) {
8656 *result = x;
8657 return 0;
8658 }
8659 else {
8660 /* wrong return value */
8661 PyErr_SetString(PyExc_TypeError,
8662 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008663 Py_DECREF(x);
8664 return -1;
8665 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008666}
8667/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00008668 if not reallocate and adjust various state variables.
8669 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008670static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008671charmaptranslate_makespace(Py_UCS4 **outobj, Py_ssize_t *psize,
Benjamin Peterson29060642009-01-31 22:14:21 +00008672 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008673{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008674 Py_ssize_t oldsize = *psize;
Walter Dörwald4894c302003-10-24 14:25:28 +00008675 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008676 /* exponentially overallocate to minimize reallocations */
8677 if (requiredsize < 2 * oldsize)
8678 requiredsize = 2 * oldsize;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008679 *outobj = PyMem_Realloc(*outobj, requiredsize * sizeof(Py_UCS4));
8680 if (*outobj == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008681 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008682 *psize = requiredsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008683 }
8684 return 0;
8685}
8686/* lookup the character, put the result in the output string and adjust
8687 various state variables. Return a new reference to the object that
8688 was put in the output buffer in *result, or Py_None, if the mapping was
8689 undefined (in which case no character was written).
8690 The called must decref result.
8691 Return 0 on success, -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008692static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008693charmaptranslate_output(PyObject *input, Py_ssize_t ipos,
8694 PyObject *mapping, Py_UCS4 **output,
8695 Py_ssize_t *osize, Py_ssize_t *opos,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008696 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008697{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008698 Py_UCS4 curinp = PyUnicode_READ_CHAR(input, ipos);
8699 if (charmaptranslate_lookup(curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00008700 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008701 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008702 /* not found => default to 1:1 mapping */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008703 (*output)[(*opos)++] = curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008704 }
8705 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008706 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00008707 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008708 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008709 (*output)[(*opos)++] = (Py_UCS4)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008710 }
8711 else if (PyUnicode_Check(*res)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008712 Py_ssize_t repsize;
8713 if (PyUnicode_READY(*res) == -1)
8714 return -1;
8715 repsize = PyUnicode_GET_LENGTH(*res);
Benjamin Peterson29060642009-01-31 22:14:21 +00008716 if (repsize==1) {
8717 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008718 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00008719 }
8720 else if (repsize!=0) {
8721 /* more than one character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008722 Py_ssize_t requiredsize = *opos +
8723 (PyUnicode_GET_LENGTH(input) - ipos) +
Benjamin Peterson29060642009-01-31 22:14:21 +00008724 repsize - 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008725 Py_ssize_t i;
8726 if (charmaptranslate_makespace(output, osize, requiredsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00008727 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008728 for(i = 0; i < repsize; i++)
8729 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00008730 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008731 }
8732 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008733 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008734 return 0;
8735}
8736
Alexander Belopolsky40018472011-02-26 01:02:56 +00008737PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008738_PyUnicode_TranslateCharmap(PyObject *input,
8739 PyObject *mapping,
8740 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008741{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008742 /* input object */
8743 char *idata;
8744 Py_ssize_t size, i;
8745 int kind;
8746 /* output buffer */
8747 Py_UCS4 *output = NULL;
8748 Py_ssize_t osize;
8749 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008750 /* current output position */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008751 Py_ssize_t opos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008752 char *reason = "character maps to <undefined>";
8753 PyObject *errorHandler = NULL;
8754 PyObject *exc = NULL;
8755 /* the following variable is used for caching string comparisons
8756 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8757 * 3=ignore, 4=xmlcharrefreplace */
8758 int known_errorHandler = -1;
8759
Guido van Rossumd57fd912000-03-10 22:53:23 +00008760 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008761 PyErr_BadArgument();
8762 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008763 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008764
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008765 if (PyUnicode_READY(input) == -1)
8766 return NULL;
8767 idata = (char*)PyUnicode_DATA(input);
8768 kind = PyUnicode_KIND(input);
8769 size = PyUnicode_GET_LENGTH(input);
8770 i = 0;
8771
8772 if (size == 0) {
8773 Py_INCREF(input);
8774 return input;
8775 }
8776
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008777 /* allocate enough for a simple 1:1 translation without
8778 replacements, if we need more, we'll resize */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008779 osize = size;
8780 output = PyMem_Malloc(osize * sizeof(Py_UCS4));
8781 opos = 0;
8782 if (output == NULL) {
8783 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00008784 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008785 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008786
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008787 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008788 /* try to encode it */
8789 PyObject *x = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008790 if (charmaptranslate_output(input, i, mapping,
8791 &output, &osize, &opos, &x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008792 Py_XDECREF(x);
8793 goto onError;
8794 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008795 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00008796 if (x!=Py_None) /* it worked => adjust input pointer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008797 ++i;
Benjamin Peterson29060642009-01-31 22:14:21 +00008798 else { /* untranslatable character */
8799 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8800 Py_ssize_t repsize;
8801 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008802 Py_ssize_t uni2;
Benjamin Peterson29060642009-01-31 22:14:21 +00008803 /* startpos for collecting untranslatable chars */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008804 Py_ssize_t collstart = i;
8805 Py_ssize_t collend = i+1;
8806 Py_ssize_t coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008807
Benjamin Peterson29060642009-01-31 22:14:21 +00008808 /* find all untranslatable characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008809 while (collend < size) {
8810 if (charmaptranslate_lookup(PyUnicode_READ(kind,idata, collend), mapping, &x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008811 goto onError;
8812 Py_XDECREF(x);
8813 if (x!=Py_None)
8814 break;
8815 ++collend;
8816 }
8817 /* cache callback name lookup
8818 * (if not done yet, i.e. it's the first error) */
8819 if (known_errorHandler==-1) {
8820 if ((errors==NULL) || (!strcmp(errors, "strict")))
8821 known_errorHandler = 1;
8822 else if (!strcmp(errors, "replace"))
8823 known_errorHandler = 2;
8824 else if (!strcmp(errors, "ignore"))
8825 known_errorHandler = 3;
8826 else if (!strcmp(errors, "xmlcharrefreplace"))
8827 known_errorHandler = 4;
8828 else
8829 known_errorHandler = 0;
8830 }
8831 switch (known_errorHandler) {
8832 case 1: /* strict */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008833 raise_translate_exception(&exc, input, collstart,
8834 collend, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008835 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008836 case 2: /* replace */
8837 /* No need to check for space, this is a 1:1 replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008838 for (coll = collstart; coll<collend; coll++)
8839 output[opos++] = '?';
Benjamin Peterson29060642009-01-31 22:14:21 +00008840 /* fall through */
8841 case 3: /* ignore */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008842 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008843 break;
8844 case 4: /* xmlcharrefreplace */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008845 /* generate replacement (temporarily (mis)uses i) */
8846 for (i = collstart; i < collend; ++i) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008847 char buffer[2+29+1+1];
8848 char *cp;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008849 sprintf(buffer, "&#%d;", PyUnicode_READ(kind, idata, i));
8850 if (charmaptranslate_makespace(&output, &osize,
8851 opos+strlen(buffer)+(size-collend)))
Benjamin Peterson29060642009-01-31 22:14:21 +00008852 goto onError;
8853 for (cp = buffer; *cp; ++cp)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008854 output[opos++] = *cp;
Benjamin Peterson29060642009-01-31 22:14:21 +00008855 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008856 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008857 break;
8858 default:
8859 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008860 reason, input, &exc,
8861 collstart, collend, &newpos);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008862 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008863 goto onError;
Benjamin Peterson9ca3ffa2012-01-01 16:04:29 -06008864 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008865 Py_DECREF(repunicode);
8866 goto onError;
8867 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008868 /* generate replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008869 repsize = PyUnicode_GET_LENGTH(repunicode);
8870 if (charmaptranslate_makespace(&output, &osize,
8871 opos+repsize+(size-collend))) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008872 Py_DECREF(repunicode);
8873 goto onError;
8874 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008875 for (uni2 = 0; repsize-->0; ++uni2)
8876 output[opos++] = PyUnicode_READ_CHAR(repunicode, uni2);
8877 i = newpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00008878 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008879 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008880 }
8881 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008882 res = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, output, opos);
8883 if (!res)
8884 goto onError;
8885 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008886 Py_XDECREF(exc);
8887 Py_XDECREF(errorHandler);
8888 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008889
Benjamin Peterson29060642009-01-31 22:14:21 +00008890 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008891 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008892 Py_XDECREF(exc);
8893 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008894 return NULL;
8895}
8896
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008897/* Deprecated. Use PyUnicode_Translate instead. */
8898PyObject *
8899PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8900 Py_ssize_t size,
8901 PyObject *mapping,
8902 const char *errors)
8903{
8904 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8905 if (!unicode)
8906 return NULL;
8907 return _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8908}
8909
Alexander Belopolsky40018472011-02-26 01:02:56 +00008910PyObject *
8911PyUnicode_Translate(PyObject *str,
8912 PyObject *mapping,
8913 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008914{
8915 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008916
Guido van Rossumd57fd912000-03-10 22:53:23 +00008917 str = PyUnicode_FromObject(str);
8918 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008919 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008920 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008921 Py_DECREF(str);
8922 return result;
Tim Petersced69f82003-09-16 20:30:58 +00008923
Benjamin Peterson29060642009-01-31 22:14:21 +00008924 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00008925 Py_XDECREF(str);
8926 return NULL;
8927}
Tim Petersced69f82003-09-16 20:30:58 +00008928
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008929static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008930fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008931{
8932 /* No need to call PyUnicode_READY(self) because this function is only
8933 called as a callback from fixup() which does it already. */
8934 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8935 const int kind = PyUnicode_KIND(self);
8936 void *data = PyUnicode_DATA(self);
8937 Py_UCS4 maxchar = 0, ch, fixed;
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008938 int modified = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008939 Py_ssize_t i;
8940
8941 for (i = 0; i < len; ++i) {
8942 ch = PyUnicode_READ(kind, data, i);
8943 fixed = 0;
8944 if (ch > 127) {
8945 if (Py_UNICODE_ISSPACE(ch))
8946 fixed = ' ';
8947 else {
8948 const int decimal = Py_UNICODE_TODECIMAL(ch);
8949 if (decimal >= 0)
8950 fixed = '0' + decimal;
8951 }
8952 if (fixed != 0) {
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008953 modified = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008954 if (fixed > maxchar)
8955 maxchar = fixed;
8956 PyUnicode_WRITE(kind, data, i, fixed);
8957 }
8958 else if (ch > maxchar)
8959 maxchar = ch;
8960 }
8961 else if (ch > maxchar)
8962 maxchar = ch;
8963 }
8964
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008965 return (modified) ? maxchar : 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008966}
8967
8968PyObject *
8969_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
8970{
8971 if (!PyUnicode_Check(unicode)) {
8972 PyErr_BadInternalCall();
8973 return NULL;
8974 }
8975 if (PyUnicode_READY(unicode) == -1)
8976 return NULL;
8977 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
8978 /* If the string is already ASCII, just return the same string */
8979 Py_INCREF(unicode);
8980 return unicode;
8981 }
Victor Stinner9310abb2011-10-05 00:59:23 +02008982 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008983}
8984
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008985PyObject *
8986PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
8987 Py_ssize_t length)
8988{
Victor Stinnerf0124502011-11-21 23:12:56 +01008989 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008990 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01008991 Py_UCS4 maxchar;
8992 enum PyUnicode_Kind kind;
8993 void *data;
8994
Victor Stinner99d7ad02012-02-22 13:37:39 +01008995 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008996 for (i = 0; i < length; i++) {
Victor Stinnerf0124502011-11-21 23:12:56 +01008997 Py_UNICODE ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008998 if (ch > 127) {
8999 int decimal = Py_UNICODE_TODECIMAL(ch);
9000 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01009001 ch = '0' + decimal;
Victor Stinner99d7ad02012-02-22 13:37:39 +01009002 maxchar = Py_MAX(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009003 }
9004 }
Victor Stinnerf0124502011-11-21 23:12:56 +01009005
9006 /* Copy to a new string */
9007 decimal = PyUnicode_New(length, maxchar);
9008 if (decimal == NULL)
9009 return decimal;
9010 kind = PyUnicode_KIND(decimal);
9011 data = PyUnicode_DATA(decimal);
9012 /* Iterate over code points */
9013 for (i = 0; i < length; i++) {
9014 Py_UNICODE ch = s[i];
9015 if (ch > 127) {
9016 int decimal = Py_UNICODE_TODECIMAL(ch);
9017 if (decimal >= 0)
9018 ch = '0' + decimal;
9019 }
9020 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009021 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01009022 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009023}
Guido van Rossum9e896b32000-04-05 20:11:21 +00009024/* --- Decimal Encoder ---------------------------------------------------- */
9025
Alexander Belopolsky40018472011-02-26 01:02:56 +00009026int
9027PyUnicode_EncodeDecimal(Py_UNICODE *s,
9028 Py_ssize_t length,
9029 char *output,
9030 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00009031{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01009032 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01009033 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01009034 enum PyUnicode_Kind kind;
9035 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009036
9037 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009038 PyErr_BadArgument();
9039 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009040 }
9041
Victor Stinner42bf7752011-11-21 22:52:58 +01009042 unicode = PyUnicode_FromUnicode(s, length);
9043 if (unicode == NULL)
9044 return -1;
9045
Benjamin Petersonbac79492012-01-14 13:34:47 -05009046 if (PyUnicode_READY(unicode) == -1) {
Victor Stinner6345be92011-11-25 20:09:01 +01009047 Py_DECREF(unicode);
9048 return -1;
9049 }
Victor Stinner42bf7752011-11-21 22:52:58 +01009050 kind = PyUnicode_KIND(unicode);
9051 data = PyUnicode_DATA(unicode);
9052
Victor Stinnerb84d7232011-11-22 01:50:07 +01009053 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01009054 PyObject *exc;
9055 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00009056 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01009057 Py_ssize_t startpos;
9058
9059 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00009060
Benjamin Peterson29060642009-01-31 22:14:21 +00009061 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009062 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01009063 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009064 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009065 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009066 decimal = Py_UNICODE_TODECIMAL(ch);
9067 if (decimal >= 0) {
9068 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009069 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009070 continue;
9071 }
9072 if (0 < ch && ch < 256) {
9073 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009074 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009075 continue;
9076 }
Victor Stinner6345be92011-11-25 20:09:01 +01009077
Victor Stinner42bf7752011-11-21 22:52:58 +01009078 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01009079 exc = NULL;
9080 raise_encode_exception(&exc, "decimal", unicode,
9081 startpos, startpos+1,
9082 "invalid decimal Unicode string");
9083 Py_XDECREF(exc);
9084 Py_DECREF(unicode);
9085 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009086 }
9087 /* 0-terminate the output string */
9088 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01009089 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00009090 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009091}
9092
Guido van Rossumd57fd912000-03-10 22:53:23 +00009093/* --- Helpers ------------------------------------------------------------ */
9094
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009095static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02009096any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009097 Py_ssize_t start,
9098 Py_ssize_t end)
9099{
9100 int kind1, kind2, kind;
9101 void *buf1, *buf2;
9102 Py_ssize_t len1, len2, result;
9103
9104 kind1 = PyUnicode_KIND(s1);
9105 kind2 = PyUnicode_KIND(s2);
9106 kind = kind1 > kind2 ? kind1 : kind2;
9107 buf1 = PyUnicode_DATA(s1);
9108 buf2 = PyUnicode_DATA(s2);
9109 if (kind1 != kind)
9110 buf1 = _PyUnicode_AsKind(s1, kind);
9111 if (!buf1)
9112 return -2;
9113 if (kind2 != kind)
9114 buf2 = _PyUnicode_AsKind(s2, kind);
9115 if (!buf2) {
9116 if (kind1 != kind) PyMem_Free(buf1);
9117 return -2;
9118 }
9119 len1 = PyUnicode_GET_LENGTH(s1);
9120 len2 = PyUnicode_GET_LENGTH(s2);
9121
Victor Stinner794d5672011-10-10 03:21:36 +02009122 if (direction > 0) {
Benjamin Petersonead6b532011-12-20 17:23:42 -06009123 switch (kind) {
Victor Stinner794d5672011-10-10 03:21:36 +02009124 case PyUnicode_1BYTE_KIND:
9125 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9126 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9127 else
9128 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9129 break;
9130 case PyUnicode_2BYTE_KIND:
9131 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9132 break;
9133 case PyUnicode_4BYTE_KIND:
9134 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9135 break;
9136 default:
9137 assert(0); result = -2;
9138 }
9139 }
9140 else {
Benjamin Petersonead6b532011-12-20 17:23:42 -06009141 switch (kind) {
Victor Stinner794d5672011-10-10 03:21:36 +02009142 case PyUnicode_1BYTE_KIND:
9143 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9144 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9145 else
9146 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9147 break;
9148 case PyUnicode_2BYTE_KIND:
9149 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9150 break;
9151 case PyUnicode_4BYTE_KIND:
9152 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9153 break;
9154 default:
9155 assert(0); result = -2;
9156 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009157 }
9158
9159 if (kind1 != kind)
9160 PyMem_Free(buf1);
9161 if (kind2 != kind)
9162 PyMem_Free(buf2);
9163
9164 return result;
9165}
9166
9167Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01009168_PyUnicode_InsertThousandsGrouping(
9169 PyObject *unicode, Py_ssize_t index,
9170 Py_ssize_t n_buffer,
9171 void *digits, Py_ssize_t n_digits,
9172 Py_ssize_t min_width,
9173 const char *grouping, PyObject *thousands_sep,
9174 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009175{
Victor Stinner41a863c2012-02-24 00:37:51 +01009176 unsigned int kind, thousands_sep_kind;
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009177 char *data, *thousands_sep_data;
Victor Stinner41a863c2012-02-24 00:37:51 +01009178 Py_ssize_t thousands_sep_len;
9179 Py_ssize_t len;
9180
9181 if (unicode != NULL) {
9182 kind = PyUnicode_KIND(unicode);
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009183 data = (char *) PyUnicode_DATA(unicode) + index * kind;
Victor Stinner41a863c2012-02-24 00:37:51 +01009184 }
9185 else {
9186 kind = PyUnicode_1BYTE_KIND;
9187 data = NULL;
9188 }
9189 thousands_sep_kind = PyUnicode_KIND(thousands_sep);
9190 thousands_sep_data = PyUnicode_DATA(thousands_sep);
9191 thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
9192 if (unicode != NULL && thousands_sep_kind != kind) {
Victor Stinner90f50d42012-02-24 01:44:47 +01009193 if (thousands_sep_kind < kind) {
9194 thousands_sep_data = _PyUnicode_AsKind(thousands_sep, kind);
9195 if (!thousands_sep_data)
9196 return -1;
9197 }
9198 else {
9199 data = _PyUnicode_AsKind(unicode, thousands_sep_kind);
9200 if (!data)
9201 return -1;
9202 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009203 }
9204
Benjamin Petersonead6b532011-12-20 17:23:42 -06009205 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009206 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009207 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
Victor Stinner41a863c2012-02-24 00:37:51 +01009208 len = asciilib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009209 (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 Stinnerc3cec782011-10-05 21:24:08 +02009212 else
Victor Stinner41a863c2012-02-24 00:37:51 +01009213 len = ucs1lib_InsertThousandsGrouping(
Victor Stinnerc3cec782011-10-05 21:24:08 +02009214 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009215 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009216 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009217 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009218 case PyUnicode_2BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009219 len = ucs2lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009220 (Py_UCS2 *) data, n_buffer, (Py_UCS2 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009221 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009222 (Py_UCS2 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009223 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009224 case PyUnicode_4BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009225 len = ucs4lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009226 (Py_UCS4 *) data, n_buffer, (Py_UCS4 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009227 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009228 (Py_UCS4 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009229 break;
9230 default:
9231 assert(0);
9232 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009233 }
Victor Stinner90f50d42012-02-24 01:44:47 +01009234 if (unicode != NULL && thousands_sep_kind != kind) {
9235 if (thousands_sep_kind < kind)
9236 PyMem_Free(thousands_sep_data);
9237 else
9238 PyMem_Free(data);
9239 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009240 if (unicode == NULL) {
9241 *maxchar = 127;
9242 if (len != n_digits) {
9243 *maxchar = Py_MAX(*maxchar,
9244 PyUnicode_MAX_CHAR_VALUE(thousands_sep));
9245 }
9246 }
9247 return len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009248}
9249
9250
Thomas Wouters477c8d52006-05-27 19:21:47 +00009251/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009252#define ADJUST_INDICES(start, end, len) \
9253 if (end > len) \
9254 end = len; \
9255 else if (end < 0) { \
9256 end += len; \
9257 if (end < 0) \
9258 end = 0; \
9259 } \
9260 if (start < 0) { \
9261 start += len; \
9262 if (start < 0) \
9263 start = 0; \
9264 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009265
Alexander Belopolsky40018472011-02-26 01:02:56 +00009266Py_ssize_t
9267PyUnicode_Count(PyObject *str,
9268 PyObject *substr,
9269 Py_ssize_t start,
9270 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009271{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009272 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009273 PyObject* str_obj;
9274 PyObject* sub_obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009275 int kind1, kind2, kind;
9276 void *buf1 = NULL, *buf2 = NULL;
9277 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009278
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009279 str_obj = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009280 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00009281 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009282 sub_obj = PyUnicode_FromObject(substr);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009283 if (!sub_obj) {
9284 Py_DECREF(str_obj);
9285 return -1;
9286 }
Benjamin Peterson4c13a4a2012-01-02 09:07:38 -06009287 if (PyUnicode_READY(sub_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
Benjamin Peterson5e458f52012-01-02 10:12:13 -06009288 Py_DECREF(sub_obj);
Benjamin Peterson29060642009-01-31 22:14:21 +00009289 Py_DECREF(str_obj);
9290 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009291 }
Tim Petersced69f82003-09-16 20:30:58 +00009292
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009293 kind1 = PyUnicode_KIND(str_obj);
9294 kind2 = PyUnicode_KIND(sub_obj);
9295 kind = kind1 > kind2 ? kind1 : kind2;
9296 buf1 = PyUnicode_DATA(str_obj);
9297 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009298 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009299 if (!buf1)
9300 goto onError;
9301 buf2 = PyUnicode_DATA(sub_obj);
9302 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009303 buf2 = _PyUnicode_AsKind(sub_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009304 if (!buf2)
9305 goto onError;
9306 len1 = PyUnicode_GET_LENGTH(str_obj);
9307 len2 = PyUnicode_GET_LENGTH(sub_obj);
9308
9309 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -06009310 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009311 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009312 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
9313 result = asciilib_count(
9314 ((Py_UCS1*)buf1) + start, end - start,
9315 buf2, len2, PY_SSIZE_T_MAX
9316 );
9317 else
9318 result = ucs1lib_count(
9319 ((Py_UCS1*)buf1) + start, end - start,
9320 buf2, len2, PY_SSIZE_T_MAX
9321 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009322 break;
9323 case PyUnicode_2BYTE_KIND:
9324 result = ucs2lib_count(
9325 ((Py_UCS2*)buf1) + start, end - start,
9326 buf2, len2, PY_SSIZE_T_MAX
9327 );
9328 break;
9329 case PyUnicode_4BYTE_KIND:
9330 result = ucs4lib_count(
9331 ((Py_UCS4*)buf1) + start, end - start,
9332 buf2, len2, PY_SSIZE_T_MAX
9333 );
9334 break;
9335 default:
9336 assert(0); result = 0;
9337 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009338
9339 Py_DECREF(sub_obj);
9340 Py_DECREF(str_obj);
9341
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009342 if (kind1 != kind)
9343 PyMem_Free(buf1);
9344 if (kind2 != kind)
9345 PyMem_Free(buf2);
9346
Guido van Rossumd57fd912000-03-10 22:53:23 +00009347 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009348 onError:
9349 Py_DECREF(sub_obj);
9350 Py_DECREF(str_obj);
9351 if (kind1 != kind && buf1)
9352 PyMem_Free(buf1);
9353 if (kind2 != kind && buf2)
9354 PyMem_Free(buf2);
9355 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009356}
9357
Alexander Belopolsky40018472011-02-26 01:02:56 +00009358Py_ssize_t
9359PyUnicode_Find(PyObject *str,
9360 PyObject *sub,
9361 Py_ssize_t start,
9362 Py_ssize_t end,
9363 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009364{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009365 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009366
Guido van Rossumd57fd912000-03-10 22:53:23 +00009367 str = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009368 if (!str)
Benjamin Peterson29060642009-01-31 22:14:21 +00009369 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009370 sub = PyUnicode_FromObject(sub);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009371 if (!sub) {
9372 Py_DECREF(str);
9373 return -2;
9374 }
9375 if (PyUnicode_READY(sub) == -1 || PyUnicode_READY(str) == -1) {
9376 Py_DECREF(sub);
Benjamin Peterson29060642009-01-31 22:14:21 +00009377 Py_DECREF(str);
9378 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009379 }
Tim Petersced69f82003-09-16 20:30:58 +00009380
Victor Stinner794d5672011-10-10 03:21:36 +02009381 result = any_find_slice(direction,
9382 str, sub, start, end
9383 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00009384
Guido van Rossumd57fd912000-03-10 22:53:23 +00009385 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009386 Py_DECREF(sub);
9387
Guido van Rossumd57fd912000-03-10 22:53:23 +00009388 return result;
9389}
9390
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009391Py_ssize_t
9392PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9393 Py_ssize_t start, Py_ssize_t end,
9394 int direction)
9395{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009396 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009397 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009398 if (PyUnicode_READY(str) == -1)
9399 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009400 if (start < 0 || end < 0) {
9401 PyErr_SetString(PyExc_IndexError, "string index out of range");
9402 return -2;
9403 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009404 if (end > PyUnicode_GET_LENGTH(str))
9405 end = PyUnicode_GET_LENGTH(str);
9406 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009407 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9408 kind, end-start, ch, direction);
9409 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009410 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009411 else
9412 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009413}
9414
Alexander Belopolsky40018472011-02-26 01:02:56 +00009415static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009416tailmatch(PyObject *self,
9417 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009418 Py_ssize_t start,
9419 Py_ssize_t end,
9420 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009421{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009422 int kind_self;
9423 int kind_sub;
9424 void *data_self;
9425 void *data_sub;
9426 Py_ssize_t offset;
9427 Py_ssize_t i;
9428 Py_ssize_t end_sub;
9429
9430 if (PyUnicode_READY(self) == -1 ||
9431 PyUnicode_READY(substring) == -1)
9432 return 0;
9433
9434 if (PyUnicode_GET_LENGTH(substring) == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009435 return 1;
9436
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009437 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9438 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009439 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009440 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009441
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009442 kind_self = PyUnicode_KIND(self);
9443 data_self = PyUnicode_DATA(self);
9444 kind_sub = PyUnicode_KIND(substring);
9445 data_sub = PyUnicode_DATA(substring);
9446 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9447
9448 if (direction > 0)
9449 offset = end;
9450 else
9451 offset = start;
9452
9453 if (PyUnicode_READ(kind_self, data_self, offset) ==
9454 PyUnicode_READ(kind_sub, data_sub, 0) &&
9455 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9456 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9457 /* If both are of the same kind, memcmp is sufficient */
9458 if (kind_self == kind_sub) {
9459 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009460 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009461 data_sub,
9462 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009463 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009464 }
9465 /* otherwise we have to compare each character by first accesing it */
9466 else {
9467 /* We do not need to compare 0 and len(substring)-1 because
9468 the if statement above ensured already that they are equal
9469 when we end up here. */
9470 // TODO: honor direction and do a forward or backwards search
9471 for (i = 1; i < end_sub; ++i) {
9472 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9473 PyUnicode_READ(kind_sub, data_sub, i))
9474 return 0;
9475 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009476 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009477 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009478 }
9479
9480 return 0;
9481}
9482
Alexander Belopolsky40018472011-02-26 01:02:56 +00009483Py_ssize_t
9484PyUnicode_Tailmatch(PyObject *str,
9485 PyObject *substr,
9486 Py_ssize_t start,
9487 Py_ssize_t end,
9488 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009489{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009490 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009491
Guido van Rossumd57fd912000-03-10 22:53:23 +00009492 str = PyUnicode_FromObject(str);
9493 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009494 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009495 substr = PyUnicode_FromObject(substr);
9496 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009497 Py_DECREF(str);
9498 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009499 }
Tim Petersced69f82003-09-16 20:30:58 +00009500
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009501 result = tailmatch(str, substr,
Benjamin Peterson29060642009-01-31 22:14:21 +00009502 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009503 Py_DECREF(str);
9504 Py_DECREF(substr);
9505 return result;
9506}
9507
Guido van Rossumd57fd912000-03-10 22:53:23 +00009508/* Apply fixfct filter to the Unicode object self and return a
9509 reference to the modified object */
9510
Alexander Belopolsky40018472011-02-26 01:02:56 +00009511static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009512fixup(PyObject *self,
9513 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009514{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009515 PyObject *u;
9516 Py_UCS4 maxchar_old, maxchar_new = 0;
Victor Stinnereaab6042011-12-11 22:22:39 +01009517 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009518
Victor Stinnerbf6e5602011-12-12 01:53:47 +01009519 u = _PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009520 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009521 return NULL;
Victor Stinner87af4f22011-11-21 23:03:47 +01009522 maxchar_old = PyUnicode_MAX_CHAR_VALUE(u);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009523
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009524 /* fix functions return the new maximum character in a string,
9525 if the kind of the resulting unicode object does not change,
9526 everything is fine. Otherwise we need to change the string kind
9527 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009528 maxchar_new = fixfct(u);
Victor Stinnereaab6042011-12-11 22:22:39 +01009529
9530 if (maxchar_new == 0) {
9531 /* no changes */;
9532 if (PyUnicode_CheckExact(self)) {
9533 Py_DECREF(u);
9534 Py_INCREF(self);
9535 return self;
9536 }
9537 else
9538 return u;
9539 }
9540
9541 if (maxchar_new <= 127)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009542 maxchar_new = 127;
9543 else if (maxchar_new <= 255)
9544 maxchar_new = 255;
9545 else if (maxchar_new <= 65535)
9546 maxchar_new = 65535;
9547 else
Victor Stinner8faf8212011-12-08 22:14:11 +01009548 maxchar_new = MAX_UNICODE;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009549
Victor Stinnereaab6042011-12-11 22:22:39 +01009550 if (maxchar_new == maxchar_old)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009551 return u;
Victor Stinnereaab6042011-12-11 22:22:39 +01009552
9553 /* In case the maximum character changed, we need to
9554 convert the string to the new category. */
9555 v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
9556 if (v == NULL) {
9557 Py_DECREF(u);
9558 return NULL;
9559 }
9560 if (maxchar_new > maxchar_old) {
9561 /* If the maxchar increased so that the kind changed, not all
9562 characters are representable anymore and we need to fix the
9563 string again. This only happens in very few cases. */
9564 copy_characters(v, 0, self, 0, PyUnicode_GET_LENGTH(self));
9565 maxchar_old = fixfct(v);
9566 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009567 }
9568 else {
Victor Stinnereaab6042011-12-11 22:22:39 +01009569 copy_characters(v, 0, u, 0, PyUnicode_GET_LENGTH(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009570 }
Victor Stinnereaab6042011-12-11 22:22:39 +01009571 Py_DECREF(u);
9572 assert(_PyUnicode_CheckConsistency(v, 1));
9573 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009574}
9575
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009576static PyObject *
9577ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009578{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009579 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9580 char *resdata, *data = PyUnicode_DATA(self);
9581 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009582
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009583 res = PyUnicode_New(len, 127);
9584 if (res == NULL)
9585 return NULL;
9586 resdata = PyUnicode_DATA(res);
9587 if (lower)
9588 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009589 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009590 _Py_bytes_upper(resdata, data, len);
9591 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009592}
9593
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009594static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009595handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009596{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009597 Py_ssize_t j;
9598 int final_sigma;
9599 Py_UCS4 c;
9600 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009601
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009602 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9603
9604 where ! is a negation and \p{xxx} is a character with property xxx.
9605 */
9606 for (j = i - 1; j >= 0; j--) {
9607 c = PyUnicode_READ(kind, data, j);
9608 if (!_PyUnicode_IsCaseIgnorable(c))
9609 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009610 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009611 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9612 if (final_sigma) {
9613 for (j = i + 1; j < length; j++) {
9614 c = PyUnicode_READ(kind, data, j);
9615 if (!_PyUnicode_IsCaseIgnorable(c))
9616 break;
9617 }
9618 final_sigma = j == length || !_PyUnicode_IsCased(c);
9619 }
9620 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009621}
9622
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009623static int
9624lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9625 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009626{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009627 /* Obscure special case. */
9628 if (c == 0x3A3) {
9629 mapped[0] = handle_capital_sigma(kind, data, length, i);
9630 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009631 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009632 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009633}
9634
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009635static Py_ssize_t
9636do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009637{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009638 Py_ssize_t i, k = 0;
9639 int n_res, j;
9640 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009641
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009642 c = PyUnicode_READ(kind, data, 0);
9643 n_res = _PyUnicode_ToUpperFull(c, mapped);
9644 for (j = 0; j < n_res; j++) {
9645 if (mapped[j] > *maxchar)
9646 *maxchar = mapped[j];
9647 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009648 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009649 for (i = 1; i < length; i++) {
9650 c = PyUnicode_READ(kind, data, i);
9651 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9652 for (j = 0; j < n_res; j++) {
9653 if (mapped[j] > *maxchar)
9654 *maxchar = mapped[j];
9655 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009656 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009657 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009658 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009659}
9660
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009661static Py_ssize_t
9662do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9663 Py_ssize_t i, k = 0;
9664
9665 for (i = 0; i < length; i++) {
9666 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9667 int n_res, j;
9668 if (Py_UNICODE_ISUPPER(c)) {
9669 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9670 }
9671 else if (Py_UNICODE_ISLOWER(c)) {
9672 n_res = _PyUnicode_ToUpperFull(c, mapped);
9673 }
9674 else {
9675 n_res = 1;
9676 mapped[0] = c;
9677 }
9678 for (j = 0; j < n_res; j++) {
9679 if (mapped[j] > *maxchar)
9680 *maxchar = mapped[j];
9681 res[k++] = mapped[j];
9682 }
9683 }
9684 return k;
9685}
9686
9687static Py_ssize_t
9688do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9689 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009690{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009691 Py_ssize_t i, k = 0;
9692
9693 for (i = 0; i < length; i++) {
9694 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9695 int n_res, j;
9696 if (lower)
9697 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9698 else
9699 n_res = _PyUnicode_ToUpperFull(c, mapped);
9700 for (j = 0; j < n_res; j++) {
9701 if (mapped[j] > *maxchar)
9702 *maxchar = mapped[j];
9703 res[k++] = mapped[j];
9704 }
9705 }
9706 return k;
9707}
9708
9709static Py_ssize_t
9710do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9711{
9712 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9713}
9714
9715static Py_ssize_t
9716do_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9717{
9718 return do_upper_or_lower(kind, data, length, res, maxchar, 1);
9719}
9720
Benjamin Petersone51757f2012-01-12 21:10:29 -05009721static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009722do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9723{
9724 Py_ssize_t i, k = 0;
9725
9726 for (i = 0; i < length; i++) {
9727 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9728 Py_UCS4 mapped[3];
9729 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9730 for (j = 0; j < n_res; j++) {
9731 if (mapped[j] > *maxchar)
9732 *maxchar = mapped[j];
9733 res[k++] = mapped[j];
9734 }
9735 }
9736 return k;
9737}
9738
9739static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009740do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9741{
9742 Py_ssize_t i, k = 0;
9743 int previous_is_cased;
9744
9745 previous_is_cased = 0;
9746 for (i = 0; i < length; i++) {
9747 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9748 Py_UCS4 mapped[3];
9749 int n_res, j;
9750
9751 if (previous_is_cased)
9752 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9753 else
9754 n_res = _PyUnicode_ToTitleFull(c, mapped);
9755
9756 for (j = 0; j < n_res; j++) {
9757 if (mapped[j] > *maxchar)
9758 *maxchar = mapped[j];
9759 res[k++] = mapped[j];
9760 }
9761
9762 previous_is_cased = _PyUnicode_IsCased(c);
9763 }
9764 return k;
9765}
9766
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009767static PyObject *
9768case_operation(PyObject *self,
9769 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9770{
9771 PyObject *res = NULL;
9772 Py_ssize_t length, newlength = 0;
9773 int kind, outkind;
9774 void *data, *outdata;
9775 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9776
Benjamin Petersoneea48462012-01-16 14:28:50 -05009777 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009778
9779 kind = PyUnicode_KIND(self);
9780 data = PyUnicode_DATA(self);
9781 length = PyUnicode_GET_LENGTH(self);
9782 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
9783 if (tmp == NULL)
9784 return PyErr_NoMemory();
9785 newlength = perform(kind, data, length, tmp, &maxchar);
9786 res = PyUnicode_New(newlength, maxchar);
9787 if (res == NULL)
9788 goto leave;
9789 tmpend = tmp + newlength;
9790 outdata = PyUnicode_DATA(res);
9791 outkind = PyUnicode_KIND(res);
9792 switch (outkind) {
9793 case PyUnicode_1BYTE_KIND:
9794 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9795 break;
9796 case PyUnicode_2BYTE_KIND:
9797 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9798 break;
9799 case PyUnicode_4BYTE_KIND:
9800 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9801 break;
9802 default:
9803 assert(0);
9804 break;
9805 }
9806 leave:
9807 PyMem_FREE(tmp);
9808 return res;
9809}
9810
Tim Peters8ce9f162004-08-27 01:49:32 +00009811PyObject *
9812PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009813{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009814 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009815 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009816 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009817 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009818 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9819 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009820 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009821 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009822 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009823 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009824 int use_memcpy;
9825 unsigned char *res_data = NULL, *sep_data = NULL;
9826 PyObject *last_obj;
9827 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009828
Tim Peters05eba1f2004-08-27 21:32:02 +00009829 fseq = PySequence_Fast(seq, "");
9830 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009831 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009832 }
9833
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009834 /* NOTE: the following code can't call back into Python code,
9835 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009836 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009837
Tim Peters05eba1f2004-08-27 21:32:02 +00009838 seqlen = PySequence_Fast_GET_SIZE(fseq);
9839 /* If empty sequence, return u"". */
9840 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009841 Py_DECREF(fseq);
9842 Py_INCREF(unicode_empty);
9843 res = unicode_empty;
9844 return res;
Tim Peters05eba1f2004-08-27 21:32:02 +00009845 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009846
Tim Peters05eba1f2004-08-27 21:32:02 +00009847 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009848 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009849 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009850 if (seqlen == 1) {
9851 if (PyUnicode_CheckExact(items[0])) {
9852 res = items[0];
9853 Py_INCREF(res);
9854 Py_DECREF(fseq);
9855 return res;
9856 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009857 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009858 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009859 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009860 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009861 /* Set up sep and seplen */
9862 if (separator == NULL) {
9863 /* fall back to a blank space separator */
9864 sep = PyUnicode_FromOrdinal(' ');
9865 if (!sep)
9866 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009867 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009868 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009869 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009870 else {
9871 if (!PyUnicode_Check(separator)) {
9872 PyErr_Format(PyExc_TypeError,
9873 "separator: expected str instance,"
9874 " %.80s found",
9875 Py_TYPE(separator)->tp_name);
9876 goto onError;
9877 }
9878 if (PyUnicode_READY(separator))
9879 goto onError;
9880 sep = separator;
9881 seplen = PyUnicode_GET_LENGTH(separator);
9882 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9883 /* inc refcount to keep this code path symmetric with the
9884 above case of a blank separator */
9885 Py_INCREF(sep);
9886 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009887 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009888 }
9889
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009890 /* There are at least two things to join, or else we have a subclass
9891 * of str in the sequence.
9892 * Do a pre-pass to figure out the total amount of space we'll
9893 * need (sz), and see whether all argument are strings.
9894 */
9895 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009896#ifdef Py_DEBUG
9897 use_memcpy = 0;
9898#else
9899 use_memcpy = 1;
9900#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009901 for (i = 0; i < seqlen; i++) {
9902 const Py_ssize_t old_sz = sz;
9903 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009904 if (!PyUnicode_Check(item)) {
9905 PyErr_Format(PyExc_TypeError,
9906 "sequence item %zd: expected str instance,"
9907 " %.80s found",
9908 i, Py_TYPE(item)->tp_name);
9909 goto onError;
9910 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009911 if (PyUnicode_READY(item) == -1)
9912 goto onError;
9913 sz += PyUnicode_GET_LENGTH(item);
9914 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009915 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009916 if (i != 0)
9917 sz += seplen;
9918 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9919 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009920 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009921 goto onError;
9922 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009923 if (use_memcpy && last_obj != NULL) {
9924 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9925 use_memcpy = 0;
9926 }
9927 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009928 }
Tim Petersced69f82003-09-16 20:30:58 +00009929
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009930 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009931 if (res == NULL)
9932 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009933
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009934 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009935#ifdef Py_DEBUG
9936 use_memcpy = 0;
9937#else
9938 if (use_memcpy) {
9939 res_data = PyUnicode_1BYTE_DATA(res);
9940 kind = PyUnicode_KIND(res);
9941 if (seplen != 0)
9942 sep_data = PyUnicode_1BYTE_DATA(sep);
9943 }
9944#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009945 for (i = 0, res_offset = 0; i < seqlen; ++i) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009946 Py_ssize_t itemlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009947 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009948 /* Copy item, and maybe the separator. */
Victor Stinner9ce5a832011-10-03 23:36:02 +02009949 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009950 if (use_memcpy) {
9951 Py_MEMCPY(res_data,
9952 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009953 kind * seplen);
9954 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009955 }
9956 else {
9957 copy_characters(res, res_offset, sep, 0, seplen);
9958 res_offset += seplen;
9959 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009960 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009961 itemlen = PyUnicode_GET_LENGTH(item);
9962 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009963 if (use_memcpy) {
9964 Py_MEMCPY(res_data,
9965 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009966 kind * itemlen);
9967 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009968 }
9969 else {
9970 copy_characters(res, res_offset, item, 0, itemlen);
9971 res_offset += itemlen;
9972 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009973 }
Tim Peters05eba1f2004-08-27 21:32:02 +00009974 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009975 if (use_memcpy)
9976 assert(res_data == PyUnicode_1BYTE_DATA(res)
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009977 + kind * PyUnicode_GET_LENGTH(res));
Victor Stinnerdd077322011-10-07 17:02:31 +02009978 else
9979 assert(res_offset == PyUnicode_GET_LENGTH(res));
Tim Peters8ce9f162004-08-27 01:49:32 +00009980
Tim Peters05eba1f2004-08-27 21:32:02 +00009981 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009982 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009983 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009984 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009985
Benjamin Peterson29060642009-01-31 22:14:21 +00009986 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00009987 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009988 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009989 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009990 return NULL;
9991}
9992
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009993#define FILL(kind, data, value, start, length) \
9994 do { \
9995 Py_ssize_t i_ = 0; \
9996 assert(kind != PyUnicode_WCHAR_KIND); \
9997 switch ((kind)) { \
9998 case PyUnicode_1BYTE_KIND: { \
9999 unsigned char * to_ = (unsigned char *)((data)) + (start); \
10000 memset(to_, (unsigned char)value, length); \
10001 break; \
10002 } \
10003 case PyUnicode_2BYTE_KIND: { \
10004 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
10005 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
10006 break; \
10007 } \
Benjamin Petersone157cf12012-01-01 15:56:20 -060010008 case PyUnicode_4BYTE_KIND: { \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010009 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
10010 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
10011 break; \
Benjamin Petersone157cf12012-01-01 15:56:20 -060010012 default: assert(0); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010013 } \
10014 } \
10015 } while (0)
10016
Victor Stinner3fe55312012-01-04 00:33:50 +010010017Py_ssize_t
10018PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10019 Py_UCS4 fill_char)
10020{
10021 Py_ssize_t maxlen;
10022 enum PyUnicode_Kind kind;
10023 void *data;
10024
10025 if (!PyUnicode_Check(unicode)) {
10026 PyErr_BadInternalCall();
10027 return -1;
10028 }
10029 if (PyUnicode_READY(unicode) == -1)
10030 return -1;
10031 if (unicode_check_modifiable(unicode))
10032 return -1;
10033
10034 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
10035 PyErr_SetString(PyExc_ValueError,
10036 "fill character is bigger than "
10037 "the string maximum character");
10038 return -1;
10039 }
10040
10041 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
10042 length = Py_MIN(maxlen, length);
10043 if (length <= 0)
10044 return 0;
10045
10046 kind = PyUnicode_KIND(unicode);
10047 data = PyUnicode_DATA(unicode);
10048 FILL(kind, data, fill_char, start, length);
10049 return length;
10050}
10051
Victor Stinner9310abb2011-10-05 00:59:23 +020010052static PyObject *
10053pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010054 Py_ssize_t left,
10055 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010056 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010057{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010058 PyObject *u;
10059 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010060 int kind;
10061 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010062
10063 if (left < 0)
10064 left = 0;
10065 if (right < 0)
10066 right = 0;
10067
Victor Stinnerc4b49542011-12-11 22:44:26 +010010068 if (left == 0 && right == 0)
10069 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010070
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010071 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
10072 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +000010073 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
10074 return NULL;
10075 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010076 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
10077 if (fill > maxchar)
10078 maxchar = fill;
10079 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010080 if (!u)
10081 return NULL;
10082
10083 kind = PyUnicode_KIND(u);
10084 data = PyUnicode_DATA(u);
10085 if (left)
10086 FILL(kind, data, fill, 0, left);
10087 if (right)
10088 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010089 copy_characters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010090 assert(_PyUnicode_CheckConsistency(u, 1));
10091 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010092}
10093
Alexander Belopolsky40018472011-02-26 01:02:56 +000010094PyObject *
10095PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010096{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010097 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010098
10099 string = PyUnicode_FromObject(string);
Benjamin Peterson22a29702012-01-02 09:00:30 -060010100 if (string == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010101 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060010102 if (PyUnicode_READY(string) == -1) {
10103 Py_DECREF(string);
10104 return NULL;
10105 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010106
Benjamin Petersonead6b532011-12-20 17:23:42 -060010107 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010108 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010109 if (PyUnicode_IS_ASCII(string))
10110 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010111 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010112 PyUnicode_GET_LENGTH(string), keepends);
10113 else
10114 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010115 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010116 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010117 break;
10118 case PyUnicode_2BYTE_KIND:
10119 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010120 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010121 PyUnicode_GET_LENGTH(string), keepends);
10122 break;
10123 case PyUnicode_4BYTE_KIND:
10124 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010125 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010126 PyUnicode_GET_LENGTH(string), keepends);
10127 break;
10128 default:
10129 assert(0);
10130 list = 0;
10131 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010132 Py_DECREF(string);
10133 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010134}
10135
Alexander Belopolsky40018472011-02-26 01:02:56 +000010136static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010137split(PyObject *self,
10138 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010139 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010140{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010141 int kind1, kind2, kind;
10142 void *buf1, *buf2;
10143 Py_ssize_t len1, len2;
10144 PyObject* out;
10145
Guido van Rossumd57fd912000-03-10 22:53:23 +000010146 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010147 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010148
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010149 if (PyUnicode_READY(self) == -1)
10150 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010151
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010152 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010153 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010154 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010155 if (PyUnicode_IS_ASCII(self))
10156 return asciilib_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 );
10160 else
10161 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010162 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010163 PyUnicode_GET_LENGTH(self), maxcount
10164 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010165 case PyUnicode_2BYTE_KIND:
10166 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010167 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010168 PyUnicode_GET_LENGTH(self), maxcount
10169 );
10170 case PyUnicode_4BYTE_KIND:
10171 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010172 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010173 PyUnicode_GET_LENGTH(self), maxcount
10174 );
10175 default:
10176 assert(0);
10177 return NULL;
10178 }
10179
10180 if (PyUnicode_READY(substring) == -1)
10181 return NULL;
10182
10183 kind1 = PyUnicode_KIND(self);
10184 kind2 = PyUnicode_KIND(substring);
10185 kind = kind1 > kind2 ? kind1 : kind2;
10186 buf1 = PyUnicode_DATA(self);
10187 buf2 = PyUnicode_DATA(substring);
10188 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010189 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010190 if (!buf1)
10191 return NULL;
10192 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010193 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010194 if (!buf2) {
10195 if (kind1 != kind) PyMem_Free(buf1);
10196 return NULL;
10197 }
10198 len1 = PyUnicode_GET_LENGTH(self);
10199 len2 = PyUnicode_GET_LENGTH(substring);
10200
Benjamin Petersonead6b532011-12-20 17:23:42 -060010201 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010202 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010203 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10204 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010205 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010206 else
10207 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010208 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010209 break;
10210 case PyUnicode_2BYTE_KIND:
10211 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010212 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010213 break;
10214 case PyUnicode_4BYTE_KIND:
10215 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010216 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010217 break;
10218 default:
10219 out = NULL;
10220 }
10221 if (kind1 != kind)
10222 PyMem_Free(buf1);
10223 if (kind2 != kind)
10224 PyMem_Free(buf2);
10225 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010226}
10227
Alexander Belopolsky40018472011-02-26 01:02:56 +000010228static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010229rsplit(PyObject *self,
10230 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010231 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010232{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010233 int kind1, kind2, kind;
10234 void *buf1, *buf2;
10235 Py_ssize_t len1, len2;
10236 PyObject* out;
10237
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010238 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010239 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010240
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010241 if (PyUnicode_READY(self) == -1)
10242 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010243
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010244 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010245 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010246 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010247 if (PyUnicode_IS_ASCII(self))
10248 return asciilib_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 );
10252 else
10253 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010254 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010255 PyUnicode_GET_LENGTH(self), maxcount
10256 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010257 case PyUnicode_2BYTE_KIND:
10258 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010259 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010260 PyUnicode_GET_LENGTH(self), maxcount
10261 );
10262 case PyUnicode_4BYTE_KIND:
10263 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010264 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010265 PyUnicode_GET_LENGTH(self), maxcount
10266 );
10267 default:
10268 assert(0);
10269 return NULL;
10270 }
10271
10272 if (PyUnicode_READY(substring) == -1)
10273 return NULL;
10274
10275 kind1 = PyUnicode_KIND(self);
10276 kind2 = PyUnicode_KIND(substring);
10277 kind = kind1 > kind2 ? kind1 : kind2;
10278 buf1 = PyUnicode_DATA(self);
10279 buf2 = PyUnicode_DATA(substring);
10280 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010281 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010282 if (!buf1)
10283 return NULL;
10284 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010285 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010286 if (!buf2) {
10287 if (kind1 != kind) PyMem_Free(buf1);
10288 return NULL;
10289 }
10290 len1 = PyUnicode_GET_LENGTH(self);
10291 len2 = PyUnicode_GET_LENGTH(substring);
10292
Benjamin Petersonead6b532011-12-20 17:23:42 -060010293 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010294 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010295 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10296 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010297 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010298 else
10299 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010300 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010301 break;
10302 case PyUnicode_2BYTE_KIND:
10303 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010304 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010305 break;
10306 case PyUnicode_4BYTE_KIND:
10307 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010308 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010309 break;
10310 default:
10311 out = NULL;
10312 }
10313 if (kind1 != kind)
10314 PyMem_Free(buf1);
10315 if (kind2 != kind)
10316 PyMem_Free(buf2);
10317 return out;
10318}
10319
10320static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010321anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10322 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010323{
Benjamin Petersonead6b532011-12-20 17:23:42 -060010324 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010325 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010326 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10327 return asciilib_find(buf1, len1, buf2, len2, offset);
10328 else
10329 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010330 case PyUnicode_2BYTE_KIND:
10331 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10332 case PyUnicode_4BYTE_KIND:
10333 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10334 }
10335 assert(0);
10336 return -1;
10337}
10338
10339static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010340anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10341 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010342{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -060010343 switch (kind) {
10344 case PyUnicode_1BYTE_KIND:
10345 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10346 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10347 else
10348 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10349 case PyUnicode_2BYTE_KIND:
10350 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10351 case PyUnicode_4BYTE_KIND:
10352 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10353 }
10354 assert(0);
10355 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010356}
10357
Alexander Belopolsky40018472011-02-26 01:02:56 +000010358static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010359replace(PyObject *self, PyObject *str1,
10360 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010361{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010362 PyObject *u;
10363 char *sbuf = PyUnicode_DATA(self);
10364 char *buf1 = PyUnicode_DATA(str1);
10365 char *buf2 = PyUnicode_DATA(str2);
10366 int srelease = 0, release1 = 0, release2 = 0;
10367 int skind = PyUnicode_KIND(self);
10368 int kind1 = PyUnicode_KIND(str1);
10369 int kind2 = PyUnicode_KIND(str2);
10370 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10371 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10372 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010373 int mayshrink;
10374 Py_UCS4 maxchar, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010375
10376 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010377 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010378 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010379 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010380
Victor Stinner59de0ee2011-10-07 10:01:28 +020010381 if (str1 == str2)
10382 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010383 if (skind < kind1)
10384 /* substring too wide to be present */
10385 goto nothing;
10386
Victor Stinner49a0a212011-10-12 23:46:10 +020010387 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
10388 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10389 /* Replacing str1 with str2 may cause a maxchar reduction in the
10390 result string. */
10391 mayshrink = (maxchar_str2 < maxchar);
10392 maxchar = Py_MAX(maxchar, maxchar_str2);
10393
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010394 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010395 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010396 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010397 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010398 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010399 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010400 Py_UCS4 u1, u2;
10401 int rkind;
Victor Stinnerf6441102011-12-18 02:43:08 +010010402 Py_ssize_t index, pos;
10403 char *src;
10404
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010405 u1 = PyUnicode_READ_CHAR(str1, 0);
Victor Stinnerf6441102011-12-18 02:43:08 +010010406 pos = findchar(sbuf, PyUnicode_KIND(self), slen, u1, 1);
10407 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010408 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010409 u2 = PyUnicode_READ_CHAR(str2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010410 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010411 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010412 goto error;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010413 copy_characters(u, 0, self, 0, slen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010414 rkind = PyUnicode_KIND(u);
Victor Stinnerf6441102011-12-18 02:43:08 +010010415
10416 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), pos, u2);
10417 index = 0;
10418 src = sbuf;
10419 while (--maxcount)
10420 {
10421 pos++;
10422 src += pos * PyUnicode_KIND(self);
10423 slen -= pos;
10424 index += pos;
10425 pos = findchar(src, PyUnicode_KIND(self), slen, u1, 1);
10426 if (pos < 0)
10427 break;
10428 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), index + pos, u2);
10429 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010430 }
10431 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010432 int rkind = skind;
10433 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010434 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010435
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010436 if (kind1 < rkind) {
10437 /* widen substring */
10438 buf1 = _PyUnicode_AsKind(str1, rkind);
10439 if (!buf1) goto error;
10440 release1 = 1;
10441 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010442 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010443 if (i < 0)
10444 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010445 if (rkind > kind2) {
10446 /* widen replacement */
10447 buf2 = _PyUnicode_AsKind(str2, rkind);
10448 if (!buf2) goto error;
10449 release2 = 1;
10450 }
10451 else if (rkind < kind2) {
10452 /* widen self and buf1 */
10453 rkind = kind2;
10454 if (release1) PyMem_Free(buf1);
10455 sbuf = _PyUnicode_AsKind(self, rkind);
10456 if (!sbuf) goto error;
10457 srelease = 1;
10458 buf1 = _PyUnicode_AsKind(str1, rkind);
10459 if (!buf1) goto error;
10460 release1 = 1;
10461 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010462 u = PyUnicode_New(slen, maxchar);
10463 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010464 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010465 assert(PyUnicode_KIND(u) == rkind);
10466 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010467
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010468 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010469 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010470 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010471 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010472 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010473 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010474
10475 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010476 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010477 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010478 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010479 if (i == -1)
10480 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010481 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010482 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010483 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010484 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010485 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010486 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010487 }
10488 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010489 Py_ssize_t n, i, j, ires;
10490 Py_ssize_t product, new_size;
10491 int rkind = skind;
10492 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010493
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010494 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010495 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010496 buf1 = _PyUnicode_AsKind(str1, rkind);
10497 if (!buf1) goto error;
10498 release1 = 1;
10499 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010500 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010501 if (n == 0)
10502 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010503 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010504 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010505 buf2 = _PyUnicode_AsKind(str2, rkind);
10506 if (!buf2) goto error;
10507 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010508 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010509 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010510 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010511 rkind = kind2;
10512 sbuf = _PyUnicode_AsKind(self, rkind);
10513 if (!sbuf) goto error;
10514 srelease = 1;
10515 if (release1) PyMem_Free(buf1);
10516 buf1 = _PyUnicode_AsKind(str1, rkind);
10517 if (!buf1) goto error;
10518 release1 = 1;
10519 }
10520 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10521 PyUnicode_GET_LENGTH(str1))); */
10522 product = n * (len2-len1);
10523 if ((product / (len2-len1)) != n) {
10524 PyErr_SetString(PyExc_OverflowError,
10525 "replace string is too long");
10526 goto error;
10527 }
10528 new_size = slen + product;
Victor Stinner49a0a212011-10-12 23:46:10 +020010529 if (new_size == 0) {
10530 Py_INCREF(unicode_empty);
10531 u = unicode_empty;
10532 goto done;
10533 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010534 if (new_size < 0 || new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
10535 PyErr_SetString(PyExc_OverflowError,
10536 "replace string is too long");
10537 goto error;
10538 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010539 u = PyUnicode_New(new_size, maxchar);
10540 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010541 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010542 assert(PyUnicode_KIND(u) == rkind);
10543 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010544 ires = i = 0;
10545 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010546 while (n-- > 0) {
10547 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010548 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010549 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010550 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010551 if (j == -1)
10552 break;
10553 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010554 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010555 memcpy(res + rkind * ires,
10556 sbuf + rkind * i,
10557 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010558 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010559 }
10560 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010561 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010562 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010563 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010564 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010565 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010566 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010567 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010568 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010569 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010570 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010571 memcpy(res + rkind * ires,
10572 sbuf + rkind * i,
10573 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010574 }
10575 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010576 /* interleave */
10577 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010578 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010579 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010580 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010581 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010582 if (--n <= 0)
10583 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010584 memcpy(res + rkind * ires,
10585 sbuf + rkind * i,
10586 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010587 ires++;
10588 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010589 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010590 memcpy(res + rkind * ires,
10591 sbuf + rkind * i,
10592 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010593 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010594 }
10595
10596 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010597 unicode_adjust_maxchar(&u);
10598 if (u == NULL)
10599 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010600 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010601
10602 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010603 if (srelease)
10604 PyMem_FREE(sbuf);
10605 if (release1)
10606 PyMem_FREE(buf1);
10607 if (release2)
10608 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010609 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010610 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010611
Benjamin Peterson29060642009-01-31 22:14:21 +000010612 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010613 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010614 if (srelease)
10615 PyMem_FREE(sbuf);
10616 if (release1)
10617 PyMem_FREE(buf1);
10618 if (release2)
10619 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010620 return unicode_result_unchanged(self);
10621
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010622 error:
10623 if (srelease && sbuf)
10624 PyMem_FREE(sbuf);
10625 if (release1 && buf1)
10626 PyMem_FREE(buf1);
10627 if (release2 && buf2)
10628 PyMem_FREE(buf2);
10629 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010630}
10631
10632/* --- Unicode Object Methods --------------------------------------------- */
10633
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010634PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010635 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010636\n\
10637Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010638characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010639
10640static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010641unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010642{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010643 if (PyUnicode_READY(self) == -1)
10644 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010645 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010646}
10647
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010648PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010649 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010650\n\
10651Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010652have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010653
10654static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010655unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010656{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010657 if (PyUnicode_READY(self) == -1)
10658 return NULL;
10659 if (PyUnicode_GET_LENGTH(self) == 0)
10660 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010661 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010662}
10663
Benjamin Petersond5890c82012-01-14 13:23:30 -050010664PyDoc_STRVAR(casefold__doc__,
10665 "S.casefold() -> str\n\
10666\n\
10667Return a version of S suitable for caseless comparisons.");
10668
10669static PyObject *
10670unicode_casefold(PyObject *self)
10671{
10672 if (PyUnicode_READY(self) == -1)
10673 return NULL;
10674 if (PyUnicode_IS_ASCII(self))
10675 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010676 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010677}
10678
10679
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010680/* Argument converter. Coerces to a single unicode character */
10681
10682static int
10683convert_uc(PyObject *obj, void *addr)
10684{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010685 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010686 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010687
Benjamin Peterson14339b62009-01-31 16:36:08 +000010688 uniobj = PyUnicode_FromObject(obj);
10689 if (uniobj == NULL) {
10690 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010691 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010692 return 0;
10693 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010694 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010695 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010696 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010697 Py_DECREF(uniobj);
10698 return 0;
10699 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010700 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010701 Py_DECREF(uniobj);
10702 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010703}
10704
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010705PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010706 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010707\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010708Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010709done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010710
10711static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010712unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010713{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010714 Py_ssize_t marg, left;
10715 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010716 Py_UCS4 fillchar = ' ';
10717
Victor Stinnere9a29352011-10-01 02:14:59 +020010718 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010719 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010720
Benjamin Petersonbac79492012-01-14 13:34:47 -050010721 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010722 return NULL;
10723
Victor Stinnerc4b49542011-12-11 22:44:26 +010010724 if (PyUnicode_GET_LENGTH(self) >= width)
10725 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010726
Victor Stinnerc4b49542011-12-11 22:44:26 +010010727 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010728 left = marg / 2 + (marg & width & 1);
10729
Victor Stinner9310abb2011-10-05 00:59:23 +020010730 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010731}
10732
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010733/* This function assumes that str1 and str2 are readied by the caller. */
10734
Marc-André Lemburge5034372000-08-08 08:04:29 +000010735static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010736unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010737{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010738 int kind1, kind2;
10739 void *data1, *data2;
10740 Py_ssize_t len1, len2, i;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010741
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010742 kind1 = PyUnicode_KIND(str1);
10743 kind2 = PyUnicode_KIND(str2);
10744 data1 = PyUnicode_DATA(str1);
10745 data2 = PyUnicode_DATA(str2);
10746 len1 = PyUnicode_GET_LENGTH(str1);
10747 len2 = PyUnicode_GET_LENGTH(str2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010748
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010749 for (i = 0; i < len1 && i < len2; ++i) {
10750 Py_UCS4 c1, c2;
10751 c1 = PyUnicode_READ(kind1, data1, i);
10752 c2 = PyUnicode_READ(kind2, data2, i);
Fredrik Lundh45714e92001-06-26 16:39:36 +000010753
10754 if (c1 != c2)
10755 return (c1 < c2) ? -1 : 1;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010756 }
10757
10758 return (len1 < len2) ? -1 : (len1 != len2);
10759}
10760
Alexander Belopolsky40018472011-02-26 01:02:56 +000010761int
10762PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010763{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010764 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10765 if (PyUnicode_READY(left) == -1 ||
10766 PyUnicode_READY(right) == -1)
10767 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010768 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010769 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010770 PyErr_Format(PyExc_TypeError,
10771 "Can't compare %.100s and %.100s",
10772 left->ob_type->tp_name,
10773 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010774 return -1;
10775}
10776
Martin v. Löwis5b222132007-06-10 09:51:05 +000010777int
10778PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10779{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010780 Py_ssize_t i;
10781 int kind;
10782 void *data;
10783 Py_UCS4 chr;
10784
Victor Stinner910337b2011-10-03 03:20:16 +020010785 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010786 if (PyUnicode_READY(uni) == -1)
10787 return -1;
10788 kind = PyUnicode_KIND(uni);
10789 data = PyUnicode_DATA(uni);
Martin v. Löwis5b222132007-06-10 09:51:05 +000010790 /* Compare Unicode string and source character set string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010791 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
10792 if (chr != str[i])
10793 return (chr < (unsigned char)(str[i])) ? -1 : 1;
Benjamin Peterson8667a9b2010-01-09 21:45:28 +000010794 /* This check keeps Python strings that end in '\0' from comparing equal
10795 to C strings identical up to that point. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010796 if (PyUnicode_GET_LENGTH(uni) != i || chr)
Benjamin Peterson29060642009-01-31 22:14:21 +000010797 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010798 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +000010799 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010800 return 0;
10801}
10802
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010803
Benjamin Peterson29060642009-01-31 22:14:21 +000010804#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010805 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010806
Alexander Belopolsky40018472011-02-26 01:02:56 +000010807PyObject *
10808PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010809{
10810 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010811
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010812 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10813 PyObject *v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010814 if (PyUnicode_READY(left) == -1 ||
10815 PyUnicode_READY(right) == -1)
10816 return NULL;
10817 if (PyUnicode_GET_LENGTH(left) != PyUnicode_GET_LENGTH(right) ||
10818 PyUnicode_KIND(left) != PyUnicode_KIND(right)) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010819 if (op == Py_EQ) {
10820 Py_INCREF(Py_False);
10821 return Py_False;
10822 }
10823 if (op == Py_NE) {
10824 Py_INCREF(Py_True);
10825 return Py_True;
10826 }
10827 }
10828 if (left == right)
10829 result = 0;
10830 else
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010831 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010832
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010833 /* Convert the return value to a Boolean */
10834 switch (op) {
10835 case Py_EQ:
10836 v = TEST_COND(result == 0);
10837 break;
10838 case Py_NE:
10839 v = TEST_COND(result != 0);
10840 break;
10841 case Py_LE:
10842 v = TEST_COND(result <= 0);
10843 break;
10844 case Py_GE:
10845 v = TEST_COND(result >= 0);
10846 break;
10847 case Py_LT:
10848 v = TEST_COND(result == -1);
10849 break;
10850 case Py_GT:
10851 v = TEST_COND(result == 1);
10852 break;
10853 default:
10854 PyErr_BadArgument();
10855 return NULL;
10856 }
10857 Py_INCREF(v);
10858 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010859 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010860
Brian Curtindfc80e32011-08-10 20:28:54 -050010861 Py_RETURN_NOTIMPLEMENTED;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010862}
10863
Alexander Belopolsky40018472011-02-26 01:02:56 +000010864int
10865PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010866{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010867 PyObject *str, *sub;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010868 int kind1, kind2, kind;
10869 void *buf1, *buf2;
10870 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010871 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010872
10873 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010874 sub = PyUnicode_FromObject(element);
10875 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010876 PyErr_Format(PyExc_TypeError,
10877 "'in <string>' requires string as left operand, not %s",
10878 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010879 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010880 }
10881
Thomas Wouters477c8d52006-05-27 19:21:47 +000010882 str = PyUnicode_FromObject(container);
Benjamin Peterson22a29702012-01-02 09:00:30 -060010883 if (!str) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010884 Py_DECREF(sub);
10885 return -1;
10886 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060010887 if (PyUnicode_READY(sub) == -1 || PyUnicode_READY(str) == -1) {
10888 Py_DECREF(sub);
10889 Py_DECREF(str);
10890 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010891
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010892 kind1 = PyUnicode_KIND(str);
10893 kind2 = PyUnicode_KIND(sub);
10894 kind = kind1 > kind2 ? kind1 : kind2;
10895 buf1 = PyUnicode_DATA(str);
10896 buf2 = PyUnicode_DATA(sub);
10897 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010898 buf1 = _PyUnicode_AsKind(str, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010899 if (!buf1) {
10900 Py_DECREF(sub);
10901 return -1;
10902 }
10903 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010904 buf2 = _PyUnicode_AsKind(sub, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010905 if (!buf2) {
10906 Py_DECREF(sub);
10907 if (kind1 != kind) PyMem_Free(buf1);
10908 return -1;
10909 }
10910 len1 = PyUnicode_GET_LENGTH(str);
10911 len2 = PyUnicode_GET_LENGTH(sub);
10912
Benjamin Petersonead6b532011-12-20 17:23:42 -060010913 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010914 case PyUnicode_1BYTE_KIND:
10915 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10916 break;
10917 case PyUnicode_2BYTE_KIND:
10918 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
10919 break;
10920 case PyUnicode_4BYTE_KIND:
10921 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
10922 break;
10923 default:
10924 result = -1;
10925 assert(0);
10926 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010927
10928 Py_DECREF(str);
10929 Py_DECREF(sub);
10930
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010931 if (kind1 != kind)
10932 PyMem_Free(buf1);
10933 if (kind2 != kind)
10934 PyMem_Free(buf2);
10935
Guido van Rossum403d68b2000-03-13 15:55:09 +000010936 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010937}
10938
Guido van Rossumd57fd912000-03-10 22:53:23 +000010939/* Concat to string or Unicode object giving a new Unicode object. */
10940
Alexander Belopolsky40018472011-02-26 01:02:56 +000010941PyObject *
10942PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010943{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010944 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020010945 Py_UCS4 maxchar, maxchar2;
Victor Stinner488fa492011-12-12 00:01:39 +010010946 Py_ssize_t u_len, v_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010947
10948 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010949 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010950 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010951 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010952 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010953 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010954 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010955
10956 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020010957 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010958 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010959 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010960 }
Victor Stinnera464fc12011-10-02 20:39:30 +020010961 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010962 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010963 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010964 }
10965
Victor Stinner488fa492011-12-12 00:01:39 +010010966 u_len = PyUnicode_GET_LENGTH(u);
10967 v_len = PyUnicode_GET_LENGTH(v);
10968 if (u_len > PY_SSIZE_T_MAX - v_len) {
10969 PyErr_SetString(PyExc_OverflowError,
10970 "strings are too large to concat");
10971 goto onError;
10972 }
10973 new_len = u_len + v_len;
10974
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010975 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020010976 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
10977 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010978
Guido van Rossumd57fd912000-03-10 22:53:23 +000010979 /* Concat the two Unicode strings */
Victor Stinner488fa492011-12-12 00:01:39 +010010980 w = PyUnicode_New(new_len, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010981 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010982 goto onError;
Victor Stinner488fa492011-12-12 00:01:39 +010010983 copy_characters(w, 0, u, 0, u_len);
10984 copy_characters(w, u_len, v, 0, v_len);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010985 Py_DECREF(u);
10986 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010987 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010988 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010989
Benjamin Peterson29060642009-01-31 22:14:21 +000010990 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010991 Py_XDECREF(u);
10992 Py_XDECREF(v);
10993 return NULL;
10994}
10995
Walter Dörwald1ab83302007-05-18 17:15:44 +000010996void
Victor Stinner23e56682011-10-03 03:54:37 +020010997PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000010998{
Victor Stinner23e56682011-10-03 03:54:37 +020010999 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010011000 Py_UCS4 maxchar, maxchar2;
11001 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020011002
11003 if (p_left == NULL) {
11004 if (!PyErr_Occurred())
11005 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000011006 return;
11007 }
Victor Stinner23e56682011-10-03 03:54:37 +020011008 left = *p_left;
11009 if (right == NULL || !PyUnicode_Check(left)) {
11010 if (!PyErr_Occurred())
11011 PyErr_BadInternalCall();
11012 goto error;
11013 }
11014
Benjamin Petersonbac79492012-01-14 13:34:47 -050011015 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011016 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050011017 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011018 goto error;
11019
Victor Stinner488fa492011-12-12 00:01:39 +010011020 /* Shortcuts */
11021 if (left == unicode_empty) {
11022 Py_DECREF(left);
11023 Py_INCREF(right);
11024 *p_left = right;
11025 return;
11026 }
11027 if (right == unicode_empty)
11028 return;
11029
11030 left_len = PyUnicode_GET_LENGTH(left);
11031 right_len = PyUnicode_GET_LENGTH(right);
11032 if (left_len > PY_SSIZE_T_MAX - right_len) {
11033 PyErr_SetString(PyExc_OverflowError,
11034 "strings are too large to concat");
11035 goto error;
11036 }
11037 new_len = left_len + right_len;
11038
11039 if (unicode_modifiable(left)
11040 && PyUnicode_CheckExact(right)
11041 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020011042 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
11043 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020011044 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020011045 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010011046 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
11047 {
11048 /* append inplace */
11049 if (unicode_resize(p_left, new_len) != 0) {
11050 /* XXX if _PyUnicode_Resize() fails, 'left' has been
11051 * deallocated so it cannot be put back into
11052 * 'variable'. The MemoryError is raised when there
11053 * is no value in 'variable', which might (very
11054 * remotely) be a cause of incompatibilities.
11055 */
11056 goto error;
Victor Stinner23e56682011-10-03 03:54:37 +020011057 }
Victor Stinner488fa492011-12-12 00:01:39 +010011058 /* copy 'right' into the newly allocated area of 'left' */
11059 copy_characters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020011060 }
Victor Stinner488fa492011-12-12 00:01:39 +010011061 else {
11062 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11063 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
11064 maxchar = Py_MAX(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020011065
Victor Stinner488fa492011-12-12 00:01:39 +010011066 /* Concat the two Unicode strings */
11067 res = PyUnicode_New(new_len, maxchar);
11068 if (res == NULL)
11069 goto error;
11070 copy_characters(res, 0, left, 0, left_len);
11071 copy_characters(res, left_len, right, 0, right_len);
11072 Py_DECREF(left);
11073 *p_left = res;
11074 }
11075 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020011076 return;
11077
11078error:
Victor Stinner488fa492011-12-12 00:01:39 +010011079 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011080}
11081
11082void
11083PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
11084{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011085 PyUnicode_Append(pleft, right);
11086 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011087}
11088
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011089PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011090 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011091\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011092Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011093string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011094interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011095
11096static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011097unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011098{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011099 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011100 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011101 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011102 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011103 int kind1, kind2, kind;
11104 void *buf1, *buf2;
11105 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011106
Jesus Ceaac451502011-04-20 17:09:23 +020011107 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
11108 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000011109 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000011110
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011111 kind1 = PyUnicode_KIND(self);
11112 kind2 = PyUnicode_KIND(substring);
11113 kind = kind1 > kind2 ? kind1 : kind2;
11114 buf1 = PyUnicode_DATA(self);
11115 buf2 = PyUnicode_DATA(substring);
11116 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010011117 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011118 if (!buf1) {
11119 Py_DECREF(substring);
11120 return NULL;
11121 }
11122 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010011123 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011124 if (!buf2) {
11125 Py_DECREF(substring);
11126 if (kind1 != kind) PyMem_Free(buf1);
11127 return NULL;
11128 }
11129 len1 = PyUnicode_GET_LENGTH(self);
11130 len2 = PyUnicode_GET_LENGTH(substring);
11131
11132 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -060011133 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011134 case PyUnicode_1BYTE_KIND:
11135 iresult = ucs1lib_count(
11136 ((Py_UCS1*)buf1) + start, end - start,
11137 buf2, len2, PY_SSIZE_T_MAX
11138 );
11139 break;
11140 case PyUnicode_2BYTE_KIND:
11141 iresult = ucs2lib_count(
11142 ((Py_UCS2*)buf1) + start, end - start,
11143 buf2, len2, PY_SSIZE_T_MAX
11144 );
11145 break;
11146 case PyUnicode_4BYTE_KIND:
11147 iresult = ucs4lib_count(
11148 ((Py_UCS4*)buf1) + start, end - start,
11149 buf2, len2, PY_SSIZE_T_MAX
11150 );
11151 break;
11152 default:
11153 assert(0); iresult = 0;
11154 }
11155
11156 result = PyLong_FromSsize_t(iresult);
11157
11158 if (kind1 != kind)
11159 PyMem_Free(buf1);
11160 if (kind2 != kind)
11161 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011162
11163 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011164
Guido van Rossumd57fd912000-03-10 22:53:23 +000011165 return result;
11166}
11167
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011168PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000011169 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011170\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000011171Encode S using the codec registered for encoding. Default encoding\n\
11172is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000011173handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000011174a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
11175'xmlcharrefreplace' as well as any other name registered with\n\
11176codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011177
11178static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011179unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011180{
Benjamin Peterson308d6372009-09-18 21:42:35 +000011181 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011182 char *encoding = NULL;
11183 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000011184
Benjamin Peterson308d6372009-09-18 21:42:35 +000011185 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
11186 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011187 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011188 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000011189}
11190
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011191PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011192 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011193\n\
11194Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011195If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011196
11197static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011198unicode_expandtabs(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011199{
Antoine Pitroue71d5742011-10-04 15:55:09 +020011200 Py_ssize_t i, j, line_pos, src_len, incr;
11201 Py_UCS4 ch;
11202 PyObject *u;
11203 void *src_data, *dest_data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011204 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011205 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011206 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011207
11208 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000011209 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011210
Antoine Pitrou22425222011-10-04 19:10:51 +020011211 if (PyUnicode_READY(self) == -1)
11212 return NULL;
11213
Thomas Wouters7e474022000-07-16 12:04:32 +000011214 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011215 src_len = PyUnicode_GET_LENGTH(self);
11216 i = j = line_pos = 0;
11217 kind = PyUnicode_KIND(self);
11218 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020011219 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011220 for (; i < src_len; i++) {
11221 ch = PyUnicode_READ(kind, src_data, i);
11222 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020011223 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000011224 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011225 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000011226 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011227 goto overflow;
11228 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011229 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011230 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011231 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011232 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011233 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011234 goto overflow;
11235 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011236 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011237 if (ch == '\n' || ch == '\r')
11238 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011239 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011240 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010011241 if (!found)
11242 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011243
Guido van Rossumd57fd912000-03-10 22:53:23 +000011244 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011245 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011246 if (!u)
11247 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011248 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011249
Antoine Pitroue71d5742011-10-04 15:55:09 +020011250 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011251
Antoine Pitroue71d5742011-10-04 15:55:09 +020011252 for (; i < src_len; i++) {
11253 ch = PyUnicode_READ(kind, src_data, i);
11254 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011255 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011256 incr = tabsize - (line_pos % tabsize);
11257 line_pos += incr;
Victor Stinnerda79e632012-02-22 13:37:04 +010011258 FILL(kind, dest_data, ' ', j, incr);
11259 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011260 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011261 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011262 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011263 line_pos++;
11264 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011265 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011266 if (ch == '\n' || ch == '\r')
11267 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011268 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011269 }
11270 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010011271 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011272
Antoine Pitroue71d5742011-10-04 15:55:09 +020011273 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011274 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11275 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011276}
11277
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011278PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011279 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011280\n\
11281Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011282such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011283arguments start and end are interpreted as in slice notation.\n\
11284\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011285Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011286
11287static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011288unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011289{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011290 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011291 Py_ssize_t start;
11292 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011293 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011294
Jesus Ceaac451502011-04-20 17:09:23 +020011295 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
11296 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011297 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011298
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011299 if (PyUnicode_READY(self) == -1)
11300 return NULL;
11301 if (PyUnicode_READY(substring) == -1)
11302 return NULL;
11303
Victor Stinner7931d9a2011-11-04 00:22:48 +010011304 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011305
11306 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011307
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011308 if (result == -2)
11309 return NULL;
11310
Christian Heimes217cfd12007-12-02 14:31:20 +000011311 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011312}
11313
11314static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011315unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011316{
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011317 Py_UCS4 ch = PyUnicode_ReadChar(self, index);
11318 if (ch == (Py_UCS4)-1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011319 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011320 return PyUnicode_FromOrdinal(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011321}
11322
Guido van Rossumc2504932007-09-18 19:42:40 +000011323/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011324 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011325static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011326unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011327{
Guido van Rossumc2504932007-09-18 19:42:40 +000011328 Py_ssize_t len;
Mark Dickinson57e683e2011-09-24 18:18:40 +010011329 Py_uhash_t x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011330
Benjamin Peterson69e97272012-02-21 11:08:50 -050011331 assert(_Py_HashSecret_Initialized);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011332 if (_PyUnicode_HASH(self) != -1)
11333 return _PyUnicode_HASH(self);
11334 if (PyUnicode_READY(self) == -1)
11335 return -1;
11336 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010011337 /*
11338 We make the hash of the empty string be 0, rather than using
11339 (prefix ^ suffix), since this slightly obfuscates the hash secret
11340 */
11341 if (len == 0) {
11342 _PyUnicode_HASH(self) = 0;
11343 return 0;
11344 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011345
11346 /* The hash function as a macro, gets expanded three times below. */
Georg Brandl2fb477c2012-02-21 00:33:36 +010011347#define HASH(P) \
11348 x ^= (Py_uhash_t) *P << 7; \
11349 while (--len >= 0) \
11350 x = (_PyHASH_MULTIPLIER * x) ^ (Py_uhash_t) *P++; \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011351
Georg Brandl2fb477c2012-02-21 00:33:36 +010011352 x = (Py_uhash_t) _Py_HashSecret.prefix;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011353 switch (PyUnicode_KIND(self)) {
11354 case PyUnicode_1BYTE_KIND: {
11355 const unsigned char *c = PyUnicode_1BYTE_DATA(self);
11356 HASH(c);
11357 break;
11358 }
11359 case PyUnicode_2BYTE_KIND: {
11360 const Py_UCS2 *s = PyUnicode_2BYTE_DATA(self);
11361 HASH(s);
11362 break;
11363 }
11364 default: {
11365 Py_UCS4 *l;
11366 assert(PyUnicode_KIND(self) == PyUnicode_4BYTE_KIND &&
11367 "Impossible switch case in unicode_hash");
11368 l = PyUnicode_4BYTE_DATA(self);
11369 HASH(l);
11370 break;
11371 }
11372 }
Georg Brandl2fb477c2012-02-21 00:33:36 +010011373 x ^= (Py_uhash_t) PyUnicode_GET_LENGTH(self);
11374 x ^= (Py_uhash_t) _Py_HashSecret.suffix;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011375
Guido van Rossumc2504932007-09-18 19:42:40 +000011376 if (x == -1)
11377 x = -2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011378 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011379 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011380}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011381#undef HASH
Guido van Rossumd57fd912000-03-10 22:53:23 +000011382
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011383PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011384 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011385\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011386Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011387
11388static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011389unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011390{
Martin v. Löwis18e16552006-02-15 17:27:45 +000011391 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011392 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011393 Py_ssize_t start;
11394 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011395
Jesus Ceaac451502011-04-20 17:09:23 +020011396 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
11397 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011398 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011399
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011400 if (PyUnicode_READY(self) == -1)
11401 return NULL;
11402 if (PyUnicode_READY(substring) == -1)
11403 return NULL;
11404
Victor Stinner7931d9a2011-11-04 00:22:48 +010011405 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011406
11407 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011408
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011409 if (result == -2)
11410 return NULL;
11411
Guido van Rossumd57fd912000-03-10 22:53:23 +000011412 if (result < 0) {
11413 PyErr_SetString(PyExc_ValueError, "substring not found");
11414 return NULL;
11415 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011416
Christian Heimes217cfd12007-12-02 14:31:20 +000011417 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011418}
11419
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011420PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011421 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011422\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011423Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011424at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011425
11426static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011427unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011428{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011429 Py_ssize_t i, length;
11430 int kind;
11431 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011432 int cased;
11433
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011434 if (PyUnicode_READY(self) == -1)
11435 return NULL;
11436 length = PyUnicode_GET_LENGTH(self);
11437 kind = PyUnicode_KIND(self);
11438 data = PyUnicode_DATA(self);
11439
Guido van Rossumd57fd912000-03-10 22:53:23 +000011440 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011441 if (length == 1)
11442 return PyBool_FromLong(
11443 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011444
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011445 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011446 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011447 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011448
Guido van Rossumd57fd912000-03-10 22:53:23 +000011449 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011450 for (i = 0; i < length; i++) {
11451 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011452
Benjamin Peterson29060642009-01-31 22:14:21 +000011453 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11454 return PyBool_FromLong(0);
11455 else if (!cased && Py_UNICODE_ISLOWER(ch))
11456 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011457 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011458 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011459}
11460
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011461PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011462 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011463\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011464Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011465at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011466
11467static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011468unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011469{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011470 Py_ssize_t i, length;
11471 int kind;
11472 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011473 int cased;
11474
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011475 if (PyUnicode_READY(self) == -1)
11476 return NULL;
11477 length = PyUnicode_GET_LENGTH(self);
11478 kind = PyUnicode_KIND(self);
11479 data = PyUnicode_DATA(self);
11480
Guido van Rossumd57fd912000-03-10 22:53:23 +000011481 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011482 if (length == 1)
11483 return PyBool_FromLong(
11484 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011485
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011486 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011487 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011488 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011489
Guido van Rossumd57fd912000-03-10 22:53:23 +000011490 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011491 for (i = 0; i < length; i++) {
11492 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011493
Benjamin Peterson29060642009-01-31 22:14:21 +000011494 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11495 return PyBool_FromLong(0);
11496 else if (!cased && Py_UNICODE_ISUPPER(ch))
11497 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011498 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011499 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011500}
11501
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011502PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011503 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011504\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011505Return True if S is a titlecased string and there is at least one\n\
11506character in S, i.e. upper- and titlecase characters may only\n\
11507follow uncased characters and lowercase characters only cased ones.\n\
11508Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011509
11510static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011511unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011512{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011513 Py_ssize_t i, length;
11514 int kind;
11515 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011516 int cased, previous_is_cased;
11517
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011518 if (PyUnicode_READY(self) == -1)
11519 return NULL;
11520 length = PyUnicode_GET_LENGTH(self);
11521 kind = PyUnicode_KIND(self);
11522 data = PyUnicode_DATA(self);
11523
Guido van Rossumd57fd912000-03-10 22:53:23 +000011524 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011525 if (length == 1) {
11526 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11527 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11528 (Py_UNICODE_ISUPPER(ch) != 0));
11529 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011530
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011531 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011532 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011533 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011534
Guido van Rossumd57fd912000-03-10 22:53:23 +000011535 cased = 0;
11536 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011537 for (i = 0; i < length; i++) {
11538 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011539
Benjamin Peterson29060642009-01-31 22:14:21 +000011540 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11541 if (previous_is_cased)
11542 return PyBool_FromLong(0);
11543 previous_is_cased = 1;
11544 cased = 1;
11545 }
11546 else if (Py_UNICODE_ISLOWER(ch)) {
11547 if (!previous_is_cased)
11548 return PyBool_FromLong(0);
11549 previous_is_cased = 1;
11550 cased = 1;
11551 }
11552 else
11553 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011554 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011555 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011556}
11557
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011558PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011559 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011560\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011561Return True if all characters in S are whitespace\n\
11562and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011563
11564static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011565unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011566{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011567 Py_ssize_t i, length;
11568 int kind;
11569 void *data;
11570
11571 if (PyUnicode_READY(self) == -1)
11572 return NULL;
11573 length = PyUnicode_GET_LENGTH(self);
11574 kind = PyUnicode_KIND(self);
11575 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011576
Guido van Rossumd57fd912000-03-10 22:53:23 +000011577 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011578 if (length == 1)
11579 return PyBool_FromLong(
11580 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011581
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011582 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011583 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011584 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011585
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011586 for (i = 0; i < length; i++) {
11587 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011588 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011589 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011590 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011591 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011592}
11593
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011594PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011595 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011596\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011597Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011598and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011599
11600static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011601unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011602{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011603 Py_ssize_t i, length;
11604 int kind;
11605 void *data;
11606
11607 if (PyUnicode_READY(self) == -1)
11608 return NULL;
11609 length = PyUnicode_GET_LENGTH(self);
11610 kind = PyUnicode_KIND(self);
11611 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011612
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011613 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011614 if (length == 1)
11615 return PyBool_FromLong(
11616 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011617
11618 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011619 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011620 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011621
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011622 for (i = 0; i < length; i++) {
11623 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011624 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011625 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011626 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011627}
11628
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011629PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011630 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011631\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011632Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011633and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011634
11635static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011636unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011637{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011638 int kind;
11639 void *data;
11640 Py_ssize_t len, i;
11641
11642 if (PyUnicode_READY(self) == -1)
11643 return NULL;
11644
11645 kind = PyUnicode_KIND(self);
11646 data = PyUnicode_DATA(self);
11647 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011648
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011649 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011650 if (len == 1) {
11651 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11652 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11653 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011654
11655 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011656 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011657 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011658
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011659 for (i = 0; i < len; i++) {
11660 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011661 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011662 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011663 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011664 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011665}
11666
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011667PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011668 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011669\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011670Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011671False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011672
11673static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011674unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011675{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011676 Py_ssize_t i, length;
11677 int kind;
11678 void *data;
11679
11680 if (PyUnicode_READY(self) == -1)
11681 return NULL;
11682 length = PyUnicode_GET_LENGTH(self);
11683 kind = PyUnicode_KIND(self);
11684 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011685
Guido van Rossumd57fd912000-03-10 22:53:23 +000011686 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011687 if (length == 1)
11688 return PyBool_FromLong(
11689 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011690
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011691 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011692 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011693 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011694
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011695 for (i = 0; i < length; i++) {
11696 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011697 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011698 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011699 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011700}
11701
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011702PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011703 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011704\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011705Return True if all characters in S are digits\n\
11706and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011707
11708static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011709unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011710{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011711 Py_ssize_t i, length;
11712 int kind;
11713 void *data;
11714
11715 if (PyUnicode_READY(self) == -1)
11716 return NULL;
11717 length = PyUnicode_GET_LENGTH(self);
11718 kind = PyUnicode_KIND(self);
11719 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011720
Guido van Rossumd57fd912000-03-10 22:53:23 +000011721 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011722 if (length == 1) {
11723 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11724 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11725 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011726
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011727 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011728 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011729 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011730
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011731 for (i = 0; i < length; i++) {
11732 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011733 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011734 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011735 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011736}
11737
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011738PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011739 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011740\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011741Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011742False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011743
11744static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011745unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011746{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011747 Py_ssize_t i, length;
11748 int kind;
11749 void *data;
11750
11751 if (PyUnicode_READY(self) == -1)
11752 return NULL;
11753 length = PyUnicode_GET_LENGTH(self);
11754 kind = PyUnicode_KIND(self);
11755 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011756
Guido van Rossumd57fd912000-03-10 22:53:23 +000011757 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011758 if (length == 1)
11759 return PyBool_FromLong(
11760 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011761
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011762 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011763 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011764 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011765
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011766 for (i = 0; i < length; i++) {
11767 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011768 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011769 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011770 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011771}
11772
Martin v. Löwis47383402007-08-15 07:32:56 +000011773int
11774PyUnicode_IsIdentifier(PyObject *self)
11775{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011776 int kind;
11777 void *data;
11778 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011779 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011780
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011781 if (PyUnicode_READY(self) == -1) {
11782 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011783 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011784 }
11785
11786 /* Special case for empty strings */
11787 if (PyUnicode_GET_LENGTH(self) == 0)
11788 return 0;
11789 kind = PyUnicode_KIND(self);
11790 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011791
11792 /* PEP 3131 says that the first character must be in
11793 XID_Start and subsequent characters in XID_Continue,
11794 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011795 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011796 letters, digits, underscore). However, given the current
11797 definition of XID_Start and XID_Continue, it is sufficient
11798 to check just for these, except that _ must be allowed
11799 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011800 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011801 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011802 return 0;
11803
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011804 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011805 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011806 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011807 return 1;
11808}
11809
11810PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011811 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011812\n\
11813Return True if S is a valid identifier according\n\
11814to the language definition.");
11815
11816static PyObject*
11817unicode_isidentifier(PyObject *self)
11818{
11819 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11820}
11821
Georg Brandl559e5d72008-06-11 18:37:52 +000011822PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011823 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011824\n\
11825Return True if all characters in S are considered\n\
11826printable in repr() or S is empty, False otherwise.");
11827
11828static PyObject*
11829unicode_isprintable(PyObject *self)
11830{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011831 Py_ssize_t i, length;
11832 int kind;
11833 void *data;
11834
11835 if (PyUnicode_READY(self) == -1)
11836 return NULL;
11837 length = PyUnicode_GET_LENGTH(self);
11838 kind = PyUnicode_KIND(self);
11839 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011840
11841 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011842 if (length == 1)
11843 return PyBool_FromLong(
11844 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011845
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011846 for (i = 0; i < length; i++) {
11847 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011848 Py_RETURN_FALSE;
11849 }
11850 }
11851 Py_RETURN_TRUE;
11852}
11853
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011854PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011855 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011856\n\
11857Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011858iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011859
11860static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011861unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011862{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011863 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011864}
11865
Martin v. Löwis18e16552006-02-15 17:27:45 +000011866static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011867unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011868{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011869 if (PyUnicode_READY(self) == -1)
11870 return -1;
11871 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011872}
11873
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011874PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011875 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011876\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011877Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011878done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011879
11880static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011881unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011882{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011883 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011884 Py_UCS4 fillchar = ' ';
11885
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011886 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011887 return NULL;
11888
Benjamin Petersonbac79492012-01-14 13:34:47 -050011889 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010011890 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011891
Victor Stinnerc4b49542011-12-11 22:44:26 +010011892 if (PyUnicode_GET_LENGTH(self) >= width)
11893 return unicode_result_unchanged(self);
11894
11895 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011896}
11897
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011898PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011899 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011900\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011901Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011902
11903static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011904unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011905{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050011906 if (PyUnicode_READY(self) == -1)
11907 return NULL;
11908 if (PyUnicode_IS_ASCII(self))
11909 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010011910 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011911}
11912
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011913#define LEFTSTRIP 0
11914#define RIGHTSTRIP 1
11915#define BOTHSTRIP 2
11916
11917/* Arrays indexed by above */
11918static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11919
11920#define STRIPNAME(i) (stripformat[i]+3)
11921
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011922/* externally visible for str.strip(unicode) */
11923PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011924_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011925{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011926 void *data;
11927 int kind;
11928 Py_ssize_t i, j, len;
11929 BLOOM_MASK sepmask;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011930
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011931 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
11932 return NULL;
11933
11934 kind = PyUnicode_KIND(self);
11935 data = PyUnicode_DATA(self);
11936 len = PyUnicode_GET_LENGTH(self);
11937 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
11938 PyUnicode_DATA(sepobj),
11939 PyUnicode_GET_LENGTH(sepobj));
Thomas Wouters477c8d52006-05-27 19:21:47 +000011940
Benjamin Peterson14339b62009-01-31 16:36:08 +000011941 i = 0;
11942 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011943 while (i < len &&
11944 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, i), sepobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011945 i++;
11946 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011947 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011948
Benjamin Peterson14339b62009-01-31 16:36:08 +000011949 j = len;
11950 if (striptype != LEFTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011951 do {
11952 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011953 } while (j >= i &&
11954 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, j), sepobj));
Benjamin Peterson29060642009-01-31 22:14:21 +000011955 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011956 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011957
Victor Stinner7931d9a2011-11-04 00:22:48 +010011958 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011959}
11960
11961PyObject*
11962PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
11963{
11964 unsigned char *data;
11965 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020011966 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011967
Victor Stinnerde636f32011-10-01 03:55:54 +020011968 if (PyUnicode_READY(self) == -1)
11969 return NULL;
11970
11971 end = Py_MIN(end, PyUnicode_GET_LENGTH(self));
11972
Victor Stinner12bab6d2011-10-01 01:53:49 +020011973 if (start == 0 && end == PyUnicode_GET_LENGTH(self))
Victor Stinnerc4b49542011-12-11 22:44:26 +010011974 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011975
Victor Stinner12bab6d2011-10-01 01:53:49 +020011976 length = end - start;
11977 if (length == 1)
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011978 return unicode_getitem(self, start);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011979
Victor Stinnerde636f32011-10-01 03:55:54 +020011980 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011981 PyErr_SetString(PyExc_IndexError, "string index out of range");
11982 return NULL;
11983 }
11984
Victor Stinnerb9275c12011-10-05 14:01:42 +020011985 if (PyUnicode_IS_ASCII(self)) {
11986 kind = PyUnicode_KIND(self);
11987 data = PyUnicode_1BYTE_DATA(self);
11988 return unicode_fromascii(data + start, length);
11989 }
11990 else {
11991 kind = PyUnicode_KIND(self);
11992 data = PyUnicode_1BYTE_DATA(self);
11993 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011994 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020011995 length);
11996 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011997}
Guido van Rossumd57fd912000-03-10 22:53:23 +000011998
11999static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012000do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012001{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012002 int kind;
12003 void *data;
12004 Py_ssize_t len, i, j;
12005
12006 if (PyUnicode_READY(self) == -1)
12007 return NULL;
12008
12009 kind = PyUnicode_KIND(self);
12010 data = PyUnicode_DATA(self);
12011 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012012
Benjamin Peterson14339b62009-01-31 16:36:08 +000012013 i = 0;
12014 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012015 while (i < len && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, i))) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012016 i++;
12017 }
12018 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012019
Benjamin Peterson14339b62009-01-31 16:36:08 +000012020 j = len;
12021 if (striptype != LEFTSTRIP) {
12022 do {
12023 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012024 } while (j >= i && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, j)));
Benjamin Peterson14339b62009-01-31 16:36:08 +000012025 j++;
12026 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012027
Victor Stinner7931d9a2011-11-04 00:22:48 +010012028 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012029}
12030
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012031
12032static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012033do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012034{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012035 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012036
Benjamin Peterson14339b62009-01-31 16:36:08 +000012037 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
12038 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012039
Benjamin Peterson14339b62009-01-31 16:36:08 +000012040 if (sep != NULL && sep != Py_None) {
12041 if (PyUnicode_Check(sep))
12042 return _PyUnicode_XStrip(self, striptype, sep);
12043 else {
12044 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012045 "%s arg must be None or str",
12046 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000012047 return NULL;
12048 }
12049 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012050
Benjamin Peterson14339b62009-01-31 16:36:08 +000012051 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012052}
12053
12054
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012055PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012056 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012057\n\
12058Return a copy of the string S with leading and trailing\n\
12059whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012060If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012061
12062static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012063unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012064{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012065 if (PyTuple_GET_SIZE(args) == 0)
12066 return do_strip(self, BOTHSTRIP); /* Common case */
12067 else
12068 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012069}
12070
12071
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012072PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012073 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012074\n\
12075Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012076If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012077
12078static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012079unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012080{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012081 if (PyTuple_GET_SIZE(args) == 0)
12082 return do_strip(self, LEFTSTRIP); /* Common case */
12083 else
12084 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012085}
12086
12087
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012088PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012089 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012090\n\
12091Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012092If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012093
12094static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012095unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012096{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012097 if (PyTuple_GET_SIZE(args) == 0)
12098 return do_strip(self, RIGHTSTRIP); /* Common case */
12099 else
12100 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012101}
12102
12103
Guido van Rossumd57fd912000-03-10 22:53:23 +000012104static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012105unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012106{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012107 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012108 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012109
Georg Brandl222de0f2009-04-12 12:01:50 +000012110 if (len < 1) {
12111 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +020012112 return unicode_empty;
Georg Brandl222de0f2009-04-12 12:01:50 +000012113 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012114
Victor Stinnerc4b49542011-12-11 22:44:26 +010012115 /* no repeat, return original string */
12116 if (len == 1)
12117 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000012118
Benjamin Petersonbac79492012-01-14 13:34:47 -050012119 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012120 return NULL;
12121
Victor Stinnerc759f3e2011-10-01 03:09:58 +020012122 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020012123 PyErr_SetString(PyExc_OverflowError,
12124 "repeated string is too long");
12125 return NULL;
12126 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012127 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012128
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012129 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012130 if (!u)
12131 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012132 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012133
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012134 if (PyUnicode_GET_LENGTH(str) == 1) {
12135 const int kind = PyUnicode_KIND(str);
12136 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010012137 if (kind == PyUnicode_1BYTE_KIND) {
12138 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012139 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010012140 }
12141 else if (kind == PyUnicode_2BYTE_KIND) {
12142 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012143 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010012144 ucs2[n] = fill_char;
12145 } else {
12146 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
12147 assert(kind == PyUnicode_4BYTE_KIND);
12148 for (n = 0; n < len; ++n)
12149 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012150 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012151 }
12152 else {
12153 /* number of characters copied this far */
12154 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012155 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012156 char *to = (char *) PyUnicode_DATA(u);
12157 Py_MEMCPY(to, PyUnicode_DATA(str),
12158 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000012159 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012160 n = (done <= nchars-done) ? done : nchars-done;
12161 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012162 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000012163 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012164 }
12165
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012166 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012167 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012168}
12169
Alexander Belopolsky40018472011-02-26 01:02:56 +000012170PyObject *
12171PyUnicode_Replace(PyObject *obj,
12172 PyObject *subobj,
12173 PyObject *replobj,
12174 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012175{
12176 PyObject *self;
12177 PyObject *str1;
12178 PyObject *str2;
12179 PyObject *result;
12180
12181 self = PyUnicode_FromObject(obj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012182 if (self == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012183 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012184 str1 = PyUnicode_FromObject(subobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012185 if (str1 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012186 Py_DECREF(self);
12187 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012188 }
12189 str2 = PyUnicode_FromObject(replobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012190 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012191 Py_DECREF(self);
12192 Py_DECREF(str1);
12193 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012194 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060012195 if (PyUnicode_READY(self) == -1 ||
12196 PyUnicode_READY(str1) == -1 ||
12197 PyUnicode_READY(str2) == -1)
12198 result = NULL;
12199 else
12200 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012201 Py_DECREF(self);
12202 Py_DECREF(str1);
12203 Py_DECREF(str2);
12204 return result;
12205}
12206
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012207PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000012208 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012209\n\
12210Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000012211old replaced by new. If the optional argument count is\n\
12212given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012213
12214static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012215unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012216{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012217 PyObject *str1;
12218 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012219 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012220 PyObject *result;
12221
Martin v. Löwis18e16552006-02-15 17:27:45 +000012222 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012223 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060012224 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012225 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012226 str1 = PyUnicode_FromObject(str1);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012227 if (str1 == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012228 return NULL;
12229 str2 = PyUnicode_FromObject(str2);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012230 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012231 Py_DECREF(str1);
12232 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000012233 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060012234 if (PyUnicode_READY(str1) == -1 || PyUnicode_READY(str2) == -1)
12235 result = NULL;
12236 else
12237 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012238
12239 Py_DECREF(str1);
12240 Py_DECREF(str2);
12241 return result;
12242}
12243
Alexander Belopolsky40018472011-02-26 01:02:56 +000012244static PyObject *
12245unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012246{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012247 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012248 Py_ssize_t isize;
12249 Py_ssize_t osize, squote, dquote, i, o;
12250 Py_UCS4 max, quote;
12251 int ikind, okind;
12252 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012253
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012254 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012255 return NULL;
12256
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012257 isize = PyUnicode_GET_LENGTH(unicode);
12258 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012259
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012260 /* Compute length of output, quote characters, and
12261 maximum character */
12262 osize = 2; /* quotes */
12263 max = 127;
12264 squote = dquote = 0;
12265 ikind = PyUnicode_KIND(unicode);
12266 for (i = 0; i < isize; i++) {
12267 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
12268 switch (ch) {
12269 case '\'': squote++; osize++; break;
12270 case '"': dquote++; osize++; break;
12271 case '\\': case '\t': case '\r': case '\n':
12272 osize += 2; break;
12273 default:
12274 /* Fast-path ASCII */
12275 if (ch < ' ' || ch == 0x7f)
12276 osize += 4; /* \xHH */
12277 else if (ch < 0x7f)
12278 osize++;
12279 else if (Py_UNICODE_ISPRINTABLE(ch)) {
12280 osize++;
12281 max = ch > max ? ch : max;
12282 }
12283 else if (ch < 0x100)
12284 osize += 4; /* \xHH */
12285 else if (ch < 0x10000)
12286 osize += 6; /* \uHHHH */
12287 else
12288 osize += 10; /* \uHHHHHHHH */
12289 }
12290 }
12291
12292 quote = '\'';
12293 if (squote) {
12294 if (dquote)
12295 /* Both squote and dquote present. Use squote,
12296 and escape them */
12297 osize += squote;
12298 else
12299 quote = '"';
12300 }
12301
12302 repr = PyUnicode_New(osize, max);
12303 if (repr == NULL)
12304 return NULL;
12305 okind = PyUnicode_KIND(repr);
12306 odata = PyUnicode_DATA(repr);
12307
12308 PyUnicode_WRITE(okind, odata, 0, quote);
12309 PyUnicode_WRITE(okind, odata, osize-1, quote);
12310
12311 for (i = 0, o = 1; i < isize; i++) {
12312 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012313
12314 /* Escape quotes and backslashes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012315 if ((ch == quote) || (ch == '\\')) {
12316 PyUnicode_WRITE(okind, odata, o++, '\\');
12317 PyUnicode_WRITE(okind, odata, o++, ch);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012318 continue;
12319 }
12320
Benjamin Peterson29060642009-01-31 22:14:21 +000012321 /* Map special whitespace to '\t', \n', '\r' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012322 if (ch == '\t') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012323 PyUnicode_WRITE(okind, odata, o++, '\\');
12324 PyUnicode_WRITE(okind, odata, o++, 't');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012325 }
12326 else if (ch == '\n') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012327 PyUnicode_WRITE(okind, odata, o++, '\\');
12328 PyUnicode_WRITE(okind, odata, o++, 'n');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012329 }
12330 else if (ch == '\r') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012331 PyUnicode_WRITE(okind, odata, o++, '\\');
12332 PyUnicode_WRITE(okind, odata, o++, 'r');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012333 }
12334
12335 /* Map non-printable US ASCII to '\xhh' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012336 else if (ch < ' ' || ch == 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012337 PyUnicode_WRITE(okind, odata, o++, '\\');
12338 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012339 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12340 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012341 }
12342
Georg Brandl559e5d72008-06-11 18:37:52 +000012343 /* Copy ASCII characters as-is */
12344 else if (ch < 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012345 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012346 }
12347
Benjamin Peterson29060642009-01-31 22:14:21 +000012348 /* Non-ASCII characters */
Georg Brandl559e5d72008-06-11 18:37:52 +000012349 else {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012350 /* Map Unicode whitespace and control characters
Georg Brandl559e5d72008-06-11 18:37:52 +000012351 (categories Z* and C* except ASCII space)
12352 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012353 if (!Py_UNICODE_ISPRINTABLE(ch)) {
Georg Brandl559e5d72008-06-11 18:37:52 +000012354 /* Map 8-bit characters to '\xhh' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012355 if (ch <= 0xff) {
12356 PyUnicode_WRITE(okind, odata, o++, '\\');
12357 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012358 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12359 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012360 }
12361 /* Map 21-bit characters to '\U00xxxxxx' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012362 else if (ch >= 0x10000) {
12363 PyUnicode_WRITE(okind, odata, o++, '\\');
12364 PyUnicode_WRITE(okind, odata, o++, 'U');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012365 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12366 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12367 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12368 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12369 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12370 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12371 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12372 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012373 }
12374 /* Map 16-bit characters to '\uxxxx' */
12375 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012376 PyUnicode_WRITE(okind, odata, o++, '\\');
12377 PyUnicode_WRITE(okind, odata, o++, 'u');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012378 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12379 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12380 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12381 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012382 }
12383 }
12384 /* Copy characters as-is */
12385 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012386 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012387 }
12388 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012389 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012390 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012391 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012392 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012393}
12394
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012395PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012396 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012397\n\
12398Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012399such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012400arguments start and end are interpreted as in slice notation.\n\
12401\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012402Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012403
12404static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012405unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012406{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012407 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012408 Py_ssize_t start;
12409 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012410 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012411
Jesus Ceaac451502011-04-20 17:09:23 +020012412 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
12413 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012414 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012415
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012416 if (PyUnicode_READY(self) == -1)
12417 return NULL;
12418 if (PyUnicode_READY(substring) == -1)
12419 return NULL;
12420
Victor Stinner7931d9a2011-11-04 00:22:48 +010012421 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012422
12423 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012424
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012425 if (result == -2)
12426 return NULL;
12427
Christian Heimes217cfd12007-12-02 14:31:20 +000012428 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012429}
12430
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012431PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012432 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012433\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012434Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012435
12436static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012437unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012438{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012439 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012440 Py_ssize_t start;
12441 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012442 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012443
Jesus Ceaac451502011-04-20 17:09:23 +020012444 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12445 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012446 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012447
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012448 if (PyUnicode_READY(self) == -1)
12449 return NULL;
12450 if (PyUnicode_READY(substring) == -1)
12451 return NULL;
12452
Victor Stinner7931d9a2011-11-04 00:22:48 +010012453 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012454
12455 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012456
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012457 if (result == -2)
12458 return NULL;
12459
Guido van Rossumd57fd912000-03-10 22:53:23 +000012460 if (result < 0) {
12461 PyErr_SetString(PyExc_ValueError, "substring not found");
12462 return NULL;
12463 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012464
Christian Heimes217cfd12007-12-02 14:31:20 +000012465 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012466}
12467
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012468PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012469 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012470\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012471Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012472done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012473
12474static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012475unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012476{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012477 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012478 Py_UCS4 fillchar = ' ';
12479
Victor Stinnere9a29352011-10-01 02:14:59 +020012480 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012481 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012482
Benjamin Petersonbac79492012-01-14 13:34:47 -050012483 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012484 return NULL;
12485
Victor Stinnerc4b49542011-12-11 22:44:26 +010012486 if (PyUnicode_GET_LENGTH(self) >= width)
12487 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012488
Victor Stinnerc4b49542011-12-11 22:44:26 +010012489 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012490}
12491
Alexander Belopolsky40018472011-02-26 01:02:56 +000012492PyObject *
12493PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012494{
12495 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012496
Guido van Rossumd57fd912000-03-10 22:53:23 +000012497 s = PyUnicode_FromObject(s);
12498 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012499 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012500 if (sep != NULL) {
12501 sep = PyUnicode_FromObject(sep);
12502 if (sep == NULL) {
12503 Py_DECREF(s);
12504 return NULL;
12505 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012506 }
12507
Victor Stinner9310abb2011-10-05 00:59:23 +020012508 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012509
12510 Py_DECREF(s);
12511 Py_XDECREF(sep);
12512 return result;
12513}
12514
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012515PyDoc_STRVAR(split__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012516 "S.split(sep=None, maxsplit=-1) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012517\n\
12518Return a list of the words in S, using sep as the\n\
12519delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012520splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012521whitespace string is a separator and empty strings are\n\
12522removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012523
12524static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012525unicode_split(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012526{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012527 static char *kwlist[] = {"sep", "maxsplit", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000012528 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012529 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012530
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012531 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:split",
12532 kwlist, &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012533 return NULL;
12534
12535 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012536 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012537 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012538 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012539 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012540 return PyUnicode_Split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012541}
12542
Thomas Wouters477c8d52006-05-27 19:21:47 +000012543PyObject *
12544PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12545{
12546 PyObject* str_obj;
12547 PyObject* sep_obj;
12548 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012549 int kind1, kind2, kind;
12550 void *buf1 = NULL, *buf2 = NULL;
12551 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012552
12553 str_obj = PyUnicode_FromObject(str_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012554 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012555 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012556 sep_obj = PyUnicode_FromObject(sep_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012557 if (!sep_obj) {
12558 Py_DECREF(str_obj);
12559 return NULL;
12560 }
12561 if (PyUnicode_READY(sep_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
12562 Py_DECREF(sep_obj);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012563 Py_DECREF(str_obj);
12564 return NULL;
12565 }
12566
Victor Stinner14f8f022011-10-05 20:58:25 +020012567 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012568 kind2 = PyUnicode_KIND(sep_obj);
Victor Stinner14f8f022011-10-05 20:58:25 +020012569 kind = Py_MAX(kind1, kind2);
12570 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012571 if (kind1 != kind)
Victor Stinner14f8f022011-10-05 20:58:25 +020012572 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012573 if (!buf1)
12574 goto onError;
12575 buf2 = PyUnicode_DATA(sep_obj);
12576 if (kind2 != kind)
12577 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12578 if (!buf2)
12579 goto onError;
12580 len1 = PyUnicode_GET_LENGTH(str_obj);
12581 len2 = PyUnicode_GET_LENGTH(sep_obj);
12582
Benjamin Petersonead6b532011-12-20 17:23:42 -060012583 switch (PyUnicode_KIND(str_obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012584 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012585 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12586 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12587 else
12588 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012589 break;
12590 case PyUnicode_2BYTE_KIND:
12591 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12592 break;
12593 case PyUnicode_4BYTE_KIND:
12594 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12595 break;
12596 default:
12597 assert(0);
12598 out = 0;
12599 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012600
12601 Py_DECREF(sep_obj);
12602 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012603 if (kind1 != kind)
12604 PyMem_Free(buf1);
12605 if (kind2 != kind)
12606 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012607
12608 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012609 onError:
12610 Py_DECREF(sep_obj);
12611 Py_DECREF(str_obj);
12612 if (kind1 != kind && buf1)
12613 PyMem_Free(buf1);
12614 if (kind2 != kind && buf2)
12615 PyMem_Free(buf2);
12616 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012617}
12618
12619
12620PyObject *
12621PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12622{
12623 PyObject* str_obj;
12624 PyObject* sep_obj;
12625 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012626 int kind1, kind2, kind;
12627 void *buf1 = NULL, *buf2 = NULL;
12628 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012629
12630 str_obj = PyUnicode_FromObject(str_in);
12631 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012632 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012633 sep_obj = PyUnicode_FromObject(sep_in);
12634 if (!sep_obj) {
12635 Py_DECREF(str_obj);
12636 return NULL;
12637 }
12638
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012639 kind1 = PyUnicode_KIND(str_in);
12640 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020012641 kind = Py_MAX(kind1, kind2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012642 buf1 = PyUnicode_DATA(str_in);
12643 if (kind1 != kind)
12644 buf1 = _PyUnicode_AsKind(str_in, kind);
12645 if (!buf1)
12646 goto onError;
12647 buf2 = PyUnicode_DATA(sep_obj);
12648 if (kind2 != kind)
12649 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12650 if (!buf2)
12651 goto onError;
12652 len1 = PyUnicode_GET_LENGTH(str_obj);
12653 len2 = PyUnicode_GET_LENGTH(sep_obj);
12654
Benjamin Petersonead6b532011-12-20 17:23:42 -060012655 switch (PyUnicode_KIND(str_in)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012656 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012657 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12658 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12659 else
12660 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012661 break;
12662 case PyUnicode_2BYTE_KIND:
12663 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12664 break;
12665 case PyUnicode_4BYTE_KIND:
12666 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12667 break;
12668 default:
12669 assert(0);
12670 out = 0;
12671 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012672
12673 Py_DECREF(sep_obj);
12674 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012675 if (kind1 != kind)
12676 PyMem_Free(buf1);
12677 if (kind2 != kind)
12678 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012679
12680 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012681 onError:
12682 Py_DECREF(sep_obj);
12683 Py_DECREF(str_obj);
12684 if (kind1 != kind && buf1)
12685 PyMem_Free(buf1);
12686 if (kind2 != kind && buf2)
12687 PyMem_Free(buf2);
12688 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012689}
12690
12691PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012692 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012693\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012694Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012695the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012696found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012697
12698static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012699unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012700{
Victor Stinner9310abb2011-10-05 00:59:23 +020012701 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012702}
12703
12704PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012705 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012706\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012707Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012708the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012709separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012710
12711static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012712unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012713{
Victor Stinner9310abb2011-10-05 00:59:23 +020012714 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012715}
12716
Alexander Belopolsky40018472011-02-26 01:02:56 +000012717PyObject *
12718PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012719{
12720 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012721
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012722 s = PyUnicode_FromObject(s);
12723 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012724 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012725 if (sep != NULL) {
12726 sep = PyUnicode_FromObject(sep);
12727 if (sep == NULL) {
12728 Py_DECREF(s);
12729 return NULL;
12730 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012731 }
12732
Victor Stinner9310abb2011-10-05 00:59:23 +020012733 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012734
12735 Py_DECREF(s);
12736 Py_XDECREF(sep);
12737 return result;
12738}
12739
12740PyDoc_STRVAR(rsplit__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012741 "S.rsplit(sep=None, maxsplit=-1) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012742\n\
12743Return a list of the words in S, using sep as the\n\
12744delimiter string, starting at the end of the string and\n\
12745working to the front. If maxsplit is given, at most maxsplit\n\
12746splits are done. If sep is not specified, any whitespace string\n\
12747is a separator.");
12748
12749static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012750unicode_rsplit(PyObject *self, PyObject *args, PyObject *kwds)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012751{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012752 static char *kwlist[] = {"sep", "maxsplit", 0};
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012753 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012754 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012755
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012756 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:rsplit",
12757 kwlist, &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012758 return NULL;
12759
12760 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012761 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012762 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012763 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012764 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012765 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012766}
12767
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012768PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012769 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012770\n\
12771Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012772Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012773is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012774
12775static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012776unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012777{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012778 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012779 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012780
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012781 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12782 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012783 return NULL;
12784
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012785 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012786}
12787
12788static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012789PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012790{
Victor Stinnerc4b49542011-12-11 22:44:26 +010012791 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012792}
12793
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012794PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012795 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012796\n\
12797Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012798and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012799
12800static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012801unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012802{
Benjamin Petersoneea48462012-01-16 14:28:50 -050012803 if (PyUnicode_READY(self) == -1)
12804 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012805 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012806}
12807
Georg Brandlceee0772007-11-27 23:48:05 +000012808PyDoc_STRVAR(maketrans__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012809 "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012810\n\
12811Return a translation table usable for str.translate().\n\
12812If there is only one argument, it must be a dictionary mapping Unicode\n\
12813ordinals (integers) or characters to Unicode ordinals, strings or None.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012814Character keys will be then converted to ordinals.\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012815If there are two arguments, they must be strings of equal length, and\n\
12816in the resulting dictionary, each character in x will be mapped to the\n\
12817character at the same position in y. If there is a third argument, it\n\
12818must be a string, whose characters will be mapped to None in the result.");
12819
12820static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012821unicode_maketrans(PyObject *null, PyObject *args)
Georg Brandlceee0772007-11-27 23:48:05 +000012822{
12823 PyObject *x, *y = NULL, *z = NULL;
12824 PyObject *new = NULL, *key, *value;
12825 Py_ssize_t i = 0;
12826 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012827
Georg Brandlceee0772007-11-27 23:48:05 +000012828 if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
12829 return NULL;
12830 new = PyDict_New();
12831 if (!new)
12832 return NULL;
12833 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012834 int x_kind, y_kind, z_kind;
12835 void *x_data, *y_data, *z_data;
12836
Georg Brandlceee0772007-11-27 23:48:05 +000012837 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012838 if (!PyUnicode_Check(x)) {
12839 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12840 "be a string if there is a second argument");
12841 goto err;
12842 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012843 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012844 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12845 "arguments must have equal length");
12846 goto err;
12847 }
12848 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012849 x_kind = PyUnicode_KIND(x);
12850 y_kind = PyUnicode_KIND(y);
12851 x_data = PyUnicode_DATA(x);
12852 y_data = PyUnicode_DATA(y);
12853 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
12854 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012855 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000012856 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060012857 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012858 if (!value) {
12859 Py_DECREF(key);
12860 goto err;
12861 }
Georg Brandlceee0772007-11-27 23:48:05 +000012862 res = PyDict_SetItem(new, key, value);
12863 Py_DECREF(key);
12864 Py_DECREF(value);
12865 if (res < 0)
12866 goto err;
12867 }
12868 /* create entries for deleting chars in z */
12869 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012870 z_kind = PyUnicode_KIND(z);
12871 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012872 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012873 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012874 if (!key)
12875 goto err;
12876 res = PyDict_SetItem(new, key, Py_None);
12877 Py_DECREF(key);
12878 if (res < 0)
12879 goto err;
12880 }
12881 }
12882 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012883 int kind;
12884 void *data;
12885
Georg Brandlceee0772007-11-27 23:48:05 +000012886 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000012887 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012888 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
12889 "to maketrans it must be a dict");
12890 goto err;
12891 }
12892 /* copy entries into the new dict, converting string keys to int keys */
12893 while (PyDict_Next(x, &i, &key, &value)) {
12894 if (PyUnicode_Check(key)) {
12895 /* convert string keys to integer keys */
12896 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012897 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000012898 PyErr_SetString(PyExc_ValueError, "string keys in translate "
12899 "table must be of length 1");
12900 goto err;
12901 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012902 kind = PyUnicode_KIND(key);
12903 data = PyUnicode_DATA(key);
12904 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000012905 if (!newkey)
12906 goto err;
12907 res = PyDict_SetItem(new, newkey, value);
12908 Py_DECREF(newkey);
12909 if (res < 0)
12910 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000012911 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012912 /* just keep integer keys */
12913 if (PyDict_SetItem(new, key, value) < 0)
12914 goto err;
12915 } else {
12916 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
12917 "be strings or integers");
12918 goto err;
12919 }
12920 }
12921 }
12922 return new;
12923 err:
12924 Py_DECREF(new);
12925 return NULL;
12926}
12927
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012928PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012929 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012930\n\
12931Return a copy of the string S, where all characters have been mapped\n\
12932through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012933Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000012934Unmapped characters are left untouched. Characters mapped to None\n\
12935are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012936
12937static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012938unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012939{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012940 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012941}
12942
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012943PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012944 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012945\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012946Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012947
12948static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012949unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012950{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050012951 if (PyUnicode_READY(self) == -1)
12952 return NULL;
12953 if (PyUnicode_IS_ASCII(self))
12954 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012955 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012956}
12957
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012958PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012959 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012960\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000012961Pad a numeric string S with zeros on the left, to fill a field\n\
12962of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012963
12964static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012965unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012966{
Martin v. Löwis18e16552006-02-15 17:27:45 +000012967 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020012968 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012969 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012970 int kind;
12971 void *data;
12972 Py_UCS4 chr;
12973
Martin v. Löwis18e16552006-02-15 17:27:45 +000012974 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012975 return NULL;
12976
Benjamin Petersonbac79492012-01-14 13:34:47 -050012977 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012978 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012979
Victor Stinnerc4b49542011-12-11 22:44:26 +010012980 if (PyUnicode_GET_LENGTH(self) >= width)
12981 return unicode_result_unchanged(self);
12982
12983 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012984
12985 u = pad(self, fill, 0, '0');
12986
Walter Dörwald068325e2002-04-15 13:36:47 +000012987 if (u == NULL)
12988 return NULL;
12989
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012990 kind = PyUnicode_KIND(u);
12991 data = PyUnicode_DATA(u);
12992 chr = PyUnicode_READ(kind, data, fill);
12993
12994 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012995 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012996 PyUnicode_WRITE(kind, data, 0, chr);
12997 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000012998 }
12999
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013000 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010013001 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013002}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013003
13004#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013005static PyObject *
13006unicode__decimal2ascii(PyObject *self)
13007{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013008 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013009}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013010#endif
13011
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013012PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013013 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013014\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013015Return True if S starts with the specified prefix, False otherwise.\n\
13016With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013017With optional end, stop comparing S at that position.\n\
13018prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013019
13020static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013021unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013022 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013023{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013024 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013025 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013026 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013027 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013028 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013029
Jesus Ceaac451502011-04-20 17:09:23 +020013030 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013031 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013032 if (PyTuple_Check(subobj)) {
13033 Py_ssize_t i;
13034 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013035 substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013036 if (substring == NULL)
13037 return NULL;
13038 result = tailmatch(self, substring, start, end, -1);
13039 Py_DECREF(substring);
13040 if (result) {
13041 Py_RETURN_TRUE;
13042 }
13043 }
13044 /* nothing matched */
13045 Py_RETURN_FALSE;
13046 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013047 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030013048 if (substring == NULL) {
13049 if (PyErr_ExceptionMatches(PyExc_TypeError))
13050 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
13051 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013052 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013053 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013054 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013055 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013056 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013057}
13058
13059
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013060PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013061 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013062\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013063Return True if S ends with the specified suffix, False otherwise.\n\
13064With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013065With optional end, stop comparing S at that position.\n\
13066suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013067
13068static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013069unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013070 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013071{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013072 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013073 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013074 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013075 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013076 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013077
Jesus Ceaac451502011-04-20 17:09:23 +020013078 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013079 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013080 if (PyTuple_Check(subobj)) {
13081 Py_ssize_t i;
13082 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013083 substring = PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000013084 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013085 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000013086 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013087 result = tailmatch(self, substring, start, end, +1);
13088 Py_DECREF(substring);
13089 if (result) {
13090 Py_RETURN_TRUE;
13091 }
13092 }
13093 Py_RETURN_FALSE;
13094 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013095 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030013096 if (substring == NULL) {
13097 if (PyErr_ExceptionMatches(PyExc_TypeError))
13098 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
13099 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013100 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013101 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013102 result = tailmatch(self, substring, start, end, +1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013103 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013104 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013105}
13106
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013107#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000013108
13109PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013110 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013111\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013112Return a formatted version of S, using substitutions from args and kwargs.\n\
13113The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000013114
Eric Smith27bbca62010-11-04 17:06:58 +000013115PyDoc_STRVAR(format_map__doc__,
13116 "S.format_map(mapping) -> str\n\
13117\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013118Return a formatted version of S, using substitutions from mapping.\n\
13119The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000013120
Eric Smith4a7d76d2008-05-30 18:10:19 +000013121static PyObject *
13122unicode__format__(PyObject* self, PyObject* args)
13123{
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013124 PyObject *format_spec, *out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013125
13126 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
13127 return NULL;
13128
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013129 out = _PyUnicode_FormatAdvanced(self, format_spec, 0,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013130 PyUnicode_GET_LENGTH(format_spec));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013131 return out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013132}
13133
Eric Smith8c663262007-08-25 02:26:07 +000013134PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013135 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013136\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013137Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000013138
13139static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013140unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013141{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013142 Py_ssize_t size;
13143
13144 /* If it's a compact object, account for base structure +
13145 character data. */
13146 if (PyUnicode_IS_COMPACT_ASCII(v))
13147 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
13148 else if (PyUnicode_IS_COMPACT(v))
13149 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013150 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013151 else {
13152 /* If it is a two-block object, account for base object, and
13153 for character block if present. */
13154 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020013155 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013156 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013157 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013158 }
13159 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013160 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020013161 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013162 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020013163 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020013164 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013165
13166 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013167}
13168
13169PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013170 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013171
13172static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020013173unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013174{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013175 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013176 if (!copy)
13177 return NULL;
13178 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013179}
13180
Guido van Rossumd57fd912000-03-10 22:53:23 +000013181static PyMethodDef unicode_methods[] = {
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000013182 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013183 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013184 {"split", (PyCFunction) unicode_split, METH_VARARGS | METH_KEYWORDS, split__doc__},
13185 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS | METH_KEYWORDS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013186 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
13187 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
Benjamin Petersond5890c82012-01-14 13:23:30 -050013188 {"casefold", (PyCFunction) unicode_casefold, METH_NOARGS, casefold__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013189 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
13190 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
13191 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
13192 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
13193 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013194 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013195 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
13196 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
13197 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013198 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013199 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13200 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
13201 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013202 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013203 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010013204 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013205 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013206 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
13207 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
13208 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
13209 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13210 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
13211 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
13212 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
13213 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
13214 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
13215 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
13216 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
13217 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
13218 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
13219 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000013220 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000013221 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013222 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000013223 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013224 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000013225 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Georg Brandlceee0772007-11-27 23:48:05 +000013226 {"maketrans", (PyCFunction) unicode_maketrans,
13227 METH_VARARGS | METH_STATIC, maketrans__doc__},
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013228 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000013229#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013230 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013231 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013232#endif
13233
Benjamin Peterson14339b62009-01-31 16:36:08 +000013234 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013235 {NULL, NULL}
13236};
13237
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013238static PyObject *
13239unicode_mod(PyObject *v, PyObject *w)
13240{
Brian Curtindfc80e32011-08-10 20:28:54 -050013241 if (!PyUnicode_Check(v))
13242 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013243 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013244}
13245
13246static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013247 0, /*nb_add*/
13248 0, /*nb_subtract*/
13249 0, /*nb_multiply*/
13250 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013251};
13252
Guido van Rossumd57fd912000-03-10 22:53:23 +000013253static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013254 (lenfunc) unicode_length, /* sq_length */
13255 PyUnicode_Concat, /* sq_concat */
13256 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13257 (ssizeargfunc) unicode_getitem, /* sq_item */
13258 0, /* sq_slice */
13259 0, /* sq_ass_item */
13260 0, /* sq_ass_slice */
13261 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013262};
13263
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013264static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013265unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013266{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013267 if (PyUnicode_READY(self) == -1)
13268 return NULL;
13269
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013270 if (PyIndex_Check(item)) {
13271 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013272 if (i == -1 && PyErr_Occurred())
13273 return NULL;
13274 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013275 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013276 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013277 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013278 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013279 PyObject *result;
13280 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013281 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013282 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013283
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013284 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013285 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013286 return NULL;
13287 }
13288
13289 if (slicelength <= 0) {
Victor Stinner382955f2011-12-11 21:44:00 +010013290 Py_INCREF(unicode_empty);
13291 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013292 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013293 slicelength == PyUnicode_GET_LENGTH(self)) {
13294 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013295 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013296 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013297 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013298 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013299 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013300 src_kind = PyUnicode_KIND(self);
13301 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013302 if (!PyUnicode_IS_ASCII(self)) {
13303 kind_limit = kind_maxchar_limit(src_kind);
13304 max_char = 0;
13305 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13306 ch = PyUnicode_READ(src_kind, src_data, cur);
13307 if (ch > max_char) {
13308 max_char = ch;
13309 if (max_char >= kind_limit)
13310 break;
13311 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013312 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013313 }
Victor Stinner55c99112011-10-13 01:17:06 +020013314 else
13315 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013316 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013317 if (result == NULL)
13318 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013319 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013320 dest_data = PyUnicode_DATA(result);
13321
13322 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013323 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13324 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013325 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013326 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013327 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013328 } else {
13329 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13330 return NULL;
13331 }
13332}
13333
13334static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013335 (lenfunc)unicode_length, /* mp_length */
13336 (binaryfunc)unicode_subscript, /* mp_subscript */
13337 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013338};
13339
Guido van Rossumd57fd912000-03-10 22:53:23 +000013340
Guido van Rossumd57fd912000-03-10 22:53:23 +000013341/* Helpers for PyUnicode_Format() */
13342
13343static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +000013344getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013345{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013346 Py_ssize_t argidx = *p_argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013347 if (argidx < arglen) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013348 (*p_argidx)++;
13349 if (arglen < 0)
13350 return args;
13351 else
13352 return PyTuple_GetItem(args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013353 }
13354 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013355 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013356 return NULL;
13357}
13358
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013359/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013360
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013361static PyObject *
13362formatfloat(PyObject *v, int flags, int prec, int type)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013363{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013364 char *p;
13365 PyObject *result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013366 double x;
Tim Petersced69f82003-09-16 20:30:58 +000013367
Guido van Rossumd57fd912000-03-10 22:53:23 +000013368 x = PyFloat_AsDouble(v);
13369 if (x == -1.0 && PyErr_Occurred())
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013370 return NULL;
13371
Guido van Rossumd57fd912000-03-10 22:53:23 +000013372 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013373 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013374
Eric Smith0923d1d2009-04-16 20:16:10 +000013375 p = PyOS_double_to_string(x, type, prec,
13376 (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013377 if (p == NULL)
13378 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013379 result = PyUnicode_DecodeASCII(p, strlen(p), NULL);
Eric Smith0923d1d2009-04-16 20:16:10 +000013380 PyMem_Free(p);
13381 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013382}
13383
Tim Peters38fd5b62000-09-21 05:43:11 +000013384static PyObject*
13385formatlong(PyObject *val, int flags, int prec, int type)
13386{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013387 char *buf;
13388 int len;
13389 PyObject *str; /* temporary string object. */
13390 PyObject *result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013391
Benjamin Peterson14339b62009-01-31 16:36:08 +000013392 str = _PyBytes_FormatLong(val, flags, prec, type, &buf, &len);
13393 if (!str)
13394 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013395 result = PyUnicode_DecodeASCII(buf, len, NULL);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013396 Py_DECREF(str);
13397 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013398}
13399
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013400static Py_UCS4
13401formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013402{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013403 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013404 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013405 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013406 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000013407 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013408 goto onError;
13409 }
13410 else {
13411 /* Integer input truncated to a character */
13412 long x;
13413 x = PyLong_AsLong(v);
13414 if (x == -1 && PyErr_Occurred())
13415 goto onError;
13416
Victor Stinner8faf8212011-12-08 22:14:11 +010013417 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013418 PyErr_SetString(PyExc_OverflowError,
13419 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013420 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013421 }
13422
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013423 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013424 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013425
Benjamin Peterson29060642009-01-31 22:14:21 +000013426 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013427 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013428 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013429 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013430}
13431
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013432static int
13433repeat_accumulate(_PyAccu *acc, PyObject *obj, Py_ssize_t count)
13434{
13435 int r;
13436 assert(count > 0);
13437 assert(PyUnicode_Check(obj));
13438 if (count > 5) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013439 PyObject *repeated = unicode_repeat(obj, count);
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013440 if (repeated == NULL)
13441 return -1;
13442 r = _PyAccu_Accumulate(acc, repeated);
13443 Py_DECREF(repeated);
13444 return r;
13445 }
13446 else {
13447 do {
13448 if (_PyAccu_Accumulate(acc, obj))
13449 return -1;
13450 } while (--count);
13451 return 0;
13452 }
13453}
13454
Alexander Belopolsky40018472011-02-26 01:02:56 +000013455PyObject *
13456PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013457{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013458 void *fmt;
13459 int fmtkind;
13460 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013461 int kind;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013462 int r;
13463 Py_ssize_t fmtcnt, fmtpos, arglen, argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013464 int args_owned = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013465 PyObject *dict = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013466 PyObject *temp = NULL;
13467 PyObject *second = NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013468 PyObject *uformat;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013469 _PyAccu acc;
13470 static PyObject *plus, *minus, *blank, *zero, *percent;
13471
13472 if (!plus && !(plus = get_latin1_char('+')))
13473 return NULL;
13474 if (!minus && !(minus = get_latin1_char('-')))
13475 return NULL;
13476 if (!blank && !(blank = get_latin1_char(' ')))
13477 return NULL;
13478 if (!zero && !(zero = get_latin1_char('0')))
13479 return NULL;
13480 if (!percent && !(percent = get_latin1_char('%')))
13481 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000013482
Guido van Rossumd57fd912000-03-10 22:53:23 +000013483 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013484 PyErr_BadInternalCall();
13485 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013486 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013487 uformat = PyUnicode_FromObject(format);
Benjamin Peterson22a29702012-01-02 09:00:30 -060013488 if (uformat == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000013489 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060013490 if (PyUnicode_READY(uformat) == -1)
13491 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013492 if (_PyAccu_Init(&acc))
13493 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013494 fmt = PyUnicode_DATA(uformat);
13495 fmtkind = PyUnicode_KIND(uformat);
13496 fmtcnt = PyUnicode_GET_LENGTH(uformat);
13497 fmtpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013498
Guido van Rossumd57fd912000-03-10 22:53:23 +000013499 if (PyTuple_Check(args)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013500 arglen = PyTuple_Size(args);
13501 argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013502 }
13503 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013504 arglen = -1;
13505 argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013506 }
Christian Heimes90aa7642007-12-19 02:45:37 +000013507 if (Py_TYPE(args)->tp_as_mapping && !PyTuple_Check(args) &&
Christian Heimesf3863112007-11-22 07:46:41 +000013508 !PyUnicode_Check(args))
Benjamin Peterson29060642009-01-31 22:14:21 +000013509 dict = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013510
13511 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013512 if (PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013513 PyObject *nonfmt;
13514 Py_ssize_t nonfmtpos;
13515 nonfmtpos = fmtpos++;
13516 while (fmtcnt >= 0 &&
13517 PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
13518 fmtpos++;
13519 fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013520 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010013521 nonfmt = PyUnicode_Substring(uformat, nonfmtpos, fmtpos);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013522 if (nonfmt == NULL)
13523 goto onError;
13524 r = _PyAccu_Accumulate(&acc, nonfmt);
13525 Py_DECREF(nonfmt);
13526 if (r)
13527 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013528 }
13529 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013530 /* Got a format specifier */
13531 int flags = 0;
13532 Py_ssize_t width = -1;
13533 int prec = -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013534 Py_UCS4 c = '\0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013535 Py_UCS4 fill, sign;
Benjamin Peterson29060642009-01-31 22:14:21 +000013536 int isnumok;
13537 PyObject *v = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013538 void *pbuf = NULL;
13539 Py_ssize_t pindex, len;
13540 PyObject *signobj = NULL, *fillobj = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013541
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013542 fmtpos++;
13543 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(') {
13544 Py_ssize_t keystart;
Benjamin Peterson29060642009-01-31 22:14:21 +000013545 Py_ssize_t keylen;
13546 PyObject *key;
13547 int pcount = 1;
Christian Heimesa612dc02008-02-24 13:08:18 +000013548
Benjamin Peterson29060642009-01-31 22:14:21 +000013549 if (dict == NULL) {
13550 PyErr_SetString(PyExc_TypeError,
13551 "format requires a mapping");
13552 goto onError;
13553 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013554 ++fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013555 --fmtcnt;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013556 keystart = fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013557 /* Skip over balanced parentheses */
13558 while (pcount > 0 && --fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013559 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == ')')
Benjamin Peterson29060642009-01-31 22:14:21 +000013560 --pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013561 else if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(')
Benjamin Peterson29060642009-01-31 22:14:21 +000013562 ++pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013563 fmtpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013564 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013565 keylen = fmtpos - keystart - 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013566 if (fmtcnt < 0 || pcount > 0) {
13567 PyErr_SetString(PyExc_ValueError,
13568 "incomplete format key");
13569 goto onError;
13570 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010013571 key = PyUnicode_Substring(uformat,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013572 keystart, keystart + keylen);
Benjamin Peterson29060642009-01-31 22:14:21 +000013573 if (key == NULL)
13574 goto onError;
13575 if (args_owned) {
13576 Py_DECREF(args);
13577 args_owned = 0;
13578 }
13579 args = PyObject_GetItem(dict, key);
13580 Py_DECREF(key);
13581 if (args == NULL) {
13582 goto onError;
13583 }
13584 args_owned = 1;
13585 arglen = -1;
13586 argidx = -2;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013587 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013588 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013589 switch (c = PyUnicode_READ(fmtkind, fmt, fmtpos++)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013590 case '-': flags |= F_LJUST; continue;
13591 case '+': flags |= F_SIGN; continue;
13592 case ' ': flags |= F_BLANK; continue;
13593 case '#': flags |= F_ALT; continue;
13594 case '0': flags |= F_ZERO; continue;
13595 }
13596 break;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013597 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013598 if (c == '*') {
13599 v = getnextarg(args, arglen, &argidx);
13600 if (v == NULL)
13601 goto onError;
13602 if (!PyLong_Check(v)) {
13603 PyErr_SetString(PyExc_TypeError,
13604 "* wants int");
13605 goto onError;
13606 }
13607 width = PyLong_AsLong(v);
13608 if (width == -1 && PyErr_Occurred())
13609 goto onError;
13610 if (width < 0) {
13611 flags |= F_LJUST;
13612 width = -width;
13613 }
13614 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013615 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013616 }
13617 else if (c >= '0' && c <= '9') {
13618 width = c - '0';
13619 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013620 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013621 if (c < '0' || c > '9')
13622 break;
13623 if ((width*10) / 10 != width) {
13624 PyErr_SetString(PyExc_ValueError,
13625 "width too big");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013626 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013627 }
13628 width = width*10 + (c - '0');
13629 }
13630 }
13631 if (c == '.') {
13632 prec = 0;
13633 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013634 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013635 if (c == '*') {
13636 v = getnextarg(args, arglen, &argidx);
13637 if (v == NULL)
13638 goto onError;
13639 if (!PyLong_Check(v)) {
13640 PyErr_SetString(PyExc_TypeError,
13641 "* wants int");
13642 goto onError;
13643 }
13644 prec = PyLong_AsLong(v);
13645 if (prec == -1 && PyErr_Occurred())
13646 goto onError;
13647 if (prec < 0)
13648 prec = 0;
13649 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013650 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013651 }
13652 else if (c >= '0' && c <= '9') {
13653 prec = c - '0';
13654 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013655 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013656 if (c < '0' || c > '9')
13657 break;
13658 if ((prec*10) / 10 != prec) {
13659 PyErr_SetString(PyExc_ValueError,
13660 "prec too big");
13661 goto onError;
13662 }
13663 prec = prec*10 + (c - '0');
13664 }
13665 }
13666 } /* prec */
13667 if (fmtcnt >= 0) {
13668 if (c == 'h' || c == 'l' || c == 'L') {
13669 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013670 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013671 }
13672 }
13673 if (fmtcnt < 0) {
13674 PyErr_SetString(PyExc_ValueError,
13675 "incomplete format");
13676 goto onError;
13677 }
13678 if (c != '%') {
13679 v = getnextarg(args, arglen, &argidx);
13680 if (v == NULL)
13681 goto onError;
13682 }
13683 sign = 0;
13684 fill = ' ';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013685 fillobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013686 switch (c) {
13687
13688 case '%':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013689 _PyAccu_Accumulate(&acc, percent);
13690 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +000013691
13692 case 's':
13693 case 'r':
13694 case 'a':
Victor Stinner808fc0a2010-03-22 12:50:40 +000013695 if (PyUnicode_CheckExact(v) && c == 's') {
Benjamin Peterson29060642009-01-31 22:14:21 +000013696 temp = v;
13697 Py_INCREF(temp);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013698 }
13699 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013700 if (c == 's')
13701 temp = PyObject_Str(v);
13702 else if (c == 'r')
13703 temp = PyObject_Repr(v);
13704 else
13705 temp = PyObject_ASCII(v);
13706 if (temp == NULL)
13707 goto onError;
13708 if (PyUnicode_Check(temp))
13709 /* nothing to do */;
13710 else {
13711 Py_DECREF(temp);
13712 PyErr_SetString(PyExc_TypeError,
13713 "%s argument has non-string str()");
13714 goto onError;
13715 }
13716 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013717 if (PyUnicode_READY(temp) == -1) {
13718 Py_CLEAR(temp);
13719 goto onError;
13720 }
13721 pbuf = PyUnicode_DATA(temp);
13722 kind = PyUnicode_KIND(temp);
13723 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013724 if (prec >= 0 && len > prec)
13725 len = prec;
13726 break;
13727
13728 case 'i':
13729 case 'd':
13730 case 'u':
13731 case 'o':
13732 case 'x':
13733 case 'X':
Benjamin Peterson29060642009-01-31 22:14:21 +000013734 isnumok = 0;
13735 if (PyNumber_Check(v)) {
13736 PyObject *iobj=NULL;
13737
13738 if (PyLong_Check(v)) {
13739 iobj = v;
13740 Py_INCREF(iobj);
13741 }
13742 else {
13743 iobj = PyNumber_Long(v);
13744 }
13745 if (iobj!=NULL) {
13746 if (PyLong_Check(iobj)) {
13747 isnumok = 1;
Senthil Kumaran9ebe08d2011-07-03 21:03:16 -070013748 temp = formatlong(iobj, flags, prec, (c == 'i'? 'd': c));
Benjamin Peterson29060642009-01-31 22:14:21 +000013749 Py_DECREF(iobj);
13750 if (!temp)
13751 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013752 if (PyUnicode_READY(temp) == -1) {
13753 Py_CLEAR(temp);
13754 goto onError;
13755 }
13756 pbuf = PyUnicode_DATA(temp);
13757 kind = PyUnicode_KIND(temp);
13758 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013759 sign = 1;
13760 }
13761 else {
13762 Py_DECREF(iobj);
13763 }
13764 }
13765 }
13766 if (!isnumok) {
13767 PyErr_Format(PyExc_TypeError,
13768 "%%%c format: a number is required, "
13769 "not %.200s", (char)c, Py_TYPE(v)->tp_name);
13770 goto onError;
13771 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013772 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013773 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013774 fillobj = zero;
13775 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013776 break;
13777
13778 case 'e':
13779 case 'E':
13780 case 'f':
13781 case 'F':
13782 case 'g':
13783 case 'G':
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013784 temp = formatfloat(v, flags, prec, c);
13785 if (!temp)
Benjamin Peterson29060642009-01-31 22:14:21 +000013786 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013787 if (PyUnicode_READY(temp) == -1) {
13788 Py_CLEAR(temp);
13789 goto onError;
13790 }
13791 pbuf = PyUnicode_DATA(temp);
13792 kind = PyUnicode_KIND(temp);
13793 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013794 sign = 1;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013795 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013796 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013797 fillobj = zero;
13798 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013799 break;
13800
13801 case 'c':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013802 {
13803 Py_UCS4 ch = formatchar(v);
13804 if (ch == (Py_UCS4) -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013805 goto onError;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013806 temp = _PyUnicode_FromUCS4(&ch, 1);
13807 if (temp == NULL)
13808 goto onError;
13809 pbuf = PyUnicode_DATA(temp);
13810 kind = PyUnicode_KIND(temp);
13811 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013812 break;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013813 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013814
13815 default:
13816 PyErr_Format(PyExc_ValueError,
13817 "unsupported format character '%c' (0x%x) "
13818 "at index %zd",
13819 (31<=c && c<=126) ? (char)c : '?',
13820 (int)c,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013821 fmtpos - 1);
Benjamin Peterson29060642009-01-31 22:14:21 +000013822 goto onError;
13823 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013824 /* pbuf is initialized here. */
13825 pindex = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +000013826 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013827 if (PyUnicode_READ(kind, pbuf, pindex) == '-') {
13828 signobj = minus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013829 len--;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013830 pindex++;
13831 }
13832 else if (PyUnicode_READ(kind, pbuf, pindex) == '+') {
13833 signobj = plus;
13834 len--;
13835 pindex++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013836 }
13837 else if (flags & F_SIGN)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013838 signobj = plus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013839 else if (flags & F_BLANK)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013840 signobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013841 else
13842 sign = 0;
13843 }
13844 if (width < len)
13845 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013846 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013847 if (fill != ' ') {
13848 assert(signobj != NULL);
13849 if (_PyAccu_Accumulate(&acc, signobj))
13850 goto onError;
13851 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013852 if (width > len)
13853 width--;
13854 }
13855 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013856 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013857 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == c);
Benjamin Peterson29060642009-01-31 22:14:21 +000013858 if (fill != ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013859 second = get_latin1_char(
13860 PyUnicode_READ(kind, pbuf, pindex + 1));
13861 pindex += 2;
13862 if (second == NULL ||
13863 _PyAccu_Accumulate(&acc, zero) ||
13864 _PyAccu_Accumulate(&acc, second))
13865 goto onError;
13866 Py_CLEAR(second);
Benjamin Peterson29060642009-01-31 22:14:21 +000013867 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013868 width -= 2;
13869 if (width < 0)
13870 width = 0;
13871 len -= 2;
13872 }
13873 if (width > len && !(flags & F_LJUST)) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013874 assert(fillobj != NULL);
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013875 if (repeat_accumulate(&acc, fillobj, width - len))
13876 goto onError;
13877 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013878 }
13879 if (fill == ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013880 if (sign) {
13881 assert(signobj != NULL);
13882 if (_PyAccu_Accumulate(&acc, signobj))
13883 goto onError;
13884 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013885 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013886 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
13887 assert(PyUnicode_READ(kind, pbuf, pindex+1) == c);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013888 second = get_latin1_char(
13889 PyUnicode_READ(kind, pbuf, pindex + 1));
13890 pindex += 2;
13891 if (second == NULL ||
13892 _PyAccu_Accumulate(&acc, zero) ||
13893 _PyAccu_Accumulate(&acc, second))
13894 goto onError;
13895 Py_CLEAR(second);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013896 }
13897 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013898 /* Copy all characters, preserving len */
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013899 if (temp != NULL) {
13900 assert(pbuf == PyUnicode_DATA(temp));
13901 v = PyUnicode_Substring(temp, pindex, pindex + len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013902 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013903 else {
13904 const char *p = (const char *) pbuf;
13905 assert(pbuf != NULL);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013906 p += kind * pindex;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013907 v = PyUnicode_FromKindAndData(kind, p, len);
13908 }
13909 if (v == NULL)
13910 goto onError;
13911 r = _PyAccu_Accumulate(&acc, v);
13912 Py_DECREF(v);
13913 if (r)
13914 goto onError;
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013915 if (width > len && repeat_accumulate(&acc, blank, width - len))
13916 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013917 if (dict && (argidx < arglen) && c != '%') {
13918 PyErr_SetString(PyExc_TypeError,
13919 "not all arguments converted during string formatting");
Benjamin Peterson29060642009-01-31 22:14:21 +000013920 goto onError;
13921 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013922 Py_CLEAR(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013923 } /* '%' */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013924 } /* until end */
13925 if (argidx < arglen && !dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013926 PyErr_SetString(PyExc_TypeError,
13927 "not all arguments converted during string formatting");
13928 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013929 }
13930
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013931 result = _PyAccu_Finish(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013932 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013933 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013934 }
13935 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013936 Py_XDECREF(temp);
13937 Py_XDECREF(second);
Victor Stinner7931d9a2011-11-04 00:22:48 +010013938 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013939
Benjamin Peterson29060642009-01-31 22:14:21 +000013940 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013941 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013942 Py_XDECREF(temp);
13943 Py_XDECREF(second);
13944 _PyAccu_Destroy(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013945 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013946 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013947 }
13948 return NULL;
13949}
13950
Jeremy Hylton938ace62002-07-17 16:30:39 +000013951static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000013952unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
13953
Tim Peters6d6c1a32001-08-02 04:15:00 +000013954static PyObject *
13955unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13956{
Benjamin Peterson29060642009-01-31 22:14:21 +000013957 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013958 static char *kwlist[] = {"object", "encoding", "errors", 0};
13959 char *encoding = NULL;
13960 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000013961
Benjamin Peterson14339b62009-01-31 16:36:08 +000013962 if (type != &PyUnicode_Type)
13963 return unicode_subtype_new(type, args, kwds);
13964 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000013965 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000013966 return NULL;
Victor Stinner382955f2011-12-11 21:44:00 +010013967 if (x == NULL) {
13968 Py_INCREF(unicode_empty);
13969 return unicode_empty;
13970 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000013971 if (encoding == NULL && errors == NULL)
13972 return PyObject_Str(x);
13973 else
Benjamin Peterson29060642009-01-31 22:14:21 +000013974 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000013975}
13976
Guido van Rossume023fe02001-08-30 03:12:59 +000013977static PyObject *
13978unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13979{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013980 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013981 Py_ssize_t length, char_size;
13982 int share_wstr, share_utf8;
13983 unsigned int kind;
13984 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000013985
Benjamin Peterson14339b62009-01-31 16:36:08 +000013986 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013987
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013988 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013989 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013990 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020013991 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050013992 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060013993 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013994 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060013995 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013996
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013997 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013998 if (self == NULL) {
13999 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014000 return NULL;
14001 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014002 kind = PyUnicode_KIND(unicode);
14003 length = PyUnicode_GET_LENGTH(unicode);
14004
14005 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014006#ifdef Py_DEBUG
14007 _PyUnicode_HASH(self) = -1;
14008#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014009 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014010#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014011 _PyUnicode_STATE(self).interned = 0;
14012 _PyUnicode_STATE(self).kind = kind;
14013 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020014014 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014015 _PyUnicode_STATE(self).ready = 1;
14016 _PyUnicode_WSTR(self) = NULL;
14017 _PyUnicode_UTF8_LENGTH(self) = 0;
14018 _PyUnicode_UTF8(self) = NULL;
14019 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020014020 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014021
14022 share_utf8 = 0;
14023 share_wstr = 0;
14024 if (kind == PyUnicode_1BYTE_KIND) {
14025 char_size = 1;
14026 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
14027 share_utf8 = 1;
14028 }
14029 else if (kind == PyUnicode_2BYTE_KIND) {
14030 char_size = 2;
14031 if (sizeof(wchar_t) == 2)
14032 share_wstr = 1;
14033 }
14034 else {
14035 assert(kind == PyUnicode_4BYTE_KIND);
14036 char_size = 4;
14037 if (sizeof(wchar_t) == 4)
14038 share_wstr = 1;
14039 }
14040
14041 /* Ensure we won't overflow the length. */
14042 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
14043 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014044 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014045 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014046 data = PyObject_MALLOC((length + 1) * char_size);
14047 if (data == NULL) {
14048 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014049 goto onError;
14050 }
14051
Victor Stinnerc3c74152011-10-02 20:39:55 +020014052 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014053 if (share_utf8) {
14054 _PyUnicode_UTF8_LENGTH(self) = length;
14055 _PyUnicode_UTF8(self) = data;
14056 }
14057 if (share_wstr) {
14058 _PyUnicode_WSTR_LENGTH(self) = length;
14059 _PyUnicode_WSTR(self) = (wchar_t *)data;
14060 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014061
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014062 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020014063 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020014064 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014065#ifdef Py_DEBUG
14066 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
14067#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020014068 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010014069 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014070
14071onError:
14072 Py_DECREF(unicode);
14073 Py_DECREF(self);
14074 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000014075}
14076
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000014077PyDoc_STRVAR(unicode_doc,
Benjamin Peterson29060642009-01-31 22:14:21 +000014078 "str(string[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000014079\n\
Collin Winterd474ce82007-08-07 19:42:11 +000014080Create a new string object from the given encoded string.\n\
Skip Montanaro35b37a52002-07-26 16:22:46 +000014081encoding defaults to the current default string encoding.\n\
14082errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000014083
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014084static PyObject *unicode_iter(PyObject *seq);
14085
Guido van Rossumd57fd912000-03-10 22:53:23 +000014086PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000014087 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014088 "str", /* tp_name */
14089 sizeof(PyUnicodeObject), /* tp_size */
14090 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014091 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014092 (destructor)unicode_dealloc, /* tp_dealloc */
14093 0, /* tp_print */
14094 0, /* tp_getattr */
14095 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014096 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014097 unicode_repr, /* tp_repr */
14098 &unicode_as_number, /* tp_as_number */
14099 &unicode_as_sequence, /* tp_as_sequence */
14100 &unicode_as_mapping, /* tp_as_mapping */
14101 (hashfunc) unicode_hash, /* tp_hash*/
14102 0, /* tp_call*/
14103 (reprfunc) unicode_str, /* tp_str */
14104 PyObject_GenericGetAttr, /* tp_getattro */
14105 0, /* tp_setattro */
14106 0, /* tp_as_buffer */
14107 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000014108 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014109 unicode_doc, /* tp_doc */
14110 0, /* tp_traverse */
14111 0, /* tp_clear */
14112 PyUnicode_RichCompare, /* tp_richcompare */
14113 0, /* tp_weaklistoffset */
14114 unicode_iter, /* tp_iter */
14115 0, /* tp_iternext */
14116 unicode_methods, /* tp_methods */
14117 0, /* tp_members */
14118 0, /* tp_getset */
14119 &PyBaseObject_Type, /* tp_base */
14120 0, /* tp_dict */
14121 0, /* tp_descr_get */
14122 0, /* tp_descr_set */
14123 0, /* tp_dictoffset */
14124 0, /* tp_init */
14125 0, /* tp_alloc */
14126 unicode_new, /* tp_new */
14127 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014128};
14129
14130/* Initialize the Unicode implementation */
14131
Victor Stinner3a50e702011-10-18 21:21:00 +020014132int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014133{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014134 int i;
14135
Thomas Wouters477c8d52006-05-27 19:21:47 +000014136 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014137 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000014138 0x000A, /* LINE FEED */
14139 0x000D, /* CARRIAGE RETURN */
14140 0x001C, /* FILE SEPARATOR */
14141 0x001D, /* GROUP SEPARATOR */
14142 0x001E, /* RECORD SEPARATOR */
14143 0x0085, /* NEXT LINE */
14144 0x2028, /* LINE SEPARATOR */
14145 0x2029, /* PARAGRAPH SEPARATOR */
14146 };
14147
Fred Drakee4315f52000-05-09 19:53:39 +000014148 /* Init the implementation */
Victor Stinnera464fc12011-10-02 20:39:30 +020014149 unicode_empty = PyUnicode_New(0, 0);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014150 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014151 Py_FatalError("Can't create empty string");
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010014152 assert(_PyUnicode_CheckConsistency(unicode_empty, 1));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014153
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014154 for (i = 0; i < 256; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +000014155 unicode_latin1[i] = NULL;
Guido van Rossumcacfc072002-05-24 19:01:59 +000014156 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014157 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000014158
14159 /* initialize the linebreak bloom filter */
14160 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014161 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020014162 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014163
14164 PyType_Ready(&EncodingMapType);
Victor Stinner3a50e702011-10-18 21:21:00 +020014165
14166#ifdef HAVE_MBCS
14167 winver.dwOSVersionInfoSize = sizeof(winver);
14168 if (!GetVersionEx((OSVERSIONINFO*)&winver)) {
14169 PyErr_SetFromWindowsErr(0);
14170 return -1;
14171 }
14172#endif
14173 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014174}
14175
14176/* Finalize the Unicode implementation */
14177
Christian Heimesa156e092008-02-16 07:38:31 +000014178int
14179PyUnicode_ClearFreeList(void)
14180{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014181 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000014182}
14183
Guido van Rossumd57fd912000-03-10 22:53:23 +000014184void
Thomas Wouters78890102000-07-22 19:25:51 +000014185_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014186{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014187 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014188
Guido van Rossum4ae8ef82000-10-03 18:09:04 +000014189 Py_XDECREF(unicode_empty);
14190 unicode_empty = NULL;
Barry Warsaw5b4c2282000-10-03 20:45:26 +000014191
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014192 for (i = 0; i < 256; i++) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014193 if (unicode_latin1[i]) {
14194 Py_DECREF(unicode_latin1[i]);
14195 unicode_latin1[i] = NULL;
14196 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014197 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020014198 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000014199 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000014200}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000014201
Walter Dörwald16807132007-05-25 13:52:07 +000014202void
14203PyUnicode_InternInPlace(PyObject **p)
14204{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014205 register PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014206 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020014207#ifdef Py_DEBUG
14208 assert(s != NULL);
14209 assert(_PyUnicode_CHECK(s));
14210#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000014211 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020014212 return;
14213#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000014214 /* If it's a subclass, we don't really know what putting
14215 it in the interned dict might do. */
14216 if (!PyUnicode_CheckExact(s))
14217 return;
14218 if (PyUnicode_CHECK_INTERNED(s))
14219 return;
14220 if (interned == NULL) {
14221 interned = PyDict_New();
14222 if (interned == NULL) {
14223 PyErr_Clear(); /* Don't leave an exception */
14224 return;
14225 }
14226 }
14227 /* It might be that the GetItem call fails even
14228 though the key is present in the dictionary,
14229 namely when this happens during a stack overflow. */
14230 Py_ALLOW_RECURSION
Victor Stinner7931d9a2011-11-04 00:22:48 +010014231 t = PyDict_GetItem(interned, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014232 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000014233
Benjamin Peterson29060642009-01-31 22:14:21 +000014234 if (t) {
14235 Py_INCREF(t);
14236 Py_DECREF(*p);
14237 *p = t;
14238 return;
14239 }
Walter Dörwald16807132007-05-25 13:52:07 +000014240
Benjamin Peterson14339b62009-01-31 16:36:08 +000014241 PyThreadState_GET()->recursion_critical = 1;
Victor Stinner7931d9a2011-11-04 00:22:48 +010014242 if (PyDict_SetItem(interned, s, s) < 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014243 PyErr_Clear();
14244 PyThreadState_GET()->recursion_critical = 0;
14245 return;
14246 }
14247 PyThreadState_GET()->recursion_critical = 0;
14248 /* The two references in interned are not counted by refcnt.
14249 The deallocator will take care of this */
14250 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014251 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000014252}
14253
14254void
14255PyUnicode_InternImmortal(PyObject **p)
14256{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014257 PyUnicode_InternInPlace(p);
14258 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020014259 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014260 Py_INCREF(*p);
14261 }
Walter Dörwald16807132007-05-25 13:52:07 +000014262}
14263
14264PyObject *
14265PyUnicode_InternFromString(const char *cp)
14266{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014267 PyObject *s = PyUnicode_FromString(cp);
14268 if (s == NULL)
14269 return NULL;
14270 PyUnicode_InternInPlace(&s);
14271 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000014272}
14273
Alexander Belopolsky40018472011-02-26 01:02:56 +000014274void
14275_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000014276{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014277 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014278 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014279 Py_ssize_t i, n;
14280 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000014281
Benjamin Peterson14339b62009-01-31 16:36:08 +000014282 if (interned == NULL || !PyDict_Check(interned))
14283 return;
14284 keys = PyDict_Keys(interned);
14285 if (keys == NULL || !PyList_Check(keys)) {
14286 PyErr_Clear();
14287 return;
14288 }
Walter Dörwald16807132007-05-25 13:52:07 +000014289
Benjamin Peterson14339b62009-01-31 16:36:08 +000014290 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
14291 detector, interned unicode strings are not forcibly deallocated;
14292 rather, we give them their stolen references back, and then clear
14293 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000014294
Benjamin Peterson14339b62009-01-31 16:36:08 +000014295 n = PyList_GET_SIZE(keys);
14296 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000014297 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014298 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014299 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014300 if (PyUnicode_READY(s) == -1) {
14301 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014302 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014303 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014304 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014305 case SSTATE_NOT_INTERNED:
14306 /* XXX Shouldn't happen */
14307 break;
14308 case SSTATE_INTERNED_IMMORTAL:
14309 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014310 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014311 break;
14312 case SSTATE_INTERNED_MORTAL:
14313 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014314 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014315 break;
14316 default:
14317 Py_FatalError("Inconsistent interned string state.");
14318 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014319 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014320 }
14321 fprintf(stderr, "total size of all interned strings: "
14322 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
14323 "mortal/immortal\n", mortal_size, immortal_size);
14324 Py_DECREF(keys);
14325 PyDict_Clear(interned);
14326 Py_DECREF(interned);
14327 interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +000014328}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014329
14330
14331/********************* Unicode Iterator **************************/
14332
14333typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014334 PyObject_HEAD
14335 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014336 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014337} unicodeiterobject;
14338
14339static void
14340unicodeiter_dealloc(unicodeiterobject *it)
14341{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014342 _PyObject_GC_UNTRACK(it);
14343 Py_XDECREF(it->it_seq);
14344 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014345}
14346
14347static int
14348unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
14349{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014350 Py_VISIT(it->it_seq);
14351 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014352}
14353
14354static PyObject *
14355unicodeiter_next(unicodeiterobject *it)
14356{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014357 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014358
Benjamin Peterson14339b62009-01-31 16:36:08 +000014359 assert(it != NULL);
14360 seq = it->it_seq;
14361 if (seq == NULL)
14362 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014363 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014364
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014365 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
14366 int kind = PyUnicode_KIND(seq);
14367 void *data = PyUnicode_DATA(seq);
14368 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
14369 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014370 if (item != NULL)
14371 ++it->it_index;
14372 return item;
14373 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014374
Benjamin Peterson14339b62009-01-31 16:36:08 +000014375 Py_DECREF(seq);
14376 it->it_seq = NULL;
14377 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014378}
14379
14380static PyObject *
14381unicodeiter_len(unicodeiterobject *it)
14382{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014383 Py_ssize_t len = 0;
14384 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020014385 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014386 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014387}
14388
14389PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
14390
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014391static PyObject *
14392unicodeiter_reduce(unicodeiterobject *it)
14393{
14394 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +020014395 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014396 it->it_seq, it->it_index);
14397 } else {
14398 PyObject *u = PyUnicode_FromUnicode(NULL, 0);
14399 if (u == NULL)
14400 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +020014401 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014402 }
14403}
14404
14405PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
14406
14407static PyObject *
14408unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
14409{
14410 Py_ssize_t index = PyLong_AsSsize_t(state);
14411 if (index == -1 && PyErr_Occurred())
14412 return NULL;
14413 if (index < 0)
14414 index = 0;
14415 it->it_index = index;
14416 Py_RETURN_NONE;
14417}
14418
14419PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
14420
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014421static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014422 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000014423 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000014424 {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
14425 reduce_doc},
14426 {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
14427 setstate_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000014428 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014429};
14430
14431PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014432 PyVarObject_HEAD_INIT(&PyType_Type, 0)
14433 "str_iterator", /* tp_name */
14434 sizeof(unicodeiterobject), /* tp_basicsize */
14435 0, /* tp_itemsize */
14436 /* methods */
14437 (destructor)unicodeiter_dealloc, /* tp_dealloc */
14438 0, /* tp_print */
14439 0, /* tp_getattr */
14440 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014441 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014442 0, /* tp_repr */
14443 0, /* tp_as_number */
14444 0, /* tp_as_sequence */
14445 0, /* tp_as_mapping */
14446 0, /* tp_hash */
14447 0, /* tp_call */
14448 0, /* tp_str */
14449 PyObject_GenericGetAttr, /* tp_getattro */
14450 0, /* tp_setattro */
14451 0, /* tp_as_buffer */
14452 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
14453 0, /* tp_doc */
14454 (traverseproc)unicodeiter_traverse, /* tp_traverse */
14455 0, /* tp_clear */
14456 0, /* tp_richcompare */
14457 0, /* tp_weaklistoffset */
14458 PyObject_SelfIter, /* tp_iter */
14459 (iternextfunc)unicodeiter_next, /* tp_iternext */
14460 unicodeiter_methods, /* tp_methods */
14461 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014462};
14463
14464static PyObject *
14465unicode_iter(PyObject *seq)
14466{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014467 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014468
Benjamin Peterson14339b62009-01-31 16:36:08 +000014469 if (!PyUnicode_Check(seq)) {
14470 PyErr_BadInternalCall();
14471 return NULL;
14472 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014473 if (PyUnicode_READY(seq) == -1)
14474 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014475 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
14476 if (it == NULL)
14477 return NULL;
14478 it->it_index = 0;
14479 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014480 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014481 _PyObject_GC_TRACK(it);
14482 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014483}
14484
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010014485
14486size_t
14487Py_UNICODE_strlen(const Py_UNICODE *u)
14488{
14489 int res = 0;
14490 while(*u++)
14491 res++;
14492 return res;
14493}
14494
14495Py_UNICODE*
14496Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
14497{
14498 Py_UNICODE *u = s1;
14499 while ((*u++ = *s2++));
14500 return s1;
14501}
14502
14503Py_UNICODE*
14504Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14505{
14506 Py_UNICODE *u = s1;
14507 while ((*u++ = *s2++))
14508 if (n-- == 0)
14509 break;
14510 return s1;
14511}
14512
14513Py_UNICODE*
14514Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
14515{
14516 Py_UNICODE *u1 = s1;
14517 u1 += Py_UNICODE_strlen(u1);
14518 Py_UNICODE_strcpy(u1, s2);
14519 return s1;
14520}
14521
14522int
14523Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
14524{
14525 while (*s1 && *s2 && *s1 == *s2)
14526 s1++, s2++;
14527 if (*s1 && *s2)
14528 return (*s1 < *s2) ? -1 : +1;
14529 if (*s1)
14530 return 1;
14531 if (*s2)
14532 return -1;
14533 return 0;
14534}
14535
14536int
14537Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14538{
14539 register Py_UNICODE u1, u2;
14540 for (; n != 0; n--) {
14541 u1 = *s1;
14542 u2 = *s2;
14543 if (u1 != u2)
14544 return (u1 < u2) ? -1 : +1;
14545 if (u1 == '\0')
14546 return 0;
14547 s1++;
14548 s2++;
14549 }
14550 return 0;
14551}
14552
14553Py_UNICODE*
14554Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
14555{
14556 const Py_UNICODE *p;
14557 for (p = s; *p; p++)
14558 if (*p == c)
14559 return (Py_UNICODE*)p;
14560 return NULL;
14561}
14562
14563Py_UNICODE*
14564Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
14565{
14566 const Py_UNICODE *p;
14567 p = s + Py_UNICODE_strlen(s);
14568 while (p != s) {
14569 p--;
14570 if (*p == c)
14571 return (Py_UNICODE*)p;
14572 }
14573 return NULL;
14574}
Victor Stinner331ea922010-08-10 16:37:20 +000014575
Victor Stinner71133ff2010-09-01 23:43:53 +000014576Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014577PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000014578{
Victor Stinner577db2c2011-10-11 22:12:48 +020014579 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014580 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000014581
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014582 if (!PyUnicode_Check(unicode)) {
14583 PyErr_BadArgument();
14584 return NULL;
14585 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014586 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020014587 if (u == NULL)
14588 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000014589 /* Ensure we won't overflow the size. */
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014590 if (len > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000014591 PyErr_NoMemory();
14592 return NULL;
14593 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014594 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000014595 size *= sizeof(Py_UNICODE);
14596 copy = PyMem_Malloc(size);
14597 if (copy == NULL) {
14598 PyErr_NoMemory();
14599 return NULL;
14600 }
Victor Stinner577db2c2011-10-11 22:12:48 +020014601 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000014602 return copy;
14603}
Martin v. Löwis5b222132007-06-10 09:51:05 +000014604
Georg Brandl66c221e2010-10-14 07:04:07 +000014605/* A _string module, to export formatter_parser and formatter_field_name_split
14606 to the string.Formatter class implemented in Python. */
14607
14608static PyMethodDef _string_methods[] = {
14609 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
14610 METH_O, PyDoc_STR("split the argument as a field name")},
14611 {"formatter_parser", (PyCFunction) formatter_parser,
14612 METH_O, PyDoc_STR("parse the argument as a format string")},
14613 {NULL, NULL}
14614};
14615
14616static struct PyModuleDef _string_module = {
14617 PyModuleDef_HEAD_INIT,
14618 "_string",
14619 PyDoc_STR("string helper module"),
14620 0,
14621 _string_methods,
14622 NULL,
14623 NULL,
14624 NULL,
14625 NULL
14626};
14627
14628PyMODINIT_FUNC
14629PyInit__string(void)
14630{
14631 return PyModule_Create(&_string_module);
14632}
14633
14634
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014635#ifdef __cplusplus
14636}
14637#endif