blob: d73145b458406de15fff39c2079730e976127cfb [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 Stinner15e9ed22012-02-22 13:36:20 +01001001 assert(maxchar <= MAX_UNICODE);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001002 kind_state = PyUnicode_4BYTE_KIND;
1003 char_size = 4;
1004 if (sizeof(wchar_t) == 4)
1005 is_sharing = 1;
1006 }
1007
1008 /* Ensure we won't overflow the size. */
1009 if (size < 0) {
1010 PyErr_SetString(PyExc_SystemError,
1011 "Negative size passed to PyUnicode_New");
1012 return NULL;
1013 }
1014 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
1015 return PyErr_NoMemory();
1016
1017 /* Duplicated allocation code from _PyObject_New() instead of a call to
1018 * PyObject_New() so we are able to allocate space for the object and
1019 * it's data buffer.
1020 */
1021 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
1022 if (obj == NULL)
1023 return PyErr_NoMemory();
1024 obj = PyObject_INIT(obj, &PyUnicode_Type);
1025 if (obj == NULL)
1026 return NULL;
1027
1028 unicode = (PyCompactUnicodeObject *)obj;
1029 if (is_ascii)
1030 data = ((PyASCIIObject*)obj) + 1;
1031 else
1032 data = unicode + 1;
1033 _PyUnicode_LENGTH(unicode) = size;
1034 _PyUnicode_HASH(unicode) = -1;
1035 _PyUnicode_STATE(unicode).interned = 0;
1036 _PyUnicode_STATE(unicode).kind = kind_state;
1037 _PyUnicode_STATE(unicode).compact = 1;
1038 _PyUnicode_STATE(unicode).ready = 1;
1039 _PyUnicode_STATE(unicode).ascii = is_ascii;
1040 if (is_ascii) {
1041 ((char*)data)[size] = 0;
1042 _PyUnicode_WSTR(unicode) = NULL;
1043 }
1044 else if (kind_state == PyUnicode_1BYTE_KIND) {
1045 ((char*)data)[size] = 0;
1046 _PyUnicode_WSTR(unicode) = NULL;
1047 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001048 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001049 unicode->utf8_length = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001050 }
1051 else {
1052 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 if (kind_state == PyUnicode_2BYTE_KIND)
1055 ((Py_UCS2*)data)[size] = 0;
1056 else /* kind_state == PyUnicode_4BYTE_KIND */
1057 ((Py_UCS4*)data)[size] = 0;
1058 if (is_sharing) {
1059 _PyUnicode_WSTR_LENGTH(unicode) = size;
1060 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
1061 }
1062 else {
1063 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1064 _PyUnicode_WSTR(unicode) = NULL;
1065 }
1066 }
Victor Stinner7931d9a2011-11-04 00:22:48 +01001067 assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001068 return obj;
1069}
1070
1071#if SIZEOF_WCHAR_T == 2
1072/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
1073 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +02001074 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001075
1076 This function assumes that unicode can hold one more code point than wstr
1077 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001078static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001079unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001080 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001081{
1082 const wchar_t *iter;
1083 Py_UCS4 *ucs4_out;
1084
Victor Stinner910337b2011-10-03 03:20:16 +02001085 assert(unicode != NULL);
1086 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001087 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1088 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
1089
1090 for (iter = begin; iter < end; ) {
1091 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1092 _PyUnicode_GET_LENGTH(unicode)));
Victor Stinner551ac952011-11-29 22:58:13 +01001093 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1094 && (iter+1) < end
1095 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001096 {
Victor Stinner551ac952011-11-29 22:58:13 +01001097 *ucs4_out++ = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001098 iter += 2;
1099 }
1100 else {
1101 *ucs4_out++ = *iter;
1102 iter++;
1103 }
1104 }
1105 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1106 _PyUnicode_GET_LENGTH(unicode)));
1107
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001108}
1109#endif
1110
Victor Stinnercd9950f2011-10-02 00:34:53 +02001111static int
Victor Stinner488fa492011-12-12 00:01:39 +01001112unicode_check_modifiable(PyObject *unicode)
Victor Stinnercd9950f2011-10-02 00:34:53 +02001113{
Victor Stinner488fa492011-12-12 00:01:39 +01001114 if (!unicode_modifiable(unicode)) {
Victor Stinner01698042011-10-04 00:04:26 +02001115 PyErr_SetString(PyExc_SystemError,
Victor Stinner488fa492011-12-12 00:01:39 +01001116 "Cannot modify a string currently used");
Victor Stinnercd9950f2011-10-02 00:34:53 +02001117 return -1;
1118 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02001119 return 0;
1120}
1121
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001122static int
1123_copy_characters(PyObject *to, Py_ssize_t to_start,
1124 PyObject *from, Py_ssize_t from_start,
1125 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001126{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001127 unsigned int from_kind, to_kind;
1128 void *from_data, *to_data;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001129 int fast;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001130
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001131 assert(PyUnicode_Check(from));
1132 assert(PyUnicode_Check(to));
1133 assert(PyUnicode_IS_READY(from));
1134 assert(PyUnicode_IS_READY(to));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001135
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001136 assert(PyUnicode_GET_LENGTH(from) >= how_many);
1137 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1138 assert(0 <= how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001139
Victor Stinnerf5ca1a22011-09-28 23:54:59 +02001140 if (how_many == 0)
1141 return 0;
1142
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001143 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001144 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001145 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001146 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001147
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001148#ifdef Py_DEBUG
1149 if (!check_maxchar
1150 && (from_kind > to_kind
1151 || (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001152 {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001153 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1154 Py_UCS4 ch;
1155 Py_ssize_t i;
1156 for (i=0; i < how_many; i++) {
1157 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1158 assert(ch <= to_maxchar);
1159 }
1160 }
1161#endif
1162 fast = (from_kind == to_kind);
1163 if (check_maxchar
1164 && (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to)))
1165 {
1166 /* deny latin1 => ascii */
1167 fast = 0;
1168 }
1169
1170 if (fast) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001171 Py_MEMCPY((char*)to_data + to_kind * to_start,
1172 (char*)from_data + from_kind * from_start,
1173 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001174 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001175 else if (from_kind == PyUnicode_1BYTE_KIND
1176 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001177 {
1178 _PyUnicode_CONVERT_BYTES(
1179 Py_UCS1, Py_UCS2,
1180 PyUnicode_1BYTE_DATA(from) + from_start,
1181 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1182 PyUnicode_2BYTE_DATA(to) + to_start
1183 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001184 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001185 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001186 && to_kind == PyUnicode_4BYTE_KIND)
1187 {
1188 _PyUnicode_CONVERT_BYTES(
1189 Py_UCS1, Py_UCS4,
1190 PyUnicode_1BYTE_DATA(from) + from_start,
1191 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1192 PyUnicode_4BYTE_DATA(to) + to_start
1193 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001194 }
1195 else if (from_kind == PyUnicode_2BYTE_KIND
1196 && to_kind == PyUnicode_4BYTE_KIND)
1197 {
1198 _PyUnicode_CONVERT_BYTES(
1199 Py_UCS2, Py_UCS4,
1200 PyUnicode_2BYTE_DATA(from) + from_start,
1201 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1202 PyUnicode_4BYTE_DATA(to) + to_start
1203 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001204 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001205 else {
Victor Stinnerf42dc442011-10-02 23:33:16 +02001206 /* check if max_char(from substring) <= max_char(to) */
1207 if (from_kind > to_kind
1208 /* latin1 => ascii */
Victor Stinnerb9275c12011-10-05 14:01:42 +02001209 || (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to)))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001210 {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001211 /* slow path to check for character overflow */
1212 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001213 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001214 Py_ssize_t i;
1215
Victor Stinner56c161a2011-10-06 02:47:11 +02001216#ifdef Py_DEBUG
Victor Stinnera0702ab2011-09-29 14:14:38 +02001217 for (i=0; i < how_many; i++) {
1218 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinner56c161a2011-10-06 02:47:11 +02001219 assert(ch <= to_maxchar);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001220 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1221 }
Victor Stinner56c161a2011-10-06 02:47:11 +02001222#else
1223 if (!check_maxchar) {
1224 for (i=0; i < how_many; i++) {
1225 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1226 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1227 }
1228 }
1229 else {
1230 for (i=0; i < how_many; i++) {
1231 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1232 if (ch > to_maxchar)
1233 return 1;
1234 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1235 }
1236 }
1237#endif
Victor Stinnera0702ab2011-09-29 14:14:38 +02001238 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001239 else {
Victor Stinner56c161a2011-10-06 02:47:11 +02001240 assert(0 && "inconsistent state");
1241 return 1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001242 }
1243 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001244 return 0;
1245}
1246
1247static void
1248copy_characters(PyObject *to, Py_ssize_t to_start,
1249 PyObject *from, Py_ssize_t from_start,
1250 Py_ssize_t how_many)
1251{
1252 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1253}
1254
1255Py_ssize_t
1256PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1257 PyObject *from, Py_ssize_t from_start,
1258 Py_ssize_t how_many)
1259{
1260 int err;
1261
1262 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1263 PyErr_BadInternalCall();
1264 return -1;
1265 }
1266
Benjamin Petersonbac79492012-01-14 13:34:47 -05001267 if (PyUnicode_READY(from) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001268 return -1;
Benjamin Petersonbac79492012-01-14 13:34:47 -05001269 if (PyUnicode_READY(to) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001270 return -1;
1271
1272 how_many = Py_MIN(PyUnicode_GET_LENGTH(from), how_many);
1273 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1274 PyErr_Format(PyExc_SystemError,
1275 "Cannot write %zi characters at %zi "
1276 "in a string of %zi characters",
1277 how_many, to_start, PyUnicode_GET_LENGTH(to));
1278 return -1;
1279 }
1280
1281 if (how_many == 0)
1282 return 0;
1283
Victor Stinner488fa492011-12-12 00:01:39 +01001284 if (unicode_check_modifiable(to))
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001285 return -1;
1286
1287 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1288 if (err) {
1289 PyErr_Format(PyExc_SystemError,
1290 "Cannot copy %s characters "
1291 "into a string of %s characters",
1292 unicode_kind_name(from),
1293 unicode_kind_name(to));
1294 return -1;
1295 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001296 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001297}
1298
Victor Stinner17222162011-09-28 22:15:37 +02001299/* Find the maximum code point and count the number of surrogate pairs so a
1300 correct string length can be computed before converting a string to UCS4.
1301 This function counts single surrogates as a character and not as a pair.
1302
1303 Return 0 on success, or -1 on error. */
1304static int
1305find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1306 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001307{
1308 const wchar_t *iter;
Victor Stinner8faf8212011-12-08 22:14:11 +01001309 Py_UCS4 ch;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001310
Victor Stinnerc53be962011-10-02 21:33:54 +02001311 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001312 *num_surrogates = 0;
1313 *maxchar = 0;
1314
1315 for (iter = begin; iter < end; ) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001316#if SIZEOF_WCHAR_T == 2
Victor Stinnerca4f2072011-11-22 03:38:40 +01001317 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1318 && (iter+1) < end
1319 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001320 {
Victor Stinner8faf8212011-12-08 22:14:11 +01001321 ch = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001322 ++(*num_surrogates);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001323 iter += 2;
1324 }
1325 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001326#endif
Victor Stinner8faf8212011-12-08 22:14:11 +01001327 {
1328 ch = *iter;
1329 iter++;
1330 }
1331 if (ch > *maxchar) {
1332 *maxchar = ch;
1333 if (*maxchar > MAX_UNICODE) {
1334 PyErr_Format(PyExc_ValueError,
1335 "character U+%x is not in range [U+0000; U+10ffff]",
1336 ch);
1337 return -1;
1338 }
1339 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001340 }
1341 return 0;
1342}
1343
1344#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +02001345static int unicode_ready_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001346#endif
1347
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001348int
1349_PyUnicode_Ready(PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001350{
1351 wchar_t *end;
1352 Py_UCS4 maxchar = 0;
1353 Py_ssize_t num_surrogates;
1354#if SIZEOF_WCHAR_T == 2
1355 Py_ssize_t length_wo_surrogates;
1356#endif
1357
Georg Brandl7597add2011-10-05 16:36:47 +02001358 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001359 strings were created using _PyObject_New() and where no canonical
1360 representation (the str field) has been set yet aka strings
1361 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001362 assert(_PyUnicode_CHECK(unicode));
1363 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001364 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001365 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001366 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001367 /* Actually, it should neither be interned nor be anything else: */
1368 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001369
1370#ifdef Py_DEBUG
1371 ++unicode_ready_calls;
1372#endif
1373
1374 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001375 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001376 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001377 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001378
1379 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001380 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1381 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001382 PyErr_NoMemory();
1383 return -1;
1384 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001385 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001386 _PyUnicode_WSTR(unicode), end,
1387 PyUnicode_1BYTE_DATA(unicode));
1388 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1389 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1390 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1391 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001392 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001393 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001394 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001395 }
1396 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001397 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001398 _PyUnicode_UTF8(unicode) = NULL;
1399 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001400 }
1401 PyObject_FREE(_PyUnicode_WSTR(unicode));
1402 _PyUnicode_WSTR(unicode) = NULL;
1403 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1404 }
1405 /* In this case we might have to convert down from 4-byte native
1406 wchar_t to 2-byte unicode. */
1407 else if (maxchar < 65536) {
1408 assert(num_surrogates == 0 &&
1409 "FindMaxCharAndNumSurrogatePairs() messed up");
1410
Victor Stinner506f5922011-09-28 22:34:18 +02001411#if SIZEOF_WCHAR_T == 2
1412 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001413 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001414 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1415 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1416 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001417 _PyUnicode_UTF8(unicode) = NULL;
1418 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001419#else
1420 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001421 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001422 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001423 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001424 PyErr_NoMemory();
1425 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001426 }
Victor Stinner506f5922011-09-28 22:34:18 +02001427 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1428 _PyUnicode_WSTR(unicode), end,
1429 PyUnicode_2BYTE_DATA(unicode));
1430 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1431 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1432 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001433 _PyUnicode_UTF8(unicode) = NULL;
1434 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001435 PyObject_FREE(_PyUnicode_WSTR(unicode));
1436 _PyUnicode_WSTR(unicode) = NULL;
1437 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1438#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001439 }
1440 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1441 else {
1442#if SIZEOF_WCHAR_T == 2
1443 /* in case the native representation is 2-bytes, we need to allocate a
1444 new normalized 4-byte version. */
1445 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001446 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1447 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001448 PyErr_NoMemory();
1449 return -1;
1450 }
1451 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1452 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001453 _PyUnicode_UTF8(unicode) = NULL;
1454 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001455 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1456 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001457 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001458 PyObject_FREE(_PyUnicode_WSTR(unicode));
1459 _PyUnicode_WSTR(unicode) = NULL;
1460 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1461#else
1462 assert(num_surrogates == 0);
1463
Victor Stinnerc3c74152011-10-02 20:39:55 +02001464 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001465 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001466 _PyUnicode_UTF8(unicode) = NULL;
1467 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001468 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1469#endif
1470 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1471 }
1472 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001473 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001474 return 0;
1475}
1476
Alexander Belopolsky40018472011-02-26 01:02:56 +00001477static void
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001478unicode_dealloc(register PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001479{
Walter Dörwald16807132007-05-25 13:52:07 +00001480 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001481 case SSTATE_NOT_INTERNED:
1482 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001483
Benjamin Peterson29060642009-01-31 22:14:21 +00001484 case SSTATE_INTERNED_MORTAL:
1485 /* revive dead object temporarily for DelItem */
1486 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001487 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001488 Py_FatalError(
1489 "deletion of interned string failed");
1490 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001491
Benjamin Peterson29060642009-01-31 22:14:21 +00001492 case SSTATE_INTERNED_IMMORTAL:
1493 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001494
Benjamin Peterson29060642009-01-31 22:14:21 +00001495 default:
1496 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001497 }
1498
Victor Stinner03490912011-10-03 23:45:12 +02001499 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001500 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001501 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001502 PyObject_DEL(_PyUnicode_UTF8(unicode));
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001503 if (!PyUnicode_IS_COMPACT(unicode) && _PyUnicode_DATA_ANY(unicode))
1504 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001505
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001506 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001507}
1508
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001509#ifdef Py_DEBUG
1510static int
1511unicode_is_singleton(PyObject *unicode)
1512{
1513 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1514 if (unicode == unicode_empty)
1515 return 1;
1516 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1517 {
1518 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1519 if (ch < 256 && unicode_latin1[ch] == unicode)
1520 return 1;
1521 }
1522 return 0;
1523}
1524#endif
1525
Alexander Belopolsky40018472011-02-26 01:02:56 +00001526static int
Victor Stinner488fa492011-12-12 00:01:39 +01001527unicode_modifiable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001528{
Victor Stinner488fa492011-12-12 00:01:39 +01001529 assert(_PyUnicode_CHECK(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001530 if (Py_REFCNT(unicode) != 1)
1531 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001532 if (_PyUnicode_HASH(unicode) != -1)
1533 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001534 if (PyUnicode_CHECK_INTERNED(unicode))
1535 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001536 if (!PyUnicode_CheckExact(unicode))
1537 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001538#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001539 /* singleton refcount is greater than 1 */
1540 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001541#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001542 return 1;
1543}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001544
Victor Stinnerfe226c02011-10-03 03:52:20 +02001545static int
1546unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1547{
1548 PyObject *unicode;
1549 Py_ssize_t old_length;
1550
1551 assert(p_unicode != NULL);
1552 unicode = *p_unicode;
1553
1554 assert(unicode != NULL);
1555 assert(PyUnicode_Check(unicode));
1556 assert(0 <= length);
1557
Victor Stinner910337b2011-10-03 03:20:16 +02001558 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001559 old_length = PyUnicode_WSTR_LENGTH(unicode);
1560 else
1561 old_length = PyUnicode_GET_LENGTH(unicode);
1562 if (old_length == length)
1563 return 0;
1564
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001565 if (length == 0) {
1566 Py_DECREF(*p_unicode);
1567 *p_unicode = unicode_empty;
1568 Py_INCREF(*p_unicode);
1569 return 0;
1570 }
1571
Victor Stinner488fa492011-12-12 00:01:39 +01001572 if (!unicode_modifiable(unicode)) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001573 PyObject *copy = resize_copy(unicode, length);
1574 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001575 return -1;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001576 Py_DECREF(*p_unicode);
1577 *p_unicode = copy;
Benjamin Peterson29060642009-01-31 22:14:21 +00001578 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001579 }
1580
Victor Stinnerfe226c02011-10-03 03:52:20 +02001581 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001582 PyObject *new_unicode = resize_compact(unicode, length);
1583 if (new_unicode == NULL)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001584 return -1;
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001585 *p_unicode = new_unicode;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001586 assert(_PyUnicode_CheckConsistency(*p_unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001587 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001588 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001589 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001590}
1591
Alexander Belopolsky40018472011-02-26 01:02:56 +00001592int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001593PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001594{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001595 PyObject *unicode;
1596 if (p_unicode == NULL) {
1597 PyErr_BadInternalCall();
1598 return -1;
1599 }
1600 unicode = *p_unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001601 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001602 {
1603 PyErr_BadInternalCall();
1604 return -1;
1605 }
1606 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001607}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001608
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001609static int
Victor Stinner0a045ef2011-11-09 00:02:42 +01001610unicode_widen(PyObject **p_unicode, unsigned int maxchar)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001611{
1612 PyObject *result;
1613 assert(PyUnicode_IS_READY(*p_unicode));
1614 if (maxchar <= PyUnicode_MAX_CHAR_VALUE(*p_unicode))
1615 return 0;
1616 result = PyUnicode_New(PyUnicode_GET_LENGTH(*p_unicode),
1617 maxchar);
1618 if (result == NULL)
1619 return -1;
1620 PyUnicode_CopyCharacters(result, 0, *p_unicode, 0,
1621 PyUnicode_GET_LENGTH(*p_unicode));
1622 Py_DECREF(*p_unicode);
1623 *p_unicode = result;
1624 return 0;
1625}
1626
1627static int
1628unicode_putchar(PyObject **p_unicode, Py_ssize_t *pos,
1629 Py_UCS4 ch)
1630{
Victor Stinner15e9ed22012-02-22 13:36:20 +01001631 assert(ch <= MAX_UNICODE);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001632 if (unicode_widen(p_unicode, ch) < 0)
1633 return -1;
1634 PyUnicode_WRITE(PyUnicode_KIND(*p_unicode),
1635 PyUnicode_DATA(*p_unicode),
1636 (*pos)++, ch);
1637 return 0;
1638}
1639
Victor Stinnerc5166102012-02-22 13:55:02 +01001640/* Copy a ASCII or latin1 char* string into a Python Unicode string.
1641 Return the length of the input string.
1642
Victor Stinnerb429d3b2012-02-22 21:22:20 +01001643 WARNING: The function doesn't copy the terminating null character and
1644 doesn't check the maximum character (may write a latin1 character in an
1645 ASCII string). */
Victor Stinnerc5166102012-02-22 13:55:02 +01001646static Py_ssize_t
1647unicode_write_cstr(PyObject *unicode, Py_ssize_t index, const char *str)
1648{
1649 enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
1650 void *data = PyUnicode_DATA(unicode);
1651
1652 switch (kind) {
1653 case PyUnicode_1BYTE_KIND: {
1654 Py_ssize_t len = strlen(str);
1655 assert(index + len <= PyUnicode_GET_LENGTH(unicode));
Antoine Pitrouba6bafc2012-02-22 16:41:50 +01001656 memcpy((char *) data + index, str, len);
Victor Stinnerc5166102012-02-22 13:55:02 +01001657 return len;
1658 }
1659 case PyUnicode_2BYTE_KIND: {
1660 Py_UCS2 *start = (Py_UCS2 *)data + index;
1661 Py_UCS2 *ucs2 = start;
1662 assert(index <= PyUnicode_GET_LENGTH(unicode));
1663
1664 for (; *str; ++ucs2, ++str)
1665 *ucs2 = (Py_UCS2)*str;
1666
1667 assert((ucs2 - start) <= PyUnicode_GET_LENGTH(unicode));
1668 return ucs2 - start;
1669 }
1670 default: {
1671 Py_UCS4 *start = (Py_UCS4 *)data + index;
1672 Py_UCS4 *ucs4 = start;
1673 assert(kind == PyUnicode_4BYTE_KIND);
1674 assert(index <= PyUnicode_GET_LENGTH(unicode));
1675
1676 for (; *str; ++ucs4, ++str)
1677 *ucs4 = (Py_UCS4)*str;
1678
1679 assert((ucs4 - start) <= PyUnicode_GET_LENGTH(unicode));
1680 return ucs4 - start;
1681 }
1682 }
1683}
1684
1685
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001686static PyObject*
1687get_latin1_char(unsigned char ch)
1688{
Victor Stinnera464fc12011-10-02 20:39:30 +02001689 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001690 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001691 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001692 if (!unicode)
1693 return NULL;
1694 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001695 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001696 unicode_latin1[ch] = unicode;
1697 }
1698 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001699 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001700}
1701
Alexander Belopolsky40018472011-02-26 01:02:56 +00001702PyObject *
1703PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001704{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001705 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001706 Py_UCS4 maxchar = 0;
1707 Py_ssize_t num_surrogates;
1708
1709 if (u == NULL)
1710 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001711
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001712 /* If the Unicode data is known at construction time, we can apply
1713 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001714
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001715 /* Optimization for empty strings */
1716 if (size == 0 && unicode_empty != NULL) {
1717 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001718 return unicode_empty;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001719 }
Tim Petersced69f82003-09-16 20:30:58 +00001720
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001721 /* Single character Unicode objects in the Latin-1 range are
1722 shared when using this constructor */
1723 if (size == 1 && *u < 256)
1724 return get_latin1_char((unsigned char)*u);
1725
1726 /* If not empty and not single character, copy the Unicode data
1727 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02001728 if (find_maxchar_surrogates(u, u + size,
1729 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001730 return NULL;
1731
Victor Stinner8faf8212011-12-08 22:14:11 +01001732 unicode = PyUnicode_New(size - num_surrogates, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001733 if (!unicode)
1734 return NULL;
1735
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001736 switch (PyUnicode_KIND(unicode)) {
1737 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001738 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001739 u, u + size, PyUnicode_1BYTE_DATA(unicode));
1740 break;
1741 case PyUnicode_2BYTE_KIND:
1742#if Py_UNICODE_SIZE == 2
1743 Py_MEMCPY(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
1744#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001745 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001746 u, u + size, PyUnicode_2BYTE_DATA(unicode));
1747#endif
1748 break;
1749 case PyUnicode_4BYTE_KIND:
1750#if SIZEOF_WCHAR_T == 2
1751 /* This is the only case which has to process surrogates, thus
1752 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001753 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001754#else
1755 assert(num_surrogates == 0);
1756 Py_MEMCPY(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
1757#endif
1758 break;
1759 default:
1760 assert(0 && "Impossible state");
1761 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001762
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001763 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001764}
1765
Alexander Belopolsky40018472011-02-26 01:02:56 +00001766PyObject *
1767PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001768{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001769 if (size < 0) {
1770 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00001771 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00001772 return NULL;
1773 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001774 if (u != NULL)
1775 return PyUnicode_DecodeUTF8Stateful(u, size, NULL, NULL);
1776 else
1777 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001778}
1779
Alexander Belopolsky40018472011-02-26 01:02:56 +00001780PyObject *
1781PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00001782{
1783 size_t size = strlen(u);
1784 if (size > PY_SSIZE_T_MAX) {
1785 PyErr_SetString(PyExc_OverflowError, "input too long");
1786 return NULL;
1787 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001788 return PyUnicode_DecodeUTF8Stateful(u, (Py_ssize_t)size, NULL, NULL);
Walter Dörwaldd2034312007-05-18 16:29:38 +00001789}
1790
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001791PyObject *
1792_PyUnicode_FromId(_Py_Identifier *id)
1793{
1794 if (!id->object) {
Victor Stinnerd1cd99b2012-02-07 23:05:55 +01001795 id->object = PyUnicode_DecodeUTF8Stateful(id->string,
1796 strlen(id->string),
1797 NULL, NULL);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001798 if (!id->object)
1799 return NULL;
1800 PyUnicode_InternInPlace(&id->object);
1801 assert(!id->next);
1802 id->next = static_strings;
1803 static_strings = id;
1804 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001805 return id->object;
1806}
1807
1808void
1809_PyUnicode_ClearStaticStrings()
1810{
1811 _Py_Identifier *i;
1812 for (i = static_strings; i; i = i->next) {
1813 Py_DECREF(i->object);
1814 i->object = NULL;
1815 i->next = NULL;
1816 }
1817}
1818
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001819/* Internal function, don't check maximum character */
1820
Victor Stinnere57b1c02011-09-28 22:20:48 +02001821static PyObject*
Victor Stinner0617b6e2011-10-05 23:26:01 +02001822unicode_fromascii(const unsigned char* s, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02001823{
Victor Stinner785938e2011-12-11 20:09:03 +01001824 PyObject *unicode;
Victor Stinnere6b2d442011-12-11 21:54:30 +01001825 if (size == 1) {
Victor Stinner0617b6e2011-10-05 23:26:01 +02001826#ifdef Py_DEBUG
Victor Stinnere6b2d442011-12-11 21:54:30 +01001827 assert(s[0] < 128);
Victor Stinner0617b6e2011-10-05 23:26:01 +02001828#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001829 return get_latin1_char(s[0]);
Victor Stinnere6b2d442011-12-11 21:54:30 +01001830 }
Victor Stinner785938e2011-12-11 20:09:03 +01001831 unicode = PyUnicode_New(size, 127);
1832 if (!unicode)
Victor Stinner702c7342011-10-05 13:50:52 +02001833 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01001834 memcpy(PyUnicode_1BYTE_DATA(unicode), s, size);
1835 assert(_PyUnicode_CheckConsistency(unicode, 1));
1836 return unicode;
Victor Stinner702c7342011-10-05 13:50:52 +02001837}
1838
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001839static Py_UCS4
1840kind_maxchar_limit(unsigned int kind)
1841{
Benjamin Petersonead6b532011-12-20 17:23:42 -06001842 switch (kind) {
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001843 case PyUnicode_1BYTE_KIND:
1844 return 0x80;
1845 case PyUnicode_2BYTE_KIND:
1846 return 0x100;
1847 case PyUnicode_4BYTE_KIND:
1848 return 0x10000;
1849 default:
1850 assert(0 && "invalid kind");
Victor Stinner8faf8212011-12-08 22:14:11 +01001851 return MAX_UNICODE;
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001852 }
1853}
1854
Victor Stinner702c7342011-10-05 13:50:52 +02001855static PyObject*
Victor Stinnere57b1c02011-09-28 22:20:48 +02001856_PyUnicode_FromUCS1(const unsigned char* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00001857{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001858 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001859 unsigned char max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001860
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001861 if (size == 0) {
1862 Py_INCREF(unicode_empty);
1863 return unicode_empty;
1864 }
1865 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001866 if (size == 1)
1867 return get_latin1_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001868
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001869 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001870 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001871 if (!res)
1872 return NULL;
1873 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001874 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001875 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001876}
1877
Victor Stinnere57b1c02011-09-28 22:20:48 +02001878static PyObject*
1879_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001880{
1881 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001882 Py_UCS2 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001883
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001884 if (size == 0) {
1885 Py_INCREF(unicode_empty);
1886 return unicode_empty;
1887 }
1888 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001889 if (size == 1 && u[0] < 256)
Victor Stinner4e101002011-10-11 23:27:52 +02001890 return get_latin1_char((unsigned char)u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001891
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001892 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001893 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001894 if (!res)
1895 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001896 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001897 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001898 else {
1899 _PyUnicode_CONVERT_BYTES(
1900 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
1901 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001902 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001903 return res;
1904}
1905
Victor Stinnere57b1c02011-09-28 22:20:48 +02001906static PyObject*
1907_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001908{
1909 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001910 Py_UCS4 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001911
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001912 if (size == 0) {
1913 Py_INCREF(unicode_empty);
1914 return unicode_empty;
1915 }
1916 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001917 if (size == 1 && u[0] < 256)
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001918 return get_latin1_char((unsigned char)u[0]);
1919
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001920 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001921 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001922 if (!res)
1923 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02001924 if (max_char < 256)
1925 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
1926 PyUnicode_1BYTE_DATA(res));
1927 else if (max_char < 0x10000)
1928 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
1929 PyUnicode_2BYTE_DATA(res));
1930 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001931 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001932 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001933 return res;
1934}
1935
1936PyObject*
1937PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
1938{
Victor Stinnercfed46e2011-11-22 01:29:14 +01001939 if (size < 0) {
1940 PyErr_SetString(PyExc_ValueError, "size must be positive");
1941 return NULL;
1942 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06001943 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001944 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001945 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001946 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001947 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001948 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001949 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001950 default:
Victor Stinnerb9275c12011-10-05 14:01:42 +02001951 PyErr_SetString(PyExc_SystemError, "invalid kind");
1952 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001953 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001954}
1955
Victor Stinner25a4b292011-10-06 12:31:55 +02001956/* Ensure that a string uses the most efficient storage, if it is not the
1957 case: create a new string with of the right kind. Write NULL into *p_unicode
1958 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02001959static void
Victor Stinner25a4b292011-10-06 12:31:55 +02001960unicode_adjust_maxchar(PyObject **p_unicode)
1961{
1962 PyObject *unicode, *copy;
1963 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001964 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02001965 unsigned int kind;
1966
1967 assert(p_unicode != NULL);
1968 unicode = *p_unicode;
1969 assert(PyUnicode_IS_READY(unicode));
1970 if (PyUnicode_IS_ASCII(unicode))
1971 return;
1972
1973 len = PyUnicode_GET_LENGTH(unicode);
1974 kind = PyUnicode_KIND(unicode);
1975 if (kind == PyUnicode_1BYTE_KIND) {
1976 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001977 max_char = ucs1lib_find_max_char(u, u + len);
1978 if (max_char >= 128)
1979 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001980 }
1981 else if (kind == PyUnicode_2BYTE_KIND) {
1982 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001983 max_char = ucs2lib_find_max_char(u, u + len);
1984 if (max_char >= 256)
1985 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001986 }
1987 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001988 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02001989 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001990 max_char = ucs4lib_find_max_char(u, u + len);
1991 if (max_char >= 0x10000)
1992 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001993 }
Victor Stinner25a4b292011-10-06 12:31:55 +02001994 copy = PyUnicode_New(len, max_char);
1995 copy_characters(copy, 0, unicode, 0, len);
1996 Py_DECREF(unicode);
1997 *p_unicode = copy;
1998}
1999
Victor Stinner034f6cf2011-09-30 02:26:44 +02002000PyObject*
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002001_PyUnicode_Copy(PyObject *unicode)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002002{
Victor Stinner87af4f22011-11-21 23:03:47 +01002003 Py_ssize_t length;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002004 PyObject *copy;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002005
Victor Stinner034f6cf2011-09-30 02:26:44 +02002006 if (!PyUnicode_Check(unicode)) {
2007 PyErr_BadInternalCall();
2008 return NULL;
2009 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05002010 if (PyUnicode_READY(unicode) == -1)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002011 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002012
Victor Stinner87af4f22011-11-21 23:03:47 +01002013 length = PyUnicode_GET_LENGTH(unicode);
2014 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002015 if (!copy)
2016 return NULL;
2017 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
2018
Victor Stinner87af4f22011-11-21 23:03:47 +01002019 Py_MEMCPY(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
2020 length * PyUnicode_KIND(unicode));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002021 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002022 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02002023}
2024
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002025
Victor Stinnerbc603d12011-10-02 01:00:40 +02002026/* Widen Unicode objects to larger buffers. Don't write terminating null
2027 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002028
2029void*
2030_PyUnicode_AsKind(PyObject *s, unsigned int kind)
2031{
Victor Stinnerbc603d12011-10-02 01:00:40 +02002032 Py_ssize_t len;
2033 void *result;
2034 unsigned int skind;
2035
Benjamin Petersonbac79492012-01-14 13:34:47 -05002036 if (PyUnicode_READY(s) == -1)
Victor Stinnerbc603d12011-10-02 01:00:40 +02002037 return NULL;
2038
2039 len = PyUnicode_GET_LENGTH(s);
2040 skind = PyUnicode_KIND(s);
2041 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02002042 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002043 return NULL;
2044 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002045 switch (kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02002046 case PyUnicode_2BYTE_KIND:
2047 result = PyMem_Malloc(len * sizeof(Py_UCS2));
2048 if (!result)
2049 return PyErr_NoMemory();
2050 assert(skind == PyUnicode_1BYTE_KIND);
2051 _PyUnicode_CONVERT_BYTES(
2052 Py_UCS1, Py_UCS2,
2053 PyUnicode_1BYTE_DATA(s),
2054 PyUnicode_1BYTE_DATA(s) + len,
2055 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002056 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002057 case PyUnicode_4BYTE_KIND:
2058 result = PyMem_Malloc(len * sizeof(Py_UCS4));
2059 if (!result)
2060 return PyErr_NoMemory();
2061 if (skind == PyUnicode_2BYTE_KIND) {
2062 _PyUnicode_CONVERT_BYTES(
2063 Py_UCS2, Py_UCS4,
2064 PyUnicode_2BYTE_DATA(s),
2065 PyUnicode_2BYTE_DATA(s) + len,
2066 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002067 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02002068 else {
2069 assert(skind == PyUnicode_1BYTE_KIND);
2070 _PyUnicode_CONVERT_BYTES(
2071 Py_UCS1, Py_UCS4,
2072 PyUnicode_1BYTE_DATA(s),
2073 PyUnicode_1BYTE_DATA(s) + len,
2074 result);
2075 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002076 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002077 default:
2078 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002079 }
Victor Stinner01698042011-10-04 00:04:26 +02002080 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002081 return NULL;
2082}
2083
2084static Py_UCS4*
2085as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2086 int copy_null)
2087{
2088 int kind;
2089 void *data;
2090 Py_ssize_t len, targetlen;
2091 if (PyUnicode_READY(string) == -1)
2092 return NULL;
2093 kind = PyUnicode_KIND(string);
2094 data = PyUnicode_DATA(string);
2095 len = PyUnicode_GET_LENGTH(string);
2096 targetlen = len;
2097 if (copy_null)
2098 targetlen++;
2099 if (!target) {
2100 if (PY_SSIZE_T_MAX / sizeof(Py_UCS4) < targetlen) {
2101 PyErr_NoMemory();
2102 return NULL;
2103 }
2104 target = PyMem_Malloc(targetlen * sizeof(Py_UCS4));
2105 if (!target) {
2106 PyErr_NoMemory();
2107 return NULL;
2108 }
2109 }
2110 else {
2111 if (targetsize < targetlen) {
2112 PyErr_Format(PyExc_SystemError,
2113 "string is longer than the buffer");
2114 if (copy_null && 0 < targetsize)
2115 target[0] = 0;
2116 return NULL;
2117 }
2118 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002119 if (kind == PyUnicode_1BYTE_KIND) {
2120 Py_UCS1 *start = (Py_UCS1 *) data;
2121 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002122 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002123 else if (kind == PyUnicode_2BYTE_KIND) {
2124 Py_UCS2 *start = (Py_UCS2 *) data;
2125 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2126 }
2127 else {
2128 assert(kind == PyUnicode_4BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002129 Py_MEMCPY(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002130 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002131 if (copy_null)
2132 target[len] = 0;
2133 return target;
2134}
2135
2136Py_UCS4*
2137PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2138 int copy_null)
2139{
Antoine Pitroude20b0b2011-11-10 21:47:38 +01002140 if (target == NULL || targetsize < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002141 PyErr_BadInternalCall();
2142 return NULL;
2143 }
2144 return as_ucs4(string, target, targetsize, copy_null);
2145}
2146
2147Py_UCS4*
2148PyUnicode_AsUCS4Copy(PyObject *string)
2149{
2150 return as_ucs4(string, NULL, 0, 1);
2151}
2152
2153#ifdef HAVE_WCHAR_H
Mark Dickinson081dfee2009-03-18 14:47:41 +00002154
Alexander Belopolsky40018472011-02-26 01:02:56 +00002155PyObject *
2156PyUnicode_FromWideChar(register const wchar_t *w, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002157{
Guido van Rossumd57fd912000-03-10 22:53:23 +00002158 if (w == NULL) {
Victor Stinner382955f2011-12-11 21:44:00 +01002159 if (size == 0) {
2160 Py_INCREF(unicode_empty);
2161 return unicode_empty;
2162 }
Benjamin Peterson29060642009-01-31 22:14:21 +00002163 PyErr_BadInternalCall();
2164 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002165 }
2166
Martin v. Löwis790465f2008-04-05 20:41:37 +00002167 if (size == -1) {
2168 size = wcslen(w);
2169 }
2170
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002171 return PyUnicode_FromUnicode(w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002172}
2173
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002174#endif /* HAVE_WCHAR_H */
Mark Dickinson081dfee2009-03-18 14:47:41 +00002175
Walter Dörwald346737f2007-05-31 10:44:43 +00002176static void
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002177makefmt(char *fmt, int longflag, int longlongflag, int size_tflag,
2178 int zeropad, int width, int precision, char c)
Walter Dörwald346737f2007-05-31 10:44:43 +00002179{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002180 *fmt++ = '%';
2181 if (width) {
2182 if (zeropad)
2183 *fmt++ = '0';
2184 fmt += sprintf(fmt, "%d", width);
2185 }
2186 if (precision)
2187 fmt += sprintf(fmt, ".%d", precision);
2188 if (longflag)
2189 *fmt++ = 'l';
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002190 else if (longlongflag) {
2191 /* longlongflag should only ever be nonzero on machines with
2192 HAVE_LONG_LONG defined */
2193#ifdef HAVE_LONG_LONG
2194 char *f = PY_FORMAT_LONG_LONG;
2195 while (*f)
2196 *fmt++ = *f++;
2197#else
2198 /* we shouldn't ever get here */
2199 assert(0);
2200 *fmt++ = 'l';
2201#endif
2202 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002203 else if (size_tflag) {
2204 char *f = PY_FORMAT_SIZE_T;
2205 while (*f)
2206 *fmt++ = *f++;
2207 }
2208 *fmt++ = c;
2209 *fmt = '\0';
Walter Dörwald346737f2007-05-31 10:44:43 +00002210}
2211
Victor Stinner96865452011-03-01 23:44:09 +00002212/* helper for PyUnicode_FromFormatV() */
2213
2214static const char*
2215parse_format_flags(const char *f,
2216 int *p_width, int *p_precision,
2217 int *p_longflag, int *p_longlongflag, int *p_size_tflag)
2218{
2219 int width, precision, longflag, longlongflag, size_tflag;
2220
2221 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
2222 f++;
2223 width = 0;
2224 while (Py_ISDIGIT((unsigned)*f))
2225 width = (width*10) + *f++ - '0';
2226 precision = 0;
2227 if (*f == '.') {
2228 f++;
2229 while (Py_ISDIGIT((unsigned)*f))
2230 precision = (precision*10) + *f++ - '0';
2231 if (*f == '%') {
2232 /* "%.3%s" => f points to "3" */
2233 f--;
2234 }
2235 }
2236 if (*f == '\0') {
2237 /* bogus format "%.1" => go backward, f points to "1" */
2238 f--;
2239 }
2240 if (p_width != NULL)
2241 *p_width = width;
2242 if (p_precision != NULL)
2243 *p_precision = precision;
2244
2245 /* Handle %ld, %lu, %lld and %llu. */
2246 longflag = 0;
2247 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002248 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002249
2250 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002251 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002252 longflag = 1;
2253 ++f;
2254 }
2255#ifdef HAVE_LONG_LONG
2256 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002257 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002258 longlongflag = 1;
2259 f += 2;
2260 }
2261#endif
2262 }
2263 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002264 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002265 size_tflag = 1;
2266 ++f;
2267 }
2268 if (p_longflag != NULL)
2269 *p_longflag = longflag;
2270 if (p_longlongflag != NULL)
2271 *p_longlongflag = longlongflag;
2272 if (p_size_tflag != NULL)
2273 *p_size_tflag = size_tflag;
2274 return f;
2275}
2276
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002277/* maximum number of characters required for output of %ld. 21 characters
2278 allows for 64-bit integers (in decimal) and an optional sign. */
2279#define MAX_LONG_CHARS 21
2280/* maximum number of characters required for output of %lld.
2281 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2282 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2283#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
2284
Walter Dörwaldd2034312007-05-18 16:29:38 +00002285PyObject *
2286PyUnicode_FromFormatV(const char *format, va_list vargs)
2287{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002288 va_list count;
2289 Py_ssize_t callcount = 0;
2290 PyObject **callresults = NULL;
2291 PyObject **callresult = NULL;
2292 Py_ssize_t n = 0;
2293 int width = 0;
2294 int precision = 0;
2295 int zeropad;
2296 const char* f;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002297 PyObject *string;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002298 /* used by sprintf */
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002299 char fmt[61]; /* should be enough for %0width.precisionlld */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002300 Py_UCS4 maxchar = 127; /* result is ASCII by default */
2301 Py_UCS4 argmaxchar;
2302 Py_ssize_t numbersize = 0;
2303 char *numberresults = NULL;
2304 char *numberresult = NULL;
2305 Py_ssize_t i;
2306 int kind;
2307 void *data;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002308
Victor Stinner4a2b7a12010-08-13 14:03:48 +00002309 Py_VA_COPY(count, vargs);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002310 /* step 1: count the number of %S/%R/%A/%s format specifications
2311 * (we call PyObject_Str()/PyObject_Repr()/PyObject_ASCII()/
2312 * PyUnicode_DecodeUTF8() for these objects once during step 3 and put the
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002313 * result in an array)
Georg Brandl7597add2011-10-05 16:36:47 +02002314 * also estimate a upper bound for all the number formats in the string,
2315 * numbers will be formatted in step 3 and be kept in a '\0'-separated
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002316 * buffer before putting everything together. */
Benjamin Peterson14339b62009-01-31 16:36:08 +00002317 for (f = format; *f; f++) {
2318 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002319 int longlongflag;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002320 /* skip width or width.precision (eg. "1.2" of "%1.2f") */
2321 f = parse_format_flags(f, &width, NULL, NULL, &longlongflag, NULL);
2322 if (*f == 's' || *f=='S' || *f=='R' || *f=='A' || *f=='V')
2323 ++callcount;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002324
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002325 else if (*f == 'd' || *f=='u' || *f=='i' || *f=='x' || *f=='p') {
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002326#ifdef HAVE_LONG_LONG
2327 if (longlongflag) {
2328 if (width < MAX_LONG_LONG_CHARS)
2329 width = MAX_LONG_LONG_CHARS;
2330 }
2331 else
2332#endif
2333 /* MAX_LONG_CHARS is enough to hold a 64-bit integer,
2334 including sign. Decimal takes the most space. This
2335 isn't enough for octal. If a width is specified we
2336 need more (which we allocate later). */
2337 if (width < MAX_LONG_CHARS)
2338 width = MAX_LONG_CHARS;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002339
2340 /* account for the size + '\0' to separate numbers
2341 inside of the numberresults buffer */
2342 numbersize += (width + 1);
2343 }
2344 }
2345 else if ((unsigned char)*f > 127) {
2346 PyErr_Format(PyExc_ValueError,
2347 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2348 "string, got a non-ASCII byte: 0x%02x",
2349 (unsigned char)*f);
2350 return NULL;
2351 }
2352 }
2353 /* step 2: allocate memory for the results of
2354 * PyObject_Str()/PyObject_Repr()/PyUnicode_DecodeUTF8() calls */
2355 if (callcount) {
2356 callresults = PyObject_Malloc(sizeof(PyObject *) * callcount);
2357 if (!callresults) {
2358 PyErr_NoMemory();
2359 return NULL;
2360 }
2361 callresult = callresults;
2362 }
2363 /* step 2.5: allocate memory for the results of formating numbers */
2364 if (numbersize) {
2365 numberresults = PyObject_Malloc(numbersize);
2366 if (!numberresults) {
2367 PyErr_NoMemory();
2368 goto fail;
2369 }
2370 numberresult = numberresults;
2371 }
2372
2373 /* step 3: format numbers and figure out how large a buffer we need */
2374 for (f = format; *f; f++) {
2375 if (*f == '%') {
2376 const char* p;
2377 int longflag;
2378 int longlongflag;
2379 int size_tflag;
2380 int numprinted;
2381
2382 p = f;
2383 zeropad = (f[1] == '0');
2384 f = parse_format_flags(f, &width, &precision,
2385 &longflag, &longlongflag, &size_tflag);
2386 switch (*f) {
2387 case 'c':
2388 {
2389 Py_UCS4 ordinal = va_arg(count, int);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002390 maxchar = Py_MAX(maxchar, ordinal);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002391 n++;
2392 break;
2393 }
2394 case '%':
2395 n++;
2396 break;
2397 case 'i':
2398 case 'd':
2399 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2400 width, precision, *f);
2401 if (longflag)
2402 numprinted = sprintf(numberresult, fmt,
2403 va_arg(count, long));
2404#ifdef HAVE_LONG_LONG
2405 else if (longlongflag)
2406 numprinted = sprintf(numberresult, fmt,
2407 va_arg(count, PY_LONG_LONG));
2408#endif
2409 else if (size_tflag)
2410 numprinted = sprintf(numberresult, fmt,
2411 va_arg(count, Py_ssize_t));
2412 else
2413 numprinted = sprintf(numberresult, fmt,
2414 va_arg(count, int));
2415 n += numprinted;
2416 /* advance by +1 to skip over the '\0' */
2417 numberresult += (numprinted + 1);
2418 assert(*(numberresult - 1) == '\0');
2419 assert(*(numberresult - 2) != '\0');
2420 assert(numprinted >= 0);
2421 assert(numberresult <= numberresults + numbersize);
2422 break;
2423 case 'u':
2424 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2425 width, precision, 'u');
2426 if (longflag)
2427 numprinted = sprintf(numberresult, fmt,
2428 va_arg(count, unsigned long));
2429#ifdef HAVE_LONG_LONG
2430 else if (longlongflag)
2431 numprinted = sprintf(numberresult, fmt,
2432 va_arg(count, unsigned PY_LONG_LONG));
2433#endif
2434 else if (size_tflag)
2435 numprinted = sprintf(numberresult, fmt,
2436 va_arg(count, size_t));
2437 else
2438 numprinted = sprintf(numberresult, fmt,
2439 va_arg(count, unsigned int));
2440 n += numprinted;
2441 numberresult += (numprinted + 1);
2442 assert(*(numberresult - 1) == '\0');
2443 assert(*(numberresult - 2) != '\0');
2444 assert(numprinted >= 0);
2445 assert(numberresult <= numberresults + numbersize);
2446 break;
2447 case 'x':
2448 makefmt(fmt, 0, 0, 0, zeropad, width, precision, 'x');
2449 numprinted = sprintf(numberresult, fmt, va_arg(count, int));
2450 n += numprinted;
2451 numberresult += (numprinted + 1);
2452 assert(*(numberresult - 1) == '\0');
2453 assert(*(numberresult - 2) != '\0');
2454 assert(numprinted >= 0);
2455 assert(numberresult <= numberresults + numbersize);
2456 break;
2457 case 'p':
2458 numprinted = sprintf(numberresult, "%p", va_arg(count, void*));
2459 /* %p is ill-defined: ensure leading 0x. */
2460 if (numberresult[1] == 'X')
2461 numberresult[1] = 'x';
2462 else if (numberresult[1] != 'x') {
2463 memmove(numberresult + 2, numberresult,
2464 strlen(numberresult) + 1);
2465 numberresult[0] = '0';
2466 numberresult[1] = 'x';
2467 numprinted += 2;
2468 }
2469 n += numprinted;
2470 numberresult += (numprinted + 1);
2471 assert(*(numberresult - 1) == '\0');
2472 assert(*(numberresult - 2) != '\0');
2473 assert(numprinted >= 0);
2474 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002475 break;
2476 case 's':
2477 {
2478 /* UTF-8 */
Georg Brandl780b2a62009-05-05 09:19:59 +00002479 const char *s = va_arg(count, const char*);
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002480 PyObject *str = PyUnicode_DecodeUTF8Stateful(s, strlen(s), "replace", NULL);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002481 if (!str)
2482 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002483 /* since PyUnicode_DecodeUTF8 returns already flexible
2484 unicode objects, there is no need to call ready on them */
2485 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002486 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002487 n += PyUnicode_GET_LENGTH(str);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002488 /* Remember the str and switch to the next slot */
2489 *callresult++ = str;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002490 break;
2491 }
2492 case 'U':
2493 {
2494 PyObject *obj = va_arg(count, PyObject *);
Victor Stinner910337b2011-10-03 03:20:16 +02002495 assert(obj && _PyUnicode_CHECK(obj));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002496 if (PyUnicode_READY(obj) == -1)
2497 goto fail;
2498 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002499 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002500 n += PyUnicode_GET_LENGTH(obj);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002501 break;
2502 }
2503 case 'V':
2504 {
2505 PyObject *obj = va_arg(count, PyObject *);
2506 const char *str = va_arg(count, const char *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002507 PyObject *str_obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002508 assert(obj || str);
Victor Stinner910337b2011-10-03 03:20:16 +02002509 assert(!obj || _PyUnicode_CHECK(obj));
Victor Stinner2512a8b2011-03-01 22:46:52 +00002510 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002511 if (PyUnicode_READY(obj) == -1)
2512 goto fail;
2513 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002514 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002515 n += PyUnicode_GET_LENGTH(obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002516 *callresult++ = NULL;
2517 }
2518 else {
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002519 str_obj = PyUnicode_DecodeUTF8Stateful(str, strlen(str), "replace", NULL);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002520 if (!str_obj)
2521 goto fail;
Benjamin Petersonbac79492012-01-14 13:34:47 -05002522 if (PyUnicode_READY(str_obj) == -1) {
Victor Stinnere1335c72011-10-04 20:53:03 +02002523 Py_DECREF(str_obj);
2524 goto fail;
2525 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002526 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002527 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002528 n += PyUnicode_GET_LENGTH(str_obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002529 *callresult++ = str_obj;
2530 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002531 break;
2532 }
2533 case 'S':
2534 {
2535 PyObject *obj = va_arg(count, PyObject *);
2536 PyObject *str;
2537 assert(obj);
2538 str = PyObject_Str(obj);
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002539 if (!str)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002540 goto fail;
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002541 if (PyUnicode_READY(str) == -1) {
2542 Py_DECREF(str);
2543 goto fail;
2544 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002545 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002546 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002547 n += PyUnicode_GET_LENGTH(str);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002548 /* Remember the str and switch to the next slot */
2549 *callresult++ = str;
2550 break;
2551 }
2552 case 'R':
2553 {
2554 PyObject *obj = va_arg(count, PyObject *);
2555 PyObject *repr;
2556 assert(obj);
2557 repr = PyObject_Repr(obj);
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002558 if (!repr)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002559 goto fail;
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002560 if (PyUnicode_READY(repr) == -1) {
2561 Py_DECREF(repr);
2562 goto fail;
2563 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002564 argmaxchar = PyUnicode_MAX_CHAR_VALUE(repr);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002565 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002566 n += PyUnicode_GET_LENGTH(repr);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002567 /* Remember the repr and switch to the next slot */
2568 *callresult++ = repr;
2569 break;
2570 }
2571 case 'A':
2572 {
2573 PyObject *obj = va_arg(count, PyObject *);
2574 PyObject *ascii;
2575 assert(obj);
2576 ascii = PyObject_ASCII(obj);
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002577 if (!ascii)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002578 goto fail;
Benjamin Petersonc8d8b882012-01-14 13:37:31 -05002579 if (PyUnicode_READY(ascii) == -1) {
2580 Py_DECREF(ascii);
2581 goto fail;
2582 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002583 argmaxchar = PyUnicode_MAX_CHAR_VALUE(ascii);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002584 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002585 n += PyUnicode_GET_LENGTH(ascii);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002586 /* Remember the repr and switch to the next slot */
2587 *callresult++ = ascii;
2588 break;
2589 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002590 default:
2591 /* if we stumble upon an unknown
2592 formatting code, copy the rest of
2593 the format string to the output
2594 string. (we cannot just skip the
2595 code, since there's no way to know
2596 what's in the argument list) */
2597 n += strlen(p);
2598 goto expand;
2599 }
2600 } else
2601 n++;
2602 }
Benjamin Peterson29060642009-01-31 22:14:21 +00002603 expand:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002604 /* step 4: fill the buffer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002605 /* Since we've analyzed how much space we need,
Benjamin Peterson14339b62009-01-31 16:36:08 +00002606 we don't have to resize the string.
2607 There can be no errors beyond this point. */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002608 string = PyUnicode_New(n, maxchar);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002609 if (!string)
2610 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002611 kind = PyUnicode_KIND(string);
2612 data = PyUnicode_DATA(string);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002613 callresult = callresults;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002614 numberresult = numberresults;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002615
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002616 for (i = 0, f = format; *f; f++) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002617 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002618 const char* p;
Victor Stinner96865452011-03-01 23:44:09 +00002619
2620 p = f;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002621 f = parse_format_flags(f, NULL, NULL, NULL, NULL, NULL);
2622 /* checking for == because the last argument could be a empty
2623 string, which causes i to point to end, the assert at the end of
2624 the loop */
2625 assert(i <= PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002626
Benjamin Peterson14339b62009-01-31 16:36:08 +00002627 switch (*f) {
2628 case 'c':
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002629 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002630 const int ordinal = va_arg(vargs, int);
2631 PyUnicode_WRITE(kind, data, i++, ordinal);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002632 break;
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002633 }
Victor Stinner6d970f42011-03-02 00:04:25 +00002634 case 'i':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002635 case 'd':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002636 case 'u':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002637 case 'x':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002638 case 'p':
Victor Stinnerc5166102012-02-22 13:55:02 +01002639 {
2640 Py_ssize_t written;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002641 /* unused, since we already have the result */
2642 if (*f == 'p')
2643 (void) va_arg(vargs, void *);
2644 else
2645 (void) va_arg(vargs, int);
2646 /* extract the result from numberresults and append. */
Victor Stinnerc5166102012-02-22 13:55:02 +01002647 written = unicode_write_cstr(string, i, numberresult);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002648 /* skip over the separating '\0' */
Victor Stinnerc5166102012-02-22 13:55:02 +01002649 i += written;
2650 numberresult += written;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002651 assert(*numberresult == '\0');
2652 numberresult++;
2653 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002654 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01002655 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002656 case 's':
2657 {
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002658 /* unused, since we already have the result */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002659 Py_ssize_t size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002660 (void) va_arg(vargs, char *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002661 size = PyUnicode_GET_LENGTH(*callresult);
2662 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002663 copy_characters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002664 i += size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002665 /* We're done with the unicode()/repr() => forget it */
2666 Py_DECREF(*callresult);
2667 /* switch to next unicode()/repr() result */
2668 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002669 break;
2670 }
2671 case 'U':
2672 {
2673 PyObject *obj = va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002674 Py_ssize_t size;
2675 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
2676 size = PyUnicode_GET_LENGTH(obj);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002677 copy_characters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002678 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002679 break;
2680 }
2681 case 'V':
2682 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002683 Py_ssize_t size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002684 PyObject *obj = va_arg(vargs, PyObject *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002685 va_arg(vargs, const char *);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002686 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002687 size = PyUnicode_GET_LENGTH(obj);
2688 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002689 copy_characters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002690 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002691 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002692 size = PyUnicode_GET_LENGTH(*callresult);
2693 assert(PyUnicode_KIND(*callresult) <=
2694 PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002695 copy_characters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002696 i += size;
Victor Stinner2512a8b2011-03-01 22:46:52 +00002697 Py_DECREF(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002698 }
Victor Stinner2512a8b2011-03-01 22:46:52 +00002699 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002700 break;
2701 }
2702 case 'S':
2703 case 'R':
Victor Stinner9a909002010-10-18 20:59:24 +00002704 case 'A':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002705 {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002706 Py_ssize_t size = PyUnicode_GET_LENGTH(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002707 /* unused, since we already have the result */
2708 (void) va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002709 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002710 copy_characters(string, i, *callresult, 0, size);
2711 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002712 /* We're done with the unicode()/repr() => forget it */
2713 Py_DECREF(*callresult);
2714 /* switch to next unicode()/repr() result */
2715 ++callresult;
2716 break;
2717 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002718 case '%':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002719 PyUnicode_WRITE(kind, data, i++, '%');
Benjamin Peterson14339b62009-01-31 16:36:08 +00002720 break;
2721 default:
Victor Stinnerc5166102012-02-22 13:55:02 +01002722 i += unicode_write_cstr(string, i, p);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002723 assert(i == PyUnicode_GET_LENGTH(string));
Benjamin Peterson14339b62009-01-31 16:36:08 +00002724 goto end;
2725 }
Victor Stinner1205f272010-09-11 00:54:47 +00002726 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002727 else {
2728 assert(i < PyUnicode_GET_LENGTH(string));
2729 PyUnicode_WRITE(kind, data, i++, *f);
2730 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002731 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002732 assert(i == PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002733
Benjamin Peterson29060642009-01-31 22:14:21 +00002734 end:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002735 if (callresults)
2736 PyObject_Free(callresults);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002737 if (numberresults)
2738 PyObject_Free(numberresults);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002739 return unicode_result(string);
Benjamin Peterson29060642009-01-31 22:14:21 +00002740 fail:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002741 if (callresults) {
2742 PyObject **callresult2 = callresults;
2743 while (callresult2 < callresult) {
Victor Stinner2512a8b2011-03-01 22:46:52 +00002744 Py_XDECREF(*callresult2);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002745 ++callresult2;
2746 }
2747 PyObject_Free(callresults);
2748 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002749 if (numberresults)
2750 PyObject_Free(numberresults);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002751 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002752}
2753
Walter Dörwaldd2034312007-05-18 16:29:38 +00002754PyObject *
2755PyUnicode_FromFormat(const char *format, ...)
2756{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002757 PyObject* ret;
2758 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002759
2760#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002761 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002762#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002763 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002764#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002765 ret = PyUnicode_FromFormatV(format, vargs);
2766 va_end(vargs);
2767 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002768}
2769
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002770#ifdef HAVE_WCHAR_H
2771
Victor Stinner5593d8a2010-10-02 11:11:27 +00002772/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2773 convert a Unicode object to a wide character string.
2774
Victor Stinnerd88d9832011-09-06 02:00:05 +02002775 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002776 character) required to convert the unicode object. Ignore size argument.
2777
Victor Stinnerd88d9832011-09-06 02:00:05 +02002778 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002779 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002780 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002781static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002782unicode_aswidechar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002783 wchar_t *w,
2784 Py_ssize_t size)
2785{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002786 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002787 const wchar_t *wstr;
2788
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002789 wstr = PyUnicode_AsUnicodeAndSize(unicode, &res);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002790 if (wstr == NULL)
2791 return -1;
2792
Victor Stinner5593d8a2010-10-02 11:11:27 +00002793 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002794 if (size > res)
2795 size = res + 1;
2796 else
2797 res = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002798 Py_MEMCPY(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002799 return res;
2800 }
2801 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002802 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002803}
2804
2805Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002806PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002807 wchar_t *w,
2808 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002809{
2810 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002811 PyErr_BadInternalCall();
2812 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002813 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002814 return unicode_aswidechar(unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002815}
2816
Victor Stinner137c34c2010-09-29 10:25:54 +00002817wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002818PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002819 Py_ssize_t *size)
2820{
2821 wchar_t* buffer;
2822 Py_ssize_t buflen;
2823
2824 if (unicode == NULL) {
2825 PyErr_BadInternalCall();
2826 return NULL;
2827 }
2828
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002829 buflen = unicode_aswidechar(unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002830 if (buflen == -1)
2831 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002832 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < buflen) {
Victor Stinner137c34c2010-09-29 10:25:54 +00002833 PyErr_NoMemory();
2834 return NULL;
2835 }
2836
Victor Stinner137c34c2010-09-29 10:25:54 +00002837 buffer = PyMem_MALLOC(buflen * sizeof(wchar_t));
2838 if (buffer == NULL) {
2839 PyErr_NoMemory();
2840 return NULL;
2841 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002842 buflen = unicode_aswidechar(unicode, buffer, buflen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002843 if (buflen == -1)
2844 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002845 if (size != NULL)
2846 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00002847 return buffer;
2848}
2849
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002850#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002851
Alexander Belopolsky40018472011-02-26 01:02:56 +00002852PyObject *
2853PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002854{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002855 PyObject *v;
Victor Stinner8faf8212011-12-08 22:14:11 +01002856 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002857 PyErr_SetString(PyExc_ValueError,
2858 "chr() arg not in range(0x110000)");
2859 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002860 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00002861
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002862 if (ordinal < 256)
2863 return get_latin1_char(ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002864
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002865 v = PyUnicode_New(1, ordinal);
2866 if (v == NULL)
2867 return NULL;
2868 PyUnicode_WRITE(PyUnicode_KIND(v), PyUnicode_DATA(v), 0, ordinal);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002869 assert(_PyUnicode_CheckConsistency(v, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002870 return v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002871}
2872
Alexander Belopolsky40018472011-02-26 01:02:56 +00002873PyObject *
2874PyUnicode_FromObject(register PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002875{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002876 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00002877 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002878 if (PyUnicode_CheckExact(obj)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05002879 if (PyUnicode_READY(obj) == -1)
Victor Stinnerd3a83d52011-10-01 03:09:33 +02002880 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00002881 Py_INCREF(obj);
2882 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002883 }
2884 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002885 /* For a Unicode subtype that's not a Unicode object,
2886 return a true Unicode object with the same data. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002887 return _PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002888 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00002889 PyErr_Format(PyExc_TypeError,
2890 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00002891 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002892 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002893}
2894
Alexander Belopolsky40018472011-02-26 01:02:56 +00002895PyObject *
2896PyUnicode_FromEncodedObject(register PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002897 const char *encoding,
2898 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002899{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002900 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002901 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00002902
Guido van Rossumd57fd912000-03-10 22:53:23 +00002903 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002904 PyErr_BadInternalCall();
2905 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002906 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002907
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002908 /* Decoding bytes objects is the most common case and should be fast */
2909 if (PyBytes_Check(obj)) {
2910 if (PyBytes_GET_SIZE(obj) == 0) {
2911 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002912 v = unicode_empty;
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002913 }
2914 else {
2915 v = PyUnicode_Decode(
2916 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
2917 encoding, errors);
2918 }
2919 return v;
2920 }
2921
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002922 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002923 PyErr_SetString(PyExc_TypeError,
2924 "decoding str is not supported");
2925 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002926 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002927
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002928 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
2929 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
2930 PyErr_Format(PyExc_TypeError,
2931 "coercing to str: need bytes, bytearray "
2932 "or buffer-like object, %.80s found",
2933 Py_TYPE(obj)->tp_name);
2934 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00002935 }
Tim Petersced69f82003-09-16 20:30:58 +00002936
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002937 if (buffer.len == 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002938 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002939 v = unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002940 }
Tim Petersced69f82003-09-16 20:30:58 +00002941 else
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002942 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00002943
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002944 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002945 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002946}
2947
Victor Stinner600d3be2010-06-10 12:00:55 +00002948/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00002949 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
2950 1 on success. */
2951static int
2952normalize_encoding(const char *encoding,
2953 char *lower,
2954 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002955{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002956 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00002957 char *l;
2958 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002959
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04002960 if (encoding == NULL) {
2961 strcpy(lower, "utf-8");
2962 return 1;
2963 }
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002964 e = encoding;
2965 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00002966 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00002967 while (*e) {
2968 if (l == l_end)
2969 return 0;
David Malcolm96960882010-11-05 17:23:41 +00002970 if (Py_ISUPPER(*e)) {
2971 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002972 }
2973 else if (*e == '_') {
2974 *l++ = '-';
2975 e++;
2976 }
2977 else {
2978 *l++ = *e++;
2979 }
2980 }
2981 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00002982 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00002983}
2984
Alexander Belopolsky40018472011-02-26 01:02:56 +00002985PyObject *
2986PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002987 Py_ssize_t size,
2988 const char *encoding,
2989 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00002990{
2991 PyObject *buffer = NULL, *unicode;
2992 Py_buffer info;
2993 char lower[11]; /* Enough for any encoding shortcut */
2994
Fred Drakee4315f52000-05-09 19:53:39 +00002995 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00002996 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002997 if ((strcmp(lower, "utf-8") == 0) ||
2998 (strcmp(lower, "utf8") == 0))
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002999 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
Victor Stinner37296e82010-06-10 13:36:23 +00003000 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003001 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00003002 (strcmp(lower, "iso-8859-1") == 0))
3003 return PyUnicode_DecodeLatin1(s, size, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003004#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00003005 else if (strcmp(lower, "mbcs") == 0)
3006 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003007#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003008 else if (strcmp(lower, "ascii") == 0)
3009 return PyUnicode_DecodeASCII(s, size, errors);
3010 else if (strcmp(lower, "utf-16") == 0)
3011 return PyUnicode_DecodeUTF16(s, size, errors, 0);
3012 else if (strcmp(lower, "utf-32") == 0)
3013 return PyUnicode_DecodeUTF32(s, size, errors, 0);
3014 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003015
3016 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003017 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00003018 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003019 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00003020 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003021 if (buffer == NULL)
3022 goto onError;
3023 unicode = PyCodec_Decode(buffer, encoding, errors);
3024 if (unicode == NULL)
3025 goto onError;
3026 if (!PyUnicode_Check(unicode)) {
3027 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003028 "decoder did not return a str object (type=%.400s)",
Christian Heimes90aa7642007-12-19 02:45:37 +00003029 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003030 Py_DECREF(unicode);
3031 goto onError;
3032 }
3033 Py_DECREF(buffer);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003034 return unicode_result(unicode);
Tim Petersced69f82003-09-16 20:30:58 +00003035
Benjamin Peterson29060642009-01-31 22:14:21 +00003036 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003037 Py_XDECREF(buffer);
3038 return NULL;
3039}
3040
Alexander Belopolsky40018472011-02-26 01:02:56 +00003041PyObject *
3042PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003043 const char *encoding,
3044 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003045{
3046 PyObject *v;
3047
3048 if (!PyUnicode_Check(unicode)) {
3049 PyErr_BadArgument();
3050 goto onError;
3051 }
3052
3053 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003054 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003055
3056 /* Decode via the codec registry */
3057 v = PyCodec_Decode(unicode, encoding, errors);
3058 if (v == NULL)
3059 goto onError;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003060 return unicode_result(v);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003061
Benjamin Peterson29060642009-01-31 22:14:21 +00003062 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003063 return NULL;
3064}
3065
Alexander Belopolsky40018472011-02-26 01:02:56 +00003066PyObject *
3067PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003068 const char *encoding,
3069 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003070{
3071 PyObject *v;
3072
3073 if (!PyUnicode_Check(unicode)) {
3074 PyErr_BadArgument();
3075 goto onError;
3076 }
3077
3078 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003079 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003080
3081 /* Decode via the codec registry */
3082 v = PyCodec_Decode(unicode, encoding, errors);
3083 if (v == NULL)
3084 goto onError;
3085 if (!PyUnicode_Check(v)) {
3086 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003087 "decoder did not return a str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003088 Py_TYPE(v)->tp_name);
3089 Py_DECREF(v);
3090 goto onError;
3091 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003092 return unicode_result(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003093
Benjamin Peterson29060642009-01-31 22:14:21 +00003094 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003095 return NULL;
3096}
3097
Alexander Belopolsky40018472011-02-26 01:02:56 +00003098PyObject *
3099PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003100 Py_ssize_t size,
3101 const char *encoding,
3102 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003103{
3104 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003105
Guido van Rossumd57fd912000-03-10 22:53:23 +00003106 unicode = PyUnicode_FromUnicode(s, size);
3107 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003108 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003109 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3110 Py_DECREF(unicode);
3111 return v;
3112}
3113
Alexander Belopolsky40018472011-02-26 01:02:56 +00003114PyObject *
3115PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003116 const char *encoding,
3117 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003118{
3119 PyObject *v;
3120
3121 if (!PyUnicode_Check(unicode)) {
3122 PyErr_BadArgument();
3123 goto onError;
3124 }
3125
3126 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003127 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003128
3129 /* Encode via the codec registry */
3130 v = PyCodec_Encode(unicode, encoding, errors);
3131 if (v == NULL)
3132 goto onError;
3133 return v;
3134
Benjamin Peterson29060642009-01-31 22:14:21 +00003135 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003136 return NULL;
3137}
3138
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003139static size_t
3140wcstombs_errorpos(const wchar_t *wstr)
3141{
3142 size_t len;
3143#if SIZEOF_WCHAR_T == 2
3144 wchar_t buf[3];
3145#else
3146 wchar_t buf[2];
3147#endif
3148 char outbuf[MB_LEN_MAX];
3149 const wchar_t *start, *previous;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003150
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003151#if SIZEOF_WCHAR_T == 2
3152 buf[2] = 0;
3153#else
3154 buf[1] = 0;
3155#endif
3156 start = wstr;
3157 while (*wstr != L'\0')
3158 {
3159 previous = wstr;
3160#if SIZEOF_WCHAR_T == 2
3161 if (Py_UNICODE_IS_HIGH_SURROGATE(wstr[0])
3162 && Py_UNICODE_IS_LOW_SURROGATE(wstr[1]))
3163 {
3164 buf[0] = wstr[0];
3165 buf[1] = wstr[1];
3166 wstr += 2;
3167 }
3168 else {
3169 buf[0] = *wstr;
3170 buf[1] = 0;
3171 wstr++;
3172 }
3173#else
3174 buf[0] = *wstr;
3175 wstr++;
3176#endif
3177 len = wcstombs(outbuf, buf, sizeof(outbuf));
Victor Stinner2f197072011-12-17 07:08:30 +01003178 if (len == (size_t)-1)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003179 return previous - start;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003180 }
3181
3182 /* failed to find the unencodable character */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003183 return 0;
3184}
3185
Victor Stinner1b579672011-12-17 05:47:23 +01003186static int
3187locale_error_handler(const char *errors, int *surrogateescape)
3188{
3189 if (errors == NULL) {
3190 *surrogateescape = 0;
3191 return 0;
3192 }
3193
3194 if (strcmp(errors, "strict") == 0) {
3195 *surrogateescape = 0;
3196 return 0;
3197 }
3198 if (strcmp(errors, "surrogateescape") == 0) {
3199 *surrogateescape = 1;
3200 return 0;
3201 }
3202 PyErr_Format(PyExc_ValueError,
3203 "only 'strict' and 'surrogateescape' error handlers "
3204 "are supported, not '%s'",
3205 errors);
3206 return -1;
3207}
3208
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003209PyObject *
Victor Stinner1b579672011-12-17 05:47:23 +01003210PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003211{
3212 Py_ssize_t wlen, wlen2;
3213 wchar_t *wstr;
3214 PyObject *bytes = NULL;
3215 char *errmsg;
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003216 PyObject *reason;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003217 PyObject *exc;
3218 size_t error_pos;
Victor Stinner1b579672011-12-17 05:47:23 +01003219 int surrogateescape;
3220
3221 if (locale_error_handler(errors, &surrogateescape) < 0)
3222 return NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003223
3224 wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3225 if (wstr == NULL)
3226 return NULL;
3227
3228 wlen2 = wcslen(wstr);
3229 if (wlen2 != wlen) {
3230 PyMem_Free(wstr);
3231 PyErr_SetString(PyExc_TypeError, "embedded null character");
3232 return NULL;
3233 }
3234
3235 if (surrogateescape) {
3236 /* locale encoding with surrogateescape */
3237 char *str;
3238
3239 str = _Py_wchar2char(wstr, &error_pos);
3240 if (str == NULL) {
3241 if (error_pos == (size_t)-1) {
3242 PyErr_NoMemory();
3243 PyMem_Free(wstr);
3244 return NULL;
3245 }
3246 else {
3247 goto encode_error;
3248 }
3249 }
3250 PyMem_Free(wstr);
3251
3252 bytes = PyBytes_FromString(str);
3253 PyMem_Free(str);
3254 }
3255 else {
3256 size_t len, len2;
3257
3258 len = wcstombs(NULL, wstr, 0);
3259 if (len == (size_t)-1) {
Victor Stinner2f197072011-12-17 07:08:30 +01003260 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003261 goto encode_error;
3262 }
3263
3264 bytes = PyBytes_FromStringAndSize(NULL, len);
3265 if (bytes == NULL) {
3266 PyMem_Free(wstr);
3267 return NULL;
3268 }
3269
3270 len2 = wcstombs(PyBytes_AS_STRING(bytes), wstr, len+1);
3271 if (len2 == (size_t)-1 || len2 > len) {
Victor Stinner2f197072011-12-17 07:08:30 +01003272 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003273 goto encode_error;
3274 }
3275 PyMem_Free(wstr);
3276 }
3277 return bytes;
3278
3279encode_error:
3280 errmsg = strerror(errno);
3281 assert(errmsg != NULL);
Victor Stinner2f197072011-12-17 07:08:30 +01003282
3283 if (error_pos == (size_t)-1)
3284 error_pos = wcstombs_errorpos(wstr);
3285
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003286 PyMem_Free(wstr);
3287 Py_XDECREF(bytes);
3288
Victor Stinner2f197072011-12-17 07:08:30 +01003289 if (errmsg != NULL) {
3290 size_t errlen;
3291 wstr = _Py_char2wchar(errmsg, &errlen);
3292 if (wstr != NULL) {
3293 reason = PyUnicode_FromWideChar(wstr, errlen);
3294 PyMem_Free(wstr);
3295 } else
3296 errmsg = NULL;
3297 }
3298 if (errmsg == NULL)
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003299 reason = PyUnicode_FromString(
3300 "wcstombs() encountered an unencodable "
3301 "wide character");
3302 if (reason == NULL)
3303 return NULL;
3304
3305 exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnnO",
3306 "locale", unicode,
3307 (Py_ssize_t)error_pos,
3308 (Py_ssize_t)(error_pos+1),
3309 reason);
3310 Py_DECREF(reason);
3311 if (exc != NULL) {
3312 PyCodec_StrictErrors(exc);
3313 Py_XDECREF(exc);
3314 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003315 return NULL;
3316}
3317
Victor Stinnerad158722010-10-27 00:25:46 +00003318PyObject *
3319PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003320{
Victor Stinner99b95382011-07-04 14:23:54 +02003321#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003322 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003323#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003324 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00003325#else
Victor Stinner793b5312011-04-27 00:24:21 +02003326 PyInterpreterState *interp = PyThreadState_GET()->interp;
3327 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3328 cannot use it to encode and decode filenames before it is loaded. Load
3329 the Python codec requires to encode at least its own filename. Use the C
3330 version of the locale codec until the codec registry is initialized and
3331 the Python codec is loaded.
3332
3333 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3334 cannot only rely on it: check also interp->fscodec_initialized for
3335 subinterpreters. */
3336 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003337 return PyUnicode_AsEncodedString(unicode,
3338 Py_FileSystemDefaultEncoding,
3339 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003340 }
3341 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003342 return PyUnicode_EncodeLocale(unicode, "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003343 }
Victor Stinnerad158722010-10-27 00:25:46 +00003344#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003345}
3346
Alexander Belopolsky40018472011-02-26 01:02:56 +00003347PyObject *
3348PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003349 const char *encoding,
3350 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003351{
3352 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00003353 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003354
Guido van Rossumd57fd912000-03-10 22:53:23 +00003355 if (!PyUnicode_Check(unicode)) {
3356 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003357 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003358 }
Fred Drakee4315f52000-05-09 19:53:39 +00003359
Fred Drakee4315f52000-05-09 19:53:39 +00003360 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00003361 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003362 if ((strcmp(lower, "utf-8") == 0) ||
3363 (strcmp(lower, "utf8") == 0))
Victor Stinnera5c68c32011-03-02 01:03:14 +00003364 {
Victor Stinner2f283c22011-03-02 01:21:46 +00003365 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003366 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00003367 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003368 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinnera5c68c32011-03-02 01:03:14 +00003369 }
Victor Stinner37296e82010-06-10 13:36:23 +00003370 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003371 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00003372 (strcmp(lower, "iso-8859-1") == 0))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003373 return _PyUnicode_AsLatin1String(unicode, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003374#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003375 else if (strcmp(lower, "mbcs") == 0)
3376 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003377#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003378 else if (strcmp(lower, "ascii") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003379 return _PyUnicode_AsASCIIString(unicode, errors);
Victor Stinner37296e82010-06-10 13:36:23 +00003380 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003381
3382 /* Encode via the codec registry */
3383 v = PyCodec_Encode(unicode, encoding, errors);
3384 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003385 return NULL;
3386
3387 /* The normal path */
3388 if (PyBytes_Check(v))
3389 return v;
3390
3391 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003392 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003393 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003394 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003395
3396 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
3397 "encoder %s returned bytearray instead of bytes",
3398 encoding);
3399 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003400 Py_DECREF(v);
3401 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003402 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003403
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003404 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3405 Py_DECREF(v);
3406 return b;
3407 }
3408
3409 PyErr_Format(PyExc_TypeError,
3410 "encoder did not return a bytes object (type=%.400s)",
3411 Py_TYPE(v)->tp_name);
3412 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003413 return NULL;
3414}
3415
Alexander Belopolsky40018472011-02-26 01:02:56 +00003416PyObject *
3417PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003418 const char *encoding,
3419 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003420{
3421 PyObject *v;
3422
3423 if (!PyUnicode_Check(unicode)) {
3424 PyErr_BadArgument();
3425 goto onError;
3426 }
3427
3428 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003429 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003430
3431 /* Encode via the codec registry */
3432 v = PyCodec_Encode(unicode, encoding, errors);
3433 if (v == NULL)
3434 goto onError;
3435 if (!PyUnicode_Check(v)) {
3436 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003437 "encoder did not return an str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003438 Py_TYPE(v)->tp_name);
3439 Py_DECREF(v);
3440 goto onError;
3441 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003442 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003443
Benjamin Peterson29060642009-01-31 22:14:21 +00003444 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003445 return NULL;
3446}
3447
Victor Stinner2f197072011-12-17 07:08:30 +01003448static size_t
3449mbstowcs_errorpos(const char *str, size_t len)
3450{
3451#ifdef HAVE_MBRTOWC
3452 const char *start = str;
3453 mbstate_t mbs;
3454 size_t converted;
3455 wchar_t ch;
3456
3457 memset(&mbs, 0, sizeof mbs);
3458 while (len)
3459 {
3460 converted = mbrtowc(&ch, (char*)str, len, &mbs);
3461 if (converted == 0)
3462 /* Reached end of string */
3463 break;
3464 if (converted == (size_t)-1 || converted == (size_t)-2) {
3465 /* Conversion error or incomplete character */
3466 return str - start;
3467 }
3468 else {
3469 str += converted;
3470 len -= converted;
3471 }
3472 }
3473 /* failed to find the undecodable byte sequence */
3474 return 0;
3475#endif
3476 return 0;
3477}
3478
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003479PyObject*
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003480PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
Victor Stinner1b579672011-12-17 05:47:23 +01003481 const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003482{
3483 wchar_t smallbuf[256];
3484 size_t smallbuf_len = Py_ARRAY_LENGTH(smallbuf);
3485 wchar_t *wstr;
3486 size_t wlen, wlen2;
3487 PyObject *unicode;
Victor Stinner1b579672011-12-17 05:47:23 +01003488 int surrogateescape;
Victor Stinner2f197072011-12-17 07:08:30 +01003489 size_t error_pos;
3490 char *errmsg;
3491 PyObject *reason, *exc;
Victor Stinner1b579672011-12-17 05:47:23 +01003492
3493 if (locale_error_handler(errors, &surrogateescape) < 0)
3494 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003495
3496 if (str[len] != '\0' || len != strlen(str)) {
3497 PyErr_SetString(PyExc_TypeError, "embedded null character");
3498 return NULL;
3499 }
3500
3501 if (surrogateescape)
3502 {
3503 wstr = _Py_char2wchar(str, &wlen);
3504 if (wstr == NULL) {
3505 if (wlen == (size_t)-1)
3506 PyErr_NoMemory();
3507 else
3508 PyErr_SetFromErrno(PyExc_OSError);
3509 return NULL;
3510 }
3511
3512 unicode = PyUnicode_FromWideChar(wstr, wlen);
3513 PyMem_Free(wstr);
3514 }
3515 else {
3516#ifndef HAVE_BROKEN_MBSTOWCS
3517 wlen = mbstowcs(NULL, str, 0);
3518#else
3519 wlen = len;
3520#endif
Victor Stinner2f197072011-12-17 07:08:30 +01003521 if (wlen == (size_t)-1)
3522 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003523 if (wlen+1 <= smallbuf_len) {
3524 wstr = smallbuf;
3525 }
3526 else {
3527 if (wlen > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1)
3528 return PyErr_NoMemory();
3529
3530 wstr = PyMem_Malloc((wlen+1) * sizeof(wchar_t));
3531 if (!wstr)
3532 return PyErr_NoMemory();
3533 }
3534
3535 /* This shouldn't fail now */
3536 wlen2 = mbstowcs(wstr, str, wlen+1);
3537 if (wlen2 == (size_t)-1) {
3538 if (wstr != smallbuf)
3539 PyMem_Free(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003540 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003541 }
3542#ifdef HAVE_BROKEN_MBSTOWCS
3543 assert(wlen2 == wlen);
3544#endif
3545 unicode = PyUnicode_FromWideChar(wstr, wlen2);
3546 if (wstr != smallbuf)
3547 PyMem_Free(wstr);
3548 }
3549 return unicode;
Victor Stinner2f197072011-12-17 07:08:30 +01003550
3551decode_error:
3552 errmsg = strerror(errno);
3553 assert(errmsg != NULL);
3554
3555 error_pos = mbstowcs_errorpos(str, len);
3556 if (errmsg != NULL) {
3557 size_t errlen;
3558 wstr = _Py_char2wchar(errmsg, &errlen);
3559 if (wstr != NULL) {
3560 reason = PyUnicode_FromWideChar(wstr, errlen);
3561 PyMem_Free(wstr);
3562 } else
3563 errmsg = NULL;
3564 }
3565 if (errmsg == NULL)
3566 reason = PyUnicode_FromString(
3567 "mbstowcs() encountered an invalid multibyte sequence");
3568 if (reason == NULL)
3569 return NULL;
3570
3571 exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nnO",
3572 "locale", str, len,
3573 (Py_ssize_t)error_pos,
3574 (Py_ssize_t)(error_pos+1),
3575 reason);
3576 Py_DECREF(reason);
3577 if (exc != NULL) {
3578 PyCodec_StrictErrors(exc);
3579 Py_XDECREF(exc);
3580 }
3581 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003582}
3583
3584PyObject*
Victor Stinner1b579672011-12-17 05:47:23 +01003585PyUnicode_DecodeLocale(const char *str, const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003586{
3587 Py_ssize_t size = (Py_ssize_t)strlen(str);
Victor Stinner1b579672011-12-17 05:47:23 +01003588 return PyUnicode_DecodeLocaleAndSize(str, size, errors);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003589}
3590
3591
3592PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003593PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003594 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003595 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3596}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003597
Christian Heimes5894ba72007-11-04 11:43:14 +00003598PyObject*
3599PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3600{
Victor Stinner99b95382011-07-04 14:23:54 +02003601#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003602 return PyUnicode_DecodeMBCS(s, size, NULL);
3603#elif defined(__APPLE__)
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003604 return PyUnicode_DecodeUTF8Stateful(s, size, "surrogateescape", NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003605#else
Victor Stinner793b5312011-04-27 00:24:21 +02003606 PyInterpreterState *interp = PyThreadState_GET()->interp;
3607 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3608 cannot use it to encode and decode filenames before it is loaded. Load
3609 the Python codec requires to encode at least its own filename. Use the C
3610 version of the locale codec until the codec registry is initialized and
3611 the Python codec is loaded.
3612
3613 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3614 cannot only rely on it: check also interp->fscodec_initialized for
3615 subinterpreters. */
3616 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003617 return PyUnicode_Decode(s, size,
3618 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00003619 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003620 }
3621 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003622 return PyUnicode_DecodeLocaleAndSize(s, size, "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003623 }
Victor Stinnerad158722010-10-27 00:25:46 +00003624#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003625}
3626
Martin v. Löwis011e8422009-05-05 04:43:17 +00003627
3628int
Antoine Pitrou13348842012-01-29 18:36:34 +01003629_PyUnicode_HasNULChars(PyObject* s)
3630{
3631 static PyObject *nul = NULL;
3632
3633 if (nul == NULL)
3634 nul = PyUnicode_FromStringAndSize("\0", 1);
3635 if (nul == NULL)
3636 return -1;
3637 return PyUnicode_Contains(s, nul);
3638}
3639
3640
3641int
Martin v. Löwis011e8422009-05-05 04:43:17 +00003642PyUnicode_FSConverter(PyObject* arg, void* addr)
3643{
3644 PyObject *output = NULL;
3645 Py_ssize_t size;
3646 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003647 if (arg == NULL) {
3648 Py_DECREF(*(PyObject**)addr);
3649 return 1;
3650 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00003651 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00003652 output = arg;
3653 Py_INCREF(output);
3654 }
3655 else {
3656 arg = PyUnicode_FromObject(arg);
3657 if (!arg)
3658 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00003659 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003660 Py_DECREF(arg);
3661 if (!output)
3662 return 0;
3663 if (!PyBytes_Check(output)) {
3664 Py_DECREF(output);
3665 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
3666 return 0;
3667 }
3668 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00003669 size = PyBytes_GET_SIZE(output);
3670 data = PyBytes_AS_STRING(output);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003671 if (size != strlen(data)) {
Benjamin Peterson7a6b44a2011-08-18 13:51:47 -05003672 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003673 Py_DECREF(output);
3674 return 0;
3675 }
3676 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003677 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003678}
3679
3680
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003681int
3682PyUnicode_FSDecoder(PyObject* arg, void* addr)
3683{
3684 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003685 if (arg == NULL) {
3686 Py_DECREF(*(PyObject**)addr);
3687 return 1;
3688 }
3689 if (PyUnicode_Check(arg)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05003690 if (PyUnicode_READY(arg) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003691 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003692 output = arg;
3693 Py_INCREF(output);
3694 }
3695 else {
3696 arg = PyBytes_FromObject(arg);
3697 if (!arg)
3698 return 0;
3699 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
3700 PyBytes_GET_SIZE(arg));
3701 Py_DECREF(arg);
3702 if (!output)
3703 return 0;
3704 if (!PyUnicode_Check(output)) {
3705 Py_DECREF(output);
3706 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
3707 return 0;
3708 }
3709 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05003710 if (PyUnicode_READY(output) == -1) {
Victor Stinner065836e2011-10-27 01:56:33 +02003711 Py_DECREF(output);
3712 return 0;
3713 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003714 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003715 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003716 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3717 Py_DECREF(output);
3718 return 0;
3719 }
3720 *(PyObject**)addr = output;
3721 return Py_CLEANUP_SUPPORTED;
3722}
3723
3724
Martin v. Löwis5b222132007-06-10 09:51:05 +00003725char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003726PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003727{
Christian Heimesf3863112007-11-22 07:46:41 +00003728 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003729
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003730 if (!PyUnicode_Check(unicode)) {
3731 PyErr_BadArgument();
3732 return NULL;
3733 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003734 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003735 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003736
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003737 if (PyUnicode_UTF8(unicode) == NULL) {
3738 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003739 bytes = _PyUnicode_AsUTF8String(unicode, "strict");
3740 if (bytes == NULL)
3741 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003742 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3743 if (_PyUnicode_UTF8(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003744 Py_DECREF(bytes);
3745 return NULL;
3746 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003747 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
3748 Py_MEMCPY(_PyUnicode_UTF8(unicode),
3749 PyBytes_AS_STRING(bytes),
3750 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003751 Py_DECREF(bytes);
3752 }
3753
3754 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003755 *psize = PyUnicode_UTF8_LENGTH(unicode);
3756 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003757}
3758
3759char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003760PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003761{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003762 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3763}
3764
3765#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +02003766static int unicode_as_unicode_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003767#endif
3768
3769
3770Py_UNICODE *
3771PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3772{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003773 const unsigned char *one_byte;
3774#if SIZEOF_WCHAR_T == 4
3775 const Py_UCS2 *two_bytes;
3776#else
3777 const Py_UCS4 *four_bytes;
3778 const Py_UCS4 *ucs4_end;
3779 Py_ssize_t num_surrogates;
3780#endif
3781 wchar_t *w;
3782 wchar_t *wchar_end;
3783
3784 if (!PyUnicode_Check(unicode)) {
3785 PyErr_BadArgument();
3786 return NULL;
3787 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003788 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003789 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003790 assert(_PyUnicode_KIND(unicode) != 0);
3791 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003792
3793#ifdef Py_DEBUG
3794 ++unicode_as_unicode_calls;
3795#endif
3796
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003797 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003798#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003799 four_bytes = PyUnicode_4BYTE_DATA(unicode);
3800 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003801 num_surrogates = 0;
3802
3803 for (; four_bytes < ucs4_end; ++four_bytes) {
3804 if (*four_bytes > 0xFFFF)
3805 ++num_surrogates;
3806 }
3807
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003808 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
3809 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
3810 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003811 PyErr_NoMemory();
3812 return NULL;
3813 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003814 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003815
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003816 w = _PyUnicode_WSTR(unicode);
3817 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
3818 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003819 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3820 if (*four_bytes > 0xFFFF) {
Victor Stinner8faf8212011-12-08 22:14:11 +01003821 assert(*four_bytes <= MAX_UNICODE);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003822 /* encode surrogate pair in this case */
Victor Stinner551ac952011-11-29 22:58:13 +01003823 *w++ = Py_UNICODE_HIGH_SURROGATE(*four_bytes);
3824 *w = Py_UNICODE_LOW_SURROGATE(*four_bytes);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003825 }
3826 else
3827 *w = *four_bytes;
3828
3829 if (w > wchar_end) {
3830 assert(0 && "Miscalculated string end");
3831 }
3832 }
3833 *w = 0;
3834#else
3835 /* sizeof(wchar_t) == 4 */
3836 Py_FatalError("Impossible unicode object state, wstr and str "
3837 "should share memory already.");
3838 return NULL;
3839#endif
3840 }
3841 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003842 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3843 (_PyUnicode_LENGTH(unicode) + 1));
3844 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003845 PyErr_NoMemory();
3846 return NULL;
3847 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003848 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
3849 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
3850 w = _PyUnicode_WSTR(unicode);
3851 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003852
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003853 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3854 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003855 for (; w < wchar_end; ++one_byte, ++w)
3856 *w = *one_byte;
3857 /* null-terminate the wstr */
3858 *w = 0;
3859 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003860 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003861#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003862 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003863 for (; w < wchar_end; ++two_bytes, ++w)
3864 *w = *two_bytes;
3865 /* null-terminate the wstr */
3866 *w = 0;
3867#else
3868 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003869 PyObject_FREE(_PyUnicode_WSTR(unicode));
3870 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003871 Py_FatalError("Impossible unicode object state, wstr "
3872 "and str should share memory already.");
3873 return NULL;
3874#endif
3875 }
3876 else {
3877 assert(0 && "This should never happen.");
3878 }
3879 }
3880 }
3881 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003882 *size = PyUnicode_WSTR_LENGTH(unicode);
3883 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00003884}
3885
Alexander Belopolsky40018472011-02-26 01:02:56 +00003886Py_UNICODE *
3887PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003888{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003889 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003890}
3891
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003892
Alexander Belopolsky40018472011-02-26 01:02:56 +00003893Py_ssize_t
3894PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003895{
3896 if (!PyUnicode_Check(unicode)) {
3897 PyErr_BadArgument();
3898 goto onError;
3899 }
3900 return PyUnicode_GET_SIZE(unicode);
3901
Benjamin Peterson29060642009-01-31 22:14:21 +00003902 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003903 return -1;
3904}
3905
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003906Py_ssize_t
3907PyUnicode_GetLength(PyObject *unicode)
3908{
Victor Stinner5a706cf2011-10-02 00:36:53 +02003909 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003910 PyErr_BadArgument();
3911 return -1;
3912 }
3913
3914 return PyUnicode_GET_LENGTH(unicode);
3915}
3916
3917Py_UCS4
3918PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
3919{
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003920 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
3921 PyErr_BadArgument();
3922 return (Py_UCS4)-1;
3923 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01003924 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003925 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003926 return (Py_UCS4)-1;
3927 }
3928 return PyUnicode_READ_CHAR(unicode, index);
3929}
3930
3931int
3932PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
3933{
3934 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003935 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003936 return -1;
3937 }
Victor Stinner488fa492011-12-12 00:01:39 +01003938 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01003939 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003940 PyErr_SetString(PyExc_IndexError, "string index out of range");
3941 return -1;
3942 }
Victor Stinner488fa492011-12-12 00:01:39 +01003943 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02003944 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003945 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
3946 index, ch);
3947 return 0;
3948}
3949
Alexander Belopolsky40018472011-02-26 01:02:56 +00003950const char *
3951PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00003952{
Victor Stinner42cb4622010-09-01 19:39:01 +00003953 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00003954}
3955
Victor Stinner554f3f02010-06-16 23:33:54 +00003956/* create or adjust a UnicodeDecodeError */
3957static void
3958make_decode_exception(PyObject **exceptionObject,
3959 const char *encoding,
3960 const char *input, Py_ssize_t length,
3961 Py_ssize_t startpos, Py_ssize_t endpos,
3962 const char *reason)
3963{
3964 if (*exceptionObject == NULL) {
3965 *exceptionObject = PyUnicodeDecodeError_Create(
3966 encoding, input, length, startpos, endpos, reason);
3967 }
3968 else {
3969 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
3970 goto onError;
3971 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
3972 goto onError;
3973 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
3974 goto onError;
3975 }
3976 return;
3977
3978onError:
3979 Py_DECREF(*exceptionObject);
3980 *exceptionObject = NULL;
3981}
3982
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003983/* error handling callback helper:
3984 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00003985 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003986 and adjust various state variables.
3987 return 0 on success, -1 on error
3988*/
3989
Alexander Belopolsky40018472011-02-26 01:02:56 +00003990static int
3991unicode_decode_call_errorhandler(const char *errors, PyObject **errorHandler,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003992 const char *encoding, const char *reason,
3993 const char **input, const char **inend, Py_ssize_t *startinpos,
3994 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003995 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003996{
Benjamin Peterson142957c2008-07-04 19:55:29 +00003997 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003998
3999 PyObject *restuple = NULL;
4000 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01004001 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004002 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004003 Py_ssize_t requiredsize;
4004 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004005 PyObject *inputobj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004006 int res = -1;
4007
Victor Stinner596a6c42011-11-09 00:02:18 +01004008 if (_PyUnicode_KIND(*output) != PyUnicode_WCHAR_KIND)
4009 outsize = PyUnicode_GET_LENGTH(*output);
4010 else
4011 outsize = _PyUnicode_WSTR_LENGTH(*output);
4012
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004013 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004014 *errorHandler = PyCodec_LookupError(errors);
4015 if (*errorHandler == NULL)
4016 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004017 }
4018
Victor Stinner554f3f02010-06-16 23:33:54 +00004019 make_decode_exception(exceptionObject,
4020 encoding,
4021 *input, *inend - *input,
4022 *startinpos, *endinpos,
4023 reason);
4024 if (*exceptionObject == NULL)
4025 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004026
4027 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4028 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004029 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004030 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00004031 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004032 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004033 }
4034 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004035 goto onError;
Benjamin Petersonbac79492012-01-14 13:34:47 -05004036 if (PyUnicode_READY(repunicode) == -1)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004037 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004038
4039 /* Copy back the bytes variables, which might have been modified by the
4040 callback */
4041 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4042 if (!inputobj)
4043 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00004044 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004045 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00004046 }
Christian Heimes72b710a2008-05-26 13:28:38 +00004047 *input = PyBytes_AS_STRING(inputobj);
4048 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004049 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00004050 /* we can DECREF safely, as the exception has another reference,
4051 so the object won't go away. */
4052 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004053
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004054 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004055 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004056 if (newpos<0 || newpos>insize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004057 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
4058 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004059 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004060
Victor Stinner596a6c42011-11-09 00:02:18 +01004061 if (_PyUnicode_KIND(*output) != PyUnicode_WCHAR_KIND) {
4062 /* need more space? (at least enough for what we
4063 have+the replacement+the rest of the string (starting
4064 at the new input position), so we won't have to check space
4065 when there are no errors in the rest of the string) */
4066 Py_ssize_t replen = PyUnicode_GET_LENGTH(repunicode);
4067 requiredsize = *outpos + replen + insize-newpos;
4068 if (requiredsize > outsize) {
4069 if (requiredsize<2*outsize)
4070 requiredsize = 2*outsize;
4071 if (unicode_resize(output, requiredsize) < 0)
4072 goto onError;
4073 }
4074 if (unicode_widen(output, PyUnicode_MAX_CHAR_VALUE(repunicode)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004075 goto onError;
Victor Stinner596a6c42011-11-09 00:02:18 +01004076 copy_characters(*output, *outpos, repunicode, 0, replen);
4077 *outpos += replen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004078 }
Victor Stinner596a6c42011-11-09 00:02:18 +01004079 else {
4080 wchar_t *repwstr;
4081 Py_ssize_t repwlen;
4082 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4083 if (repwstr == NULL)
4084 goto onError;
4085 /* need more space? (at least enough for what we
4086 have+the replacement+the rest of the string (starting
4087 at the new input position), so we won't have to check space
4088 when there are no errors in the rest of the string) */
4089 requiredsize = *outpos + repwlen + insize-newpos;
4090 if (requiredsize > outsize) {
4091 if (requiredsize < 2*outsize)
4092 requiredsize = 2*outsize;
4093 if (unicode_resize(output, requiredsize) < 0)
4094 goto onError;
4095 }
4096 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
4097 *outpos += repwlen;
4098 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004099 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004100 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004101
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004102 /* we made it! */
4103 res = 0;
4104
Benjamin Peterson29060642009-01-31 22:14:21 +00004105 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004106 Py_XDECREF(restuple);
4107 return res;
4108}
4109
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004110/* --- UTF-7 Codec -------------------------------------------------------- */
4111
Antoine Pitrou244651a2009-05-04 18:56:13 +00004112/* See RFC2152 for details. We encode conservatively and decode liberally. */
4113
4114/* Three simple macros defining base-64. */
4115
4116/* Is c a base-64 character? */
4117
4118#define IS_BASE64(c) \
4119 (((c) >= 'A' && (c) <= 'Z') || \
4120 ((c) >= 'a' && (c) <= 'z') || \
4121 ((c) >= '0' && (c) <= '9') || \
4122 (c) == '+' || (c) == '/')
4123
4124/* given that c is a base-64 character, what is its base-64 value? */
4125
4126#define FROM_BASE64(c) \
4127 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4128 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4129 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4130 (c) == '+' ? 62 : 63)
4131
4132/* What is the base-64 character of the bottom 6 bits of n? */
4133
4134#define TO_BASE64(n) \
4135 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4136
4137/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4138 * decoded as itself. We are permissive on decoding; the only ASCII
4139 * byte not decoding to itself is the + which begins a base64
4140 * string. */
4141
4142#define DECODE_DIRECT(c) \
4143 ((c) <= 127 && (c) != '+')
4144
4145/* The UTF-7 encoder treats ASCII characters differently according to
4146 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4147 * the above). See RFC2152. This array identifies these different
4148 * sets:
4149 * 0 : "Set D"
4150 * alphanumeric and '(),-./:?
4151 * 1 : "Set O"
4152 * !"#$%&*;<=>@[]^_`{|}
4153 * 2 : "whitespace"
4154 * ht nl cr sp
4155 * 3 : special (must be base64 encoded)
4156 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4157 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004158
Tim Petersced69f82003-09-16 20:30:58 +00004159static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004160char utf7_category[128] = {
4161/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4162 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4163/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4164 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4165/* sp ! " # $ % & ' ( ) * + , - . / */
4166 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4167/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4168 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4169/* @ A B C D E F G H I J K L M N O */
4170 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4171/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4172 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4173/* ` a b c d e f g h i j k l m n o */
4174 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4175/* p q r s t u v w x y z { | } ~ del */
4176 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004177};
4178
Antoine Pitrou244651a2009-05-04 18:56:13 +00004179/* ENCODE_DIRECT: this character should be encoded as itself. The
4180 * answer depends on whether we are encoding set O as itself, and also
4181 * on whether we are encoding whitespace as itself. RFC2152 makes it
4182 * clear that the answers to these questions vary between
4183 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004184
Antoine Pitrou244651a2009-05-04 18:56:13 +00004185#define ENCODE_DIRECT(c, directO, directWS) \
4186 ((c) < 128 && (c) > 0 && \
4187 ((utf7_category[(c)] == 0) || \
4188 (directWS && (utf7_category[(c)] == 2)) || \
4189 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004190
Alexander Belopolsky40018472011-02-26 01:02:56 +00004191PyObject *
4192PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004193 Py_ssize_t size,
4194 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004195{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004196 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4197}
4198
Antoine Pitrou244651a2009-05-04 18:56:13 +00004199/* The decoder. The only state we preserve is our read position,
4200 * i.e. how many characters we have consumed. So if we end in the
4201 * middle of a shift sequence we have to back off the read position
4202 * and the output to the beginning of the sequence, otherwise we lose
4203 * all the shift state (seen bits, number of bits seen, high
4204 * surrogate). */
4205
Alexander Belopolsky40018472011-02-26 01:02:56 +00004206PyObject *
4207PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004208 Py_ssize_t size,
4209 const char *errors,
4210 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004211{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004212 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004213 Py_ssize_t startinpos;
4214 Py_ssize_t endinpos;
4215 Py_ssize_t outpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004216 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004217 PyObject *unicode;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004218 const char *errmsg = "";
4219 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004220 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004221 unsigned int base64bits = 0;
4222 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004223 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004224 PyObject *errorHandler = NULL;
4225 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004226
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004227 /* Start off assuming it's all ASCII. Widen later as necessary. */
4228 unicode = PyUnicode_New(size, 127);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004229 if (!unicode)
4230 return NULL;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004231 if (size == 0) {
4232 if (consumed)
4233 *consumed = 0;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004234 return unicode;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004235 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004236
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004237 shiftOutStart = outpos = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004238 e = s + size;
4239
4240 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004241 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004242 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004243 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004244
Antoine Pitrou244651a2009-05-04 18:56:13 +00004245 if (inShift) { /* in a base-64 section */
4246 if (IS_BASE64(ch)) { /* consume a base-64 character */
4247 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4248 base64bits += 6;
4249 s++;
4250 if (base64bits >= 16) {
4251 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004252 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004253 base64bits -= 16;
4254 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
4255 if (surrogate) {
4256 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004257 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4258 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004259 if (unicode_putchar(&unicode, &outpos, ch2) < 0)
4260 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004261 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004262 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004263 }
4264 else {
Antoine Pitrou78edf752011-11-15 01:44:16 +01004265 if (unicode_putchar(&unicode, &outpos, surrogate) < 0)
4266 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004267 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004268 }
4269 }
Victor Stinner551ac952011-11-29 22:58:13 +01004270 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004271 /* first surrogate */
4272 surrogate = outCh;
4273 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004274 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004275 if (unicode_putchar(&unicode, &outpos, outCh) < 0)
4276 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004277 }
4278 }
4279 }
4280 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004281 inShift = 0;
4282 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004283 if (surrogate) {
Antoine Pitrou78edf752011-11-15 01:44:16 +01004284 if (unicode_putchar(&unicode, &outpos, surrogate) < 0)
4285 goto onError;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004286 surrogate = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004287 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004288 if (base64bits > 0) { /* left-over bits */
4289 if (base64bits >= 6) {
4290 /* We've seen at least one base-64 character */
4291 errmsg = "partial character in shift sequence";
4292 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004293 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004294 else {
4295 /* Some bits remain; they should be zero */
4296 if (base64buffer != 0) {
4297 errmsg = "non-zero padding bits in shift sequence";
4298 goto utf7Error;
4299 }
4300 }
4301 }
4302 if (ch != '-') {
4303 /* '-' is absorbed; other terminating
4304 characters are preserved */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004305 if (unicode_putchar(&unicode, &outpos, ch) < 0)
4306 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004307 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004308 }
4309 }
4310 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004311 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004312 s++; /* consume '+' */
4313 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004314 s++;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004315 if (unicode_putchar(&unicode, &outpos, '+') < 0)
4316 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004317 }
4318 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004319 inShift = 1;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004320 shiftOutStart = outpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004321 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004322 }
4323 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004324 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004325 if (unicode_putchar(&unicode, &outpos, ch) < 0)
4326 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004327 s++;
4328 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004329 else {
4330 startinpos = s-starts;
4331 s++;
4332 errmsg = "unexpected special character";
4333 goto utf7Error;
4334 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004335 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004336utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004337 endinpos = s-starts;
4338 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00004339 errors, &errorHandler,
4340 "utf7", errmsg,
4341 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004342 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004343 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004344 }
4345
Antoine Pitrou244651a2009-05-04 18:56:13 +00004346 /* end of string */
4347
4348 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4349 /* if we're in an inconsistent state, that's an error */
4350 if (surrogate ||
4351 (base64bits >= 6) ||
4352 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004353 endinpos = size;
4354 if (unicode_decode_call_errorhandler(
4355 errors, &errorHandler,
4356 "utf7", "unterminated shift sequence",
4357 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004358 &unicode, &outpos))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004359 goto onError;
4360 if (s < e)
4361 goto restart;
4362 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004363 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004364
4365 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004366 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004367 if (inShift) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004368 outpos = shiftOutStart; /* back off output */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004369 *consumed = startinpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004370 }
4371 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004372 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004373 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004374 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004375
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004376 if (unicode_resize(&unicode, outpos) < 0)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004377 goto onError;
4378
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004379 Py_XDECREF(errorHandler);
4380 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01004381 return unicode_result(unicode);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004382
Benjamin Peterson29060642009-01-31 22:14:21 +00004383 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004384 Py_XDECREF(errorHandler);
4385 Py_XDECREF(exc);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004386 Py_DECREF(unicode);
4387 return NULL;
4388}
4389
4390
Alexander Belopolsky40018472011-02-26 01:02:56 +00004391PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004392_PyUnicode_EncodeUTF7(PyObject *str,
4393 int base64SetO,
4394 int base64WhiteSpace,
4395 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004396{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004397 int kind;
4398 void *data;
4399 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004400 PyObject *v;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004401 Py_ssize_t allocated;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004402 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004403 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004404 unsigned int base64bits = 0;
4405 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004406 char * out;
4407 char * start;
4408
Benjamin Petersonbac79492012-01-14 13:34:47 -05004409 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004410 return NULL;
4411 kind = PyUnicode_KIND(str);
4412 data = PyUnicode_DATA(str);
4413 len = PyUnicode_GET_LENGTH(str);
4414
4415 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004416 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004417
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004418 /* It might be possible to tighten this worst case */
4419 allocated = 8 * len;
4420 if (allocated / 8 != len)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004421 return PyErr_NoMemory();
4422
Antoine Pitrou244651a2009-05-04 18:56:13 +00004423 v = PyBytes_FromStringAndSize(NULL, allocated);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004424 if (v == NULL)
4425 return NULL;
4426
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004427 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004428 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004429 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004430
Antoine Pitrou244651a2009-05-04 18:56:13 +00004431 if (inShift) {
4432 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4433 /* shifting out */
4434 if (base64bits) { /* output remaining bits */
4435 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4436 base64buffer = 0;
4437 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004438 }
4439 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004440 /* Characters not in the BASE64 set implicitly unshift the sequence
4441 so no '-' is required, except if the character is itself a '-' */
4442 if (IS_BASE64(ch) || ch == '-') {
4443 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004444 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004445 *out++ = (char) ch;
4446 }
4447 else {
4448 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004449 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004450 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004451 else { /* not in a shift sequence */
4452 if (ch == '+') {
4453 *out++ = '+';
4454 *out++ = '-';
4455 }
4456 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4457 *out++ = (char) ch;
4458 }
4459 else {
4460 *out++ = '+';
4461 inShift = 1;
4462 goto encode_char;
4463 }
4464 }
4465 continue;
4466encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004467 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004468 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004469
Antoine Pitrou244651a2009-05-04 18:56:13 +00004470 /* code first surrogate */
4471 base64bits += 16;
4472 base64buffer = (base64buffer << 16) | 0xd800 | ((ch-0x10000) >> 10);
4473 while (base64bits >= 6) {
4474 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4475 base64bits -= 6;
4476 }
4477 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004478 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004479 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004480 base64bits += 16;
4481 base64buffer = (base64buffer << 16) | ch;
4482 while (base64bits >= 6) {
4483 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4484 base64bits -= 6;
4485 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004486 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004487 if (base64bits)
4488 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4489 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004490 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004491 if (_PyBytes_Resize(&v, out - start) < 0)
4492 return NULL;
4493 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004494}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004495PyObject *
4496PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4497 Py_ssize_t size,
4498 int base64SetO,
4499 int base64WhiteSpace,
4500 const char *errors)
4501{
4502 PyObject *result;
4503 PyObject *tmp = PyUnicode_FromUnicode(s, size);
4504 if (tmp == NULL)
4505 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004506 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004507 base64WhiteSpace, errors);
4508 Py_DECREF(tmp);
4509 return result;
4510}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004511
Antoine Pitrou244651a2009-05-04 18:56:13 +00004512#undef IS_BASE64
4513#undef FROM_BASE64
4514#undef TO_BASE64
4515#undef DECODE_DIRECT
4516#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004517
Guido van Rossumd57fd912000-03-10 22:53:23 +00004518/* --- UTF-8 Codec -------------------------------------------------------- */
4519
Tim Petersced69f82003-09-16 20:30:58 +00004520static
Guido van Rossumd57fd912000-03-10 22:53:23 +00004521char utf8_code_length[256] = {
Ezio Melotti57221d02010-07-01 07:32:02 +00004522 /* Map UTF-8 encoded prefix byte to sequence length. Zero means
4523 illegal prefix. See RFC 3629 for details */
4524 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 00-0F */
4525 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Victor Stinner4a2b7a12010-08-13 14:03:48 +00004526 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Guido van Rossumd57fd912000-03-10 22:53:23 +00004527 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4528 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4529 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4530 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Ezio Melotti57221d02010-07-01 07:32:02 +00004531 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 70-7F */
4532 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 +00004533 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4534 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
Ezio Melotti57221d02010-07-01 07:32:02 +00004535 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* B0-BF */
4536 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* C0-C1 + C2-CF */
4537 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* D0-DF */
4538 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* E0-EF */
4539 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 +00004540};
4541
Alexander Belopolsky40018472011-02-26 01:02:56 +00004542PyObject *
4543PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004544 Py_ssize_t size,
4545 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004546{
Walter Dörwald69652032004-09-07 20:24:22 +00004547 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4548}
4549
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004550#include "stringlib/ucs1lib.h"
4551#include "stringlib/codecs.h"
4552#include "stringlib/undef.h"
4553
4554#include "stringlib/ucs2lib.h"
4555#include "stringlib/codecs.h"
4556#include "stringlib/undef.h"
4557
4558#include "stringlib/ucs4lib.h"
4559#include "stringlib/codecs.h"
4560#include "stringlib/undef.h"
4561
Antoine Pitrouab868312009-01-10 15:40:25 +00004562/* Mask to check or force alignment of a pointer to C 'long' boundaries */
4563#define LONG_PTR_MASK (size_t) (SIZEOF_LONG - 1)
4564
4565/* Mask to quickly check whether a C 'long' contains a
4566 non-ASCII, UTF8-encoded char. */
4567#if (SIZEOF_LONG == 8)
4568# define ASCII_CHAR_MASK 0x8080808080808080L
4569#elif (SIZEOF_LONG == 4)
4570# define ASCII_CHAR_MASK 0x80808080L
4571#else
4572# error C 'long' size should be either 4 or 8!
4573#endif
4574
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004575/* Scans a UTF-8 string and returns the maximum character to be expected
4576 and the size of the decoded unicode string.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004577
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004578 This function doesn't check for errors, these checks are performed in
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004579 PyUnicode_DecodeUTF8Stateful.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004580 */
4581static Py_UCS4
Victor Stinnera1d12bb2011-12-11 21:53:09 +01004582utf8_scanner(const unsigned char *p, Py_ssize_t string_size, Py_ssize_t *unicode_size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004583{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004584 Py_ssize_t char_count = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004585 const unsigned char *end = p + string_size;
4586 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004587
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004588 assert(unicode_size != NULL);
4589
4590 /* By having a cascade of independent loops which fallback onto each
4591 other, we minimize the amount of work done in the average loop
4592 iteration, and we also maximize the CPU's ability to predict
4593 branches correctly (because a given condition will have always the
4594 same boolean outcome except perhaps in the last iteration of the
4595 corresponding loop).
4596 In the general case this brings us rather close to decoding
4597 performance pre-PEP 393, despite the two-pass decoding.
4598
4599 Note that the pure ASCII loop is not duplicated once a non-ASCII
4600 character has been encountered. It is actually a pessimization (by
4601 a significant factor) to use this loop on text with many non-ASCII
4602 characters, and it is important to avoid bad performance on valid
4603 utf-8 data (invalid utf-8 being a different can of worms).
4604 */
4605
4606 /* ASCII */
4607 for (; p < end; ++p) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004608 /* Only check value if it's not a ASCII char... */
4609 if (*p < 0x80) {
4610 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
4611 an explanation. */
4612 if (!((size_t) p & LONG_PTR_MASK)) {
4613 /* Help register allocation */
4614 register const unsigned char *_p = p;
4615 while (_p < aligned_end) {
4616 unsigned long value = *(unsigned long *) _p;
4617 if (value & ASCII_CHAR_MASK)
4618 break;
4619 _p += SIZEOF_LONG;
4620 char_count += SIZEOF_LONG;
4621 }
4622 p = _p;
4623 if (p == end)
4624 break;
4625 }
4626 }
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004627 if (*p < 0x80)
4628 ++char_count;
4629 else
4630 goto _ucs1loop;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004631 }
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004632 *unicode_size = char_count;
4633 return 127;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004634
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004635_ucs1loop:
4636 for (; p < end; ++p) {
4637 if (*p < 0xc4)
4638 char_count += ((*p & 0xc0) != 0x80);
4639 else
4640 goto _ucs2loop;
4641 }
4642 *unicode_size = char_count;
4643 return 255;
4644
4645_ucs2loop:
4646 for (; p < end; ++p) {
4647 if (*p < 0xf0)
4648 char_count += ((*p & 0xc0) != 0x80);
4649 else
4650 goto _ucs4loop;
4651 }
4652 *unicode_size = char_count;
4653 return 65535;
4654
4655_ucs4loop:
4656 for (; p < end; ++p) {
4657 char_count += ((*p & 0xc0) != 0x80);
4658 }
4659 *unicode_size = char_count;
4660 return 65537;
4661}
4662
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004663/* Similar to PyUnicode_WRITE but may attempt to widen and resize the string
Victor Stinner785938e2011-12-11 20:09:03 +01004664 in case of errors. Implicit parameters: unicode, kind, data, onError.
4665 Potential resizing overallocates, so the result needs to shrink at the end.
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004666*/
Victor Stinner785938e2011-12-11 20:09:03 +01004667#define WRITE_MAYBE_FAIL(index, value) \
4668 do { \
4669 Py_ssize_t pos = index; \
4670 if (pos > PyUnicode_GET_LENGTH(unicode) && \
4671 unicode_resize(&unicode, pos + pos/8) < 0) \
4672 goto onError; \
4673 if (unicode_putchar(&unicode, &pos, value) < 0) \
4674 goto onError; \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004675 } while (0)
4676
Victor Stinnerbf6e5602011-12-12 01:53:47 +01004677static PyObject *
Victor Stinner785938e2011-12-11 20:09:03 +01004678decode_utf8_errors(const char *starts,
4679 Py_ssize_t size,
4680 const char *errors,
4681 Py_ssize_t *consumed,
4682 const char *s,
4683 PyObject *unicode,
4684 Py_ssize_t i)
Walter Dörwald69652032004-09-07 20:24:22 +00004685{
Guido van Rossumd57fd912000-03-10 22:53:23 +00004686 int n;
Ezio Melotti57221d02010-07-01 07:32:02 +00004687 int k;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004688 Py_ssize_t startinpos;
4689 Py_ssize_t endinpos;
Victor Stinner785938e2011-12-11 20:09:03 +01004690 const char *e = starts + size;
4691 const char *aligned_end;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004692 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004693 PyObject *errorHandler = NULL;
4694 PyObject *exc = NULL;
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004695
Antoine Pitrouab868312009-01-10 15:40:25 +00004696 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004697
4698 while (s < e) {
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004699 Py_UCS4 ch = (unsigned char)*s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004700
4701 if (ch < 0x80) {
Antoine Pitrouab868312009-01-10 15:40:25 +00004702 /* Fast path for runs of ASCII characters. Given that common UTF-8
4703 input will consist of an overwhelming majority of ASCII
4704 characters, we try to optimize for this case by checking
4705 as many characters as a C 'long' can contain.
4706 First, check if we can do an aligned read, as most CPUs have
4707 a penalty for unaligned reads.
4708 */
4709 if (!((size_t) s & LONG_PTR_MASK)) {
4710 /* Help register allocation */
4711 register const char *_s = s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004712 register Py_ssize_t _i = i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004713 while (_s < aligned_end) {
4714 /* Read a whole long at a time (either 4 or 8 bytes),
4715 and do a fast unrolled copy if it only contains ASCII
4716 characters. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004717 unsigned long value = *(unsigned long *) _s;
4718 if (value & ASCII_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00004719 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004720 WRITE_MAYBE_FAIL(_i+0, _s[0]);
4721 WRITE_MAYBE_FAIL(_i+1, _s[1]);
4722 WRITE_MAYBE_FAIL(_i+2, _s[2]);
4723 WRITE_MAYBE_FAIL(_i+3, _s[3]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004724#if (SIZEOF_LONG == 8)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004725 WRITE_MAYBE_FAIL(_i+4, _s[4]);
4726 WRITE_MAYBE_FAIL(_i+5, _s[5]);
4727 WRITE_MAYBE_FAIL(_i+6, _s[6]);
4728 WRITE_MAYBE_FAIL(_i+7, _s[7]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004729#endif
4730 _s += SIZEOF_LONG;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004731 _i += SIZEOF_LONG;
Antoine Pitrouab868312009-01-10 15:40:25 +00004732 }
4733 s = _s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004734 i = _i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004735 if (s == e)
4736 break;
4737 ch = (unsigned char)*s;
4738 }
4739 }
4740
4741 if (ch < 0x80) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004742 WRITE_MAYBE_FAIL(i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004743 s++;
4744 continue;
4745 }
4746
4747 n = utf8_code_length[ch];
4748
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004749 if (s + n > e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004750 if (consumed)
4751 break;
4752 else {
4753 errmsg = "unexpected end of data";
4754 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004755 endinpos = startinpos+1;
4756 for (k=1; (k < size-startinpos) && ((s[k]&0xC0) == 0x80); k++)
4757 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004758 goto utf8Error;
4759 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00004760 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004761
4762 switch (n) {
4763
4764 case 0:
Ezio Melotti57221d02010-07-01 07:32:02 +00004765 errmsg = "invalid start byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004766 startinpos = s-starts;
4767 endinpos = startinpos+1;
4768 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004769
4770 case 1:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004771 errmsg = "internal error";
Benjamin Peterson29060642009-01-31 22:14:21 +00004772 startinpos = s-starts;
4773 endinpos = startinpos+1;
4774 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004775
4776 case 2:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004777 if ((s[1] & 0xc0) != 0x80) {
Ezio Melotti57221d02010-07-01 07:32:02 +00004778 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004779 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004780 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00004781 goto utf8Error;
4782 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004783 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004784 assert ((ch > 0x007F) && (ch <= 0x07FF));
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004785 WRITE_MAYBE_FAIL(i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004786 break;
4787
4788 case 3:
Ezio Melotti9bf2b3a2010-07-03 04:52:19 +00004789 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
4790 will result in surrogates in range d800-dfff. Surrogates are
4791 not valid UTF-8 so they are rejected.
4792 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
4793 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
Tim Petersced69f82003-09-16 20:30:58 +00004794 if ((s[1] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004795 (s[2] & 0xc0) != 0x80 ||
4796 ((unsigned char)s[0] == 0xE0 &&
4797 (unsigned char)s[1] < 0xA0) ||
4798 ((unsigned char)s[0] == 0xED &&
4799 (unsigned char)s[1] > 0x9F)) {
4800 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004801 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004802 endinpos = startinpos + 1;
4803
4804 /* if s[1] first two bits are 1 and 0, then the invalid
4805 continuation byte is s[2], so increment endinpos by 1,
4806 if not, s[1] is invalid and endinpos doesn't need to
4807 be incremented. */
4808 if ((s[1] & 0xC0) == 0x80)
4809 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004810 goto utf8Error;
4811 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004812 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004813 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004814 WRITE_MAYBE_FAIL(i++, ch);
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004815 break;
4816
4817 case 4:
4818 if ((s[1] & 0xc0) != 0x80 ||
4819 (s[2] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004820 (s[3] & 0xc0) != 0x80 ||
4821 ((unsigned char)s[0] == 0xF0 &&
4822 (unsigned char)s[1] < 0x90) ||
4823 ((unsigned char)s[0] == 0xF4 &&
4824 (unsigned char)s[1] > 0x8F)) {
4825 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004826 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004827 endinpos = startinpos + 1;
4828 if ((s[1] & 0xC0) == 0x80) {
4829 endinpos++;
4830 if ((s[2] & 0xC0) == 0x80)
4831 endinpos++;
4832 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004833 goto utf8Error;
4834 }
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004835 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
Ezio Melotti57221d02010-07-01 07:32:02 +00004836 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
Victor Stinner8faf8212011-12-08 22:14:11 +01004837 assert ((ch > 0xFFFF) && (ch <= MAX_UNICODE));
Ezio Melotti57221d02010-07-01 07:32:02 +00004838
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004839 WRITE_MAYBE_FAIL(i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004840 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004841 }
4842 s += n;
Benjamin Peterson29060642009-01-31 22:14:21 +00004843 continue;
Tim Petersced69f82003-09-16 20:30:58 +00004844
Benjamin Peterson29060642009-01-31 22:14:21 +00004845 utf8Error:
Benjamin Peterson29060642009-01-31 22:14:21 +00004846 if (unicode_decode_call_errorhandler(
4847 errors, &errorHandler,
Victor Stinnercbe01342012-02-14 01:17:45 +01004848 "utf-8", errmsg,
Benjamin Peterson29060642009-01-31 22:14:21 +00004849 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004850 &unicode, &i))
Benjamin Peterson29060642009-01-31 22:14:21 +00004851 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004852 /* Update data because unicode_decode_call_errorhandler might have
4853 re-created or resized the unicode object. */
Benjamin Peterson29060642009-01-31 22:14:21 +00004854 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004855 }
Walter Dörwald69652032004-09-07 20:24:22 +00004856 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00004857 *consumed = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004858
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004859 /* Adjust length and ready string when it contained errors and
4860 is of the old resizable kind. */
Victor Stinner785938e2011-12-11 20:09:03 +01004861 if (unicode_resize(&unicode, i) < 0)
4862 goto onError;
4863 unicode_adjust_maxchar(&unicode);
4864 if (unicode == NULL)
4865 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004866
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004867 Py_XDECREF(errorHandler);
4868 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02004869 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01004870 return unicode;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004871
Benjamin Peterson29060642009-01-31 22:14:21 +00004872 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004873 Py_XDECREF(errorHandler);
4874 Py_XDECREF(exc);
Victor Stinner785938e2011-12-11 20:09:03 +01004875 Py_XDECREF(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004876 return NULL;
4877}
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004878#undef WRITE_MAYBE_FAIL
Antoine Pitrouab868312009-01-10 15:40:25 +00004879
Victor Stinner785938e2011-12-11 20:09:03 +01004880PyObject *
4881PyUnicode_DecodeUTF8Stateful(const char *s,
4882 Py_ssize_t size,
4883 const char *errors,
4884 Py_ssize_t *consumed)
4885{
4886 Py_UCS4 maxchar = 0;
4887 Py_ssize_t unicode_size;
4888 int has_errors = 0;
4889 PyObject *unicode;
4890 int kind;
4891 void *data;
4892 const char *starts = s;
4893 const char *e;
4894 Py_ssize_t i;
4895
4896 if (size == 0) {
4897 if (consumed)
4898 *consumed = 0;
Victor Stinner382955f2011-12-11 21:44:00 +01004899 Py_INCREF(unicode_empty);
4900 return unicode_empty;
Victor Stinner785938e2011-12-11 20:09:03 +01004901 }
4902
Victor Stinnera1d12bb2011-12-11 21:53:09 +01004903 maxchar = utf8_scanner((const unsigned char *)s, size, &unicode_size);
Victor Stinner785938e2011-12-11 20:09:03 +01004904
4905 /* When the string is ASCII only, just use memcpy and return.
4906 unicode_size may be != size if there is an incomplete UTF-8
4907 sequence at the end of the ASCII block. */
4908 if (maxchar < 128 && size == unicode_size) {
4909 if (consumed)
4910 *consumed = size;
Victor Stinnerab870212011-12-17 22:39:43 +01004911 return unicode_fromascii((const unsigned char *)s, size);
Victor Stinner785938e2011-12-11 20:09:03 +01004912 }
4913
4914 unicode = PyUnicode_New(unicode_size, maxchar);
4915 if (!unicode)
4916 return NULL;
4917 kind = PyUnicode_KIND(unicode);
4918 data = PyUnicode_DATA(unicode);
4919
4920 /* Unpack UTF-8 encoded data */
4921 i = 0;
4922 e = starts + size;
4923 switch (kind) {
4924 case PyUnicode_1BYTE_KIND:
4925 has_errors = ucs1lib_utf8_try_decode(s, e, (Py_UCS1 *) data, &s, &i);
4926 break;
4927 case PyUnicode_2BYTE_KIND:
4928 has_errors = ucs2lib_utf8_try_decode(s, e, (Py_UCS2 *) data, &s, &i);
4929 break;
4930 case PyUnicode_4BYTE_KIND:
4931 has_errors = ucs4lib_utf8_try_decode(s, e, (Py_UCS4 *) data, &s, &i);
4932 break;
4933 }
4934 if (!has_errors) {
4935 /* Ensure the unicode size calculation was correct */
4936 assert(i == unicode_size);
4937 assert(s == e);
4938 if (consumed)
4939 *consumed = size;
4940 return unicode;
4941 }
4942
4943 /* In case of errors, maxchar and size computation might be incorrect;
4944 code below refits and resizes as necessary. */
4945 return decode_utf8_errors(starts, size, errors, consumed, s, unicode, i);
4946}
4947
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004948#ifdef __APPLE__
4949
4950/* Simplified UTF-8 decoder using surrogateescape error handler,
4951 used to decode the command line arguments on Mac OS X. */
4952
4953wchar_t*
4954_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4955{
4956 int n;
4957 const char *e;
4958 wchar_t *unicode, *p;
4959
4960 /* Note: size will always be longer than the resulting Unicode
4961 character count */
4962 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1)) {
4963 PyErr_NoMemory();
4964 return NULL;
4965 }
4966 unicode = PyMem_Malloc((size + 1) * sizeof(wchar_t));
4967 if (!unicode)
4968 return NULL;
4969
4970 /* Unpack UTF-8 encoded data */
4971 p = unicode;
4972 e = s + size;
4973 while (s < e) {
4974 Py_UCS4 ch = (unsigned char)*s;
4975
4976 if (ch < 0x80) {
4977 *p++ = (wchar_t)ch;
4978 s++;
4979 continue;
4980 }
4981
4982 n = utf8_code_length[ch];
4983 if (s + n > e) {
4984 goto surrogateescape;
4985 }
4986
4987 switch (n) {
4988 case 0:
4989 case 1:
4990 goto surrogateescape;
4991
4992 case 2:
4993 if ((s[1] & 0xc0) != 0x80)
4994 goto surrogateescape;
4995 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
4996 assert ((ch > 0x007F) && (ch <= 0x07FF));
4997 *p++ = (wchar_t)ch;
4998 break;
4999
5000 case 3:
5001 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
5002 will result in surrogates in range d800-dfff. Surrogates are
5003 not valid UTF-8 so they are rejected.
5004 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
5005 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
5006 if ((s[1] & 0xc0) != 0x80 ||
5007 (s[2] & 0xc0) != 0x80 ||
5008 ((unsigned char)s[0] == 0xE0 &&
5009 (unsigned char)s[1] < 0xA0) ||
5010 ((unsigned char)s[0] == 0xED &&
5011 (unsigned char)s[1] > 0x9F)) {
5012
5013 goto surrogateescape;
5014 }
5015 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
5016 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005017 *p++ = (wchar_t)ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005018 break;
5019
5020 case 4:
5021 if ((s[1] & 0xc0) != 0x80 ||
5022 (s[2] & 0xc0) != 0x80 ||
5023 (s[3] & 0xc0) != 0x80 ||
5024 ((unsigned char)s[0] == 0xF0 &&
5025 (unsigned char)s[1] < 0x90) ||
5026 ((unsigned char)s[0] == 0xF4 &&
5027 (unsigned char)s[1] > 0x8F)) {
5028 goto surrogateescape;
5029 }
5030 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
5031 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
Victor Stinner8faf8212011-12-08 22:14:11 +01005032 assert ((ch > 0xFFFF) && (ch <= MAX_UNICODE));
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005033
5034#if SIZEOF_WCHAR_T == 4
5035 *p++ = (wchar_t)ch;
5036#else
5037 /* compute and append the two surrogates: */
Victor Stinner551ac952011-11-29 22:58:13 +01005038 *p++ = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
5039 *p++ = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005040#endif
5041 break;
5042 }
5043 s += n;
5044 continue;
5045
5046 surrogateescape:
5047 *p++ = 0xDC00 + ch;
5048 s++;
5049 }
5050 *p = L'\0';
5051 return unicode;
5052}
5053
5054#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00005055
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005056/* Primary internal function which creates utf8 encoded bytes objects.
5057
5058 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00005059 and allocate exactly as much space needed at the end. Else allocate the
5060 maximum possible needed (4 result bytes per Unicode character), and return
5061 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00005062*/
Tim Peters7e3d9612002-04-21 03:26:37 +00005063PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01005064_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005065{
Victor Stinner6099a032011-12-18 14:22:26 +01005066 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005067 void *data;
5068 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00005069
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005070 if (!PyUnicode_Check(unicode)) {
5071 PyErr_BadArgument();
5072 return NULL;
5073 }
5074
5075 if (PyUnicode_READY(unicode) == -1)
5076 return NULL;
5077
Victor Stinnere90fe6a2011-10-01 16:48:13 +02005078 if (PyUnicode_UTF8(unicode))
5079 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
5080 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005081
5082 kind = PyUnicode_KIND(unicode);
5083 data = PyUnicode_DATA(unicode);
5084 size = PyUnicode_GET_LENGTH(unicode);
5085
Benjamin Petersonead6b532011-12-20 17:23:42 -06005086 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01005087 default:
5088 assert(0);
5089 case PyUnicode_1BYTE_KIND:
5090 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
5091 assert(!PyUnicode_IS_ASCII(unicode));
5092 return ucs1lib_utf8_encoder(unicode, data, size, errors);
5093 case PyUnicode_2BYTE_KIND:
5094 return ucs2lib_utf8_encoder(unicode, data, size, errors);
5095 case PyUnicode_4BYTE_KIND:
5096 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00005097 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005098}
5099
Alexander Belopolsky40018472011-02-26 01:02:56 +00005100PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005101PyUnicode_EncodeUTF8(const Py_UNICODE *s,
5102 Py_ssize_t size,
5103 const char *errors)
5104{
5105 PyObject *v, *unicode;
5106
5107 unicode = PyUnicode_FromUnicode(s, size);
5108 if (unicode == NULL)
5109 return NULL;
5110 v = _PyUnicode_AsUTF8String(unicode, errors);
5111 Py_DECREF(unicode);
5112 return v;
5113}
5114
5115PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005116PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005117{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005118 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005119}
5120
Walter Dörwald41980ca2007-08-16 21:55:45 +00005121/* --- UTF-32 Codec ------------------------------------------------------- */
5122
5123PyObject *
5124PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005125 Py_ssize_t size,
5126 const char *errors,
5127 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005128{
5129 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
5130}
5131
5132PyObject *
5133PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005134 Py_ssize_t size,
5135 const char *errors,
5136 int *byteorder,
5137 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005138{
5139 const char *starts = s;
5140 Py_ssize_t startinpos;
5141 Py_ssize_t endinpos;
5142 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005143 PyObject *unicode;
Mark Dickinson7db923c2010-06-12 09:10:14 +00005144 const unsigned char *q, *e;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005145 int bo = 0; /* assume native ordering by default */
5146 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00005147 /* Offsets from q for retrieving bytes in the right order. */
5148#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5149 int iorder[] = {0, 1, 2, 3};
5150#else
5151 int iorder[] = {3, 2, 1, 0};
5152#endif
5153 PyObject *errorHandler = NULL;
5154 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00005155
Walter Dörwald41980ca2007-08-16 21:55:45 +00005156 q = (unsigned char *)s;
5157 e = q + size;
5158
5159 if (byteorder)
5160 bo = *byteorder;
5161
5162 /* Check for BOM marks (U+FEFF) in the input and adjust current
5163 byte order setting accordingly. In native mode, the leading BOM
5164 mark is skipped, in all other modes, it is copied to the output
5165 stream as-is (giving a ZWNBSP character). */
5166 if (bo == 0) {
5167 if (size >= 4) {
5168 const Py_UCS4 bom = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
Benjamin Peterson29060642009-01-31 22:14:21 +00005169 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00005170#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00005171 if (bom == 0x0000FEFF) {
5172 q += 4;
5173 bo = -1;
5174 }
5175 else if (bom == 0xFFFE0000) {
5176 q += 4;
5177 bo = 1;
5178 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005179#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005180 if (bom == 0x0000FEFF) {
5181 q += 4;
5182 bo = 1;
5183 }
5184 else if (bom == 0xFFFE0000) {
5185 q += 4;
5186 bo = -1;
5187 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005188#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005189 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005190 }
5191
5192 if (bo == -1) {
5193 /* force LE */
5194 iorder[0] = 0;
5195 iorder[1] = 1;
5196 iorder[2] = 2;
5197 iorder[3] = 3;
5198 }
5199 else if (bo == 1) {
5200 /* force BE */
5201 iorder[0] = 3;
5202 iorder[1] = 2;
5203 iorder[2] = 1;
5204 iorder[3] = 0;
5205 }
5206
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005207 /* This might be one to much, because of a BOM */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005208 unicode = PyUnicode_New((size+3)/4, 127);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005209 if (!unicode)
5210 return NULL;
5211 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005212 return unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005213 outpos = 0;
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005214
Walter Dörwald41980ca2007-08-16 21:55:45 +00005215 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005216 Py_UCS4 ch;
5217 /* remaining bytes at the end? (size should be divisible by 4) */
5218 if (e-q<4) {
5219 if (consumed)
5220 break;
5221 errmsg = "truncated data";
5222 startinpos = ((const char *)q)-starts;
5223 endinpos = ((const char *)e)-starts;
5224 goto utf32Error;
5225 /* The remaining input chars are ignored if the callback
5226 chooses to skip the input */
5227 }
5228 ch = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
5229 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00005230
Benjamin Peterson29060642009-01-31 22:14:21 +00005231 if (ch >= 0x110000)
5232 {
5233 errmsg = "codepoint not in range(0x110000)";
5234 startinpos = ((const char *)q)-starts;
5235 endinpos = startinpos+4;
5236 goto utf32Error;
5237 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005238 if (unicode_putchar(&unicode, &outpos, ch) < 0)
5239 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005240 q += 4;
5241 continue;
5242 utf32Error:
Benjamin Peterson29060642009-01-31 22:14:21 +00005243 if (unicode_decode_call_errorhandler(
5244 errors, &errorHandler,
5245 "utf32", errmsg,
5246 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005247 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005248 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005249 }
5250
5251 if (byteorder)
5252 *byteorder = bo;
5253
5254 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005255 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005256
5257 /* Adjust length */
Victor Stinner16e6a802011-12-12 13:24:15 +01005258 if (unicode_resize(&unicode, outpos) < 0)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005259 goto onError;
5260
5261 Py_XDECREF(errorHandler);
5262 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005263 return unicode_result(unicode);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005264
Benjamin Peterson29060642009-01-31 22:14:21 +00005265 onError:
Walter Dörwald41980ca2007-08-16 21:55:45 +00005266 Py_DECREF(unicode);
5267 Py_XDECREF(errorHandler);
5268 Py_XDECREF(exc);
5269 return NULL;
5270}
5271
5272PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005273_PyUnicode_EncodeUTF32(PyObject *str,
5274 const char *errors,
5275 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005276{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005277 int kind;
5278 void *data;
5279 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005280 PyObject *v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005281 unsigned char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005282 Py_ssize_t nsize, bytesize, i;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005283 /* Offsets from p for storing byte pairs in the right order. */
5284#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5285 int iorder[] = {0, 1, 2, 3};
5286#else
5287 int iorder[] = {3, 2, 1, 0};
5288#endif
5289
Benjamin Peterson29060642009-01-31 22:14:21 +00005290#define STORECHAR(CH) \
5291 do { \
5292 p[iorder[3]] = ((CH) >> 24) & 0xff; \
5293 p[iorder[2]] = ((CH) >> 16) & 0xff; \
5294 p[iorder[1]] = ((CH) >> 8) & 0xff; \
5295 p[iorder[0]] = (CH) & 0xff; \
5296 p += 4; \
Walter Dörwald41980ca2007-08-16 21:55:45 +00005297 } while(0)
5298
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005299 if (!PyUnicode_Check(str)) {
5300 PyErr_BadArgument();
5301 return NULL;
5302 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005303 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005304 return NULL;
5305 kind = PyUnicode_KIND(str);
5306 data = PyUnicode_DATA(str);
5307 len = PyUnicode_GET_LENGTH(str);
5308
5309 nsize = len + (byteorder == 0);
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005310 bytesize = nsize * 4;
5311 if (bytesize / 4 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005312 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005313 v = PyBytes_FromStringAndSize(NULL, bytesize);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005314 if (v == NULL)
5315 return NULL;
5316
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005317 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005318 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005319 STORECHAR(0xFEFF);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005320 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005321 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005322
5323 if (byteorder == -1) {
5324 /* force LE */
5325 iorder[0] = 0;
5326 iorder[1] = 1;
5327 iorder[2] = 2;
5328 iorder[3] = 3;
5329 }
5330 else if (byteorder == 1) {
5331 /* force BE */
5332 iorder[0] = 3;
5333 iorder[1] = 2;
5334 iorder[2] = 1;
5335 iorder[3] = 0;
5336 }
5337
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005338 for (i = 0; i < len; i++)
5339 STORECHAR(PyUnicode_READ(kind, data, i));
Guido van Rossum98297ee2007-11-06 21:34:58 +00005340
5341 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005342 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005343#undef STORECHAR
5344}
5345
Alexander Belopolsky40018472011-02-26 01:02:56 +00005346PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005347PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5348 Py_ssize_t size,
5349 const char *errors,
5350 int byteorder)
5351{
5352 PyObject *result;
5353 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5354 if (tmp == NULL)
5355 return NULL;
5356 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5357 Py_DECREF(tmp);
5358 return result;
5359}
5360
5361PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005362PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005363{
Victor Stinnerb960b342011-11-20 19:12:52 +01005364 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005365}
5366
Guido van Rossumd57fd912000-03-10 22:53:23 +00005367/* --- UTF-16 Codec ------------------------------------------------------- */
5368
Tim Peters772747b2001-08-09 22:21:55 +00005369PyObject *
5370PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005371 Py_ssize_t size,
5372 const char *errors,
5373 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005374{
Walter Dörwald69652032004-09-07 20:24:22 +00005375 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5376}
5377
Antoine Pitrouab868312009-01-10 15:40:25 +00005378/* Two masks for fast checking of whether a C 'long' may contain
5379 UTF16-encoded surrogate characters. This is an efficient heuristic,
5380 assuming that non-surrogate characters with a code point >= 0x8000 are
5381 rare in most input.
5382 FAST_CHAR_MASK is used when the input is in native byte ordering,
5383 SWAPPED_FAST_CHAR_MASK when the input is in byteswapped ordering.
Benjamin Peterson29060642009-01-31 22:14:21 +00005384*/
Antoine Pitrouab868312009-01-10 15:40:25 +00005385#if (SIZEOF_LONG == 8)
5386# define FAST_CHAR_MASK 0x8000800080008000L
5387# define SWAPPED_FAST_CHAR_MASK 0x0080008000800080L
5388#elif (SIZEOF_LONG == 4)
5389# define FAST_CHAR_MASK 0x80008000L
5390# define SWAPPED_FAST_CHAR_MASK 0x00800080L
5391#else
5392# error C 'long' size should be either 4 or 8!
5393#endif
5394
Walter Dörwald69652032004-09-07 20:24:22 +00005395PyObject *
5396PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005397 Py_ssize_t size,
5398 const char *errors,
5399 int *byteorder,
5400 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005401{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005402 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005403 Py_ssize_t startinpos;
5404 Py_ssize_t endinpos;
5405 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005406 PyObject *unicode;
Antoine Pitrouab868312009-01-10 15:40:25 +00005407 const unsigned char *q, *e, *aligned_end;
Tim Peters772747b2001-08-09 22:21:55 +00005408 int bo = 0; /* assume native ordering by default */
Antoine Pitrouab868312009-01-10 15:40:25 +00005409 int native_ordering = 0;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005410 const char *errmsg = "";
Tim Peters772747b2001-08-09 22:21:55 +00005411 /* Offsets from q for retrieving byte pairs in the right order. */
5412#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5413 int ihi = 1, ilo = 0;
5414#else
5415 int ihi = 0, ilo = 1;
5416#endif
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005417 PyObject *errorHandler = NULL;
5418 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005419
5420 /* Note: size will always be longer than the resulting Unicode
5421 character count */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005422 unicode = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005423 if (!unicode)
5424 return NULL;
5425 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005426 return unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005427 outpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005428
Tim Peters772747b2001-08-09 22:21:55 +00005429 q = (unsigned char *)s;
Antoine Pitrouab868312009-01-10 15:40:25 +00005430 e = q + size - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005431
5432 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005433 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005434
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005435 /* Check for BOM marks (U+FEFF) in the input and adjust current
5436 byte order setting accordingly. In native mode, the leading BOM
5437 mark is skipped, in all other modes, it is copied to the output
5438 stream as-is (giving a ZWNBSP character). */
5439 if (bo == 0) {
Walter Dörwald69652032004-09-07 20:24:22 +00005440 if (size >= 2) {
Victor Stinner24729f32011-11-10 20:31:37 +01005441 const Py_UCS4 bom = (q[ihi] << 8) | q[ilo];
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005442#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00005443 if (bom == 0xFEFF) {
5444 q += 2;
5445 bo = -1;
5446 }
5447 else if (bom == 0xFFFE) {
5448 q += 2;
5449 bo = 1;
5450 }
Tim Petersced69f82003-09-16 20:30:58 +00005451#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005452 if (bom == 0xFEFF) {
5453 q += 2;
5454 bo = 1;
5455 }
5456 else if (bom == 0xFFFE) {
5457 q += 2;
5458 bo = -1;
5459 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005460#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005461 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005462 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005463
Tim Peters772747b2001-08-09 22:21:55 +00005464 if (bo == -1) {
5465 /* force LE */
5466 ihi = 1;
5467 ilo = 0;
5468 }
5469 else if (bo == 1) {
5470 /* force BE */
5471 ihi = 0;
5472 ilo = 1;
5473 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005474#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5475 native_ordering = ilo < ihi;
5476#else
5477 native_ordering = ilo > ihi;
5478#endif
Tim Peters772747b2001-08-09 22:21:55 +00005479
Antoine Pitrouab868312009-01-10 15:40:25 +00005480 aligned_end = (const unsigned char *) ((size_t) e & ~LONG_PTR_MASK);
Tim Peters772747b2001-08-09 22:21:55 +00005481 while (q < e) {
Victor Stinner24729f32011-11-10 20:31:37 +01005482 Py_UCS4 ch;
Antoine Pitrouab868312009-01-10 15:40:25 +00005483 /* First check for possible aligned read of a C 'long'. Unaligned
5484 reads are more expensive, better to defer to another iteration. */
5485 if (!((size_t) q & LONG_PTR_MASK)) {
5486 /* Fast path for runs of non-surrogate chars. */
5487 register const unsigned char *_q = q;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005488 int kind = PyUnicode_KIND(unicode);
5489 void *data = PyUnicode_DATA(unicode);
5490 while (_q < aligned_end) {
5491 unsigned long block = * (unsigned long *) _q;
5492 unsigned short *pblock = (unsigned short*)&block;
5493 Py_UCS4 maxch;
5494 if (native_ordering) {
5495 /* Can use buffer directly */
5496 if (block & FAST_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00005497 break;
Antoine Pitrouab868312009-01-10 15:40:25 +00005498 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005499 else {
5500 /* Need to byte-swap */
5501 unsigned char *_p = (unsigned char*)pblock;
5502 if (block & SWAPPED_FAST_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00005503 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005504 _p[0] = _q[1];
5505 _p[1] = _q[0];
5506 _p[2] = _q[3];
5507 _p[3] = _q[2];
Antoine Pitrouab868312009-01-10 15:40:25 +00005508#if (SIZEOF_LONG == 8)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005509 _p[4] = _q[5];
5510 _p[5] = _q[4];
5511 _p[6] = _q[7];
5512 _p[7] = _q[6];
Antoine Pitrouab868312009-01-10 15:40:25 +00005513#endif
Antoine Pitrouab868312009-01-10 15:40:25 +00005514 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005515 maxch = Py_MAX(pblock[0], pblock[1]);
5516#if SIZEOF_LONG == 8
5517 maxch = Py_MAX(maxch, Py_MAX(pblock[2], pblock[3]));
5518#endif
5519 if (maxch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
5520 if (unicode_widen(&unicode, maxch) < 0)
5521 goto onError;
5522 kind = PyUnicode_KIND(unicode);
5523 data = PyUnicode_DATA(unicode);
5524 }
5525 PyUnicode_WRITE(kind, data, outpos++, pblock[0]);
5526 PyUnicode_WRITE(kind, data, outpos++, pblock[1]);
5527#if SIZEOF_LONG == 8
5528 PyUnicode_WRITE(kind, data, outpos++, pblock[2]);
5529 PyUnicode_WRITE(kind, data, outpos++, pblock[3]);
5530#endif
5531 _q += SIZEOF_LONG;
Antoine Pitrouab868312009-01-10 15:40:25 +00005532 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005533 q = _q;
5534 if (q >= e)
5535 break;
5536 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005537 ch = (q[ihi] << 8) | q[ilo];
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005538
Benjamin Peterson14339b62009-01-31 16:36:08 +00005539 q += 2;
Benjamin Peterson29060642009-01-31 22:14:21 +00005540
Victor Stinner551ac952011-11-29 22:58:13 +01005541 if (!Py_UNICODE_IS_SURROGATE(ch)) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005542 if (unicode_putchar(&unicode, &outpos, ch) < 0)
5543 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005544 continue;
5545 }
5546
5547 /* UTF-16 code pair: */
5548 if (q > e) {
5549 errmsg = "unexpected end of data";
5550 startinpos = (((const char *)q) - 2) - starts;
5551 endinpos = ((const char *)e) + 1 - starts;
5552 goto utf16Error;
5553 }
Victor Stinner2e9cfad2011-11-20 18:40:27 +01005554 if (Py_UNICODE_IS_HIGH_SURROGATE(ch)) {
5555 Py_UCS4 ch2 = (q[ihi] << 8) | q[ilo];
Benjamin Peterson29060642009-01-31 22:14:21 +00005556 q += 2;
Victor Stinner2e9cfad2011-11-20 18:40:27 +01005557 if (Py_UNICODE_IS_LOW_SURROGATE(ch2)) {
Victor Stinner62aa4d02011-11-09 00:03:45 +01005558 if (unicode_putchar(&unicode, &outpos,
Victor Stinner2e9cfad2011-11-20 18:40:27 +01005559 Py_UNICODE_JOIN_SURROGATES(ch, ch2)) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005560 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005561 continue;
5562 }
5563 else {
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005564 errmsg = "illegal UTF-16 surrogate";
Benjamin Peterson29060642009-01-31 22:14:21 +00005565 startinpos = (((const char *)q)-4)-starts;
5566 endinpos = startinpos+2;
5567 goto utf16Error;
5568 }
5569
Benjamin Peterson14339b62009-01-31 16:36:08 +00005570 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005571 errmsg = "illegal encoding";
5572 startinpos = (((const char *)q)-2)-starts;
5573 endinpos = startinpos+2;
5574 /* Fall through to report the error */
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005575
Benjamin Peterson29060642009-01-31 22:14:21 +00005576 utf16Error:
Benjamin Peterson29060642009-01-31 22:14:21 +00005577 if (unicode_decode_call_errorhandler(
Antoine Pitrouab868312009-01-10 15:40:25 +00005578 errors,
5579 &errorHandler,
5580 "utf16", errmsg,
5581 &starts,
5582 (const char **)&e,
5583 &startinpos,
5584 &endinpos,
5585 &exc,
5586 (const char **)&q,
5587 &unicode,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005588 &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005589 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005590 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005591 /* remaining byte at the end? (size should be even) */
5592 if (e == q) {
5593 if (!consumed) {
5594 errmsg = "truncated data";
5595 startinpos = ((const char *)q) - starts;
5596 endinpos = ((const char *)e) + 1 - starts;
Antoine Pitrouab868312009-01-10 15:40:25 +00005597 if (unicode_decode_call_errorhandler(
5598 errors,
5599 &errorHandler,
5600 "utf16", errmsg,
5601 &starts,
5602 (const char **)&e,
5603 &startinpos,
5604 &endinpos,
5605 &exc,
5606 (const char **)&q,
5607 &unicode,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005608 &outpos))
Antoine Pitrouab868312009-01-10 15:40:25 +00005609 goto onError;
5610 /* The remaining input chars are ignored if the callback
5611 chooses to skip the input */
5612 }
5613 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005614
5615 if (byteorder)
5616 *byteorder = bo;
5617
Walter Dörwald69652032004-09-07 20:24:22 +00005618 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005619 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005620
Guido van Rossumd57fd912000-03-10 22:53:23 +00005621 /* Adjust length */
Victor Stinner16e6a802011-12-12 13:24:15 +01005622 if (unicode_resize(&unicode, outpos) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005623 goto onError;
5624
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005625 Py_XDECREF(errorHandler);
5626 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01005627 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005628
Benjamin Peterson29060642009-01-31 22:14:21 +00005629 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005630 Py_DECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005631 Py_XDECREF(errorHandler);
5632 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005633 return NULL;
5634}
5635
Antoine Pitrouab868312009-01-10 15:40:25 +00005636#undef FAST_CHAR_MASK
5637#undef SWAPPED_FAST_CHAR_MASK
5638
Tim Peters772747b2001-08-09 22:21:55 +00005639PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005640_PyUnicode_EncodeUTF16(PyObject *str,
5641 const char *errors,
5642 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005643{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005644 int kind;
5645 void *data;
5646 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005647 PyObject *v;
Tim Peters772747b2001-08-09 22:21:55 +00005648 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005649 Py_ssize_t nsize, bytesize;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005650 Py_ssize_t i, pairs;
Tim Peters772747b2001-08-09 22:21:55 +00005651 /* Offsets from p for storing byte pairs in the right order. */
5652#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5653 int ihi = 1, ilo = 0;
5654#else
5655 int ihi = 0, ilo = 1;
5656#endif
5657
Benjamin Peterson29060642009-01-31 22:14:21 +00005658#define STORECHAR(CH) \
5659 do { \
5660 p[ihi] = ((CH) >> 8) & 0xff; \
5661 p[ilo] = (CH) & 0xff; \
5662 p += 2; \
Tim Peters772747b2001-08-09 22:21:55 +00005663 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005664
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005665 if (!PyUnicode_Check(str)) {
5666 PyErr_BadArgument();
5667 return NULL;
5668 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005669 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005670 return NULL;
5671 kind = PyUnicode_KIND(str);
5672 data = PyUnicode_DATA(str);
5673 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005674
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005675 pairs = 0;
5676 if (kind == PyUnicode_4BYTE_KIND)
5677 for (i = 0; i < len; i++)
5678 if (PyUnicode_READ(kind, data, i) >= 0x10000)
5679 pairs++;
5680 /* 2 * (len + pairs + (byteorder == 0)) */
5681 if (len > PY_SSIZE_T_MAX - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005682 return PyErr_NoMemory();
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005683 nsize = len + pairs + (byteorder == 0);
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005684 bytesize = nsize * 2;
5685 if (bytesize / 2 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005686 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005687 v = PyBytes_FromStringAndSize(NULL, bytesize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005688 if (v == NULL)
5689 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005690
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005691 p = (unsigned char *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005692 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005693 STORECHAR(0xFEFF);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005694 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005695 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005696
5697 if (byteorder == -1) {
5698 /* force LE */
5699 ihi = 1;
5700 ilo = 0;
5701 }
5702 else if (byteorder == 1) {
5703 /* force BE */
5704 ihi = 0;
5705 ilo = 1;
5706 }
5707
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005708 for (i = 0; i < len; i++) {
5709 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
5710 Py_UCS4 ch2 = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +00005711 if (ch >= 0x10000) {
Victor Stinner551ac952011-11-29 22:58:13 +01005712 ch2 = Py_UNICODE_LOW_SURROGATE(ch);
5713 ch = Py_UNICODE_HIGH_SURROGATE(ch);
Benjamin Peterson29060642009-01-31 22:14:21 +00005714 }
Tim Peters772747b2001-08-09 22:21:55 +00005715 STORECHAR(ch);
5716 if (ch2)
5717 STORECHAR(ch2);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005718 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005719
5720 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005721 return v;
Tim Peters772747b2001-08-09 22:21:55 +00005722#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005723}
5724
Alexander Belopolsky40018472011-02-26 01:02:56 +00005725PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005726PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5727 Py_ssize_t size,
5728 const char *errors,
5729 int byteorder)
5730{
5731 PyObject *result;
5732 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5733 if (tmp == NULL)
5734 return NULL;
5735 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5736 Py_DECREF(tmp);
5737 return result;
5738}
5739
5740PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005741PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005742{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005743 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005744}
5745
5746/* --- Unicode Escape Codec ----------------------------------------------- */
5747
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005748/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5749 if all the escapes in the string make it still a valid ASCII string.
5750 Returns -1 if any escapes were found which cause the string to
5751 pop out of ASCII range. Otherwise returns the length of the
5752 required buffer to hold the string.
5753 */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02005754static Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005755length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5756{
5757 const unsigned char *p = (const unsigned char *)s;
5758 const unsigned char *end = p + size;
5759 Py_ssize_t length = 0;
5760
5761 if (size < 0)
5762 return -1;
5763
5764 for (; p < end; ++p) {
5765 if (*p > 127) {
5766 /* Non-ASCII */
5767 return -1;
5768 }
5769 else if (*p != '\\') {
5770 /* Normal character */
5771 ++length;
5772 }
5773 else {
5774 /* Backslash-escape, check next char */
5775 ++p;
5776 /* Escape sequence reaches till end of string or
5777 non-ASCII follow-up. */
5778 if (p >= end || *p > 127)
5779 return -1;
5780 switch (*p) {
5781 case '\n':
5782 /* backslash + \n result in zero characters */
5783 break;
5784 case '\\': case '\'': case '\"':
5785 case 'b': case 'f': case 't':
5786 case 'n': case 'r': case 'v': case 'a':
5787 ++length;
5788 break;
5789 case '0': case '1': case '2': case '3':
5790 case '4': case '5': case '6': case '7':
5791 case 'x': case 'u': case 'U': case 'N':
5792 /* these do not guarantee ASCII characters */
5793 return -1;
5794 default:
5795 /* count the backslash + the other character */
5796 length += 2;
5797 }
5798 }
5799 }
5800 return length;
5801}
5802
Fredrik Lundh06d12682001-01-24 07:59:11 +00005803static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005804
Alexander Belopolsky40018472011-02-26 01:02:56 +00005805PyObject *
5806PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005807 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005808 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005809{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005810 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005811 Py_ssize_t startinpos;
5812 Py_ssize_t endinpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005813 int j;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005814 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005815 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005816 char* message;
5817 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005818 PyObject *errorHandler = NULL;
5819 PyObject *exc = NULL;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005820 Py_ssize_t len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005821 Py_ssize_t i;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005822
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005823 len = length_of_escaped_ascii_string(s, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005824
5825 /* After length_of_escaped_ascii_string() there are two alternatives,
5826 either the string is pure ASCII with named escapes like \n, etc.
5827 and we determined it's exact size (common case)
5828 or it contains \x, \u, ... escape sequences. then we create a
5829 legacy wchar string and resize it at the end of this function. */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005830 if (len >= 0) {
5831 v = PyUnicode_New(len, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005832 if (!v)
5833 goto onError;
5834 assert(PyUnicode_KIND(v) == PyUnicode_1BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005835 }
5836 else {
5837 /* Escaped strings will always be longer than the resulting
5838 Unicode string, so we start with size here and then reduce the
5839 length after conversion to the true value.
5840 (but if the error callback returns a long replacement string
5841 we'll have to allocate more space) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005842 v = PyUnicode_New(size, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005843 if (!v)
5844 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005845 len = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005846 }
5847
Guido van Rossumd57fd912000-03-10 22:53:23 +00005848 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005849 return v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005850 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005851 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005852
Guido van Rossumd57fd912000-03-10 22:53:23 +00005853 while (s < end) {
5854 unsigned char c;
Victor Stinner24729f32011-11-10 20:31:37 +01005855 Py_UCS4 x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005856 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005857
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005858 /* The only case in which i == ascii_length is a backslash
5859 followed by a newline. */
5860 assert(i <= len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005861
Guido van Rossumd57fd912000-03-10 22:53:23 +00005862 /* Non-escape characters are interpreted as Unicode ordinals */
5863 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005864 if (unicode_putchar(&v, &i, (unsigned char) *s++) < 0)
5865 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005866 continue;
5867 }
5868
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005869 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005870 /* \ - Escapes */
5871 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005872 c = *s++;
5873 if (s > end)
5874 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005875
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005876 /* The only case in which i == ascii_length is a backslash
5877 followed by a newline. */
5878 assert(i < len || (i == len && c == '\n'));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005879
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005880 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005881
Benjamin Peterson29060642009-01-31 22:14:21 +00005882 /* \x escapes */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005883#define WRITECHAR(ch) \
5884 do { \
5885 if (unicode_putchar(&v, &i, ch) < 0) \
5886 goto onError; \
5887 }while(0)
5888
Guido van Rossumd57fd912000-03-10 22:53:23 +00005889 case '\n': break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005890 case '\\': WRITECHAR('\\'); break;
5891 case '\'': WRITECHAR('\''); break;
5892 case '\"': WRITECHAR('\"'); break;
5893 case 'b': WRITECHAR('\b'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005894 /* FF */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005895 case 'f': WRITECHAR('\014'); break;
5896 case 't': WRITECHAR('\t'); break;
5897 case 'n': WRITECHAR('\n'); break;
5898 case 'r': WRITECHAR('\r'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005899 /* VT */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005900 case 'v': WRITECHAR('\013'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005901 /* BEL, not classic C */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005902 case 'a': WRITECHAR('\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005903
Benjamin Peterson29060642009-01-31 22:14:21 +00005904 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005905 case '0': case '1': case '2': case '3':
5906 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005907 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005908 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005909 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005910 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005911 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00005912 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005913 WRITECHAR(x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005914 break;
5915
Benjamin Peterson29060642009-01-31 22:14:21 +00005916 /* hex escapes */
5917 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005918 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005919 digits = 2;
5920 message = "truncated \\xXX escape";
5921 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005922
Benjamin Peterson29060642009-01-31 22:14:21 +00005923 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005924 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005925 digits = 4;
5926 message = "truncated \\uXXXX escape";
5927 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005928
Benjamin Peterson29060642009-01-31 22:14:21 +00005929 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005930 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005931 digits = 8;
5932 message = "truncated \\UXXXXXXXX escape";
5933 hexescape:
5934 chr = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005935 if (s+digits>end) {
5936 endinpos = size;
5937 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005938 errors, &errorHandler,
5939 "unicodeescape", "end of string in escape sequence",
5940 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005941 &v, &i))
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005942 goto onError;
5943 goto nextByte;
5944 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005945 for (j = 0; j < digits; ++j) {
5946 c = (unsigned char) s[j];
David Malcolm96960882010-11-05 17:23:41 +00005947 if (!Py_ISXDIGIT(c)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005948 endinpos = (s+j+1)-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005949 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005950 errors, &errorHandler,
5951 "unicodeescape", message,
5952 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005953 &v, &i))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005954 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005955 len = PyUnicode_GET_LENGTH(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005956 goto nextByte;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005957 }
5958 chr = (chr<<4) & ~0xF;
5959 if (c >= '0' && c <= '9')
5960 chr += c - '0';
5961 else if (c >= 'a' && c <= 'f')
5962 chr += 10 + c - 'a';
5963 else
5964 chr += 10 + c - 'A';
5965 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005966 s += j;
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005967 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005968 /* _decoding_error will have already written into the
5969 target buffer. */
5970 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005971 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005972 /* when we get here, chr is a 32-bit unicode character */
Victor Stinner8faf8212011-12-08 22:14:11 +01005973 if (chr <= MAX_UNICODE) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005974 WRITECHAR(chr);
Fredrik Lundhdf846752000-09-03 11:29:49 +00005975 } else {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005976 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005977 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005978 errors, &errorHandler,
5979 "unicodeescape", "illegal Unicode character",
5980 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005981 &v, &i))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005982 goto onError;
5983 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005984 break;
5985
Benjamin Peterson29060642009-01-31 22:14:21 +00005986 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005987 case 'N':
5988 message = "malformed \\N character escape";
5989 if (ucnhash_CAPI == NULL) {
5990 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005991 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
5992 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005993 if (ucnhash_CAPI == NULL)
5994 goto ucnhashError;
5995 }
5996 if (*s == '{') {
5997 const char *start = s+1;
5998 /* look for the closing brace */
5999 while (*s != '}' && s < end)
6000 s++;
6001 if (s > start && s < end && *s == '}') {
6002 /* found a name. look it up in the unicode database */
6003 message = "unknown Unicode character name";
6004 s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006005 if (ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
Ezio Melotti931b8aa2011-10-21 21:57:36 +03006006 &chr, 0))
Fredrik Lundhccc74732001-02-18 22:13:49 +00006007 goto store;
6008 }
6009 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006010 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006011 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00006012 errors, &errorHandler,
6013 "unicodeescape", message,
6014 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006015 &v, &i))
Fredrik Lundhccc74732001-02-18 22:13:49 +00006016 goto onError;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006017 break;
6018
6019 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00006020 if (s > end) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006021 message = "\\ at end of string";
6022 s--;
6023 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006024 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00006025 errors, &errorHandler,
6026 "unicodeescape", message,
6027 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006028 &v, &i))
Walter Dörwald8c077222002-03-25 11:16:18 +00006029 goto onError;
6030 }
6031 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006032 WRITECHAR('\\');
6033 WRITECHAR(s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00006034 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00006035 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006036 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006037 nextByte:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006038 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006039 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006040#undef WRITECHAR
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006041
Victor Stinner16e6a802011-12-12 13:24:15 +01006042 if (unicode_resize(&v, i) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006043 goto onError;
Walter Dörwaldd4ade082003-08-15 15:00:26 +00006044 Py_XDECREF(errorHandler);
6045 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006046 return unicode_result(v);
Walter Dörwald8c077222002-03-25 11:16:18 +00006047
Benjamin Peterson29060642009-01-31 22:14:21 +00006048 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00006049 PyErr_SetString(
6050 PyExc_UnicodeError,
6051 "\\N escapes not supported (can't load unicodedata module)"
6052 );
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00006053 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006054 Py_XDECREF(errorHandler);
6055 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00006056 return NULL;
6057
Benjamin Peterson29060642009-01-31 22:14:21 +00006058 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006059 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006060 Py_XDECREF(errorHandler);
6061 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006062 return NULL;
6063}
6064
6065/* Return a Unicode-Escape string version of the Unicode object.
6066
6067 If quotes is true, the string is enclosed in u"" or u'' quotes as
6068 appropriate.
6069
6070*/
6071
Alexander Belopolsky40018472011-02-26 01:02:56 +00006072PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006073PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006074{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006075 Py_ssize_t i, len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006076 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006077 char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006078 int kind;
6079 void *data;
6080 Py_ssize_t expandsize = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006081
Thomas Wouters89f507f2006-12-13 04:49:30 +00006082 /* Initial allocation is based on the longest-possible unichr
6083 escape.
6084
6085 In wide (UTF-32) builds '\U00xxxxxx' is 10 chars per source
6086 unichr, so in this case it's the longest unichr escape. In
6087 narrow (UTF-16) builds this is five chars per source unichr
6088 since there are two unichrs in the surrogate pair, so in narrow
6089 (UTF-16) builds it's not the longest unichr escape.
6090
6091 In wide or narrow builds '\uxxxx' is 6 chars per source unichr,
6092 so in the narrow (UTF-16) build case it's the longest unichr
6093 escape.
6094 */
6095
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006096 if (!PyUnicode_Check(unicode)) {
6097 PyErr_BadArgument();
6098 return NULL;
6099 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05006100 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006101 return NULL;
6102 len = PyUnicode_GET_LENGTH(unicode);
6103 kind = PyUnicode_KIND(unicode);
6104 data = PyUnicode_DATA(unicode);
Benjamin Petersonead6b532011-12-20 17:23:42 -06006105 switch (kind) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006106 case PyUnicode_1BYTE_KIND: expandsize = 4; break;
6107 case PyUnicode_2BYTE_KIND: expandsize = 6; break;
6108 case PyUnicode_4BYTE_KIND: expandsize = 10; break;
6109 }
6110
6111 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006112 return PyBytes_FromStringAndSize(NULL, 0);
6113
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006114 if (len > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006115 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00006116
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006117 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00006118 2
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006119 + expandsize*len
Benjamin Peterson29060642009-01-31 22:14:21 +00006120 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006121 if (repr == NULL)
6122 return NULL;
6123
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006124 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006125
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006126 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01006127 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006128
Walter Dörwald79e913e2007-05-12 11:08:06 +00006129 /* Escape backslashes */
6130 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006131 *p++ = '\\';
6132 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00006133 continue;
Tim Petersced69f82003-09-16 20:30:58 +00006134 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006135
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00006136 /* Map 21-bit characters to '\U00xxxxxx' */
6137 else if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01006138 assert(ch <= MAX_UNICODE);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00006139 *p++ = '\\';
6140 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006141 *p++ = Py_hexdigits[(ch >> 28) & 0x0000000F];
6142 *p++ = Py_hexdigits[(ch >> 24) & 0x0000000F];
6143 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
6144 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
6145 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
6146 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
6147 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
6148 *p++ = Py_hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00006149 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00006150 }
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00006151
Guido van Rossumd57fd912000-03-10 22:53:23 +00006152 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00006153 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006154 *p++ = '\\';
6155 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006156 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
6157 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
6158 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6159 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006160 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006161
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006162 /* Map special whitespace to '\t', \n', '\r' */
6163 else if (ch == '\t') {
6164 *p++ = '\\';
6165 *p++ = 't';
6166 }
6167 else if (ch == '\n') {
6168 *p++ = '\\';
6169 *p++ = 'n';
6170 }
6171 else if (ch == '\r') {
6172 *p++ = '\\';
6173 *p++ = 'r';
6174 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006175
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006176 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00006177 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006178 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006179 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006180 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6181 *p++ = Py_hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00006182 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006183
Guido van Rossumd57fd912000-03-10 22:53:23 +00006184 /* Copy everything else as-is */
6185 else
6186 *p++ = (char) ch;
6187 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006188
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006189 assert(p - PyBytes_AS_STRING(repr) > 0);
6190 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
6191 return NULL;
6192 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006193}
6194
Alexander Belopolsky40018472011-02-26 01:02:56 +00006195PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006196PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
6197 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006198{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006199 PyObject *result;
6200 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6201 if (tmp == NULL)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006202 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006203 result = PyUnicode_AsUnicodeEscapeString(tmp);
6204 Py_DECREF(tmp);
6205 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006206}
6207
6208/* --- Raw Unicode Escape Codec ------------------------------------------- */
6209
Alexander Belopolsky40018472011-02-26 01:02:56 +00006210PyObject *
6211PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006212 Py_ssize_t size,
6213 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006214{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006215 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006216 Py_ssize_t startinpos;
6217 Py_ssize_t endinpos;
6218 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006219 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006220 const char *end;
6221 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006222 PyObject *errorHandler = NULL;
6223 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006224
Guido van Rossumd57fd912000-03-10 22:53:23 +00006225 /* Escaped strings will always be longer than the resulting
6226 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006227 length after conversion to the true value. (But decoding error
6228 handler might have to resize the string) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006229 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006230 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006231 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006232 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006233 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006234 outpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006235 end = s + size;
6236 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006237 unsigned char c;
6238 Py_UCS4 x;
6239 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006240 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006241
Benjamin Peterson29060642009-01-31 22:14:21 +00006242 /* Non-escape characters are interpreted as Unicode ordinals */
6243 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006244 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
6245 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006246 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006247 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006248 startinpos = s-starts;
6249
6250 /* \u-escapes are only interpreted iff the number of leading
6251 backslashes if odd */
6252 bs = s;
6253 for (;s < end;) {
6254 if (*s != '\\')
6255 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006256 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
6257 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006258 }
6259 if (((s - bs) & 1) == 0 ||
6260 s >= end ||
6261 (*s != 'u' && *s != 'U')) {
6262 continue;
6263 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006264 outpos--;
Benjamin Peterson29060642009-01-31 22:14:21 +00006265 count = *s=='u' ? 4 : 8;
6266 s++;
6267
6268 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
Benjamin Peterson29060642009-01-31 22:14:21 +00006269 for (x = 0, i = 0; i < count; ++i, ++s) {
6270 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00006271 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006272 endinpos = s-starts;
6273 if (unicode_decode_call_errorhandler(
6274 errors, &errorHandler,
6275 "rawunicodeescape", "truncated \\uXXXX",
6276 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006277 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006278 goto onError;
6279 goto nextByte;
6280 }
6281 x = (x<<4) & ~0xF;
6282 if (c >= '0' && c <= '9')
6283 x += c - '0';
6284 else if (c >= 'a' && c <= 'f')
6285 x += 10 + c - 'a';
6286 else
6287 x += 10 + c - 'A';
6288 }
Victor Stinner8faf8212011-12-08 22:14:11 +01006289 if (x <= MAX_UNICODE) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006290 if (unicode_putchar(&v, &outpos, x) < 0)
6291 goto onError;
Christian Heimesfe337bf2008-03-23 21:54:12 +00006292 } else {
6293 endinpos = s-starts;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006294 if (unicode_decode_call_errorhandler(
6295 errors, &errorHandler,
6296 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00006297 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006298 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006299 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006300 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006301 nextByte:
6302 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006303 }
Victor Stinner16e6a802011-12-12 13:24:15 +01006304 if (unicode_resize(&v, outpos) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006305 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006306 Py_XDECREF(errorHandler);
6307 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006308 return unicode_result(v);
Tim Petersced69f82003-09-16 20:30:58 +00006309
Benjamin Peterson29060642009-01-31 22:14:21 +00006310 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006311 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006312 Py_XDECREF(errorHandler);
6313 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006314 return NULL;
6315}
6316
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006317
Alexander Belopolsky40018472011-02-26 01:02:56 +00006318PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006319PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006320{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006321 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006322 char *p;
6323 char *q;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006324 Py_ssize_t expandsize, pos;
6325 int kind;
6326 void *data;
6327 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006328
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006329 if (!PyUnicode_Check(unicode)) {
6330 PyErr_BadArgument();
6331 return NULL;
6332 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05006333 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006334 return NULL;
6335 kind = PyUnicode_KIND(unicode);
6336 data = PyUnicode_DATA(unicode);
6337 len = PyUnicode_GET_LENGTH(unicode);
Benjamin Peterson1518e872011-11-23 10:44:52 -06006338 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6339 bytes, and 1 byte characters 4. */
6340 expandsize = kind * 2 + 2;
Victor Stinner0e368262011-11-10 20:12:49 +01006341
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006342 if (len > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006343 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00006344
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006345 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006346 if (repr == NULL)
6347 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006348 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006349 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006350
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006351 p = q = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006352 for (pos = 0; pos < len; pos++) {
6353 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006354 /* Map 32-bit characters to '\Uxxxxxxxx' */
6355 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01006356 assert(ch <= MAX_UNICODE);
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006357 *p++ = '\\';
6358 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006359 *p++ = Py_hexdigits[(ch >> 28) & 0xf];
6360 *p++ = Py_hexdigits[(ch >> 24) & 0xf];
6361 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6362 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6363 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6364 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6365 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6366 *p++ = Py_hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00006367 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006368 /* Map 16-bit characters to '\uxxxx' */
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006369 else if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006370 *p++ = '\\';
6371 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006372 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6373 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6374 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6375 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006376 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006377 /* Copy everything else as-is */
6378 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00006379 *p++ = (char) ch;
6380 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006381
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006382 assert(p > q);
6383 if (_PyBytes_Resize(&repr, p - q) < 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006384 return NULL;
6385 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006386}
6387
Alexander Belopolsky40018472011-02-26 01:02:56 +00006388PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006389PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6390 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006391{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006392 PyObject *result;
6393 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6394 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006395 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006396 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6397 Py_DECREF(tmp);
6398 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006399}
6400
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006401/* --- Unicode Internal Codec ------------------------------------------- */
6402
Alexander Belopolsky40018472011-02-26 01:02:56 +00006403PyObject *
6404_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006405 Py_ssize_t size,
6406 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006407{
6408 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006409 Py_ssize_t startinpos;
6410 Py_ssize_t endinpos;
6411 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006412 PyObject *v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006413 const char *end;
6414 const char *reason;
6415 PyObject *errorHandler = NULL;
6416 PyObject *exc = NULL;
6417
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006418 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006419 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006420 1))
6421 return NULL;
6422
Thomas Wouters89f507f2006-12-13 04:49:30 +00006423 /* XXX overflow detection missing */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006424 v = PyUnicode_New((size+Py_UNICODE_SIZE-1)/ Py_UNICODE_SIZE, 127);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006425 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006426 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006427 if (PyUnicode_GET_LENGTH(v) == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006428 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006429 outpos = 0;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006430 end = s + size;
6431
6432 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006433 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006434 Py_UCS4 ch;
6435 /* We copy the raw representation one byte at a time because the
6436 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006437 ((char *) &uch)[0] = s[0];
6438 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006439#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006440 ((char *) &uch)[2] = s[2];
6441 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006442#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006443 ch = uch;
6444
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006445 /* We have to sanity check the raw data, otherwise doom looms for
6446 some malformed UCS-4 data. */
6447 if (
Benjamin Peterson29060642009-01-31 22:14:21 +00006448#ifdef Py_UNICODE_WIDE
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006449 ch > 0x10ffff ||
Benjamin Peterson29060642009-01-31 22:14:21 +00006450#endif
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006451 end-s < Py_UNICODE_SIZE
6452 )
Benjamin Peterson29060642009-01-31 22:14:21 +00006453 {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006454 startinpos = s - starts;
6455 if (end-s < Py_UNICODE_SIZE) {
6456 endinpos = end-starts;
6457 reason = "truncated input";
6458 }
6459 else {
6460 endinpos = s - starts + Py_UNICODE_SIZE;
6461 reason = "illegal code point (> 0x10FFFF)";
6462 }
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006463 if (unicode_decode_call_errorhandler(
6464 errors, &errorHandler,
6465 "unicode_internal", reason,
Walter Dörwalde78178e2007-07-30 13:31:40 +00006466 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006467 &v, &outpos))
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006468 goto onError;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006469 continue;
6470 }
6471
6472 s += Py_UNICODE_SIZE;
6473#ifndef Py_UNICODE_WIDE
Victor Stinner551ac952011-11-29 22:58:13 +01006474 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && s < end)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006475 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006476 Py_UNICODE uch2;
6477 ((char *) &uch2)[0] = s[0];
6478 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006479 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006480 {
Victor Stinner551ac952011-11-29 22:58:13 +01006481 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006482 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006483 }
6484 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006485#endif
6486
6487 if (unicode_putchar(&v, &outpos, ch) < 0)
6488 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006489 }
6490
Victor Stinner16e6a802011-12-12 13:24:15 +01006491 if (unicode_resize(&v, outpos) < 0)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006492 goto onError;
6493 Py_XDECREF(errorHandler);
6494 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006495 return unicode_result(v);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006496
Benjamin Peterson29060642009-01-31 22:14:21 +00006497 onError:
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006498 Py_XDECREF(v);
6499 Py_XDECREF(errorHandler);
6500 Py_XDECREF(exc);
6501 return NULL;
6502}
6503
Guido van Rossumd57fd912000-03-10 22:53:23 +00006504/* --- Latin-1 Codec ------------------------------------------------------ */
6505
Alexander Belopolsky40018472011-02-26 01:02:56 +00006506PyObject *
6507PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006508 Py_ssize_t size,
6509 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006510{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006511 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006512 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006513}
6514
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006515/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006516static void
6517make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006518 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006519 PyObject *unicode,
6520 Py_ssize_t startpos, Py_ssize_t endpos,
6521 const char *reason)
6522{
6523 if (*exceptionObject == NULL) {
6524 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006525 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006526 encoding, unicode, startpos, endpos, reason);
6527 }
6528 else {
6529 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6530 goto onError;
6531 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6532 goto onError;
6533 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6534 goto onError;
6535 return;
6536 onError:
6537 Py_DECREF(*exceptionObject);
6538 *exceptionObject = NULL;
6539 }
6540}
6541
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006542/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006543static void
6544raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006545 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006546 PyObject *unicode,
6547 Py_ssize_t startpos, Py_ssize_t endpos,
6548 const char *reason)
6549{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006550 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006551 encoding, unicode, startpos, endpos, reason);
6552 if (*exceptionObject != NULL)
6553 PyCodec_StrictErrors(*exceptionObject);
6554}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006555
6556/* error handling callback helper:
6557 build arguments, call the callback and check the arguments,
6558 put the result into newpos and return the replacement string, which
6559 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006560static PyObject *
6561unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006562 PyObject **errorHandler,
6563 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006564 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006565 Py_ssize_t startpos, Py_ssize_t endpos,
6566 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006567{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006568 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006569 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006570 PyObject *restuple;
6571 PyObject *resunicode;
6572
6573 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006574 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006575 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006576 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006577 }
6578
Benjamin Petersonbac79492012-01-14 13:34:47 -05006579 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006580 return NULL;
6581 len = PyUnicode_GET_LENGTH(unicode);
6582
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006583 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006584 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006585 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006586 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006587
6588 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006589 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006590 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006591 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006592 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006593 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006594 Py_DECREF(restuple);
6595 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006596 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006597 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006598 &resunicode, newpos)) {
6599 Py_DECREF(restuple);
6600 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006601 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006602 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6603 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6604 Py_DECREF(restuple);
6605 return NULL;
6606 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006607 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006608 *newpos = len + *newpos;
6609 if (*newpos<0 || *newpos>len) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006610 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
6611 Py_DECREF(restuple);
6612 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006613 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006614 Py_INCREF(resunicode);
6615 Py_DECREF(restuple);
6616 return resunicode;
6617}
6618
Alexander Belopolsky40018472011-02-26 01:02:56 +00006619static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006620unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006621 const char *errors,
Victor Stinnerfcd96532011-11-04 00:28:50 +01006622 unsigned int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006623{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006624 /* input state */
6625 Py_ssize_t pos=0, size;
6626 int kind;
6627 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006628 /* output object */
6629 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006630 /* pointer into the output */
6631 char *str;
6632 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006633 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006634 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6635 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006636 PyObject *errorHandler = NULL;
6637 PyObject *exc = NULL;
6638 /* the following variable is used for caching string comparisons
6639 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6640 int known_errorHandler = -1;
6641
Benjamin Petersonbac79492012-01-14 13:34:47 -05006642 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006643 return NULL;
6644 size = PyUnicode_GET_LENGTH(unicode);
6645 kind = PyUnicode_KIND(unicode);
6646 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006647 /* allocate enough for a simple encoding without
6648 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006649 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006650 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006651 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006652 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006653 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006654 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006655 ressize = size;
6656
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006657 while (pos < size) {
6658 Py_UCS4 c = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006659
Benjamin Peterson29060642009-01-31 22:14:21 +00006660 /* can we encode this? */
6661 if (c<limit) {
6662 /* no overflow check, because we know that the space is enough */
6663 *str++ = (char)c;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006664 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006665 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006666 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006667 Py_ssize_t requiredsize;
6668 PyObject *repunicode;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006669 Py_ssize_t repsize, newpos, respos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006670 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006671 Py_ssize_t collstart = pos;
6672 Py_ssize_t collend = pos;
Benjamin Peterson29060642009-01-31 22:14:21 +00006673 /* find all unecodable characters */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006674 while ((collend < size) && (PyUnicode_READ(kind, data, collend)>=limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006675 ++collend;
6676 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
6677 if (known_errorHandler==-1) {
6678 if ((errors==NULL) || (!strcmp(errors, "strict")))
6679 known_errorHandler = 1;
6680 else if (!strcmp(errors, "replace"))
6681 known_errorHandler = 2;
6682 else if (!strcmp(errors, "ignore"))
6683 known_errorHandler = 3;
6684 else if (!strcmp(errors, "xmlcharrefreplace"))
6685 known_errorHandler = 4;
6686 else
6687 known_errorHandler = 0;
6688 }
6689 switch (known_errorHandler) {
6690 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006691 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006692 goto onError;
6693 case 2: /* replace */
6694 while (collstart++<collend)
6695 *str++ = '?'; /* fall through */
6696 case 3: /* ignore */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006697 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006698 break;
6699 case 4: /* xmlcharrefreplace */
6700 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006701 /* determine replacement size */
6702 for (i = collstart, repsize = 0; i < collend; ++i) {
6703 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
6704 if (ch < 10)
Benjamin Peterson29060642009-01-31 22:14:21 +00006705 repsize += 2+1+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006706 else if (ch < 100)
Benjamin Peterson29060642009-01-31 22:14:21 +00006707 repsize += 2+2+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006708 else if (ch < 1000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006709 repsize += 2+3+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006710 else if (ch < 10000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006711 repsize += 2+4+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006712 else if (ch < 100000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006713 repsize += 2+5+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006714 else if (ch < 1000000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006715 repsize += 2+6+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006716 else {
Victor Stinner8faf8212011-12-08 22:14:11 +01006717 assert(ch <= MAX_UNICODE);
Benjamin Peterson29060642009-01-31 22:14:21 +00006718 repsize += 2+7+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006719 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006720 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006721 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006722 if (requiredsize > ressize) {
6723 if (requiredsize<2*ressize)
6724 requiredsize = 2*ressize;
6725 if (_PyBytes_Resize(&res, requiredsize))
6726 goto onError;
6727 str = PyBytes_AS_STRING(res) + respos;
6728 ressize = requiredsize;
6729 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006730 /* generate replacement */
6731 for (i = collstart; i < collend; ++i) {
6732 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
Benjamin Peterson29060642009-01-31 22:14:21 +00006733 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006734 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006735 break;
6736 default:
6737 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006738 encoding, reason, unicode, &exc,
6739 collstart, collend, &newpos);
6740 if (repunicode == NULL || (PyUnicode_Check(repunicode) &&
Benjamin Petersonbac79492012-01-14 13:34:47 -05006741 PyUnicode_READY(repunicode) == -1))
Benjamin Peterson29060642009-01-31 22:14:21 +00006742 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006743 if (PyBytes_Check(repunicode)) {
6744 /* Directly copy bytes result to output. */
6745 repsize = PyBytes_Size(repunicode);
6746 if (repsize > 1) {
6747 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006748 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006749 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
6750 Py_DECREF(repunicode);
6751 goto onError;
6752 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006753 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006754 ressize += repsize-1;
6755 }
6756 memcpy(str, PyBytes_AsString(repunicode), repsize);
6757 str += repsize;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006758 pos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006759 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006760 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006761 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006762 /* need more space? (at least enough for what we
6763 have+the replacement+the rest of the string, so
6764 we won't have to check space for encodable characters) */
6765 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006766 repsize = PyUnicode_GET_LENGTH(repunicode);
6767 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006768 if (requiredsize > ressize) {
6769 if (requiredsize<2*ressize)
6770 requiredsize = 2*ressize;
6771 if (_PyBytes_Resize(&res, requiredsize)) {
6772 Py_DECREF(repunicode);
6773 goto onError;
6774 }
6775 str = PyBytes_AS_STRING(res) + respos;
6776 ressize = requiredsize;
6777 }
6778 /* check if there is anything unencodable in the replacement
6779 and copy it to the output */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006780 for (i = 0; repsize-->0; ++i, ++str) {
6781 c = PyUnicode_READ_CHAR(repunicode, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00006782 if (c >= limit) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006783 raise_encode_exception(&exc, encoding, unicode,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006784 pos, pos+1, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006785 Py_DECREF(repunicode);
6786 goto onError;
6787 }
6788 *str = (char)c;
6789 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006790 pos = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006791 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006792 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006793 }
6794 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006795 /* Resize if we allocated to much */
6796 size = str - PyBytes_AS_STRING(res);
6797 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00006798 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006799 if (_PyBytes_Resize(&res, size) < 0)
6800 goto onError;
6801 }
6802
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006803 Py_XDECREF(errorHandler);
6804 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006805 return res;
6806
6807 onError:
6808 Py_XDECREF(res);
6809 Py_XDECREF(errorHandler);
6810 Py_XDECREF(exc);
6811 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006812}
6813
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006814/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006815PyObject *
6816PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006817 Py_ssize_t size,
6818 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006819{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006820 PyObject *result;
6821 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6822 if (unicode == NULL)
6823 return NULL;
6824 result = unicode_encode_ucs1(unicode, errors, 256);
6825 Py_DECREF(unicode);
6826 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006827}
6828
Alexander Belopolsky40018472011-02-26 01:02:56 +00006829PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006830_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006831{
6832 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006833 PyErr_BadArgument();
6834 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006835 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006836 if (PyUnicode_READY(unicode) == -1)
6837 return NULL;
6838 /* Fast path: if it is a one-byte string, construct
6839 bytes object directly. */
6840 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6841 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6842 PyUnicode_GET_LENGTH(unicode));
6843 /* Non-Latin-1 characters present. Defer to above function to
6844 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006845 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006846}
6847
6848PyObject*
6849PyUnicode_AsLatin1String(PyObject *unicode)
6850{
6851 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006852}
6853
6854/* --- 7-bit ASCII Codec -------------------------------------------------- */
6855
Alexander Belopolsky40018472011-02-26 01:02:56 +00006856PyObject *
6857PyUnicode_DecodeASCII(const char *s,
6858 Py_ssize_t size,
6859 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006860{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006861 const char *starts = s;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006862 PyObject *v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006863 int kind;
6864 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006865 Py_ssize_t startinpos;
6866 Py_ssize_t endinpos;
6867 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006868 const char *e;
Victor Stinner702c7342011-10-05 13:50:52 +02006869 int has_error;
6870 const unsigned char *p = (const unsigned char *)s;
6871 const unsigned char *end = p + size;
6872 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006873 PyObject *errorHandler = NULL;
6874 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006875
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006876 if (size == 0) {
6877 Py_INCREF(unicode_empty);
6878 return unicode_empty;
6879 }
6880
Guido van Rossumd57fd912000-03-10 22:53:23 +00006881 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006882 if (size == 1 && (unsigned char)s[0] < 128)
6883 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006884
Victor Stinner702c7342011-10-05 13:50:52 +02006885 has_error = 0;
6886 while (p < end && !has_error) {
6887 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
6888 an explanation. */
6889 if (!((size_t) p & LONG_PTR_MASK)) {
6890 /* Help register allocation */
6891 register const unsigned char *_p = p;
6892 while (_p < aligned_end) {
6893 unsigned long value = *(unsigned long *) _p;
6894 if (value & ASCII_CHAR_MASK) {
6895 has_error = 1;
6896 break;
6897 }
6898 _p += SIZEOF_LONG;
6899 }
6900 if (_p == end)
6901 break;
6902 if (has_error)
6903 break;
6904 p = _p;
6905 }
6906 if (*p & 0x80) {
6907 has_error = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006908 break;
Victor Stinner702c7342011-10-05 13:50:52 +02006909 }
6910 else {
6911 ++p;
6912 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00006913 }
Victor Stinner702c7342011-10-05 13:50:52 +02006914 if (!has_error)
6915 return unicode_fromascii((const unsigned char *)s, size);
Tim Petersced69f82003-09-16 20:30:58 +00006916
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006917 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006918 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006919 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006920 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006921 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006922 kind = PyUnicode_KIND(v);
6923 data = PyUnicode_DATA(v);
6924 outpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006925 e = s + size;
6926 while (s < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006927 register unsigned char c = (unsigned char)*s;
6928 if (c < 128) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006929 PyUnicode_WRITE(kind, data, outpos++, c);
Benjamin Peterson29060642009-01-31 22:14:21 +00006930 ++s;
6931 }
6932 else {
6933 startinpos = s-starts;
6934 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006935 if (unicode_decode_call_errorhandler(
6936 errors, &errorHandler,
6937 "ascii", "ordinal not in range(128)",
6938 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006939 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006940 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006941 kind = PyUnicode_KIND(v);
6942 data = PyUnicode_DATA(v);
Benjamin Peterson29060642009-01-31 22:14:21 +00006943 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006944 }
Victor Stinner16e6a802011-12-12 13:24:15 +01006945 if (unicode_resize(&v, outpos) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006946 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006947 Py_XDECREF(errorHandler);
6948 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006949 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01006950 return v;
Tim Petersced69f82003-09-16 20:30:58 +00006951
Benjamin Peterson29060642009-01-31 22:14:21 +00006952 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006953 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006954 Py_XDECREF(errorHandler);
6955 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006956 return NULL;
6957}
6958
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006959/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006960PyObject *
6961PyUnicode_EncodeASCII(const Py_UNICODE *p,
6962 Py_ssize_t size,
6963 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006964{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006965 PyObject *result;
6966 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6967 if (unicode == NULL)
6968 return NULL;
6969 result = unicode_encode_ucs1(unicode, errors, 128);
6970 Py_DECREF(unicode);
6971 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006972}
6973
Alexander Belopolsky40018472011-02-26 01:02:56 +00006974PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006975_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006976{
6977 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006978 PyErr_BadArgument();
6979 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006980 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006981 if (PyUnicode_READY(unicode) == -1)
6982 return NULL;
6983 /* Fast path: if it is an ASCII-only string, construct bytes object
6984 directly. Else defer to above function to raise the exception. */
6985 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
6986 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6987 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006988 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006989}
6990
6991PyObject *
6992PyUnicode_AsASCIIString(PyObject *unicode)
6993{
6994 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006995}
6996
Victor Stinner99b95382011-07-04 14:23:54 +02006997#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006998
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006999/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007000
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00007001#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007002#define NEED_RETRY
7003#endif
7004
Victor Stinner3a50e702011-10-18 21:21:00 +02007005#ifndef WC_ERR_INVALID_CHARS
7006# define WC_ERR_INVALID_CHARS 0x0080
7007#endif
7008
7009static char*
7010code_page_name(UINT code_page, PyObject **obj)
7011{
7012 *obj = NULL;
7013 if (code_page == CP_ACP)
7014 return "mbcs";
7015 if (code_page == CP_UTF7)
7016 return "CP_UTF7";
7017 if (code_page == CP_UTF8)
7018 return "CP_UTF8";
7019
7020 *obj = PyBytes_FromFormat("cp%u", code_page);
7021 if (*obj == NULL)
7022 return NULL;
7023 return PyBytes_AS_STRING(*obj);
7024}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007025
Alexander Belopolsky40018472011-02-26 01:02:56 +00007026static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007027is_dbcs_lead_byte(UINT code_page, const char *s, int offset)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007028{
7029 const char *curr = s + offset;
Victor Stinner3a50e702011-10-18 21:21:00 +02007030 const char *prev;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007031
Victor Stinner3a50e702011-10-18 21:21:00 +02007032 if (!IsDBCSLeadByteEx(code_page, *curr))
7033 return 0;
7034
7035 prev = CharPrevExA(code_page, s, curr, 0);
7036 if (prev == curr)
7037 return 1;
7038 /* FIXME: This code is limited to "true" double-byte encodings,
7039 as it assumes an incomplete character consists of a single
7040 byte. */
7041 if (curr - prev == 2)
7042 return 1;
7043 if (!IsDBCSLeadByteEx(code_page, *prev))
7044 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007045 return 0;
7046}
7047
Victor Stinner3a50e702011-10-18 21:21:00 +02007048static DWORD
7049decode_code_page_flags(UINT code_page)
7050{
7051 if (code_page == CP_UTF7) {
7052 /* The CP_UTF7 decoder only supports flags=0 */
7053 return 0;
7054 }
7055 else
7056 return MB_ERR_INVALID_CHARS;
7057}
7058
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007059/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007060 * Decode a byte string from a Windows code page into unicode object in strict
7061 * mode.
7062 *
7063 * Returns consumed size if succeed, returns -2 on decode error, or raise a
7064 * WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007065 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007066static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007067decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007068 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02007069 const char *in,
7070 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007071{
Victor Stinner3a50e702011-10-18 21:21:00 +02007072 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01007073 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007074 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007075
7076 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007077 assert(insize > 0);
7078 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
7079 if (outsize <= 0)
7080 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007081
7082 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007083 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01007084 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007085 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00007086 if (*v == NULL)
7087 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007088 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007089 }
7090 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007091 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007092 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01007093 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007094 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007095 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007096 }
7097
7098 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007099 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
7100 if (outsize <= 0)
7101 goto error;
7102 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007103
Victor Stinner3a50e702011-10-18 21:21:00 +02007104error:
7105 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7106 return -2;
7107 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007108 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007109}
7110
Victor Stinner3a50e702011-10-18 21:21:00 +02007111/*
7112 * Decode a byte string from a code page into unicode object with an error
7113 * handler.
7114 *
7115 * Returns consumed size if succeed, or raise a WindowsError or
7116 * UnicodeDecodeError exception and returns -1 on error.
7117 */
7118static int
7119decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007120 PyObject **v,
7121 const char *in, const int size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007122 const char *errors)
7123{
7124 const char *startin = in;
7125 const char *endin = in + size;
7126 const DWORD flags = decode_code_page_flags(code_page);
7127 /* Ideally, we should get reason from FormatMessage. This is the Windows
7128 2000 English version of the message. */
7129 const char *reason = "No mapping for the Unicode character exists "
7130 "in the target code page.";
7131 /* each step cannot decode more than 1 character, but a character can be
7132 represented as a surrogate pair */
7133 wchar_t buffer[2], *startout, *out;
7134 int insize, outsize;
7135 PyObject *errorHandler = NULL;
7136 PyObject *exc = NULL;
7137 PyObject *encoding_obj = NULL;
7138 char *encoding;
7139 DWORD err;
7140 int ret = -1;
7141
7142 assert(size > 0);
7143
7144 encoding = code_page_name(code_page, &encoding_obj);
7145 if (encoding == NULL)
7146 return -1;
7147
7148 if (errors == NULL || strcmp(errors, "strict") == 0) {
7149 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
7150 UnicodeDecodeError. */
7151 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
7152 if (exc != NULL) {
7153 PyCodec_StrictErrors(exc);
7154 Py_CLEAR(exc);
7155 }
7156 goto error;
7157 }
7158
7159 if (*v == NULL) {
7160 /* Create unicode object */
7161 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7162 PyErr_NoMemory();
7163 goto error;
7164 }
Victor Stinnerab595942011-12-17 04:59:06 +01007165 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007166 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02007167 if (*v == NULL)
7168 goto error;
7169 startout = PyUnicode_AS_UNICODE(*v);
7170 }
7171 else {
7172 /* Extend unicode object */
7173 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
7174 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7175 PyErr_NoMemory();
7176 goto error;
7177 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007178 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007179 goto error;
7180 startout = PyUnicode_AS_UNICODE(*v) + n;
7181 }
7182
7183 /* Decode the byte string character per character */
7184 out = startout;
7185 while (in < endin)
7186 {
7187 /* Decode a character */
7188 insize = 1;
7189 do
7190 {
7191 outsize = MultiByteToWideChar(code_page, flags,
7192 in, insize,
7193 buffer, Py_ARRAY_LENGTH(buffer));
7194 if (outsize > 0)
7195 break;
7196 err = GetLastError();
7197 if (err != ERROR_NO_UNICODE_TRANSLATION
7198 && err != ERROR_INSUFFICIENT_BUFFER)
7199 {
7200 PyErr_SetFromWindowsErr(0);
7201 goto error;
7202 }
7203 insize++;
7204 }
7205 /* 4=maximum length of a UTF-8 sequence */
7206 while (insize <= 4 && (in + insize) <= endin);
7207
7208 if (outsize <= 0) {
7209 Py_ssize_t startinpos, endinpos, outpos;
7210
7211 startinpos = in - startin;
7212 endinpos = startinpos + 1;
7213 outpos = out - PyUnicode_AS_UNICODE(*v);
7214 if (unicode_decode_call_errorhandler(
7215 errors, &errorHandler,
7216 encoding, reason,
7217 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01007218 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02007219 {
7220 goto error;
7221 }
Victor Stinner596a6c42011-11-09 00:02:18 +01007222 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007223 }
7224 else {
7225 in += insize;
7226 memcpy(out, buffer, outsize * sizeof(wchar_t));
7227 out += outsize;
7228 }
7229 }
7230
7231 /* write a NUL character at the end */
7232 *out = 0;
7233
7234 /* Extend unicode object */
7235 outsize = out - startout;
7236 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01007237 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007238 goto error;
Victor Stinner76a31a62011-11-04 00:05:13 +01007239 ret = size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007240
7241error:
7242 Py_XDECREF(encoding_obj);
7243 Py_XDECREF(errorHandler);
7244 Py_XDECREF(exc);
7245 return ret;
7246}
7247
Victor Stinner3a50e702011-10-18 21:21:00 +02007248static PyObject *
7249decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007250 const char *s, Py_ssize_t size,
7251 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007252{
Victor Stinner76a31a62011-11-04 00:05:13 +01007253 PyObject *v = NULL;
7254 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007255
Victor Stinner3a50e702011-10-18 21:21:00 +02007256 if (code_page < 0) {
7257 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7258 return NULL;
7259 }
7260
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007261 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007262 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007263
Victor Stinner76a31a62011-11-04 00:05:13 +01007264 do
7265 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007266#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007267 if (size > INT_MAX) {
7268 chunk_size = INT_MAX;
7269 final = 0;
7270 done = 0;
7271 }
7272 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007273#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007274 {
7275 chunk_size = (int)size;
7276 final = (consumed == NULL);
7277 done = 1;
7278 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007279
Victor Stinner76a31a62011-11-04 00:05:13 +01007280 /* Skip trailing lead-byte unless 'final' is set */
7281 if (!final && is_dbcs_lead_byte(code_page, s, chunk_size - 1))
7282 --chunk_size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007283
Victor Stinner76a31a62011-11-04 00:05:13 +01007284 if (chunk_size == 0 && done) {
7285 if (v != NULL)
7286 break;
7287 Py_INCREF(unicode_empty);
7288 return unicode_empty;
7289 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007290
Victor Stinner76a31a62011-11-04 00:05:13 +01007291
7292 converted = decode_code_page_strict(code_page, &v,
7293 s, chunk_size);
7294 if (converted == -2)
7295 converted = decode_code_page_errors(code_page, &v,
7296 s, chunk_size,
7297 errors);
7298 assert(converted != 0);
7299
7300 if (converted < 0) {
7301 Py_XDECREF(v);
7302 return NULL;
7303 }
7304
7305 if (consumed)
7306 *consumed += converted;
7307
7308 s += converted;
7309 size -= converted;
7310 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007311
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007312 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007313}
7314
Alexander Belopolsky40018472011-02-26 01:02:56 +00007315PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007316PyUnicode_DecodeCodePageStateful(int code_page,
7317 const char *s,
7318 Py_ssize_t size,
7319 const char *errors,
7320 Py_ssize_t *consumed)
7321{
7322 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7323}
7324
7325PyObject *
7326PyUnicode_DecodeMBCSStateful(const char *s,
7327 Py_ssize_t size,
7328 const char *errors,
7329 Py_ssize_t *consumed)
7330{
7331 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7332}
7333
7334PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007335PyUnicode_DecodeMBCS(const char *s,
7336 Py_ssize_t size,
7337 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007338{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007339 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7340}
7341
Victor Stinner3a50e702011-10-18 21:21:00 +02007342static DWORD
7343encode_code_page_flags(UINT code_page, const char *errors)
7344{
7345 if (code_page == CP_UTF8) {
7346 if (winver.dwMajorVersion >= 6)
7347 /* CP_UTF8 supports WC_ERR_INVALID_CHARS on Windows Vista
7348 and later */
7349 return WC_ERR_INVALID_CHARS;
7350 else
7351 /* CP_UTF8 only supports flags=0 on Windows older than Vista */
7352 return 0;
7353 }
7354 else if (code_page == CP_UTF7) {
7355 /* CP_UTF7 only supports flags=0 */
7356 return 0;
7357 }
7358 else {
7359 if (errors != NULL && strcmp(errors, "replace") == 0)
7360 return 0;
7361 else
7362 return WC_NO_BEST_FIT_CHARS;
7363 }
7364}
7365
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007366/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007367 * Encode a Unicode string to a Windows code page into a byte string in strict
7368 * mode.
7369 *
7370 * Returns consumed characters if succeed, returns -2 on encode error, or raise
7371 * a WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007372 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007373static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007374encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007375 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007376 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007377{
Victor Stinner554f3f02010-06-16 23:33:54 +00007378 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007379 BOOL *pusedDefaultChar = &usedDefaultChar;
7380 int outsize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007381 PyObject *exc = NULL;
Victor Stinner24729f32011-11-10 20:31:37 +01007382 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007383 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007384 const DWORD flags = encode_code_page_flags(code_page, NULL);
7385 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007386 /* Create a substring so that we can get the UTF-16 representation
7387 of just the slice under consideration. */
7388 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007389
Martin v. Löwis3d325192011-11-04 18:23:06 +01007390 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007391
Victor Stinner3a50e702011-10-18 21:21:00 +02007392 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007393 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007394 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007395 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007396
Victor Stinner2fc507f2011-11-04 20:06:39 +01007397 substring = PyUnicode_Substring(unicode, offset, offset+len);
7398 if (substring == NULL)
7399 return -1;
7400 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7401 if (p == NULL) {
7402 Py_DECREF(substring);
7403 return -1;
7404 }
Martin v. Löwis3d325192011-11-04 18:23:06 +01007405
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007406 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007407 outsize = WideCharToMultiByte(code_page, flags,
7408 p, size,
7409 NULL, 0,
7410 NULL, pusedDefaultChar);
7411 if (outsize <= 0)
7412 goto error;
7413 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007414 if (pusedDefaultChar && *pusedDefaultChar) {
7415 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007416 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007417 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007418
Victor Stinner3a50e702011-10-18 21:21:00 +02007419 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007420 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007421 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007422 if (*outbytes == NULL) {
7423 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007424 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007425 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007426 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007427 }
7428 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007429 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007430 const Py_ssize_t n = PyBytes_Size(*outbytes);
7431 if (outsize > PY_SSIZE_T_MAX - n) {
7432 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007433 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007434 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007435 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007436 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7437 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007438 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007439 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007440 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007441 }
7442
7443 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007444 outsize = WideCharToMultiByte(code_page, flags,
7445 p, size,
7446 out, outsize,
7447 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007448 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007449 if (outsize <= 0)
7450 goto error;
7451 if (pusedDefaultChar && *pusedDefaultChar)
7452 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007453 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007454
Victor Stinner3a50e702011-10-18 21:21:00 +02007455error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007456 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007457 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7458 return -2;
7459 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007460 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007461}
7462
Victor Stinner3a50e702011-10-18 21:21:00 +02007463/*
7464 * Encode a Unicode string to a Windows code page into a byte string using a
7465 * error handler.
7466 *
7467 * Returns consumed characters if succeed, or raise a WindowsError and returns
7468 * -1 on other error.
7469 */
7470static int
7471encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007472 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007473 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007474{
Victor Stinner3a50e702011-10-18 21:21:00 +02007475 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007476 Py_ssize_t pos = unicode_offset;
7477 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007478 /* Ideally, we should get reason from FormatMessage. This is the Windows
7479 2000 English version of the message. */
7480 const char *reason = "invalid character";
7481 /* 4=maximum length of a UTF-8 sequence */
7482 char buffer[4];
7483 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7484 Py_ssize_t outsize;
7485 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007486 PyObject *errorHandler = NULL;
7487 PyObject *exc = NULL;
7488 PyObject *encoding_obj = NULL;
7489 char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007490 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007491 PyObject *rep;
7492 int ret = -1;
7493
7494 assert(insize > 0);
7495
7496 encoding = code_page_name(code_page, &encoding_obj);
7497 if (encoding == NULL)
7498 return -1;
7499
7500 if (errors == NULL || strcmp(errors, "strict") == 0) {
7501 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7502 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007503 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007504 if (exc != NULL) {
7505 PyCodec_StrictErrors(exc);
7506 Py_DECREF(exc);
7507 }
7508 Py_XDECREF(encoding_obj);
7509 return -1;
7510 }
7511
7512 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7513 pusedDefaultChar = &usedDefaultChar;
7514 else
7515 pusedDefaultChar = NULL;
7516
7517 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7518 PyErr_NoMemory();
7519 goto error;
7520 }
7521 outsize = insize * Py_ARRAY_LENGTH(buffer);
7522
7523 if (*outbytes == NULL) {
7524 /* Create string object */
7525 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7526 if (*outbytes == NULL)
7527 goto error;
7528 out = PyBytes_AS_STRING(*outbytes);
7529 }
7530 else {
7531 /* Extend string object */
7532 Py_ssize_t n = PyBytes_Size(*outbytes);
7533 if (n > PY_SSIZE_T_MAX - outsize) {
7534 PyErr_NoMemory();
7535 goto error;
7536 }
7537 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7538 goto error;
7539 out = PyBytes_AS_STRING(*outbytes) + n;
7540 }
7541
7542 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007543 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007544 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007545 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7546 wchar_t chars[2];
7547 int charsize;
7548 if (ch < 0x10000) {
7549 chars[0] = (wchar_t)ch;
7550 charsize = 1;
7551 }
7552 else {
7553 ch -= 0x10000;
7554 chars[0] = 0xd800 + (ch >> 10);
7555 chars[1] = 0xdc00 + (ch & 0x3ff);
7556 charsize = 2;
7557 }
7558
Victor Stinner3a50e702011-10-18 21:21:00 +02007559 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007560 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007561 buffer, Py_ARRAY_LENGTH(buffer),
7562 NULL, pusedDefaultChar);
7563 if (outsize > 0) {
7564 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7565 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007566 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007567 memcpy(out, buffer, outsize);
7568 out += outsize;
7569 continue;
7570 }
7571 }
7572 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7573 PyErr_SetFromWindowsErr(0);
7574 goto error;
7575 }
7576
Victor Stinner3a50e702011-10-18 21:21:00 +02007577 rep = unicode_encode_call_errorhandler(
7578 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007579 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007580 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007581 if (rep == NULL)
7582 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007583 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007584
7585 if (PyBytes_Check(rep)) {
7586 outsize = PyBytes_GET_SIZE(rep);
7587 if (outsize != 1) {
7588 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7589 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7590 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7591 Py_DECREF(rep);
7592 goto error;
7593 }
7594 out = PyBytes_AS_STRING(*outbytes) + offset;
7595 }
7596 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7597 out += outsize;
7598 }
7599 else {
7600 Py_ssize_t i;
7601 enum PyUnicode_Kind kind;
7602 void *data;
7603
Benjamin Petersonbac79492012-01-14 13:34:47 -05007604 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007605 Py_DECREF(rep);
7606 goto error;
7607 }
7608
7609 outsize = PyUnicode_GET_LENGTH(rep);
7610 if (outsize != 1) {
7611 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7612 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7613 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7614 Py_DECREF(rep);
7615 goto error;
7616 }
7617 out = PyBytes_AS_STRING(*outbytes) + offset;
7618 }
7619 kind = PyUnicode_KIND(rep);
7620 data = PyUnicode_DATA(rep);
7621 for (i=0; i < outsize; i++) {
7622 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7623 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007624 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007625 encoding, unicode,
7626 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007627 "unable to encode error handler result to ASCII");
7628 Py_DECREF(rep);
7629 goto error;
7630 }
7631 *out = (unsigned char)ch;
7632 out++;
7633 }
7634 }
7635 Py_DECREF(rep);
7636 }
7637 /* write a NUL byte */
7638 *out = 0;
7639 outsize = out - PyBytes_AS_STRING(*outbytes);
7640 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7641 if (_PyBytes_Resize(outbytes, outsize) < 0)
7642 goto error;
7643 ret = 0;
7644
7645error:
7646 Py_XDECREF(encoding_obj);
7647 Py_XDECREF(errorHandler);
7648 Py_XDECREF(exc);
7649 return ret;
7650}
7651
Victor Stinner3a50e702011-10-18 21:21:00 +02007652static PyObject *
7653encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007654 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007655 const char *errors)
7656{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007657 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007658 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007659 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007660 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007661
Benjamin Petersonbac79492012-01-14 13:34:47 -05007662 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007663 return NULL;
7664 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007665
Victor Stinner3a50e702011-10-18 21:21:00 +02007666 if (code_page < 0) {
7667 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7668 return NULL;
7669 }
7670
Martin v. Löwis3d325192011-11-04 18:23:06 +01007671 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007672 return PyBytes_FromStringAndSize(NULL, 0);
7673
Victor Stinner7581cef2011-11-03 22:32:33 +01007674 offset = 0;
7675 do
7676 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007677#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007678 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007679 chunks. */
7680 if (len > INT_MAX/2) {
7681 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007682 done = 0;
7683 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007684 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007685#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007686 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007687 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007688 done = 1;
7689 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007690
Victor Stinner76a31a62011-11-04 00:05:13 +01007691 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007692 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007693 errors);
7694 if (ret == -2)
7695 ret = encode_code_page_errors(code_page, &outbytes,
7696 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007697 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007698 if (ret < 0) {
7699 Py_XDECREF(outbytes);
7700 return NULL;
7701 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007702
Victor Stinner7581cef2011-11-03 22:32:33 +01007703 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007704 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007705 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007706
Victor Stinner3a50e702011-10-18 21:21:00 +02007707 return outbytes;
7708}
7709
7710PyObject *
7711PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7712 Py_ssize_t size,
7713 const char *errors)
7714{
Victor Stinner7581cef2011-11-03 22:32:33 +01007715 PyObject *unicode, *res;
7716 unicode = PyUnicode_FromUnicode(p, size);
7717 if (unicode == NULL)
7718 return NULL;
7719 res = encode_code_page(CP_ACP, unicode, errors);
7720 Py_DECREF(unicode);
7721 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007722}
7723
7724PyObject *
7725PyUnicode_EncodeCodePage(int code_page,
7726 PyObject *unicode,
7727 const char *errors)
7728{
Victor Stinner7581cef2011-11-03 22:32:33 +01007729 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007730}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007731
Alexander Belopolsky40018472011-02-26 01:02:56 +00007732PyObject *
7733PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007734{
7735 if (!PyUnicode_Check(unicode)) {
7736 PyErr_BadArgument();
7737 return NULL;
7738 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007739 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007740}
7741
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007742#undef NEED_RETRY
7743
Victor Stinner99b95382011-07-04 14:23:54 +02007744#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007745
Guido van Rossumd57fd912000-03-10 22:53:23 +00007746/* --- Character Mapping Codec -------------------------------------------- */
7747
Alexander Belopolsky40018472011-02-26 01:02:56 +00007748PyObject *
7749PyUnicode_DecodeCharmap(const char *s,
7750 Py_ssize_t size,
7751 PyObject *mapping,
7752 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007753{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007754 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007755 Py_ssize_t startinpos;
7756 Py_ssize_t endinpos;
7757 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007758 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01007759 PyObject *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007760 Py_ssize_t extrachars = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007761 PyObject *errorHandler = NULL;
7762 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00007763
Guido van Rossumd57fd912000-03-10 22:53:23 +00007764 /* Default to Latin-1 */
7765 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007766 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007767
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007768 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007769 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007770 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007771 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01007772 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007773 outpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007774 e = s + size;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007775 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007776 Py_ssize_t maplen;
7777 enum PyUnicode_Kind kind;
7778 void *data;
7779 Py_UCS4 x;
7780
Benjamin Petersonbac79492012-01-14 13:34:47 -05007781 if (PyUnicode_READY(mapping) == -1)
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007782 return NULL;
7783
7784 maplen = PyUnicode_GET_LENGTH(mapping);
7785 data = PyUnicode_DATA(mapping);
7786 kind = PyUnicode_KIND(mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007787 while (s < e) {
7788 unsigned char ch = *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007789
Benjamin Peterson29060642009-01-31 22:14:21 +00007790 if (ch < maplen)
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007791 x = PyUnicode_READ(kind, data, ch);
7792 else
7793 x = 0xfffe; /* invalid value */
Guido van Rossumd57fd912000-03-10 22:53:23 +00007794
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007795 if (x == 0xfffe)
7796 {
Benjamin Peterson29060642009-01-31 22:14:21 +00007797 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007798 startinpos = s-starts;
7799 endinpos = startinpos+1;
7800 if (unicode_decode_call_errorhandler(
7801 errors, &errorHandler,
7802 "charmap", "character maps to <undefined>",
7803 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007804 &v, &outpos)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007805 goto onError;
7806 }
7807 continue;
7808 }
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007809
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007810 if (unicode_putchar(&v, &outpos, x) < 0)
7811 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007812 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007813 }
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007814 }
7815 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007816 while (s < e) {
7817 unsigned char ch = *s;
7818 PyObject *w, *x;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007819
Benjamin Peterson29060642009-01-31 22:14:21 +00007820 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7821 w = PyLong_FromLong((long)ch);
7822 if (w == NULL)
7823 goto onError;
7824 x = PyObject_GetItem(mapping, w);
7825 Py_DECREF(w);
7826 if (x == NULL) {
7827 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7828 /* No mapping found means: mapping is undefined. */
7829 PyErr_Clear();
7830 x = Py_None;
7831 Py_INCREF(x);
7832 } else
7833 goto onError;
7834 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007835
Benjamin Peterson29060642009-01-31 22:14:21 +00007836 /* Apply mapping */
7837 if (PyLong_Check(x)) {
7838 long value = PyLong_AS_LONG(x);
7839 if (value < 0 || value > 65535) {
7840 PyErr_SetString(PyExc_TypeError,
7841 "character mapping must be in range(65536)");
7842 Py_DECREF(x);
7843 goto onError;
7844 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007845 if (unicode_putchar(&v, &outpos, value) < 0)
7846 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007847 }
7848 else if (x == Py_None) {
7849 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007850 startinpos = s-starts;
7851 endinpos = startinpos+1;
7852 if (unicode_decode_call_errorhandler(
7853 errors, &errorHandler,
7854 "charmap", "character maps to <undefined>",
7855 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007856 &v, &outpos)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007857 Py_DECREF(x);
7858 goto onError;
7859 }
7860 Py_DECREF(x);
7861 continue;
7862 }
7863 else if (PyUnicode_Check(x)) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007864 Py_ssize_t targetsize;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007865
Benjamin Petersonbac79492012-01-14 13:34:47 -05007866 if (PyUnicode_READY(x) == -1)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007867 goto onError;
7868 targetsize = PyUnicode_GET_LENGTH(x);
7869
7870 if (targetsize == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007871 /* 1-1 mapping */
Victor Stinner62aa4d02011-11-09 00:03:45 +01007872 if (unicode_putchar(&v, &outpos,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007873 PyUnicode_READ_CHAR(x, 0)) < 0)
7874 goto onError;
7875 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007876 else if (targetsize > 1) {
7877 /* 1-n mapping */
7878 if (targetsize > extrachars) {
7879 /* resize first */
Benjamin Peterson29060642009-01-31 22:14:21 +00007880 Py_ssize_t needed = (targetsize - extrachars) + \
7881 (targetsize << 2);
7882 extrachars += needed;
7883 /* XXX overflow detection missing */
Victor Stinner16e6a802011-12-12 13:24:15 +01007884 if (unicode_resize(&v,
7885 PyUnicode_GET_LENGTH(v) + needed) < 0)
7886 {
Benjamin Peterson29060642009-01-31 22:14:21 +00007887 Py_DECREF(x);
7888 goto onError;
7889 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007890 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007891 if (unicode_widen(&v, PyUnicode_MAX_CHAR_VALUE(x)) < 0)
7892 goto onError;
7893 PyUnicode_CopyCharacters(v, outpos, x, 0, targetsize);
7894 outpos += targetsize;
Benjamin Peterson29060642009-01-31 22:14:21 +00007895 extrachars -= targetsize;
7896 }
7897 /* 1-0 mapping: skip the character */
7898 }
7899 else {
7900 /* wrong return value */
7901 PyErr_SetString(PyExc_TypeError,
7902 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00007903 Py_DECREF(x);
7904 goto onError;
7905 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007906 Py_DECREF(x);
7907 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007908 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007909 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007910 if (unicode_resize(&v, outpos) < 0)
Antoine Pitroua8f63c02011-11-08 18:37:16 +01007911 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007912 Py_XDECREF(errorHandler);
7913 Py_XDECREF(exc);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007914 return unicode_result(v);
Tim Petersced69f82003-09-16 20:30:58 +00007915
Benjamin Peterson29060642009-01-31 22:14:21 +00007916 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007917 Py_XDECREF(errorHandler);
7918 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007919 Py_XDECREF(v);
7920 return NULL;
7921}
7922
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007923/* Charmap encoding: the lookup table */
7924
Alexander Belopolsky40018472011-02-26 01:02:56 +00007925struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007926 PyObject_HEAD
7927 unsigned char level1[32];
7928 int count2, count3;
7929 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007930};
7931
7932static PyObject*
7933encoding_map_size(PyObject *obj, PyObject* args)
7934{
7935 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007936 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007937 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007938}
7939
7940static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007941 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007942 PyDoc_STR("Return the size (in bytes) of this object") },
7943 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007944};
7945
7946static void
7947encoding_map_dealloc(PyObject* o)
7948{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007949 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007950}
7951
7952static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007953 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007954 "EncodingMap", /*tp_name*/
7955 sizeof(struct encoding_map), /*tp_basicsize*/
7956 0, /*tp_itemsize*/
7957 /* methods */
7958 encoding_map_dealloc, /*tp_dealloc*/
7959 0, /*tp_print*/
7960 0, /*tp_getattr*/
7961 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007962 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007963 0, /*tp_repr*/
7964 0, /*tp_as_number*/
7965 0, /*tp_as_sequence*/
7966 0, /*tp_as_mapping*/
7967 0, /*tp_hash*/
7968 0, /*tp_call*/
7969 0, /*tp_str*/
7970 0, /*tp_getattro*/
7971 0, /*tp_setattro*/
7972 0, /*tp_as_buffer*/
7973 Py_TPFLAGS_DEFAULT, /*tp_flags*/
7974 0, /*tp_doc*/
7975 0, /*tp_traverse*/
7976 0, /*tp_clear*/
7977 0, /*tp_richcompare*/
7978 0, /*tp_weaklistoffset*/
7979 0, /*tp_iter*/
7980 0, /*tp_iternext*/
7981 encoding_map_methods, /*tp_methods*/
7982 0, /*tp_members*/
7983 0, /*tp_getset*/
7984 0, /*tp_base*/
7985 0, /*tp_dict*/
7986 0, /*tp_descr_get*/
7987 0, /*tp_descr_set*/
7988 0, /*tp_dictoffset*/
7989 0, /*tp_init*/
7990 0, /*tp_alloc*/
7991 0, /*tp_new*/
7992 0, /*tp_free*/
7993 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007994};
7995
7996PyObject*
7997PyUnicode_BuildEncodingMap(PyObject* string)
7998{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007999 PyObject *result;
8000 struct encoding_map *mresult;
8001 int i;
8002 int need_dict = 0;
8003 unsigned char level1[32];
8004 unsigned char level2[512];
8005 unsigned char *mlevel1, *mlevel2, *mlevel3;
8006 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008007 int kind;
8008 void *data;
8009 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008010
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008011 if (!PyUnicode_Check(string) || PyUnicode_GET_LENGTH(string) != 256) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008012 PyErr_BadArgument();
8013 return NULL;
8014 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008015 kind = PyUnicode_KIND(string);
8016 data = PyUnicode_DATA(string);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008017 memset(level1, 0xFF, sizeof level1);
8018 memset(level2, 0xFF, sizeof level2);
8019
8020 /* If there isn't a one-to-one mapping of NULL to \0,
8021 or if there are non-BMP characters, we need to use
8022 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008023 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008024 need_dict = 1;
8025 for (i = 1; i < 256; i++) {
8026 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008027 ch = PyUnicode_READ(kind, data, i);
8028 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008029 need_dict = 1;
8030 break;
8031 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008032 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008033 /* unmapped character */
8034 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008035 l1 = ch >> 11;
8036 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008037 if (level1[l1] == 0xFF)
8038 level1[l1] = count2++;
8039 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00008040 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008041 }
8042
8043 if (count2 >= 0xFF || count3 >= 0xFF)
8044 need_dict = 1;
8045
8046 if (need_dict) {
8047 PyObject *result = PyDict_New();
8048 PyObject *key, *value;
8049 if (!result)
8050 return NULL;
8051 for (i = 0; i < 256; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008052 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00008053 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008054 if (!key || !value)
8055 goto failed1;
8056 if (PyDict_SetItem(result, key, value) == -1)
8057 goto failed1;
8058 Py_DECREF(key);
8059 Py_DECREF(value);
8060 }
8061 return result;
8062 failed1:
8063 Py_XDECREF(key);
8064 Py_XDECREF(value);
8065 Py_DECREF(result);
8066 return NULL;
8067 }
8068
8069 /* Create a three-level trie */
8070 result = PyObject_MALLOC(sizeof(struct encoding_map) +
8071 16*count2 + 128*count3 - 1);
8072 if (!result)
8073 return PyErr_NoMemory();
8074 PyObject_Init(result, &EncodingMapType);
8075 mresult = (struct encoding_map*)result;
8076 mresult->count2 = count2;
8077 mresult->count3 = count3;
8078 mlevel1 = mresult->level1;
8079 mlevel2 = mresult->level23;
8080 mlevel3 = mresult->level23 + 16*count2;
8081 memcpy(mlevel1, level1, 32);
8082 memset(mlevel2, 0xFF, 16*count2);
8083 memset(mlevel3, 0, 128*count3);
8084 count3 = 0;
8085 for (i = 1; i < 256; i++) {
8086 int o1, o2, o3, i2, i3;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008087 if (PyUnicode_READ(kind, data, i) == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008088 /* unmapped character */
8089 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008090 o1 = PyUnicode_READ(kind, data, i)>>11;
8091 o2 = (PyUnicode_READ(kind, data, i)>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008092 i2 = 16*mlevel1[o1] + o2;
8093 if (mlevel2[i2] == 0xFF)
8094 mlevel2[i2] = count3++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008095 o3 = PyUnicode_READ(kind, data, i) & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008096 i3 = 128*mlevel2[i2] + o3;
8097 mlevel3[i3] = i;
8098 }
8099 return result;
8100}
8101
8102static int
Victor Stinner22168992011-11-20 17:09:18 +01008103encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008104{
8105 struct encoding_map *map = (struct encoding_map*)mapping;
8106 int l1 = c>>11;
8107 int l2 = (c>>7) & 0xF;
8108 int l3 = c & 0x7F;
8109 int i;
8110
Victor Stinner22168992011-11-20 17:09:18 +01008111 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00008112 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008113 if (c == 0)
8114 return 0;
8115 /* level 1*/
8116 i = map->level1[l1];
8117 if (i == 0xFF) {
8118 return -1;
8119 }
8120 /* level 2*/
8121 i = map->level23[16*i+l2];
8122 if (i == 0xFF) {
8123 return -1;
8124 }
8125 /* level 3 */
8126 i = map->level23[16*map->count2 + 128*i + l3];
8127 if (i == 0) {
8128 return -1;
8129 }
8130 return i;
8131}
8132
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008133/* Lookup the character ch in the mapping. If the character
8134 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00008135 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008136static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01008137charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008138{
Christian Heimes217cfd12007-12-02 14:31:20 +00008139 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008140 PyObject *x;
8141
8142 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008143 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008144 x = PyObject_GetItem(mapping, w);
8145 Py_DECREF(w);
8146 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008147 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8148 /* No mapping found means: mapping is undefined. */
8149 PyErr_Clear();
8150 x = Py_None;
8151 Py_INCREF(x);
8152 return x;
8153 } else
8154 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008155 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00008156 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008157 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00008158 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008159 long value = PyLong_AS_LONG(x);
8160 if (value < 0 || value > 255) {
8161 PyErr_SetString(PyExc_TypeError,
8162 "character mapping must be in range(256)");
8163 Py_DECREF(x);
8164 return NULL;
8165 }
8166 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008167 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008168 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008169 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008170 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008171 /* wrong return value */
8172 PyErr_Format(PyExc_TypeError,
8173 "character mapping must return integer, bytes or None, not %.400s",
8174 x->ob_type->tp_name);
8175 Py_DECREF(x);
8176 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008177 }
8178}
8179
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008180static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008181charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008182{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008183 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8184 /* exponentially overallocate to minimize reallocations */
8185 if (requiredsize < 2*outsize)
8186 requiredsize = 2*outsize;
8187 if (_PyBytes_Resize(outobj, requiredsize))
8188 return -1;
8189 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008190}
8191
Benjamin Peterson14339b62009-01-31 16:36:08 +00008192typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008193 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008194} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008195/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008196 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008197 space is available. Return a new reference to the object that
8198 was put in the output buffer, or Py_None, if the mapping was undefined
8199 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008200 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008201static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01008202charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008203 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008204{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008205 PyObject *rep;
8206 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008207 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008208
Christian Heimes90aa7642007-12-19 02:45:37 +00008209 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008210 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008211 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008212 if (res == -1)
8213 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008214 if (outsize<requiredsize)
8215 if (charmapencode_resize(outobj, outpos, requiredsize))
8216 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008217 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008218 outstart[(*outpos)++] = (char)res;
8219 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008220 }
8221
8222 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008223 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008224 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008225 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008226 Py_DECREF(rep);
8227 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008228 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008229 if (PyLong_Check(rep)) {
8230 Py_ssize_t requiredsize = *outpos+1;
8231 if (outsize<requiredsize)
8232 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8233 Py_DECREF(rep);
8234 return enc_EXCEPTION;
8235 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008236 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008237 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008238 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008239 else {
8240 const char *repchars = PyBytes_AS_STRING(rep);
8241 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8242 Py_ssize_t requiredsize = *outpos+repsize;
8243 if (outsize<requiredsize)
8244 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8245 Py_DECREF(rep);
8246 return enc_EXCEPTION;
8247 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008248 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008249 memcpy(outstart + *outpos, repchars, repsize);
8250 *outpos += repsize;
8251 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008252 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008253 Py_DECREF(rep);
8254 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008255}
8256
8257/* handle an error in PyUnicode_EncodeCharmap
8258 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008259static int
8260charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008261 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008262 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00008263 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008264 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008265{
8266 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008267 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008268 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008269 enum PyUnicode_Kind kind;
8270 void *data;
8271 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008272 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008273 Py_ssize_t collstartpos = *inpos;
8274 Py_ssize_t collendpos = *inpos+1;
8275 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008276 char *encoding = "charmap";
8277 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008278 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008279 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008280 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008281
Benjamin Petersonbac79492012-01-14 13:34:47 -05008282 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008283 return -1;
8284 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008285 /* find all unencodable characters */
8286 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008287 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008288 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008289 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008290 val = encoding_map_lookup(ch, mapping);
8291 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008292 break;
8293 ++collendpos;
8294 continue;
8295 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008296
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008297 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8298 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008299 if (rep==NULL)
8300 return -1;
8301 else if (rep!=Py_None) {
8302 Py_DECREF(rep);
8303 break;
8304 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008305 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008306 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008307 }
8308 /* cache callback name lookup
8309 * (if not done yet, i.e. it's the first error) */
8310 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008311 if ((errors==NULL) || (!strcmp(errors, "strict")))
8312 *known_errorHandler = 1;
8313 else if (!strcmp(errors, "replace"))
8314 *known_errorHandler = 2;
8315 else if (!strcmp(errors, "ignore"))
8316 *known_errorHandler = 3;
8317 else if (!strcmp(errors, "xmlcharrefreplace"))
8318 *known_errorHandler = 4;
8319 else
8320 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008321 }
8322 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008323 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008324 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008325 return -1;
8326 case 2: /* replace */
8327 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008328 x = charmapencode_output('?', mapping, res, respos);
8329 if (x==enc_EXCEPTION) {
8330 return -1;
8331 }
8332 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008333 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008334 return -1;
8335 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008336 }
8337 /* fall through */
8338 case 3: /* ignore */
8339 *inpos = collendpos;
8340 break;
8341 case 4: /* xmlcharrefreplace */
8342 /* generate replacement (temporarily (mis)uses p) */
8343 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008344 char buffer[2+29+1+1];
8345 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008346 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008347 for (cp = buffer; *cp; ++cp) {
8348 x = charmapencode_output(*cp, mapping, res, respos);
8349 if (x==enc_EXCEPTION)
8350 return -1;
8351 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008352 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008353 return -1;
8354 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008355 }
8356 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008357 *inpos = collendpos;
8358 break;
8359 default:
8360 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008361 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008362 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008363 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008364 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008365 if (PyBytes_Check(repunicode)) {
8366 /* Directly copy bytes result to output. */
8367 Py_ssize_t outsize = PyBytes_Size(*res);
8368 Py_ssize_t requiredsize;
8369 repsize = PyBytes_Size(repunicode);
8370 requiredsize = *respos + repsize;
8371 if (requiredsize > outsize)
8372 /* Make room for all additional bytes. */
8373 if (charmapencode_resize(res, respos, requiredsize)) {
8374 Py_DECREF(repunicode);
8375 return -1;
8376 }
8377 memcpy(PyBytes_AsString(*res) + *respos,
8378 PyBytes_AsString(repunicode), repsize);
8379 *respos += repsize;
8380 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008381 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008382 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008383 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008384 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008385 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008386 Py_DECREF(repunicode);
8387 return -1;
8388 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008389 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008390 data = PyUnicode_DATA(repunicode);
8391 kind = PyUnicode_KIND(repunicode);
8392 for (index = 0; index < repsize; index++) {
8393 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8394 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008395 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008396 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008397 return -1;
8398 }
8399 else if (x==enc_FAILED) {
8400 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008401 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008402 return -1;
8403 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008404 }
8405 *inpos = newpos;
8406 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008407 }
8408 return 0;
8409}
8410
Alexander Belopolsky40018472011-02-26 01:02:56 +00008411PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008412_PyUnicode_EncodeCharmap(PyObject *unicode,
8413 PyObject *mapping,
8414 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008415{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008416 /* output object */
8417 PyObject *res = NULL;
8418 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008419 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008420 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008421 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008422 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008423 PyObject *errorHandler = NULL;
8424 PyObject *exc = NULL;
8425 /* the following variable is used for caching string comparisons
8426 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8427 * 3=ignore, 4=xmlcharrefreplace */
8428 int known_errorHandler = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008429
Benjamin Petersonbac79492012-01-14 13:34:47 -05008430 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008431 return NULL;
8432 size = PyUnicode_GET_LENGTH(unicode);
8433
Guido van Rossumd57fd912000-03-10 22:53:23 +00008434 /* Default to Latin-1 */
8435 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008436 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008437
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008438 /* allocate enough for a simple encoding without
8439 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008440 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008441 if (res == NULL)
8442 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008443 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008444 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008445
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008446 while (inpos<size) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008447 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008448 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008449 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008450 if (x==enc_EXCEPTION) /* error */
8451 goto onError;
8452 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008453 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008454 &exc,
8455 &known_errorHandler, &errorHandler, errors,
8456 &res, &respos)) {
8457 goto onError;
8458 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008459 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008460 else
8461 /* done with this character => adjust input position */
8462 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008463 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008464
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008465 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008466 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008467 if (_PyBytes_Resize(&res, respos) < 0)
8468 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008469
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008470 Py_XDECREF(exc);
8471 Py_XDECREF(errorHandler);
8472 return res;
8473
Benjamin Peterson29060642009-01-31 22:14:21 +00008474 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008475 Py_XDECREF(res);
8476 Py_XDECREF(exc);
8477 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008478 return NULL;
8479}
8480
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008481/* Deprecated */
8482PyObject *
8483PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8484 Py_ssize_t size,
8485 PyObject *mapping,
8486 const char *errors)
8487{
8488 PyObject *result;
8489 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8490 if (unicode == NULL)
8491 return NULL;
8492 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8493 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008494 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008495}
8496
Alexander Belopolsky40018472011-02-26 01:02:56 +00008497PyObject *
8498PyUnicode_AsCharmapString(PyObject *unicode,
8499 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008500{
8501 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008502 PyErr_BadArgument();
8503 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008504 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008505 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008506}
8507
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008508/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008509static void
8510make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008511 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008512 Py_ssize_t startpos, Py_ssize_t endpos,
8513 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008514{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008515 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008516 *exceptionObject = _PyUnicodeTranslateError_Create(
8517 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008518 }
8519 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008520 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8521 goto onError;
8522 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8523 goto onError;
8524 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8525 goto onError;
8526 return;
8527 onError:
8528 Py_DECREF(*exceptionObject);
8529 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008530 }
8531}
8532
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008533/* raises a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008534static void
8535raise_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008536 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008537 Py_ssize_t startpos, Py_ssize_t endpos,
8538 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008539{
8540 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008541 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008542 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008543 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008544}
8545
8546/* error handling callback helper:
8547 build arguments, call the callback and check the arguments,
8548 put the result into newpos and return the replacement string, which
8549 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008550static PyObject *
8551unicode_translate_call_errorhandler(const char *errors,
8552 PyObject **errorHandler,
8553 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008554 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008555 Py_ssize_t startpos, Py_ssize_t endpos,
8556 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008557{
Benjamin Peterson142957c2008-07-04 19:55:29 +00008558 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008559
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008560 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008561 PyObject *restuple;
8562 PyObject *resunicode;
8563
8564 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008565 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008566 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008567 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008568 }
8569
8570 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008571 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008572 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008573 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008574
8575 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008576 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008577 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008578 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008579 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008580 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008581 Py_DECREF(restuple);
8582 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008583 }
8584 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008585 &resunicode, &i_newpos)) {
8586 Py_DECREF(restuple);
8587 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008588 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008589 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008590 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008591 else
8592 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008593 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008594 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
8595 Py_DECREF(restuple);
8596 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008597 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008598 Py_INCREF(resunicode);
8599 Py_DECREF(restuple);
8600 return resunicode;
8601}
8602
8603/* Lookup the character ch in the mapping and put the result in result,
8604 which must be decrefed by the caller.
8605 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008606static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008607charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008608{
Christian Heimes217cfd12007-12-02 14:31:20 +00008609 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008610 PyObject *x;
8611
8612 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008613 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008614 x = PyObject_GetItem(mapping, w);
8615 Py_DECREF(w);
8616 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008617 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8618 /* No mapping found means: use 1:1 mapping. */
8619 PyErr_Clear();
8620 *result = NULL;
8621 return 0;
8622 } else
8623 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008624 }
8625 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008626 *result = x;
8627 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008628 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008629 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008630 long value = PyLong_AS_LONG(x);
8631 long max = PyUnicode_GetMax();
8632 if (value < 0 || value > max) {
8633 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00008634 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008635 Py_DECREF(x);
8636 return -1;
8637 }
8638 *result = x;
8639 return 0;
8640 }
8641 else if (PyUnicode_Check(x)) {
8642 *result = x;
8643 return 0;
8644 }
8645 else {
8646 /* wrong return value */
8647 PyErr_SetString(PyExc_TypeError,
8648 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008649 Py_DECREF(x);
8650 return -1;
8651 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008652}
8653/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00008654 if not reallocate and adjust various state variables.
8655 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008656static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008657charmaptranslate_makespace(Py_UCS4 **outobj, Py_ssize_t *psize,
Benjamin Peterson29060642009-01-31 22:14:21 +00008658 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008659{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008660 Py_ssize_t oldsize = *psize;
Walter Dörwald4894c302003-10-24 14:25:28 +00008661 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008662 /* exponentially overallocate to minimize reallocations */
8663 if (requiredsize < 2 * oldsize)
8664 requiredsize = 2 * oldsize;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008665 *outobj = PyMem_Realloc(*outobj, requiredsize * sizeof(Py_UCS4));
8666 if (*outobj == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008667 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008668 *psize = requiredsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008669 }
8670 return 0;
8671}
8672/* lookup the character, put the result in the output string and adjust
8673 various state variables. Return a new reference to the object that
8674 was put in the output buffer in *result, or Py_None, if the mapping was
8675 undefined (in which case no character was written).
8676 The called must decref result.
8677 Return 0 on success, -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008678static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008679charmaptranslate_output(PyObject *input, Py_ssize_t ipos,
8680 PyObject *mapping, Py_UCS4 **output,
8681 Py_ssize_t *osize, Py_ssize_t *opos,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008682 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008683{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008684 Py_UCS4 curinp = PyUnicode_READ_CHAR(input, ipos);
8685 if (charmaptranslate_lookup(curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00008686 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008687 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008688 /* not found => default to 1:1 mapping */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008689 (*output)[(*opos)++] = curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008690 }
8691 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008692 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00008693 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008694 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008695 (*output)[(*opos)++] = (Py_UCS4)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008696 }
8697 else if (PyUnicode_Check(*res)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008698 Py_ssize_t repsize;
8699 if (PyUnicode_READY(*res) == -1)
8700 return -1;
8701 repsize = PyUnicode_GET_LENGTH(*res);
Benjamin Peterson29060642009-01-31 22:14:21 +00008702 if (repsize==1) {
8703 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008704 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00008705 }
8706 else if (repsize!=0) {
8707 /* more than one character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008708 Py_ssize_t requiredsize = *opos +
8709 (PyUnicode_GET_LENGTH(input) - ipos) +
Benjamin Peterson29060642009-01-31 22:14:21 +00008710 repsize - 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008711 Py_ssize_t i;
8712 if (charmaptranslate_makespace(output, osize, requiredsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00008713 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008714 for(i = 0; i < repsize; i++)
8715 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00008716 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008717 }
8718 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008719 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008720 return 0;
8721}
8722
Alexander Belopolsky40018472011-02-26 01:02:56 +00008723PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008724_PyUnicode_TranslateCharmap(PyObject *input,
8725 PyObject *mapping,
8726 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008727{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008728 /* input object */
8729 char *idata;
8730 Py_ssize_t size, i;
8731 int kind;
8732 /* output buffer */
8733 Py_UCS4 *output = NULL;
8734 Py_ssize_t osize;
8735 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008736 /* current output position */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008737 Py_ssize_t opos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008738 char *reason = "character maps to <undefined>";
8739 PyObject *errorHandler = NULL;
8740 PyObject *exc = NULL;
8741 /* the following variable is used for caching string comparisons
8742 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8743 * 3=ignore, 4=xmlcharrefreplace */
8744 int known_errorHandler = -1;
8745
Guido van Rossumd57fd912000-03-10 22:53:23 +00008746 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008747 PyErr_BadArgument();
8748 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008749 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008750
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008751 if (PyUnicode_READY(input) == -1)
8752 return NULL;
8753 idata = (char*)PyUnicode_DATA(input);
8754 kind = PyUnicode_KIND(input);
8755 size = PyUnicode_GET_LENGTH(input);
8756 i = 0;
8757
8758 if (size == 0) {
8759 Py_INCREF(input);
8760 return input;
8761 }
8762
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008763 /* allocate enough for a simple 1:1 translation without
8764 replacements, if we need more, we'll resize */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008765 osize = size;
8766 output = PyMem_Malloc(osize * sizeof(Py_UCS4));
8767 opos = 0;
8768 if (output == NULL) {
8769 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00008770 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008771 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008772
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008773 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008774 /* try to encode it */
8775 PyObject *x = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008776 if (charmaptranslate_output(input, i, mapping,
8777 &output, &osize, &opos, &x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008778 Py_XDECREF(x);
8779 goto onError;
8780 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008781 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00008782 if (x!=Py_None) /* it worked => adjust input pointer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008783 ++i;
Benjamin Peterson29060642009-01-31 22:14:21 +00008784 else { /* untranslatable character */
8785 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8786 Py_ssize_t repsize;
8787 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008788 Py_ssize_t uni2;
Benjamin Peterson29060642009-01-31 22:14:21 +00008789 /* startpos for collecting untranslatable chars */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008790 Py_ssize_t collstart = i;
8791 Py_ssize_t collend = i+1;
8792 Py_ssize_t coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008793
Benjamin Peterson29060642009-01-31 22:14:21 +00008794 /* find all untranslatable characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008795 while (collend < size) {
8796 if (charmaptranslate_lookup(PyUnicode_READ(kind,idata, collend), mapping, &x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008797 goto onError;
8798 Py_XDECREF(x);
8799 if (x!=Py_None)
8800 break;
8801 ++collend;
8802 }
8803 /* cache callback name lookup
8804 * (if not done yet, i.e. it's the first error) */
8805 if (known_errorHandler==-1) {
8806 if ((errors==NULL) || (!strcmp(errors, "strict")))
8807 known_errorHandler = 1;
8808 else if (!strcmp(errors, "replace"))
8809 known_errorHandler = 2;
8810 else if (!strcmp(errors, "ignore"))
8811 known_errorHandler = 3;
8812 else if (!strcmp(errors, "xmlcharrefreplace"))
8813 known_errorHandler = 4;
8814 else
8815 known_errorHandler = 0;
8816 }
8817 switch (known_errorHandler) {
8818 case 1: /* strict */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008819 raise_translate_exception(&exc, input, collstart,
8820 collend, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008821 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008822 case 2: /* replace */
8823 /* No need to check for space, this is a 1:1 replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008824 for (coll = collstart; coll<collend; coll++)
8825 output[opos++] = '?';
Benjamin Peterson29060642009-01-31 22:14:21 +00008826 /* fall through */
8827 case 3: /* ignore */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008828 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008829 break;
8830 case 4: /* xmlcharrefreplace */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008831 /* generate replacement (temporarily (mis)uses i) */
8832 for (i = collstart; i < collend; ++i) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008833 char buffer[2+29+1+1];
8834 char *cp;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008835 sprintf(buffer, "&#%d;", PyUnicode_READ(kind, idata, i));
8836 if (charmaptranslate_makespace(&output, &osize,
8837 opos+strlen(buffer)+(size-collend)))
Benjamin Peterson29060642009-01-31 22:14:21 +00008838 goto onError;
8839 for (cp = buffer; *cp; ++cp)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008840 output[opos++] = *cp;
Benjamin Peterson29060642009-01-31 22:14:21 +00008841 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008842 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008843 break;
8844 default:
8845 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008846 reason, input, &exc,
8847 collstart, collend, &newpos);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008848 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008849 goto onError;
Benjamin Peterson9ca3ffa2012-01-01 16:04:29 -06008850 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008851 Py_DECREF(repunicode);
8852 goto onError;
8853 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008854 /* generate replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008855 repsize = PyUnicode_GET_LENGTH(repunicode);
8856 if (charmaptranslate_makespace(&output, &osize,
8857 opos+repsize+(size-collend))) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008858 Py_DECREF(repunicode);
8859 goto onError;
8860 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008861 for (uni2 = 0; repsize-->0; ++uni2)
8862 output[opos++] = PyUnicode_READ_CHAR(repunicode, uni2);
8863 i = newpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00008864 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008865 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008866 }
8867 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008868 res = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, output, opos);
8869 if (!res)
8870 goto onError;
8871 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008872 Py_XDECREF(exc);
8873 Py_XDECREF(errorHandler);
8874 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008875
Benjamin Peterson29060642009-01-31 22:14:21 +00008876 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008877 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008878 Py_XDECREF(exc);
8879 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008880 return NULL;
8881}
8882
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008883/* Deprecated. Use PyUnicode_Translate instead. */
8884PyObject *
8885PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8886 Py_ssize_t size,
8887 PyObject *mapping,
8888 const char *errors)
8889{
8890 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8891 if (!unicode)
8892 return NULL;
8893 return _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8894}
8895
Alexander Belopolsky40018472011-02-26 01:02:56 +00008896PyObject *
8897PyUnicode_Translate(PyObject *str,
8898 PyObject *mapping,
8899 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008900{
8901 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008902
Guido van Rossumd57fd912000-03-10 22:53:23 +00008903 str = PyUnicode_FromObject(str);
8904 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008905 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008906 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008907 Py_DECREF(str);
8908 return result;
Tim Petersced69f82003-09-16 20:30:58 +00008909
Benjamin Peterson29060642009-01-31 22:14:21 +00008910 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00008911 Py_XDECREF(str);
8912 return NULL;
8913}
Tim Petersced69f82003-09-16 20:30:58 +00008914
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008915static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008916fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008917{
8918 /* No need to call PyUnicode_READY(self) because this function is only
8919 called as a callback from fixup() which does it already. */
8920 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8921 const int kind = PyUnicode_KIND(self);
8922 void *data = PyUnicode_DATA(self);
8923 Py_UCS4 maxchar = 0, ch, fixed;
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008924 int modified = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008925 Py_ssize_t i;
8926
8927 for (i = 0; i < len; ++i) {
8928 ch = PyUnicode_READ(kind, data, i);
8929 fixed = 0;
8930 if (ch > 127) {
8931 if (Py_UNICODE_ISSPACE(ch))
8932 fixed = ' ';
8933 else {
8934 const int decimal = Py_UNICODE_TODECIMAL(ch);
8935 if (decimal >= 0)
8936 fixed = '0' + decimal;
8937 }
8938 if (fixed != 0) {
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008939 modified = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008940 if (fixed > maxchar)
8941 maxchar = fixed;
8942 PyUnicode_WRITE(kind, data, i, fixed);
8943 }
8944 else if (ch > maxchar)
8945 maxchar = ch;
8946 }
8947 else if (ch > maxchar)
8948 maxchar = ch;
8949 }
8950
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008951 return (modified) ? maxchar : 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008952}
8953
8954PyObject *
8955_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
8956{
8957 if (!PyUnicode_Check(unicode)) {
8958 PyErr_BadInternalCall();
8959 return NULL;
8960 }
8961 if (PyUnicode_READY(unicode) == -1)
8962 return NULL;
8963 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
8964 /* If the string is already ASCII, just return the same string */
8965 Py_INCREF(unicode);
8966 return unicode;
8967 }
Victor Stinner9310abb2011-10-05 00:59:23 +02008968 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008969}
8970
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008971PyObject *
8972PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
8973 Py_ssize_t length)
8974{
Victor Stinnerf0124502011-11-21 23:12:56 +01008975 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008976 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01008977 Py_UCS4 maxchar;
8978 enum PyUnicode_Kind kind;
8979 void *data;
8980
Victor Stinner99d7ad02012-02-22 13:37:39 +01008981 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008982 for (i = 0; i < length; i++) {
Victor Stinnerf0124502011-11-21 23:12:56 +01008983 Py_UNICODE ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008984 if (ch > 127) {
8985 int decimal = Py_UNICODE_TODECIMAL(ch);
8986 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01008987 ch = '0' + decimal;
Victor Stinner99d7ad02012-02-22 13:37:39 +01008988 maxchar = Py_MAX(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008989 }
8990 }
Victor Stinnerf0124502011-11-21 23:12:56 +01008991
8992 /* Copy to a new string */
8993 decimal = PyUnicode_New(length, maxchar);
8994 if (decimal == NULL)
8995 return decimal;
8996 kind = PyUnicode_KIND(decimal);
8997 data = PyUnicode_DATA(decimal);
8998 /* Iterate over code points */
8999 for (i = 0; i < length; i++) {
9000 Py_UNICODE ch = s[i];
9001 if (ch > 127) {
9002 int decimal = Py_UNICODE_TODECIMAL(ch);
9003 if (decimal >= 0)
9004 ch = '0' + decimal;
9005 }
9006 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009007 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01009008 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009009}
Guido van Rossum9e896b32000-04-05 20:11:21 +00009010/* --- Decimal Encoder ---------------------------------------------------- */
9011
Alexander Belopolsky40018472011-02-26 01:02:56 +00009012int
9013PyUnicode_EncodeDecimal(Py_UNICODE *s,
9014 Py_ssize_t length,
9015 char *output,
9016 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00009017{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01009018 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01009019 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01009020 enum PyUnicode_Kind kind;
9021 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009022
9023 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009024 PyErr_BadArgument();
9025 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009026 }
9027
Victor Stinner42bf7752011-11-21 22:52:58 +01009028 unicode = PyUnicode_FromUnicode(s, length);
9029 if (unicode == NULL)
9030 return -1;
9031
Benjamin Petersonbac79492012-01-14 13:34:47 -05009032 if (PyUnicode_READY(unicode) == -1) {
Victor Stinner6345be92011-11-25 20:09:01 +01009033 Py_DECREF(unicode);
9034 return -1;
9035 }
Victor Stinner42bf7752011-11-21 22:52:58 +01009036 kind = PyUnicode_KIND(unicode);
9037 data = PyUnicode_DATA(unicode);
9038
Victor Stinnerb84d7232011-11-22 01:50:07 +01009039 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01009040 PyObject *exc;
9041 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00009042 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01009043 Py_ssize_t startpos;
9044
9045 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00009046
Benjamin Peterson29060642009-01-31 22:14:21 +00009047 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009048 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01009049 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009050 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009051 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009052 decimal = Py_UNICODE_TODECIMAL(ch);
9053 if (decimal >= 0) {
9054 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009055 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009056 continue;
9057 }
9058 if (0 < ch && ch < 256) {
9059 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009060 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009061 continue;
9062 }
Victor Stinner6345be92011-11-25 20:09:01 +01009063
Victor Stinner42bf7752011-11-21 22:52:58 +01009064 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01009065 exc = NULL;
9066 raise_encode_exception(&exc, "decimal", unicode,
9067 startpos, startpos+1,
9068 "invalid decimal Unicode string");
9069 Py_XDECREF(exc);
9070 Py_DECREF(unicode);
9071 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009072 }
9073 /* 0-terminate the output string */
9074 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01009075 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00009076 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009077}
9078
Guido van Rossumd57fd912000-03-10 22:53:23 +00009079/* --- Helpers ------------------------------------------------------------ */
9080
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009081static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02009082any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009083 Py_ssize_t start,
9084 Py_ssize_t end)
9085{
9086 int kind1, kind2, kind;
9087 void *buf1, *buf2;
9088 Py_ssize_t len1, len2, result;
9089
9090 kind1 = PyUnicode_KIND(s1);
9091 kind2 = PyUnicode_KIND(s2);
9092 kind = kind1 > kind2 ? kind1 : kind2;
9093 buf1 = PyUnicode_DATA(s1);
9094 buf2 = PyUnicode_DATA(s2);
9095 if (kind1 != kind)
9096 buf1 = _PyUnicode_AsKind(s1, kind);
9097 if (!buf1)
9098 return -2;
9099 if (kind2 != kind)
9100 buf2 = _PyUnicode_AsKind(s2, kind);
9101 if (!buf2) {
9102 if (kind1 != kind) PyMem_Free(buf1);
9103 return -2;
9104 }
9105 len1 = PyUnicode_GET_LENGTH(s1);
9106 len2 = PyUnicode_GET_LENGTH(s2);
9107
Victor Stinner794d5672011-10-10 03:21:36 +02009108 if (direction > 0) {
Benjamin Petersonead6b532011-12-20 17:23:42 -06009109 switch (kind) {
Victor Stinner794d5672011-10-10 03:21:36 +02009110 case PyUnicode_1BYTE_KIND:
9111 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9112 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9113 else
9114 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9115 break;
9116 case PyUnicode_2BYTE_KIND:
9117 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9118 break;
9119 case PyUnicode_4BYTE_KIND:
9120 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9121 break;
9122 default:
9123 assert(0); result = -2;
9124 }
9125 }
9126 else {
Benjamin Petersonead6b532011-12-20 17:23:42 -06009127 switch (kind) {
Victor Stinner794d5672011-10-10 03:21:36 +02009128 case PyUnicode_1BYTE_KIND:
9129 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9130 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9131 else
9132 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9133 break;
9134 case PyUnicode_2BYTE_KIND:
9135 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9136 break;
9137 case PyUnicode_4BYTE_KIND:
9138 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9139 break;
9140 default:
9141 assert(0); result = -2;
9142 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009143 }
9144
9145 if (kind1 != kind)
9146 PyMem_Free(buf1);
9147 if (kind2 != kind)
9148 PyMem_Free(buf2);
9149
9150 return result;
9151}
9152
9153Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01009154_PyUnicode_InsertThousandsGrouping(
9155 PyObject *unicode, Py_ssize_t index,
9156 Py_ssize_t n_buffer,
9157 void *digits, Py_ssize_t n_digits,
9158 Py_ssize_t min_width,
9159 const char *grouping, PyObject *thousands_sep,
9160 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009161{
Victor Stinner41a863c2012-02-24 00:37:51 +01009162 unsigned int kind, thousands_sep_kind;
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009163 char *data, *thousands_sep_data;
Victor Stinner41a863c2012-02-24 00:37:51 +01009164 Py_ssize_t thousands_sep_len;
9165 Py_ssize_t len;
9166
9167 if (unicode != NULL) {
9168 kind = PyUnicode_KIND(unicode);
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009169 data = (char *) PyUnicode_DATA(unicode) + index * kind;
Victor Stinner41a863c2012-02-24 00:37:51 +01009170 }
9171 else {
9172 kind = PyUnicode_1BYTE_KIND;
9173 data = NULL;
9174 }
9175 thousands_sep_kind = PyUnicode_KIND(thousands_sep);
9176 thousands_sep_data = PyUnicode_DATA(thousands_sep);
9177 thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
9178 if (unicode != NULL && thousands_sep_kind != kind) {
Victor Stinner90f50d42012-02-24 01:44:47 +01009179 if (thousands_sep_kind < kind) {
9180 thousands_sep_data = _PyUnicode_AsKind(thousands_sep, kind);
9181 if (!thousands_sep_data)
9182 return -1;
9183 }
9184 else {
9185 data = _PyUnicode_AsKind(unicode, thousands_sep_kind);
9186 if (!data)
9187 return -1;
9188 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009189 }
9190
Benjamin Petersonead6b532011-12-20 17:23:42 -06009191 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009192 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009193 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
Victor Stinner41a863c2012-02-24 00:37:51 +01009194 len = asciilib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009195 (Py_UCS1 *) data, n_buffer, (Py_UCS1 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009196 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009197 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009198 else
Victor Stinner41a863c2012-02-24 00:37:51 +01009199 len = ucs1lib_InsertThousandsGrouping(
Victor Stinnerc3cec782011-10-05 21:24:08 +02009200 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009201 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009202 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009203 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009204 case PyUnicode_2BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009205 len = ucs2lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009206 (Py_UCS2 *) data, n_buffer, (Py_UCS2 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009207 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009208 (Py_UCS2 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009209 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009210 case PyUnicode_4BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009211 len = ucs4lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009212 (Py_UCS4 *) data, n_buffer, (Py_UCS4 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009213 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009214 (Py_UCS4 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009215 break;
9216 default:
9217 assert(0);
9218 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009219 }
Victor Stinner90f50d42012-02-24 01:44:47 +01009220 if (unicode != NULL && thousands_sep_kind != kind) {
9221 if (thousands_sep_kind < kind)
9222 PyMem_Free(thousands_sep_data);
9223 else
9224 PyMem_Free(data);
9225 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009226 if (unicode == NULL) {
9227 *maxchar = 127;
9228 if (len != n_digits) {
9229 *maxchar = Py_MAX(*maxchar,
9230 PyUnicode_MAX_CHAR_VALUE(thousands_sep));
9231 }
9232 }
9233 return len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009234}
9235
9236
Thomas Wouters477c8d52006-05-27 19:21:47 +00009237/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009238#define ADJUST_INDICES(start, end, len) \
9239 if (end > len) \
9240 end = len; \
9241 else if (end < 0) { \
9242 end += len; \
9243 if (end < 0) \
9244 end = 0; \
9245 } \
9246 if (start < 0) { \
9247 start += len; \
9248 if (start < 0) \
9249 start = 0; \
9250 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009251
Alexander Belopolsky40018472011-02-26 01:02:56 +00009252Py_ssize_t
9253PyUnicode_Count(PyObject *str,
9254 PyObject *substr,
9255 Py_ssize_t start,
9256 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009257{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009258 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009259 PyObject* str_obj;
9260 PyObject* sub_obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009261 int kind1, kind2, kind;
9262 void *buf1 = NULL, *buf2 = NULL;
9263 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009264
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009265 str_obj = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009266 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00009267 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009268 sub_obj = PyUnicode_FromObject(substr);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009269 if (!sub_obj) {
9270 Py_DECREF(str_obj);
9271 return -1;
9272 }
Benjamin Peterson4c13a4a2012-01-02 09:07:38 -06009273 if (PyUnicode_READY(sub_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
Benjamin Peterson5e458f52012-01-02 10:12:13 -06009274 Py_DECREF(sub_obj);
Benjamin Peterson29060642009-01-31 22:14:21 +00009275 Py_DECREF(str_obj);
9276 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009277 }
Tim Petersced69f82003-09-16 20:30:58 +00009278
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009279 kind1 = PyUnicode_KIND(str_obj);
9280 kind2 = PyUnicode_KIND(sub_obj);
9281 kind = kind1 > kind2 ? kind1 : kind2;
9282 buf1 = PyUnicode_DATA(str_obj);
9283 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009284 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009285 if (!buf1)
9286 goto onError;
9287 buf2 = PyUnicode_DATA(sub_obj);
9288 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009289 buf2 = _PyUnicode_AsKind(sub_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009290 if (!buf2)
9291 goto onError;
9292 len1 = PyUnicode_GET_LENGTH(str_obj);
9293 len2 = PyUnicode_GET_LENGTH(sub_obj);
9294
9295 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -06009296 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009297 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009298 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
9299 result = asciilib_count(
9300 ((Py_UCS1*)buf1) + start, end - start,
9301 buf2, len2, PY_SSIZE_T_MAX
9302 );
9303 else
9304 result = ucs1lib_count(
9305 ((Py_UCS1*)buf1) + start, end - start,
9306 buf2, len2, PY_SSIZE_T_MAX
9307 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009308 break;
9309 case PyUnicode_2BYTE_KIND:
9310 result = ucs2lib_count(
9311 ((Py_UCS2*)buf1) + start, end - start,
9312 buf2, len2, PY_SSIZE_T_MAX
9313 );
9314 break;
9315 case PyUnicode_4BYTE_KIND:
9316 result = ucs4lib_count(
9317 ((Py_UCS4*)buf1) + start, end - start,
9318 buf2, len2, PY_SSIZE_T_MAX
9319 );
9320 break;
9321 default:
9322 assert(0); result = 0;
9323 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009324
9325 Py_DECREF(sub_obj);
9326 Py_DECREF(str_obj);
9327
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009328 if (kind1 != kind)
9329 PyMem_Free(buf1);
9330 if (kind2 != kind)
9331 PyMem_Free(buf2);
9332
Guido van Rossumd57fd912000-03-10 22:53:23 +00009333 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009334 onError:
9335 Py_DECREF(sub_obj);
9336 Py_DECREF(str_obj);
9337 if (kind1 != kind && buf1)
9338 PyMem_Free(buf1);
9339 if (kind2 != kind && buf2)
9340 PyMem_Free(buf2);
9341 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009342}
9343
Alexander Belopolsky40018472011-02-26 01:02:56 +00009344Py_ssize_t
9345PyUnicode_Find(PyObject *str,
9346 PyObject *sub,
9347 Py_ssize_t start,
9348 Py_ssize_t end,
9349 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009350{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009351 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009352
Guido van Rossumd57fd912000-03-10 22:53:23 +00009353 str = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009354 if (!str)
Benjamin Peterson29060642009-01-31 22:14:21 +00009355 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009356 sub = PyUnicode_FromObject(sub);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009357 if (!sub) {
9358 Py_DECREF(str);
9359 return -2;
9360 }
9361 if (PyUnicode_READY(sub) == -1 || PyUnicode_READY(str) == -1) {
9362 Py_DECREF(sub);
Benjamin Peterson29060642009-01-31 22:14:21 +00009363 Py_DECREF(str);
9364 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009365 }
Tim Petersced69f82003-09-16 20:30:58 +00009366
Victor Stinner794d5672011-10-10 03:21:36 +02009367 result = any_find_slice(direction,
9368 str, sub, start, end
9369 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00009370
Guido van Rossumd57fd912000-03-10 22:53:23 +00009371 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009372 Py_DECREF(sub);
9373
Guido van Rossumd57fd912000-03-10 22:53:23 +00009374 return result;
9375}
9376
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009377Py_ssize_t
9378PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9379 Py_ssize_t start, Py_ssize_t end,
9380 int direction)
9381{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009382 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009383 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009384 if (PyUnicode_READY(str) == -1)
9385 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009386 if (start < 0 || end < 0) {
9387 PyErr_SetString(PyExc_IndexError, "string index out of range");
9388 return -2;
9389 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009390 if (end > PyUnicode_GET_LENGTH(str))
9391 end = PyUnicode_GET_LENGTH(str);
9392 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009393 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9394 kind, end-start, ch, direction);
9395 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009396 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009397 else
9398 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009399}
9400
Alexander Belopolsky40018472011-02-26 01:02:56 +00009401static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009402tailmatch(PyObject *self,
9403 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009404 Py_ssize_t start,
9405 Py_ssize_t end,
9406 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009407{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009408 int kind_self;
9409 int kind_sub;
9410 void *data_self;
9411 void *data_sub;
9412 Py_ssize_t offset;
9413 Py_ssize_t i;
9414 Py_ssize_t end_sub;
9415
9416 if (PyUnicode_READY(self) == -1 ||
9417 PyUnicode_READY(substring) == -1)
9418 return 0;
9419
9420 if (PyUnicode_GET_LENGTH(substring) == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009421 return 1;
9422
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009423 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9424 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009425 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009426 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009427
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009428 kind_self = PyUnicode_KIND(self);
9429 data_self = PyUnicode_DATA(self);
9430 kind_sub = PyUnicode_KIND(substring);
9431 data_sub = PyUnicode_DATA(substring);
9432 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9433
9434 if (direction > 0)
9435 offset = end;
9436 else
9437 offset = start;
9438
9439 if (PyUnicode_READ(kind_self, data_self, offset) ==
9440 PyUnicode_READ(kind_sub, data_sub, 0) &&
9441 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9442 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9443 /* If both are of the same kind, memcmp is sufficient */
9444 if (kind_self == kind_sub) {
9445 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009446 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009447 data_sub,
9448 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009449 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009450 }
9451 /* otherwise we have to compare each character by first accesing it */
9452 else {
9453 /* We do not need to compare 0 and len(substring)-1 because
9454 the if statement above ensured already that they are equal
9455 when we end up here. */
9456 // TODO: honor direction and do a forward or backwards search
9457 for (i = 1; i < end_sub; ++i) {
9458 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9459 PyUnicode_READ(kind_sub, data_sub, i))
9460 return 0;
9461 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009462 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009463 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009464 }
9465
9466 return 0;
9467}
9468
Alexander Belopolsky40018472011-02-26 01:02:56 +00009469Py_ssize_t
9470PyUnicode_Tailmatch(PyObject *str,
9471 PyObject *substr,
9472 Py_ssize_t start,
9473 Py_ssize_t end,
9474 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009475{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009476 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009477
Guido van Rossumd57fd912000-03-10 22:53:23 +00009478 str = PyUnicode_FromObject(str);
9479 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009480 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009481 substr = PyUnicode_FromObject(substr);
9482 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009483 Py_DECREF(str);
9484 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009485 }
Tim Petersced69f82003-09-16 20:30:58 +00009486
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009487 result = tailmatch(str, substr,
Benjamin Peterson29060642009-01-31 22:14:21 +00009488 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009489 Py_DECREF(str);
9490 Py_DECREF(substr);
9491 return result;
9492}
9493
Guido van Rossumd57fd912000-03-10 22:53:23 +00009494/* Apply fixfct filter to the Unicode object self and return a
9495 reference to the modified object */
9496
Alexander Belopolsky40018472011-02-26 01:02:56 +00009497static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009498fixup(PyObject *self,
9499 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009500{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009501 PyObject *u;
9502 Py_UCS4 maxchar_old, maxchar_new = 0;
Victor Stinnereaab6042011-12-11 22:22:39 +01009503 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009504
Victor Stinnerbf6e5602011-12-12 01:53:47 +01009505 u = _PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009506 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009507 return NULL;
Victor Stinner87af4f22011-11-21 23:03:47 +01009508 maxchar_old = PyUnicode_MAX_CHAR_VALUE(u);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009509
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009510 /* fix functions return the new maximum character in a string,
9511 if the kind of the resulting unicode object does not change,
9512 everything is fine. Otherwise we need to change the string kind
9513 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009514 maxchar_new = fixfct(u);
Victor Stinnereaab6042011-12-11 22:22:39 +01009515
9516 if (maxchar_new == 0) {
9517 /* no changes */;
9518 if (PyUnicode_CheckExact(self)) {
9519 Py_DECREF(u);
9520 Py_INCREF(self);
9521 return self;
9522 }
9523 else
9524 return u;
9525 }
9526
9527 if (maxchar_new <= 127)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009528 maxchar_new = 127;
9529 else if (maxchar_new <= 255)
9530 maxchar_new = 255;
9531 else if (maxchar_new <= 65535)
9532 maxchar_new = 65535;
9533 else
Victor Stinner8faf8212011-12-08 22:14:11 +01009534 maxchar_new = MAX_UNICODE;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009535
Victor Stinnereaab6042011-12-11 22:22:39 +01009536 if (maxchar_new == maxchar_old)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009537 return u;
Victor Stinnereaab6042011-12-11 22:22:39 +01009538
9539 /* In case the maximum character changed, we need to
9540 convert the string to the new category. */
9541 v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
9542 if (v == NULL) {
9543 Py_DECREF(u);
9544 return NULL;
9545 }
9546 if (maxchar_new > maxchar_old) {
9547 /* If the maxchar increased so that the kind changed, not all
9548 characters are representable anymore and we need to fix the
9549 string again. This only happens in very few cases. */
9550 copy_characters(v, 0, self, 0, PyUnicode_GET_LENGTH(self));
9551 maxchar_old = fixfct(v);
9552 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009553 }
9554 else {
Victor Stinnereaab6042011-12-11 22:22:39 +01009555 copy_characters(v, 0, u, 0, PyUnicode_GET_LENGTH(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009556 }
Victor Stinnereaab6042011-12-11 22:22:39 +01009557 Py_DECREF(u);
9558 assert(_PyUnicode_CheckConsistency(v, 1));
9559 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009560}
9561
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009562static PyObject *
9563ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009564{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009565 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9566 char *resdata, *data = PyUnicode_DATA(self);
9567 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009568
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009569 res = PyUnicode_New(len, 127);
9570 if (res == NULL)
9571 return NULL;
9572 resdata = PyUnicode_DATA(res);
9573 if (lower)
9574 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009575 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009576 _Py_bytes_upper(resdata, data, len);
9577 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009578}
9579
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009580static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009581handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009582{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009583 Py_ssize_t j;
9584 int final_sigma;
9585 Py_UCS4 c;
9586 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009587
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009588 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9589
9590 where ! is a negation and \p{xxx} is a character with property xxx.
9591 */
9592 for (j = i - 1; j >= 0; j--) {
9593 c = PyUnicode_READ(kind, data, j);
9594 if (!_PyUnicode_IsCaseIgnorable(c))
9595 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009596 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009597 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9598 if (final_sigma) {
9599 for (j = i + 1; j < length; j++) {
9600 c = PyUnicode_READ(kind, data, j);
9601 if (!_PyUnicode_IsCaseIgnorable(c))
9602 break;
9603 }
9604 final_sigma = j == length || !_PyUnicode_IsCased(c);
9605 }
9606 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009607}
9608
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009609static int
9610lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9611 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009612{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009613 /* Obscure special case. */
9614 if (c == 0x3A3) {
9615 mapped[0] = handle_capital_sigma(kind, data, length, i);
9616 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009617 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009618 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009619}
9620
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009621static Py_ssize_t
9622do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009623{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009624 Py_ssize_t i, k = 0;
9625 int n_res, j;
9626 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009627
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009628 c = PyUnicode_READ(kind, data, 0);
9629 n_res = _PyUnicode_ToUpperFull(c, mapped);
9630 for (j = 0; j < n_res; j++) {
9631 if (mapped[j] > *maxchar)
9632 *maxchar = mapped[j];
9633 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009634 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009635 for (i = 1; i < length; i++) {
9636 c = PyUnicode_READ(kind, data, i);
9637 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9638 for (j = 0; j < n_res; j++) {
9639 if (mapped[j] > *maxchar)
9640 *maxchar = mapped[j];
9641 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009642 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009643 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009644 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009645}
9646
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009647static Py_ssize_t
9648do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9649 Py_ssize_t i, k = 0;
9650
9651 for (i = 0; i < length; i++) {
9652 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9653 int n_res, j;
9654 if (Py_UNICODE_ISUPPER(c)) {
9655 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9656 }
9657 else if (Py_UNICODE_ISLOWER(c)) {
9658 n_res = _PyUnicode_ToUpperFull(c, mapped);
9659 }
9660 else {
9661 n_res = 1;
9662 mapped[0] = c;
9663 }
9664 for (j = 0; j < n_res; j++) {
9665 if (mapped[j] > *maxchar)
9666 *maxchar = mapped[j];
9667 res[k++] = mapped[j];
9668 }
9669 }
9670 return k;
9671}
9672
9673static Py_ssize_t
9674do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9675 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009676{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009677 Py_ssize_t i, k = 0;
9678
9679 for (i = 0; i < length; i++) {
9680 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9681 int n_res, j;
9682 if (lower)
9683 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9684 else
9685 n_res = _PyUnicode_ToUpperFull(c, mapped);
9686 for (j = 0; j < n_res; j++) {
9687 if (mapped[j] > *maxchar)
9688 *maxchar = mapped[j];
9689 res[k++] = mapped[j];
9690 }
9691 }
9692 return k;
9693}
9694
9695static Py_ssize_t
9696do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9697{
9698 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9699}
9700
9701static Py_ssize_t
9702do_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9703{
9704 return do_upper_or_lower(kind, data, length, res, maxchar, 1);
9705}
9706
Benjamin Petersone51757f2012-01-12 21:10:29 -05009707static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009708do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9709{
9710 Py_ssize_t i, k = 0;
9711
9712 for (i = 0; i < length; i++) {
9713 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9714 Py_UCS4 mapped[3];
9715 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9716 for (j = 0; j < n_res; j++) {
9717 if (mapped[j] > *maxchar)
9718 *maxchar = mapped[j];
9719 res[k++] = mapped[j];
9720 }
9721 }
9722 return k;
9723}
9724
9725static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009726do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9727{
9728 Py_ssize_t i, k = 0;
9729 int previous_is_cased;
9730
9731 previous_is_cased = 0;
9732 for (i = 0; i < length; i++) {
9733 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9734 Py_UCS4 mapped[3];
9735 int n_res, j;
9736
9737 if (previous_is_cased)
9738 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9739 else
9740 n_res = _PyUnicode_ToTitleFull(c, mapped);
9741
9742 for (j = 0; j < n_res; j++) {
9743 if (mapped[j] > *maxchar)
9744 *maxchar = mapped[j];
9745 res[k++] = mapped[j];
9746 }
9747
9748 previous_is_cased = _PyUnicode_IsCased(c);
9749 }
9750 return k;
9751}
9752
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009753static PyObject *
9754case_operation(PyObject *self,
9755 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9756{
9757 PyObject *res = NULL;
9758 Py_ssize_t length, newlength = 0;
9759 int kind, outkind;
9760 void *data, *outdata;
9761 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9762
Benjamin Petersoneea48462012-01-16 14:28:50 -05009763 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009764
9765 kind = PyUnicode_KIND(self);
9766 data = PyUnicode_DATA(self);
9767 length = PyUnicode_GET_LENGTH(self);
9768 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
9769 if (tmp == NULL)
9770 return PyErr_NoMemory();
9771 newlength = perform(kind, data, length, tmp, &maxchar);
9772 res = PyUnicode_New(newlength, maxchar);
9773 if (res == NULL)
9774 goto leave;
9775 tmpend = tmp + newlength;
9776 outdata = PyUnicode_DATA(res);
9777 outkind = PyUnicode_KIND(res);
9778 switch (outkind) {
9779 case PyUnicode_1BYTE_KIND:
9780 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9781 break;
9782 case PyUnicode_2BYTE_KIND:
9783 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9784 break;
9785 case PyUnicode_4BYTE_KIND:
9786 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9787 break;
9788 default:
9789 assert(0);
9790 break;
9791 }
9792 leave:
9793 PyMem_FREE(tmp);
9794 return res;
9795}
9796
Tim Peters8ce9f162004-08-27 01:49:32 +00009797PyObject *
9798PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009799{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009800 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009801 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009802 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009803 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009804 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9805 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009806 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009807 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009808 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009809 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009810 int use_memcpy;
9811 unsigned char *res_data = NULL, *sep_data = NULL;
9812 PyObject *last_obj;
9813 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009814
Tim Peters05eba1f2004-08-27 21:32:02 +00009815 fseq = PySequence_Fast(seq, "");
9816 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009817 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009818 }
9819
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009820 /* NOTE: the following code can't call back into Python code,
9821 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009822 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009823
Tim Peters05eba1f2004-08-27 21:32:02 +00009824 seqlen = PySequence_Fast_GET_SIZE(fseq);
9825 /* If empty sequence, return u"". */
9826 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009827 Py_DECREF(fseq);
9828 Py_INCREF(unicode_empty);
9829 res = unicode_empty;
9830 return res;
Tim Peters05eba1f2004-08-27 21:32:02 +00009831 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009832
Tim Peters05eba1f2004-08-27 21:32:02 +00009833 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009834 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009835 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009836 if (seqlen == 1) {
9837 if (PyUnicode_CheckExact(items[0])) {
9838 res = items[0];
9839 Py_INCREF(res);
9840 Py_DECREF(fseq);
9841 return res;
9842 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009843 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009844 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009845 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009846 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009847 /* Set up sep and seplen */
9848 if (separator == NULL) {
9849 /* fall back to a blank space separator */
9850 sep = PyUnicode_FromOrdinal(' ');
9851 if (!sep)
9852 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009853 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009854 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009855 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009856 else {
9857 if (!PyUnicode_Check(separator)) {
9858 PyErr_Format(PyExc_TypeError,
9859 "separator: expected str instance,"
9860 " %.80s found",
9861 Py_TYPE(separator)->tp_name);
9862 goto onError;
9863 }
9864 if (PyUnicode_READY(separator))
9865 goto onError;
9866 sep = separator;
9867 seplen = PyUnicode_GET_LENGTH(separator);
9868 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9869 /* inc refcount to keep this code path symmetric with the
9870 above case of a blank separator */
9871 Py_INCREF(sep);
9872 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009873 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009874 }
9875
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009876 /* There are at least two things to join, or else we have a subclass
9877 * of str in the sequence.
9878 * Do a pre-pass to figure out the total amount of space we'll
9879 * need (sz), and see whether all argument are strings.
9880 */
9881 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009882#ifdef Py_DEBUG
9883 use_memcpy = 0;
9884#else
9885 use_memcpy = 1;
9886#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009887 for (i = 0; i < seqlen; i++) {
9888 const Py_ssize_t old_sz = sz;
9889 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009890 if (!PyUnicode_Check(item)) {
9891 PyErr_Format(PyExc_TypeError,
9892 "sequence item %zd: expected str instance,"
9893 " %.80s found",
9894 i, Py_TYPE(item)->tp_name);
9895 goto onError;
9896 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009897 if (PyUnicode_READY(item) == -1)
9898 goto onError;
9899 sz += PyUnicode_GET_LENGTH(item);
9900 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009901 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009902 if (i != 0)
9903 sz += seplen;
9904 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9905 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009906 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009907 goto onError;
9908 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009909 if (use_memcpy && last_obj != NULL) {
9910 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9911 use_memcpy = 0;
9912 }
9913 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009914 }
Tim Petersced69f82003-09-16 20:30:58 +00009915
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009916 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009917 if (res == NULL)
9918 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009919
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009920 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009921#ifdef Py_DEBUG
9922 use_memcpy = 0;
9923#else
9924 if (use_memcpy) {
9925 res_data = PyUnicode_1BYTE_DATA(res);
9926 kind = PyUnicode_KIND(res);
9927 if (seplen != 0)
9928 sep_data = PyUnicode_1BYTE_DATA(sep);
9929 }
9930#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009931 for (i = 0, res_offset = 0; i < seqlen; ++i) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009932 Py_ssize_t itemlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009933 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009934 /* Copy item, and maybe the separator. */
Victor Stinner9ce5a832011-10-03 23:36:02 +02009935 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009936 if (use_memcpy) {
9937 Py_MEMCPY(res_data,
9938 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009939 kind * seplen);
9940 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009941 }
9942 else {
9943 copy_characters(res, res_offset, sep, 0, seplen);
9944 res_offset += seplen;
9945 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009946 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009947 itemlen = PyUnicode_GET_LENGTH(item);
9948 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009949 if (use_memcpy) {
9950 Py_MEMCPY(res_data,
9951 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009952 kind * itemlen);
9953 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009954 }
9955 else {
9956 copy_characters(res, res_offset, item, 0, itemlen);
9957 res_offset += itemlen;
9958 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009959 }
Tim Peters05eba1f2004-08-27 21:32:02 +00009960 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009961 if (use_memcpy)
9962 assert(res_data == PyUnicode_1BYTE_DATA(res)
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009963 + kind * PyUnicode_GET_LENGTH(res));
Victor Stinnerdd077322011-10-07 17:02:31 +02009964 else
9965 assert(res_offset == PyUnicode_GET_LENGTH(res));
Tim Peters8ce9f162004-08-27 01:49:32 +00009966
Tim Peters05eba1f2004-08-27 21:32:02 +00009967 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009968 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009969 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009970 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009971
Benjamin Peterson29060642009-01-31 22:14:21 +00009972 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00009973 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009974 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009975 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009976 return NULL;
9977}
9978
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009979#define FILL(kind, data, value, start, length) \
9980 do { \
9981 Py_ssize_t i_ = 0; \
9982 assert(kind != PyUnicode_WCHAR_KIND); \
9983 switch ((kind)) { \
9984 case PyUnicode_1BYTE_KIND: { \
9985 unsigned char * to_ = (unsigned char *)((data)) + (start); \
9986 memset(to_, (unsigned char)value, length); \
9987 break; \
9988 } \
9989 case PyUnicode_2BYTE_KIND: { \
9990 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
9991 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9992 break; \
9993 } \
Benjamin Petersone157cf12012-01-01 15:56:20 -06009994 case PyUnicode_4BYTE_KIND: { \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009995 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
9996 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9997 break; \
Benjamin Petersone157cf12012-01-01 15:56:20 -06009998 default: assert(0); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009999 } \
10000 } \
10001 } while (0)
10002
Victor Stinner3fe55312012-01-04 00:33:50 +010010003Py_ssize_t
10004PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10005 Py_UCS4 fill_char)
10006{
10007 Py_ssize_t maxlen;
10008 enum PyUnicode_Kind kind;
10009 void *data;
10010
10011 if (!PyUnicode_Check(unicode)) {
10012 PyErr_BadInternalCall();
10013 return -1;
10014 }
10015 if (PyUnicode_READY(unicode) == -1)
10016 return -1;
10017 if (unicode_check_modifiable(unicode))
10018 return -1;
10019
10020 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
10021 PyErr_SetString(PyExc_ValueError,
10022 "fill character is bigger than "
10023 "the string maximum character");
10024 return -1;
10025 }
10026
10027 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
10028 length = Py_MIN(maxlen, length);
10029 if (length <= 0)
10030 return 0;
10031
10032 kind = PyUnicode_KIND(unicode);
10033 data = PyUnicode_DATA(unicode);
10034 FILL(kind, data, fill_char, start, length);
10035 return length;
10036}
10037
Victor Stinner9310abb2011-10-05 00:59:23 +020010038static PyObject *
10039pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010040 Py_ssize_t left,
10041 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010042 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010043{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010044 PyObject *u;
10045 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010046 int kind;
10047 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010048
10049 if (left < 0)
10050 left = 0;
10051 if (right < 0)
10052 right = 0;
10053
Victor Stinnerc4b49542011-12-11 22:44:26 +010010054 if (left == 0 && right == 0)
10055 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010056
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010057 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
10058 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +000010059 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
10060 return NULL;
10061 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010062 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
10063 if (fill > maxchar)
10064 maxchar = fill;
10065 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010066 if (!u)
10067 return NULL;
10068
10069 kind = PyUnicode_KIND(u);
10070 data = PyUnicode_DATA(u);
10071 if (left)
10072 FILL(kind, data, fill, 0, left);
10073 if (right)
10074 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010075 copy_characters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010076 assert(_PyUnicode_CheckConsistency(u, 1));
10077 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010078}
10079
Alexander Belopolsky40018472011-02-26 01:02:56 +000010080PyObject *
10081PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010082{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010083 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010084
10085 string = PyUnicode_FromObject(string);
Benjamin Peterson22a29702012-01-02 09:00:30 -060010086 if (string == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010087 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060010088 if (PyUnicode_READY(string) == -1) {
10089 Py_DECREF(string);
10090 return NULL;
10091 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010092
Benjamin Petersonead6b532011-12-20 17:23:42 -060010093 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010094 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010095 if (PyUnicode_IS_ASCII(string))
10096 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010097 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010098 PyUnicode_GET_LENGTH(string), keepends);
10099 else
10100 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010101 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010102 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010103 break;
10104 case PyUnicode_2BYTE_KIND:
10105 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010106 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010107 PyUnicode_GET_LENGTH(string), keepends);
10108 break;
10109 case PyUnicode_4BYTE_KIND:
10110 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010111 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010112 PyUnicode_GET_LENGTH(string), keepends);
10113 break;
10114 default:
10115 assert(0);
10116 list = 0;
10117 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010118 Py_DECREF(string);
10119 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010120}
10121
Alexander Belopolsky40018472011-02-26 01:02:56 +000010122static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010123split(PyObject *self,
10124 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010125 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010126{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010127 int kind1, kind2, kind;
10128 void *buf1, *buf2;
10129 Py_ssize_t len1, len2;
10130 PyObject* out;
10131
Guido van Rossumd57fd912000-03-10 22:53:23 +000010132 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010133 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010134
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010135 if (PyUnicode_READY(self) == -1)
10136 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010137
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010138 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010139 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010140 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010141 if (PyUnicode_IS_ASCII(self))
10142 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010143 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010144 PyUnicode_GET_LENGTH(self), maxcount
10145 );
10146 else
10147 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010148 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010149 PyUnicode_GET_LENGTH(self), maxcount
10150 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010151 case PyUnicode_2BYTE_KIND:
10152 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010153 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010154 PyUnicode_GET_LENGTH(self), maxcount
10155 );
10156 case PyUnicode_4BYTE_KIND:
10157 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010158 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010159 PyUnicode_GET_LENGTH(self), maxcount
10160 );
10161 default:
10162 assert(0);
10163 return NULL;
10164 }
10165
10166 if (PyUnicode_READY(substring) == -1)
10167 return NULL;
10168
10169 kind1 = PyUnicode_KIND(self);
10170 kind2 = PyUnicode_KIND(substring);
10171 kind = kind1 > kind2 ? kind1 : kind2;
10172 buf1 = PyUnicode_DATA(self);
10173 buf2 = PyUnicode_DATA(substring);
10174 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010175 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010176 if (!buf1)
10177 return NULL;
10178 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010179 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010180 if (!buf2) {
10181 if (kind1 != kind) PyMem_Free(buf1);
10182 return NULL;
10183 }
10184 len1 = PyUnicode_GET_LENGTH(self);
10185 len2 = PyUnicode_GET_LENGTH(substring);
10186
Benjamin Petersonead6b532011-12-20 17:23:42 -060010187 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010188 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010189 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10190 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010191 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010192 else
10193 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010194 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010195 break;
10196 case PyUnicode_2BYTE_KIND:
10197 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010198 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010199 break;
10200 case PyUnicode_4BYTE_KIND:
10201 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010202 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010203 break;
10204 default:
10205 out = NULL;
10206 }
10207 if (kind1 != kind)
10208 PyMem_Free(buf1);
10209 if (kind2 != kind)
10210 PyMem_Free(buf2);
10211 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010212}
10213
Alexander Belopolsky40018472011-02-26 01:02:56 +000010214static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010215rsplit(PyObject *self,
10216 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010217 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010218{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010219 int kind1, kind2, kind;
10220 void *buf1, *buf2;
10221 Py_ssize_t len1, len2;
10222 PyObject* out;
10223
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010224 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010225 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010226
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010227 if (PyUnicode_READY(self) == -1)
10228 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010229
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010230 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010231 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010232 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010233 if (PyUnicode_IS_ASCII(self))
10234 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010235 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010236 PyUnicode_GET_LENGTH(self), maxcount
10237 );
10238 else
10239 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010240 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010241 PyUnicode_GET_LENGTH(self), maxcount
10242 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010243 case PyUnicode_2BYTE_KIND:
10244 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010245 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010246 PyUnicode_GET_LENGTH(self), maxcount
10247 );
10248 case PyUnicode_4BYTE_KIND:
10249 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010250 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010251 PyUnicode_GET_LENGTH(self), maxcount
10252 );
10253 default:
10254 assert(0);
10255 return NULL;
10256 }
10257
10258 if (PyUnicode_READY(substring) == -1)
10259 return NULL;
10260
10261 kind1 = PyUnicode_KIND(self);
10262 kind2 = PyUnicode_KIND(substring);
10263 kind = kind1 > kind2 ? kind1 : kind2;
10264 buf1 = PyUnicode_DATA(self);
10265 buf2 = PyUnicode_DATA(substring);
10266 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010267 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010268 if (!buf1)
10269 return NULL;
10270 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010271 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010272 if (!buf2) {
10273 if (kind1 != kind) PyMem_Free(buf1);
10274 return NULL;
10275 }
10276 len1 = PyUnicode_GET_LENGTH(self);
10277 len2 = PyUnicode_GET_LENGTH(substring);
10278
Benjamin Petersonead6b532011-12-20 17:23:42 -060010279 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010280 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010281 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10282 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010283 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010284 else
10285 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010286 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010287 break;
10288 case PyUnicode_2BYTE_KIND:
10289 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010290 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010291 break;
10292 case PyUnicode_4BYTE_KIND:
10293 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010294 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010295 break;
10296 default:
10297 out = NULL;
10298 }
10299 if (kind1 != kind)
10300 PyMem_Free(buf1);
10301 if (kind2 != kind)
10302 PyMem_Free(buf2);
10303 return out;
10304}
10305
10306static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010307anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10308 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010309{
Benjamin Petersonead6b532011-12-20 17:23:42 -060010310 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010311 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010312 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10313 return asciilib_find(buf1, len1, buf2, len2, offset);
10314 else
10315 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010316 case PyUnicode_2BYTE_KIND:
10317 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10318 case PyUnicode_4BYTE_KIND:
10319 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10320 }
10321 assert(0);
10322 return -1;
10323}
10324
10325static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010326anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10327 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010328{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -060010329 switch (kind) {
10330 case PyUnicode_1BYTE_KIND:
10331 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10332 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10333 else
10334 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10335 case PyUnicode_2BYTE_KIND:
10336 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10337 case PyUnicode_4BYTE_KIND:
10338 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10339 }
10340 assert(0);
10341 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010342}
10343
Alexander Belopolsky40018472011-02-26 01:02:56 +000010344static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010345replace(PyObject *self, PyObject *str1,
10346 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010347{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010348 PyObject *u;
10349 char *sbuf = PyUnicode_DATA(self);
10350 char *buf1 = PyUnicode_DATA(str1);
10351 char *buf2 = PyUnicode_DATA(str2);
10352 int srelease = 0, release1 = 0, release2 = 0;
10353 int skind = PyUnicode_KIND(self);
10354 int kind1 = PyUnicode_KIND(str1);
10355 int kind2 = PyUnicode_KIND(str2);
10356 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10357 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10358 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010359 int mayshrink;
10360 Py_UCS4 maxchar, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010361
10362 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010363 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010364 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010365 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010366
Victor Stinner59de0ee2011-10-07 10:01:28 +020010367 if (str1 == str2)
10368 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010369 if (skind < kind1)
10370 /* substring too wide to be present */
10371 goto nothing;
10372
Victor Stinner49a0a212011-10-12 23:46:10 +020010373 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
10374 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10375 /* Replacing str1 with str2 may cause a maxchar reduction in the
10376 result string. */
10377 mayshrink = (maxchar_str2 < maxchar);
10378 maxchar = Py_MAX(maxchar, maxchar_str2);
10379
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010380 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010381 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010382 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010383 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010384 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010385 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010386 Py_UCS4 u1, u2;
10387 int rkind;
Victor Stinnerf6441102011-12-18 02:43:08 +010010388 Py_ssize_t index, pos;
10389 char *src;
10390
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010391 u1 = PyUnicode_READ_CHAR(str1, 0);
Victor Stinnerf6441102011-12-18 02:43:08 +010010392 pos = findchar(sbuf, PyUnicode_KIND(self), slen, u1, 1);
10393 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010394 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010395 u2 = PyUnicode_READ_CHAR(str2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010396 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010397 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010398 goto error;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010399 copy_characters(u, 0, self, 0, slen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010400 rkind = PyUnicode_KIND(u);
Victor Stinnerf6441102011-12-18 02:43:08 +010010401
10402 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), pos, u2);
10403 index = 0;
10404 src = sbuf;
10405 while (--maxcount)
10406 {
10407 pos++;
10408 src += pos * PyUnicode_KIND(self);
10409 slen -= pos;
10410 index += pos;
10411 pos = findchar(src, PyUnicode_KIND(self), slen, u1, 1);
10412 if (pos < 0)
10413 break;
10414 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), index + pos, u2);
10415 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010416 }
10417 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010418 int rkind = skind;
10419 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010420 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010421
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010422 if (kind1 < rkind) {
10423 /* widen substring */
10424 buf1 = _PyUnicode_AsKind(str1, rkind);
10425 if (!buf1) goto error;
10426 release1 = 1;
10427 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010428 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010429 if (i < 0)
10430 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010431 if (rkind > kind2) {
10432 /* widen replacement */
10433 buf2 = _PyUnicode_AsKind(str2, rkind);
10434 if (!buf2) goto error;
10435 release2 = 1;
10436 }
10437 else if (rkind < kind2) {
10438 /* widen self and buf1 */
10439 rkind = kind2;
10440 if (release1) PyMem_Free(buf1);
10441 sbuf = _PyUnicode_AsKind(self, rkind);
10442 if (!sbuf) goto error;
10443 srelease = 1;
10444 buf1 = _PyUnicode_AsKind(str1, rkind);
10445 if (!buf1) goto error;
10446 release1 = 1;
10447 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010448 u = PyUnicode_New(slen, maxchar);
10449 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010450 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010451 assert(PyUnicode_KIND(u) == rkind);
10452 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010453
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010454 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010455 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010456 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010457 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010458 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010459 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010460
10461 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010462 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010463 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010464 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010465 if (i == -1)
10466 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010467 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010468 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010469 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010470 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010471 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010472 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010473 }
10474 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010475 Py_ssize_t n, i, j, ires;
10476 Py_ssize_t product, new_size;
10477 int rkind = skind;
10478 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010479
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010480 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010481 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010482 buf1 = _PyUnicode_AsKind(str1, rkind);
10483 if (!buf1) goto error;
10484 release1 = 1;
10485 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010486 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010487 if (n == 0)
10488 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010489 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010490 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010491 buf2 = _PyUnicode_AsKind(str2, rkind);
10492 if (!buf2) goto error;
10493 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010494 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010495 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010496 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010497 rkind = kind2;
10498 sbuf = _PyUnicode_AsKind(self, rkind);
10499 if (!sbuf) goto error;
10500 srelease = 1;
10501 if (release1) PyMem_Free(buf1);
10502 buf1 = _PyUnicode_AsKind(str1, rkind);
10503 if (!buf1) goto error;
10504 release1 = 1;
10505 }
10506 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10507 PyUnicode_GET_LENGTH(str1))); */
10508 product = n * (len2-len1);
10509 if ((product / (len2-len1)) != n) {
10510 PyErr_SetString(PyExc_OverflowError,
10511 "replace string is too long");
10512 goto error;
10513 }
10514 new_size = slen + product;
Victor Stinner49a0a212011-10-12 23:46:10 +020010515 if (new_size == 0) {
10516 Py_INCREF(unicode_empty);
10517 u = unicode_empty;
10518 goto done;
10519 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010520 if (new_size < 0 || new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
10521 PyErr_SetString(PyExc_OverflowError,
10522 "replace string is too long");
10523 goto error;
10524 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010525 u = PyUnicode_New(new_size, maxchar);
10526 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010527 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010528 assert(PyUnicode_KIND(u) == rkind);
10529 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010530 ires = i = 0;
10531 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010532 while (n-- > 0) {
10533 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010534 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010535 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010536 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010537 if (j == -1)
10538 break;
10539 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010540 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010541 memcpy(res + rkind * ires,
10542 sbuf + rkind * i,
10543 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010544 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010545 }
10546 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010547 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010548 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010549 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010550 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010551 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010552 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010553 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010554 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010555 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010556 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010557 memcpy(res + rkind * ires,
10558 sbuf + rkind * i,
10559 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010560 }
10561 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010562 /* interleave */
10563 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010564 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010565 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010566 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010567 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010568 if (--n <= 0)
10569 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010570 memcpy(res + rkind * ires,
10571 sbuf + rkind * i,
10572 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010573 ires++;
10574 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010575 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010576 memcpy(res + rkind * ires,
10577 sbuf + rkind * i,
10578 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010579 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010580 }
10581
10582 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010583 unicode_adjust_maxchar(&u);
10584 if (u == NULL)
10585 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010586 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010587
10588 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010589 if (srelease)
10590 PyMem_FREE(sbuf);
10591 if (release1)
10592 PyMem_FREE(buf1);
10593 if (release2)
10594 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010595 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010596 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010597
Benjamin Peterson29060642009-01-31 22:14:21 +000010598 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010599 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010600 if (srelease)
10601 PyMem_FREE(sbuf);
10602 if (release1)
10603 PyMem_FREE(buf1);
10604 if (release2)
10605 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010606 return unicode_result_unchanged(self);
10607
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010608 error:
10609 if (srelease && sbuf)
10610 PyMem_FREE(sbuf);
10611 if (release1 && buf1)
10612 PyMem_FREE(buf1);
10613 if (release2 && buf2)
10614 PyMem_FREE(buf2);
10615 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010616}
10617
10618/* --- Unicode Object Methods --------------------------------------------- */
10619
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010620PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010621 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010622\n\
10623Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010624characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010625
10626static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010627unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010628{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010629 if (PyUnicode_READY(self) == -1)
10630 return NULL;
Victor Stinnerabc649d2012-02-25 00:43:27 +010010631 if (PyUnicode_IS_ASCII(self))
10632 return ascii_case_operation(self, ascii_do_title);
10633 else
10634 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010635}
10636
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010637PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010638 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010639\n\
10640Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010641have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010642
10643static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010644unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010645{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010646 if (PyUnicode_READY(self) == -1)
10647 return NULL;
10648 if (PyUnicode_GET_LENGTH(self) == 0)
10649 return unicode_result_unchanged(self);
Victor Stinnerabc649d2012-02-25 00:43:27 +010010650 if (PyUnicode_IS_ASCII(self))
10651 return ascii_case_operation(self, ascii_do_capitalize);
10652 else
10653 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010654}
10655
Benjamin Petersond5890c82012-01-14 13:23:30 -050010656PyDoc_STRVAR(casefold__doc__,
10657 "S.casefold() -> str\n\
10658\n\
10659Return a version of S suitable for caseless comparisons.");
10660
10661static PyObject *
10662unicode_casefold(PyObject *self)
10663{
10664 if (PyUnicode_READY(self) == -1)
10665 return NULL;
10666 if (PyUnicode_IS_ASCII(self))
10667 return ascii_upper_or_lower(self, 1);
Victor Stinnerabc649d2012-02-25 00:43:27 +010010668 else
10669 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010670}
10671
10672
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010673/* Argument converter. Coerces to a single unicode character */
10674
10675static int
10676convert_uc(PyObject *obj, void *addr)
10677{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010678 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010679 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010680
Benjamin Peterson14339b62009-01-31 16:36:08 +000010681 uniobj = PyUnicode_FromObject(obj);
10682 if (uniobj == NULL) {
10683 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010684 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010685 return 0;
10686 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010687 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010688 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010689 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010690 Py_DECREF(uniobj);
10691 return 0;
10692 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010693 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010694 Py_DECREF(uniobj);
10695 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010696}
10697
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010698PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010699 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010700\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010701Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010702done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010703
10704static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010705unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010706{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010707 Py_ssize_t marg, left;
10708 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010709 Py_UCS4 fillchar = ' ';
10710
Victor Stinnere9a29352011-10-01 02:14:59 +020010711 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010712 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010713
Benjamin Petersonbac79492012-01-14 13:34:47 -050010714 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010715 return NULL;
10716
Victor Stinnerc4b49542011-12-11 22:44:26 +010010717 if (PyUnicode_GET_LENGTH(self) >= width)
10718 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010719
Victor Stinnerc4b49542011-12-11 22:44:26 +010010720 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010721 left = marg / 2 + (marg & width & 1);
10722
Victor Stinner9310abb2011-10-05 00:59:23 +020010723 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010724}
10725
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010726/* This function assumes that str1 and str2 are readied by the caller. */
10727
Marc-André Lemburge5034372000-08-08 08:04:29 +000010728static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010729unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010730{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010731 int kind1, kind2;
10732 void *data1, *data2;
10733 Py_ssize_t len1, len2, i;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010734
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010735 kind1 = PyUnicode_KIND(str1);
10736 kind2 = PyUnicode_KIND(str2);
10737 data1 = PyUnicode_DATA(str1);
10738 data2 = PyUnicode_DATA(str2);
10739 len1 = PyUnicode_GET_LENGTH(str1);
10740 len2 = PyUnicode_GET_LENGTH(str2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010741
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010742 for (i = 0; i < len1 && i < len2; ++i) {
10743 Py_UCS4 c1, c2;
10744 c1 = PyUnicode_READ(kind1, data1, i);
10745 c2 = PyUnicode_READ(kind2, data2, i);
Fredrik Lundh45714e92001-06-26 16:39:36 +000010746
10747 if (c1 != c2)
10748 return (c1 < c2) ? -1 : 1;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010749 }
10750
10751 return (len1 < len2) ? -1 : (len1 != len2);
10752}
10753
Alexander Belopolsky40018472011-02-26 01:02:56 +000010754int
10755PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010756{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010757 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10758 if (PyUnicode_READY(left) == -1 ||
10759 PyUnicode_READY(right) == -1)
10760 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010761 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010762 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010763 PyErr_Format(PyExc_TypeError,
10764 "Can't compare %.100s and %.100s",
10765 left->ob_type->tp_name,
10766 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010767 return -1;
10768}
10769
Martin v. Löwis5b222132007-06-10 09:51:05 +000010770int
10771PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10772{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010773 Py_ssize_t i;
10774 int kind;
10775 void *data;
10776 Py_UCS4 chr;
10777
Victor Stinner910337b2011-10-03 03:20:16 +020010778 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010779 if (PyUnicode_READY(uni) == -1)
10780 return -1;
10781 kind = PyUnicode_KIND(uni);
10782 data = PyUnicode_DATA(uni);
Martin v. Löwis5b222132007-06-10 09:51:05 +000010783 /* Compare Unicode string and source character set string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010784 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
10785 if (chr != str[i])
10786 return (chr < (unsigned char)(str[i])) ? -1 : 1;
Benjamin Peterson8667a9b2010-01-09 21:45:28 +000010787 /* This check keeps Python strings that end in '\0' from comparing equal
10788 to C strings identical up to that point. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010789 if (PyUnicode_GET_LENGTH(uni) != i || chr)
Benjamin Peterson29060642009-01-31 22:14:21 +000010790 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010791 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +000010792 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010793 return 0;
10794}
10795
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010796
Benjamin Peterson29060642009-01-31 22:14:21 +000010797#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010798 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010799
Alexander Belopolsky40018472011-02-26 01:02:56 +000010800PyObject *
10801PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010802{
10803 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010804
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010805 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10806 PyObject *v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010807 if (PyUnicode_READY(left) == -1 ||
10808 PyUnicode_READY(right) == -1)
10809 return NULL;
10810 if (PyUnicode_GET_LENGTH(left) != PyUnicode_GET_LENGTH(right) ||
10811 PyUnicode_KIND(left) != PyUnicode_KIND(right)) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010812 if (op == Py_EQ) {
10813 Py_INCREF(Py_False);
10814 return Py_False;
10815 }
10816 if (op == Py_NE) {
10817 Py_INCREF(Py_True);
10818 return Py_True;
10819 }
10820 }
10821 if (left == right)
10822 result = 0;
10823 else
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010824 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010825
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010826 /* Convert the return value to a Boolean */
10827 switch (op) {
10828 case Py_EQ:
10829 v = TEST_COND(result == 0);
10830 break;
10831 case Py_NE:
10832 v = TEST_COND(result != 0);
10833 break;
10834 case Py_LE:
10835 v = TEST_COND(result <= 0);
10836 break;
10837 case Py_GE:
10838 v = TEST_COND(result >= 0);
10839 break;
10840 case Py_LT:
10841 v = TEST_COND(result == -1);
10842 break;
10843 case Py_GT:
10844 v = TEST_COND(result == 1);
10845 break;
10846 default:
10847 PyErr_BadArgument();
10848 return NULL;
10849 }
10850 Py_INCREF(v);
10851 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010852 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010853
Brian Curtindfc80e32011-08-10 20:28:54 -050010854 Py_RETURN_NOTIMPLEMENTED;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010855}
10856
Alexander Belopolsky40018472011-02-26 01:02:56 +000010857int
10858PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010859{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010860 PyObject *str, *sub;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010861 int kind1, kind2, kind;
10862 void *buf1, *buf2;
10863 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010864 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010865
10866 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010867 sub = PyUnicode_FromObject(element);
10868 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010869 PyErr_Format(PyExc_TypeError,
10870 "'in <string>' requires string as left operand, not %s",
10871 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010872 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010873 }
10874
Thomas Wouters477c8d52006-05-27 19:21:47 +000010875 str = PyUnicode_FromObject(container);
Benjamin Peterson22a29702012-01-02 09:00:30 -060010876 if (!str) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010877 Py_DECREF(sub);
10878 return -1;
10879 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060010880 if (PyUnicode_READY(sub) == -1 || PyUnicode_READY(str) == -1) {
10881 Py_DECREF(sub);
10882 Py_DECREF(str);
10883 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010884
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010885 kind1 = PyUnicode_KIND(str);
10886 kind2 = PyUnicode_KIND(sub);
10887 kind = kind1 > kind2 ? kind1 : kind2;
10888 buf1 = PyUnicode_DATA(str);
10889 buf2 = PyUnicode_DATA(sub);
10890 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010891 buf1 = _PyUnicode_AsKind(str, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010892 if (!buf1) {
10893 Py_DECREF(sub);
10894 return -1;
10895 }
10896 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010897 buf2 = _PyUnicode_AsKind(sub, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010898 if (!buf2) {
10899 Py_DECREF(sub);
10900 if (kind1 != kind) PyMem_Free(buf1);
10901 return -1;
10902 }
10903 len1 = PyUnicode_GET_LENGTH(str);
10904 len2 = PyUnicode_GET_LENGTH(sub);
10905
Benjamin Petersonead6b532011-12-20 17:23:42 -060010906 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010907 case PyUnicode_1BYTE_KIND:
10908 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10909 break;
10910 case PyUnicode_2BYTE_KIND:
10911 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
10912 break;
10913 case PyUnicode_4BYTE_KIND:
10914 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
10915 break;
10916 default:
10917 result = -1;
10918 assert(0);
10919 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010920
10921 Py_DECREF(str);
10922 Py_DECREF(sub);
10923
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010924 if (kind1 != kind)
10925 PyMem_Free(buf1);
10926 if (kind2 != kind)
10927 PyMem_Free(buf2);
10928
Guido van Rossum403d68b2000-03-13 15:55:09 +000010929 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010930}
10931
Guido van Rossumd57fd912000-03-10 22:53:23 +000010932/* Concat to string or Unicode object giving a new Unicode object. */
10933
Alexander Belopolsky40018472011-02-26 01:02:56 +000010934PyObject *
10935PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010936{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010937 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020010938 Py_UCS4 maxchar, maxchar2;
Victor Stinner488fa492011-12-12 00:01:39 +010010939 Py_ssize_t u_len, v_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010940
10941 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010942 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010943 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010944 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010945 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010946 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010947 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010948
10949 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020010950 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010951 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010952 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010953 }
Victor Stinnera464fc12011-10-02 20:39:30 +020010954 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010955 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010956 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010957 }
10958
Victor Stinner488fa492011-12-12 00:01:39 +010010959 u_len = PyUnicode_GET_LENGTH(u);
10960 v_len = PyUnicode_GET_LENGTH(v);
10961 if (u_len > PY_SSIZE_T_MAX - v_len) {
10962 PyErr_SetString(PyExc_OverflowError,
10963 "strings are too large to concat");
10964 goto onError;
10965 }
10966 new_len = u_len + v_len;
10967
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010968 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020010969 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
10970 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010971
Guido van Rossumd57fd912000-03-10 22:53:23 +000010972 /* Concat the two Unicode strings */
Victor Stinner488fa492011-12-12 00:01:39 +010010973 w = PyUnicode_New(new_len, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010974 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010975 goto onError;
Victor Stinner488fa492011-12-12 00:01:39 +010010976 copy_characters(w, 0, u, 0, u_len);
10977 copy_characters(w, u_len, v, 0, v_len);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010978 Py_DECREF(u);
10979 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010980 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010981 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010982
Benjamin Peterson29060642009-01-31 22:14:21 +000010983 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010984 Py_XDECREF(u);
10985 Py_XDECREF(v);
10986 return NULL;
10987}
10988
Walter Dörwald1ab83302007-05-18 17:15:44 +000010989void
Victor Stinner23e56682011-10-03 03:54:37 +020010990PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000010991{
Victor Stinner23e56682011-10-03 03:54:37 +020010992 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010010993 Py_UCS4 maxchar, maxchar2;
10994 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020010995
10996 if (p_left == NULL) {
10997 if (!PyErr_Occurred())
10998 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000010999 return;
11000 }
Victor Stinner23e56682011-10-03 03:54:37 +020011001 left = *p_left;
11002 if (right == NULL || !PyUnicode_Check(left)) {
11003 if (!PyErr_Occurred())
11004 PyErr_BadInternalCall();
11005 goto error;
11006 }
11007
Benjamin Petersonbac79492012-01-14 13:34:47 -050011008 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011009 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050011010 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011011 goto error;
11012
Victor Stinner488fa492011-12-12 00:01:39 +010011013 /* Shortcuts */
11014 if (left == unicode_empty) {
11015 Py_DECREF(left);
11016 Py_INCREF(right);
11017 *p_left = right;
11018 return;
11019 }
11020 if (right == unicode_empty)
11021 return;
11022
11023 left_len = PyUnicode_GET_LENGTH(left);
11024 right_len = PyUnicode_GET_LENGTH(right);
11025 if (left_len > PY_SSIZE_T_MAX - right_len) {
11026 PyErr_SetString(PyExc_OverflowError,
11027 "strings are too large to concat");
11028 goto error;
11029 }
11030 new_len = left_len + right_len;
11031
11032 if (unicode_modifiable(left)
11033 && PyUnicode_CheckExact(right)
11034 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020011035 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
11036 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020011037 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020011038 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010011039 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
11040 {
11041 /* append inplace */
11042 if (unicode_resize(p_left, new_len) != 0) {
11043 /* XXX if _PyUnicode_Resize() fails, 'left' has been
11044 * deallocated so it cannot be put back into
11045 * 'variable'. The MemoryError is raised when there
11046 * is no value in 'variable', which might (very
11047 * remotely) be a cause of incompatibilities.
11048 */
11049 goto error;
Victor Stinner23e56682011-10-03 03:54:37 +020011050 }
Victor Stinner488fa492011-12-12 00:01:39 +010011051 /* copy 'right' into the newly allocated area of 'left' */
11052 copy_characters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020011053 }
Victor Stinner488fa492011-12-12 00:01:39 +010011054 else {
11055 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11056 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
11057 maxchar = Py_MAX(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020011058
Victor Stinner488fa492011-12-12 00:01:39 +010011059 /* Concat the two Unicode strings */
11060 res = PyUnicode_New(new_len, maxchar);
11061 if (res == NULL)
11062 goto error;
11063 copy_characters(res, 0, left, 0, left_len);
11064 copy_characters(res, left_len, right, 0, right_len);
11065 Py_DECREF(left);
11066 *p_left = res;
11067 }
11068 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020011069 return;
11070
11071error:
Victor Stinner488fa492011-12-12 00:01:39 +010011072 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011073}
11074
11075void
11076PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
11077{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011078 PyUnicode_Append(pleft, right);
11079 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011080}
11081
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011082PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011083 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011084\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011085Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011086string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011087interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011088
11089static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011090unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011091{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011092 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011093 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011094 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011095 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011096 int kind1, kind2, kind;
11097 void *buf1, *buf2;
11098 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011099
Jesus Ceaac451502011-04-20 17:09:23 +020011100 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
11101 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000011102 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000011103
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011104 kind1 = PyUnicode_KIND(self);
11105 kind2 = PyUnicode_KIND(substring);
11106 kind = kind1 > kind2 ? kind1 : kind2;
11107 buf1 = PyUnicode_DATA(self);
11108 buf2 = PyUnicode_DATA(substring);
11109 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010011110 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011111 if (!buf1) {
11112 Py_DECREF(substring);
11113 return NULL;
11114 }
11115 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010011116 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011117 if (!buf2) {
11118 Py_DECREF(substring);
11119 if (kind1 != kind) PyMem_Free(buf1);
11120 return NULL;
11121 }
11122 len1 = PyUnicode_GET_LENGTH(self);
11123 len2 = PyUnicode_GET_LENGTH(substring);
11124
11125 ADJUST_INDICES(start, end, len1);
Benjamin Petersonead6b532011-12-20 17:23:42 -060011126 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011127 case PyUnicode_1BYTE_KIND:
11128 iresult = ucs1lib_count(
11129 ((Py_UCS1*)buf1) + start, end - start,
11130 buf2, len2, PY_SSIZE_T_MAX
11131 );
11132 break;
11133 case PyUnicode_2BYTE_KIND:
11134 iresult = ucs2lib_count(
11135 ((Py_UCS2*)buf1) + start, end - start,
11136 buf2, len2, PY_SSIZE_T_MAX
11137 );
11138 break;
11139 case PyUnicode_4BYTE_KIND:
11140 iresult = ucs4lib_count(
11141 ((Py_UCS4*)buf1) + start, end - start,
11142 buf2, len2, PY_SSIZE_T_MAX
11143 );
11144 break;
11145 default:
11146 assert(0); iresult = 0;
11147 }
11148
11149 result = PyLong_FromSsize_t(iresult);
11150
11151 if (kind1 != kind)
11152 PyMem_Free(buf1);
11153 if (kind2 != kind)
11154 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011155
11156 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011157
Guido van Rossumd57fd912000-03-10 22:53:23 +000011158 return result;
11159}
11160
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011161PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000011162 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011163\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000011164Encode S using the codec registered for encoding. Default encoding\n\
11165is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000011166handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000011167a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
11168'xmlcharrefreplace' as well as any other name registered with\n\
11169codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011170
11171static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011172unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011173{
Benjamin Peterson308d6372009-09-18 21:42:35 +000011174 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011175 char *encoding = NULL;
11176 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000011177
Benjamin Peterson308d6372009-09-18 21:42:35 +000011178 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
11179 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011180 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011181 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000011182}
11183
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011184PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011185 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011186\n\
11187Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011188If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011189
11190static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011191unicode_expandtabs(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011192{
Antoine Pitroue71d5742011-10-04 15:55:09 +020011193 Py_ssize_t i, j, line_pos, src_len, incr;
11194 Py_UCS4 ch;
11195 PyObject *u;
11196 void *src_data, *dest_data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011197 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011198 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011199 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011200
11201 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000011202 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011203
Antoine Pitrou22425222011-10-04 19:10:51 +020011204 if (PyUnicode_READY(self) == -1)
11205 return NULL;
11206
Thomas Wouters7e474022000-07-16 12:04:32 +000011207 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011208 src_len = PyUnicode_GET_LENGTH(self);
11209 i = j = line_pos = 0;
11210 kind = PyUnicode_KIND(self);
11211 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020011212 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011213 for (; i < src_len; i++) {
11214 ch = PyUnicode_READ(kind, src_data, i);
11215 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020011216 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000011217 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011218 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000011219 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011220 goto overflow;
11221 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011222 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011223 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011224 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011225 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011226 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011227 goto overflow;
11228 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011229 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011230 if (ch == '\n' || ch == '\r')
11231 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011232 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011233 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010011234 if (!found)
11235 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011236
Guido van Rossumd57fd912000-03-10 22:53:23 +000011237 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011238 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011239 if (!u)
11240 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011241 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011242
Antoine Pitroue71d5742011-10-04 15:55:09 +020011243 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011244
Antoine Pitroue71d5742011-10-04 15:55:09 +020011245 for (; i < src_len; i++) {
11246 ch = PyUnicode_READ(kind, src_data, i);
11247 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011248 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011249 incr = tabsize - (line_pos % tabsize);
11250 line_pos += incr;
Victor Stinnerda79e632012-02-22 13:37:04 +010011251 FILL(kind, dest_data, ' ', j, incr);
11252 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011253 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011254 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011255 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011256 line_pos++;
11257 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011258 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011259 if (ch == '\n' || ch == '\r')
11260 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011261 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011262 }
11263 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010011264 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011265
Antoine Pitroue71d5742011-10-04 15:55:09 +020011266 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011267 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11268 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011269}
11270
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011271PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011272 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011273\n\
11274Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011275such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011276arguments start and end are interpreted as in slice notation.\n\
11277\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011278Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011279
11280static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011281unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011282{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011283 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011284 Py_ssize_t start;
11285 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011286 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011287
Jesus Ceaac451502011-04-20 17:09:23 +020011288 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
11289 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011290 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011291
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011292 if (PyUnicode_READY(self) == -1)
11293 return NULL;
11294 if (PyUnicode_READY(substring) == -1)
11295 return NULL;
11296
Victor Stinner7931d9a2011-11-04 00:22:48 +010011297 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011298
11299 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011300
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011301 if (result == -2)
11302 return NULL;
11303
Christian Heimes217cfd12007-12-02 14:31:20 +000011304 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011305}
11306
11307static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011308unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011309{
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011310 Py_UCS4 ch = PyUnicode_ReadChar(self, index);
11311 if (ch == (Py_UCS4)-1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011312 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011313 return PyUnicode_FromOrdinal(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011314}
11315
Guido van Rossumc2504932007-09-18 19:42:40 +000011316/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011317 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011318static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011319unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011320{
Guido van Rossumc2504932007-09-18 19:42:40 +000011321 Py_ssize_t len;
Mark Dickinson57e683e2011-09-24 18:18:40 +010011322 Py_uhash_t x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011323
Benjamin Peterson69e97272012-02-21 11:08:50 -050011324 assert(_Py_HashSecret_Initialized);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011325 if (_PyUnicode_HASH(self) != -1)
11326 return _PyUnicode_HASH(self);
11327 if (PyUnicode_READY(self) == -1)
11328 return -1;
11329 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010011330 /*
11331 We make the hash of the empty string be 0, rather than using
11332 (prefix ^ suffix), since this slightly obfuscates the hash secret
11333 */
11334 if (len == 0) {
11335 _PyUnicode_HASH(self) = 0;
11336 return 0;
11337 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011338
11339 /* The hash function as a macro, gets expanded three times below. */
Georg Brandl2fb477c2012-02-21 00:33:36 +010011340#define HASH(P) \
11341 x ^= (Py_uhash_t) *P << 7; \
11342 while (--len >= 0) \
11343 x = (_PyHASH_MULTIPLIER * x) ^ (Py_uhash_t) *P++; \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011344
Georg Brandl2fb477c2012-02-21 00:33:36 +010011345 x = (Py_uhash_t) _Py_HashSecret.prefix;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011346 switch (PyUnicode_KIND(self)) {
11347 case PyUnicode_1BYTE_KIND: {
11348 const unsigned char *c = PyUnicode_1BYTE_DATA(self);
11349 HASH(c);
11350 break;
11351 }
11352 case PyUnicode_2BYTE_KIND: {
11353 const Py_UCS2 *s = PyUnicode_2BYTE_DATA(self);
11354 HASH(s);
11355 break;
11356 }
11357 default: {
11358 Py_UCS4 *l;
11359 assert(PyUnicode_KIND(self) == PyUnicode_4BYTE_KIND &&
11360 "Impossible switch case in unicode_hash");
11361 l = PyUnicode_4BYTE_DATA(self);
11362 HASH(l);
11363 break;
11364 }
11365 }
Georg Brandl2fb477c2012-02-21 00:33:36 +010011366 x ^= (Py_uhash_t) PyUnicode_GET_LENGTH(self);
11367 x ^= (Py_uhash_t) _Py_HashSecret.suffix;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011368
Guido van Rossumc2504932007-09-18 19:42:40 +000011369 if (x == -1)
11370 x = -2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011371 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011372 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011373}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011374#undef HASH
Guido van Rossumd57fd912000-03-10 22:53:23 +000011375
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011376PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011377 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011378\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011379Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011380
11381static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011382unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011383{
Martin v. Löwis18e16552006-02-15 17:27:45 +000011384 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011385 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011386 Py_ssize_t start;
11387 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011388
Jesus Ceaac451502011-04-20 17:09:23 +020011389 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
11390 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011391 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011392
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011393 if (PyUnicode_READY(self) == -1)
11394 return NULL;
11395 if (PyUnicode_READY(substring) == -1)
11396 return NULL;
11397
Victor Stinner7931d9a2011-11-04 00:22:48 +010011398 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011399
11400 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011401
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011402 if (result == -2)
11403 return NULL;
11404
Guido van Rossumd57fd912000-03-10 22:53:23 +000011405 if (result < 0) {
11406 PyErr_SetString(PyExc_ValueError, "substring not found");
11407 return NULL;
11408 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011409
Christian Heimes217cfd12007-12-02 14:31:20 +000011410 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011411}
11412
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011413PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011414 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011415\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011416Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011417at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011418
11419static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011420unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011421{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011422 Py_ssize_t i, length;
11423 int kind;
11424 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011425 int cased;
11426
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011427 if (PyUnicode_READY(self) == -1)
11428 return NULL;
11429 length = PyUnicode_GET_LENGTH(self);
11430 kind = PyUnicode_KIND(self);
11431 data = PyUnicode_DATA(self);
11432
Guido van Rossumd57fd912000-03-10 22:53:23 +000011433 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011434 if (length == 1)
11435 return PyBool_FromLong(
11436 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011437
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011438 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011439 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011440 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011441
Guido van Rossumd57fd912000-03-10 22:53:23 +000011442 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011443 for (i = 0; i < length; i++) {
11444 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011445
Benjamin Peterson29060642009-01-31 22:14:21 +000011446 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11447 return PyBool_FromLong(0);
11448 else if (!cased && Py_UNICODE_ISLOWER(ch))
11449 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011450 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011451 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011452}
11453
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011454PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011455 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011456\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011457Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011458at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011459
11460static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011461unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011462{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011463 Py_ssize_t i, length;
11464 int kind;
11465 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011466 int cased;
11467
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011468 if (PyUnicode_READY(self) == -1)
11469 return NULL;
11470 length = PyUnicode_GET_LENGTH(self);
11471 kind = PyUnicode_KIND(self);
11472 data = PyUnicode_DATA(self);
11473
Guido van Rossumd57fd912000-03-10 22:53:23 +000011474 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011475 if (length == 1)
11476 return PyBool_FromLong(
11477 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011478
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011479 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011480 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011481 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011482
Guido van Rossumd57fd912000-03-10 22:53:23 +000011483 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011484 for (i = 0; i < length; i++) {
11485 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011486
Benjamin Peterson29060642009-01-31 22:14:21 +000011487 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11488 return PyBool_FromLong(0);
11489 else if (!cased && Py_UNICODE_ISUPPER(ch))
11490 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011491 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011492 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011493}
11494
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011495PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011496 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011497\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011498Return True if S is a titlecased string and there is at least one\n\
11499character in S, i.e. upper- and titlecase characters may only\n\
11500follow uncased characters and lowercase characters only cased ones.\n\
11501Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011502
11503static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011504unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011505{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011506 Py_ssize_t i, length;
11507 int kind;
11508 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011509 int cased, previous_is_cased;
11510
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011511 if (PyUnicode_READY(self) == -1)
11512 return NULL;
11513 length = PyUnicode_GET_LENGTH(self);
11514 kind = PyUnicode_KIND(self);
11515 data = PyUnicode_DATA(self);
11516
Guido van Rossumd57fd912000-03-10 22:53:23 +000011517 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011518 if (length == 1) {
11519 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11520 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11521 (Py_UNICODE_ISUPPER(ch) != 0));
11522 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011523
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011524 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011525 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011526 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011527
Guido van Rossumd57fd912000-03-10 22:53:23 +000011528 cased = 0;
11529 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011530 for (i = 0; i < length; i++) {
11531 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011532
Benjamin Peterson29060642009-01-31 22:14:21 +000011533 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11534 if (previous_is_cased)
11535 return PyBool_FromLong(0);
11536 previous_is_cased = 1;
11537 cased = 1;
11538 }
11539 else if (Py_UNICODE_ISLOWER(ch)) {
11540 if (!previous_is_cased)
11541 return PyBool_FromLong(0);
11542 previous_is_cased = 1;
11543 cased = 1;
11544 }
11545 else
11546 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011547 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011548 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011549}
11550
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011551PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011552 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011553\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011554Return True if all characters in S are whitespace\n\
11555and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011556
11557static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011558unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011559{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011560 Py_ssize_t i, length;
11561 int kind;
11562 void *data;
11563
11564 if (PyUnicode_READY(self) == -1)
11565 return NULL;
11566 length = PyUnicode_GET_LENGTH(self);
11567 kind = PyUnicode_KIND(self);
11568 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011569
Guido van Rossumd57fd912000-03-10 22:53:23 +000011570 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011571 if (length == 1)
11572 return PyBool_FromLong(
11573 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011574
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011575 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011576 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011577 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011578
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011579 for (i = 0; i < length; i++) {
11580 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011581 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011582 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011583 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011584 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011585}
11586
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011587PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011588 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011589\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011590Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011591and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011592
11593static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011594unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011595{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011596 Py_ssize_t i, length;
11597 int kind;
11598 void *data;
11599
11600 if (PyUnicode_READY(self) == -1)
11601 return NULL;
11602 length = PyUnicode_GET_LENGTH(self);
11603 kind = PyUnicode_KIND(self);
11604 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011605
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011606 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011607 if (length == 1)
11608 return PyBool_FromLong(
11609 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011610
11611 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011612 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011613 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011614
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011615 for (i = 0; i < length; i++) {
11616 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011617 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011618 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011619 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011620}
11621
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011622PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011623 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011624\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011625Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011626and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011627
11628static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011629unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011630{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011631 int kind;
11632 void *data;
11633 Py_ssize_t len, i;
11634
11635 if (PyUnicode_READY(self) == -1)
11636 return NULL;
11637
11638 kind = PyUnicode_KIND(self);
11639 data = PyUnicode_DATA(self);
11640 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011641
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011642 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011643 if (len == 1) {
11644 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11645 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11646 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011647
11648 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011649 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011650 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011651
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011652 for (i = 0; i < len; i++) {
11653 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011654 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011655 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011656 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011657 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011658}
11659
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011660PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011661 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011662\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011663Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011664False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011665
11666static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011667unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011668{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011669 Py_ssize_t i, length;
11670 int kind;
11671 void *data;
11672
11673 if (PyUnicode_READY(self) == -1)
11674 return NULL;
11675 length = PyUnicode_GET_LENGTH(self);
11676 kind = PyUnicode_KIND(self);
11677 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011678
Guido van Rossumd57fd912000-03-10 22:53:23 +000011679 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011680 if (length == 1)
11681 return PyBool_FromLong(
11682 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011683
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011684 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011685 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011686 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011687
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011688 for (i = 0; i < length; i++) {
11689 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011690 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011691 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011692 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011693}
11694
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011695PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011696 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011697\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011698Return True if all characters in S are digits\n\
11699and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011700
11701static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011702unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011703{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011704 Py_ssize_t i, length;
11705 int kind;
11706 void *data;
11707
11708 if (PyUnicode_READY(self) == -1)
11709 return NULL;
11710 length = PyUnicode_GET_LENGTH(self);
11711 kind = PyUnicode_KIND(self);
11712 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011713
Guido van Rossumd57fd912000-03-10 22:53:23 +000011714 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011715 if (length == 1) {
11716 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11717 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11718 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011719
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011720 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011721 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011722 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011723
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011724 for (i = 0; i < length; i++) {
11725 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011726 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011727 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011728 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011729}
11730
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011731PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011732 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011733\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011734Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011735False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011736
11737static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011738unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011739{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011740 Py_ssize_t i, length;
11741 int kind;
11742 void *data;
11743
11744 if (PyUnicode_READY(self) == -1)
11745 return NULL;
11746 length = PyUnicode_GET_LENGTH(self);
11747 kind = PyUnicode_KIND(self);
11748 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011749
Guido van Rossumd57fd912000-03-10 22:53:23 +000011750 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011751 if (length == 1)
11752 return PyBool_FromLong(
11753 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011754
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011755 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011756 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011757 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011758
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011759 for (i = 0; i < length; i++) {
11760 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011761 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011762 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011763 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011764}
11765
Martin v. Löwis47383402007-08-15 07:32:56 +000011766int
11767PyUnicode_IsIdentifier(PyObject *self)
11768{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011769 int kind;
11770 void *data;
11771 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011772 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011773
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011774 if (PyUnicode_READY(self) == -1) {
11775 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011776 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011777 }
11778
11779 /* Special case for empty strings */
11780 if (PyUnicode_GET_LENGTH(self) == 0)
11781 return 0;
11782 kind = PyUnicode_KIND(self);
11783 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011784
11785 /* PEP 3131 says that the first character must be in
11786 XID_Start and subsequent characters in XID_Continue,
11787 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011788 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011789 letters, digits, underscore). However, given the current
11790 definition of XID_Start and XID_Continue, it is sufficient
11791 to check just for these, except that _ must be allowed
11792 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011793 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011794 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011795 return 0;
11796
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011797 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011798 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011799 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011800 return 1;
11801}
11802
11803PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011804 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011805\n\
11806Return True if S is a valid identifier according\n\
11807to the language definition.");
11808
11809static PyObject*
11810unicode_isidentifier(PyObject *self)
11811{
11812 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11813}
11814
Georg Brandl559e5d72008-06-11 18:37:52 +000011815PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011816 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011817\n\
11818Return True if all characters in S are considered\n\
11819printable in repr() or S is empty, False otherwise.");
11820
11821static PyObject*
11822unicode_isprintable(PyObject *self)
11823{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011824 Py_ssize_t i, length;
11825 int kind;
11826 void *data;
11827
11828 if (PyUnicode_READY(self) == -1)
11829 return NULL;
11830 length = PyUnicode_GET_LENGTH(self);
11831 kind = PyUnicode_KIND(self);
11832 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011833
11834 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011835 if (length == 1)
11836 return PyBool_FromLong(
11837 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011838
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011839 for (i = 0; i < length; i++) {
11840 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011841 Py_RETURN_FALSE;
11842 }
11843 }
11844 Py_RETURN_TRUE;
11845}
11846
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011847PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011848 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011849\n\
11850Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011851iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011852
11853static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011854unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011855{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011856 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011857}
11858
Martin v. Löwis18e16552006-02-15 17:27:45 +000011859static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011860unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011861{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011862 if (PyUnicode_READY(self) == -1)
11863 return -1;
11864 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011865}
11866
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011867PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011868 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011869\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011870Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011871done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011872
11873static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011874unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011875{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011876 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011877 Py_UCS4 fillchar = ' ';
11878
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011879 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011880 return NULL;
11881
Benjamin Petersonbac79492012-01-14 13:34:47 -050011882 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010011883 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011884
Victor Stinnerc4b49542011-12-11 22:44:26 +010011885 if (PyUnicode_GET_LENGTH(self) >= width)
11886 return unicode_result_unchanged(self);
11887
11888 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011889}
11890
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011891PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011892 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011893\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011894Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011895
11896static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011897unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011898{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050011899 if (PyUnicode_READY(self) == -1)
11900 return NULL;
11901 if (PyUnicode_IS_ASCII(self))
11902 return ascii_upper_or_lower(self, 1);
Victor Stinnerabc649d2012-02-25 00:43:27 +010011903 else
11904 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011905}
11906
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011907#define LEFTSTRIP 0
11908#define RIGHTSTRIP 1
11909#define BOTHSTRIP 2
11910
11911/* Arrays indexed by above */
11912static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11913
11914#define STRIPNAME(i) (stripformat[i]+3)
11915
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011916/* externally visible for str.strip(unicode) */
11917PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011918_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011919{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011920 void *data;
11921 int kind;
11922 Py_ssize_t i, j, len;
11923 BLOOM_MASK sepmask;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011924
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011925 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
11926 return NULL;
11927
11928 kind = PyUnicode_KIND(self);
11929 data = PyUnicode_DATA(self);
11930 len = PyUnicode_GET_LENGTH(self);
11931 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
11932 PyUnicode_DATA(sepobj),
11933 PyUnicode_GET_LENGTH(sepobj));
Thomas Wouters477c8d52006-05-27 19:21:47 +000011934
Benjamin Peterson14339b62009-01-31 16:36:08 +000011935 i = 0;
11936 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011937 while (i < len &&
11938 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, i), sepobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011939 i++;
11940 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011941 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011942
Benjamin Peterson14339b62009-01-31 16:36:08 +000011943 j = len;
11944 if (striptype != LEFTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011945 do {
11946 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011947 } while (j >= i &&
11948 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, j), sepobj));
Benjamin Peterson29060642009-01-31 22:14:21 +000011949 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011950 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011951
Victor Stinner7931d9a2011-11-04 00:22:48 +010011952 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011953}
11954
11955PyObject*
11956PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
11957{
11958 unsigned char *data;
11959 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020011960 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011961
Victor Stinnerde636f32011-10-01 03:55:54 +020011962 if (PyUnicode_READY(self) == -1)
11963 return NULL;
11964
11965 end = Py_MIN(end, PyUnicode_GET_LENGTH(self));
11966
Victor Stinner12bab6d2011-10-01 01:53:49 +020011967 if (start == 0 && end == PyUnicode_GET_LENGTH(self))
Victor Stinnerc4b49542011-12-11 22:44:26 +010011968 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011969
Victor Stinner12bab6d2011-10-01 01:53:49 +020011970 length = end - start;
11971 if (length == 1)
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011972 return unicode_getitem(self, start);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011973
Victor Stinnerde636f32011-10-01 03:55:54 +020011974 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011975 PyErr_SetString(PyExc_IndexError, "string index out of range");
11976 return NULL;
11977 }
11978
Victor Stinnerb9275c12011-10-05 14:01:42 +020011979 if (PyUnicode_IS_ASCII(self)) {
11980 kind = PyUnicode_KIND(self);
11981 data = PyUnicode_1BYTE_DATA(self);
11982 return unicode_fromascii(data + start, length);
11983 }
11984 else {
11985 kind = PyUnicode_KIND(self);
11986 data = PyUnicode_1BYTE_DATA(self);
11987 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011988 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020011989 length);
11990 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011991}
Guido van Rossumd57fd912000-03-10 22:53:23 +000011992
11993static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011994do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011995{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011996 int kind;
11997 void *data;
11998 Py_ssize_t len, i, j;
11999
12000 if (PyUnicode_READY(self) == -1)
12001 return NULL;
12002
12003 kind = PyUnicode_KIND(self);
12004 data = PyUnicode_DATA(self);
12005 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012006
Benjamin Peterson14339b62009-01-31 16:36:08 +000012007 i = 0;
12008 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012009 while (i < len && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, i))) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012010 i++;
12011 }
12012 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012013
Benjamin Peterson14339b62009-01-31 16:36:08 +000012014 j = len;
12015 if (striptype != LEFTSTRIP) {
12016 do {
12017 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012018 } while (j >= i && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, j)));
Benjamin Peterson14339b62009-01-31 16:36:08 +000012019 j++;
12020 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012021
Victor Stinner7931d9a2011-11-04 00:22:48 +010012022 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012023}
12024
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012025
12026static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012027do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012028{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012029 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012030
Benjamin Peterson14339b62009-01-31 16:36:08 +000012031 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
12032 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012033
Benjamin Peterson14339b62009-01-31 16:36:08 +000012034 if (sep != NULL && sep != Py_None) {
12035 if (PyUnicode_Check(sep))
12036 return _PyUnicode_XStrip(self, striptype, sep);
12037 else {
12038 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012039 "%s arg must be None or str",
12040 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000012041 return NULL;
12042 }
12043 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012044
Benjamin Peterson14339b62009-01-31 16:36:08 +000012045 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012046}
12047
12048
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012049PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012050 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012051\n\
12052Return a copy of the string S with leading and trailing\n\
12053whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012054If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012055
12056static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012057unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012058{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012059 if (PyTuple_GET_SIZE(args) == 0)
12060 return do_strip(self, BOTHSTRIP); /* Common case */
12061 else
12062 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012063}
12064
12065
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012066PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012067 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012068\n\
12069Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012070If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012071
12072static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012073unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012074{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012075 if (PyTuple_GET_SIZE(args) == 0)
12076 return do_strip(self, LEFTSTRIP); /* Common case */
12077 else
12078 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012079}
12080
12081
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012082PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012083 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012084\n\
12085Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012086If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012087
12088static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012089unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012090{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012091 if (PyTuple_GET_SIZE(args) == 0)
12092 return do_strip(self, RIGHTSTRIP); /* Common case */
12093 else
12094 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012095}
12096
12097
Guido van Rossumd57fd912000-03-10 22:53:23 +000012098static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012099unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012100{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012101 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012102 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012103
Georg Brandl222de0f2009-04-12 12:01:50 +000012104 if (len < 1) {
12105 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +020012106 return unicode_empty;
Georg Brandl222de0f2009-04-12 12:01:50 +000012107 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012108
Victor Stinnerc4b49542011-12-11 22:44:26 +010012109 /* no repeat, return original string */
12110 if (len == 1)
12111 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000012112
Benjamin Petersonbac79492012-01-14 13:34:47 -050012113 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012114 return NULL;
12115
Victor Stinnerc759f3e2011-10-01 03:09:58 +020012116 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020012117 PyErr_SetString(PyExc_OverflowError,
12118 "repeated string is too long");
12119 return NULL;
12120 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012121 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012122
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012123 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012124 if (!u)
12125 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012126 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012127
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012128 if (PyUnicode_GET_LENGTH(str) == 1) {
12129 const int kind = PyUnicode_KIND(str);
12130 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010012131 if (kind == PyUnicode_1BYTE_KIND) {
12132 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012133 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010012134 }
12135 else if (kind == PyUnicode_2BYTE_KIND) {
12136 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012137 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010012138 ucs2[n] = fill_char;
12139 } else {
12140 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
12141 assert(kind == PyUnicode_4BYTE_KIND);
12142 for (n = 0; n < len; ++n)
12143 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012144 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012145 }
12146 else {
12147 /* number of characters copied this far */
12148 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012149 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012150 char *to = (char *) PyUnicode_DATA(u);
12151 Py_MEMCPY(to, PyUnicode_DATA(str),
12152 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000012153 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012154 n = (done <= nchars-done) ? done : nchars-done;
12155 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012156 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000012157 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012158 }
12159
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012160 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012161 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012162}
12163
Alexander Belopolsky40018472011-02-26 01:02:56 +000012164PyObject *
12165PyUnicode_Replace(PyObject *obj,
12166 PyObject *subobj,
12167 PyObject *replobj,
12168 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012169{
12170 PyObject *self;
12171 PyObject *str1;
12172 PyObject *str2;
12173 PyObject *result;
12174
12175 self = PyUnicode_FromObject(obj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012176 if (self == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012177 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012178 str1 = PyUnicode_FromObject(subobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012179 if (str1 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012180 Py_DECREF(self);
12181 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012182 }
12183 str2 = PyUnicode_FromObject(replobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012184 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012185 Py_DECREF(self);
12186 Py_DECREF(str1);
12187 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012188 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060012189 if (PyUnicode_READY(self) == -1 ||
12190 PyUnicode_READY(str1) == -1 ||
12191 PyUnicode_READY(str2) == -1)
12192 result = NULL;
12193 else
12194 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012195 Py_DECREF(self);
12196 Py_DECREF(str1);
12197 Py_DECREF(str2);
12198 return result;
12199}
12200
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012201PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000012202 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012203\n\
12204Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000012205old replaced by new. If the optional argument count is\n\
12206given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012207
12208static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012209unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012210{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012211 PyObject *str1;
12212 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012213 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012214 PyObject *result;
12215
Martin v. Löwis18e16552006-02-15 17:27:45 +000012216 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012217 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060012218 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012219 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012220 str1 = PyUnicode_FromObject(str1);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012221 if (str1 == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012222 return NULL;
12223 str2 = PyUnicode_FromObject(str2);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012224 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012225 Py_DECREF(str1);
12226 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000012227 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060012228 if (PyUnicode_READY(str1) == -1 || PyUnicode_READY(str2) == -1)
12229 result = NULL;
12230 else
12231 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012232
12233 Py_DECREF(str1);
12234 Py_DECREF(str2);
12235 return result;
12236}
12237
Alexander Belopolsky40018472011-02-26 01:02:56 +000012238static PyObject *
12239unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012240{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012241 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012242 Py_ssize_t isize;
12243 Py_ssize_t osize, squote, dquote, i, o;
12244 Py_UCS4 max, quote;
12245 int ikind, okind;
12246 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012247
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012248 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012249 return NULL;
12250
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012251 isize = PyUnicode_GET_LENGTH(unicode);
12252 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012253
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012254 /* Compute length of output, quote characters, and
12255 maximum character */
12256 osize = 2; /* quotes */
12257 max = 127;
12258 squote = dquote = 0;
12259 ikind = PyUnicode_KIND(unicode);
12260 for (i = 0; i < isize; i++) {
12261 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
12262 switch (ch) {
12263 case '\'': squote++; osize++; break;
12264 case '"': dquote++; osize++; break;
12265 case '\\': case '\t': case '\r': case '\n':
12266 osize += 2; break;
12267 default:
12268 /* Fast-path ASCII */
12269 if (ch < ' ' || ch == 0x7f)
12270 osize += 4; /* \xHH */
12271 else if (ch < 0x7f)
12272 osize++;
12273 else if (Py_UNICODE_ISPRINTABLE(ch)) {
12274 osize++;
12275 max = ch > max ? ch : max;
12276 }
12277 else if (ch < 0x100)
12278 osize += 4; /* \xHH */
12279 else if (ch < 0x10000)
12280 osize += 6; /* \uHHHH */
12281 else
12282 osize += 10; /* \uHHHHHHHH */
12283 }
12284 }
12285
12286 quote = '\'';
12287 if (squote) {
12288 if (dquote)
12289 /* Both squote and dquote present. Use squote,
12290 and escape them */
12291 osize += squote;
12292 else
12293 quote = '"';
12294 }
12295
12296 repr = PyUnicode_New(osize, max);
12297 if (repr == NULL)
12298 return NULL;
12299 okind = PyUnicode_KIND(repr);
12300 odata = PyUnicode_DATA(repr);
12301
12302 PyUnicode_WRITE(okind, odata, 0, quote);
12303 PyUnicode_WRITE(okind, odata, osize-1, quote);
12304
12305 for (i = 0, o = 1; i < isize; i++) {
12306 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012307
12308 /* Escape quotes and backslashes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012309 if ((ch == quote) || (ch == '\\')) {
12310 PyUnicode_WRITE(okind, odata, o++, '\\');
12311 PyUnicode_WRITE(okind, odata, o++, ch);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012312 continue;
12313 }
12314
Benjamin Peterson29060642009-01-31 22:14:21 +000012315 /* Map special whitespace to '\t', \n', '\r' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012316 if (ch == '\t') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012317 PyUnicode_WRITE(okind, odata, o++, '\\');
12318 PyUnicode_WRITE(okind, odata, o++, 't');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012319 }
12320 else if (ch == '\n') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012321 PyUnicode_WRITE(okind, odata, o++, '\\');
12322 PyUnicode_WRITE(okind, odata, o++, 'n');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012323 }
12324 else if (ch == '\r') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012325 PyUnicode_WRITE(okind, odata, o++, '\\');
12326 PyUnicode_WRITE(okind, odata, o++, 'r');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012327 }
12328
12329 /* Map non-printable US ASCII to '\xhh' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012330 else if (ch < ' ' || ch == 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012331 PyUnicode_WRITE(okind, odata, o++, '\\');
12332 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012333 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12334 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012335 }
12336
Georg Brandl559e5d72008-06-11 18:37:52 +000012337 /* Copy ASCII characters as-is */
12338 else if (ch < 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012339 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012340 }
12341
Benjamin Peterson29060642009-01-31 22:14:21 +000012342 /* Non-ASCII characters */
Georg Brandl559e5d72008-06-11 18:37:52 +000012343 else {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012344 /* Map Unicode whitespace and control characters
Georg Brandl559e5d72008-06-11 18:37:52 +000012345 (categories Z* and C* except ASCII space)
12346 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012347 if (!Py_UNICODE_ISPRINTABLE(ch)) {
Georg Brandl559e5d72008-06-11 18:37:52 +000012348 /* Map 8-bit characters to '\xhh' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012349 if (ch <= 0xff) {
12350 PyUnicode_WRITE(okind, odata, o++, '\\');
12351 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012352 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12353 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012354 }
12355 /* Map 21-bit characters to '\U00xxxxxx' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012356 else if (ch >= 0x10000) {
12357 PyUnicode_WRITE(okind, odata, o++, '\\');
12358 PyUnicode_WRITE(okind, odata, o++, 'U');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012359 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12360 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12361 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12362 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12363 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12364 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12365 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12366 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012367 }
12368 /* Map 16-bit characters to '\uxxxx' */
12369 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012370 PyUnicode_WRITE(okind, odata, o++, '\\');
12371 PyUnicode_WRITE(okind, odata, o++, 'u');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012372 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12373 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12374 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12375 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012376 }
12377 }
12378 /* Copy characters as-is */
12379 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012380 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012381 }
12382 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012383 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012384 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012385 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012386 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012387}
12388
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012389PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012390 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012391\n\
12392Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012393such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012394arguments start and end are interpreted as in slice notation.\n\
12395\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012396Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012397
12398static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012399unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012400{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012401 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012402 Py_ssize_t start;
12403 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012404 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012405
Jesus Ceaac451502011-04-20 17:09:23 +020012406 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
12407 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012408 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012409
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012410 if (PyUnicode_READY(self) == -1)
12411 return NULL;
12412 if (PyUnicode_READY(substring) == -1)
12413 return NULL;
12414
Victor Stinner7931d9a2011-11-04 00:22:48 +010012415 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012416
12417 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012418
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012419 if (result == -2)
12420 return NULL;
12421
Christian Heimes217cfd12007-12-02 14:31:20 +000012422 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012423}
12424
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012425PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012426 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012427\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012428Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012429
12430static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012431unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012432{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012433 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012434 Py_ssize_t start;
12435 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012436 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012437
Jesus Ceaac451502011-04-20 17:09:23 +020012438 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12439 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012440 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012441
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012442 if (PyUnicode_READY(self) == -1)
12443 return NULL;
12444 if (PyUnicode_READY(substring) == -1)
12445 return NULL;
12446
Victor Stinner7931d9a2011-11-04 00:22:48 +010012447 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012448
12449 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012450
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012451 if (result == -2)
12452 return NULL;
12453
Guido van Rossumd57fd912000-03-10 22:53:23 +000012454 if (result < 0) {
12455 PyErr_SetString(PyExc_ValueError, "substring not found");
12456 return NULL;
12457 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012458
Christian Heimes217cfd12007-12-02 14:31:20 +000012459 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012460}
12461
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012462PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012463 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012464\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012465Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012466done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012467
12468static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012469unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012470{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012471 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012472 Py_UCS4 fillchar = ' ';
12473
Victor Stinnere9a29352011-10-01 02:14:59 +020012474 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012475 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012476
Benjamin Petersonbac79492012-01-14 13:34:47 -050012477 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012478 return NULL;
12479
Victor Stinnerc4b49542011-12-11 22:44:26 +010012480 if (PyUnicode_GET_LENGTH(self) >= width)
12481 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012482
Victor Stinnerc4b49542011-12-11 22:44:26 +010012483 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012484}
12485
Alexander Belopolsky40018472011-02-26 01:02:56 +000012486PyObject *
12487PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012488{
12489 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012490
Guido van Rossumd57fd912000-03-10 22:53:23 +000012491 s = PyUnicode_FromObject(s);
12492 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012493 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012494 if (sep != NULL) {
12495 sep = PyUnicode_FromObject(sep);
12496 if (sep == NULL) {
12497 Py_DECREF(s);
12498 return NULL;
12499 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012500 }
12501
Victor Stinner9310abb2011-10-05 00:59:23 +020012502 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012503
12504 Py_DECREF(s);
12505 Py_XDECREF(sep);
12506 return result;
12507}
12508
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012509PyDoc_STRVAR(split__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012510 "S.split([sep[, maxsplit]]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012511\n\
12512Return a list of the words in S, using sep as the\n\
12513delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012514splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012515whitespace string is a separator and empty strings are\n\
12516removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012517
12518static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012519unicode_split(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012520{
12521 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012522 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012523
Martin v. Löwis18e16552006-02-15 17:27:45 +000012524 if (!PyArg_ParseTuple(args, "|On:split", &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012525 return NULL;
12526
12527 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012528 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012529 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012530 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012531 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012532 return PyUnicode_Split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012533}
12534
Thomas Wouters477c8d52006-05-27 19:21:47 +000012535PyObject *
12536PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12537{
12538 PyObject* str_obj;
12539 PyObject* sep_obj;
12540 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012541 int kind1, kind2, kind;
12542 void *buf1 = NULL, *buf2 = NULL;
12543 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012544
12545 str_obj = PyUnicode_FromObject(str_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012546 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012547 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012548 sep_obj = PyUnicode_FromObject(sep_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012549 if (!sep_obj) {
12550 Py_DECREF(str_obj);
12551 return NULL;
12552 }
12553 if (PyUnicode_READY(sep_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
12554 Py_DECREF(sep_obj);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012555 Py_DECREF(str_obj);
12556 return NULL;
12557 }
12558
Victor Stinner14f8f022011-10-05 20:58:25 +020012559 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012560 kind2 = PyUnicode_KIND(sep_obj);
Victor Stinner14f8f022011-10-05 20:58:25 +020012561 kind = Py_MAX(kind1, kind2);
12562 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012563 if (kind1 != kind)
Victor Stinner14f8f022011-10-05 20:58:25 +020012564 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012565 if (!buf1)
12566 goto onError;
12567 buf2 = PyUnicode_DATA(sep_obj);
12568 if (kind2 != kind)
12569 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12570 if (!buf2)
12571 goto onError;
12572 len1 = PyUnicode_GET_LENGTH(str_obj);
12573 len2 = PyUnicode_GET_LENGTH(sep_obj);
12574
Benjamin Petersonead6b532011-12-20 17:23:42 -060012575 switch (PyUnicode_KIND(str_obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012576 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012577 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12578 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12579 else
12580 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012581 break;
12582 case PyUnicode_2BYTE_KIND:
12583 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12584 break;
12585 case PyUnicode_4BYTE_KIND:
12586 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12587 break;
12588 default:
12589 assert(0);
12590 out = 0;
12591 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012592
12593 Py_DECREF(sep_obj);
12594 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012595 if (kind1 != kind)
12596 PyMem_Free(buf1);
12597 if (kind2 != kind)
12598 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012599
12600 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012601 onError:
12602 Py_DECREF(sep_obj);
12603 Py_DECREF(str_obj);
12604 if (kind1 != kind && buf1)
12605 PyMem_Free(buf1);
12606 if (kind2 != kind && buf2)
12607 PyMem_Free(buf2);
12608 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012609}
12610
12611
12612PyObject *
12613PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12614{
12615 PyObject* str_obj;
12616 PyObject* sep_obj;
12617 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012618 int kind1, kind2, kind;
12619 void *buf1 = NULL, *buf2 = NULL;
12620 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012621
12622 str_obj = PyUnicode_FromObject(str_in);
12623 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012624 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012625 sep_obj = PyUnicode_FromObject(sep_in);
12626 if (!sep_obj) {
12627 Py_DECREF(str_obj);
12628 return NULL;
12629 }
12630
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012631 kind1 = PyUnicode_KIND(str_in);
12632 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020012633 kind = Py_MAX(kind1, kind2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012634 buf1 = PyUnicode_DATA(str_in);
12635 if (kind1 != kind)
12636 buf1 = _PyUnicode_AsKind(str_in, kind);
12637 if (!buf1)
12638 goto onError;
12639 buf2 = PyUnicode_DATA(sep_obj);
12640 if (kind2 != kind)
12641 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12642 if (!buf2)
12643 goto onError;
12644 len1 = PyUnicode_GET_LENGTH(str_obj);
12645 len2 = PyUnicode_GET_LENGTH(sep_obj);
12646
Benjamin Petersonead6b532011-12-20 17:23:42 -060012647 switch (PyUnicode_KIND(str_in)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012648 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012649 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12650 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12651 else
12652 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012653 break;
12654 case PyUnicode_2BYTE_KIND:
12655 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12656 break;
12657 case PyUnicode_4BYTE_KIND:
12658 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12659 break;
12660 default:
12661 assert(0);
12662 out = 0;
12663 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012664
12665 Py_DECREF(sep_obj);
12666 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012667 if (kind1 != kind)
12668 PyMem_Free(buf1);
12669 if (kind2 != kind)
12670 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012671
12672 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012673 onError:
12674 Py_DECREF(sep_obj);
12675 Py_DECREF(str_obj);
12676 if (kind1 != kind && buf1)
12677 PyMem_Free(buf1);
12678 if (kind2 != kind && buf2)
12679 PyMem_Free(buf2);
12680 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012681}
12682
12683PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012684 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012685\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012686Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012687the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012688found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012689
12690static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012691unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012692{
Victor Stinner9310abb2011-10-05 00:59:23 +020012693 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012694}
12695
12696PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012697 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012698\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012699Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012700the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012701separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012702
12703static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012704unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012705{
Victor Stinner9310abb2011-10-05 00:59:23 +020012706 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012707}
12708
Alexander Belopolsky40018472011-02-26 01:02:56 +000012709PyObject *
12710PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012711{
12712 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012713
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012714 s = PyUnicode_FromObject(s);
12715 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012716 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012717 if (sep != NULL) {
12718 sep = PyUnicode_FromObject(sep);
12719 if (sep == NULL) {
12720 Py_DECREF(s);
12721 return NULL;
12722 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012723 }
12724
Victor Stinner9310abb2011-10-05 00:59:23 +020012725 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012726
12727 Py_DECREF(s);
12728 Py_XDECREF(sep);
12729 return result;
12730}
12731
12732PyDoc_STRVAR(rsplit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012733 "S.rsplit([sep[, maxsplit]]) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012734\n\
12735Return a list of the words in S, using sep as the\n\
12736delimiter string, starting at the end of the string and\n\
12737working to the front. If maxsplit is given, at most maxsplit\n\
12738splits are done. If sep is not specified, any whitespace string\n\
12739is a separator.");
12740
12741static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012742unicode_rsplit(PyObject *self, PyObject *args)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012743{
12744 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012745 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012746
Martin v. Löwis18e16552006-02-15 17:27:45 +000012747 if (!PyArg_ParseTuple(args, "|On:rsplit", &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012748 return NULL;
12749
12750 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012751 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012752 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012753 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012754 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012755 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012756}
12757
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012758PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012759 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012760\n\
12761Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012762Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012763is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012764
12765static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012766unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012767{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012768 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012769 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012770
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012771 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12772 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012773 return NULL;
12774
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012775 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012776}
12777
12778static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012779PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012780{
Victor Stinnerc4b49542011-12-11 22:44:26 +010012781 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012782}
12783
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012784PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012785 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012786\n\
12787Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012788and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012789
12790static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012791unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012792{
Benjamin Petersoneea48462012-01-16 14:28:50 -050012793 if (PyUnicode_READY(self) == -1)
12794 return NULL;
Victor Stinnerabc649d2012-02-25 00:43:27 +010012795 if (PyUnicode_IS_ASCII(self))
12796 return ascii_case_operation(self, ascii_do_swapcase);
12797 else
12798 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012799}
12800
Georg Brandlceee0772007-11-27 23:48:05 +000012801PyDoc_STRVAR(maketrans__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012802 "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012803\n\
12804Return a translation table usable for str.translate().\n\
12805If there is only one argument, it must be a dictionary mapping Unicode\n\
12806ordinals (integers) or characters to Unicode ordinals, strings or None.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012807Character keys will be then converted to ordinals.\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012808If there are two arguments, they must be strings of equal length, and\n\
12809in the resulting dictionary, each character in x will be mapped to the\n\
12810character at the same position in y. If there is a third argument, it\n\
12811must be a string, whose characters will be mapped to None in the result.");
12812
12813static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012814unicode_maketrans(PyObject *null, PyObject *args)
Georg Brandlceee0772007-11-27 23:48:05 +000012815{
12816 PyObject *x, *y = NULL, *z = NULL;
12817 PyObject *new = NULL, *key, *value;
12818 Py_ssize_t i = 0;
12819 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012820
Georg Brandlceee0772007-11-27 23:48:05 +000012821 if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
12822 return NULL;
12823 new = PyDict_New();
12824 if (!new)
12825 return NULL;
12826 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012827 int x_kind, y_kind, z_kind;
12828 void *x_data, *y_data, *z_data;
12829
Georg Brandlceee0772007-11-27 23:48:05 +000012830 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012831 if (!PyUnicode_Check(x)) {
12832 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12833 "be a string if there is a second argument");
12834 goto err;
12835 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012836 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012837 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12838 "arguments must have equal length");
12839 goto err;
12840 }
12841 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012842 x_kind = PyUnicode_KIND(x);
12843 y_kind = PyUnicode_KIND(y);
12844 x_data = PyUnicode_DATA(x);
12845 y_data = PyUnicode_DATA(y);
12846 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
12847 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012848 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000012849 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060012850 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012851 if (!value) {
12852 Py_DECREF(key);
12853 goto err;
12854 }
Georg Brandlceee0772007-11-27 23:48:05 +000012855 res = PyDict_SetItem(new, key, value);
12856 Py_DECREF(key);
12857 Py_DECREF(value);
12858 if (res < 0)
12859 goto err;
12860 }
12861 /* create entries for deleting chars in z */
12862 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012863 z_kind = PyUnicode_KIND(z);
12864 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012865 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012866 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012867 if (!key)
12868 goto err;
12869 res = PyDict_SetItem(new, key, Py_None);
12870 Py_DECREF(key);
12871 if (res < 0)
12872 goto err;
12873 }
12874 }
12875 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012876 int kind;
12877 void *data;
12878
Georg Brandlceee0772007-11-27 23:48:05 +000012879 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000012880 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012881 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
12882 "to maketrans it must be a dict");
12883 goto err;
12884 }
12885 /* copy entries into the new dict, converting string keys to int keys */
12886 while (PyDict_Next(x, &i, &key, &value)) {
12887 if (PyUnicode_Check(key)) {
12888 /* convert string keys to integer keys */
12889 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012890 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000012891 PyErr_SetString(PyExc_ValueError, "string keys in translate "
12892 "table must be of length 1");
12893 goto err;
12894 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012895 kind = PyUnicode_KIND(key);
12896 data = PyUnicode_DATA(key);
12897 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000012898 if (!newkey)
12899 goto err;
12900 res = PyDict_SetItem(new, newkey, value);
12901 Py_DECREF(newkey);
12902 if (res < 0)
12903 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000012904 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012905 /* just keep integer keys */
12906 if (PyDict_SetItem(new, key, value) < 0)
12907 goto err;
12908 } else {
12909 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
12910 "be strings or integers");
12911 goto err;
12912 }
12913 }
12914 }
12915 return new;
12916 err:
12917 Py_DECREF(new);
12918 return NULL;
12919}
12920
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012921PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012922 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012923\n\
12924Return a copy of the string S, where all characters have been mapped\n\
12925through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012926Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000012927Unmapped characters are left untouched. Characters mapped to None\n\
12928are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012929
12930static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012931unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012932{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012933 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012934}
12935
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012936PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012937 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012938\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012939Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012940
12941static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012942unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012943{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050012944 if (PyUnicode_READY(self) == -1)
12945 return NULL;
12946 if (PyUnicode_IS_ASCII(self))
12947 return ascii_upper_or_lower(self, 0);
Victor Stinnerabc649d2012-02-25 00:43:27 +010012948 else
12949 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012950}
12951
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012952PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012953 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012954\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000012955Pad a numeric string S with zeros on the left, to fill a field\n\
12956of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012957
12958static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012959unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012960{
Martin v. Löwis18e16552006-02-15 17:27:45 +000012961 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020012962 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012963 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012964 int kind;
12965 void *data;
12966 Py_UCS4 chr;
12967
Martin v. Löwis18e16552006-02-15 17:27:45 +000012968 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012969 return NULL;
12970
Benjamin Petersonbac79492012-01-14 13:34:47 -050012971 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012972 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012973
Victor Stinnerc4b49542011-12-11 22:44:26 +010012974 if (PyUnicode_GET_LENGTH(self) >= width)
12975 return unicode_result_unchanged(self);
12976
12977 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012978
12979 u = pad(self, fill, 0, '0');
12980
Walter Dörwald068325e2002-04-15 13:36:47 +000012981 if (u == NULL)
12982 return NULL;
12983
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012984 kind = PyUnicode_KIND(u);
12985 data = PyUnicode_DATA(u);
12986 chr = PyUnicode_READ(kind, data, fill);
12987
12988 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012989 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012990 PyUnicode_WRITE(kind, data, 0, chr);
12991 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000012992 }
12993
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012994 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010012995 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012996}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012997
12998#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012999static PyObject *
13000unicode__decimal2ascii(PyObject *self)
13001{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013002 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013003}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013004#endif
13005
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013006PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013007 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013008\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013009Return True if S starts with the specified prefix, False otherwise.\n\
13010With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013011With optional end, stop comparing S at that position.\n\
13012prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013013
13014static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013015unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013016 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013017{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013018 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013019 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013020 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013021 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013022 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013023
Jesus Ceaac451502011-04-20 17:09:23 +020013024 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013025 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013026 if (PyTuple_Check(subobj)) {
13027 Py_ssize_t i;
13028 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013029 substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013030 if (substring == NULL)
13031 return NULL;
13032 result = tailmatch(self, substring, start, end, -1);
13033 Py_DECREF(substring);
13034 if (result) {
13035 Py_RETURN_TRUE;
13036 }
13037 }
13038 /* nothing matched */
13039 Py_RETURN_FALSE;
13040 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013041 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030013042 if (substring == NULL) {
13043 if (PyErr_ExceptionMatches(PyExc_TypeError))
13044 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
13045 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013046 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013047 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013048 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013049 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013050 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013051}
13052
13053
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013054PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013055 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013056\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013057Return True if S ends with the specified suffix, False otherwise.\n\
13058With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013059With optional end, stop comparing S at that position.\n\
13060suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013061
13062static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013063unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013064 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013065{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013066 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013067 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013068 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013069 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013070 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013071
Jesus Ceaac451502011-04-20 17:09:23 +020013072 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013073 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013074 if (PyTuple_Check(subobj)) {
13075 Py_ssize_t i;
13076 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013077 substring = PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000013078 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013079 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000013080 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013081 result = tailmatch(self, substring, start, end, +1);
13082 Py_DECREF(substring);
13083 if (result) {
13084 Py_RETURN_TRUE;
13085 }
13086 }
13087 Py_RETURN_FALSE;
13088 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013089 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030013090 if (substring == NULL) {
13091 if (PyErr_ExceptionMatches(PyExc_TypeError))
13092 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
13093 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013094 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013095 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013096 result = tailmatch(self, substring, start, end, +1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013097 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013098 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013099}
13100
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013101#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000013102
13103PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013104 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013105\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013106Return a formatted version of S, using substitutions from args and kwargs.\n\
13107The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000013108
Eric Smith27bbca62010-11-04 17:06:58 +000013109PyDoc_STRVAR(format_map__doc__,
13110 "S.format_map(mapping) -> str\n\
13111\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013112Return a formatted version of S, using substitutions from mapping.\n\
13113The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000013114
Eric Smith4a7d76d2008-05-30 18:10:19 +000013115static PyObject *
13116unicode__format__(PyObject* self, PyObject* args)
13117{
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013118 PyObject *format_spec, *out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013119
13120 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
13121 return NULL;
13122
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013123 out = _PyUnicode_FormatAdvanced(self, format_spec, 0,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013124 PyUnicode_GET_LENGTH(format_spec));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013125 return out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013126}
13127
Eric Smith8c663262007-08-25 02:26:07 +000013128PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013129 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013130\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013131Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000013132
13133static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013134unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013135{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013136 Py_ssize_t size;
13137
13138 /* If it's a compact object, account for base structure +
13139 character data. */
13140 if (PyUnicode_IS_COMPACT_ASCII(v))
13141 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
13142 else if (PyUnicode_IS_COMPACT(v))
13143 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013144 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013145 else {
13146 /* If it is a two-block object, account for base object, and
13147 for character block if present. */
13148 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020013149 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013150 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013151 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013152 }
13153 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013154 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020013155 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013156 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020013157 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020013158 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013159
13160 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013161}
13162
13163PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013164 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013165
13166static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020013167unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013168{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013169 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013170 if (!copy)
13171 return NULL;
13172 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013173}
13174
Guido van Rossumd57fd912000-03-10 22:53:23 +000013175static PyMethodDef unicode_methods[] = {
13176
13177 /* Order is according to common usage: often used methods should
13178 appear first, since lookup is done sequentially. */
13179
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000013180 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013181 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
13182 {"split", (PyCFunction) unicode_split, METH_VARARGS, split__doc__},
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013183 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013184 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
13185 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
Benjamin Petersond5890c82012-01-14 13:23:30 -050013186 {"casefold", (PyCFunction) unicode_casefold, METH_NOARGS, casefold__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013187 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
13188 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
13189 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
13190 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
13191 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013192 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013193 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
13194 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
13195 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013196 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013197 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13198 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
13199 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013200 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013201 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010013202 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013203 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013204 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
13205 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
13206 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
13207 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13208 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
13209 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
13210 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
13211 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
13212 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
13213 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
13214 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
13215 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
13216 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
13217 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000013218 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000013219 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013220 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000013221 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013222 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000013223 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Georg Brandlceee0772007-11-27 23:48:05 +000013224 {"maketrans", (PyCFunction) unicode_maketrans,
13225 METH_VARARGS | METH_STATIC, maketrans__doc__},
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013226 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000013227#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013228 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013229 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013230#endif
13231
Benjamin Peterson14339b62009-01-31 16:36:08 +000013232 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013233 {NULL, NULL}
13234};
13235
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013236static PyObject *
13237unicode_mod(PyObject *v, PyObject *w)
13238{
Brian Curtindfc80e32011-08-10 20:28:54 -050013239 if (!PyUnicode_Check(v))
13240 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013241 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013242}
13243
13244static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013245 0, /*nb_add*/
13246 0, /*nb_subtract*/
13247 0, /*nb_multiply*/
13248 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013249};
13250
Guido van Rossumd57fd912000-03-10 22:53:23 +000013251static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013252 (lenfunc) unicode_length, /* sq_length */
13253 PyUnicode_Concat, /* sq_concat */
13254 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13255 (ssizeargfunc) unicode_getitem, /* sq_item */
13256 0, /* sq_slice */
13257 0, /* sq_ass_item */
13258 0, /* sq_ass_slice */
13259 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013260};
13261
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013262static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013263unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013264{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013265 if (PyUnicode_READY(self) == -1)
13266 return NULL;
13267
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013268 if (PyIndex_Check(item)) {
13269 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013270 if (i == -1 && PyErr_Occurred())
13271 return NULL;
13272 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013273 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013274 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013275 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013276 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013277 PyObject *result;
13278 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013279 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013280 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013281
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013282 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013283 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013284 return NULL;
13285 }
13286
13287 if (slicelength <= 0) {
Victor Stinner382955f2011-12-11 21:44:00 +010013288 Py_INCREF(unicode_empty);
13289 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013290 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013291 slicelength == PyUnicode_GET_LENGTH(self)) {
13292 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013293 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013294 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013295 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013296 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013297 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013298 src_kind = PyUnicode_KIND(self);
13299 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013300 if (!PyUnicode_IS_ASCII(self)) {
13301 kind_limit = kind_maxchar_limit(src_kind);
13302 max_char = 0;
13303 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13304 ch = PyUnicode_READ(src_kind, src_data, cur);
13305 if (ch > max_char) {
13306 max_char = ch;
13307 if (max_char >= kind_limit)
13308 break;
13309 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013310 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013311 }
Victor Stinner55c99112011-10-13 01:17:06 +020013312 else
13313 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013314 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013315 if (result == NULL)
13316 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013317 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013318 dest_data = PyUnicode_DATA(result);
13319
13320 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013321 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13322 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013323 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013324 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013325 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013326 } else {
13327 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13328 return NULL;
13329 }
13330}
13331
13332static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013333 (lenfunc)unicode_length, /* mp_length */
13334 (binaryfunc)unicode_subscript, /* mp_subscript */
13335 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013336};
13337
Guido van Rossumd57fd912000-03-10 22:53:23 +000013338
Guido van Rossumd57fd912000-03-10 22:53:23 +000013339/* Helpers for PyUnicode_Format() */
13340
13341static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +000013342getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013343{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013344 Py_ssize_t argidx = *p_argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013345 if (argidx < arglen) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013346 (*p_argidx)++;
13347 if (arglen < 0)
13348 return args;
13349 else
13350 return PyTuple_GetItem(args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013351 }
13352 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013353 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013354 return NULL;
13355}
13356
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013357/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013358
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013359static PyObject *
13360formatfloat(PyObject *v, int flags, int prec, int type)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013361{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013362 char *p;
13363 PyObject *result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013364 double x;
Tim Petersced69f82003-09-16 20:30:58 +000013365
Guido van Rossumd57fd912000-03-10 22:53:23 +000013366 x = PyFloat_AsDouble(v);
13367 if (x == -1.0 && PyErr_Occurred())
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013368 return NULL;
13369
Guido van Rossumd57fd912000-03-10 22:53:23 +000013370 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013371 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013372
Eric Smith0923d1d2009-04-16 20:16:10 +000013373 p = PyOS_double_to_string(x, type, prec,
13374 (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013375 if (p == NULL)
13376 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013377 result = PyUnicode_DecodeASCII(p, strlen(p), NULL);
Eric Smith0923d1d2009-04-16 20:16:10 +000013378 PyMem_Free(p);
13379 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013380}
13381
Tim Peters38fd5b62000-09-21 05:43:11 +000013382static PyObject*
13383formatlong(PyObject *val, int flags, int prec, int type)
13384{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013385 char *buf;
13386 int len;
13387 PyObject *str; /* temporary string object. */
13388 PyObject *result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013389
Benjamin Peterson14339b62009-01-31 16:36:08 +000013390 str = _PyBytes_FormatLong(val, flags, prec, type, &buf, &len);
13391 if (!str)
13392 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013393 result = PyUnicode_DecodeASCII(buf, len, NULL);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013394 Py_DECREF(str);
13395 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013396}
13397
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013398static Py_UCS4
13399formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013400{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013401 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013402 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013403 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013404 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000013405 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013406 goto onError;
13407 }
13408 else {
13409 /* Integer input truncated to a character */
13410 long x;
13411 x = PyLong_AsLong(v);
13412 if (x == -1 && PyErr_Occurred())
13413 goto onError;
13414
Victor Stinner8faf8212011-12-08 22:14:11 +010013415 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013416 PyErr_SetString(PyExc_OverflowError,
13417 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013418 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013419 }
13420
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013421 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013422 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013423
Benjamin Peterson29060642009-01-31 22:14:21 +000013424 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013425 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013426 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013427 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013428}
13429
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013430static int
13431repeat_accumulate(_PyAccu *acc, PyObject *obj, Py_ssize_t count)
13432{
13433 int r;
13434 assert(count > 0);
13435 assert(PyUnicode_Check(obj));
13436 if (count > 5) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013437 PyObject *repeated = unicode_repeat(obj, count);
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013438 if (repeated == NULL)
13439 return -1;
13440 r = _PyAccu_Accumulate(acc, repeated);
13441 Py_DECREF(repeated);
13442 return r;
13443 }
13444 else {
13445 do {
13446 if (_PyAccu_Accumulate(acc, obj))
13447 return -1;
13448 } while (--count);
13449 return 0;
13450 }
13451}
13452
Alexander Belopolsky40018472011-02-26 01:02:56 +000013453PyObject *
13454PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013455{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013456 void *fmt;
13457 int fmtkind;
13458 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013459 int kind;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013460 int r;
13461 Py_ssize_t fmtcnt, fmtpos, arglen, argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013462 int args_owned = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013463 PyObject *dict = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013464 PyObject *temp = NULL;
13465 PyObject *second = NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013466 PyObject *uformat;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013467 _PyAccu acc;
13468 static PyObject *plus, *minus, *blank, *zero, *percent;
13469
13470 if (!plus && !(plus = get_latin1_char('+')))
13471 return NULL;
13472 if (!minus && !(minus = get_latin1_char('-')))
13473 return NULL;
13474 if (!blank && !(blank = get_latin1_char(' ')))
13475 return NULL;
13476 if (!zero && !(zero = get_latin1_char('0')))
13477 return NULL;
13478 if (!percent && !(percent = get_latin1_char('%')))
13479 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000013480
Guido van Rossumd57fd912000-03-10 22:53:23 +000013481 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013482 PyErr_BadInternalCall();
13483 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013484 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013485 uformat = PyUnicode_FromObject(format);
Benjamin Peterson22a29702012-01-02 09:00:30 -060013486 if (uformat == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000013487 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060013488 if (PyUnicode_READY(uformat) == -1)
13489 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013490 if (_PyAccu_Init(&acc))
13491 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013492 fmt = PyUnicode_DATA(uformat);
13493 fmtkind = PyUnicode_KIND(uformat);
13494 fmtcnt = PyUnicode_GET_LENGTH(uformat);
13495 fmtpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013496
Guido van Rossumd57fd912000-03-10 22:53:23 +000013497 if (PyTuple_Check(args)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013498 arglen = PyTuple_Size(args);
13499 argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013500 }
13501 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013502 arglen = -1;
13503 argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013504 }
Christian Heimes90aa7642007-12-19 02:45:37 +000013505 if (Py_TYPE(args)->tp_as_mapping && !PyTuple_Check(args) &&
Christian Heimesf3863112007-11-22 07:46:41 +000013506 !PyUnicode_Check(args))
Benjamin Peterson29060642009-01-31 22:14:21 +000013507 dict = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013508
13509 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013510 if (PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013511 PyObject *nonfmt;
13512 Py_ssize_t nonfmtpos;
13513 nonfmtpos = fmtpos++;
13514 while (fmtcnt >= 0 &&
13515 PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
13516 fmtpos++;
13517 fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013518 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010013519 nonfmt = PyUnicode_Substring(uformat, nonfmtpos, fmtpos);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013520 if (nonfmt == NULL)
13521 goto onError;
13522 r = _PyAccu_Accumulate(&acc, nonfmt);
13523 Py_DECREF(nonfmt);
13524 if (r)
13525 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013526 }
13527 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013528 /* Got a format specifier */
13529 int flags = 0;
13530 Py_ssize_t width = -1;
13531 int prec = -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013532 Py_UCS4 c = '\0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013533 Py_UCS4 fill, sign;
Benjamin Peterson29060642009-01-31 22:14:21 +000013534 int isnumok;
13535 PyObject *v = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013536 void *pbuf = NULL;
13537 Py_ssize_t pindex, len;
13538 PyObject *signobj = NULL, *fillobj = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013539
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013540 fmtpos++;
13541 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(') {
13542 Py_ssize_t keystart;
Benjamin Peterson29060642009-01-31 22:14:21 +000013543 Py_ssize_t keylen;
13544 PyObject *key;
13545 int pcount = 1;
Christian Heimesa612dc02008-02-24 13:08:18 +000013546
Benjamin Peterson29060642009-01-31 22:14:21 +000013547 if (dict == NULL) {
13548 PyErr_SetString(PyExc_TypeError,
13549 "format requires a mapping");
13550 goto onError;
13551 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013552 ++fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013553 --fmtcnt;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013554 keystart = fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013555 /* Skip over balanced parentheses */
13556 while (pcount > 0 && --fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013557 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == ')')
Benjamin Peterson29060642009-01-31 22:14:21 +000013558 --pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013559 else 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 fmtpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013562 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013563 keylen = fmtpos - keystart - 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013564 if (fmtcnt < 0 || pcount > 0) {
13565 PyErr_SetString(PyExc_ValueError,
13566 "incomplete format key");
13567 goto onError;
13568 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010013569 key = PyUnicode_Substring(uformat,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013570 keystart, keystart + keylen);
Benjamin Peterson29060642009-01-31 22:14:21 +000013571 if (key == NULL)
13572 goto onError;
13573 if (args_owned) {
13574 Py_DECREF(args);
13575 args_owned = 0;
13576 }
13577 args = PyObject_GetItem(dict, key);
13578 Py_DECREF(key);
13579 if (args == NULL) {
13580 goto onError;
13581 }
13582 args_owned = 1;
13583 arglen = -1;
13584 argidx = -2;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013585 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013586 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013587 switch (c = PyUnicode_READ(fmtkind, fmt, fmtpos++)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013588 case '-': flags |= F_LJUST; continue;
13589 case '+': flags |= F_SIGN; continue;
13590 case ' ': flags |= F_BLANK; continue;
13591 case '#': flags |= F_ALT; continue;
13592 case '0': flags |= F_ZERO; continue;
13593 }
13594 break;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013595 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013596 if (c == '*') {
13597 v = getnextarg(args, arglen, &argidx);
13598 if (v == NULL)
13599 goto onError;
13600 if (!PyLong_Check(v)) {
13601 PyErr_SetString(PyExc_TypeError,
13602 "* wants int");
13603 goto onError;
13604 }
13605 width = PyLong_AsLong(v);
13606 if (width == -1 && PyErr_Occurred())
13607 goto onError;
13608 if (width < 0) {
13609 flags |= F_LJUST;
13610 width = -width;
13611 }
13612 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013613 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013614 }
13615 else if (c >= '0' && c <= '9') {
13616 width = c - '0';
13617 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013618 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013619 if (c < '0' || c > '9')
13620 break;
13621 if ((width*10) / 10 != width) {
13622 PyErr_SetString(PyExc_ValueError,
13623 "width too big");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013624 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013625 }
13626 width = width*10 + (c - '0');
13627 }
13628 }
13629 if (c == '.') {
13630 prec = 0;
13631 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013632 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013633 if (c == '*') {
13634 v = getnextarg(args, arglen, &argidx);
13635 if (v == NULL)
13636 goto onError;
13637 if (!PyLong_Check(v)) {
13638 PyErr_SetString(PyExc_TypeError,
13639 "* wants int");
13640 goto onError;
13641 }
13642 prec = PyLong_AsLong(v);
13643 if (prec == -1 && PyErr_Occurred())
13644 goto onError;
13645 if (prec < 0)
13646 prec = 0;
13647 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013648 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013649 }
13650 else if (c >= '0' && c <= '9') {
13651 prec = c - '0';
13652 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013653 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013654 if (c < '0' || c > '9')
13655 break;
13656 if ((prec*10) / 10 != prec) {
13657 PyErr_SetString(PyExc_ValueError,
13658 "prec too big");
13659 goto onError;
13660 }
13661 prec = prec*10 + (c - '0');
13662 }
13663 }
13664 } /* prec */
13665 if (fmtcnt >= 0) {
13666 if (c == 'h' || c == 'l' || c == 'L') {
13667 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013668 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013669 }
13670 }
13671 if (fmtcnt < 0) {
13672 PyErr_SetString(PyExc_ValueError,
13673 "incomplete format");
13674 goto onError;
13675 }
13676 if (c != '%') {
13677 v = getnextarg(args, arglen, &argidx);
13678 if (v == NULL)
13679 goto onError;
13680 }
13681 sign = 0;
13682 fill = ' ';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013683 fillobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013684 switch (c) {
13685
13686 case '%':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013687 _PyAccu_Accumulate(&acc, percent);
13688 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +000013689
13690 case 's':
13691 case 'r':
13692 case 'a':
Victor Stinner808fc0a2010-03-22 12:50:40 +000013693 if (PyUnicode_CheckExact(v) && c == 's') {
Benjamin Peterson29060642009-01-31 22:14:21 +000013694 temp = v;
13695 Py_INCREF(temp);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013696 }
13697 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013698 if (c == 's')
13699 temp = PyObject_Str(v);
13700 else if (c == 'r')
13701 temp = PyObject_Repr(v);
13702 else
13703 temp = PyObject_ASCII(v);
13704 if (temp == NULL)
13705 goto onError;
13706 if (PyUnicode_Check(temp))
13707 /* nothing to do */;
13708 else {
13709 Py_DECREF(temp);
13710 PyErr_SetString(PyExc_TypeError,
13711 "%s argument has non-string str()");
13712 goto onError;
13713 }
13714 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013715 if (PyUnicode_READY(temp) == -1) {
13716 Py_CLEAR(temp);
13717 goto onError;
13718 }
13719 pbuf = PyUnicode_DATA(temp);
13720 kind = PyUnicode_KIND(temp);
13721 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013722 if (prec >= 0 && len > prec)
13723 len = prec;
13724 break;
13725
13726 case 'i':
13727 case 'd':
13728 case 'u':
13729 case 'o':
13730 case 'x':
13731 case 'X':
Benjamin Peterson29060642009-01-31 22:14:21 +000013732 isnumok = 0;
13733 if (PyNumber_Check(v)) {
13734 PyObject *iobj=NULL;
13735
13736 if (PyLong_Check(v)) {
13737 iobj = v;
13738 Py_INCREF(iobj);
13739 }
13740 else {
13741 iobj = PyNumber_Long(v);
13742 }
13743 if (iobj!=NULL) {
13744 if (PyLong_Check(iobj)) {
13745 isnumok = 1;
Senthil Kumaran9ebe08d2011-07-03 21:03:16 -070013746 temp = formatlong(iobj, flags, prec, (c == 'i'? 'd': c));
Benjamin Peterson29060642009-01-31 22:14:21 +000013747 Py_DECREF(iobj);
13748 if (!temp)
13749 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013750 if (PyUnicode_READY(temp) == -1) {
13751 Py_CLEAR(temp);
13752 goto onError;
13753 }
13754 pbuf = PyUnicode_DATA(temp);
13755 kind = PyUnicode_KIND(temp);
13756 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013757 sign = 1;
13758 }
13759 else {
13760 Py_DECREF(iobj);
13761 }
13762 }
13763 }
13764 if (!isnumok) {
13765 PyErr_Format(PyExc_TypeError,
13766 "%%%c format: a number is required, "
13767 "not %.200s", (char)c, Py_TYPE(v)->tp_name);
13768 goto onError;
13769 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013770 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013771 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013772 fillobj = zero;
13773 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013774 break;
13775
13776 case 'e':
13777 case 'E':
13778 case 'f':
13779 case 'F':
13780 case 'g':
13781 case 'G':
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013782 temp = formatfloat(v, flags, prec, c);
13783 if (!temp)
Benjamin Peterson29060642009-01-31 22:14:21 +000013784 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013785 if (PyUnicode_READY(temp) == -1) {
13786 Py_CLEAR(temp);
13787 goto onError;
13788 }
13789 pbuf = PyUnicode_DATA(temp);
13790 kind = PyUnicode_KIND(temp);
13791 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013792 sign = 1;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013793 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013794 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013795 fillobj = zero;
13796 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013797 break;
13798
13799 case 'c':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013800 {
13801 Py_UCS4 ch = formatchar(v);
13802 if (ch == (Py_UCS4) -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013803 goto onError;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013804 temp = _PyUnicode_FromUCS4(&ch, 1);
13805 if (temp == NULL)
13806 goto onError;
13807 pbuf = PyUnicode_DATA(temp);
13808 kind = PyUnicode_KIND(temp);
13809 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013810 break;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013811 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013812
13813 default:
13814 PyErr_Format(PyExc_ValueError,
13815 "unsupported format character '%c' (0x%x) "
13816 "at index %zd",
13817 (31<=c && c<=126) ? (char)c : '?',
13818 (int)c,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013819 fmtpos - 1);
Benjamin Peterson29060642009-01-31 22:14:21 +000013820 goto onError;
13821 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013822 /* pbuf is initialized here. */
13823 pindex = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +000013824 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013825 if (PyUnicode_READ(kind, pbuf, pindex) == '-') {
13826 signobj = minus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013827 len--;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013828 pindex++;
13829 }
13830 else if (PyUnicode_READ(kind, pbuf, pindex) == '+') {
13831 signobj = plus;
13832 len--;
13833 pindex++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013834 }
13835 else if (flags & F_SIGN)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013836 signobj = plus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013837 else if (flags & F_BLANK)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013838 signobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013839 else
13840 sign = 0;
13841 }
13842 if (width < len)
13843 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013844 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013845 if (fill != ' ') {
13846 assert(signobj != NULL);
13847 if (_PyAccu_Accumulate(&acc, signobj))
13848 goto onError;
13849 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013850 if (width > len)
13851 width--;
13852 }
13853 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013854 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013855 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == c);
Benjamin Peterson29060642009-01-31 22:14:21 +000013856 if (fill != ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013857 second = get_latin1_char(
13858 PyUnicode_READ(kind, pbuf, pindex + 1));
13859 pindex += 2;
13860 if (second == NULL ||
13861 _PyAccu_Accumulate(&acc, zero) ||
13862 _PyAccu_Accumulate(&acc, second))
13863 goto onError;
13864 Py_CLEAR(second);
Benjamin Peterson29060642009-01-31 22:14:21 +000013865 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013866 width -= 2;
13867 if (width < 0)
13868 width = 0;
13869 len -= 2;
13870 }
13871 if (width > len && !(flags & F_LJUST)) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013872 assert(fillobj != NULL);
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013873 if (repeat_accumulate(&acc, fillobj, width - len))
13874 goto onError;
13875 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013876 }
13877 if (fill == ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013878 if (sign) {
13879 assert(signobj != NULL);
13880 if (_PyAccu_Accumulate(&acc, signobj))
13881 goto onError;
13882 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013883 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013884 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
13885 assert(PyUnicode_READ(kind, pbuf, pindex+1) == c);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013886 second = get_latin1_char(
13887 PyUnicode_READ(kind, pbuf, pindex + 1));
13888 pindex += 2;
13889 if (second == NULL ||
13890 _PyAccu_Accumulate(&acc, zero) ||
13891 _PyAccu_Accumulate(&acc, second))
13892 goto onError;
13893 Py_CLEAR(second);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013894 }
13895 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013896 /* Copy all characters, preserving len */
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013897 if (temp != NULL) {
13898 assert(pbuf == PyUnicode_DATA(temp));
13899 v = PyUnicode_Substring(temp, pindex, pindex + len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013900 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013901 else {
13902 const char *p = (const char *) pbuf;
13903 assert(pbuf != NULL);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013904 p += kind * pindex;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013905 v = PyUnicode_FromKindAndData(kind, p, len);
13906 }
13907 if (v == NULL)
13908 goto onError;
13909 r = _PyAccu_Accumulate(&acc, v);
13910 Py_DECREF(v);
13911 if (r)
13912 goto onError;
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013913 if (width > len && repeat_accumulate(&acc, blank, width - len))
13914 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013915 if (dict && (argidx < arglen) && c != '%') {
13916 PyErr_SetString(PyExc_TypeError,
13917 "not all arguments converted during string formatting");
Benjamin Peterson29060642009-01-31 22:14:21 +000013918 goto onError;
13919 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013920 Py_CLEAR(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013921 } /* '%' */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013922 } /* until end */
13923 if (argidx < arglen && !dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013924 PyErr_SetString(PyExc_TypeError,
13925 "not all arguments converted during string formatting");
13926 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013927 }
13928
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013929 result = _PyAccu_Finish(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013930 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013931 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013932 }
13933 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013934 Py_XDECREF(temp);
13935 Py_XDECREF(second);
Victor Stinner7931d9a2011-11-04 00:22:48 +010013936 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013937
Benjamin Peterson29060642009-01-31 22:14:21 +000013938 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013939 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013940 Py_XDECREF(temp);
13941 Py_XDECREF(second);
13942 _PyAccu_Destroy(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013943 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013944 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013945 }
13946 return NULL;
13947}
13948
Jeremy Hylton938ace62002-07-17 16:30:39 +000013949static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000013950unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
13951
Tim Peters6d6c1a32001-08-02 04:15:00 +000013952static PyObject *
13953unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13954{
Benjamin Peterson29060642009-01-31 22:14:21 +000013955 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013956 static char *kwlist[] = {"object", "encoding", "errors", 0};
13957 char *encoding = NULL;
13958 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000013959
Benjamin Peterson14339b62009-01-31 16:36:08 +000013960 if (type != &PyUnicode_Type)
13961 return unicode_subtype_new(type, args, kwds);
13962 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000013963 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000013964 return NULL;
Victor Stinner382955f2011-12-11 21:44:00 +010013965 if (x == NULL) {
13966 Py_INCREF(unicode_empty);
13967 return unicode_empty;
13968 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000013969 if (encoding == NULL && errors == NULL)
13970 return PyObject_Str(x);
13971 else
Benjamin Peterson29060642009-01-31 22:14:21 +000013972 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000013973}
13974
Guido van Rossume023fe02001-08-30 03:12:59 +000013975static PyObject *
13976unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13977{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013978 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013979 Py_ssize_t length, char_size;
13980 int share_wstr, share_utf8;
13981 unsigned int kind;
13982 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000013983
Benjamin Peterson14339b62009-01-31 16:36:08 +000013984 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013985
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013986 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013987 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013988 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020013989 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050013990 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060013991 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013992 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060013993 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013994
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013995 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013996 if (self == NULL) {
13997 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013998 return NULL;
13999 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014000 kind = PyUnicode_KIND(unicode);
14001 length = PyUnicode_GET_LENGTH(unicode);
14002
14003 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014004#ifdef Py_DEBUG
14005 _PyUnicode_HASH(self) = -1;
14006#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014007 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014008#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014009 _PyUnicode_STATE(self).interned = 0;
14010 _PyUnicode_STATE(self).kind = kind;
14011 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020014012 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014013 _PyUnicode_STATE(self).ready = 1;
14014 _PyUnicode_WSTR(self) = NULL;
14015 _PyUnicode_UTF8_LENGTH(self) = 0;
14016 _PyUnicode_UTF8(self) = NULL;
14017 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020014018 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014019
14020 share_utf8 = 0;
14021 share_wstr = 0;
14022 if (kind == PyUnicode_1BYTE_KIND) {
14023 char_size = 1;
14024 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
14025 share_utf8 = 1;
14026 }
14027 else if (kind == PyUnicode_2BYTE_KIND) {
14028 char_size = 2;
14029 if (sizeof(wchar_t) == 2)
14030 share_wstr = 1;
14031 }
14032 else {
14033 assert(kind == PyUnicode_4BYTE_KIND);
14034 char_size = 4;
14035 if (sizeof(wchar_t) == 4)
14036 share_wstr = 1;
14037 }
14038
14039 /* Ensure we won't overflow the length. */
14040 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
14041 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014042 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014043 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014044 data = PyObject_MALLOC((length + 1) * char_size);
14045 if (data == NULL) {
14046 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014047 goto onError;
14048 }
14049
Victor Stinnerc3c74152011-10-02 20:39:55 +020014050 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014051 if (share_utf8) {
14052 _PyUnicode_UTF8_LENGTH(self) = length;
14053 _PyUnicode_UTF8(self) = data;
14054 }
14055 if (share_wstr) {
14056 _PyUnicode_WSTR_LENGTH(self) = length;
14057 _PyUnicode_WSTR(self) = (wchar_t *)data;
14058 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014059
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014060 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020014061 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020014062 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014063#ifdef Py_DEBUG
14064 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
14065#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020014066 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010014067 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014068
14069onError:
14070 Py_DECREF(unicode);
14071 Py_DECREF(self);
14072 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000014073}
14074
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000014075PyDoc_STRVAR(unicode_doc,
Benjamin Peterson29060642009-01-31 22:14:21 +000014076 "str(string[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000014077\n\
Collin Winterd474ce82007-08-07 19:42:11 +000014078Create a new string object from the given encoded string.\n\
Skip Montanaro35b37a52002-07-26 16:22:46 +000014079encoding defaults to the current default string encoding.\n\
14080errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000014081
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014082static PyObject *unicode_iter(PyObject *seq);
14083
Guido van Rossumd57fd912000-03-10 22:53:23 +000014084PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000014085 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014086 "str", /* tp_name */
14087 sizeof(PyUnicodeObject), /* tp_size */
14088 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014089 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014090 (destructor)unicode_dealloc, /* tp_dealloc */
14091 0, /* tp_print */
14092 0, /* tp_getattr */
14093 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014094 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014095 unicode_repr, /* tp_repr */
14096 &unicode_as_number, /* tp_as_number */
14097 &unicode_as_sequence, /* tp_as_sequence */
14098 &unicode_as_mapping, /* tp_as_mapping */
14099 (hashfunc) unicode_hash, /* tp_hash*/
14100 0, /* tp_call*/
14101 (reprfunc) unicode_str, /* tp_str */
14102 PyObject_GenericGetAttr, /* tp_getattro */
14103 0, /* tp_setattro */
14104 0, /* tp_as_buffer */
14105 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000014106 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014107 unicode_doc, /* tp_doc */
14108 0, /* tp_traverse */
14109 0, /* tp_clear */
14110 PyUnicode_RichCompare, /* tp_richcompare */
14111 0, /* tp_weaklistoffset */
14112 unicode_iter, /* tp_iter */
14113 0, /* tp_iternext */
14114 unicode_methods, /* tp_methods */
14115 0, /* tp_members */
14116 0, /* tp_getset */
14117 &PyBaseObject_Type, /* tp_base */
14118 0, /* tp_dict */
14119 0, /* tp_descr_get */
14120 0, /* tp_descr_set */
14121 0, /* tp_dictoffset */
14122 0, /* tp_init */
14123 0, /* tp_alloc */
14124 unicode_new, /* tp_new */
14125 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014126};
14127
14128/* Initialize the Unicode implementation */
14129
Victor Stinner3a50e702011-10-18 21:21:00 +020014130int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014131{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014132 int i;
14133
Thomas Wouters477c8d52006-05-27 19:21:47 +000014134 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014135 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000014136 0x000A, /* LINE FEED */
14137 0x000D, /* CARRIAGE RETURN */
14138 0x001C, /* FILE SEPARATOR */
14139 0x001D, /* GROUP SEPARATOR */
14140 0x001E, /* RECORD SEPARATOR */
14141 0x0085, /* NEXT LINE */
14142 0x2028, /* LINE SEPARATOR */
14143 0x2029, /* PARAGRAPH SEPARATOR */
14144 };
14145
Fred Drakee4315f52000-05-09 19:53:39 +000014146 /* Init the implementation */
Victor Stinnera464fc12011-10-02 20:39:30 +020014147 unicode_empty = PyUnicode_New(0, 0);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014148 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014149 Py_FatalError("Can't create empty string");
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010014150 assert(_PyUnicode_CheckConsistency(unicode_empty, 1));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014151
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014152 for (i = 0; i < 256; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +000014153 unicode_latin1[i] = NULL;
Guido van Rossumcacfc072002-05-24 19:01:59 +000014154 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014155 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000014156
14157 /* initialize the linebreak bloom filter */
14158 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014159 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020014160 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014161
14162 PyType_Ready(&EncodingMapType);
Victor Stinner3a50e702011-10-18 21:21:00 +020014163
14164#ifdef HAVE_MBCS
14165 winver.dwOSVersionInfoSize = sizeof(winver);
14166 if (!GetVersionEx((OSVERSIONINFO*)&winver)) {
14167 PyErr_SetFromWindowsErr(0);
14168 return -1;
14169 }
14170#endif
14171 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014172}
14173
14174/* Finalize the Unicode implementation */
14175
Christian Heimesa156e092008-02-16 07:38:31 +000014176int
14177PyUnicode_ClearFreeList(void)
14178{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014179 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000014180}
14181
Guido van Rossumd57fd912000-03-10 22:53:23 +000014182void
Thomas Wouters78890102000-07-22 19:25:51 +000014183_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014184{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014185 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014186
Guido van Rossum4ae8ef82000-10-03 18:09:04 +000014187 Py_XDECREF(unicode_empty);
14188 unicode_empty = NULL;
Barry Warsaw5b4c2282000-10-03 20:45:26 +000014189
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014190 for (i = 0; i < 256; i++) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014191 if (unicode_latin1[i]) {
14192 Py_DECREF(unicode_latin1[i]);
14193 unicode_latin1[i] = NULL;
14194 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014195 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020014196 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000014197 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000014198}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000014199
Walter Dörwald16807132007-05-25 13:52:07 +000014200void
14201PyUnicode_InternInPlace(PyObject **p)
14202{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014203 register PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014204 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020014205#ifdef Py_DEBUG
14206 assert(s != NULL);
14207 assert(_PyUnicode_CHECK(s));
14208#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000014209 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020014210 return;
14211#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000014212 /* If it's a subclass, we don't really know what putting
14213 it in the interned dict might do. */
14214 if (!PyUnicode_CheckExact(s))
14215 return;
14216 if (PyUnicode_CHECK_INTERNED(s))
14217 return;
14218 if (interned == NULL) {
14219 interned = PyDict_New();
14220 if (interned == NULL) {
14221 PyErr_Clear(); /* Don't leave an exception */
14222 return;
14223 }
14224 }
14225 /* It might be that the GetItem call fails even
14226 though the key is present in the dictionary,
14227 namely when this happens during a stack overflow. */
14228 Py_ALLOW_RECURSION
Victor Stinner7931d9a2011-11-04 00:22:48 +010014229 t = PyDict_GetItem(interned, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014230 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000014231
Benjamin Peterson29060642009-01-31 22:14:21 +000014232 if (t) {
14233 Py_INCREF(t);
14234 Py_DECREF(*p);
14235 *p = t;
14236 return;
14237 }
Walter Dörwald16807132007-05-25 13:52:07 +000014238
Benjamin Peterson14339b62009-01-31 16:36:08 +000014239 PyThreadState_GET()->recursion_critical = 1;
Victor Stinner7931d9a2011-11-04 00:22:48 +010014240 if (PyDict_SetItem(interned, s, s) < 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014241 PyErr_Clear();
14242 PyThreadState_GET()->recursion_critical = 0;
14243 return;
14244 }
14245 PyThreadState_GET()->recursion_critical = 0;
14246 /* The two references in interned are not counted by refcnt.
14247 The deallocator will take care of this */
14248 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014249 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000014250}
14251
14252void
14253PyUnicode_InternImmortal(PyObject **p)
14254{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014255 PyUnicode_InternInPlace(p);
14256 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020014257 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014258 Py_INCREF(*p);
14259 }
Walter Dörwald16807132007-05-25 13:52:07 +000014260}
14261
14262PyObject *
14263PyUnicode_InternFromString(const char *cp)
14264{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014265 PyObject *s = PyUnicode_FromString(cp);
14266 if (s == NULL)
14267 return NULL;
14268 PyUnicode_InternInPlace(&s);
14269 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000014270}
14271
Alexander Belopolsky40018472011-02-26 01:02:56 +000014272void
14273_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000014274{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014275 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014276 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014277 Py_ssize_t i, n;
14278 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000014279
Benjamin Peterson14339b62009-01-31 16:36:08 +000014280 if (interned == NULL || !PyDict_Check(interned))
14281 return;
14282 keys = PyDict_Keys(interned);
14283 if (keys == NULL || !PyList_Check(keys)) {
14284 PyErr_Clear();
14285 return;
14286 }
Walter Dörwald16807132007-05-25 13:52:07 +000014287
Benjamin Peterson14339b62009-01-31 16:36:08 +000014288 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
14289 detector, interned unicode strings are not forcibly deallocated;
14290 rather, we give them their stolen references back, and then clear
14291 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000014292
Benjamin Peterson14339b62009-01-31 16:36:08 +000014293 n = PyList_GET_SIZE(keys);
14294 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000014295 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014296 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014297 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014298 if (PyUnicode_READY(s) == -1) {
14299 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014300 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014301 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014302 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014303 case SSTATE_NOT_INTERNED:
14304 /* XXX Shouldn't happen */
14305 break;
14306 case SSTATE_INTERNED_IMMORTAL:
14307 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014308 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014309 break;
14310 case SSTATE_INTERNED_MORTAL:
14311 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014312 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014313 break;
14314 default:
14315 Py_FatalError("Inconsistent interned string state.");
14316 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014317 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014318 }
14319 fprintf(stderr, "total size of all interned strings: "
14320 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
14321 "mortal/immortal\n", mortal_size, immortal_size);
14322 Py_DECREF(keys);
14323 PyDict_Clear(interned);
14324 Py_DECREF(interned);
14325 interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +000014326}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014327
14328
14329/********************* Unicode Iterator **************************/
14330
14331typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014332 PyObject_HEAD
14333 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014334 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014335} unicodeiterobject;
14336
14337static void
14338unicodeiter_dealloc(unicodeiterobject *it)
14339{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014340 _PyObject_GC_UNTRACK(it);
14341 Py_XDECREF(it->it_seq);
14342 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014343}
14344
14345static int
14346unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
14347{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014348 Py_VISIT(it->it_seq);
14349 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014350}
14351
14352static PyObject *
14353unicodeiter_next(unicodeiterobject *it)
14354{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014355 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014356
Benjamin Peterson14339b62009-01-31 16:36:08 +000014357 assert(it != NULL);
14358 seq = it->it_seq;
14359 if (seq == NULL)
14360 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014361 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014362
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014363 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
14364 int kind = PyUnicode_KIND(seq);
14365 void *data = PyUnicode_DATA(seq);
14366 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
14367 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014368 if (item != NULL)
14369 ++it->it_index;
14370 return item;
14371 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014372
Benjamin Peterson14339b62009-01-31 16:36:08 +000014373 Py_DECREF(seq);
14374 it->it_seq = NULL;
14375 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014376}
14377
14378static PyObject *
14379unicodeiter_len(unicodeiterobject *it)
14380{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014381 Py_ssize_t len = 0;
14382 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020014383 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014384 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014385}
14386
14387PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
14388
14389static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014390 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000014391 length_hint_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000014392 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014393};
14394
14395PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014396 PyVarObject_HEAD_INIT(&PyType_Type, 0)
14397 "str_iterator", /* tp_name */
14398 sizeof(unicodeiterobject), /* tp_basicsize */
14399 0, /* tp_itemsize */
14400 /* methods */
14401 (destructor)unicodeiter_dealloc, /* tp_dealloc */
14402 0, /* tp_print */
14403 0, /* tp_getattr */
14404 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014405 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014406 0, /* tp_repr */
14407 0, /* tp_as_number */
14408 0, /* tp_as_sequence */
14409 0, /* tp_as_mapping */
14410 0, /* tp_hash */
14411 0, /* tp_call */
14412 0, /* tp_str */
14413 PyObject_GenericGetAttr, /* tp_getattro */
14414 0, /* tp_setattro */
14415 0, /* tp_as_buffer */
14416 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
14417 0, /* tp_doc */
14418 (traverseproc)unicodeiter_traverse, /* tp_traverse */
14419 0, /* tp_clear */
14420 0, /* tp_richcompare */
14421 0, /* tp_weaklistoffset */
14422 PyObject_SelfIter, /* tp_iter */
14423 (iternextfunc)unicodeiter_next, /* tp_iternext */
14424 unicodeiter_methods, /* tp_methods */
14425 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014426};
14427
14428static PyObject *
14429unicode_iter(PyObject *seq)
14430{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014431 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014432
Benjamin Peterson14339b62009-01-31 16:36:08 +000014433 if (!PyUnicode_Check(seq)) {
14434 PyErr_BadInternalCall();
14435 return NULL;
14436 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014437 if (PyUnicode_READY(seq) == -1)
14438 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014439 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
14440 if (it == NULL)
14441 return NULL;
14442 it->it_index = 0;
14443 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014444 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014445 _PyObject_GC_TRACK(it);
14446 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014447}
14448
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010014449
14450size_t
14451Py_UNICODE_strlen(const Py_UNICODE *u)
14452{
14453 int res = 0;
14454 while(*u++)
14455 res++;
14456 return res;
14457}
14458
14459Py_UNICODE*
14460Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
14461{
14462 Py_UNICODE *u = s1;
14463 while ((*u++ = *s2++));
14464 return s1;
14465}
14466
14467Py_UNICODE*
14468Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14469{
14470 Py_UNICODE *u = s1;
14471 while ((*u++ = *s2++))
14472 if (n-- == 0)
14473 break;
14474 return s1;
14475}
14476
14477Py_UNICODE*
14478Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
14479{
14480 Py_UNICODE *u1 = s1;
14481 u1 += Py_UNICODE_strlen(u1);
14482 Py_UNICODE_strcpy(u1, s2);
14483 return s1;
14484}
14485
14486int
14487Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
14488{
14489 while (*s1 && *s2 && *s1 == *s2)
14490 s1++, s2++;
14491 if (*s1 && *s2)
14492 return (*s1 < *s2) ? -1 : +1;
14493 if (*s1)
14494 return 1;
14495 if (*s2)
14496 return -1;
14497 return 0;
14498}
14499
14500int
14501Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14502{
14503 register Py_UNICODE u1, u2;
14504 for (; n != 0; n--) {
14505 u1 = *s1;
14506 u2 = *s2;
14507 if (u1 != u2)
14508 return (u1 < u2) ? -1 : +1;
14509 if (u1 == '\0')
14510 return 0;
14511 s1++;
14512 s2++;
14513 }
14514 return 0;
14515}
14516
14517Py_UNICODE*
14518Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
14519{
14520 const Py_UNICODE *p;
14521 for (p = s; *p; p++)
14522 if (*p == c)
14523 return (Py_UNICODE*)p;
14524 return NULL;
14525}
14526
14527Py_UNICODE*
14528Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
14529{
14530 const Py_UNICODE *p;
14531 p = s + Py_UNICODE_strlen(s);
14532 while (p != s) {
14533 p--;
14534 if (*p == c)
14535 return (Py_UNICODE*)p;
14536 }
14537 return NULL;
14538}
Victor Stinner331ea922010-08-10 16:37:20 +000014539
Victor Stinner71133ff2010-09-01 23:43:53 +000014540Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014541PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000014542{
Victor Stinner577db2c2011-10-11 22:12:48 +020014543 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014544 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000014545
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014546 if (!PyUnicode_Check(unicode)) {
14547 PyErr_BadArgument();
14548 return NULL;
14549 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014550 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020014551 if (u == NULL)
14552 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000014553 /* Ensure we won't overflow the size. */
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014554 if (len > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000014555 PyErr_NoMemory();
14556 return NULL;
14557 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014558 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000014559 size *= sizeof(Py_UNICODE);
14560 copy = PyMem_Malloc(size);
14561 if (copy == NULL) {
14562 PyErr_NoMemory();
14563 return NULL;
14564 }
Victor Stinner577db2c2011-10-11 22:12:48 +020014565 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000014566 return copy;
14567}
Martin v. Löwis5b222132007-06-10 09:51:05 +000014568
Georg Brandl66c221e2010-10-14 07:04:07 +000014569/* A _string module, to export formatter_parser and formatter_field_name_split
14570 to the string.Formatter class implemented in Python. */
14571
14572static PyMethodDef _string_methods[] = {
14573 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
14574 METH_O, PyDoc_STR("split the argument as a field name")},
14575 {"formatter_parser", (PyCFunction) formatter_parser,
14576 METH_O, PyDoc_STR("parse the argument as a format string")},
14577 {NULL, NULL}
14578};
14579
14580static struct PyModuleDef _string_module = {
14581 PyModuleDef_HEAD_INIT,
14582 "_string",
14583 PyDoc_STR("string helper module"),
14584 0,
14585 _string_methods,
14586 NULL,
14587 NULL,
14588 NULL,
14589 NULL
14590};
14591
14592PyMODINIT_FUNC
14593PyInit__string(void)
14594{
14595 return PyModule_Create(&_string_module);
14596}
14597
14598
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014599#ifdef __cplusplus
14600}
14601#endif